core/scene
씬.
- 원본은 Scene 클래스를 상속해 create / tick / draw 를 덮어쓴다.
- 러스트 판은 Scene 트레이트를 구현하고, 씬 공통 상태(노드 트리, 터치 대상)는 SceneBase 에 둔다.
- 노드는 SceneBase 의 NodeTree 가 들고, 게임 코드는 NodeId 핸들로 가리킨다. (get_node_tree_mut().create_child(...)) 원본의 super.tick() / super.draw() 자리는 get_scene_base_mut().tick() / .draw() 를 부른다.
- 원본 GameScene 의 pre_draw (캔버스 전체를 배경색으로 칠하고 뷰 좌표계를 거는 것)는 SceneBase::draw_scene_background 로 옮겼다.
- 트윈은 원본처럼 씬이 목록으로 들고(start_tween), tick 에서 노드 → 터치 다음에 돌리며 끝난 것을 뺀다. 원본은 트윈 객체로 가리키지만, 러스트 판은 트윈을 넘겨받고 TweenId 를 돌려준다. (stop_tween(tween_id))
- 원본 SceneManager.unloadScene(scene) 은 씬 객체로 가리킨다. 러스트 판은 엔진이 씬을 들고 있어 load_scene 이 돌려주는 SceneId 나 씬 공통 상태(&SceneBase, 원본처럼 씬으로)로 가리킨다. 씬 스스로는 get_scene_base().get_scene_id() 로 자기 핸들을 안다.
- 내릴 때는 원본처럼 finalize 다음 unload 를 부르고, 러스트 판은 씬을 버리기 직전에 destroy 를 더 부른다.
- 원본 async load(engine) 자리: load 에서 Engine::spawn_scene_task 로 불러오기 작업을 맡기고 track_task 로 씬에 맡긴다. 작업 안에서는 원본처럼 await 로 애셋을 기다리고, SceneContext::with 안에서 씬과 엔진을 만진다. 맡긴 작업과 애셋이 모두 끝나야 initialize 를 부른다. 애셋 손잡이를 track_asset 으로 맡기는 동기 꼴도 그대로 된다. (둘을 섞어도 된다) 원본 await unload(engine) 자리: unload 에서 맡긴 작업(track_task)이 끝날 때까지 씬은 목록에 남아 tick, draw 를 받고, 끝나면 목록에서 빠진다. 그 뒤에도 그 씬의 작업이 남았으면 원본의 Promise 사슬처럼 다 끝날 때까지 씬 값이 살고(tick, draw 는 받지 않는다), 불러오는 도중에 내린 씬은 원본 SceneManager.loadScene 처럼 불러오기가 끝나면 initialize 까지 받는다. 다 끝나면 엔진이 destroy 를 부르고 버린다.
- 원본 Scene.load 가 루트를 뷰 크기로 맞추는 것(자리 0, 왼쪽 위 피벗, 콘텐츠 크기는 뷰 크기)은 엔진이 create 와 load 사이에 한다. 원본 SceneManager.loadScene 처럼 맡긴 애셋이 다 끝난 뒤에도 로딩 화면(draw_on_load)을 최소 0.3초 더 보이고 initialize 를 부른다.
- 씬의 터치 훅(touch_press, touch_move, touch_release, touch_cancel, touch_wheel)은 원본 Scene.tickTouch 차례로 엔진이 tick 뒤에 부른다. SceneBase.tick 은 씬 꼴과 상관없이 가장 앞의 누를 수 있는 노드에도 넘긴다. (원본 Scene.tickTouch 가 씬의 TouchRaycaster 로 넘기는 것과 같다)
- 씬 훅은 원본과 달리 엔진(&Engine)을 받는다. (전역 엔진 Engine::get_engine 과 같은 엔진이다)
Scene.
- The original inherits the Scene class and overrides create / tick / draw.
- The Rust version implements the Scene trait and keeps the common scene state (node tree, touch target) in SceneBase.
- Nodes are held by SceneBase's NodeTree, and game code points to them with NodeId handles. (get_node_tree_mut().create_child(...)) In place of the original super.tick() / super.draw(), call get_scene_base_mut().tick() / .draw().
- The original GameScene's pre_draw (filling the whole canvas with the background color and applying the view coordinate system) moved to SceneBase::draw_scene_background.
- Like the original, the scene holds tweens in a list (start_tween), runs them on tick after nodes → touch, and removes finished ones. The original points to them by tween object, but the Rust version takes ownership of the tween and returns a TweenId. (stop_tween(tween_id))
- The original SceneManager.unloadScene(scene) points by scene object. In the Rust version the engine holds the scenes, so it points by the SceneId returned from load_scene or by the common scene state (&SceneBase, by scene as in the original). A scene knows its own handle with get_scene_base().get_scene_id().
- When unloading, like the original it calls finalize then unload, and the Rust version additionally calls destroy right before dropping the scene.
- In place of the original async load(engine): in load, hand the loading work to Engine::spawn_scene_task and entrust it to the scene with track_task. Inside the task, await assets as in the original and touch the scene and engine inside SceneContext::with. initialize is called only after all entrusted tasks and assets finish. The synchronous form of entrusting asset handles with track_asset still works. (the two can be mixed) In place of the original await unload(engine): the scene stays in the list receiving tick, draw until the tasks entrusted in unload (track_task) finish, then leaves the list. If that scene's tasks still remain after that, the scene value lives until they all finish, like the original's Promise chain (it receives no tick, draw), and a scene unloaded while loading receives initialize once loading finishes, like the original SceneManager.loadScene. When everything is done, the engine calls destroy and drops it.
- What the original Scene.load does to fit the root to the view size (position 0, top-left pivot, content size is the view size) is done by the engine between create and load. Like the original SceneManager.loadScene, after all entrusted assets finish it keeps showing the loading screen (draw_on_load) for at least 0.3 seconds more, then calls initialize.
- The scene's touch hooks (touch_press, touch_move, touch_release, touch_cancel, touch_wheel) are called by the engine after tick, in the original Scene.tickTouch order. SceneBase.tick also passes them to the frontmost interactable node regardless of the scene type. (same as the original Scene.tickTouch passing them to the scene's TouchRaycaster)
- Unlike the original, scene hooks receive the engine (&Engine). (it is the same engine as the global engine Engine::get_engine)
SceneIdstruct traits Clone, Copy, Debug, PartialEq, Eq, Hash, From<&SceneBase>
씬 핸들. (Engine::load_scene 이 돌려주고 Engine::unload_scene 이 받는다)
Scene handle. (returned by Engine::load_scene and taken by Engine::unload_scene)
use vanilla::{Engine, EngineConfiguration, Scene, SceneBase, SceneId};
struct EmptyScene {
scene_base: SceneBase,
}
impl Scene for EmptyScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
}
let engine = Engine::new(EngineConfiguration::new());
let first_scene_id: SceneId = engine.load_scene(Box::new(EmptyScene { scene_base: SceneBase::new() }));
let second_scene_id: SceneId = engine.load_scene(Box::new(EmptyScene { scene_base: SceneBase::new() }));
assert_ne!(first_scene_id, second_scene_id);
engine.unload_scene(second_scene_id);SceneBasestruct traits Default
씬 공통 상태.
- 노드 트리, 트윈 목록, 맡긴 애셋과 작업, 터치 대상, 배경색을 든다. 씬 구조체가 하나 들고 get_scene_base 로 내준다.
Common scene state.
- Holds the node tree, tween list, entrusted assets and tasks, touch target and background color. A scene struct holds one and exposes it via get_scene_base.
use vanilla::{SceneBase, Tween, TweenProperty, Vector2};
let mut scene_base = SceneBase::new();
let root_id = scene_base.get_root_id();
let player_id = scene_base.get_node_tree_mut().create_child(root_id, "player");
let tween = Tween::create_node_tween(player_id, TweenProperty::LocalPosition, Vector2::zero(), Vector2::create(100.0, 0.0), 1.0);
let tween_id = scene_base.start_tween(tween);
assert_eq!(scene_base.get_tween_count(), 1);
scene_base.tick_tweens(0.5);
assert_eq!(scene_base.get_node_tree()[player_id].get_local_position(), Vector2::create(50.0, 0.0));
scene_base.tick_tweens(0.5);
assert_eq!(scene_base.get_tween_count(), 0);
assert!(scene_base.get_tween(tween_id).is_none());생성.
Constructor.
반환ReturnsSceneBase 새 씬 공통 상태. (루트 하나인 노드 트리, 배경색 검정, 불러오기 전, 기즈모 끔)New common scene state. (a node tree with just the root, black background, before loading, gizmos off)
짝Counterpart: vanilla.js Scene.constructor
이번 프레임의 휠을 받아 쓴 컴포넌트(스크롤 칸 등)가 있었는지. (tick_touch 뒤에 읽는다, 없으면 게임이 지도 확대 등에 쓴다)
Whether a component (scroll pane and such) consumed this frame's wheel. (read after tick_touch, if none, the game uses it for map zoom and such)
반환Returnsbool 이번 프레임의 휠을 컴포넌트가 썼으면 true.True if a component consumed this frame's wheel.
씬 핸들. (엔진에 load_scene 으로 넘긴 뒤부터 있다)
Scene handle. (present after it is passed to the engine with load_scene)
반환ReturnsOption<SceneId> 이 씬의 핸들. (load_scene 전이면 None)This scene's handle. (None before load_scene)
첫 터치 콜백 설정. (처음 누를 때 한 번. 웹에서 오디오 잠금을 푸는 자리, 원본 TouchRaycaster)
Sets the first touch callback. (once, on the first press. Where audio is unlocked on the web, the original TouchRaycaster)
- first_touch_callbackBox<dyn FnMut()>
- 처음 누를 때 부를 함수. (앞서 건 함수는 바꾼다)Function to call on the first press. (replaces a previously set function)
짝Counterpart: vanilla.js TouchRaycaster.setFirstTouchCallback
노드에 터치 넘기기 켜고 끄기. (원본 Scene.setTouchDispatchEnabled, setTouchRaycaster(null) 과 같은 효과)
- 끄면 tick_touch 가 노드에 누름, 이동, 뗌, 휠을 넘기지 않고(첫 터치 콜백도 부르지 않는다) 씬의 터치 훅만 불린다. (훅에서 가로채 직접 넘길 때)
Turns passing touches to nodes on or off. (the original Scene.setTouchDispatchEnabled, same effect as setTouchRaycaster(null))
- When off, tick_touch does not pass press, move, release or wheel to nodes (and does not call the first touch callback), and only the scene's touch hooks are called. (for intercepting in the hooks and passing directly)
- is_enabledbool
- 노드에 넘기면 참. (기본 참)true to pass to nodes. (true by default)
짝Counterpart: vanilla.js Scene.setTouchDispatchEnabled
use vanilla::SceneBase;
let mut scene_base = SceneBase::new();
scene_base.set_touch_dispatch_enabled(false);
assert!(!scene_base.is_touch_dispatch_enabled());노드에 터치를 넘기는지.
Whether touches are passed to nodes.
반환Returnsbool 넘기면 참.true if it passes.
짝Counterpart: vanilla.js Scene.isTouchDispatchEnabled
지금 눌려 있는 노드. (원본 TouchRaycaster.getTouchTarget)
The node currently pressed. (the original TouchRaycaster.getTouchTarget)
반환ReturnsOption<NodeId> 누를 때 찾은 맨 위의 누를 수 있는 노드. (누르고 있지 않거나 빈 곳을 눌렀으면 None)The topmost pressable node found on press. (None if not pressing or an empty spot was pressed)
짝Counterpart: vanilla.js TouchRaycaster.getTouchTarget
애셋 맡기기. (load 에서 읽기를 요청한 애셋. 맡긴 것이 다 읽히면 엔진이 initialize 를 부른다)
Entrusts an asset. (an asset whose loading was requested in load. When all entrusted ones are read, the engine calls initialize)
- asset&dyn Asset
- load 를 요청한 애셋. (읽기 손잡이가 없는 애셋은 맡기지 않는다)Asset whose load was requested. (assets without a read handle are not entrusted)
읽기 손잡이 맡기기. (애셋 꼴이 아닌 것)
Entrusts a read handle. (for things not in asset form)
- load_handle&AssetLoadHandle
- 기다릴 읽기 손잡이. (복제해 든다)Read handle to wait for. (held as a clone)
오디오 애셋 맡기기. (engine.load_audio_asset 으로 받은 것. 웹은 디코딩이 끝나야 읽힌 것으로 친다)
Entrusts an audio asset. (one received from engine.load_audio_asset. On the web it counts as read only once decoding finishes)
- audio_asset&Rc<AudioAsset>
- 기다릴 오디오 애셋. (읽혔거나 실패하면 끝난 것으로 친다)Audio asset to wait for. (counts as finished when read or failed)
작업 맡기기. (원본 async load 자리, load 에서 spawn_scene_task 로 맡긴 불러오기 작업. 끝나야 엔진이 initialize 를 부른다)
- unload 에서 맡기면 원본 await scene.unload 처럼 끝나야 내리기가 끝난다. (그동안 씬은 목록에 남는다)
Entrusts a task. (in place of the original async load, a loading task entrusted with spawn_scene_task in load. The engine calls initialize only after it finishes)
- If entrusted in unload, unloading finishes only after it finishes, like the original await scene.unload. (the scene stays in the list meanwhile)
- task_handle&TaskHandle
- 기다릴 작업의 손잡이. (spawn_scene_task, spawn_task 가 돌려준 것)Handle of the task to wait for. (returned by spawn_scene_task, spawn_task)
use vanilla::{Engine, Scene, SceneBase, SceneContext};
struct StageScene {
scene_base: SceneBase,
stage_byte_count: usize,
}
impl Scene for StageScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
fn load(&mut self, engine: &Engine) {
let task_handle = engine.spawn_scene_task(self, |mut scene_context: SceneContext<StageScene>| async move {
let load_handle = scene_context.with(|_scene, engine| engine.request_asset_bytes("examples/assets/scenedocument.scene.json"));
if let Ok(bytes) = load_handle.await {
scene_context.with(|scene, _engine| {
scene.stage_byte_count = bytes.len();
});
}
});
self.scene_base.track_task(&task_handle);
}
fn initialize(&mut self, _engine: &Engine) {
println!("{}", self.stage_byte_count);
}
}unload 에서 맡긴 것이 다 끝났는지. (읽혔거나 실패했거나 작업이 끝났거나)
Whether everything entrusted in unload is finished. (read, failed, or task finished)
반환Returnsbool unload 에서 맡긴 것이 모두 끝났으면 true. (맡긴 것이 없으면 true)True if everything entrusted in unload is finished. (true if nothing was entrusted)
맡긴 애셋이 다 끝났는지. (읽혔거나 실패했거나. 실패한 애셋 때문에 씬이 멈추지 않게 한다)
Whether all entrusted assets are finished. (read or failed. Keeps a failed asset from stalling the scene)
반환Returnsbool 불러오기에 맡긴 애셋과 작업이 모두 끝났으면 true. (맡긴 것이 없으면 true)True if all assets and tasks entrusted for loading are finished. (true if nothing was entrusted)
pub fn are_tracked_assets_finished_except(&self, excluded_load_handle: &AssetLoadHandle) -> bool#맡긴 애셋이 하나를 빼고 다 끝났는지. (GameSceneBase 가 로딩 문을 빼고 원본 loadAssets 가 끝났는지 볼 때)
Whether all tracked assets except one have finished. (used by GameSceneBase to check whether the original loadAssets has finished, excluding the loading door)
- excluded_load_handle&AssetLoadHandle
- 끝났는지 보지 않을 읽기 손잡이. (같은 읽기를 가리키는 손잡이를 모두 뺀다)Read handle not to check for completion. (all handles pointing to the same read are left out)
반환Returnsbool 그 손잡이를 뺀 나머지가 모두 끝났으면 true.True if all the rest except that handle are finished.
맡긴 애셋 가운데 끝난 비율. (로딩 화면 진행 막대용, 맡긴 것이 없으면 1)
Ratio of entrusted assets that are finished. (for the loading screen progress bar, 1 if nothing was entrusted)
반환Returnsf64 끝난 수 / 맡긴 수. (0 ~ 1, 실패한 것도 끝난 것으로 센다)Finished count / entrusted count. (0 ~ 1, failed ones count as finished)
use vanilla::{AssetLoadHandle, SceneBase};
let mut scene_base = SceneBase::new();
let scene_load_handle = AssetLoadHandle::create_pending("examples/assets/scenedocument.scene.json");
let atlas_load_handle = AssetLoadHandle::create_pending("examples/assets/atlas/icons.json");
scene_base.track_load_handle(&scene_load_handle);
scene_base.track_load_handle(&atlas_load_handle);
assert_eq!(scene_base.get_tracked_asset_progress(), 0.0);
scene_load_handle.finish(Ok(b"{}".to_vec()));
assert_eq!(scene_base.get_tracked_asset_progress(), 0.5);
atlas_load_handle.finish(Err(String::from("not found")));
assert!(scene_base.are_tracked_assets_finished());맡긴 애셋 비우기. (initialize 직전에 엔진이 부른다)
Clears the entrusted assets. (the engine calls it right before initialize)
한 번이라도 눌린 적이 있는지. (원본 Scene.hasEverTouched, 처음 누를 때 참이 된다)
Whether it has ever been pressed. (the original Scene.hasEverTouched, becomes true on the first press)
반환Returnsbool 이 씬에서 한 번이라도 눌렀으면 true.True if it has been pressed at least once in this scene.
짝Counterpart: vanilla.js TouchRaycaster.hasEverTouched
노드 트리.
Node tree.
반환Returns&NodeTree 이 씬의 노드 트리.This scene's node tree.
pub fn get_engine(&self) -> Result<&'static crate::core::engine::Engine, crate::core::globalengine::EngineAccessError>#엔진 반환. (원본 Scene.getEngine, 이 씬을 불러온 엔진. 러스트 판은 엔진이 하나라 전역 엔진을 준다)
- Engine::get_engine 과 같다. 씬 함수, 컴포넌트, async 작업 어디서나 씬 함수의 engine 인자와 같은 엔진을 준다.
Returns the engine. (the original Scene.getEngine, the engine that loaded this scene. The Rust version has one engine, so it gives the global engine)
- The same as Engine::get_engine. Anywhere in scene functions, components and async tasks it gives the same engine as the engine argument of scene functions.
반환ReturnsResult<&'static crate::core::engine::Engine, crate::core::globalengine::EngineAccessError> 전역 엔진, 못 꺼내면 그 까닭.The global engine, or the reason it could not be taken.
짝Counterpart: vanilla.js Scene.getEngine
노드 트리. (변경용)
Node tree. (mutable)
반환Returns&mut NodeTree 이 씬의 노드 트리. (노드 만들기, 붙이기, 지우기)This scene's node tree. (creating, attaching and removing nodes)
루트 노드 핸들.
Root node handle.
반환ReturnsNodeId 노드 트리의 루트 노드 핸들.Root node handle of the node tree.
루트 노드.
Root node.
반환Returns&WorldNode 루트 노드. (엔진이 create 와 load 사이에 뷰 크기로 맞춘다)Root node. (the engine fits it to the view size between create and load)
짝Counterpart: vanilla.js Scene.getRoot
루트 노드. (변경용)
Root node. (mutable)
반환Returns&mut WorldNode 루트 노드.Root node.
짝Counterpart: vanilla.js Scene.getRoot
로드 완료 설정.
Sets load completion.
- is_loadedbool
- 불러오기를 마쳤는지. (엔진이 initialize 뒤에 true 로 둔다)Whether loading is done. (the engine sets it to true after initialize)
짝Counterpart: vanilla.js Scene.setLoaded
로드 완료 여부.
Whether loading is complete.
반환Returnsbool initialize 를 마쳤으면 true. (그 전에는 엔진이 tick, draw 대신 draw_on_load 를 부른다)True if initialize is done. (before that, the engine calls draw_on_load instead of tick, draw)
짝Counterpart: vanilla.js Scene.isLoaded
기즈모 표시 설정.
Sets gizmo drawing.
- is_gizmo_visiblebool
- true 면 엔진이 post_draw 뒤에 draw_gizmos 를 부른다.If true, the engine calls draw_gizmos after post_draw.
짝Counterpart: vanilla.js Scene.setGizmoVisible
기즈모 표시 여부.
Whether gizmos are drawn.
반환Returnsbool 기즈모를 그리면 true. (기본 false)True if gizmos are drawn. (default false)
짝Counterpart: vanilla.js Scene.isGizmoVisible
배경색 설정. (draw_scene_background 가 칠한다)
Sets the background color. (draw_scene_background fills it)
- colorimpl Into<Color>
- 배경색. (Color 나 "#202020" 같은 색 글)Background color. (a Color or a color string like "#202020")
짝Counterpart: vanilla.js Scene.setSceneBackgroundColor
배경색 반환.
Returns the background color.
반환ReturnsColor 배경색. (기본 검정)Background color. (default black)
짝Counterpart: vanilla.js Scene.getSceneBackgroundColor
기본 갱신. (루트 노드 → 터치 → 트윈)
Default update. (root node → touch → tweens)
- time_deltaf64
- 배율을 곱한 프레임 간격. (초)Frame interval multiplied by the time scale. (seconds)
짝Counterpart: vanilla.js Scene.tick
트윈 목록 갱신. (원본처럼 뒤에서부터 돌고, 끝난 트윈은 목록에서 뺀다)
- 같은 속성을 둘이 움직이면 먼저 시작한 트윈이 나중에 돌아 이긴다. (원본과 같음)
Updates the tween list. (iterates from the back as in the original, and removes finished tweens from the list)
- If two tweens animate the same property, the one started first runs later and wins. (same as the original)
- time_deltaf64
- 진행할 시간. (초)Time to advance. (seconds)
트윈 시작. (트윈을 넘겨받아 start 하고 목록 끝에 붙인다. 가리킬 핸들을 돌려준다)
Starts a tween. (takes ownership of the tween, starts it and appends it to the list. Returns a handle to point to it)
- tweenTween
- 돌릴 트윈. (씬이 소유한다)Tween to run. (owned by the scene)
반환ReturnsTweenId 그 트윈의 핸들. (stop_tween, get_tween 에 넘긴다)Handle of that tween. (pass to stop_tween, get_tween)
짝Counterpart: vanilla.js Scene.startTween
트윈 중단. (완료 콜백 없이 멈추고 목록에서 뺀다. 이미 끝나 빠졌으면 아무것도 하지 않는다)
Stops a tween. (stops without the completion callback and removes it from the list. Does nothing if it already finished and was removed)
- tween_idTweenId
- 멈출 트윈의 핸들. (start_tween 이 돌려준 것)Handle of the tween to stop. (returned by start_tween)
짝Counterpart: vanilla.js Scene.stopTween
모든 트윈 중단.
Stops all tweens.
짝Counterpart: vanilla.js Scene.stopAllTweens
트윈 반환. (끝나서 목록에서 빠졌으면 None. 원본에서 트윈 객체를 들고 묻던 자리)
Returns the tween. (None if it finished and was removed from the list. Where the original held the tween object to query it)
- tween_idTweenId
- 찾을 트윈의 핸들.Handle of the tween to find.
반환ReturnsOption<&Tween> 돌고 있는 그 트윈. (끝났거나 멈춰 빠졌으면 None)That running tween. (None if it finished or was stopped and removed)
트윈 반환. (변경용)
Returns the tween. (mutable)
- tween_idTweenId
- 찾을 트윈의 핸들.Handle of the tween to find.
반환ReturnsOption<&mut Tween> 돌고 있는 그 트윈. (끝났거나 멈춰 빠졌으면 None)That running tween. (None if it finished or was stopped and removed)
돌고 있는 트윈 수.
Number of running tweens.
반환Returnsusize 목록의 트윈 수. (대기 중인 것 포함)Number of tweens in the list. (including waiting ones)
짝Counterpart: vanilla.js Scene.getTweenCount
터치 갱신. (눌린 곳 맨 위의 interactable 노드를 찾아 눌림 / 이동 / 뗌을 전달)
- 휠은 누름과 상관없이 그 자리의 가장 앞 스크롤 칸이나 누를 수 있는 노드부터 부모 쪽으로 넘긴다.
Touch update. (finds the topmost interactable node at the pressed spot and dispatches press / move / release)
- The wheel, regardless of pressing, is passed from the frontmost scroll pane or pressable node at that position toward the parents.
- _time_deltaf64
- 배율을 곱한 프레임 간격. (초, 원본 tickTouch(timeDelta) 와 같은 인자. 입력은 엔진의 입력 매니저에서 읽는다)The frame interval multiplied by the time scale. (seconds, the same argument as the original tickTouch(timeDelta). Input is read from the engine's input manager)
짝Counterpart: vanilla.js Scene.tickTouch
기본 출력. (루트 노드 재귀)
Default draw. (recursive from the root node)
- graphic&mut Graphic
- 그릴 그래픽.Graphic to draw with.
짝Counterpart: vanilla.js Scene.draw
캔버스 전체를 배경색으로 칠하고 뷰 좌표계를 건다. (원본 GameScene.preDraw)
Fills the whole canvas with the background color and sets the view coordinate system. (the original GameScene.preDraw)
- graphic&mut Graphic
- 칠할 그래픽. (끝나면 뷰 좌표계가 걸려 있다)Graphic to fill with. (the view coordinate system is applied when done)
짝Counterpart: vanilla.js Scene.drawSceneBackground
use vanilla::{Engine, Graphic, Scene, SceneBase};
struct MainScene {
scene_base: SceneBase,
}
impl Scene for MainScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
fn load(&mut self, _engine: &Engine) {
self.scene_base.set_scene_background_color("#203040");
}
fn pre_draw(&mut self, graphic: &mut Graphic) {
self.scene_base.draw_scene_background(graphic);
}
}SceneAnytrait
씬을 그 타입으로 꺼내기. (SceneContext 가 &mut dyn Scene 을 작업을 맡긴 씬의 타입으로 되돌릴 때 쓴다, 모든 씬에 저절로 붙는다)
Takes the scene out as its type. (used when SceneContext turns &mut dyn Scene back into the type of the scene that entrusted the task, attached to every scene automatically)
use vanilla::core::scene::SceneAny;
use vanilla::{Scene, SceneBase};
struct MainScene {
scene_base: SceneBase,
score: u32,
}
impl Scene for MainScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
}
let mut boxed_scene: Box<dyn Scene> = Box::new(MainScene { scene_base: SceneBase::new(), score: 7 });
let main_scene = boxed_scene.as_scene_any_mut().downcast_mut::<MainScene>().unwrap();
assert_eq!(main_scene.score, 7);Any 로 빌리기.
Borrows as Any.
반환Returns&mut dyn std::any::Any 이 씬을 dyn Any 로 빌린 것. (downcast_mut 로 씬 타입으로 되돌린다)This scene borrowed as dyn Any. (turned back into the scene type with downcast_mut)
Scenetrait traits SceneAny
씬 트레이트.
- get_scene_base, get_scene_base_mut 만 꼭 구현하고, 나머지 훅은 필요한 것만 덮어쓴다.
Scene trait.
- Only get_scene_base and get_scene_base_mut must be implemented, and the other hooks are overridden only as needed.
use vanilla::{Colors, Engine, EngineConfiguration, Graphic, Rect, Scene, SceneBase, Vector2};
struct MainScene {
scene_base: SceneBase,
}
impl Scene for MainScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
fn pre_draw(&mut self, graphic: &mut Graphic) {
self.scene_base.draw_scene_background(graphic);
}
fn draw(&mut self, graphic: &mut Graphic) {
graphic.set_fill_color(Colors::WHITE);
graphic.draw_rect(Rect::create(100.0, 100.0, 200.0, 120.0));
}
}
let mut engine_configuration = EngineConfiguration::new();
engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
let engine = Engine::new(engine_configuration);
let main_scene = MainScene {
scene_base: SceneBase::new(),
};
if let Err(error) = engine.run(Box::new(main_scene)) {
eprintln!("{}", error);
}use vanilla::{Engine, Scene, SceneBase, Vector2};
struct TouchScene {
scene_base: SceneBase,
last_touch_position: Vector2,
}
impl Scene for TouchScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
fn touch_press(&mut self, view_input_position: Vector2) {
self.last_touch_position = view_input_position;
}
}씬 공통 상태 반환.
Returns the common scene state.
반환Returns&SceneBase 씬이 든 씬 공통 상태.The common scene state the scene holds.
씬 공통 상태 반환. (변경용)
Returns the common scene state. (mutable)
반환Returns&mut SceneBase 씬이 든 씬 공통 상태.The common scene state the scene holds.
생성. (엔진이 씬을 불러올 때 load 앞에 한 번, 원본 create)
- 씬 공통 상태는 SceneBase::new 가 이미 만들었다. 엔진이 필요 없는 칸 채우기를 여기서 한다. (엔진은 Engine::get_engine())
Create. (once before load when the engine loads the scene, the original create)
- SceneBase::new has already built the shared scene state. Fill fields that do not need the engine here. (Take the engine with Engine::get_engine())
짝Counterpart: vanilla.js Scene.create
불러오기. (엔진이 씬을 불러올 때 create 뒤에 한 번, 원본 async load. 노드 트리와 애셋을 여기서 만든다)
- 원본 await 자리: engine.spawn_scene_task(self, |mut scene_context| async move { ... }) 로 맡긴 작업을 get_scene_base_mut().track_task 로 맡긴다. 맡긴 애셋과 작업이 다 끝나야 initialize 로 넘어간다. (원본 load 의 Promise 가 끝나는 때)
Load. (once after create when the engine loads the scene, the original async load. Build the node tree and assets here)
- In place of the original await: entrust the task given with engine.spawn_scene_task(self, |mut scene_context| async move { ... }) via get_scene_base_mut().track_task. It moves on to initialize only after the tracked assets and tasks have all finished. (when the original load's Promise finishes)
- _engine&Engine
- 엔진. (애셋 읽기, 작업 맡기기, 매니저)Engine. (reading assets, entrusting tasks, managers)
짝Counterpart: vanilla.js Scene.load
초기화. (load 에서 맡긴 애셋이 다 읽히고 0.3 초 뒤 한 번. 원본 initialize. 맡긴 것이 없어도 load 뒤 0.3 초를 기다린다)
- 웹은 애셋이 나중에 오므로, 애셋을 쓰는 노드는 여기서 만든다. 데스크탑은 load 에서 만들어도 된다.
Initialization. (once, 0.3 seconds after the assets tracked in load have all loaded. The original initialize. Waits 0.3 seconds after load even if nothing was tracked)
- On the web assets arrive later, so create nodes that use assets here. On desktop they may be created in load.
- _engine&Engine
- 엔진.Engine.
짝Counterpart: vanilla.js Scene.initialize
로딩 중 출력. (initialize 전까지 tick / draw 대신 불린다. 원본 drawOnLoad)
Drawing while loading. (called instead of tick / draw until initialize. The original drawOnLoad)
- _graphic&mut Graphic
- 로딩 화면을 그릴 그래픽.Graphic to draw the loading screen with.
짝Counterpart: vanilla.js Scene.drawOnLoad
종료처리. (내릴 때 unload 앞에 한 번, 원본 finalize)
Finalize. (once before unload when unloading, the original finalize)
- _engine&Engine
- 엔진.Engine.
짝Counterpart: vanilla.js Scene.finalize
로딩 해제. (내릴 때 finalize 뒤에 한 번, 원본 async unload. 여기서 track_task 로 맡긴 작업이 끝나야 내리기가 끝난다)
Unload loading. (once after finalize when unloading, the original async unload. Unloading finishes only after tasks entrusted here with track_task finish)
- _engine&Engine
- 엔진.Engine.
짝Counterpart: vanilla.js Scene.unload
해제. (엔진이 씬을 내릴 때 unload 뒤, 씬을 버리기 직전에 한 번. 그 씬의 작업이 남았으면 다 끝난 뒤)
Destroy. (once when the engine unloads the scene, after unload, right before dropping the scene. After all of that scene's remaining tasks finish)
짝Counterpart: vanilla.js Scene.destroy
터치 누름. (원본 Scene.touchPress, 엔진이 tick 뒤에 부른다)
Touch press. (the original Scene.touchPress, called by the engine after tick)
- _view_input_positionVector2
- 누른 자리. (뷰 좌표)Press position. (view coordinates)
짝Counterpart: vanilla.js Scene.touchPress
터치 이동. (누르고 있는 동안, 누른 프레임과 뗀 프레임에는 부르지 않는다)
Touch move. (while pressing, not called on the press frame or the release frame)
- _view_input_positionVector2
- 지금 자리. (뷰 좌표)Current position. (view coordinates)
짝Counterpart: vanilla.js Scene.touchMove
터치 뗌. (한 프레임 안에 눌렀다 떼면 누름 뒤에 바로)
Touch release. (right after press if pressed and released within one frame)
- _view_input_positionVector2
- 뗀 자리. (뷰 좌표)Release position. (view coordinates)
짝Counterpart: vanilla.js Scene.touchRelease
터치 취소됨.
Touch cancelled.
- _view_input_positionVector2
- 취소된 때의 자리. (뷰 좌표)Position at cancel. (view coordinates)
짝Counterpart: vanilla.js Scene.touchCancel
마우스 휠. (이번 프레임에 쌓인 휠이 있을 때)
Mouse wheel. (when there is wheel accumulated this frame)
- _view_input_positionVector2
- 마우스 자리. (뷰 좌표)Mouse position. (view coordinates)
- _wheel_deltaVector2
- 이번 프레임에 쌓인 휠 양. (x 가로, y 세로, 입력 매니저의 get_wheel_delta_x, get_wheel_delta_y)Wheel amount accumulated this frame. (x horizontal, y vertical, the input manager's get_wheel_delta_x, get_wheel_delta_y)
짝Counterpart: vanilla.js Scene.touchWheel
페이지 프로세스 파기 뒤 복원. (Chromium 의 freeze 뒤 resume, bfcache 에서 돌아온 pageshow 등)
- 엔진이 소리를 다시 깨우고 입력 상태를 비운 뒤 불러온 모든 씬에 부른다.
Restore after the page process is discarded. (resume after a Chromium freeze, pageshow returning from bfcache, etc.)
- The engine wakes the sound again, clears the input state, then calls it on all loaded scenes.
짝Counterpart: vanilla.js Scene.onPageProcessRestored
페이지 가시성 복원. (백그라운드 → 포어그라운드, 웹 visibilitychange 의 visible, 데스크탑 창 가림이 풀림)
- 엔진이 소리를 다시 깨우고 입력 상태를 비운 뒤 불러온 모든 씬에 부른다.
Page visibility restored. (background → foreground, visible of the web visibilitychange, a desktop window being uncovered)
- The engine wakes the sound again, clears the input state, then calls it on all loaded scenes.
짝Counterpart: vanilla.js Scene.onPageVisibilityRestored
화면 영역 변경. (창 크기가 바뀌었을 때, 불러온 직후에도 한 번)
Screen area changed. (when the window size changes, also once right after loading)
- _canvas_native_sizeVector2
- 창 안쪽 논리 크기. (뷰 매니저의 get_canvas_native_size)Logical size of the window interior. (the view manager's get_canvas_native_size)
짝Counterpart: vanilla.js Scene.resize
주기적 갱신.
- 기본 구현은 씬 공통 상태의 tick 을 부른다. 덮어쓰면 get_scene_base_mut().tick(time_delta) 를 직접 부른다.
Periodic update.
- The default implementation calls the common scene state's tick. If overridden, call get_scene_base_mut().tick(time_delta) directly.
- time_deltaf64
- 배율을 곱한 프레임 간격. (초, 시간 관리자의 get_time_delta)Frame interval multiplied by the time scale. (seconds, the time manager's get_time_delta)
짝Counterpart: vanilla.js Scene.tick
이전 출력.
Pre-draw.
- _graphic&mut Graphic
- 그릴 그래픽.Graphic to draw with.
짝Counterpart: vanilla.js Scene.preDraw
출력.
- 기본 구현은 씬 공통 상태의 draw 로 노드 트리를 그린다.
Draw.
- The default implementation draws the node tree with the common scene state's draw.
- graphic&mut Graphic
- 그릴 그래픽.Graphic to draw with.
짝Counterpart: vanilla.js Scene.draw
이후 출력.
Post-draw.
- _graphic&mut Graphic
- 그릴 그래픽.Graphic to draw with.
짝Counterpart: vanilla.js Scene.postDraw
기즈모 출력.
- 기즈모 표시(set_gizmo_visible)를 켠 씬에만 post_draw 뒤에 부른다.
Gizmo draw.
- Called after post_draw only on scenes with gizmo display (set_gizmo_visible) on.
- _graphic&mut Graphic
- 그릴 그래픽.Graphic to draw with.
짝Counterpart: vanilla.js Scene.drawGizmos