graphics3d/toon/toonrenderer
툰 렌더러. (vanilla.js graphics3d/toon/toonrenderer.js 의 ToonRenderer)
- MeshBuilder 의 배열이나 read_glb_arrays 로 읽은 모형을 한 색 재질과 바깥선으로 그린다.
- 빛: ToonLightSet 하나를 기본으로 든다. 해(방향과 색, 그림자), 하늘색과 땅색의 바탕빛, 채움 빛, 점광과 스포트라이트(TOON_MAXIMUM_POINT_LIGHTS 까지), 림 빛, 하이라이트, 빛 꼴(÷π). 셀 셰이딩은 그늘 램프다. (유니티 툰 셰이더의 바탕, 1 차 그늘, 2 차 그늘과 Step, Feather, 그림자는 그늘 색으로 들어간다, 경계는 fwidth 로 계단 없이, 램프 텍스처도 된다) 해는 램프 색을 통째로, 채움 빛과 점광과 스포트라이트는 램프의 밝기 단계를 받는다. 하이라이트와 림은 단단한 툰 꼴에서 부드러운 꼴까지. 셈은 toonlightset.rs 머리말에 있다. set_light, set_sun_direction, set_fill_light, set_shade, set_shade_ramp, clear_shade_ramp, set_band_count, set_band_ramp, set_ramp_texture, set_rim_light, set_specular, set_point_lights, set_point_light_limit, set_light_model 은 기본 묶음을 고친다. 그리기마다 ToonDrawOptions 의 light_set 으로 다른 묶음(create_light_set)을 줄 수 있다.
- 노멀: 모형 행렬과 본 행렬의 왼쪽 위 3x3 의 역행렬의 전치로 옮긴다. (늘이고 줄인 모형도 빛이 맞다, 정점 조각이 고친 행렬도 같다)
- 재질: 꼭짓점의 색(sRGB), 빛남(바탕색에 곱해 더함), 빛을 받지 않음. 꼭짓점 UV(arrays.uv_data, 2 씩)가 있으면 텍스처를 읽는다.
- 그리기 꼴(ToonDrawOptions, 기본값이면 지금까지와 같은 화면): tint_color [r, g, b, a] sRGB 와 alpha. tint_amount 를 주면(0 ~ 1) 틴트를 곱하지 않고 sRGB 로 섞는다. (맞은 번쩍임, 고장 빨강) glow_scale 꼭짓점 빛남의 배(기본 1), color_scale 마지막 선형 색의 배(기본 1, 거울에 비친 모습을 어둡게), emissive_color [r, g, b] sRGB 와 emissive_intensity(선형 배, 기본 1, 색 기본 검정). base_color_texture(바탕색에 곱함, 알파는 불투명도에), emissive_texture(빛남 색에 곱함), uv_transform [u 옮김, v 옮김, u 배, v 배] (KHR_texture_transform 의 offset, scale). decal_texture 는 바탕색 위에 알파로 덮는다(색 = 텍스처 x decal_color). decal_emission 만큼 그 색으로 빛난다. decal_uv_transform 은 묶음 그림의 한 칸을 고를 때. alpha_cutoff 는 불투명도가 그보다 작은 화소를 버린다. (0 이면 끔, glTF MASK) blend_mode: ToonBlendMode::Alpha(기본, 곧은 알파), Premultiplied(미리 곱한 알파), Additive(더하기). Alpha 가 아니면 비치는 것으로 그린다. soft_edge 는 pow(|dot(N, V)|, soft_edge) 를 불투명도에 곱해 가장자리를 엷게 한다. (0 이면 끔, 프레넬 꼴) is_mirrored 는 감기를 뒤집어 그린다. None 이면 모형 행렬의 행렬식이 음수일 때 스스로 뒤집는다. 보기 행렬이 거울에 비쳤으면 그것도 더해 뒤집는다. index_start, index_count 는 몸의 꼭짓점 번호 가운데 그 자리만 그린다. (0 이면 끝까지, GLB 재질 범위, 숨긴 부분) outline_index_start, outline_index_count 는 바깥선 껍데기. material(ToonMaterial), textures([(유니폼 이름, 텍스처)]), on_before_draw(program, gl, ToonProgramKind) 는 확장 자리다. (toonmaterial.rs 머리말) light_set(ToonLightSet) 은 그 그리기의 빛 묶음이다. group, is_depth_prepassed 는 ToonDrawQueue 만 읽는다. receives_shadow (기본 true) 가 false 면 해의 그림자를 보지 않는다. shade_offset 은 빛을 받는 몫에 더해 그늘 경계를 옮긴다. (길티기어 Xrd 의 꼭짓점 색 문턱, 유니티 툰 셰이더의 Shading Grade Map 꼴) specular_scale, rim_scale (기본 1) 은 그 그리기의 하이라이트와 림 배다. (0 이면 없음, 재질마다의 세기) matcap_texture 는 보기 공간 노멀로 읽는 매트캡이다. matcap_strength (기본 1), matcap_blend (ToonMatcapBlend::Multiply 기본, Add) outline_color [r, g, b, a] sRGB 는 그 그리기의 껍데기 바깥선 색 (None 이면 set_outline_color), outline_width_scale (기본 1) 은 지은 굵기의 배다. outline_offset_z (기본 0) 는 껍데기를 카메라에서 먼 쪽으로 미는 월드 길이다. (몸 앞으로 비치지 않게, 유니티 툰 셰이더의 Offset Z) angel_ring_texture 는 천사 고리 텍스처다. u 는 보기 공간 노멀의 x, v 는 2 번 UV 의 y 와 보기 노멀의 y 를 angel_ring_offset_v (기본 0.3) 로 섞은 것이다. (유니티 툰 셰이더의 Angel Ring) angel_ring_color [r, g, b] (선형 배, 기본 흰색), angel_ring_offset_u (0 ~ 0.5, 기본 0), is_angel_ring_alpha (기본 false 면 더하고 true 면 텍스처 알파로 덮는다) 천사 고리 UV 는 카메라 기울임만큼 되돌려 돌린다. (read_camera_roll, 유니티 툰 셰이더의 Camera Rolling Stabilizer, 카메라를 기울여도 고리는 머리에 붙어 있다) line_id, has_screen_outline, has_crease_line 은 ToonDrawQueue 가 화면 공간 바깥선에 넘기는 값이다. (렌더러는 읽지 않는다)
- 바깥선 껍데기(inverted hull): MeshBuilder 가 지은 껍데기의 바탕 자리와 미는 쪽(지은 굵기, 같은 자리의 노멀을 평균한 쪽)을 올리고, 셰이더가 outline_width_scale 만큼 밀어 뒷면만 그린다. set_outline_distance_scale(기준 거리, 가장 작은 배, 가장 큰 배) 를 주면 카메라까지의 거리 / 기준 거리 를 굵기에 곱해 화면 굵기를 맞춘다. (원근만) set_outline_fade_distance(가까운 거리, 먼 거리) 를 주면 모형의 자리에서 카메라까지가 먼 거리에 다가갈수록 굵기가 0 이 된다. (smoothstep, 유니티 툰 셰이더의 Nearest, Farthest Distance) 껍데기 색은 빛 묶음의 outline 빛 색 쓰기가 켜져 있으면(기본) 해의 색을 곱한다. (세기가 1 이상이면 세기로 나눈 색, 유니티 툰 셰이더 바깥선과 같다)
- 뼈대: write_skin_pose 가 셈한 본 행렬을 draw_mesh 에 넘긴다. (TOON_MAXIMUM_JOINTS 까지, 엔진 SkinnedModelRenderer 와 같은 96)
- GPU 인스턴싱: draw_mesh_instanced 로 같은 모형 여럿을 인스턴스마다 행렬과 틴트로 한 번에 그린다. (몸과 바깥선 모두, 그릴 때마다 걸러서 올림) 오래 두는 인스턴스는 create_instance_layout 과 create_instance_buffer 로 영구 버퍼를 짓고 draw_mesh_instance_buffer 로 그린다. (버퍼 전체의 경계로 통째 거름, 머티리얼 정점 조각이 사용자 어트리뷰트를 읽음) 고칠 때는 update_instance_buffer(전체) 나 update_instance_buffer_range(일부, bufferSubData). 몸, 바깥선 껍데기, 그림자, 화면 공간 바깥선의 선의 판이 같은 GPU 버퍼를 같이 쓴다.
- 화면 밖 거르기: 모형의 경계 구를 보기와 투영의 절두체에 대어 밖이면 그리지 않는다. (인스턴스는 하나씩 걸러 남은 것만 올린다)
- 그림자: 엔진 ShadowMap 에 begin_shadow_pass 와 draw_mesh 로 드리우고, set_shadow 로 받는다. (3x3 PCF, 치우침은 ShadowMap::set_bias 의 텍셀 단위 값에 텍셀 크기와 기울기를 곱한다) 점광과 스포트라이트 그림자는 ShadowAtlas 에 begin_shadow_atlas_pass, 칸마다 set_shadow_atlas_tile 과 draw_mesh 로 드리우고, set_local_shadows 로 받는다. (점광은 큐브 여섯 칸, 스포트라이트는 원근 한 칸) 그 빛의 받는 몫에 그림자를 곱해 그늘 램프에 넣는다. (해와 같은 꼴) casts_shadow 가 true 인 점광만 칸을 받는다. (SHADOW_ATLAS_MAXIMUM_LIGHTS 까지) 그림자를 받지 않을 때도 두 그림자 유닛에 1x1 비교 깊이 텍스처를 묶는다. (sampler2DShadow 유닛에 깊이 텍스처가 없으면 맥 드라이버가 알리고, 색 텍스처가 묶여 있으면 WebGL 이 그리기를 거부한다)
- HDR: set_hdr_output(true) 면 감마를 걸지 않은 선형 색을 낸다. 실수 렌더 타겟(ToonPostProcess)에 그리고 블룸과 톤매핑으로 마무리한다.
- 사용: create_mesh(gl, arrays) → 매 프레임 begin_frame(gl, 보기와 투영) → draw_mesh / draw_mesh_instanced → end_frame(gl) → 다 쓰면 delete_mesh. begin_frame 이 앞의 그리기 상태(섞기, 깊이, 면 가리기, 프로그램, 버텍스 어레이)를 적어 두고 깊이 시험과 면 가리기를 켜며, end_frame 이 적어 둔 상태로 돌린다. (엔진 2D 그리기 사이에 끼울 때, 그 전에 Graphic 의 묶음을 내보낸다) begin_frame_with_matrices(gl, 보기, 투영) 는 두 행렬로 시작한다. (직교 원 행렬 카메라) 카메라의 자리와 보기 돌림(하이라이트, 림, 소프트 엣지, 매트캡)은 보기와 투영에서 읽는다.
- 프로그램마다 프레임 값(보기와 투영, 카메라, 그림자, HDR)과 빛 묶음은 바뀔 때만 올린다. 그리기마다 바뀌는 값(모형 행렬, 틴트, 텍스처)만 매번 올린다.
- read_program_sources 로 ShaderWarmer 에 넘길 기본 소스를, read_material_program_sources(머티리얼, 인스턴스 꼴, 모서리 어둠, 색 공간) 으로 그 프로그램의 소스를 준다. (원본은 한 함수에 선택 인자)
- 노드 사각형 안에 그리기: set_screen_rect(x, y, 너비, 높이) 를 주면 begin_frame 이 보기와 투영의 클립 공간을 그 사각형으로 옮기고 가위로 밖을 자른다. 사각형은 begin_frame 때의 뷰포트(보통 드로잉 버퍼 전체) 안의 픽셀이고 왼쪽 위가 원점이다. 화면 밖 거르기는 옮기기 전의 절두체로 한다. end_frame 이 가위를 푼다.
- begin_frame_with_camera(Camera3D) 는 카메라의 보기와 투영으로 begin_frame 을 부른다. 2D 표시(Camera3D::project_to_view)와 같은 카메라를 쓴다.
- draw_mesh_outline 은 바깥선 껍데기만 그린다. (ToonDrawQueue 가 불투명한 몸을 다 그린 뒤 바깥선을 몰아 그릴 때, 그린 수는 세지 않는다)
- ToonDrawOptions 의 casts_shadow 는 ToonDrawQueue::draw_shadows 만 읽는다. is_body_drawn 이 false 면 바깥선만 그린다. (원본은 꼴 객체에 이름으로 단다)
- 텍스처: create_texture(gl, 너비, 높이, RGBA 바이트, ToonTextureOptions) 로 짓는다. UV (0, 0) 이 그림의 왼쪽 위다. (glTF 와 같음)
- 색 공간: new_with_options 의 ToonRendererOptions::color_space(기본은 엔진의 EngineConfiguration::color_space, 엔진이 없으면 Gamma)로 정하고 바뀌지 않는다. (get_color_space) Gamma(기본): 넘기는 색과 색 텍스처는 sRGB 이고 바탕색, 틴트, 데칼은 sRGB 로 곱하고 섞은 뒤 pow(색, 2.2) 로 선형으로 바꿔 빛을 셈한다. 화면에 낼 때 pow(1 / 2.2) 를 건다. Linear: 색 텍스처를 sRGB 형식으로 올려 GPU 가 선형으로 풀고, 넘기는 색은 sRGB 표준 곡선으로 선형으로 바꿔 곱하고 섞는다. 화면에 낼 때 같은 곡선으로 sRGB 로 바꾼다. 셰이더 소스마다 #define VANILLA_COLOR_SPACE_LINEAR 1 이 들어간다. (ToonPostProcess, ToonScreenOutline 도 같은 값으로 짓는다)
- 텍스처 유닛: 점광 그림자 아틀라스 0, 램프 1, 매트캡 2, 해 그림자 3, 바탕색 4, 빛남 5, 데칼 6, 천사 고리 7, 머티리얼 8 ~ 15, 모서리 어둠 16. 유닛 0 의 묶음은 begin_frame 이 적어 두고 end_frame 이 돌린다. 유닛마다 묶인 텍스처가 같으면 묶지 않고, 고른 유닛도 그리기마다 0 으로 되돌리지 않는다. (고른 유닛은 end_frame 이 돌린다, 단계 콜백과 on_before_draw 에는 유닛 0 을 고른 채 넘긴다)
- 모서리 어둠: set_ambient_occlusion_texture(ToonPostProcess::draw_ambient_occlusion 의 결과, 직접 빛 몫) 를 건 동안 몸은 TOON_AMBIENT_OCCLUSION 을 정의한 몸 프로그램으로 그린다. (원점과 직접 빛 몫은 프레임 블록 ToonFrame 의 칸 ambientOcclusionOrigin, ambientOcclusionDirectLightingStrength 로 올린다, 원본과 같다)
- 2 번 UV: 배열에 uv1_data 가 있으면 vertexUv 가 (UV, 2 번 UV) 넷이다. 셰이더 조각은 ToonSurface.uv1 로 읽는다. (없으면 (0, 1))
- 빛 색 쓰기(set_light_color_usage), 그늘 쪽 림(set_shade_rim_light), 빛 세기 막기(set_light_intensity_limited)는 빛 묶음(ToonLightSet)에 둔다.
Toon renderer. (ToonRenderer of vanilla.js graphics3d/toon/toonrenderer.js)
- Draws models from MeshBuilder arrays or read_glb_arrays with single-color material and outline.
- Light: holds one ToonLightSet as the default. Sun (direction and color, shadow), ambient light of sky color and ground color, fill light, point lights and spotlights (up to TOON_MAXIMUM_POINT_LIGHTS), rim light, highlight, light model (÷π). Cel shading is a shade ramp. (Base, 1st shade, 2nd shade with Step and Feather of the Unity Toon Shader, shadows enter as the shade color, boundaries without stairs by fwidth, a ramp texture also works) The sun receives the whole ramp color, while the fill light, point lights and spotlights receive the ramp's brightness level. Highlight and rim range from the hard toon form to the soft form. The math is in the toonlightset.rs header. set_light, set_sun_direction, set_fill_light, set_shade, set_shade_ramp, clear_shade_ramp, set_band_count, set_band_ramp, set_ramp_texture, set_rim_light, set_specular, set_point_lights, set_point_light_limit, set_light_model modify the default set. A different set (create_light_set) can be given per draw via the light_set of ToonDrawOptions.
- Normals: transformed by the transpose of the inverse of the upper left 3x3 of the model matrix and the joint matrix. (Light stays correct on stretched and squashed models, the same goes for matrices changed by the vertex chunk)
- Material: vertex color (sRGB), glow (multiplied by the base color and added), unlit. If vertex UVs (arrays.uv_data, 2 each) exist, textures are sampled.
- Draw options (ToonDrawOptions, defaults give the same image as before):
tint_color [r, g, b, a] sRGB and alpha. If tint_amount is given (0 ~ 1), the tint is mixed in sRGB instead of multiplied. (hit flash, malfunction red)
glow_scale multiplier of vertex glow (default 1), color_scale multiplier of the final linear color (default 1, darkens a mirrored image), emissive_color [r, g, b] sRGB and emissive_intensity (linear multiplier, default 1, color default black).
base_color_texture (multiplied into base color, alpha into opacity), emissive_texture (multiplied into glow color), uv_transform [u offset, v offset, u scale, v scale] (offset, scale of KHR_texture_transform).
decal_texture overlays the base color by alpha (color = texture x decal_color). Glows in that color by decal_emission. decal_uv_transform is for picking one cell of an atlas.
alpha_cutoff discards pixels whose opacity is below it. (0 disables, glTF MASK)
blend_mode: ToonBlendMode::Alpha (default, straight alpha), Premultiplied (premultiplied alpha), Additive (additive). Anything other than Alpha is drawn as transparent.
soft_edge multiplies opacity by pow(|dot(N, V)|, soft_edge) to fade the edges. (0 disables, Fresnel style)
is_mirrored draws with the winding flipped. If None, it flips by itself when the determinant of the model matrix is negative. If the view matrix is mirrored, that flip is added too.
index_start, index_count draw only that span of the body vertex indices. (0 means to the end, GLB material ranges, hidden parts) outline_index_start, outline_index_count are for the outline shell.
material (ToonMaterial), textures ([(uniform name, texture)]), on_before_draw(program, gl, ToonProgramKind) are extension points. (toonmaterial.rs header)
light_set (ToonLightSet) is the light set of that draw. group, is_depth_prepassed are read only by ToonDrawQueue.
If receives_shadow (default true) is false, the sun's shadow is not looked up. shade_offset is added to the received light amount to move the shade boundary. (Vertex color threshold of Guilty Gear Xrd, Shading Grade Map form of the Unity Toon Shader)
specular_scale, rim_scale (default 1) are the highlight and rim multipliers of that draw. (0 means none, strength per material)
matcap_texture is a matcap read with the view-space normal. matcap_strength (default 1), matcap_blend (ToonMatcapBlend::Multiply default, Add)
outline_color [r, g, b, a] sRGB is the shell outline color of that draw (set_outline_color if None), outline_width_scale (default 1) is the multiplier of the built thickness.
outline_offset_z (default 0) is the world length the shell is pushed away from the camera. (So it does not show in front of the body, Offset Z of the Unity Toon Shader)
angel_ring_texture is the angel ring texture. u is the x of the view-space normal, v is the y of the second UV mixed with the y of the view normal by angel_ring_offset_v (default 0.3). (Angel Ring of the Unity Toon Shader)
angel_ring_color [r, g, b] (linear multiplier, default white), angel_ring_offset_u (0 ~ 0.5, default 0), is_angel_ring_alpha (default false adds, true covers with the texture alpha)
The angel ring UV is rotated back by the camera roll. (read_camera_roll, Camera Rolling Stabilizer of the Unity Toon Shader, the ring stays on the head even when the camera is tilted)
line_id, has_screen_outline, has_crease_line are values ToonDrawQueue passes to the screen-space outline. (The renderer does not read them)- Outline shell (inverted hull): uploads the base position and push direction (built thickness, the averaged normal of the same position) of the shell MeshBuilder built, and the shader pushes it by outline_width_scale and draws only back faces. If set_outline_distance_scale(reference distance, minimum scale, maximum scale) is given, distance to the camera / reference distance is multiplied into the thickness to keep the screen thickness. (Perspective only) If set_outline_fade_distance(near distance, far distance) is given, the thickness goes to 0 as the distance from the model position to the camera approaches the far distance. (smoothstep, Nearest and Farthest Distance of the Unity Toon Shader) The shell color is multiplied by the sun color when the outline light color usage of the light set is on (default). (Divided by its intensity when the intensity is 1 or more, same as the Unity Toon Shader outline)
- Skeleton: the joint matrices computed by write_skin_pose are passed to draw_mesh. (Up to TOON_MAXIMUM_JOINTS, 96 like the engine's SkinnedModelRenderer)
- GPU instancing: draw_mesh_instanced draws many copies of the same model at once with a matrix and tint per instance. (both body and outline, culled and uploaded on every draw) For long-lived instances, build a persistent buffer with create_instance_layout and create_instance_buffer and draw with draw_mesh_instance_buffer. (culls the whole buffer by its bounds, the material vertex snippet reads user attributes) When changing, use update_instance_buffer (whole) or update_instance_buffer_range (part, bufferSubData). The body, the outline shell, the shadow and the screen-space outline board share the same GPU buffer.
- Off-screen culling: tests the model's bounding sphere against the view-projection frustum and skips drawing if outside. (instances are culled one by one and only the rest are uploaded)
- Shadows: cast into the engine ShadowMap with begin_shadow_pass and draw_mesh, received with set_shadow. (3x3 PCF, the bias is the texel-unit value of ShadowMap::set_bias multiplied by the texel size and slope) Point light and spotlight shadows are cast into a ShadowAtlas with begin_shadow_atlas_pass and, per tile, set_shadow_atlas_tile and draw_mesh, and received with set_local_shadows. (A point light uses six cube tiles, a spotlight one perspective tile) The shadow is multiplied into that light's received amount and goes into the shade ramp. (Same form as the sun) Only point lights with casts_shadow true get tiles. (Up to SHADOW_ATLAS_MAXIMUM_LIGHTS) Even when shadows are not received, a 1x1 comparison depth texture is bound to both shadow units. (Without a depth texture on a sampler2DShadow unit the Mac driver reports it, and if a color texture is bound WebGL refuses to draw)
- HDR: set_hdr_output(true) outputs linear color without gamma. Draw into a float render target (ToonPostProcess) and finish with bloom and tone mapping.
- Usage: create_mesh(gl, arrays) → every frame begin_frame(gl, view and projection) → draw_mesh / draw_mesh_instanced → end_frame(gl) → delete_mesh when done. begin_frame records the previous draw state (blending, depth, face culling, program, vertex array) and enables depth testing and face culling, and end_frame restores the recorded state. (When inserting between engine 2D draws, flush the Graphic batch before it) begin_frame_with_matrices(gl, view, projection) starts with two matrices. (orthographic or raw matrix camera) The camera position and view rotation (highlight, rim, soft edge, matcap) are read from the view and projection.
- Per program, frame values (view and projection, camera, shadow, HDR) and the light set are uploaded only when they change. Only per-draw values (model matrix, tint, textures) are uploaded every time.
- read_program_sources gives the default sources to hand to ShaderWarmer, and read_material_program_sources(material, instance layout, ambient occlusion, color space) gives the sources of that program. (the original has one function with optional arguments)
- Drawing inside a node rectangle: given set_screen_rect(x, y, width, height), begin_frame moves the view-projection clip space into that rectangle and scissors out the rest. The rectangle is in pixels within the viewport at begin_frame time (usually the whole drawing buffer), with the origin at the top left. Off-screen culling uses the frustum before the move. end_frame releases the scissor.
- begin_frame_with_camera(Camera3D) calls begin_frame with the camera's view and projection. It uses the same camera as the 2D display (Camera3D::project_to_view).
- draw_mesh_outline draws only the outline shell. (when ToonDrawQueue draws all outlines together after drawing every opaque body, draws are not counted)
- casts_shadow of ToonDrawOptions is read only by ToonDrawQueue::draw_shadows. If is_body_drawn is false, only the outline is drawn. (The original attaches them by name to the options object)
- Textures: built with create_texture(gl, width, height, RGBA bytes, ToonTextureOptions). UV (0, 0) is the top left of the image. (Same as glTF)
- Color space: set by ToonRendererOptions::color_space of new_with_options (default is the engine's EngineConfiguration::color_space, Gamma without an engine) and does not change. (get_color_space) Gamma (default): passed colors and color textures are sRGB; base color, tint and decal are multiplied and mixed in sRGB and then converted to linear with pow(color, 2.2) to compute light. pow(1 / 2.2) is applied for the screen. Linear: color textures are uploaded in an sRGB format so the GPU decodes them to linear, and passed colors are converted to linear with the standard sRGB curve before they are multiplied and mixed. The same curve converts back to sRGB for the screen. Every shader source gets #define VANILLA_COLOR_SPACE_LINEAR 1. (ToonPostProcess and ToonScreenOutline are built with the same value too)
- Texture units: point light shadow atlas 0, ramp 1, matcap 2, sun shadow 3, base color 4, emission 5, decal 6, angel ring 7, material 8 ~ 15, ambient occlusion 16. begin_frame records the binding of unit 0 and end_frame restores it. A texture already bound to a unit is not bound again, and the chosen unit is not set back to 0 after every draw. (end_frame restores the chosen unit; stage callbacks and on_before_draw are called with unit 0 chosen)
- Ambient occlusion: while set_ambient_occlusion_texture(the result of ToonPostProcess::draw_ambient_occlusion, direct lighting strength) is set, bodies are drawn with the body program that defines TOON_AMBIENT_OCCLUSION. (The origin and the direct lighting strength go in the ambientOcclusionOrigin and ambientOcclusionDirectLightingStrength slots of the ToonFrame frame block, same as the original)
- Second UV: if the arrays have uv1_data, vertexUv is four values (UV, second UV). Shader chunks read it as ToonSurface.uv1. ((0, 1) if none)
- Light color usage (set_light_color_usage), shade-side rim (set_shade_rim_light) and light intensity limit (set_light_intensity_limited) live in the light set (ToonLightSet).
ToonProgramSourcesstruct traits Clone, Debug
세 프로그램의 소스와 어트리뷰트 자리. (compose_toon_program_sources 의 결과)
Sources and attribute locations of the three programs. (result of compose_toon_program_sources)
use vanilla::{compose_toon_program_sources, ColorSpace, ToonInstanceLayout, ToonMaterial, ToonMaterialChunks};
let material = ToonMaterial::new(ToonMaterialChunks {
name: String::from("pulse"),
uniform_chunk: String::from("uniform float pulse;\n"),
surface_chunk: String::from("void applySurface(inout ToonSurface surface) {\n\tsurface.emission += vec3(pulse);\n}\n"),
..ToonMaterialChunks::default()
});
let instance_layout = ToonInstanceLayout::new(&[("instanceOffset", 3)]).unwrap();
let sources = compose_toon_program_sources(Some(&material), Some(&instance_layout), false, ColorSpace::Gamma, &[]);
assert!(sources.solid_fragment_shader.contains("uniform float pulse;"));
let linear_sources = compose_toon_program_sources(Some(&material), Some(&instance_layout), true, ColorSpace::Linear, &[]);
assert!(linear_sources.solid_fragment_shader.starts_with("#version 300 es\n#define VANILLA_COLOR_SPACE_LINEAR 1\n#define TOON_AMBIENT_OCCLUSION\n"));
assert!(sources.solid_vertex_shader.contains("in vec3 instanceOffset;"));
assert!(sources.attribute_locations.iter().any(|(name, _)| name == "instanceOffset"));바깥선 껍데기 정점 셰이더.
Outline shell vertex shader.
반환ReturnsString
바깥선 껍데기 조각 셰이더.
Outline shell fragment shader.
반환ReturnsString
그림자 깊이 조각 셰이더.
Shadow depth fragment shader.
반환ReturnsString
어트리뷰트 이름과 자리. (TOON_ATTRIBUTE_LOCATIONS 에 인스턴스 꼴의 사용자 어트리뷰트를 더한 것)
Attribute names and locations. (TOON_ATTRIBUTE_LOCATIONS plus the user attributes of the instance layout)
반환ReturnsVec<(String, u32)>
ToonMeshstruct
GPU 에 올린 모형.
A model uploaded to the GPU.
use vanilla::{create_box_geometry, create_sphere_geometry, Matrix4, MeshBuilder, ToonPartOptions, ToonRenderer};
fn upload_mesh(gl: &vanilla::GlContext, renderer: &ToonRenderer) {
let mut builder = MeshBuilder::new();
builder.add_part(&create_box_geometry(1.0, 1.0, 1.0), &Matrix4::create_identity(), "#d06060", ToonPartOptions::default());
builder.add_part(&create_sphere_geometry(0.4, 16, 12, std::f64::consts::PI), &Matrix4::create_translation(0.0, 0.9, 0.0), "#f0c8a0", ToonPartOptions::default());
if let Some(mesh) = renderer.create_mesh(gl, &builder.read_arrays()) {
let (center, radius) = mesh.get_bounding_sphere();
let (body_index_count, outline_index_count) = mesh.get_index_counts();
println!("{:?} {} {} {} {}", center, radius, body_index_count, outline_index_count, mesh.has_outline());
renderer.delete_mesh(gl, mesh);
}
}뼈대로 움직이는 모형인지.
Whether the model is moved by a skeleton.
반환Returnsbool 뼈대(skin_data)가 있으면 true.true if there is a skeleton (skin_data).
텍스처 좌표가 있는지.
Whether it has texture coordinates.
반환Returnsbool 꼭짓점마다 UV 가 있으면 true.true if every vertex has a UV.
경계 구. (모형 좌표의 가운데와 반지름, 뼈대 모형은 쉬는 자세의 1.5 배)
Bounding sphere. (center and radius in model coordinates, 1.5 times the rest pose for skeletal models)
반환Returns([f64; 3], f64) (모형 좌표의 가운데 [x, y, z], 반지름)(center [x, y, z] in model coordinates, radius)
몸과 바깥선 껍데기의 꼭짓점 번호 수.
Vertex index counts of the body and outline shell.
반환Returns(usize, usize) (몸의 꼭짓점 번호 수, 바깥선 껍데기의 꼭짓점 번호 수)(body vertex index count, outline shell vertex index count)
바깥선 껍데기가 있는지.
Whether it has an outline shell.
반환Returnsbool 바깥선 껍데기가 있으면 true.true if there is an outline shell.
ToonInstanceBufferstruct
영구 인스턴스 버퍼. (create_instance_buffer 의 결과, 모형마다 함께 묶은 버텍스 어레이를 처음 그릴 때 지어 둔다)
Persistent instance buffer. (result of create_instance_buffer, a vertex array bound together with each model is built on the first draw)
use vanilla::{Matrix4, ToonBufferUsage, ToonDrawOptions, ToonMesh, ToonRenderer};
fn draw_trees(gl: &vanilla::GlContext, renderer: &mut ToonRenderer, mesh: &ToonMesh, view_projection_matrix: &Matrix4) -> Result<(), String> {
let instance_layout = renderer.create_instance_layout(&[("instanceMatrix", 16), ("instanceTint", 4)])?;
let mut data: Vec<f32> = Vec::new();
for index in 0..9 {
let model_matrix = Matrix4::create_translation((index % 3) as f64 - 1.0, 0.0, (index / 3) as f64 - 1.0);
data.extend_from_slice(model_matrix.get_elements());
data.extend_from_slice(&[1.0, 1.0 - index as f32 * 0.05, 1.0, 1.0]);
}
let instance_buffer = renderer.create_instance_buffer(gl, &instance_layout, &data, ToonBufferUsage::Static)?;
renderer.begin_frame(gl, view_projection_matrix);
renderer.draw_mesh_instance_buffer(gl, mesh, &instance_buffer, instance_buffer.get_instance_count(), ToonDrawOptions::default());
renderer.end_frame(gl);
renderer.delete_instance_buffer(gl, instance_buffer);
Ok(())
}인스턴스 꼴 반환.
Returns the instance layout.
반환Returns&ToonInstanceLayout 버퍼의 인스턴스 꼴.Instance layout of the buffer.
담은 수 개수.
Number of values held.
반환Returnsusize 담은 수 개수.Number of values held.
담은 인스턴스 수. (수 개수를 꼴의 수 개수로 나눈 것)
Number of instances held. (the value count divided by the layout's value count)
반환Returnsusize 담은 인스턴스 수.Number of stored instances.
버퍼 번호. (버퍼마다 다르다, 그림자 캐시가 버퍼를 알아본다)
Buffer id. (different for every buffer, the shadow cache recognizes the buffer by it)
반환Returnsu64 버퍼 번호.Buffer id.
고친 횟수. (update_instance_buffer 와 update_instance_buffer_range 마다 1 씩 는다, 그림자 캐시가 버퍼 바뀜을 안다)
Number of changes. (+1 on every update_instance_buffer and update_instance_buffer_range, the shadow cache notices buffer changes through it)
반환Returnsu64 고친 횟수.Number of changes.
버퍼 전체의 경계. (꼴에 행렬이 있을 때만)
Bounds of the whole buffer. (only when the layout has a matrix)
반환ReturnsOption<ToonInstanceBounds> 경계. 행렬이 없거나 인스턴스가 없으면 None.The bounds. None when there is no matrix or no instance.
경계를 다시 셀 사본. (꼴에 행렬이 있을 때만, 고치지 않는다)
The copy used to recompute the bounds. (only when the layout has a matrix, do not modify it)
반환ReturnsOption<std::cell::Ref<'_, [f32]>> 수 사본. 행렬이 없으면 None.The copy of the numbers. None when there is no matrix.
ToonInstanceBoundsstruct traits Clone, Copy, Debug, PartialEq
인스턴스 버퍼 전체의 경계. (꼴에 행렬이 있을 때만, 자리들의 상자 가운데와 가장 먼 자리까지의 거리, 가장 큰 크기, 원본 bounds)
- 어느 모형으로 그려도 쓰도록 모형의 경계 구는 그릴 때 더한다. (read_instance_buffer_sphere)
Bounds of a whole instance buffer. (only when the layout has a matrix: the center of the position box, the distance to the farthest position and the largest scale; the original bounds)
- The mesh bounding sphere is added when drawing, so the bounds serve any mesh. (read_instance_buffer_sphere)
use vanilla::ToonInstanceBounds;
let bounds = ToonInstanceBounds { center: [0.0, 1.0, 0.0], radius: 5.0, scale: 2.0 };
assert_eq!(bounds.radius, 5.0);가운데에서 가장 먼 자리까지의 거리.
Distance from the center to the farthest position.
반환Returnsf64
ToonTextureOptionsstruct traits Clone, Copy, Debug, PartialEq, Eq, Default
텍스처를 지을 때의 꼴. (밉맵, 되풀이, 고르게 읽기)
Options for building a texture. (mipmaps, repeat, smooth filtering)
use vanilla::core::graphic::GlTexture;
use vanilla::{ToonRenderer, ToonTextureOptions};
fn create_matcap_texture(gl: &vanilla::GlContext, renderer: &ToonRenderer) -> Result<GlTexture, String> {
let pixels = [60, 60, 70, 255, 255, 255, 255, 255, 60, 60, 70, 255, 160, 160, 180, 255];
renderer.create_texture(gl, 2, 2, &pixels, ToonTextureOptions { is_mipmapped: false, is_repeated: false, ..ToonTextureOptions::default() })
}밉맵을 지을지. (기본 true)
Whether to build mipmaps. (default true)
반환Returnsbool
되풀이할지. (기본 true, false 면 가장자리 붙임)
Whether to repeat. (default true, false clamps to the edge)
반환Returnsbool
고르게 읽을지. (기본 true, false 면 가까운 화소)
Whether to filter smoothly. (default true, false uses the nearest pixel)
반환Returnsbool
색인지. (기본 true 면 색, false 면 노멀이나 마스크 같은 자료, 선형 색 공간에서만 가른다: 색은 SRGB8_ALPHA8, 자료는 RGBA8, 감마 색 공간은 늘 RGBA)
Whether it is a color. (default true means color, false means data such as normals or masks, only distinguished in the linear color space: colors are SRGB8_ALPHA8, data RGBA8, and the gamma color space always uses RGBA)
반환Returnsbool
ToonBeforeDrawCallbacktype
그리기 전에 부르는 콜백. (프로그램, GL, 프로그램 종류, 머티리얼의 유니폼을 쓸 때)
Callback called before drawing. (program, GL, program kind, for setting the material's uniforms)
pub type ToonBeforeDrawCallback<'a> = &'a dyn Fn(&ShaderProgram, &GlContext, ToonProgramKind)ToonDrawOptionsstruct traits Clone, Copy, Default, std::fmt::Debug
모형 하나를 그릴 때의 꼴.
Options for drawing one model.
use vanilla::{ToonBlendMode, ToonDrawOptions};
let options = ToonDrawOptions {
tint_color: [1.0, 0.6, 0.6, 1.0],
alpha: 0.5,
outline_color: Some([0.1, 0.06, 0.08, 1.0]),
outline_width_scale: 1.5,
..ToonDrawOptions::default()
};
assert!(options.has_outline && options.is_culled);
assert_eq!(options.blend_mode, ToonBlendMode::Alpha);틴트 색. ([r, g, b, a] sRGB, 기본 흰색, tint_amount 가 없으면 바탕색에 곱한다, 알파는 불투명도에 곱한다)
Tint color. ([r, g, b, a] sRGB, default white, multiplied into the base color when tint_amount is not given, alpha is multiplied into opacity)
반환Returns[f64; 4]
불투명도. (기본 1, 1 보다 작으면 비치는 것으로 그린다)
Opacity. (default 1, drawn as transparent when below 1)
반환Returnsf64
본 행렬의 수. (write_skin_pose 가 셈한 것, 본마다 16, None 이면 뼈대로 움직이지 않는다)
Joint matrix values. (computed by write_skin_pose, 16 per joint, None means no skeletal motion)
반환ReturnsOption<&'a [f32]>
바깥선 껍데기를 그릴지. (기본 true)
Whether to draw the outline shell. (default true)
반환Returnsbool
화면 밖이면 거를지. (기본 true)
Whether to cull when off screen. (default true)
반환Returnsbool
그림자를 드리울지. (기본 true, ToonDrawQueue::draw_shadows 만 읽는다)
Whether to cast shadows. (default true, read only by ToonDrawQueue::draw_shadows)
반환Returnsbool
몸을 그릴지. (기본 true, false 면 바깥선만 그린다)
Whether to draw the body. (default true, false draws only the outline)
반환Returnsbool
틴트를 섞는 몫. (0 ~ 1, 주면 틴트를 곱하지 않고 sRGB 로 섞는다, 맞은 번쩍임, 고장 빨강)
Tint mix amount. (0 ~ 1, if given the tint is mixed in sRGB instead of multiplied, hit flash, malfunction red)
반환ReturnsOption<f64>
마지막 선형 색의 배. (기본 1, 거울에 비친 모습을 어둡게)
Multiplier of the final linear color. (default 1, darkens a mirrored image)
반환Returnsf64
빛남 색. ([r, g, b] sRGB, 기본 검정)
Glow color. ([r, g, b] sRGB, default black)
반환Returns[f64; 3]
빛남 색의 세기. (선형 배, 기본 1)
Glow color intensity. (linear multiplier, default 1)
반환Returnsf64
바탕색 텍스처. (바탕색에 곱함, 알파는 불투명도에, None 이면 없음)
Base color texture. (multiplied into the base color, alpha into opacity, None means none)
반환ReturnsOption<GlTexture>
빛남 텍스처. (빛남 색에 곱함, None 이면 없음)
Glow texture. (multiplied into the glow color, None means none)
반환ReturnsOption<GlTexture>
UV 옮김과 배. ([u 옮김, v 옮김, u 배, v 배], KHR_texture_transform 의 offset, scale)
UV offset and scale. ([u offset, v offset, u scale, v scale], offset, scale of KHR_texture_transform)
반환Returns[f64; 4]
데칼 텍스처. (바탕색 위에 알파로 덮는다, 색 = 텍스처 x decal_color, None 이면 없음)
Decal texture. (overlays the base color by alpha, color = texture x decal_color, None means none)
반환ReturnsOption<GlTexture>
데칼 색. (텍스처에 곱한다, 기본 흰색)
Decal color. (multiplied into the texture, default white)
반환Returns[f64; 3]
데칼이 그 색으로 빛나는 몫. (기본 0)
Amount the decal glows in its color. (default 0)
반환Returnsf64
데칼 UV 옮김과 배. ([u 옮김, v 옮김, u 배, v 배], 묶음 그림의 한 칸을 고를 때)
Decal UV offset and scale. ([u offset, v offset, u scale, v scale], for picking one cell of an atlas)
반환Returns[f64; 4]
불투명도가 그보다 작은 화소를 버린다. (0 이면 끔, glTF MASK)
Discards pixels whose opacity is below it. (0 disables, glTF MASK)
반환Returnsf64
섞는 방식. (기본 ToonBlendMode::Alpha, Alpha 가 아니면 비치는 것으로 그린다)
Blend mode. (default ToonBlendMode::Alpha, anything other than Alpha is drawn as transparent)
반환ReturnsToonBlendMode
가장자리를 엷게 하는 지수. (pow(|dot(N, V)|, soft_edge) 를 불투명도에 곱한다, 0 이면 끔, 프레넬 꼴)
Exponent that fades the edges. (opacity is multiplied by pow(|dot(N, V)|, soft_edge), 0 disables, Fresnel style)
반환Returnsf64
감기를 뒤집어 그릴지. (None 이면 모형 행렬의 행렬식이 음수일 때 스스로 뒤집는다, 보기 행렬이 거울에 비쳤으면 그것도 더해 뒤집는다)
Whether to draw with the winding flipped. (None flips by itself when the determinant of the model matrix is negative, if the view matrix is mirrored that flip is added too)
반환ReturnsOption<bool>
몸의 꼭짓점 번호 가운데 그릴 첫 자리. (GLB 재질 범위, 숨긴 부분)
First position to draw among the body vertex indices. (GLB material range, hidden parts)
반환Returnsusize
몸의 꼭짓점 번호 가운데 그릴 수. (0 이면 끝까지)
Number to draw among the body vertex indices. (0 means to the end)
반환Returnsusize
바깥선 껍데기의 꼭짓점 번호 가운데 그릴 첫 자리.
First position to draw among the outline shell vertex indices.
반환Returnsusize
바깥선 껍데기의 꼭짓점 번호 가운데 그릴 수. (0 이면 끝까지)
Number to draw among the outline shell vertex indices. (0 means to the end)
반환Returnsusize
셰이더 조각을 끼울 머티리얼. (None 이면 기본 프로그램, toonmaterial.rs 머리말)
Material whose shader chunks are inserted. (None means the default program, toonmaterial.rs header)
반환ReturnsOption<&'a ToonMaterial>
머티리얼 텍스처. ([(유니폼 이름, 텍스처)], 유닛 8 부터 TOON_MAXIMUM_MATERIAL_TEXTURES 개까지)
Material textures. ([(uniform name, texture)], from unit 8, up to TOON_MAXIMUM_MATERIAL_TEXTURES)
반환Returns&'a [(&'a str, GlTexture)]
그리기 전에 부르는 콜백. (프로그램, GL, 프로그램 종류, 머티리얼의 유니폼을 쓸 때)
Callback called before drawing. (program, GL, program kind, for setting the material's uniforms)
반환ReturnsOption<ToonBeforeDrawCallback<'a>>
그 그리기의 빛 묶음. (None 이면 렌더러의 기본 묶음)
Light set of that draw. (None means the renderer's default set)
반환ReturnsOption<&'a ToonLightSet>
비치는 것의 묶음 번호. (같은 번호는 한 덩어리로 정렬한다, ToonDrawQueue 만 읽는다)
Group number of transparent draws. (the same number is sorted as one lump, read only by ToonDrawQueue)
반환ReturnsOption<u32>
묶음의 깊이만 먼저 그릴지. (ToonDrawQueue 만 읽는다)
Whether to draw only the depth of the group first. (read only by ToonDrawQueue)
반환Returnsbool
그림자를 받을지. (false 면 해의 그림자를 보지 않는다)
Whether to receive shadows. (if false, the sun's shadows are ignored)
반환Returnsbool
빛을 받는 몫 x 에 더할 값. (그늘 경계를 옮긴다, 길티기어 Xrd 의 꼭짓점 색 문턱, 유니티 툰 셰이더의 Shading Grade Map 꼴, 표면 조각이 surface.shadeOffset 으로 더 고칠 수 있다)
Value added to the light-receiving amount x. (shifts the shade boundary, the vertex color threshold of Guilty Gear Xrd, the Shading Grade Map style of Unity Toon Shader, the surface snippet can adjust it further with surface.shadeOffset)
반환Returnsf64
하이라이트 배. (0 이면 이 그리기는 하이라이트가 없다, 재질마다의 세기)
Specular highlight multiplier. (0 means no specular highlight for this draw, per-material strength)
반환Returnsf64
림 빛 배. (0 이면 이 그리기는 림 빛이 없다)
Rim light multiplier. (0 means no rim light for this draw)
반환Returnsf64
매트캡 텍스처. (보기 공간 노멀로 읽는 공 그림, None 이면 없음)
Matcap texture. (a sphere image read with view-space normals, None for none)
반환ReturnsOption<GlTexture>
매트캡 섞기. (곱하기나 더하기)
Matcap blend. (multiply or add)
반환ReturnsToonMatcapBlend
껍데기 바깥선 색. (sRGB 와 알파, None 이면 렌더러의 set_outline_color)
Shell outline color. (sRGB and alpha, None for the renderer's set_outline_color)
반환ReturnsOption<[f64; 4]>
껍데기 바깥선 굵기 배. (지은 굵기에 곱한다)
Shell outline width multiplier. (multiplied by the built width)
반환Returnsf64
껍데기 바깥선을 카메라에서 먼 쪽으로 밀 거리. (월드 길이, 몸 앞으로 비치지 않게, 유니티 툰 셰이더의 Offset Z 꼴)
Distance to push the shell outline away from the camera. (World length, so it does not show through in front of the body, the form of Offset Z of the Unity Toon Shader)
반환Returnsf64
천사 고리 텍스처. (보기 공간 노멀의 x 와 2 번 UV 의 y 로 읽는 머리카락 반사 띠, None 이면 없음, 유니티 툰 셰이더의 Angel Ring)
Angel ring texture. (A hair reflection band read with the x of the view-space normal and the y of the second UV, none if None, Angel Ring of the Unity Toon Shader)
반환ReturnsOption<GlTexture>
천사 고리 색. (선형 배)
Angel ring color. (Linear multiplier)
반환Returns[f64; 3]
천사 고리 u 를 화면 가운데 쪽으로 당기는 몫. (0 ~ 0.5, AR_OffsetU)
Amount that pulls the angel ring u toward the screen center. (0 ~ 0.5, AR_OffsetU)
반환Returnsf64
천사 고리 v 를 2 번 UV 에서 보기 노멀 쪽으로 옮기는 몫. (0 ~ 1, AR_OffsetV, 기본 0.3)
Amount that shifts the angel ring v from the second UV toward the view normal. (0 ~ 1, AR_OffsetV, default 0.3)
반환Returnsf64
천사 고리를 텍스처 알파로 덮을지. (false 면 더한다, ARSampler_AlphaOn)
Whether the angel ring covers by texture alpha. (Adds if false, ARSampler_AlphaOn)
반환Returnsbool
화면 공간 바깥선의 선 번호. (ToonDrawQueue 가 선의 판에 그릴 때, None 이면 담은 차례 + 1)
Line ID for the screen-space outline. (when ToonDrawQueue draws into the line target, None uses the queue order + 1)
반환ReturnsOption<u32>
화면 공간 바깥선을 낼지. (false 면 선은 내지 않고 뒤의 선만 가린다)
Whether to output the screen-space outline. (when false, no line is output and only the lines behind are hidden)
반환Returnsbool
화면 공간 꺾임 선을 낼지.
Whether to output screen-space crease lines.
반환Returnsbool
ToonInstancestruct traits Clone, Copy, Debug, Default
인스턴스 하나. (모형 행렬과 틴트, 틴트의 알파는 바깥선에도 곱한다)
- emissive_color 는 그 인스턴스에 더하는 빛남 sRGB(None 이면 없음, 명암과 무늬 위에 더해 그 인스턴스만 밝힌다), emissive_intensity 는 빛남의 선형 배(원본 기본 1)다. 모형 행렬은 아핀으로 읽는다. (TOON_INSTANCE_FLOAT_COUNT 머리말, 빛남은 행렬의 아래 줄에 싣는다)
- line_id 는 ToonScreenOutline::draw_mesh_instanced 가 읽는 이 인스턴스의 선 번호다. (원본 lineId, None 이면 공통 번호, ToonRenderer 는 읽지 않는다)
One instance. (model matrix and tint, the tint alpha also multiplies the outline)
- emissive_color is the emission sRGB added to that instance (None for none, added on top of the shading and pattern so only that instance brightens), and emissive_intensity is the linear multiplier of the emission (original default 1). The model matrix is read as affine. (see TOON_INSTANCE_FLOAT_COUNT, the emission goes into the bottom row of the matrix)
- line_id is this instance's line ID read by ToonScreenOutline::draw_mesh_instanced. (the original lineId, None uses the common ID, ToonRenderer does not read it)
use vanilla::{Matrix4, ToonDrawOptions, ToonInstance, ToonMesh, ToonRenderer};
fn draw_rocks(gl: &vanilla::GlContext, renderer: &mut ToonRenderer, mesh: &ToonMesh, view_projection_matrix: &Matrix4) {
let instance_list: Vec<ToonInstance> = (0..20).map(|index| {
let shade = 0.6 + (index % 5) as f64 * 0.1;
ToonInstance {
model_matrix: Matrix4::create_translation((index % 5) as f64 * 1.5, 0.0, (index / 5) as f64 * 1.5),
tint_color: [shade, shade, shade, 1.0],
..ToonInstance::default()
}
}).collect();
renderer.begin_frame(gl, view_projection_matrix);
renderer.draw_mesh_instanced(gl, mesh, &instance_list, ToonDrawOptions::default());
renderer.end_frame(gl);
}틴트 색. ([r, g, b, a] sRGB, 알파는 바깥선에도 곱한다)
Tint color. ([r, g, b, a] sRGB, alpha is also multiplied into the outline)
반환Returns[f64; 4]
화면 공간 바깥선의 선 번호. (None 이면 공통 번호, ToonRenderer 는 읽지 않는다)
Line number for the screen-space outline. (None means the shared number, ToonRenderer does not read it)
반환ReturnsOption<u32>
더하는 빛남 색. ([r, g, b] sRGB, None 이면 빛남 없음)
Added emission color. ([r, g, b] sRGB, None for no emission)
반환ReturnsOption<[f64; 3]>
빛남의 선형 배. (원본 기본 1, emissive_color 가 None 이면 읽지 않는다)
Linear multiplier of the emission. (original default 1, not read when emissive_color is None)
반환Returnsf64
ToonFrameStatisticsstruct traits Clone, Copy, Debug, Default
그린 수와 거른 수. (한 프레임, begin_frame 이 비운다)
Drawn and culled counts. (one frame, cleared by begin_frame)
use vanilla::{ToonFrameStatistics, ToonRenderer};
fn print_statistics(renderer: &ToonRenderer) {
let statistics: ToonFrameStatistics = renderer.get_frame_statistics();
println!("draw calls {}, drawn {}, culled {}", statistics.draw_call_count, statistics.drawn_object_count, statistics.culled_object_count);
}그린 모형 수. (인스턴스는 하나씩 센다)
Number of drawn models. (instances are counted one by one)
반환Returnsu32
화면 밖이라 거른 모형 수. (인스턴스는 하나씩 센다)
Number of models culled as off screen. (instances are counted one by one)
반환Returnsu32
ToonFrameCamerastruct traits Clone, Copy, Debug, PartialEq
보기와 투영에서 읽은 카메라. (position 은 원근이면 [x, y, z, 1], 직교면 [0, 0, 0, 0], forward 는 보는 방향, is_mirrored 는 보기 행렬이 거울에 비쳤는지)
Camera read from the view and projection. (position is [x, y, z, 1] for perspective, [0, 0, 0, 0] for orthographic, forward is the view direction, is_mirrored is whether the view matrix is mirrored)
use vanilla::{read_frame_camera, Matrix4, Vector3};
let mut view_projection_matrix = Matrix4::create_perspective(0.8, 16.0 / 9.0, 0.1, 100.0);
view_projection_matrix.multiply(&Matrix4::create_look_at(Vector3::create(0.0, 2.0, 5.0), Vector3::create(0.0, 2.0, 0.0), Vector3::create(0.0, 1.0, 0.0)));
let frame_camera = read_frame_camera(&view_projection_matrix);
assert_eq!(frame_camera.position[3], 1.0);
assert!((frame_camera.position[2] - 5.0).abs() < 0.001);
assert!(frame_camera.forward[2] < -0.999);
assert!(!frame_camera.is_mirrored);눈의 자리. ([x, y, z, 1] 원근, [0, 0, 0, 0] 직교)
Eye position. ([x, y, z, 1] perspective, [0, 0, 0, 0] orthographic)
반환Returns[f64; 4]
보는 방향. ([x, y, z], 단위)
View direction. ([x, y, z], unit)
반환Returns[f64; 3]
ToonProgramPrewarmOptionsstruct traits Clone, Copy, Default
미리 짓기에 더할 조합 목록. (원본 prewarmDrawQueue 의 options, 기본값은 아무것도 더하지 않음)
List of combinations to add to the prewarm. (The options of the original prewarmDrawQueue; the default adds nothing)
use vanilla::ToonProgramPrewarmOptions;
let options = ToonProgramPrewarmOptions::default();
assert!(options.light_feature_list.is_empty());더 읽을 그리기 줄. (나중에 나올 재질이나 인스턴스 꼴을 담은 줄, 원본 queueList)
Draw queues to read more from. (Queues holding materials or instance layouts that appear later; the original queueList)
반환Returns&'a [&'a ToonDrawQueue<'q>]
그리기 줄의 모든 그리기에 더 맞춰 볼 빛 묶음. (지금 값의 기능 비트를 쓴다, 원본 lightSetList)
Light sets to additionally match against every draw in the draw queue. (Uses the feature bits of their current values; the original lightSetList)
반환Returns&'a [&'a ToonLightSet]
더 맞춰 볼 빛 묶음 쪽 기능 조합. (조합마다 "rampTexture", "shadeStops", "rim", "shadeRim", "intensityLimit" 중 더 켜질 것의 이름, 원본 lightFeatureList)
Light set side feature combinations to additionally match. (Per combination, the names among "rampTexture", "shadeStops", "rim", "shadeRim" and "intensityLimit" that will additionally turn on; the original lightFeatureList)
반환Returns&'a [&'a [&'a str]]
ToonProgramPrewarmstruct
프로그램 변형 미리 짓기의 진행. (ToonRenderer::prewarm_draw_queue 의 결과, 원본 ToonProgramPrewarm)
- 병렬 컴파일 확장이 없으면 만들어질 때 이미 끝나 있다. 있으면 맡긴 컴파일을 step 으로 프레임마다 나눠 끝낸다.
Progress of prewarming program variants. (The result of ToonRenderer::prewarm_draw_queue, the original ToonProgramPrewarm)
- Without the parallel compile extension it is already finished when created. With it, the handed-off compiles are finished a few per frame by step.
use vanilla::{ToonDrawQueue, ToonRenderer};
fn update_loading(gl: &vanilla::GlContext, renderer: &mut ToonRenderer, queue: &ToonDrawQueue) -> bool {
let mut prewarm = renderer.prewarm_draw_queue(gl, queue);
while !prewarm.step(gl, renderer) {
// Call again each frame.
}
prewarm.is_ready()
}한 걸음. (끝난 컴파일을 끝내 프로그램 칸에 넣는다, 한 걸음에 몇 개까지만, 프레임마다 부른다)
One step. (Finishes compiled programs and puts them in the program slots, only a few per step, call it every frame)
- gl&crate::GlContext
- 렌더러를 지은 GL 컨텍스트.GL context that built the renderer.
- renderer&mut ToonRenderer
- prewarm_draw_queue 를 부른 렌더러.The renderer that prewarm_draw_queue was called on.
반환Returnsbool 모두 끝났으면 true.True if everything is finished.
다 지었는지. (그려도 되지만 안 지은 것은 그 자리에서 짓는다)
Whether everything is built. (Drawing is allowed anyway; anything not built is built on the spot)
반환Returnsbool 모두 지었으면 true.True if everything is built.
짝Counterpart: vanilla.js ToonProgramPrewarm.isReady
다 지을 때까지 기다리기. (남은 컴파일을 이 호출 안에서 모두 끝낸다)
Waits until everything is built. (Finishes all the remaining compiles inside this call)
- gl&crate::GlContext
- 렌더러를 지은 GL 컨텍스트.GL context that built the renderer.
- renderer&mut ToonRenderer
- prewarm_draw_queue 를 부른 렌더러.The renderer that prewarm_draw_queue was called on.
짝Counterpart: vanilla.js ToonProgramPrewarm.wait
ToonRendererstruct
툰 렌더러. (머리말 참고)
Toon renderer. (see the header comment)
use vanilla::{create_capsule_geometry, Matrix4, MeshBuilder, ToonDrawOptions, ToonPartOptions, ToonRenderer, Vector3};
fn draw_once(gl: &vanilla::GlContext) -> Result<(), String> {
let mut renderer = ToonRenderer::new(gl)?;
renderer.set_light([-0.4, -1.0, -0.3], [1.0, 0.96, 0.9], [0.45, 0.5, 0.6], [0.25, 0.22, 0.2]);
renderer.set_outline_color([0.1, 0.06, 0.08, 1.0]);
let mut builder = MeshBuilder::new();
builder.add_part(&create_capsule_geometry(0.3, 0.6, 8, 16), &Matrix4::create_identity(), "#a0d0a0", ToonPartOptions { outline_width: 0.02, ..ToonPartOptions::default() });
let mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("empty mesh")?;
let view_matrix = Matrix4::create_look_at(Vector3::create(0.0, 1.0, 3.0), Vector3::create(0.0, 0.0, 0.0), Vector3::create(0.0, 1.0, 0.0));
let projection_matrix = Matrix4::create_perspective(0.8, 1.0, 0.1, 20.0);
renderer.begin_frame_with_matrices(gl, &view_matrix, &projection_matrix);
renderer.draw_mesh(gl, &mesh, &Matrix4::create_identity(), ToonDrawOptions::default());
renderer.draw_mesh(gl, &mesh, &Matrix4::create_translation(0.0, 0.0, 50.0), ToonDrawOptions::default());
renderer.end_frame(gl);
let statistics = renderer.get_frame_statistics();
assert_eq!((statistics.drawn_object_count, statistics.culled_object_count), (1, 1));
renderer.delete_mesh(gl, mesh);
renderer.destroy(gl);
Ok(())
}생성. (기본 세 프로그램을 짓는다, 색 공간은 엔진의 것)
Creation. (builds the three default programs, the color space is the engine's)
- gl&crate::GlContext
- 그릴 GL 컨텍스트.GL context to draw with.
반환ReturnsResult<ToonRenderer, String> 새 렌더러. 기본 프로그램이나 텍스처를 짓지 못하면 Err(오류 글).New renderer. Err(error text) if the default programs or textures cannot be built.
짝Counterpart: vanilla.js ToonRenderer.constructor
셰이더 소스. ((정점, 조각) 세 벌: 몸, 바깥선, 그림자 깊이, 기본 프로그램)
Shader sources. (three (vertex, fragment) pairs: body, outline, shadow depth, for the default programs)
반환Returns[(String, String); 3] (정점, 조각) 소스 세 벌. (몸, 바깥선, 그림자 깊이)Three sets of (vertex, fragment) sources. (body, outline, shadow depth)
짝Counterpart: vanilla.js ToonRenderer.readProgramSources
pub fn read_material_program_sources(material: Option<&ToonMaterial>, instance_layout: Option<&ToonInstanceLayout>, is_ambient_occlusion: bool, color_space: ColorSpace) -> [(String, String); 3]#머티리얼과 인스턴스 꼴의 셰이더 소스. ((정점, 조각) 세 벌, 어트리뷰트 자리는 compose_toon_program_sources 의 attribute_locations)
Shader sources for a material and instance layout. (three (vertex, fragment) pairs, the attribute locations are attribute_locations of compose_toon_program_sources)
- materialOption<&ToonMaterial>
- 셰이더 조각을 끼울 머티리얼. (None 이면 빈 조각)Material whose shader chunks are inserted. (None means empty chunks)
- instance_layoutOption<&ToonInstanceLayout>
- 인스턴스 꼴. (None 이면 없음)Instance layout. (None means none)
- is_ambient_occlusionbool
- 모서리 어둠을 켠 프레임의 몸 프로그램인지. (원본 기본 false, set_ambient_occlusion_texture 로 텍스처를 건 프레임은 이 몸 프로그램을 쓴다)Whether it is the body program of a frame with ambient occlusion on. (original default false; frames with a texture set by set_ambient_occlusion_texture use this body program)
- color_spaceColorSpace
- 색 공간. (원본 기본은 엔진의 색 공간, 렌더러가 짓는 것과 같은 값을 준다)Color space. (original default is the engine's color space; pass the same value the renderer builds with)
반환Returns[(String, String); 3] (정점, 조각) 소스 세 벌. (몸, 바깥선, 그림자 깊이)Three sets of (vertex, fragment) sources. (body, outline, shadow depth)
pub fn new_with_options(gl: &crate::GlContext, options: ToonRendererOptions) -> Result<ToonRenderer, String>#꼴을 주어 생성. (원본 new ToonRenderer(gl, options), 기본 세 프로그램을 짓는다)
- 색 공간은 생성 때 정하고 바뀌지 않는다. (get_color_space) Gamma(기본): 넘기는 색(꼭짓점 색, 틴트, 빛남 색, 데칼 색, 바깥선 색)과 색 텍스처는 sRGB 이고 바탕색, 틴트, 데칼은 sRGB 로 곱하고 섞은 뒤 pow(색, 2.2) 로 선형으로 바꿔 빛을 셈한다. 화면에 낼 때 pow(1 / 2.2) 를 건다. (HDR 출력이면 선형 그대로) Linear: 색 텍스처를 sRGB 형식으로 올려 GPU 가 선형으로 풀고, 넘기는 색은 sRGB 표준 곡선(IEC 61966-2-1)으로 선형으로 바꿔 곱하고 섞는다. 화면에 낼 때 같은 곡선으로 sRGB 로 바꾼다. 셰이더 소스마다 #define VANILLA_COLOR_SPACE_LINEAR 1 이 들어간다. (ToonPostProcess, ToonScreenOutline 도 같은 값으로 짓는다)
Creation with options. (original new ToonRenderer(gl, options), builds the three default programs)
- The color space is fixed at creation and does not change. (get_color_space) Gamma (default): passed colors (vertex color, tint, emissive color, decal color, outline color) and color textures are sRGB; base color, tint and decal are multiplied and mixed in sRGB and then converted to linear with pow(color, 2.2) to compute light. pow(1 / 2.2) is applied for the screen. (linear as is for HDR output) Linear: color textures are uploaded in an sRGB format so the GPU decodes them to linear, and passed colors are converted to linear with the standard sRGB curve (IEC 61966-2-1) before they are multiplied and mixed. The same curve converts back to sRGB for the screen. Every shader source gets #define VANILLA_COLOR_SPACE_LINEAR 1. (ToonPostProcess and ToonScreenOutline are built with the same value too)
- gl&crate::GlContext
- 그릴 GL 컨텍스트.GL context to draw with.
- optionsToonRendererOptions
- 색 공간. (ToonRendererOptions)Color space. (ToonRendererOptions)
반환ReturnsResult<ToonRenderer, String> 새 렌더러. 기본 프로그램이나 텍스처를 짓지 못하면 Err(오류 글).New renderer. Err(error text) if the default programs or textures cannot be built.
머티리얼 짓기. (셰이더 조각, toonmaterial.rs 머리말)
Creates a material. (shader snippets, toonmaterial.rs header comment)
- chunksToonMaterialChunks
- 셰이더 조각. (name, uniform_chunk, surface_chunk, light_chunk, vertex_chunk, 빈 글이면 엔진의 빈 함수)Shader chunks. (name, uniform_chunk, surface_chunk, light_chunk, vertex_chunk, an empty text means the engine's empty function)
반환ReturnsToonMaterial 지은 머티리얼.The built material.
짝Counterpart: vanilla.js ToonRenderer.createMaterial
처음 보는 몸 변형을 맡기고 기본 몸으로 그릴지 정하기. (원본 setAsyncProgramBuild, 기본 true, 병렬 컴파일 확장이 없으면 이 값과 상관없이 그 자리에서 짓는다)
Sets whether to hand off a body variant first seen and draw with the default body meanwhile. (The original setAsyncProgramBuild; default true; without the parallel compile extension it is built on the spot regardless of this value)
- is_asyncbool
- true 면 장면 중간에 처음 보는 몸 변형을 그 자리에서 짓지 않고, 다 지어질 때까지 전부 켠 기본 몸(같은 화면)으로 그린다. false 면 그 자리에서 짓고 기다린다.If true, a body variant first seen mid-scene is not built on the spot; it is drawn with the default body with every feature on (same picture) until it finishes building. If false, it is built on the spot and waited for.
짝Counterpart: vanilla.js ToonRenderer.setAsyncProgramBuild
use vanilla::ToonRenderer;
fn configure(gl: &vanilla::GlContext) -> Result<(), String> {
let mut renderer = ToonRenderer::new(gl)?;
renderer.set_async_program_build(false);
assert!(!renderer.is_async_program_build());
Ok(())
}처음 보는 몸 변형을 맡기고 기본 몸으로 그리는지 읽기. (원본 isAsyncProgramBuild)
Reads whether a body variant first seen is handed off and the default body is drawn meanwhile. (The original isAsyncProgramBuild)
반환Returnsbool 맡기고 기본 몸으로 그리면 true. (기본 true)True if handed off and drawn with the default body. (Default true)
짝Counterpart: vanilla.js ToonRenderer.isAsyncProgramBuild
use vanilla::ToonRenderer;
fn read(gl: &vanilla::GlContext) -> Result<(), String> {
let renderer = ToonRenderer::new(gl)?;
assert!(renderer.is_async_program_build());
Ok(())
}pub fn prepare_material(&mut self, gl: &crate::GlContext, material: Option<&ToonMaterial>, instance_layout: Option<&ToonInstanceLayout>) -> bool#머티리얼의 프로그램을 미리 짓기. (처음 그릴 때의 멈춤을 피할 때, 짓지 못하면 false)
Prebuilds a material's programs. (to avoid a stall on first draw, false on failure)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- materialOption<&ToonMaterial>
- 미리 지을 머티리얼. (None 이면 기본 프로그램)Material to build in advance. (None means the default program)
- instance_layoutOption<&ToonInstanceLayout>
- 함께 쓸 인스턴스 꼴. (None 이면 없음)Instance layout to use with it. (None means none)
반환Returnsbool 짓지 못하면 false.false if it could not be built.
짝Counterpart: vanilla.js ToonRenderer.prepareMaterial
pub fn prewarm_draw_queue(&mut self, gl: &crate::GlContext, queue: &ToonDrawQueue) -> ToonProgramPrewarm#그리기 줄에 담긴 것이 쓸 프로그램 변형을 그리지 않고 미리 짓기. (원본 prewarmDrawQueue, 유니티 ShaderVariantCollection.WarmUp, 언리얼 PSO 캐시 꼴)
- 머티리얼, 인스턴스 꼴, 몸 기능 비트(빛 묶음과 그리기 꼴이 정함), 모서리 어둠 몸, 바깥선, 그림자 깊이를 그리기 줄이 그릴 때와 같은 열쇠로 짓는다.
- 첫 그리기에서 처음 보는 조합의 프로그램을 짓느라 한 프레임이 끊기는 것을 불러오는 동안으로 옮긴다. 장면을 담은 뒤 첫 프레임 앞에서 한 번 부른다.
- GL_KHR_parallel_shader_compile 이 있으면(웹은 같은 확장) 컴파일만 맡기고, 프레임마다 ToonProgramPrewarm::step 으로 끝났는지 물어 나눠 끝낸다. 없으면 이 호출 안에서 짓는다.
- 미리 짓기가 끝나기 전에 그려도 된다. 아직 안 지어진 변형은 그 자리에서 지어 쓴다. (동작은 같다)
- 그리기 줄이 쓰는 인스턴스 꼴이 생기면 그 꼴의 변형도 같은 열쇠로 짓는다. (ToonProgramRequest 의 instance_layout)
Prewarms, without drawing, the program variants that the items in a draw queue will use. (The original prewarmDrawQueue; same idea as Unity ShaderVariantCollection.WarmUp and Unreal PSO caches)
- Builds the material, body feature bits (decided by the light set and draw options), ambient occlusion body, outline and shadow depth programs with the same keys the draw queue uses when drawing.
- Moves the one-frame hitch of building a program for a combination first seen in the first draw into loading time. Call it once after adding the scene and before the first frame.
- With GL_KHR_parallel_shader_compile (the web uses the same extension) it only hands off compiling and finishes the compiled ones each frame with ToonProgramPrewarm::step. Without it, programs are built inside this call.
- Drawing before the prewarm finishes is fine. A variant not built yet is built on the spot. (Same behavior)
- Once the draw queue gets instance layouts, their variants are built with the same keys. (instance_layout of ToonProgramRequest)
- gl&crate::GlContext
- 렌더러를 지은 GL 컨텍스트.GL context that built the renderer.
- queue&ToonDrawQueue
- 변형을 읽을 그리기 줄. (담은 것만 읽고 그리지 않는다)Draw queue to read the variants from. (Only reads what was added; does not draw)
반환ReturnsToonProgramPrewarm 미리 짓기의 진행. (is_ready, step, wait)Progress of the prewarm. (is_ready, step, wait)
짝Counterpart: vanilla.js ToonRenderer.prewarmDrawQueue
use vanilla::{create_sphere_geometry, Matrix4, MeshBuilder, ToonDrawOptions, ToonDrawQueue, ToonPartOptions, ToonRenderer};
fn prewarm(gl: &vanilla::GlContext) -> Result<(), String> {
let mut renderer = ToonRenderer::new(gl)?;
let mut builder = MeshBuilder::new();
builder.add_part(&create_sphere_geometry(0.5, 16, 10, std::f64::consts::PI), &Matrix4::create_identity(), "#f0e8e0", ToonPartOptions::default());
let mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("empty mesh")?;
let mut queue = ToonDrawQueue::new();
queue.add_mesh(&mesh, &Matrix4::create_identity(), ToonDrawOptions { casts_shadow: false, ..ToonDrawOptions::default() });
let mut prewarm = renderer.prewarm_draw_queue(gl, &queue);
prewarm.wait(gl, &mut renderer);
assert!(prewarm.is_ready());
Ok(())
}pub fn prewarm_draw_queue_with_options<'x, 'a: 'x, 'q: 'x>(&mut self, gl: &crate::GlContext, queue: &ToonDrawQueue<'a>, options: &ToonProgramPrewarmOptions<'_, 'q>) -> Result<ToonProgramPrewarm, String>#그리기 줄에 담긴 것에 게임이 장면 중간에 쓸 조합까지 더해 미리 짓기. (원본 prewarmDrawQueue(queue, options), 유니티 ShaderVariantCollection 처럼 조합 목록을 준다)
- 줄이 담은 변형에 options 의 빛 기능 조합, 빛 묶음, 다른 줄이 읽은 변형을 더해 지금 담기지 않은 것까지 같은 열쇠로 짓는다. 그 밖은 prewarm_draw_queue 와 같다.
- 빛 기능 이름이 rampTexture, shadeStops, rim, shadeRim, intensityLimit 가 아니면 아무것도 짓지 않고 Err 로 돌려준다. (원본은 던진다)
Prewarms what a draw queue holds plus the combinations the game will use mid-scene. (The original prewarmDrawQueue(queue, options); like Unity ShaderVariantCollection, you give a list of combinations)
- To the variants the queue holds it adds the light feature combinations of options, the light sets and the variants read from other queues, and builds even what is not in the queue now with the same keys. Everything else is the same as prewarm_draw_queue.
- If a light feature name is not rampTexture, shadeStops, rim, shadeRim or intensityLimit, nothing is built and Err is returned. (The original throws)
- gl&crate::GlContext
- 렌더러를 지은 GL 컨텍스트.GL context that built the renderer.
- queue&ToonDrawQueue<'a>
- 변형을 읽을 그리기 줄.Draw queue to read the variants from.
- options&ToonProgramPrewarmOptions<'_, 'q>
- 더 지을 조합 목록. (ToonProgramPrewarmOptions::default() 는 prewarm_draw_queue 와 같다)List of combinations to build in addition. (ToonProgramPrewarmOptions::default() is the same as prewarm_draw_queue)
반환ReturnsResult<ToonProgramPrewarm, String> 미리 짓기의 진행. 잘못된 빛 기능 이름이면 Err.Progress of the prewarm. Err if a light feature name is wrong.
use vanilla::{create_sphere_geometry, Matrix4, MeshBuilder, ToonDrawOptions, ToonDrawQueue, ToonPartOptions, ToonProgramPrewarmOptions, ToonRenderer};
fn prewarm(gl: &vanilla::GlContext) -> Result<(), String> {
let mut renderer = ToonRenderer::new(gl)?;
let mut builder = MeshBuilder::new();
builder.add_part(&create_sphere_geometry(0.5, 16, 10, std::f64::consts::PI), &Matrix4::create_identity(), "#f0e8e0", ToonPartOptions::default());
let mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("empty mesh")?;
let mut queue = ToonDrawQueue::new();
queue.add_mesh(&mesh, &Matrix4::create_identity(), ToonDrawOptions { casts_shadow: false, ..ToonDrawOptions::default() });
let rim: &[&str] = &["rim"];
let rim_and_shade_rim: &[&str] = &["rim", "shadeRim"];
let options = ToonProgramPrewarmOptions { light_feature_list: &[rim, rim_and_shade_rim], ..ToonProgramPrewarmOptions::default() };
let mut prewarm = renderer.prewarm_draw_queue_with_options(gl, &queue, &options)?;
prewarm.wait(gl, &mut renderer);
assert!(prewarm.is_ready());
Ok(())
}머티리얼의 프로그램 지우기. (모든 인스턴스 꼴의 것, 다시 그리면 새로 짓는다)
Deletes a material's programs. (for all instance layouts, rebuilt when drawn again)
- gl&crate::GlContext
- 프로그램을 지은 GL 컨텍스트.GL context that built the programs.
- material&ToonMaterial
- 프로그램을 지울 머티리얼.Material whose programs to delete.
짝Counterpart: vanilla.js ToonRenderer.deleteMaterial
빛 묶음 짓기. (그리기마다 ToonDrawOptions 의 light_set 으로 줄 것, 기본 빛과 같은 값으로 시작)
Creates a light set. (to pass per draw through light_set of ToonDrawOptions, starts with the same values as the default lighting)
반환ReturnsToonLightSet 기본 빛과 같은 값으로 시작하는 새 빛 묶음.A new light set starting with the same values as the default light.
짝Counterpart: vanilla.js ToonRenderer.createLightSet
기본 빛 묶음 반환.
Returns the default light set.
반환Returns&ToonLightSet 기본 빛 묶음.The default light set.
짝Counterpart: vanilla.js ToonRenderer.getLightSet
기본 빛 묶음 반환. (고칠 때)
Returns the default light set. (for modifying it)
반환Returns&mut ToonLightSet 기본 빛 묶음. (고칠 수 있는 참조)The default light set. (a mutable reference)
짝Counterpart: vanilla.js ToonRenderer.getLightSet
pub fn create_instance_layout(&self, attributes: &[(&str, usize)]) -> Result<ToonInstanceLayout, String>#인스턴스 꼴 짓기. ((이름, 크기) 목록, toonmaterial.rs 의 ToonInstanceLayout)
Creates an instance layout. ((name, size) list, ToonInstanceLayout in toonmaterial.rs)
- attributes&[(&str, usize)]
- (이름, 크기) 의 목록.List of (name, size).
반환ReturnsResult<ToonInstanceLayout, String> 지은 인스턴스 꼴. 이름이 셰이더 이름 꼴이 아니거나 겹치거나, 크기가 맞지 않거나, 사용자 어트리뷰트가 너무 많으면 Err(오류 글).Built instance layout. Err(error text) if a name is not a shader name or is duplicated, a size does not fit, or there are too many user attributes.
짝Counterpart: vanilla.js ToonRenderer.createInstanceLayout
pub fn create_instance_buffer(&self, gl: &crate::GlContext, instance_layout: &ToonInstanceLayout, data: &[f32], usage: ToonBufferUsage) -> Result<ToonInstanceBuffer, String>#영구 인스턴스 버퍼 짓기. (꼴의 수 개수씩 담은 data, ToonBufferUsage::Static 이면 한 번 올리고 오래 그림)
Creates a persistent instance buffer. (data holding the layout's value count per instance, with ToonBufferUsage::Static it is uploaded once and drawn for a long time)
- gl&crate::GlContext
- 버퍼를 지을 GL 컨텍스트.GL context to build the buffer with.
- instance_layout&ToonInstanceLayout
- 인스턴스 하나의 꼴.Layout of one instance.
- data&[f32]
- 꼴의 수 개수씩 인스턴스를 이어 담은 수.Numbers of instances stored one after another, layout float count each.
- usageToonBufferUsage
- ToonBufferUsage 의 값. (Static 이면 한 번 올리고 오래 그림)A ToonBufferUsage value. (Static uploads once and draws for a long time)
반환ReturnsResult<ToonInstanceBuffer, String> 인스턴스 버퍼. 버퍼를 짓지 못하면 Err(GL 의 오류 글).Instance buffer. Err(the GL error text) if the buffer cannot be built.
짝Counterpart: vanilla.js ToonRenderer.createInstanceBuffer
pub fn update_instance_buffer(&self, gl: &crate::GlContext, instance_buffer: &ToonInstanceBuffer, data: &[f32])#인스턴스 버퍼 고치기. (전체를 다시 올림)
Updates an instance buffer. (re-uploads the whole thing)
- gl&crate::GlContext
- 버퍼를 지은 GL 컨텍스트.GL context that built the buffer.
- instance_buffer&ToonInstanceBuffer
- create_instance_buffer 의 결과.Result of create_instance_buffer.
- data&[f32]
- 새 수. (인스턴스 수가 바뀌어도 된다)New numbers. (The instance count may change)
짝Counterpart: vanilla.js ToonRenderer.updateInstanceBuffer
pub fn update_instance_buffer_range(&self, gl: &crate::GlContext, instance_buffer: &ToonInstanceBuffer, first_instance: usize, data: &[f32]) -> Result<(), String>#인스턴스 버퍼의 일부 고치기. (first_instance 번째부터 data 의 인스턴스 수만큼만 올림, bufferSubData)
Update part of an instance buffer. (uploads only as many instances as data holds, from instance first_instance, bufferSubData)
- gl&crate::GlContext
- 버퍼를 지은 GL 컨텍스트.GL context that built the buffer.
- instance_buffer&ToonInstanceBuffer
- create_instance_buffer 의 결과.Result of create_instance_buffer.
- first_instanceusize
- 고칠 첫 인스턴스 번호. (0 부터)Number of the first instance to update. (from 0)
- data&[f32]
- 꼴의 수 개수씩 고칠 인스턴스를 이어 담은 수. (버퍼에 든 인스턴스 수를 넘으면 Err, 늘리려면 update_instance_buffer)The numbers of the instances to update, laid out one layout float count after another. (Err beyond the instances in the buffer; use update_instance_buffer to grow it)
반환ReturnsResult<(), String> 고쳤으면 Ok. 자리가 맞지 않으면 Err(까닭 글).Ok when updated. Err(reason text) when the range does not fit.
짝Counterpart: vanilla.js ToonRenderer.updateInstanceBufferRange
use vanilla::{create_octahedron_geometry, Matrix4, MeshBuilder, ToonBufferUsage, ToonDrawOptions, ToonPartOptions, ToonRenderer, Vector3};
fn move_one_rock(gl: &vanilla::GlContext) -> Result<(), String> {
let mut renderer = ToonRenderer::new(gl)?;
let mut builder = MeshBuilder::new();
builder.add_part(&create_octahedron_geometry(0.3), &Matrix4::create_identity(), "#909098", ToonPartOptions { has_outline: true, ..ToonPartOptions::default() });
let rock_mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("mesh failed")?;
let instance_layout = renderer.create_instance_layout(&[("instanceMatrix", 16), ("instanceTint", 4)])?;
let mut data: Vec<f32> = Vec::new();
for index in 0..3 {
data.extend_from_slice(Matrix4::create_translation(index as f64 - 1.0, 0.0, 0.0).get_elements());
data.extend_from_slice(&[1.0, 1.0, 1.0, 1.0]);
}
let instance_buffer = renderer.create_instance_buffer(gl, &instance_layout, &data, ToonBufferUsage::Dynamic)?;
let mut moved: Vec<f32> = Vec::new();
moved.extend_from_slice(Matrix4::create_translation(0.0, 0.5, 0.0).get_elements());
moved.extend_from_slice(&[1.0, 0.6, 0.6, 1.0]);
renderer.update_instance_buffer_range(gl, &instance_buffer, 1, &moved)?;
let view_matrix = Matrix4::create_look_at(Vector3::create(0.0, 2.0, 4.0), Vector3::create(0.0, 0.0, 0.0), Vector3::create(0.0, 1.0, 0.0));
renderer.begin_frame_with_matrices(gl, &view_matrix, &Matrix4::create_perspective(0.8, 1.0, 0.1, 30.0));
renderer.draw_mesh_instance_buffer(gl, &rock_mesh, &instance_buffer, 3, ToonDrawOptions::default());
renderer.end_frame(gl);
assert_eq!(instance_buffer.get_generation(), 1);
Ok(())
}pub fn delete_instance_buffer(&self, gl: &crate::GlContext, instance_buffer: ToonInstanceBuffer)#인스턴스 버퍼 지우기. (그 버퍼로 지은 버텍스 어레이도, 모형보다 먼저 지운다)
Deletes an instance buffer. (also the vertex arrays built with it, delete before the model)
- gl&crate::GlContext
- 버퍼를 지은 GL 컨텍스트.GL context that built the buffer.
- instance_bufferToonInstanceBuffer
- create_instance_buffer 의 결과.Result of create_instance_buffer.
짝Counterpart: vanilla.js ToonRenderer.deleteInstanceBuffer
pub fn create_texture(&self, gl: &crate::GlContext, width: u32, height: u32, pixels: &[u8], options: ToonTextureOptions) -> Result<GlTexture, String>#텍스처 짓기. (RGBA 바이트 너비 x 높이 x 4, 그림 풀기는 decode_glb_image 나 image 크레이트)
- 선형 색 공간(ColorSpace::Linear)이면 색 텍스처(바탕색, 빛남, 데칼, 매트캡, 천사 고리, 램프)를 sRGB 형식(SRGB8_ALPHA8)으로 올린다. GPU 가 읽을 때 선형으로 풀어 거르기와 밉맵이 선형 공간에서 일어나고, 셰이더는 받은 값을 선형 색으로 그대로 쓴다. (유니티, 언리얼의 sRGB 텍스처와 같음) 노멀, 마스크, 번호 같은 자료 텍스처는 is_color_data: false 로 RGBA8 에 그대로 올린다. (머티리얼 조각이 읽는 자료)
- 감마 색 공간(기본)은 is_color_data 와 상관없이 RGBA 로 올리고 셰이더가 색 텍스처를 pow 2.2 로 선형으로 바꾼다. (지금까지와 같음)
Creates a texture. (RGBA bytes width x height x 4, decode images with decode_glb_image or the image crate)
- In the linear color space (ColorSpace::Linear), color textures (base color, emission, decal, matcap, angel ring, ramp) are uploaded in an sRGB format (SRGB8_ALPHA8). The GPU decodes them to linear when reading, so filtering and mipmaps happen in linear space, and the shader uses the values as linear colors as they are. (the same as sRGB textures in Unity and Unreal) Data textures such as normals, masks and ids are uploaded to RGBA8 as they are with is_color_data: false. (data read by material chunks)
- The gamma color space (default) uploads RGBA regardless of is_color_data, and the shader converts color textures to linear with pow 2.2. (the same as before)
- gl&crate::GlContext
- 텍스처를 지을 GL 컨텍스트.GL context to build the texture with.
- widthu32
- 너비. (픽셀)Width. (pixels)
- heightu32
- 높이. (픽셀)Height. (pixels)
- pixels&[u8]
- RGBA 바이트. (너비 x 높이 x 4 개 이상)RGBA bytes. (width x height x 4 or more)
- optionsToonTextureOptions
- 밉맵, 되풀이, 고르게 읽기, 색인지. (ToonTextureOptions)Mipmaps, repeat, filtering, whether it is a color. (ToonTextureOptions)
반환ReturnsResult<GlTexture, String> 지은 RGBA 텍스처. 너비나 높이가 0 이거나 바이트가 모자라거나 텍스처를 짓지 못하면 Err(오류 글).Built RGBA texture. Err(error text) if the width or height is 0, the bytes are short, or the texture cannot be built.
짝Counterpart: vanilla.js ToonRenderer.createTexture
텍스처 지우기.
Deletes a texture.
- gl&crate::GlContext
- 텍스처를 지은 GL 컨텍스트.GL context that built the texture.
- textureGlTexture
- 지울 텍스처.Texture to delete.
짝Counterpart: vanilla.js ToonRenderer.deleteTexture
렌더러 지우기. (모든 프로그램과 빈 텍스처, 모형과 인스턴스 버퍼와 텍스처는 따로)
Deletes the renderer. (all programs and the empty texture, models, instance buffers and textures are deleted separately)
- gl&crate::GlContext
- 렌더러를 지은 GL 컨텍스트.GL context that built the renderer.
짝Counterpart: vanilla.js ToonRenderer.destroy
pub fn create_mesh(&self, gl: &crate::GlContext, arrays: &ToonMeshArrays) -> Option<ToonMesh>#모형 올리기. (몸이 비면 None)
- GL 버퍼나 버텍스 어레이를 짓다 실패하면 그때까지 지은 것을 지우고 None 을 돌려준다.
Uploads a mesh. (None if the body is empty)
- If building a GL buffer or vertex array fails, deletes what was built so far and returns None.
- gl&crate::GlContext
- 모형을 올릴 GL 컨텍스트.GL context to upload the model with.
- arrays&ToonMeshArrays
- MeshBuilder::read_arrays 나 read_glb_arrays 의 결과.Result of MeshBuilder::read_arrays or read_glb_arrays.
반환ReturnsOption<ToonMesh> GPU 에 올린 모형. (몸의 꼭짓점 번호가 비거나 GL 버퍼를 짓지 못하면 None)Model uploaded to the GPU. (None if the body vertex indices are empty or GL buffers cannot be built)
짝Counterpart: vanilla.js ToonRenderer.createMesh
모형 지우기.
Deletes a model.
- gl&crate::GlContext
- 모형을 올린 GL 컨텍스트.GL context that uploaded the model.
- meshToonMesh
- create_mesh 의 결과.Result of create_mesh.
짝Counterpart: vanilla.js ToonRenderer.deleteMesh
프레임의 그리기 상태 걸기. (섞기 끔, 깊이 시험 LEQUAL 과 쓰기, 뒷면 가리기, 앞면 CCW, ToonDrawQueue 가 단계 콜백 뒤에 다시 건다)
Applies the frame's draw state. (blending off, depth test LEQUAL and depth write, back-face culling, front face CCW, ToonDrawQueue reapplies it after stage callbacks)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
짝Counterpart: vanilla.js ToonRenderer.applyFrameState
프레임 시작. (보기와 투영과 절두체를 정하고, 앞의 상태를 적어 둔 뒤 깊이 시험과 면 가리기를 켠다, 깊이를 비우는 것은 부르는 쪽이 정한다)
Begins a frame. (sets view, projection and frustum, records the previous state, then enables depth testing and face culling, the caller decides whether to clear depth)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- view_projection_matrix&Matrix4
- 보기와 투영 행렬. (투영 x 보기)View and projection matrix. (Projection x view)
짝Counterpart: vanilla.js ToonRenderer.beginFrame
프레임 끝. (적어 둔 상태로 돌린다)
Ends a frame. (restores the recorded state)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
짝Counterpart: vanilla.js ToonRenderer.endFrame
카메라로 프레임 시작. (Camera3D 의 보기와 투영으로 begin_frame)
Begins a frame with a camera. (begin_frame with the Camera3D's view and projection)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- camera&Camera3D
- Camera3D. (보기와 투영을 읽는다)Camera3D. (Reads view and projection)
짝Counterpart: vanilla.js ToonRenderer.beginFrameWithCamera
pub fn begin_frame_with_matrices(&mut self, gl: &crate::GlContext, view_matrix: &Matrix4, projection_matrix: &Matrix4)#보기와 투영 행렬로 프레임 시작. (Camera3D 없이, 투영 x 보기로 begin_frame)
Begins a frame with view and projection matrices. (without Camera3D, begin_frame with projection x view)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- view_matrix&Matrix4
- 보기 행렬.View matrix.
- projection_matrix&Matrix4
- 투영 행렬.Projection matrix.
짝Counterpart: vanilla.js ToonRenderer.beginFrameWithMatrices
이번 프레임의 카메라 반환. (보기와 투영에서 읽은 것)
Returns this frame's camera. (read from view and projection)
반환ReturnsToonFrameCamera 이번 프레임의 카메라. (position [x, y, z, w(1 원근, 0 직교)], forward, is_mirrored)Camera of this frame. (position [x, y, z, w(1 perspective, 0 orthographic)], forward, is_mirrored)
짝Counterpart: vanilla.js ToonRenderer.getFrameCamera
그릴 화면 사각형 설정. (뷰포트 픽셀, 왼쪽 위 원점, 다음 begin_frame 부터)
Sets the screen rectangle to draw into. (viewport pixels, top-left origin, from the next begin_frame)
- xf64
- 왼쪽 끝. (뷰포트 픽셀)Left edge. (Viewport pixels)
- yf64
- 위쪽 끝. (뷰포트 픽셀, 위가 0)Top edge. (Viewport pixels, top is 0)
- widthf64
- 너비. (픽셀)Width. (pixels)
- heightf64
- 높이. (픽셀)Height. (pixels)
짝Counterpart: vanilla.js ToonRenderer.setScreenRect
그릴 화면 사각형 풀기. (뷰포트 전체에 그림)
Clears the screen rectangle to draw into. (draws to the whole viewport)
짝Counterpart: vanilla.js ToonRenderer.clearScreenRect
그릴 화면 사각형 반환. (없으면 None)
Returns the screen rectangle to draw into. (None if none)
반환ReturnsOption<Rect> 그릴 화면 사각형. (없으면 None)Screen rectangle to draw in. (None if none)
짝Counterpart: vanilla.js ToonRenderer.getScreenRect
그림자 깊이 패스 시작. (ShadowMap 의 프레임버퍼에 빛의 보기와 투영으로, 앞의 프레임버퍼와 뷰포트는 end_shadow_pass 가 돌린다)
Begins the shadow depth pass. (into the ShadowMap's framebuffer with the light's view and projection, end_shadow_pass restores the previous framebuffer and viewport)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- shadow_map&ShadowMap
- ShadowMap. (깊이를 그릴 곳, update_light_matrix 로 빛 행렬을 정해 둔다)ShadowMap. (where depth is drawn, set the light matrix with update_light_matrix beforehand)
짝Counterpart: vanilla.js ToonRenderer.beginShadowPass
pub fn begin_shadow_atlas_pass(&mut self, gl: &crate::GlContext, shadow_atlas: &ShadowAtlas)#그림자 아틀라스 깊이 패스 시작. (아틀라스를 묶어 비우고 앞의 상태를 적어 둔다, 칸마다 set_shadow_atlas_tile 뒤에 draw_mesh 가 깊이만 그린다, 끝은 end_shadow_pass)
Begins the shadow atlas depth pass. (Binds and clears the atlas and notes the previous state, per tile draw_mesh draws only depth after set_shadow_atlas_tile, end with end_shadow_pass)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- shadow_atlas&ShadowAtlas
- ShadowAtlas.
짝Counterpart: vanilla.js ToonRenderer.beginShadowAtlasPass
pub fn set_shadow_atlas_tile(&mut self, gl: &crate::GlContext, shadow_atlas: &ShadowAtlas, tile_index: usize)#그림자 아틀라스의 칸 고르기. (그 칸의 보기와 투영과 절두체, 뷰포트를 건다, begin_shadow_atlas_pass 와 end_shadow_pass 사이)
Selects a tile of the shadow atlas. (Sets that tile's view, projection, frustum and viewport, between begin_shadow_atlas_pass and end_shadow_pass)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- shadow_atlas&ShadowAtlas
- ShadowAtlas.
- tile_indexusize
- 칸 번호.Cell index.
짝Counterpart: vanilla.js ToonRenderer.setShadowAtlasTile
그림자 깊이 패스 끝. (프레임버퍼와 뷰포트와 상태를 돌린다)
Ends the shadow depth pass. (restores the framebuffer, viewport and state)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
짝Counterpart: vanilla.js ToonRenderer.endShadowPass
경계 구가 절두체 안에 드는지. (모형 행렬로 옮긴 가운데, 가장 큰 크기를 곱한 반지름)
Whether the bounding sphere is inside the frustum. (center transformed by the model matrix, radius multiplied by the largest scale)
- mesh&ToonMesh
- create_mesh 의 결과.Result of create_mesh.
- model_matrix&Matrix4
- 모형 행렬.Model matrix.
반환Returnsbool 절두체 안에 들면 true.true if inside the frustum.
짝Counterpart: vanilla.js ToonRenderer.isVisible
pub fn draw_mesh(&mut self, gl: &crate::GlContext, mesh: &ToonMesh, model_matrix: &Matrix4, options: ToonDrawOptions)#모형 하나 그리기. (그림자 패스면 깊이만, 화면 밖이면 건너뛴다)
Draws one model. (depth only in the shadow pass, skipped if off-screen)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- mesh&ToonMesh
- create_mesh 의 결과.Result of create_mesh.
- model_matrix&Matrix4
- 모형 행렬.Model matrix.
- optionsToonDrawOptions
- 그리기 꼴. (ToonDrawOptions, 머리말)Draw options. (ToonDrawOptions, header comment)
짝Counterpart: vanilla.js ToonRenderer.drawMesh
pub fn draw_mesh_instanced(&mut self, gl: &crate::GlContext, mesh: &ToonMesh, instance_list: &[ToonInstance], options: ToonDrawOptions)#같은 모형 여럿을 한 번에 그리기. (GPU 인스턴싱, 화면 밖 인스턴스는 걸러 남은 것만 올린다)
- 뼈대 모형은 모든 인스턴스가 같은 자세다. (options 의 joint_matrices)
- 감기는 첫 인스턴스의 행렬로 가린다. (is_mirrored 를 주면 그것)
Draws many copies of the same model at once. (GPU instancing, off-screen instances are culled and only the rest are uploaded)
- For skeletal models, all instances share the same pose. (joint_matrices of options)
- The winding is decided by the first instance's matrix. (or by is_mirrored if given)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- mesh&ToonMesh
- create_mesh 의 결과.Result of create_mesh.
- instance_list&[ToonInstance]
- 인스턴스마다의 모형 행렬, 틴트, 빛남. (틴트는 곱하는 sRGB 와 알파, 빛남은 더하는 sRGB 와 선형 배, 모형 행렬은 아핀으로 읽는다)Model matrix, tint and emission per instance. (the tint is a multiplied sRGB and alpha, the emission is an added sRGB and linear multiplier, the model matrix is read as affine)
- optionsToonDrawOptions
- draw_mesh 와 같다. (모든 인스턴스에 같게 건다)Same as draw_mesh. (applied the same to every instance)
짝Counterpart: vanilla.js ToonRenderer.drawMeshInstanced
use vanilla::{create_octahedron_geometry, Matrix4, MeshBuilder, ToonDrawOptions, ToonInstance, ToonPartOptions, ToonRenderer, Vector3};
fn draw_glowing_rock(gl: &vanilla::GlContext) -> Result<(), String> {
let mut renderer = ToonRenderer::new(gl)?;
let mut builder = MeshBuilder::new();
builder.add_part(&create_octahedron_geometry(0.3), &Matrix4::create_identity(), "#909098", ToonPartOptions { has_outline: true, ..ToonPartOptions::default() });
let rock_mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("mesh failed")?;
let mut instance_list: Vec<ToonInstance> = (0..3).map(|index| ToonInstance { model_matrix: Matrix4::create_translation(index as f64 - 1.0, 0.0, 0.0), ..ToonInstance::default() }).collect();
instance_list[1].emissive_color = Some([1.0, 0.85, 0.3]);
instance_list[1].emissive_intensity = 0.35;
let view_matrix = Matrix4::create_look_at(Vector3::create(0.0, 2.0, 3.0), Vector3::create(0.0, 0.0, 0.0), Vector3::create(0.0, 1.0, 0.0));
renderer.begin_frame_with_matrices(gl, &view_matrix, &Matrix4::create_perspective(0.8, 1.0, 0.1, 30.0));
renderer.draw_mesh_instanced(gl, &rock_mesh, &instance_list, ToonDrawOptions::default());
renderer.end_frame(gl);
Ok(())
}pub fn draw_mesh_instance_buffer(&mut self, gl: &crate::GlContext, mesh: &ToonMesh, instance_buffer: &ToonInstanceBuffer, instance_count: usize, options: ToonDrawOptions)#영구 인스턴스 버퍼로 그리기. (버퍼 전체의 경계로 통째 거른다, instance_count 개, 꼴에 행렬이 없으면 정점 조각이 자리를 정하고 거르지 않는다)
Draw with a persistent instance buffer. (culls the whole buffer by its bounds, instance_count instances; when the layout has no matrix the vertex chunk decides the position and nothing is culled)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- mesh&ToonMesh
- create_mesh 의 결과.Result of create_mesh.
- instance_buffer&ToonInstanceBuffer
- create_instance_buffer 의 결과.Result of create_instance_buffer.
- instance_countusize
- 그릴 인스턴스 수. (버퍼에 든 수를 넘으면 자른다)Number of instances to draw. (Clamped if more than the buffer holds)
- optionsToonDrawOptions
- draw_mesh 와 같다. (material 의 정점 조각이 사용자 어트리뷰트를 읽는다, is_culled 가 false 면 거르지 않는다)Same as draw_mesh. (the vertex chunk of the material reads the user attributes; with is_culled false nothing is culled)
짝Counterpart: vanilla.js ToonRenderer.drawMeshInstanceBuffer
pub fn draw_mesh_outline(&mut self, gl: &crate::GlContext, mesh: &ToonMesh, model_matrix: &Matrix4, options: ToonDrawOptions)#모형 하나의 바깥선만 그리기. (거르지도 세지도 않는다, 껍데기가 없거나 has_outline 이 false 거나 그림자 패스면 그리지 않는다)
Draws only the outline of one model. (neither culled nor counted, not drawn if there is no shell, has_outline is false, or it is the shadow pass)
- gl&crate::GlContext
- GL 컨텍스트.GL context.
- mesh&ToonMesh
- create_mesh 의 결과.Result of create_mesh.
- model_matrix&Matrix4
- 모형 행렬.Model matrix.
- optionsToonDrawOptions
- draw_mesh 와 같다.Same as draw_mesh.
짝Counterpart: vanilla.js ToonRenderer.drawMeshOutline
pub fn set_light(&mut self, sun_direction: [f64; 3], sun_color: [f64; 3], sky_color: [f64; 3], ground_color: [f64; 3])#빛 설정. (해가 비추는 방향, 해의 색, 하늘색, 땅색, 모두 선형 색 0 ~, HDR 이면 1 을 넘어도 된다, 기본 빛 묶음)
Sets the lighting. (sun direction, sun color, sky color, ground color, all linear colors 0 ~, may exceed 1 with HDR, default light set)
- sun_direction[f64; 3]
- 해가 비추는 방향. ([x, y, z], 빛이 나아가는 쪽)Direction the sun shines. ([x, y, z], the way the light travels)
- sun_color[f64; 3]
- 해의 선형 색.Linear color of the sun.
- sky_color[f64; 3]
- 위에서 오는 바탕빛의 선형 색.Linear color of the ambient light from above.
- ground_color[f64; 3]
- 아래에서 오는 바탕빛의 선형 색.Linear color of the ambient light from below.
짝Counterpart: vanilla.js ToonRenderer.setLight
해가 비추는 방향 설정. (빛이 나아가는 쪽, toonlightset.rs 머리말)
Sets the sun direction. (the direction light travels, toonlightset.rs header comment)
- sun_direction[f64; 3]
- 빛이 나아가는 방향. ([x, y, z])Direction the light travels. ([x, y, z])
짝Counterpart: vanilla.js ToonRenderer.setSunDirection
해가 비추는 방향 반환. (ShadowMap::update_light_matrix 에 그대로 넘긴다)
Returns the sun direction. (pass it as is to ShadowMap::update_light_matrix)
반환Returns[f64; 3] 해가 비추는 방향. ([x, y, z])Direction the sun shines. ([x, y, z])
짝Counterpart: vanilla.js ToonRenderer.getSunDirection
채움 빛 설정. (빛이 나아가는 방향과 선형 색)
Sets the fill light. (direction light travels and linear color)
- fill_direction[f64; 3]
- 빛이 나아가는 방향. ([x, y, z])Direction the light travels. ([x, y, z])
- fill_color[f64; 3]
- 선형 색. (0 이면 없음)Linear color. (0 means none)
짝Counterpart: vanilla.js ToonRenderer.setFillLight
pub fn set_rim_light(&mut self, rim_color: [f64; 3], rim_power: f64, rim_feather: f64, rim_light_mask: f64)#림 빛 설정. (ToonLightSet::set_rim_light, 선형 색, 거듭제곱, 부드러움 0 ~ 1, 해를 받는 쪽에만 둘 몫 0 ~ 1)
Sets the rim light. (ToonLightSet::set_rim_light, linear color, power, softness 0 ~ 1, fraction kept only on the sunlit side 0 ~ 1)
- rim_color[f64; 3]
- 더할 선형 색.Linear color to add.
- rim_powerf64
- 거듭제곱. (0 이면 없음)Power. (0 means none)
- rim_featherf64
- 0 단단한 테 ~ 1 부드러운 테.0 hard rim ~ 1 soft rim.
- rim_light_maskf64
- 1 이면 해를 받는 쪽에만.1 means only on the side that receives the sun.
짝Counterpart: vanilla.js ToonRenderer.setRimLight
pub fn set_specular(&mut self, specular_strength: f64, specular_exponent: f64, specular_feather: f64, specular_color: [f64; 3])#하이라이트 설정. (ToonLightSet::set_specular, 세기, 지수, 부드러움 0 ~ 1, 선형 색)
Sets the specular highlight. (ToonLightSet::set_specular, strength, exponent, softness 0 ~ 1, linear color)
- specular_strengthf64
- 세기. (0 이면 없음)Strength. (0 means none)
- specular_exponentf64
- 블린 퐁 지수.Blinn-Phong exponent.
- specular_featherf64
- 0 단단한 점 ~ 1 부드러운 빛.0 hard spot ~ 1 soft light.
- specular_color[f64; 3]
- 선형 색.Linear color.
짝Counterpart: vanilla.js ToonRenderer.setSpecular
점광과 스포트라이트 설정. (ToonLightSet::set_point_lights)
Sets point lights and spotlights. (ToonLightSet::set_point_lights)
- point_light_list&[ToonPointLight]
- 점광과 스포트라이트 목록. (ToonLightSet::set_point_lights 의 꼴)List of point lights and spotlights. (the form of ToonLightSet::set_point_lights)
짝Counterpart: vanilla.js ToonRenderer.setPointLights
점광 수의 한도 설정. (ToonLightSet::set_point_light_limit)
Sets the limit on the number of point lights. (ToonLightSet::set_point_light_limit)
- point_light_limitusize
- 받을 점광 수. (0 ~ TOON_MAXIMUM_POINT_LIGHTS)Number of point lights to receive. (0 ~ TOON_MAXIMUM_POINT_LIGHTS)
짝Counterpart: vanilla.js ToonRenderer.setPointLightLimit
그늘 셋 설정. (ToonLightSet::set_shade, 유니티 툰 셰이더의 바탕, 1 차 그늘, 2 차 그늘)
Sets the three shades. (ToonLightSet::set_shade, base, 1st shade and 2nd shade of Unity Toon Shader)
- shadeToonShade
- 바탕에서 1 차, 2 차 그늘로 넘어가는 문턱, 부드러움, 색. (ToonShade)Thresholds, softness and colors from the base to the 1st and 2nd shade. (ToonShade)
짝Counterpart: vanilla.js ToonRenderer.setShade
pub fn set_shade_ramp(&mut self, positions: &[f64], colors: &[[f64; 3]], feathers: &[f64], is_half_lambert: bool)#그늘 램프 설정. (ToonLightSet::set_shade_ramp)
Sets the shade ramp. (ToonLightSet::set_shade_ramp)
- positions&[f64]
- 칸마다의 자리.Position per cell.
- colors&[[f64; 3]]
- 칸마다의 선형 배.Linear multiplier per cell.
- feathers&[f64]
- 칸마다의 부드러움.Softness per cell.
- is_half_lambertbool
- 반 램버트로 셀지.Whether to count with half Lambert.
짝Counterpart: vanilla.js ToonRenderer.setShadeRamp
그늘 램프 끄기. (부드러운 램버트)
Turns off the shade ramp. (smooth Lambert)
짝Counterpart: vanilla.js ToonRenderer.clearShadeRamp
고른 칸 설정. (ToonLightSet::set_band_count, 0 이면 부드럽게)
Sets uniform bands. (ToonLightSet::set_band_count, 0 for smooth)
- band_countu32
- 칸 수.Number of cells.
짝Counterpart: vanilla.js ToonRenderer.setBandCount
pub fn set_band_ramp(&mut self, thresholds: &[f64], values: &[f64], is_half_lambert: bool)#회색 칸 램프 설정. (ToonLightSet::set_band_ramp)
Sets the gray band ramp. (ToonLightSet::set_band_ramp)
- thresholds&[f64]
- 오름차순 문턱.Ascending thresholds.
- values&[f64]
- 칸마다의 받는 몫.Received amount per cell.
- is_half_lambertbool
- 반 램버트로 셀지.Whether to count with half Lambert.
짝Counterpart: vanilla.js ToonRenderer.setBandRamp
pub fn set_ramp_texture(&mut self, ramp_texture: Option<GlTexture>, is_half_lambert: bool)#램프 텍스처 설정. (ToonLightSet::set_ramp_texture, None 이면 칸으로)
Sets the ramp texture. (ToonLightSet::set_ramp_texture, None for bands)
- ramp_textureOption<GlTexture>
- create_texture 로 지은 램프 텍스처나 None.Ramp texture built with create_texture, or None.
- is_half_lambertbool
- 반 램버트로 셀지.Whether to count with half Lambert.
짝Counterpart: vanilla.js ToonRenderer.setRampTexture
빛 꼴 설정.
Sets the light model.
- light_modelToonLightModel
- 빛 꼴. (is_energy_normalized 가 true 면 바탕색 x 빛을 π 로 나눈다)Light model. (if is_energy_normalized is true, base color x light is divided by π)
짝Counterpart: vanilla.js ToonRenderer.setLightModel
바깥선 색 설정. (sRGB 0 ~ 1 과 알파)
Sets the outline color. (sRGB 0 ~ 1 and alpha)
- outline_color[f64; 4]
- [r, g, b, a] (sRGB 0 ~ 1 과 알파)[r, g, b, a] (sRGB 0 ~ 1 and alpha)
짝Counterpart: vanilla.js ToonRenderer.setOutlineColor
pub fn set_outline_distance_scale(&mut self, reference_distance: f64, minimum_scale: f64, maximum_scale: f64)#껍데기 바깥선의 거리 배 설정. (기준 거리에서 지은 굵기, 멀면 그만큼 굵게 밀어 화면 굵기를 맞춘다, 배는 가장 작은 것과 큰 것 사이, 기준 거리 0 이면 끔)
- 원근 카메라에서만 건다. 꼭짓점마다 카메라까지의 거리 / 기준 거리 를 굵기에 곱한다. (길티기어 Xrd 처럼 거리와 상관없이 비슷한 화면 굵기)
Sets the distance multiplier of the shell outline. (the width is built at the reference distance and pushed thicker by that much when far to keep the screen width, the multiplier is between the smallest and largest, reference distance 0 turns it off)
- Applied only with perspective cameras. The per-vertex distance to the camera / reference distance is multiplied into the width. (a similar screen width regardless of distance, like Guilty Gear Xrd)
- reference_distancef64
- 지은 굵기 그대로인 거리. (0 이면 끔)Distance at which the built thickness is kept. (0 turns it off)
- minimum_scalef64
- 가장 작은 배.Minimum scale.
- maximum_scalef64
- 가장 큰 배.Maximum scale.
짝Counterpart: vanilla.js ToonRenderer.setOutlineDistanceScale
껍데기 바깥선이 멀면 사라지는 거리 설정. (가까운 거리 이하는 지은 굵기, 먼 거리 이상은 0, 사이는 smoothstep, 먼 거리가 가까운 거리 이하면 끔, 유니티 툰 셰이더의 Nearest, Farthest Distance)
Sets the distance at which the shell outline fades when far. (Built width up to the near distance, 0 from the far distance, smoothstep in between, off if the far distance is not above the near distance, Nearest and Farthest Distance of the Unity Toon Shader)
- near_distancef64
- 지은 굵기 그대로인 거리.Distance at which the built thickness is kept.
- far_distancef64
- 굵기가 0 이 되는 거리.Distance at which the thickness becomes 0.
짝Counterpart: vanilla.js ToonRenderer.setOutlineFadeDistance
껍데기 바깥선이 사라지는 거리 반환. ([가까운 거리, 먼 거리])
Returns the distance at which the shell outline fades. ([near distance, far distance])
반환Returns[f64; 2] [가까운 거리, 먼 거리][near distance, far distance]
짝Counterpart: vanilla.js ToonRenderer.getOutlineFadeDistance
받을 점광과 스포트라이트 그림자 설정. (ShadowAtlas 나 None, 세기 0 ~ 1, 아틀라스는 기본 빛 묶음의 점광 목록으로 지은 것)
Sets the point light and spotlight shadows to receive. (ShadowAtlas or None, strength 0 ~ 1, the atlas is the one built from the point light list of the default light set)
- shadow_atlasOption<&ShadowAtlas>
- ShadowAtlas 나 None.ShadowAtlas or None.
- strengthf64
- 그림자 세기. (0 ~ 1)Shadow strength. (0 ~ 1)
짝Counterpart: vanilla.js ToonRenderer.setLocalShadows
빛 색 쓰기 설정. (ToonLightSet::set_light_color_usage)
Sets the light color usage. (ToonLightSet::set_light_color_usage)
- light_color_usageToonLightColorUsage
- 칸마다 해의 색을 쓸지. (ToonLightColorUsage)Whether each part uses the sun color. (ToonLightColorUsage)
짝Counterpart: vanilla.js ToonRenderer.setLightColorUsage
빛 세기 막기 설정. (ToonLightSet::set_light_intensity_limited, 기본 true)
Sets light intensity limiting. (ToonLightSet::set_light_intensity_limited, default true)
- is_limitedbool
- true 면 빛마다 받은 몫을 1 로 막는다. (기본 true)If true, limits what each light gives to 1. (Default true)
짝Counterpart: vanilla.js ToonRenderer.setLightIntensityLimited
그늘 쪽 림 빛 설정. (ToonLightSet::set_shade_rim_light)
Sets the shade-side rim light. (ToonLightSet::set_shade_rim_light)
- shade_rim_color[f64; 3]
- 더할 선형 색.Linear color to add.
- shade_rim_powerf64
- 거듭제곱. (0 이면 없음)Power. (0 means none)
짝Counterpart: vanilla.js ToonRenderer.setShadeRimLight
껍데기 바깥선의 거리 배 반환. ([기준 거리, 가장 작은 배, 가장 큰 배])
Returns the distance multiplier of the shell outline. ([reference distance, smallest multiplier, largest multiplier])
반환Returns[f64; 3] [기준 거리, 가장 작은 배, 가장 큰 배][reference distance, minimum scale, maximum scale]
짝Counterpart: vanilla.js ToonRenderer.getOutlineDistanceScale
HDR 출력 설정. (true 면 감마를 걸지 않은 선형 색을 낸다, ToonPostProcess 의 실수 렌더 타겟에 그릴 때)
Sets HDR output. (if true, outputs linear color without gamma, for drawing into the float render target of ToonPostProcess)
- is_hdr_outputbool
- true 면 감마를 걸지 않은 선형 색을 낸다.If true, outputs linear color without gamma.
짝Counterpart: vanilla.js ToonRenderer.setHdrOutput
받을 그림자 설정. (ShadowMap 이나 None, 세기 0 ~ 1, 원본 기본 세기는 0.6)
Sets the shadow to receive. (ShadowMap or None, strength 0 ~ 1, the original default strength is 0.6)
- shadow_mapOption<&ShadowMap>
- 받을 ShadowMap. (None 이면 그림자를 받지 않는다)ShadowMap to receive. (None means no shadows are received)
- strengthf64
- 그림자 세기 0 ~ 1.Shadow strength 0 ~ 1.
짝Counterpart: vanilla.js ToonRenderer.setShadow
이번 프레임의 그린 수와 거른 수.
This frame's drawn and culled counts.
반환ReturnsToonFrameStatistics 이번 프레임의 셈. (draw_call_count, drawn_object_count, culled_object_count)Counts of this frame. (draw_call_count, drawn_object_count, culled_object_count)
짝Counterpart: vanilla.js ToonRenderer.getFrameStatistics
pub fn get_program(&self, material: Option<&ToonMaterial>, instance_layout: Option<&ToonInstanceLayout>, kind: ToonProgramKind) -> Option<&ShaderProgram>#머티리얼과 인스턴스 꼴의 프로그램 반환. (지은 것만, 원본 getSolidProgram(material) 들)
Returns the programs for a material and instance layout. (only built ones, the original getSolidProgram(material) family)
- materialOption<&ToonMaterial>
- 머티리얼. (None 이면 빈 조각)Material. (None means empty chunks)
- instance_layoutOption<&ToonInstanceLayout>
- 인스턴스 꼴. (None 이면 없음)Instance layout. (None means none)
- kindToonProgramKind
- 프로그램 종류. (몸, 바깥선, 그림자 깊이)Program kind. (body, outline, shadow depth)
반환ReturnsOption<&ShaderProgram> 그 프로그램. (아직 짓지 않았거나 짓지 못했으면 None)That program. (None if it has not been built yet or could not be built)
색 공간 반환. (원본 getColorSpace, 생성 때 정한 값, 바뀌지 않는다)
Returns the color space. (original getColorSpace, fixed at creation, does not change)
반환ReturnsColorSpace ColorSpace::Gamma 나 ColorSpace::Linear.ColorSpace::Gamma or ColorSpace::Linear.
짝Counterpart: vanilla.js ToonRenderer.getColorSpace
use vanilla::{ColorSpace, ToonPostProcess, ToonPostProcessOptions, ToonRenderer, ToonRendererOptions, ToonScreenOutline, ToonScreenOutlineOptions};
fn create_linear_set(gl: &vanilla::GlContext) -> Result<(), String> {
let renderer = ToonRenderer::new_with_options(gl, ToonRendererOptions { color_space: ColorSpace::Linear })?;
let post_process = ToonPostProcess::new_with_options(gl, 320, 180, ToonPostProcessOptions { color_space: renderer.get_color_space(), ..ToonPostProcessOptions::default() })?;
let screen_outline = ToonScreenOutline::new_with_options(gl, ToonScreenOutlineOptions { color_space: renderer.get_color_space() })?;
assert_eq!(post_process.get_color_space(), ColorSpace::Linear);
assert_eq!(screen_outline.get_color_space(), ColorSpace::Linear);
Ok(())
}pub fn set_ambient_occlusion_texture(&mut self, texture: Option<GlTexture>, direct_lighting_strength: f64)#모서리 어둠 텍스처 설정. (원본 setAmbientOcclusionTexture, ToonPostProcess::draw_ambient_occlusion 의 결과나 None, 다음 begin_frame 부터)
- 텍스처를 건 동안 몸은 모서리 어둠 몸 프로그램(TOON_AMBIENT_OCCLUSION)으로 그리고, 화면 자리의 보임을 바탕빛(하늘과 땅 빛)에 곱한다. direct_lighting_strength 만큼 해, 채움빛, 점광의 확산과 반사광에도 1 - 몫 x (1 - 보임) 을 곱한다. (칸을 고른 뒤라 칸 경계는 그대로, URP 의 Direct Lighting Strength) 테두리빛, 빛남, 매트캡, 천사 고리는 그대로다. 비치는 것(alpha 나 틴트 알파가 1 보다 작음)과 텍스처의 깊이와 다른 면(선의 판에 없던 것)은 곱하지 않는다.
- None 이면 기본 몸 프로그램으로 돌아가 텍스처를 읽지 않는다. (끈 화면은 건 적이 없을 때와 같다)
- 머티리얼 텍스처 8 개를 다 쓰는 머티리얼은 조각 셰이더 유닛이 16 개인 기기에서 모서리 어둠 없이 그린다.
Sets the ambient occlusion texture. (original setAmbientOcclusionTexture, the result of ToonPostProcess::draw_ambient_occlusion or None, from the next begin_frame)
- While the texture is set, bodies are drawn with the ambient occlusion body program (TOON_AMBIENT_OCCLUSION), which multiplies the visibility at the screen position into the ambient light (sky and ground light). By direct_lighting_strength it also multiplies the diffuse and specular of the sun, fill light and point lights by 1 - strength x (1 - visibility). (after the band is chosen, so band edges stay, Direct Lighting Strength of URP) Rim light, glow, matcap and angel ring stay as they are. Transparent things (alpha or tint alpha below 1) and surfaces whose depth differs from the texture (not in the line target) are not multiplied.
- None goes back to the default body program, which does not read the texture. (a screen with it off is the same as one where it was never set)
- Materials that use all 8 material textures are drawn without ambient occlusion on devices with 16 fragment shader units.
- textureOption<GlTexture>
- 모서리 어둠 결과 텍스처. (r 세기를 건 보임, gba 깊이 24 비트, None 이면 끔)Ambient occlusion result texture. (r visibility with intensity applied, gba 24-bit depth, None turns it off)
- direct_lighting_strengthf64
- 직접 빛에 미치는 몫. (0 ~ 1 로 자름, 원본 기본 0)Share applied to direct light. (clamped to 0 ~ 1, original default 0)
짝Counterpart: vanilla.js ToonRenderer.setAmbientOcclusionTexture
모서리 어둠 텍스처 반환. (원본 getAmbientOcclusionTexture)
Returns the ambient occlusion texture. (original getAmbientOcclusionTexture)
반환ReturnsOption<GlTexture> 건 텍스처. (걸지 않았으면 None)The set texture. (None if not set)
짝Counterpart: vanilla.js ToonRenderer.getAmbientOcclusionTexture
모서리 어둠이 직접 빛에 미치는 몫 반환. (원본 getAmbientOcclusionDirectLightingStrength)
Returns the share of ambient occlusion applied to direct light. (original getAmbientOcclusionDirectLightingStrength)
반환Returnsf64 set_ambient_occlusion_texture 의 둘째 인자. (0 ~ 1, 걸지 않았으면 0)The second argument of set_ambient_occlusion_texture. (0 ~ 1, 0 if not set)
짝Counterpart: vanilla.js ToonRenderer.getAmbientOcclusionDirectLightingStrength
몸 프로그램 반환. (기본 프로그램)
Returns the body program. (default program)
반환Returns&ShaderProgram 몸 프로그램.Body program.
짝Counterpart: vanilla.js ToonRenderer.getSolidProgram
바깥선 프로그램 반환. (기본 프로그램)
Returns the outline program. (default program)
반환Returns&ShaderProgram 바깥선 프로그램.Outline program.
짝Counterpart: vanilla.js ToonRenderer.getOutlineProgram
그림자 깊이 프로그램 반환. (기본 프로그램)
Returns the shadow depth program. (default program)
반환Returns&ShaderProgram 그림자 깊이 프로그램.Shadow depth program.
짝Counterpart: vanilla.js ToonRenderer.getDepthProgram
ToonRendererOptionsstruct traits Clone, Copy, Debug, PartialEq, Eq, Default
툰 렌더러를 지을 때의 꼴. (원본 생성 options)
Options for building a toon renderer. (original constructor options)
use vanilla::{ColorSpace, ToonRenderer, ToonRendererOptions};
fn create_linear_renderer(gl: &vanilla::GlContext) -> Result<ToonRenderer, String> {
let renderer = ToonRenderer::new_with_options(gl, ToonRendererOptions { color_space: ColorSpace::Linear })?;
assert_eq!(renderer.get_color_space(), ColorSpace::Linear);
Ok(renderer)
}색 공간. (원본 colorSpace, 기본은 엔진의 색 공간 EngineConfiguration::color_space, 엔진이 없으면 Gamma)
Color space. (original colorSpace, default is the engine's color space EngineConfiguration::color_space, Gamma without an engine)
반환ReturnsColorSpace
함수Functions
pub fn compose_toon_program_sources(material: Option<&ToonMaterial>, instance_layout: Option<&ToonInstanceLayout>, is_ambient_occlusion: bool, color_space: ColorSpace, disabled_features: &[&str]) -> ToonProgramSources#머티리얼과 인스턴스 꼴로 세 프로그램의 소스 짓기. (둘 다 None 이면 기본 프로그램) # Panics disabled_features 에 모르는 이름이 있으면 패닉한다. (원본은 던진다)
Builds the sources of the three programs from a material and instance layout. (the default program if both are None) # Panics Panics if disabled_features has an unknown name. (the original throws)
- materialOption<&ToonMaterial>
- 셰이더 조각을 끼울 머티리얼. (None 이면 빈 조각)Material whose shader chunks are inserted. (None means empty chunks)
- instance_layoutOption<&ToonInstanceLayout>
- 사용자 어트리뷰트를 선언할 인스턴스 꼴. (None 이면 없음)Instance layout that declares the user attributes. (None means none)
- is_ambient_occlusionbool
- 몸 조각 셰이더에 TOON_AMBIENT_OCCLUSION 을 정의해 모서리 어둠 텍스처를 바탕빛에 곱할지. (원본 기본 false)Whether to define TOON_AMBIENT_OCCLUSION in the body fragment shader and multiply the ambient occlusion texture into the ambient light. (original default false)
- color_spaceColorSpace
- 색 공간. (원본 기본은 엔진의 색 공간, Linear 면 소스마다 #define VANILLA_COLOR_SPACE_LINEAR 1 이 들어간다)Color space. (original default is the engine's color space; with Linear every source gets #define VANILLA_COLOR_SPACE_LINEAR 1)
- disabled_features&[&str]
- 몸 조각 셰이더에서 컴파일 때 지울 기능 갈래. (baseTexture, emissiveTexture, decalTexture, matcap, angelRing, rampTexture, shadeStops, rim, shadeRim, shadow, intensityLimit 가운데, 원본 기본은 없음, 지운 갈래를 그리기 때 켜면 그 갈래는 그려지지 않는다. 렌더러는 그리기가 쓰지 않는 갈래를 스스로 알아 넘긴다)Feature branches to remove from the body fragment shader at compile time. (any of baseTexture, emissiveTexture, decalTexture, matcap, angelRing, rampTexture, shadeStops, rim, shadeRim, shadow, intensityLimit; none by default in the original; a removed branch is not drawn if a draw turns it on. The renderer finds the branches a draw does not use and passes them itself)
반환ReturnsToonProgramSources 세 프로그램의 소스와 어트리뷰트 자리. (ToonProgramSources)Sources and attribute locations of the three programs. (ToonProgramSources)
짝Counterpart: vanilla.js composeToonProgramSources
pub fn read_instance_buffer_sphere(mesh: &ToonMesh, instance_buffer: &ToonInstanceBuffer) -> Option<[f64; 4]>#모형을 인스턴스 버퍼로 그릴 때의 월드 경계 구. (버퍼의 경계에 모형의 경계 구를 가장 큰 크기로 더한 것, 걸러도 빠지는 화소가 없다, 원본 readInstanceBufferSphere)
World bounding sphere when a mesh is drawn with an instance buffer. (the buffer bounds plus the mesh bounding sphere at the largest scale, culling by it drops no pixels; the original readInstanceBufferSphere)
- mesh&ToonMesh
- ToonRenderer::create_mesh 의 결과.Result of ToonRenderer::create_mesh.
- instance_buffer&ToonInstanceBuffer
- create_instance_buffer 의 결과.Result of create_instance_buffer.
반환ReturnsOption<[f64; 4]> [x, y, z, 반지름]. 꼴에 행렬이 없어 경계를 모르면 None.[x, y, z, radius]. None when the layout has no matrix and the bounds are unknown.
짝Counterpart: vanilla.js readInstanceBufferSphere
구가 절두체 안에 드는지. (extract_frustum_planes 의 면 여섯, 원본 isSphereInFrustum)
Whether a sphere is inside the frustum. (the six planes of extract_frustum_planes; the original isSphereInFrustum)
- frustum_planes&[[f64; 4]; 6]
- extract_frustum_planes 의 결과.The result of extract_frustum_planes.
- sphere&[f64; 4]
- [x, y, z, 반지름].[x, y, z, radius].
반환Returnsbool 절두체 안에 들거나 걸치면 true.true when inside or touching the frustum.
짝Counterpart: vanilla.js isSphereInFrustum
보기와 투영 행렬에서 절두체의 면 여섯. (ax + by + cz + d >= 0 이 안쪽, 정규화)
The six frustum planes from a view-projection matrix. (ax + by + cz + d >= 0 is inside, normalized)
- matrix&Matrix4
- 보기와 투영 행렬. (투영 x 보기)View and projection matrix. (Projection x view)
반환Returns[[f64; 4]; 6] 면 여섯의 [a, b, c, d]. (왼쪽, 오른쪽, 아래, 위, 가까운 면, 먼 면)[a, b, c, d] of the six planes. (Left, right, bottom, top, near, far)
짝Counterpart: vanilla.js extractFrustumPlanes
모형 행렬 왼쪽 위 3x3 의 행렬식. (음수면 거울에 비친 행렬, 감기가 뒤집힌다)
Determinant of the model matrix's upper-left 3x3. (negative means a mirrored matrix, winding is flipped)
- matrix&Matrix4
- 모형 행렬.Model matrix.
반환Returnsf64 왼쪽 위 3x3 의 행렬식. (음수면 거울에 비친 행렬)Determinant of the upper left 3x3. (Negative means a mirrored matrix)
짝Counterpart: vanilla.js readMatrixDeterminant
보기와 투영 행렬에서 카메라 읽기. (원근이면 눈의 자리, 직교면 보는 방향, 행렬이 거울에 비친 것인지)
- 원근: 클립 x, y, w 가 모두 0 이 되는 점이 눈이다. (행 0, 1, 3 의 연립 방정식)
- 직교: 행 3 의 xyz 가 0 이라 눈이 무한히 멀다. 보는 방향은 행 0, 1 의 외적을 깊이가 느는 쪽으로 둔다.
- 보통의 투영(가까운 면 < 먼 면)은 왼쪽 위 3x3 의 행렬식이 음수다. 양수면 보기 행렬이 거울에 비친 것이다.
Reads the camera from view and projection matrices. (eye position if perspective, view direction if orthographic, whether the matrix is mirrored)
- Perspective: the eye is the point where clip x, y, w are all 0. (system of equations from rows 0, 1, 3)
- Orthographic: xyz of row 3 is 0, so the eye is infinitely far. The view direction is the cross product of rows 0, 1, oriented toward increasing depth.
- A normal projection (near plane < far plane) has a negative determinant in its upper-left 3x3. If positive, the view matrix is mirrored.
- matrix&Matrix4
- 보기와 투영 행렬.View and projection matrix.
반환ReturnsToonFrameCamera 읽은 카메라. (position [x, y, z, w(1 원근, 0 직교)], forward [x, y, z], is_mirrored)Read camera. (position [x, y, z, w(1 perspective, 0 orthographic)], forward [x, y, z], is_mirrored)
짝Counterpart: vanilla.js readFrameCamera
pub fn read_view_rotation(view_projection_matrix: &Matrix4, forward: [f64; 3]) -> [f64; 9]#보기와 투영 행렬에서 보기 돌림 3x3 읽기. (열 차례, 행이 오른쪽, 위, 뒤, 매트캡의 보기 공간 노멀을 셀 때)
- 오른쪽은 행 0 의 xyz 에서 보는 방향 몫을 뺀 것이다. (대칭 원근과 직교, 화면 사각형으로 옮긴 투영 모두)
Reads the 3x3 view rotation from the view-projection matrix. (column order, rows are right, up, back, for computing view-space normals for matcaps)
- Right is row 0's xyz minus the view direction component. (for symmetric perspective, orthographic and projections moved to a screen rectangle alike)
- view_projection_matrix&Matrix4
- 보기와 투영 행렬.View and projection matrix.
- forward[f64; 3]
- 보는 방향. (read_frame_camera 의 forward)View direction. (the forward of read_frame_camera)
반환Returns[f64; 9] mat3 의 수 9. (열 차례)The 9 numbers of a mat3. (Column order)
짝Counterpart: vanilla.js readViewRotation
카메라 기울임을 되돌리는 각 읽기. (유니티 툰 셰이더의 천사 고리 Camera Rolling Stabilizer 와 같은 셈, 원본 readCameraRoll)
- 카메라 오른쪽(보기 돌림의 행 0)과 수평 오른쪽 축이 이루는 각 roll, 오른쪽의 y 가 음수면 쪽 dir 이 -1, 돌려주는 각은 -(dir x roll) 이다.
- 유니티는 왼손 좌표라 수평 오른쪽 축이 cross(뒤, 위) 이고, 엔진은 오른손 좌표라 같은 쪽이 cross(앞, 위) 다. 거울에 비친 프레임이면 축을 뒤집는다. (유니티 툰 셰이더의 mirrorFlag)
- 바로 위나 아래를 보면 수평 축이 없어 0 이다.
Reads the angle that undoes camera roll. (the same computation as the Unity Toon Shader angel ring Camera Rolling Stabilizer, original readCameraRoll)
- roll is the angle between the camera right (row 0 of the view rotation) and the horizontal right axis, dir is -1 if the right's y is negative, and the returned angle is -(dir x roll).
- Unity is left-handed so its horizontal right axis is cross(back, up), and the engine is right-handed so the same side is cross(forward, up). For a mirrored frame the axis is flipped. (the Unity Toon Shader mirrorFlag)
- Looking straight up or down there is no horizontal axis, so it is 0.
- view_rotation&[f32; 9]
- mat3 의 수 9. (read_view_rotation 의 결과, 열 차례)The 9 values of a mat3. (result of read_view_rotation, column order)
- is_mirroredbool
- 보기 행렬이 거울에 비쳤는지. (read_frame_camera 의 is_mirrored)Whether the view matrix is mirrored. (the is_mirrored of read_frame_camera)
반환Returnsf64 천사 고리 UV 를 (0.5, 0.5) 둘레로 돌릴 각. (라디안)Angle to rotate the angel ring UV around (0.5, 0.5). (Radians)
짝Counterpart: vanilla.js readCameraRoll
pub fn read_uv_data(uv_data: &[f32], uv1_data: Option<&[f32]>, vertex_count: usize) -> Vec<f32>#UV 꼭짓점 배열 짓기. (2 번 UV 가 없으면 점마다 UV 2, 있으면 UV 와 2 번 UV 를 섞어 4, 셰이더의 vertexUv 는 vec4 라 2 개만 올리면 zw 는 (0, 1))
Builds the UV vertex array. (UV 2 per point without a second UV, UV and second UV interleaved as 4 with one, vertexUv in the shader is a vec4, so if only 2 are uploaded zw is (0, 1))
- uv_data&[f32]
- UV. (점마다 2)UV. (2 per point)
- uv1_dataOption<&[f32]>
- 2 번 UV. (점마다 2, 없으면 None)Second UV. (2 per point, None if none)
- vertex_countusize
- 점 수.Number of points.
반환ReturnsVec<f32> 점마다 2 나 4.2 or 4 per point.
짝Counterpart: vanilla.js readUvData
pub fn read_outline_vertex_data(outline_vertex_data: &[f32], outline_base_data: &[f32]) -> Vec<f32>#껍데기 꼭짓점 배열 짓기. (점마다 바탕 자리 3 과 미는 쪽 3, 미는 쪽은 사본 자리 - 바탕 자리)
- 바탕 자리가 없거나 길이가 다르면(GLB 에 지어 둔 껍데기) 사본 자리를 바탕으로 두고 미는 쪽은 0 이다. (굵기 배를 걸지 않는다)
Builds the shell vertex array. (per point, base position 3 and push direction 3, the push direction is copy position - base position)
- If there are no base positions or the length differs (a shell prebuilt in the GLB), the copy positions are used as the base and the push direction is 0. (the width multiplier is not applied)
- outline_vertex_data&[f32]
- 지은 굵기로 민 사본 자리. (3 씩)Copy positions pushed by the built thickness. (3 each)
- outline_base_data&[f32]
- 밀기 전 바탕 자리. (3 씩, 길이가 다르면 사본 자리를 바탕으로 둔다)Base positions before pushing. (3 each, if the length differs the copied positions are used as the base)
반환ReturnsVec<f32> 점마다 6 개.6 per point.
짝Counterpart: vanilla.js readOutlineVertexData
pub fn create_reflection_matrix(plane_point: [f64; 3], plane_normal: [f64; 3]) -> Matrix4#평면에 비친 행렬 짓기. (평면 위 한 점과 노멀, 평면 거울의 모형이나 보기 행렬에 곱한다)
- 비친 행렬로 그리면 감기가 뒤집힌다. ToonRenderer 는 모형 행렬의 행렬식이 음수면 스스로 앞면을 뒤집는다. (is_mirrored 로 정할 수도 있다)
Builds a reflection matrix across a plane. (a point on the plane and its normal, multiplied into the model or view matrix for a planar mirror)
- Drawing with a reflected matrix flips the winding. ToonRenderer flips the front face itself if the model matrix determinant is negative. (can also be set with is_mirrored)
- plane_point[f64; 3]
- 평면 위 한 점. ([x, y, z])A point on the plane. ([x, y, z])
- plane_normal[f64; 3]
- 평면의 노멀. ([x, y, z], 길이는 상관없다)Normal of the plane. ([x, y, z], length does not matter)
반환ReturnsMatrix4 평면에 비친 행렬.Matrix reflected across the plane.
짝Counterpart: vanilla.js createReflectionMatrix
상수Constants
pub const TOON_MAXIMUM_JOINTS: usize = crate::graphics3d::jointblock::JOINT_BLOCK_MAXIMUM#한 모형이 쓰는 뼈대 수의 상한. (셰이더의 유니폼 배열 크기)
Upper limit on the number of bones one model uses. (the size of the shader's uniform array)
반환Returnsusize
짝Counterpart: vanilla.js TOON_MAXIMUM_JOINTS
인스턴스 하나의 수 개수. (행렬 16, 틴트 4)
- 행렬은 아핀 3x4 로 읽는다. 아래 줄 네 칸(원소 3, 7, 11, 15)은 인스턴스 빛남(sRGB r, g, b 와 선형 세기)이다. (Godot MultiMesh, 유니티 BatchRendererGroup 의 3x4 행렬 꼴) Matrix4 원소를 그대로 담으면 아래 줄이 0, 0, 0, 1 이라 빛남이 없다.
Number of values per instance. (matrix 16, tint 4)
- The matrix is read as an affine 3x4. The four values of the bottom row (elements 3, 7, 11, 15) are the instance emission (sRGB r, g, b and linear intensity). (The 3x4 matrix form of Godot MultiMesh and Unity BatchRendererGroup) Storing Matrix4 elements as they are leaves the bottom row 0, 0, 0, 1, so there is no emission.
반환Returnsusize
짝Counterpart: vanilla.js TOON_INSTANCE_FLOAT_COUNT
머티리얼이 그리기마다 묶을 수 있는 텍스처 수의 상한. (유닛 8 ~ 15)
Upper limit of textures a material can bind per draw. (Units 8 ~ 15)
반환Returnsusize
짝Counterpart: vanilla.js TOON_MAXIMUM_MATERIAL_TEXTURES
어트리뷰트 자리. (모든 프로그램이 같은 자리를 쓴다, 인스턴스 꼴의 사용자 어트리뷰트는 13 부터)
Attribute locations. (all programs use the same locations, instance layout user attributes start at 13)
반환Returns[(&str, u32); 13]
짝Counterpart: vanilla.js TOON_ATTRIBUTE_LOCATIONS
ToonProgramKindenum traits Clone, Copy, Debug, PartialEq, Eq
그리기의 프로그램 종류. (on_before_draw 의 셋째 인자)
Program kind of a draw. (third argument of on_before_draw)
| 이름Name | 설명Description |
|---|---|
Solid | 몸.Body. |
Outline | 바깥선 껍데기.Outline shell. |
Depth | 그림자 깊이.Shadow depth. |