core/engine
엔진.
- 원본은 캔버스를 잡고 request_animation_frame 으로 프레임을 돈다. 러스트 판은 창, GL 컨텍스트, 입력 이벤트, 화면 넘기기를 플랫폼 층(crate::platform)이 맡고, 여기 EngineRunner 는 플랫폼을 모른 채 씬과 프레임 흐름만 돈다. (데스크탑: platform/desktop.rs, 웹: platform/web.rs)
- 씬에는 &Engine 을 넘긴다. 씬은 여기서 매니저(시간, 뷰, 입력)를 꺼내 쓴다. 엔진을 받지 않는 자리는 원본 Engine.getEngine() 처럼 Engine::get_engine() 으로 전역 엔진을 꺼낸다. (core/globalengine.rs)
- Graphic 은 플랫폼이 GL 컨텍스트를 만든 뒤 attach_graphic 으로 넘겨받아 엔진이 든다. 원본 getGraphic 처럼 씬의 어느 훅에서나 get_graphic, get_graphic_mut 로 꺼낸다. 씬의 draw 계열은 지금처럼 graphic 인자를 받는다. 그 인자는 엔진이 든 그래픽을 Option::take 로 잠깐 꺼내 넘긴 것이다. (&Engine 과 &mut Graphic 을 함께 넘기려면 그래픽이 엔진 밖에 있어야 해서, 그동안 engine.get_graphic() 은 None 이고 인자의 graphic 이 곧 그 그래픽이다. with_graphic 도 같다. RefCell 도 unsafe 도 쓰지 않는다)
- 오디오 매니저를 원본처럼 생성할 때 만들어 든다. AudioContext(소리 장치)는 처음 쓸 때 만든다. 프레임마다 하는 오디오 일은 없다. 웹은 플랫폼이 click / touchstart / keydown 에서 resume_on_user_gesture, focus / visibilitychange 에서 resume 을 부른다.
- 원본 SceneManager.getAllLoadedScenes 는 get_all_loaded_scenes 로, 씬 객체 대신 핸들(SceneId)을 돌려준다. (씬마다 &Engine 을 받아 도는 동안 다른 씬을 빌릴 수 없다)
- 원본처럼 씬을 불러오면 루트를 뷰 크기로 맞추고(create 와 load 사이), 맡긴 애셋이 다 끝난 뒤에도 로딩 화면을 0.3초 더 보이고 initialize 를 부른다.
- 글자 입력칸 포커스(is_text_input_focused)는 원본처럼 문서의 초점을 보고, 문서가 없는 데스크탑은 엔진 입력 필드의 포커스를 본다.
- 씬 하나만 내리기(unload_scene)는 원본 SceneManager.unloadScene 자리다. 원본은 씬 객체로, 러스트 판은 load_scene 이 돌려준 SceneId 로 가리키고, unload_all_scenes 처럼 이번 프레임이 끝난 뒤 내린다. 아직 create 전인(같은 프레임에 불러온) 씬이면 create 도 destroy 도 부르지 않고 뺀다.
- 페이지 이벤트(PageEvent): 원본은 모듈마다 document / window 에 리스너를 단다. 러스트 판은 플랫폼이 엔진에 알리고 엔진이 add_page_event_listener 로 받은 리스너에 그 자리에서 넘긴다. (SoundSystem 이 가려짐과 포커스를 이것으로 받는다) 웹: visibilitychange(Hidden, Visible), blur(Blurred), focus(Focused), pointerdown(PointerDown). 데스크탑: 창 가림(Occluded, 맥과 X11 이 알린다), 최소화(윈도우가 이것으로 알린다), 앱 멈춤(모바일), 웨이랜드 프레임 콜백이 3 초 넘게 오지 않음은 Hidden, 포커스, 마우스 단추와 손가락 누름.
- 페이지 복원 훅: 원본 setupAllDocumentEvents 처럼 소리를 다시 깨우고 입력을 비운 뒤 씬마다 부른다. 웹: visibilitychange 의 visible → on_page_visibility_restored, 문서 resume 과 pageshow(persisted) → on_page_process_restored. pageshow 는 resume 과 같은 복구를 한다. (원본이 정의되지 않은 dispatchPageProcessRestored 를 불러 예외가 나던 것은 원본에서도 같게 고쳤다) 데스크탑: 창 가림이 풀리면 on_page_visibility_restored, 앱이 suspended 뒤 resumed 되면 on_page_process_restored. (윈도우, 맥, 리눅스의 winit 은 suspended 를 보내지 않아 데스크탑에서는 on_page_process_restored 가 불리지 않는다)
- async/await: 엔진이 스레드 하나짜리 실행기(core/task.rs)를 품는다. spawn_task, spawn_scene_task 는 원본 async 함수처럼 맡기는 자리에서 첫 await 까지 돌리고, 남은 작업은 프레임마다 씬의 tick 앞에서 깨어난 것만 한 번씩 폴링한다. 원본에서 Promise 를 돌려주는 엔진 함수는 await 할 수 있는 꼴을 같이 둔다. (load_scene_async, unload_scene_async, unload_all_scenes_async, read_clipboard_text_async, request_frame_capture_async, alert_async, confirm_async, prompt_async(원본 engine.alertAsync 들). 질문 창이 떠 있는 동안은 원본처럼 작업도 폴링하지 않는다)
- 씬 내리기는 원본 SceneManager.unloadScene 처럼 finalize, unload 를 부르고, unload 가 track_task 로 맡긴 작업이 끝나기를 기다린다. (그동안은 원본처럼 목록에 남아 tick 과 draw 를 받는다) 끝나면 목록에서 빼고, 그 씬의 작업이 남았으면 원본의 Promise 사슬처럼 다 끝날 때까지 씬 값을 살려 둔다. (tick, draw 는 받지 않고 SceneContext::with 는 그 씬을 준다) 불러오는 도중에 내린 씬은 원본 loadScene 처럼 불러오기가 끝나면 initialize 까지 받는다. 다 끝나면 destroy 를 부르고 버린다.
매 프레임 (update_engine): 1. graphic.apply_settings() # 뷰포트/프로젝션 갱신 + 상태 리셋 + 화면 비우기 2. time_manager.update() # time_delta 산출 3. input_manager.tick() 4. 깨어난 작업 폴링 (begin_poll_frame, 깨운 차례 줄이 빌 때까지 poll_woken_tasks 와 내리기 마무리) 5. 씬마다 tick → pre_draw → draw → post_draw (→ draw_gizmos) 6. 통계 출력(옵션) → 1회성 입력 플래그 클리어(글 입력 줄 마무리 포함) → 묶음 내보내기 → (검증용 화면 저장) 화면 넘기기는 플랫폼이 update_engine 다음에 한다.
Engine.
- The original grabs a canvas and runs frames with request_animation_frame. In the Rust version the platform layer (crate::platform) handles the window, GL context, input events and presenting the screen, and EngineRunner here runs only the scenes and frame flow without knowing the platform. (desktop: platform/desktop.rs, web: platform/web.rs)
- Scenes are passed &Engine. Scenes take the managers (time, view, input) from it. Places that do not receive the engine take the global engine with Engine::get_engine(), like the original Engine.getEngine(). (core/globalengine.rs)
- The Graphic is handed over through attach_graphic after the platform creates the GL context and is held by the engine. Like the original getGraphic, it is taken with get_graphic and get_graphic_mut in any scene hook. The scene's draw family takes the graphic argument as before. That argument is the engine's graphic taken out for a moment with Option::take and passed in. (to pass &Engine and &mut Graphic together the graphic has to be outside the engine, so meanwhile engine.get_graphic() is None and the graphic argument is that graphic. with_graphic is the same. Neither RefCell nor unsafe is used)
- As in the original, the audio manager is created and held at construction. The AudioContext (sound device) is created on first use. There is no per-frame audio work. On the web the platform calls resume_on_user_gesture on click / touchstart / keydown, and resume on focus / visibilitychange.
- The original SceneManager.getAllLoadedScenes is get_all_loaded_scenes, which returns handles (SceneId) instead of scene objects. (while each scene runs with &Engine, other scenes cannot be borrowed)
- As in the original, loading a scene fits the root to the view size (between create and load), and even after the tracked assets have all finished, shows the loading screen 0.3 seconds longer and calls initialize.
- Text input focus (is_text_input_focused) looks at the document focus as in the original, and desktop, which has no document, looks at the focus of the engine input field.
- Unloading a single scene (unload_scene) stands in for the original SceneManager.unloadScene. The original refers to it by the scene object, the Rust version by the SceneId returned by load_scene, and like unload_all_scenes it unloads after the current frame ends. A scene not yet created (loaded in the same frame) is removed without calling create or destroy.
- Page events (PageEvent): in the original each module attaches listeners to document / window. In the Rust version the platform notifies the engine, and the engine passes it on the spot to the listeners received through add_page_event_listener. (SoundSystem receives occlusion and focus through this) Web: visibilitychange (Hidden, Visible), blur (Blurred), focus (Focused), pointerdown (PointerDown). Desktop: window occlusion (Occluded, reported by macOS and X11), minimization (how Windows reports it), app suspension (mobile) and Wayland frame callbacks not arriving for more than 3 seconds are Hidden; also focus, and mouse button and finger presses.
- Page restore hooks: as in the original setupAllDocumentEvents, wakes the sound again, clears input, then calls each scene. Web: visible of visibilitychange → on_page_visibility_restored, document resume and pageshow (persisted) → on_page_process_restored. pageshow does the same recovery as resume. (the original called the undefined dispatchPageProcessRestored and threw, which was fixed the same way in the original too) Desktop: on_page_visibility_restored when window occlusion ends, on_page_process_restored when the app is resumed after being suspended. (winit on Windows, Mac and Linux does not send suspended, so on_page_process_restored is not called on desktop)
- async/await: the engine contains a single-threaded executor (core/task.rs). spawn_task and spawn_scene_task, like original async functions, run at the call site up to the first await, and the remaining tasks are polled once per frame before the scenes' tick, only those that were woken. Engine functions that return a Promise in the original also have a form that can be awaited. (load_scene_async, unload_scene_async, unload_all_scenes_async, read_clipboard_text_async, request_frame_capture_async, and alert_async, confirm_async, prompt_async (the original engine.alertAsync and the others). While a question dialog is open, tasks are not polled either, as in the original)
- Unloading a scene calls finalize and unload like the original SceneManager.unloadScene, and waits for the tasks unload tracked with track_task to finish. (meanwhile it stays in the list and receives tick and draw, as in the original) When done it is removed from the list, and if the scene still has tasks, like the original Promise chain the scene value is kept alive until they all finish. (it receives no tick or draw, and SceneContext::with gives that scene) A scene unloaded while loading, like the original loadScene, still receives initialize once loading finishes. When everything is done, destroy is called and it is dropped.
Every frame (update_engine): 1. graphic.apply_settings() # viewport/projection update + state reset + clear screen 2. time_manager.update() # compute time_delta 3. input_manager.tick() 4. Poll woken tasks (begin_poll_frame, poll_woken_tasks and unload finishing until the woken queue is empty) 5. For each scene tick → pre_draw → draw → post_draw (→ draw_gizmos) 6. Stats output (optional) → clear one-shot input flags (including finishing the text input line) → flush batches → (screen capture for verification) The platform presents the screen after update_engine.
EngineConfigurationstruct traits Default
엔진 설정.
- EngineConfiguration::new() 의 기본값에서 필요한 칸만 바꿔 Engine::new 에 넘긴다.
Engine configuration.
- Change only the fields you need from the defaults of EngineConfiguration::new() and pass it to Engine::new.
use std::path::PathBuf;
use vanilla::{Engine, EngineConfiguration, Vector2, ViewScaleMode};
let mut engine_configuration = EngineConfiguration::new();
engine_configuration.title = String::from("My Game");
engine_configuration.reference_resolution_size = Vector2::create(1920.0, 1080.0);
engine_configuration.view_scale_mode = ViewScaleMode::StretchShortExpandLong;
engine_configuration.asset_directory_paths = vec![PathBuf::from("examples/assets")];
engine_configuration.maximum_frame_per_second = 60.0;
engine_configuration.antialias = true;
assert!(engine_configuration.use_vertical_sync);
let engine = Engine::new(engine_configuration);
assert_eq!(engine.get_engine_configuration().title, "My Game");
assert_eq!(engine.resolve_asset_path("atlas/icons.png"), PathBuf::from("examples/assets/atlas/icons.png"));생성.
Constructor.
반환ReturnsEngineConfiguration 기본 설정. (기준 해상도 1280x720, StretchShort, 제목 바닐라엔진, 창 크기 0(기준 해상도), 크기 바꾸기 켬, 수직 동기 켬, 최대 FPS 0(제한 없음), 개발자 도구 켬, 캔버스 id mainCanvas, 안티에일리어싱 켬, 나머지는 끔이거나 빈 값)Default configuration. (reference resolution 1280x720, StretchShort, title VanillaEngine, window size 0 (reference resolution), resizing on, vertical sync on, maximum FPS 0 (unlimited), developer tools on, canvas id mainCanvas, antialiasing on, everything else off or empty)
짝Counterpart: vanilla.js EngineConfiguration.constructor
기준 해상도. (뷰 스케일 모드가 none 이 아니면 씬은 이 좌표계로 그린다)
Reference resolution. (if the view scale mode is not none, scenes draw in this coordinate system)
반환ReturnsVector2
짝Counterpart: vanilla.js EngineConfiguration.referenceResolutionSize
뷰 스케일 모드.
View scale mode.
반환ReturnsViewScaleMode
짝Counterpart: vanilla.js EngineConfiguration.viewScaleMode
창 제목. (데스크탑 창 제목, 웹은 비어 있지 않고 기본값이 아니면 원본처럼 시작할 때 문서 제목(document.title)에 쓴다)
Window title. (the desktop window title; on the web, if not empty and not the default, it is written to the document title (document.title) at startup as in the original)
반환ReturnsString
짝Counterpart: vanilla.js EngineConfiguration.title
처음 창 크기. (논리 크기, 0 이면 기준 해상도)
Initial window size. (logical size, the reference resolution if 0)
반환ReturnsVector2
화면 왼쪽 위에 FPS / 드로우 콜 출력.
Shows FPS / draw calls at the top left of the screen.
반환Returnsbool
짝Counterpart: vanilla.js EngineConfiguration.useStatistics
개발자 도구(F2 하이어라키/인스펙터)를 GameSceneBase 가 만드는지. (원본 useDevTools, 기본 true)
Whether GameSceneBase creates the developer tools (F2 hierarchy/inspector). (the original useDevTools, default true)
반환Returnsbool
짝Counterpart: vanilla.js EngineConfiguration.useDevTools
최대 FPS. 0 이면 제한하지 않는다. (수직 동기를 켜면 화면 주사율을 따른다)
Maximum FPS. No limit if 0. (with vertical sync on, follows the display refresh rate)
반환Returnsf64
짝Counterpart: vanilla.js EngineConfiguration.maximumFramePerSecond
기본 글꼴 사슬의 파일. (데스크탑, 비우면(기본) 원본 SYSTEM_FONT_STRING 의 이름을 차례로 운영체제 글꼴에서 찾아 잇는다)
- 주면 읽히는 파일을 모두 차례로 잇는다. 앞 글꼴에 없는 글자는 뒤 글꼴로 그린다. (원본 글꼴 목록과 같다) TTC 는 굵기로 얼굴을 고르고, 가변 글꼴은 굵기를 축 값으로 만든다.
Files of the default font chain. (desktop, if empty (default), looks up the names of the original SYSTEM_FONT_STRING in order among the operating system fonts and chains them)
- If given, chains all readable files in order. Characters missing from an earlier font are drawn with a later font. (same as the original font list) For TTC the face is chosen by weight, and for variable fonts the weight becomes an axis value.
반환ReturnsVec<PathBuf>
기본 글꼴 사슬의 굵은 파일. (default_font_paths 와 같은 자리의 글꼴의 굵기 700 얼굴, 데스크탑)
Bold files of the default font chain. (the weight 700 face of the font in the same position as default_font_paths, desktop)
반환ReturnsVec<PathBuf>
대체 글꼴 후보 경로. (데스크탑, 비우면(기본) 원본 브라우저처럼 어느 글꼴에도 없는 글자를 운영체제가 고른 대체 글꼴로 그린다. 맥 CoreText, 윈도우 DirectWrite, 리눅스 fontconfig)
- 주면 운영체제에 묻지 않고 등록된 어느 글꼴에도 없는 글자가 나올 때 앞에서부터 읽어 대체 폰트로 쓴다. 색 이모지 글꼴(색 글리프 표가 있는 파일)은 이모지 표시 글자가 나올 때 먼저 읽고, 다른 글자 때문에는 마지막에 읽는다.
Fallback font candidate paths. (desktop, if empty (default), like the original browser, characters missing from every font are drawn with a fallback font chosen by the operating system. Mac CoreText, Windows DirectWrite, Linux fontconfig)
- If given, without asking the operating system, when a character missing from every registered font appears, they are loaded from the front and used as fallback fonts. Color emoji fonts (files with color glyph tables) are loaded first when an emoji presentation character appears, and last when needed for other characters.
반환ReturnsVec<PathBuf>
애셋 폴더 후보. (resolve_asset_path 가 앞에서부터 찾는다)
Asset folder candidates. (resolve_asset_path searches from the front)
반환ReturnsVec<PathBuf>
창 아이콘 PNG. (애셋 폴더 기준 상대 경로, 비우면 기본 아이콘)
Window icon PNG. (relative path from the asset folder, the default icon if empty)
반환ReturnsString
기본 폰트 파일 내용. (있으면 경로 후보보다 먼저 쓴다. 파일을 못 읽는 웹에서 미리 받아 넘긴다)
Default font file contents. (used before the path candidates if present. On the web, which cannot read files, it is downloaded in advance and passed)
반환ReturnsOption<Vec<u8>>
굵은 기본 폰트 파일 내용.
Bold default font file contents.
반환ReturnsOption<Vec<u8>>
웹에서 그릴 캔버스 id. (없으면 만들어 body 에 붙인다)
Canvas id to draw to on the web. (created and attached to body if missing)
반환ReturnsString
짝Counterpart: vanilla.js EngineConfiguration.canvasId
웹 기본 폰트 주소. (원본 defaultFontUrl. 웹에서 default_font_bytes 가 없으면 여기서 받아 기본 폰트로 쓴다. 빈 글이면 받지 않는다)
- 기본값은 빈 글이다. (원본 기본값 DOSGothic 은 넣지 않는다) 아무 글꼴도 주지 않으면 원본처럼 브라우저 시스템 글꼴로 그린다.
- 게임 글꼴을 쓰려면 이 주소나 default_font_bytes, FontAsset 으로 준다.
- 데스크탑은 쓰지 않고 default_font_paths(비면 운영체제가 찾은 시스템 글꼴 사슬)를 본다.
Web default font URL. (the original defaultFontUrl. On the web, if default_font_bytes is absent, the font is fetched from here and used as the default font. Nothing is fetched if empty)
- The default is an empty string. (the original default DOSGothic is not included) If no font is given at all, it draws with the browser system font as in the original.
- To use a game font, give this URL, default_font_bytes, or a FontAsset.
- Desktop does not use it and looks at default_font_paths (if empty, the system font chain found by the operating system).
반환ReturnsString
짝Counterpart: vanilla.js EngineConfiguration.defaultFontUrl
웹에서 touchend 와 pointerup 도 user gesture 로 보고 오디오를 재개한다. (원본과 같이 기본은 끔)
On the web, also treats touchend and pointerup as user gestures and resumes audio. (off by default, as in the original)
반환Returnsbool
짝Counterpart: vanilla.js EngineConfiguration.resumeAudioOnTouchEnd
웹에서 애셋 주소 앞에 붙일 것. (비우면 페이지 기준 상대 주소. 데스크탑은 asset_directory_paths 를 쓴다)
Prefix for asset URLs on the web. (if empty, relative to the page. Desktop uses asset_directory_paths)
반환ReturnsString
창 크기가 바뀌면 캔버스를 창에 맞춘다. (원본처럼 기본은 끔. 켜면 visualViewport 크기에 맞추고 캔버스 비 상한을 건다. 끄면 웹은 페이지가 정한 캔버스 크기를 읽는다) 데스크탑 창은 캔버스가 창을 가득 채운 페이지와 같아, 끄면 창 크기 그대로이고 화면 키보드에 줄지 않으며 캔버스 비 상한도 걸지 않는다.
Fits the canvas to the window when the window size changes. (off by default as in the original. When on, fits to the visualViewport size and applies the canvas ratio limit. When off, the web reads the canvas size set by the page) A desktop window is like a page whose canvas fills the window, so when off it stays at the window size, does not shrink for the on-screen keyboard, and does not apply the canvas ratio limit.
반환Returnsbool
짝Counterpart: vanilla.js EngineConfiguration.autoResizeOnWindowResize
프레임이 끝난 뒤에도 그린 것을 캔버스에 남긴다. (원본 WebGL 컨텍스트 옵션 preserveDrawingBuffer, 켜면 프레임 첫머리에 색을 비우지 않아 지난 프레임 그림 위에 그린다. 웹은 컨텍스트 옵션으로 넘기고, 데스크탑은 다 그린 프레임을 떠 두었다가 다음 프레임 첫머리에 되그린다. platform/desktop/preserveddrawingbuffer.rs)
Keeps what was drawn on the canvas even after the frame ends. (the original WebGL context option preserveDrawingBuffer, when on, the color is not cleared at the start of the frame, so it draws over the last frame's picture. The web passes it as a context option, desktop captures the finished frame and redraws it at the start of the next frame. platform/desktop/preserveddrawingbuffer.rs)
반환Returnsbool
짝Counterpart: vanilla.js EngineConfiguration.preserveDrawingBuffer
캔버스(기본 프레임 버퍼)의 멀티샘플 안티에일리어싱(MSAA)을 켤지. (원본 antialias, 기본 true, 생성 때 정한다)
- 끄면 도형과 3D 의 가장자리가 계단져 보이는 대신 고해상도 모바일에서 프레임마다 드는 리졸브 비용이 빠진다.
- 웹은 WebGL 컨텍스트 속성 antialias 로 켬과 끔만 고르고 표본 수는 브라우저가 정한다. 데스크탑은 켜면 표본 4, 끄면 멀티샘플 없는 GL 설정을 고른다.
- 후처리(ToonPostProcess)가 자기 MSAA 판에 그리므로 그걸 쓰는 게임은 캔버스 antialias 를 false 로 짓는다. true 면 캔버스 자체가 MSAA 라 화면에 옮기는 패스와 UI 가 표본마다 섞여 값이 더 든다. (맥미니 2560x1440 툰 후처리 장면 GPU 처리량 6.89 → 6.49 ms, 끈 판 6.81 → 5.22 ms, 원본 같은 장면에서 잰 값)
- 예: engine_configuration.antialias = false; (ToonPostProcess 를 쓰는 게임)
Whether to turn on multisample antialiasing (MSAA) for the canvas (default framebuffer). (Original antialias, default true, decided at creation)
- Turning it off makes the edges of shapes and 3D look jagged, but removes the per-frame resolve cost on high-resolution mobile devices.
- On the web only on or off is chosen through the WebGL context attribute antialias, and the browser decides the sample count. On desktop, on means 4 samples and off picks a GL configuration without multisampling.
- A game that uses a post process (ToonPostProcess) should build the canvas with antialias set to false, because the post process draws into its own MSAA target. With true, the canvas itself is MSAA, so the pass that copies to the screen and the UI blend per sample and cost more. (Mac mini, 2560x1440 toon post process scene, GPU throughput 6.89 → 6.49 ms, with it off 6.81 → 5.22 ms, measured on the same scene in the original)
- Example: engine_configuration.antialias = false; (for a game that uses ToonPostProcess)
반환Returnsbool
짝Counterpart: vanilla.js EngineConfiguration.antialias
GPU 메모리 셈(개발용)을 처음부터 켤지. (원본 trackGpuMemory, 기본 false, 생성 때 정한다) 끄면 GL 짓기와 크기 정하기 호출이 깃발 하나만 보고 지나가 프레임에 드는 일이 없다.
- 켜면 엔진이 처음 짓는 자원까지 센다. 나중에 켜려면 Engine::enable_gpu_memory_tracking 이고 그 뒤에 지은 것부터 센다.
- 예: engine_configuration.track_gpu_memory = true; (프로파일링 때)
Whether to turn GPU memory tracking (for development) on from the start. (original trackGpuMemory, default false, decided at creation) When off, GL creation and sizing calls only look at one flag, so nothing runs per frame.
- When on, the resources the engine creates first are counted too. To turn it on later, use Engine::enable_gpu_memory_tracking, which counts what is created after it.
- Example: engine_configuration.track_gpu_memory = true; (when profiling)
반환Returnsbool
짝Counterpart: vanilla.js EngineConfiguration.trackGpuMemory
화면 키보드: 글자 입력칸이 포커스된 동안 가로가 같고 세로만 줄었으면 크기를 그대로 둔다. (auto_resize_on_window_resize 일 때, 데스크탑은 크롬 윈도우처럼 터치 키보드가 visualViewport 를 줄인다. 맥과 리눅스는 크롬처럼 줄지 않는다)
On-screen keyboard: while a text input is focused, keeps the size as is if the width is the same and only the height shrank. (with auto_resize_on_window_resize, on desktop the touch keyboard shrinks the visualViewport as in Chrome on Windows. On Mac and Linux it does not shrink, as in Chrome)
반환Returnsbool
짝Counterpart: vanilla.js EngineConfiguration.ignoreVirtualKeyboardResize
캔버스의 가로세로 비 상한. (창이 그보다 길쭉하면 캔버스를 줄여 창의 가운데에 둔다, 0 이면 제한 없음)
Upper limit of the canvas aspect ratio. (if the window is more elongated than that, the canvas is shrunk and centered in the window, no limit if 0)
반환Returnsf64
짝Counterpart: vanilla.js EngineConfiguration.maxCanvasAspectRatio
글꼴이 늦게 받아지면 그 글꼴로 구운 글자 가운데 그 글꼴의 글자 범위에 든 것만 버려 다시 굽게 할지. (원본 rebakeTextOnFontLoad, 원본처럼 기본 끔) 끄면 받기 전에 다른 글꼴로 구운 글자는 캐시에서 밀려날 때까지 그대로 남는다. (글자 범위로 나눈 글꼴 조각을 그때그때 받는 프로젝트가 켠다)
Whether, when a font arrives late, to discard only the text baked with that font that falls within the font's character range so it is rebaked. (the original rebakeTextOnFontLoad, off by default as in the original) When off, text baked with another font before the download stays as is until it is pushed out of the cache. (turned on by projects that download font pieces split by character range as needed)
반환Returnsbool
짝Counterpart: vanilla.js EngineConfiguration.rebakeTextOnFontLoad
문서 언어. (웹 판 index.html 의 html lang 자리, Document::get_language. 비우면 데스크탑은 빈 글이고 웹은 페이지가 적어 둔 그대로)
Document language. (in place of html lang in the web version's index.html, Document::get_language. If empty, an empty string on desktop and as written by the page on the web)
반환ReturnsString
문서의 meta. ((이름, content) 목록, 웹 판 index.html 의 head 의 meta 자리. Document::get_meta_content, BuildInfo 가 build-version 을 읽는다)
- 데스크탑 배포 빌드는 웹 판이 index.html 에 적는 판을 여기에 넣는다. (build.rs 의 rustc-env 를 env! 로 읽는 것 같은 것) 웹에서도 비어 있지 않으면 문서에 쓴다.
Document meta. (a list of (name, content), in place of the meta in the head of the web version's index.html. Document::get_meta_content, BuildInfo reads build-version)
- Desktop release builds put here the version the web version writes in index.html. (such as reading build.rs's rustc-env with env!) On the web it is also written to the document if not empty.
반환ReturnsVec<(String, String)>
3D 색 공간. (원본 colorSpace, 기본 Gamma, 생성 때 정한다. Linear 면 툰 렌더러, 후처리, 화면 바깥선, GLB 읽기가 선형 공간에서 빛을 셈한다, colorspace.rs 머리말)
- 2D(Graphic 의 2D 묶음, 글자, UI)는 어느 값이든 감마 공간에서 합성한다.
3D color space. (original colorSpace, default Gamma, fixed at creation. With Linear, the toon renderer, post process, screen outline and GLB readers compute light in linear space, see the colorspace.rs header)
- 2D (Graphic's 2D batches, text, UI) is composited in gamma space either way.
반환ReturnsColorSpace
짝Counterpart: vanilla.js EngineConfiguration.colorSpace
PageEventListenertype
페이지 이벤트 리스너. (엔진은 약한 참조로 들어, 리스너를 버리면 더 부르지 않는다)
Page event listener. (the engine holds it by weak reference, so dropping the listener stops it from being called)
pub type PageEventListener = Rc<RefCell<dyn FnMut(PageEvent)>>GraphicContextEventListenertype
그래픽 컨텍스트 이벤트 리스너. (엔진은 약한 참조로 들어, 리스너를 버리면 더 부르지 않는다)
Graphic context event listener. (The engine holds it by a weak reference, dropping the listener stops further calls)
pub type GraphicContextEventListener = Rc<RefCell<dyn FnMut(GraphicContextEvent)>>GraphicErrorstruct traits Clone, Debug, PartialEq, Eq
그래픽 오류. (원본의 { kind, name, error })
Graphic error. (The original's { kind, name, error })
use vanilla::{GraphicError, GraphicErrorKind};
let error = GraphicError {
kind: GraphicErrorKind::ShaderBuildFailed,
name: String::from("ScreenEffect.blur"),
error: String::from("link failed"),
};
assert_eq!(error.kind, GraphicErrorKind::ShaderBuildFailed);
assert_eq!(error.name, "ScreenEffect.blur");짓지 못한 것의 이름. (툰 렌더러는 "ToonRenderer.머티리얼 이름", 화면 효과는 "ScreenEffect.패스 이름")
Name of what could not be built. ("ToonRenderer.material name" for the toon renderer, "ScreenEffect.pass name" for screen effects)
반환ReturnsString
GraphicErrorListenertype
그래픽 오류 리스너. (엔진은 약한 참조로 들어, 리스너를 버리면 더 부르지 않는다)
Graphic error listener. (The engine holds it by a weak reference, dropping the listener stops further calls)
pub type GraphicErrorListener = Rc<RefCell<dyn FnMut(&GraphicError)>>FrameCaptureHandlertype
검증용 화면 저장을 받는 함수. (그 프레임을 다 그린 화면의 PNG 바이트, 원본은 PNG data URL)
Function that receives the verification screen capture. (PNG bytes of the fully drawn screen of that frame, a PNG data URL in the original)
pub type FrameCaptureHandler = Box<dyn FnOnce(&[u8])>Enginestruct
엔진.
- 설정으로 만들고 run 에 첫 씬을 넘겨 돌린다. 씬의 훅은 &Engine 을 받아 매니저(시간, 뷰, 입력, 오디오, 커서)와 그래픽(get_graphic, 데스크탑 주 스레드는 Engine::new 직후부터)을 꺼내 쓴다.
Engine.
- Make it from a configuration and pass the first scene to run. Scene hooks receive &Engine and take out the managers (time, view, input, audio, cursor) and the graphic (get_graphic, on the desktop main thread right after Engine::new).
use vanilla::{Engine, EngineConfiguration, 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
}
}
let mut engine_configuration = EngineConfiguration::new();
engine_configuration.auto_resize_on_window_resize = true;
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);
std::process::exit(1);
}use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
assert_eq!(engine.get_frame_number(), 1);
assert!(!engine.get_version_string().is_empty());
engine.get_time_manager_mut().set_time_scale(0.5);
assert_eq!(engine.get_time_manager().get_time_scale(), 0.5);
engine.set_maximum_frame_per_second(30.0);
assert_eq!(engine.get_maximum_frame_per_second(), 30.0);
assert_eq!(engine.get_canvas().is_some(), engine.get_graphic().is_some());생성.
- 매니저(시간, 뷰, 입력, 커서, 오디오)를 만들고 문서 언어와 meta 를 설정대로 둔다.
- 데스크탑 주 스레드에서는 원본 생성자처럼 그래픽도 짓는다. (이벤트 루프와 숨긴 창, GL 컨텍스트를 만들고 run 이 그 창을 보인다. GL 을 지을 수 없거나 주 스레드가 아니면 run 이 창을 열 때 짓는다) 웹은 run 이 캔버스를 잡을 때 짓는다.
Creates the engine.
- Makes the managers (time, view, input, cursor, audio) and sets the document language and meta from the configuration.
- On the desktop main thread it also builds the graphic, like the original constructor. (It makes the event loop, a hidden window and the GL context, and run shows that window. If GL cannot be built or this is not the main thread, it is built when run opens the window) On the web it is built when run takes the canvas.
- engine_configurationEngineConfiguration
- 엔진 설정. (엔진이 소유한다, get_engine_configuration 으로 읽는다)Engine configuration. (owned by the engine, read with get_engine_configuration)
반환Returns&'static Engine 새 엔진. (프레임 번호 1, 씬 없음. 프로그램 끝까지 사는 자리에 두어 &'static 으로 주고, 전역 엔진이 된다)A new engine. (frame number 1, no scenes. It is put in a place that lives until the program ends and given as &'static, and it becomes the global engine)
짝Counterpart: vanilla.js Engine.constructor
pub fn get_engine() -> Result<&'static crate::core::engine::Engine, crate::core::globalengine::EngineAccessError>#전역 엔진. (원본 static Engine.getEngine(), 마지막으로 만든 엔진)
- 엔진은 처음 한 번 만들고 지우지 않는다. Engine::new 가 프로그램 끝까지 사는 자리에 두므로 &'static Engine 을 준다. (언리얼 GEngine, 고도 Engine 싱글톤과 같은 꼴)
- Engine::new 직후부터 어디서나 꺼낸다: 씬 함수(load, tick, draw 같은), 컴포넌트 tick 과 draw, 위젯 콜백, 페이지 이벤트 리스너, async 작업 안. 씬 함수가 받은 engine 인자와 같은 엔진이다.
- 엔진의 공개 함수는 모두 &self 다. (고치는 칸은 안쪽 가변성) 매니저의 get_x_mut 으로 받은 것을 쥔 채 같은 매니저를 또 빌리면 함수 이름을 적은 패닉으로 멈춘다.
- 엔진을 만든 스레드가 아닌 스레드에서 부르면 Err(OtherThread), 엔진을 만든 적이 없으면 Err(NotCreated) 다.
The global engine. (the original static Engine.getEngine(), the last created engine)
- The engine is created once and never removed. Engine::new puts it in a place that lives until the program ends, so this gives &'static Engine. (the same form as Unreal's GEngine and Godot's Engine singleton)
- It is taken anywhere right after Engine::new: scene functions (load, tick, draw and so on), component tick and draw, widget callbacks, page event listeners, inside async tasks. It is the same engine as the engine argument a scene function receives.
- All public engine functions are &self. (the fields they change use interior mutability) Borrowing the same manager again while holding what a manager's get_x_mut gave stops with a panic that names the function.
- Called from a thread other than the one that created the engine it is Err(OtherThread), and if no engine was ever created it is Err(NotCreated).
반환ReturnsResult<&'static crate::core::engine::Engine, crate::core::globalengine::EngineAccessError> 꺼낸 엔진, 못 꺼내면 그 까닭.The taken engine, or the reason it could not be taken.
짝Counterpart: vanilla.js Engine.getEngine
use vanilla::{Component, ComponentBase, ComponentContext, Engine, EngineConfiguration, NodeTree};
fn read_frame_number() -> u64 {
let engine = Engine::get_engine().unwrap();
engine.get_frame_number()
}
struct FrameReader {
component_base: ComponentBase,
frame_number: u64,
}
#[vanilla::reflect]
impl FrameReader {}
#[vanilla::reflect]
impl Component for FrameReader {
fn tick(&mut self, _context: &mut ComponentContext, _time_delta: f64) {
self.frame_number = read_frame_number();
}
}
let engine = Engine::new(EngineConfiguration::new());
assert!(std::ptr::eq(Engine::get_engine().unwrap(), engine));
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let reader_id = node_tree.create_child(root_id, "reader");
node_tree[reader_id].add_component(FrameReader {
component_base: ComponentBase::new(),
frame_number: 0,
});
node_tree.tick(engine, 0.016);
let frame_number = node_tree[reader_id].get_component::<FrameReader>().unwrap().frame_number;
assert_eq!(frame_number, engine.get_frame_number());개발자 도구로 노드 검사하기 부탁. (크롬 문맥 메뉴의 검사 자리. 그 노드를 가진 씬의 DevTools 가 다음 tick 에 열고 고른다)
Requests inspecting a node with the developer tools. (in place of Inspect in Chrome's context menu. The DevTools of the scene holding the node opens and selects it on the next tick)
- node_idcrate::core::node::nodetree::NodeId
- 검사할 노드. (앞서 부탁한 노드는 바꾼다)Node to inspect. (replaces a previously requested node)
알림 창. (window.alert 자리, 원본 engine.alert 와 같다, 확인만 있다. 손잡이는 확인하면 끝난다)
- 엔진이 그린 창을 띄우고, 닫힐 때까지 씬을 갱신하지 않는다. (웹과 데스크탑 같다, core/modaldialog.rs)
Alert dialog. (in place of window.alert, the same as the original engine.alert, only OK. The handle finishes when confirmed)
- Shows a dialog drawn by the engine and does not update the scene until it closes. (the same on the web and the desktop, core/modaldialog.rs)
- message&str
- 창에 보일 글.Text to show in the dialog.
반환ReturnsModalDialogHandle 질문 창 손잡이. (확인하면 끝난다)Question dialog handle. (finishes when confirmed)
짝Counterpart: vanilla.js Engine.alert
확인 창. (window.confirm 자리, 원본 engine.confirm 과 같다, 손잡이의 is_confirmed 가 원본 Promise 의 값)
Confirm dialog. (in place of window.confirm, the same as the original engine.confirm, the handle's is_confirmed is the value of the original Promise)
- message&str
- 창에 보일 글.Text to show in the dialog.
반환ReturnsModalDialogHandle 질문 창 손잡이. (확인이나 취소로 답하면 끝난다)Question dialog handle. (finishes when answered with OK or Cancel)
짝Counterpart: vanilla.js Engine.confirm
입력 창. (window.prompt(message, default) 자리, 원본 engine.prompt 와 같다, 손잡이의 get_prompt_text 가 원본 Promise 의 값, 취소는 None)
Prompt dialog. (in place of window.prompt(message, default), the same as the original engine.prompt, the handle's get_prompt_text is the value of the original Promise, None when cancelled)
- message&str
- 창에 보일 글.Text to show in the dialog.
- default_value&str
- 입력 칸에 처음 넣어 둘 글. (모두 고른 채로 초점을 받는다)Text to put in the input field at first. (it receives focus with everything selected)
반환ReturnsModalDialogHandle 질문 창 손잡이. (확인이나 취소로 답하면 끝난다)Question dialog handle. (finishes when answered with OK or Cancel)
짝Counterpart: vanilla.js Engine.prompt
알림 창을 띄우고 닫힐 때 풀리는 Promise. (원본 engine.alertAsync)
A Promise that resolves when the alert dialog shown closes. (the original engine.alertAsync)
- message&str
- 창에 보일 글.Text to show in the dialog.
반환ReturnsPromise<()> 창이 닫히면 풀리는 Promise.Promise that resolves when the dialog closes.
짝Counterpart: vanilla.js Engine.alertAsync
확인 창을 띄우고 답하면 풀리는 Promise. (원본 engine.confirmAsync)
A Promise that resolves when the confirm dialog shown is answered. (the original engine.confirmAsync)
- message&str
- 창에 보일 글.Text to show in the dialog.
반환ReturnsPromise<bool> 답하면 풀리는 Promise. (확인이면 true, 취소면 false)Promise that resolves when answered. (true for OK, false for Cancel)
짝Counterpart: vanilla.js Engine.confirmAsync
use vanilla::Engine;
fn ask_exit(engine: &Engine) {
engine.spawn_task(|mut engine_context| async move {
let is_confirmed = engine_context.with(|engine| engine.confirm_async("Exit?")).await;
if is_confirmed {
engine_context.with(|engine| engine.exit_application());
}
});
}입력 창을 띄우고 답하면 풀리는 Promise. (원본 engine.promptAsync, 취소는 원본 null 자리의 None)
A Promise that resolves when the prompt dialog shown is answered. (the original engine.promptAsync, None in place of the original null when cancelled)
- message&str
- 창에 보일 글.Text to show in the dialog.
- default_value&str
- 입력 칸에 처음 넣어 둘 글.Text to put in the input field initially.
반환ReturnsPromise<Option<String>> 답하면 풀리는 Promise. (확인이면 입력한 글, 취소면 None)Promise that resolves when answered. (the entered text for OK, None for Cancel)
짝Counterpart: vanilla.js Engine.promptAsync
질문 창이 떠 있는지. (떠 있는 동안 엔진은 씬을 갱신하지 않는다)
Whether a question dialog is open. (the engine does not update the scene while it is open)
반환Returnsbool 떠 있거나 기다리는 질문 창이 있으면 true.true if a question dialog is open or waiting.
짝Counterpart: vanilla.js Engine.isModalDialogOpen
시작.
- 데스크탑: 창을 닫거나 exit_application 을 부를 때까지 돌아오지 않는다.
- 웹: 캔버스와 WebGL2 를 잡고 request_animation_frame 을 걸어 둔 뒤 바로 돌아온다.
Start.
- Desktop: does not return until the window is closed or exit_application is called.
- Web: grabs the canvas and WebGL2, registers request_animation_frame, and returns right away.
- sceneBox<dyn Scene>
- 첫 씬. (load_scene 으로 불러온다)First scene. (loaded with load_scene)
반환ReturnsResult<(), String> 정상으로 끝나면 Ok. (데스크탑은 창이 닫혀 이벤트 루프가 끝날 때, 웹은 프레임을 걸어 둔 뒤 바로) 이벤트 루프나 창, GL 컨텍스트를 만들지 못하는 등 플랫폼이 실패하면 Err(까닭).Ok on normal exit. (on desktop when the window closes and the event loop ends, on the web right after registering the frame) Err(reason) if the platform fails, such as being unable to create the event loop, window or GL context.
짝Counterpart: vanilla.js Engine.run
씬 불러오기. (이번 프레임이 끝난 뒤 목록에 더한다. unload_scene 에 넘길 핸들을 돌려준다)
- 목록에 더할 때 create 를 부르고 루트를 뷰 크기로 맞춘 뒤 load 를 부른다. 맡긴 애셋과 작업이 다 끝나고 0.3 초 뒤 initialize 를 부른다.
Loads a scene. (added to the list after the current frame ends. Returns the handle to pass to unload_scene)
- When added to the list, create is called, the root is fitted to the view size, and then load is called. initialize is called 0.3 seconds after the tracked assets and tasks have all finished.
- sceneBox<dyn Scene>
- 불러올 씬. (엔진이 소유한다)Scene to load. (owned by the engine)
반환ReturnsSceneId 그 씬의 핸들. (1 부터 매긴다)Handle of the scene. (numbered from 1)
짝Counterpart: vanilla.js Engine.loadScene
씬 하나 내리기. (이번 프레임이 끝난 뒤 finalize, unload 를 부르고, unload 가 맡긴 작업이 끝나면 목록에서 뺀다. 없는 핸들이면 아무것도 하지 않는다)
- 핸들(SceneId)이나 원본처럼 씬(씬 공통 상태 &SceneBase)을 받는다.
- 그 씬의 작업이 남았으면 다 끝날 때까지 씬 값을 살려 두고, 다 끝나면 destroy 를 부르고 버린다.
Unloads one scene. (after the current frame ends, calls finalize and unload, and removes it from the list when the tasks tracked by unload finish. Does nothing for an unknown handle)
- Takes a handle (SceneId) or, as in the original, a scene (the common scene state &SceneBase).
- If the scene still has tasks, the scene value is kept alive until they all finish, then destroy is called and it is dropped.
- sceneimpl Into<SceneId>
- 내릴 씬의 핸들(SceneId)이나 씬 공통 상태(&SceneBase).Handle (SceneId) or common scene state (&SceneBase) of the scene to unload.
짝Counterpart: vanilla.js Engine.unloadScene
use vanilla::{Engine, Scene, SceneBase, Vector2};
struct PopupScene {
scene_base: SceneBase,
}
impl Scene for PopupScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
fn touch_release(&mut self, _view_input_position: Vector2) {
let engine = Engine::get_engine().unwrap();
engine.unload_scene(&self.scene_base);
}
}모든 씬 내리기. (이번 프레임이 끝난 뒤, load_scene 과 같이 부르면 내린 다음 불러온다)
Unloads all scenes. (after the current frame ends, if called together with load_scene, unloads and then loads)
짝Counterpart: vanilla.js Engine.unloadAllScenes
씬 불러오기. (원본 await SceneManager.loadScene(scene), initialize 까지 끝나면 그 씬의 핸들로 풀리는 Promise 를 돌려준다)
- 불러오기는 load_scene 과 같다. 같은 프레임에 create 전에 그 씬을 내리면 풀리지 않는다. (create 뒤에 내리면 initialize 까지 마치고 풀린다)
Loads a scene. (the original await SceneManager.loadScene(scene), returns a Promise that resolves with the scene's handle once initialize finishes)
- Loading is the same as load_scene. If the scene is unloaded before create in the same frame, it does not resolve. (if unloaded after create, it resolves after finishing initialize)
- sceneBox<dyn Scene>
- 불러올 씬. (엔진이 소유한다)Scene to load. (owned by the engine)
반환ReturnsPromise<SceneId> initialize 가 끝나면 그 씬의 핸들로 풀리는 Promise.Promise that resolves with the scene's handle once initialize finishes.
짝Counterpart: vanilla.js Engine.loadScene
use vanilla::{Engine, Scene, SceneId};
fn change_scene(engine: &Engine, current_scene_id: SceneId, next_scene: Box<dyn Scene>) {
engine.spawn_task(move |mut engine_context| async move {
let next_scene_id = engine_context.with(|engine| engine.load_scene_async(next_scene)).await;
engine_context.with(|engine| engine.unload_scene_async(current_scene_id)).await;
println!("{:?}", next_scene_id);
});
}씬 하나 내리기. (원본 await SceneManager.unloadScene(scene), 내리기가 끝나면 풀리는 Promise 를 돌려준다. 없는 핸들이어도 풀린다)
- 이번 프레임 끝에 finalize, unload 를 부르고, unload 가 track_task 로 맡긴 작업까지 끝나면 목록에서 뺀 뒤 푼다.
Unloads one scene. (the original await SceneManager.unloadScene(scene), returns a Promise that resolves when unloading finishes. Resolves even for an unknown handle)
- Calls finalize and unload at the end of the current frame, and resolves after removing it from the list once the tasks unload tracked with track_task have also finished.
- sceneimpl Into<SceneId>
- 내릴 씬의 핸들(SceneId)이나 씬 공통 상태(&SceneBase).Handle (SceneId) or common scene state (&SceneBase) of the scene to unload.
반환ReturnsPromise<()> 내리기가 끝나면 풀리는 Promise.Promise that resolves when unloading finishes.
짝Counterpart: vanilla.js Engine.unloadScene
모든 씬 내리기. (원본 await SceneManager.unloadAllScenes(), 그때의 모든 씬의 내리기가 끝나면 풀리는 Promise 를 돌려준다)
Unloads all scenes. (the original await SceneManager.unloadAllScenes(), returns a Promise that resolves when all scenes at that time have finished unloading)
반환ReturnsPromise<()> 그때 불러와 있던 모든 씬의 내리기가 끝나면 풀리는 Promise.Promise that resolves when all scenes loaded at that time have finished unloading.
짝Counterpart: vanilla.js Engine.unloadAllScenes
pub fn spawn_task<F, TaskFuture>(&self, task_function: F) -> TaskHandle where F: FnOnce(EngineContext) -> TaskFuture, TaskFuture: Future<Output = ()> + 'static,#엔진 작업 맡기기. (씬과 따로 사는 async 작업, 작업 함수가 받은 EngineContext 의 with 안에서 엔진을 빌린다)
- 원본 async 함수를 부를 때처럼 이 자리에서 첫 await 까지 돌고, 남은 것은 깨어날 때마다 프레임의 폴링 차례에 돈다.
- 돌려준 손잡이로 끝났는지 묻거나 await 한다.
Spawns an engine task. (an async task living apart from scenes, borrows the engine inside the with of the EngineContext the task function receives)
- Like calling an original async function, runs here up to the first await, and the rest runs in the frame's polling turn each time it is woken.
- Use the returned handle to ask whether it finished, or await it.
- task_functionF
- EngineContext 를 받아 퓨처를 돌려주는 함수. (보통
|mut engine_context| async move { ... }, 퓨처는 Send 가 아니어도 된다)Function that takes an EngineContext and returns a future. (usually|mut engine_context| async move { ... }, the future need not be Send)
반환ReturnsTaskHandle 작업 손잡이. (첫 구간에서 끝났으면 이미 끝난 손잡이)Task handle. (an already finished handle if it finished in the first segment)
use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
let task_handle = engine.spawn_task(|mut engine_context| async move {
engine_context.with(|engine| {
engine.set_maximum_frame_per_second(30.0);
});
});
assert!(task_handle.is_finished());
assert_eq!(engine.get_maximum_frame_per_second(), 30.0);pub fn spawn_scene_task<S, F, TaskFuture>(&self, scene: &mut S, task_function: F) -> TaskHandle where S: Scene + 'static, F: FnOnce(SceneContext<S>) -> TaskFuture, TaskFuture: Future<Output = ()> + 'static,#씬 작업 맡기기. (그 씬의 async 작업, 작업 함수가 받은 SceneContext 의 with 안에서 그 씬(S 타입)과 엔진을 빌린다)
- 원본 async 함수 안에서 this 를 쓰는 자리다. 원본처럼 이 자리에서 첫 await 까지 돌고, 남은 것은 깨어날 때마다 프레임의 폴링 차례에 돈다. (첫 구간의 with_graphic 도 엔진의 그래픽을 준다. 그리기 함수 안에서 맡기면 그 함수가 인자로 그래픽을 쥐고 있어 None 이다)
- 씬을 내려도 원본처럼 이어 돈다. (씬 값은 작업이 다 끝날 때까지 산다) load_scene 전의 씬이면 첫 구간만 돌고 버린다.
- 불러오기 작업이면 load 에서 씬의 track_task 로 맡겨 끝날 때까지 initialize 를 미룬다. (unload 에서 맡기면 내리기 끝을 미룬다)
Spawns a scene task. (an async task of that scene, borrows the scene (type S) and the engine inside the with of the SceneContext the task function receives)
- This is where an original async function uses this. As in the original, runs here up to the first await, and the rest runs in the frame's polling turn each time it is woken. (with_graphic in the first segment also gives the engine's graphic. Spawned inside a drawing function, it is None because that function holds the graphic as its argument)
- It keeps running even if the scene is unloaded, as in the original. (the scene value lives until the task finishes) For a scene before load_scene, only the first segment runs and it is dropped.
- For a loading task, track it with the scene's track_task in load to delay initialize until it finishes. (tracking it in unload delays the end of unloading)
- scene&mut S
- 작업을 맡기는 씬. (보통 훅 안의 self)Scene spawning the task. (usually self inside a hook)
- task_functionF
SceneContext<S>를 받아 퓨처를 돌려주는 함수. (보통|mut scene_context| async move { ... })Function that takes aSceneContext<S>and returns a future. (usually|mut scene_context| async move { ... })
반환ReturnsTaskHandle 작업 손잡이. (track_task 에 넘기거나 await 한다)Task handle. (pass it to track_task or await it)
use vanilla::{Engine, Scene, SceneBase, SceneContext};
struct StageScene {
scene_base: SceneBase,
stage_bytes: Vec<u8>,
}
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"));
let stage_bytes = load_handle.await.map(|bytes| bytes.to_vec()).unwrap_or_default();
scene_context.with(|scene, _engine| {
scene.stage_bytes = stage_bytes;
});
});
self.scene_base.track_task(&task_handle);
}
}pub fn spawn_deferred_task<F, TaskFuture>(&self, task_function: F) -> TaskHandle where F: FnOnce(EngineContext) -> TaskFuture, TaskFuture: Future<Output = ()> + 'static,#엔진 작업을 다음 폴링 차례로 맡기기. (&Engine 만 있는 자리, 컴포넌트 문맥처럼. 다음 프레임의 폴링 차례에 처음 돈다)
Spawns an engine task for the next polling turn. (for places with only &Engine, like a component context. First runs in the next frame's polling turn)
- task_functionF
- EngineContext 를 받아 퓨처를 돌려주는 함수.Function that takes an EngineContext and returns a future.
반환ReturnsTaskHandle 작업 손잡이. (다음 폴링 차례 전에는 끝나지 않은 손잡이)Task handle. (a handle that is not finished before the next polling turn)
use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
let task_handle = engine.spawn_deferred_task(|_engine_context| async move {});
assert!(!task_handle.is_finished());pub fn spawn_deferred_scene_task<S, F, TaskFuture>(&self, scene: &S, task_function: F) -> TaskHandle where S: Scene + 'static, F: FnOnce(SceneContext<S>) -> TaskFuture, TaskFuture: Future<Output = ()> + 'static,#씬 작업을 다음 폴링 차례로 맡기기. (&Engine 과 &씬만 있는 자리, 다음 프레임의 폴링 차례에 처음 돈다)
- 그 씬이 다음 폴링 차례에 불러온 씬 목록에도 살려 둔 씬 목록에도 없으면 작업을 버린다.
Spawns a scene task for the next polling turn. (for places with only &Engine and &scene, first runs in the next frame's polling turn)
- If the scene is in neither the loaded scene list nor the kept-alive scene list at the next polling turn, the task is dropped.
- scene&S
- 작업을 맡기는 씬.Scene spawning the task.
- task_functionF
SceneContext<S>를 받아 퓨처를 돌려주는 함수.Function that takes aSceneContext<S>and returns a future.
반환ReturnsTaskHandle 작업 손잡이. (다음 폴링 차례 전에는 끝나지 않은 손잡이)Task handle. (a handle that is not finished before the next polling turn)
불러온 모든 씬의 핸들. (원본 SceneManager.getAllLoadedScenes, 불러온 차례, 로딩 중인 씬도 든다)
- 원본은 씬 객체를 돌려준다. 러스트 판은 씬마다 &Engine 을 받아 도는 동안 다른 씬을 빌릴 수 없어서 핸들을 돌려준다. load_scene 한 프레임이 끝나 create 가 불린 씬부터 들고, 내린 씬은 빠진다.
Handles of all loaded scenes. (the original SceneManager.getAllLoadedScenes, in load order, scenes still loading included)
- The original returns scene objects. The Rust version returns handles because while each scene runs with &Engine, other scenes cannot be borrowed. Scenes are included from when the load_scene frame ends and create is called, and unloaded scenes are removed.
반환ReturnsRef<'_, [SceneId]> 불러온 씬의 핸들 목록. (불러온 차례)List of handles of loaded scenes. (in load order)
짝Counterpart: vanilla.js Engine.getAllLoadedScenes
애셋 경로 찾기. (설정의 애셋 폴더 후보에서 처음 있는 것, 없으면 첫 후보 기준)
Finds an asset path. (the first existing one among the configured asset folder candidates, relative to the first candidate if none)
- relative_path&str
- 애셋 폴더 기준 상대 경로.Path relative to the asset folder.
반환ReturnsPathBuf 파일이 있는 첫 후보 폴더의 경로. (어디에도 없으면 첫 후보 기준 경로, 후보가 없으면 상대 경로 그대로)Path in the first candidate folder that has the file. (the path relative to the first candidate if found nowhere, the relative path as is if there are no candidates)
이미지 애셋 읽기. (원본 new ImageAsset() + load(path), 데스크탑은 그 자리에서 읽는다)
- "data:" 주소도 받는다. (주소의 형으로 푼다)
- 웹은 그 자리에서 읽고 풀 수 없어 늘 Err 다. (원본처럼 브라우저가 비동기로 푼다, ImageAsset::load 나 AssetLoader 를 쓴다)
Loads an image asset. (the original new ImageAsset() + load(path); desktop loads it on the spot)
- Also accepts "data:" URLs. (decoded by the URL's type)
- On the web it is always Err, since it cannot load and decode on the spot. (as in the original, the browser decodes asynchronously; use ImageAsset::load or AssetLoader)
- relative_path&str
- 애셋 폴더 기준 상대 경로나 "data:" 주소.Path relative to the asset folder, or a "data:" URL.
반환ReturnsResult<Rc<Image>, String> 읽은 이미지. 파일을 못 읽거나 풀지 못하면 Err(까닭).The loaded image. Err(reason) if the file cannot be read or decoded.
use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
let image = engine.load_image("examples/assets/atlas/icons.png").unwrap();
assert!(image.get_width() > 0);
assert!(engine.load_image("examples/assets/missing.png").is_err());애셋 바이트 부탁. (애셋들의 load 가 부른다)
- 데스크탑: 애셋 폴더 후보에서 파일을 찾아 그 자리에서 읽고 끝낸다.
- 웹: asset_base_url + 상대 경로를 fetch 하고, 받으면 끝낸다. (그 사이 프레임은 계속 돈다)
- "data:" 주소는 원본 fetch 처럼 주소 그대로 푼다. (데스크탑은 그 자리에서 base/dataurl.rs 로 풀고 형을 응답 형으로 둔다, 웹은 기준 주소를 붙이지 않고 fetch)
Requests asset bytes. (called by the assets' load)
- Desktop: finds the file among the asset folder candidates, reads it on the spot and finishes.
- Web: fetches asset_base_url + the relative path and finishes when received. (frames keep running meanwhile)
- "data:" URLs are decoded from the URL itself like the original fetch. (desktop decodes it on the spot with base/dataurl.rs and uses its type as the response type, the web fetches without prefixing the base URL)
- relative_path&str
- 애셋 폴더 기준 상대 경로나 "data:" 주소.Path relative to the asset folder, or a "data:" URL.
반환ReturnsAssetLoadHandle 읽기 손잡이. (읽히면 바이트, 실패하면 까닭을 든다. await 할 수 있다)Load handle. (holds the bytes when loaded, the reason on failure. Can be awaited)
use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
let load_handle = engine.request_asset_bytes("examples/assets/atlas/icons.json");
assert!(load_handle.is_loaded());
let data_load_handle = engine.request_asset_bytes("data:text/plain,hello");
assert_eq!(data_load_handle.get_bytes().unwrap().as_slice(), b"hello");
assert!(engine.request_asset_bytes("examples/assets/missing.json").is_failed());pub fn request_asset_bytes_with_cache(&self, relative_path: &str, is_no_cache: bool) -> AssetLoadHandle#애셋 바이트 부탁. (is_no_cache 면 웹은 브라우저 캐시를 쓰지 않고 다시 확인한다, 원본 TextAsset.setNoCache)
Requests asset bytes. (with is_no_cache, the web skips the browser cache and checks again, the original TextAsset.setNoCache)
- relative_path&str
- 애셋 폴더 기준 상대 경로나 "data:" 주소.Path relative to the asset folder, or a "data:" URL.
- is_no_cachebool
- true 면 웹은 브라우저 캐시를 쓰지 않는다. (데스크탑은 늘 파일을 읽어 상관없다)If true, the web does not use the browser cache. (desktop always reads the file, so it does not matter)
반환ReturnsAssetLoadHandle 읽기 손잡이.Load handle.
pub fn request_asset_bytes_into(&self, relative_path: &str, load_handle: &AssetLoadHandle)#애셋 바이트 부탁. (이미 만든 읽기 손잡이를 끝낸다. AssetLoader 가 미리 나눠 준 손잡이를 차례가 오면 채울 때 쓴다)
Requests asset bytes. (finishes an already created load handle. Used by AssetLoader to fill handles it handed out in advance when their turn comes)
- relative_path&str
- 애셋 폴더 기준 상대 경로나 "data:" 주소.Path relative to the asset folder, or a "data:" URL.
- load_handle&AssetLoadHandle
- 끝낼 읽기 손잡이. (AssetLoadHandle::create_pending 으로 만든 것)Load handle to finish. (created with AssetLoadHandle::create_pending)
use vanilla::{AssetLoadHandle, Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
let load_handle = AssetLoadHandle::create_pending("examples/assets/atlas/icons.json");
assert!(!load_handle.is_finished());
engine.request_asset_bytes_into("examples/assets/atlas/icons.json", &load_handle);
assert!(load_handle.is_loaded());pub fn register_font_when_loaded(&self, family: &str, is_bold: bool, load_handle: AssetLoadHandle) -> FontLoadHandle#글꼴 바이트가 오면 이름으로 등록해 달라고 맡기기. (FontAsset 이 부른다. 등록은 프레임 시작에 한다, 올리면 끝나는 손잡이를 돌려준다)
Asks to register font bytes under a name when they arrive. (called by FontAsset. Registration happens at frame start, returns a handle that finishes when loaded)
- family&str
- 글꼴 이름. (글자를 그릴 때 쓰는 이름)Font name. (the name used when drawing text)
- is_boldbool
- true 면 굵기 700 얼굴, false 면 400 얼굴로 올린다.If true, loads it as the weight 700 face, if false as the 400 face.
- load_handleAssetLoadHandle
- 글꼴 파일 바이트의 읽기 손잡이.Load handle of the font file bytes.
반환ReturnsFontLoadHandle 글꼴 목록에 올리면(또는 받기나 올리기에 실패하면) 끝나는 손잡이.Handle that finishes when added to the font list (or when downloading or adding fails).
pub fn register_font_face_when_loaded(&self, family: &str, mut font_face_descriptors: FontFaceDescriptors, load_handle: AssetLoadHandle) -> FontLoadHandle#글꼴 얼굴 바이트가 오면 서술자(굵기, 기울기, 글자 범위)대로 이름 아래에 올려 달라고 맡기기. (원본 new FontFace(family, url, descriptors) + document.fonts.add)
- 서술자의 source_key 가 비었으면 읽기 손잡이의 경로를 쓴다.
- 돌려준 손잡이는 글꼴 목록에 올리면(또는 받기나 올리기에 실패하면) 끝난다. (원본 await fontFace.load() 와 document.fonts.add 자리)
Asks to add font face bytes under a name with the descriptors (weight, style, character range) when they arrive. (the original new FontFace(family, url, descriptors) + document.fonts.add)
- If the descriptors' source_key is empty, the load handle's path is used.
- The returned handle finishes when added to the font list (or when downloading or adding fails). (in place of the original await fontFace.load() and document.fonts.add)
- family&str
- 글꼴 이름.Font name.
- font_face_descriptorsFontFaceDescriptors
- 굵기, 기울기, 글자 범위, 얼굴 열쇠. (열쇠가 비었으면 읽기 손잡이의 경로)Weight, style, character range, face key. (the load handle's path if the key is empty)
- load_handleAssetLoadHandle
- 글꼴 파일 바이트의 읽기 손잡이.Load handle of the font file bytes.
반환ReturnsFontLoadHandle 글꼴 목록에 올리면(또는 받기나 올리기에 실패하면) 끝나는 손잡이.Handle that finishes when added to the font list (or when downloading or adding fails).
글꼴 얼굴 지우기 맡기기. (원본 document.fonts.delete, 열쇠는 등록할 때의 source_key 또는 경로)
- 아직 바이트를 기다리는 같은 얼굴의 등록은 바로 뺀다. (이름은 대소문자를 가리지 않는다) 지우기는 다음 프레임 시작에 한다.
Asks to remove a font face. (the original document.fonts.delete, the key is the source_key at registration or the path)
- Registrations of the same face still waiting for bytes are removed immediately. (names are case-insensitive) Removal happens at the start of the next frame.
- family&str
- 글꼴 이름.Font name.
- source_key&str
- 지울 얼굴의 열쇠.Key of the face to remove.
한 이름의 얼굴 차례 정하기 맡기기. (얼굴 열쇠 목록, 뒤가 먼저 그린다, TextStringTextureCache.set_font_face_order)
Asks to set the face order for a name. (a list of face keys, later ones draw first, TextStringTextureCache.set_font_face_order)
- family&str
- 글꼴 이름.Font name.
- source_key_listVec<String>
- 얼굴 열쇠 목록. (뒤의 얼굴이 먼저 그린다, 다음 프레임 시작에 건다)List of face keys. (later faces draw first, applied at the start of the next frame)
구운 글자 모두 버리기 맡기기. (원본 textStringTextureCache.clear, 다음 프레임 시작에)
Asks to discard all baked text. (the original textStringTextureCache.clear, at the start of the next frame)
아직 바이트가 오지 않은 글꼴 얼굴 수. (UI 글꼴이 기다릴 때 본다)
Number of font faces whose bytes have not arrived yet. (checked while UI fonts are waiting)
반환Returnsusize 등록을 기다리는 글꼴 얼굴 수. (바이트를 기다리는 것과 다음 프레임 시작에 올릴 것)Number of font faces waiting for registration. (those waiting for bytes and those to be added at the start of the next frame)
오디오 애셋 읽기. (원본 new AudioAsset() + load(path), 애셋 폴더 기준 경로나 "data:" 주소)
- 데스크탑: 그 자리에서 읽고 디코딩한다. 실패하면 Err. data: 주소는 형을 보지 않고 바이트를 내용으로 가려 푼다. (원본 decodeAudioData 와 같다)
- 웹: fetch 와 디코딩을 걸어 두고 바로 애셋을 돌려준다. 끝나면 is_loaded() 가 참이 된다. (실패는 get_load_error())
Loads an audio asset. (the original new AudioAsset() + load(path), a path relative to the asset folder or a "data:" URL)
- Desktop: reads and decodes on the spot. Err on failure. A data: URL is decoded by sniffing the bytes as content without looking at the type. (same as the original decodeAudioData)
- Web: starts fetching and decoding and returns the asset right away. When done, is_loaded() becomes true. (failure in get_load_error())
- relative_path&str
- 애셋 폴더 기준 상대 경로나 "data:" 주소.Path relative to the asset folder, or a "data:" URL.
반환ReturnsResult<Rc<AudioAsset>, String> 오디오 애셋. 데스크탑은 읽기나 디코딩에 실패하면 Err(까닭). (웹은 그 자리에서 실패한 것만 Err)Audio asset. On desktop, Err(reason) if reading or decoding fails. (on the web only failures on the spot are Err)
use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
let audio_asset = engine.load_audio_asset("tests/assets/audio/wav_s16_stereo.wav").unwrap();
assert!(audio_asset.is_loaded());
assert!(audio_asset.get_duration() > 0.0);
assert!(engine.load_audio_asset("tests/assets/audio/missing.wav").is_err());오디오 애셋 경로 풀기. (데스크탑은 애셋 폴더 후보에서 찾은 경로, 웹은 asset_base_url + 상대 경로, 웹의 data: 주소는 그대로)
Resolves an audio asset path. (desktop: the path found among the asset folder candidates, web: asset_base_url + the relative path, data: URLs on the web as is)
- relative_path&str
- 애셋 폴더 기준 상대 경로.Path relative to the asset folder.
반환ReturnsPathBuf 읽을 경로. (웹은 주소를 경로 꼴에 담는다)Path to load. (the web holds the URL in path form)
오디오 컨텍스트 재개. (focus, visibilitychange 같은 user gesture 가 아닌 복귀. gesture 전이면 아무것도 하지 않는다)
Resumes the audio context. (for returns that are not user gestures, such as focus and visibilitychange. Does nothing before a gesture)
짝Counterpart: vanilla.js Engine.resume
user gesture (click / touch / keydown) 핸들러. AudioManager 에 user gesture 발생을 알리고 컨텍스트 재개를 시도한다.
User gesture (click / touch / keydown) handler. Notifies AudioManager that a user gesture occurred and tries to resume the context.
짝Counterpart: vanilla.js Engine.resumeOnUserGesture
종료 요청. (원본 exitApplication, 데스크탑은 이번 프레임 뒤 창을 닫고, 웹은 원본처럼 Capacitor App.exitApp 이나 window.close 를 시도하고 프레임을 멈춘다)
Requests exit. (the original exitApplication, desktop closes the window after the current frame, the web tries Capacitor App.exitApp or window.close as in the original and stops the frames)
짝Counterpart: vanilla.js Engine.exitApplication
바깥 주소 열기. (원본 Engine.openUrl)
- 웹은 window.open(주소, "_blank", "noopener") 로 새 탭에 연다. 사용자 입력(누름, 탭, 키) 처리 안에서 부를 때만 열린다. 브라우저의 팝업 차단 규칙이다. 입력과 상관없이(타이머, 프레임) 부르면 막혀 열리지 않는다.
- 데스크탑은 운영체제의 기본 프로그램으로 연다. (맥
open, 윈도우 ShellExecuteW, 리눅스 xdg-open) - 열 수 있는 것은 http, https, mailto, tel 뿐이다. 그 밖의 꼴(javascript:, file: 같은)은 열지 않고 false.
Opens an outside URL. (original Engine.openUrl)
- On the web it opens a new tab with window.open(url, "_blank", "noopener"). It opens only when called inside user input (click, tap, key) handling. This is the browser's popup-blocking rule. Called regardless of input (timer, frame), it is blocked and does not open.
- On desktop it opens with the OS default program. (macOS
open, Windows ShellExecuteW, Linux xdg-open) - Only http, https, mailto and tel can be opened. Other forms (such as javascript: and file:) are not opened and return false.
- url&str
- 열 주소. (http, https, mailto, tel)URL to open. (http, https, mailto, tel)
반환Returnsbool 열기를 운영체제나 브라우저에 넘겼으면 true. (주소가 맞지 않거나 넘기지 못하면 false)True if the open was handed to the OS or browser. (false if the URL is not allowed or could not be handed over)
짝Counterpart: vanilla.js Engine.openUrl
use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
assert!(!engine.open_url("javascript:alert(1)"));
assert!(!engine.open_url("file:///etc/passwd"));현지 시각 읽기. (원본 Engine.readLocalTime, 지금에서 분 오프셋만큼 더한 때를 이 기계의 시간대로 본 달력 시각)
- 웹은 Date, 맥과 리눅스는 localtime_r, 윈도우는 SystemTimeToTzSpecificLocalTime 이다. 더한 때의 일광 절약 시간까지 반영한다.
Read the local time. (same as the original Engine.readLocalTime, the calendar time of now plus a minute offset in this machine's time zone)
- On the web it reads with Date, on Mac and Linux with localtime_r, and on Windows with SystemTimeToTzSpecificLocalTime. Daylight saving time at the shifted moment is applied. (same as the original's new Date(Date.now() + offset))
- minute_offsetf64
- 지금에 더할 분. (음수는 과거, 0 이면 지금)Minutes to add to now. (negative is the past, 0 is now)
반환Returnsplatform::LocalTime 현지 시각. (해, 달 1 에서 12, 날, 시, 분, 초, 요일 0 이 일요일)Local time. (year, month 1 to 12, day, hour, minute, second, weekday with 0 as Sunday)
짝Counterpart: vanilla.js Engine.readLocalTime
use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
let now = engine.read_local_time(0.0);
assert!(now.hour < 24 && now.minute < 60 && (1..=12).contains(&now.month));
let later = engine.read_local_time(120.0);
let earlier = engine.read_local_time(-120.0);
assert_ne!((later.day, later.hour), (earlier.day, earlier.hour));종료 요청 여부.
Whether exit was requested.
반환Returnsbool exit_application 을 불렀으면 true.true if exit_application was called.
짝Counterpart: vanilla.js Engine.isExitRequested
커서 보이기 설정.
Sets cursor visibility.
- is_visiblebool
- false 면 창이나 캔버스 위에서 마우스 커서를 숨긴다. (플랫폼이 붙이기 전에는 아무것도 하지 않는다)If false, hides the mouse cursor over the window or canvas. (does nothing before the platform attaches)
짝Counterpart: vanilla.js Engine.setVisibleCursor
해상도 다시 맞추기. (원본 resize, 설정을 바꾼 뒤 부르면 플랫폼이 다음 프레임 첫머리에 캔버스와 뷰 영역을 다시 셈하고 씬마다 resize 를 부른다)
Refits the resolution. (the original resize, calling it after changing settings makes the platform recompute the canvas and view area at the start of the next frame and call resize on each scene)
짝Counterpart: vanilla.js Engine.resize
캔버스. (원본 getCanvas, 웹은 그리는 캔버스 요소, 데스크탑은 창, 플랫폼이 붙이기 전에는 None)
Canvas. (the original getCanvas, the canvas element being drawn on the web, the window on desktop, None before the platform attaches)
반환ReturnsOption<Ref<'_, PlatformWindow>> 플랫폼 창 손잡이. (데스크탑 주 스레드는 Engine::new 가 숨긴 채 지은 창, 그 밖에는 run 이 창이나 캔버스를 잡기 전에는 None)Platform window handle. (On the desktop main thread the window Engine::new built hidden; elsewhere None until run takes the window or canvas)
짝Counterpart: vanilla.js Engine.getCanvas
GPU 메모리 셈 켜기. (원본 Engine.enableGpuMemoryTracking, 개발용)
- 켠 뒤에 지은 텍스처, 렌더버퍼, 버퍼부터 센다. 이미 켰으면 아무것도 하지 않는다. 처음부터 세려면 EngineConfiguration::track_gpu_memory.
Turns GPU memory tracking on. (original Engine.enableGpuMemoryTracking, for development)
- Counts the textures, renderbuffers and buffers created after it is turned on. Does nothing if it is already on. To count from the start, use EngineConfiguration::track_gpu_memory.
짝Counterpart: vanilla.js Engine.enableGpuMemoryTracking
use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
engine.enable_gpu_memory_tracking();
assert!(engine.is_gpu_memory_tracking_enabled());GPU 메모리 셈이 켜져 있는지. (원본 Engine.isGpuMemoryTrackingEnabled)
Whether GPU memory tracking is on. (original Engine.isGpuMemoryTrackingEnabled)
반환Returnsbool 켜져 있으면 true.true if enabled.
짝Counterpart: vanilla.js Engine.isGpuMemoryTrackingEnabled
use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
assert!(!engine.is_gpu_memory_tracking_enabled());pub fn read_gpu_memory_usage(&self) -> Option<crate::core::gpumemorytracker::GpuMemoryUsage>#GPU 메모리 읽기. (원본 Engine.readGpuMemoryUsage, 개발용, Graphic::read_gpu_memory_usage 와 같다)
- 셈이 꺼져 있으면 이 호출이 켜고 그 뒤에 지은 것부터 센다. 그래픽이 아직 없으면 None.
Reads GPU memory. (original Engine.readGpuMemoryUsage, for development, the same as Graphic::read_gpu_memory_usage)
- If tracking is off, this call turns it on and counts what is created after it. None if there is no graphic yet.
반환ReturnsOption<crate::core::gpumemorytracker::GpuMemoryUsage> 합, 캔버스 몫, 종류별과 주인별 몫.The total, the canvas share, and the shares by kind and by owner.
짝Counterpart: vanilla.js Engine.readGpuMemoryUsage
use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
if let Some(usage) = engine.read_gpu_memory_usage() {
assert_eq!(usage.total_bytes, usage.canvas_bytes + usage.kind_table.values().map(|kind_usage| kind_usage.bytes).sum::<u64>());
}
assert!(engine.is_gpu_memory_tracking_enabled() || engine.get_graphic().is_none());그래픽. (원본 getGraphic, 씬의 load, initialize, tick 이나 컴포넌트의 tick 에서 GL 자원(텍스처, 렌더 타겟, 셰이더 프로그램, 툰 렌더러 같은)을 짓는다)
- 원본 생성자처럼 데스크탑은 Engine::new 가 주 스레드에서 숨긴 창과 GL 컨텍스트를 지어 바로 있다. (run 은 그 창을 보인다) GL 을 지을 수 없는 기계(화면 없는 CI 같은)나 주 스레드가 아닌 곳(단위 시험)에서는 run 이 창을 열 때까지 None 이다. 웹은 run 이 캔버스를 잡을 때까지 None 이다.
- 그리기 함수(pre_draw, draw, post_draw, draw_on_load, draw_gizmos)와 with_graphic 의 클로저 안에서는 그래픽을 인자로 내어 주어 None 이다. (그 자리에서는 인자로 받은 graphic 이 이 그래픽이다)
Graphic. (The original getGraphic; build GL resources (textures, render targets, shader programs, toon renderers and the like) in a scene's load, initialize, tick or a component's tick)
- Like the original constructor, on the desktop Engine::new builds a hidden window and GL context on the main thread so it is there right away. (run shows that window) On machines that cannot build GL (such as CI without a display) or off the main thread (unit tests) it is None until run opens the window. On the web it is None until run takes the canvas.
- Inside draw functions (pre_draw, draw, post_draw, draw_on_load, draw_gizmos) and the closure of with_graphic it is None because the graphic is lent as an argument. (There, the graphic received as an argument is this graphic)
반환ReturnsOption<Ref<'_, Graphic>> 엔진의 그래픽. (붙이기 전이거나 인자로 내어 준 동안은 None)The engine's graphic. (None before it is attached or while it is lent as an argument)
짝Counterpart: vanilla.js Engine.getGraphic
use vanilla::{Engine, Scene, SceneBase, ShaderProgram};
const VERTEX_SHADER_SOURCE: &str = "#version 300 es
in vec2 vertexPosition;
void main() {
gl_Position = vec4(vertexPosition, 0.0, 1.0);
}
";
const FRAGMENT_SHADER_SOURCE: &str = "#version 300 es
precision highp float;
out vec4 outputColor;
void main() {
outputColor = vec4(1.0);
}
";
struct MainScene {
scene_base: SceneBase,
shader_program: Option<ShaderProgram>,
}
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) {
if let Some(graphic) = engine.get_graphic() {
self.shader_program = ShaderProgram::new(graphic.get_gl(), VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE).ok();
}
}
}use vanilla::{Engine, EngineConfiguration, RenderTarget};
let engine = Engine::new(EngineConfiguration::new());
if let Some(graphic) = engine.get_graphic() {
let render_target = RenderTarget::new(graphic.get_gl(), 64, 64, false, None);
assert!(render_target.is_ok());
}그래픽. (변경용, 글꼴 캐시, 기즈모 강제 표시, 묶어 그리기 같은 설정을 그리기 밖에서 바꾼다)
- get_graphic 처럼 붙이기 전과 인자로 내어 준 동안은 None 이다.
Graphic. (mutable, changes settings such as the text cache, forced gizmo display and batching outside drawing)
- Like get_graphic, None before it is attached and while it is lent as an argument.
반환ReturnsOption<RefMut<'_, Graphic>> 엔진의 그래픽. (붙이기 전이거나 인자로 내어 준 동안은 None)The engine's graphic. (None before it is attached or while it is lent as an argument)
짝Counterpart: vanilla.js Engine.getGraphic
use vanilla::{Engine, KeyCode, 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 tick(&mut self, time_delta: f64) {
let engine = Engine::get_engine().unwrap();
self.scene_base.tick(time_delta);
let is_key_g = engine.get_input_manager().is_key_pressed(KeyCode::G);
if let Some(mut graphic) = engine.get_graphic_mut() {
graphic.set_force_gizmos_visible(is_key_g);
}
}
}pub fn with_graphic<R>(&self, graphic_function: impl FnOnce(&Engine, &mut Graphic) -> R) -> Option<R>#엔진과 그래픽을 함께 빌리기. (그래픽과 엔진을 둘 다 &mut 로 받는 함수를 그리기 밖에서 부를 때)
- 그래픽을 엔진에서 잠깐 꺼내(Option::take) 클로저에 넘기고, 클로저가 끝나면 돌려 넣는다. 엔진이 그리기 함수에 그래픽을 넘기는 것과 같은 길이다. 클로저 안에서는 engine.get_graphic() 이 None 이고, 인자로 받은 graphic 을 쓴다.
Borrows the engine and the graphic together. (when calling, outside drawing, a function that takes both the graphic and the engine as &mut)
- Takes the graphic out of the engine for a moment (Option::take), passes it to the closure, and puts it back when the closure ends. It is the same path the engine uses to pass the graphic to drawing functions. Inside the closure engine.get_graphic() is None, and you use the graphic argument.
- graphic_functionimpl FnOnce(&Engine, &mut Graphic) -> R
- 엔진과 그래픽을 받아 일하는 클로저.Closure that works with the engine and graphic.
반환ReturnsOption<R> 클로저가 돌려준 값. (그래픽이 없거나 이미 내어 준 동안이면 클로저를 부르지 않고 None)The value the closure returned. (None without calling the closure if there is no graphic or while it is already lent)
use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
let has_graphic = engine.get_graphic().is_some();
let result = engine.with_graphic(|_engine, graphic| graphic.get_global_alpha());
assert_eq!(result.is_some(), has_graphic);use vanilla::{Engine, 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 initialize(&mut self, engine: &Engine) {
engine.with_graphic(|engine, graphic| {
engine.get_time_manager_mut().set_time_scale(1.0);
graphic.set_force_gizmos_visible(false);
});
}
}글자 입력칸이 포커스되어 있는지. (원본 isTextInputFocused, 웹은 문서의 초점이 글자 input, textarea, contenteditable 이면 참)
- 원본의 엔진 입력 필드는 숨긴 DOM input 에 초점을 두어 여기서 참이 된다. 데스크탑에는 문서가 없어 엔진 입력 필드의 포커스를 본다. (입력 매니저의 is_typing_in_text_field 와 같다)
Whether a text input is focused. (the original isTextInputFocused, on the web true if the document focus is a text input, textarea or contenteditable)
- The original's engine input field puts focus on a hidden DOM input, so this becomes true. Desktop has no document, so it looks at the focus of the engine input field. (same as the input manager's is_typing_in_text_field)
반환Returnsbool 글자 입력칸에 초점이 있으면 true.true if a text input has focus.
짝Counterpart: vanilla.js Engine.isTextInputFocused
창 제목 설정.
Sets the window title.
- title&str
- 새 창 제목. (웹은 문서 제목, 데스크탑은 창이 생기기 전에는 아무것도 하지 않는다)New window title. (the document title on the web, does nothing on desktop before the window exists)
짝Counterpart: vanilla.js Engine.setTitle
시스템 클립보드에 글 쓰기. (데스크탑 arboard, 웹 navigator.clipboard.writeText. 원본 UIInputField.writeClipboard 자리)
Writes text to the system clipboard. (desktop arboard, web navigator.clipboard.writeText. In place of the original UIInputField.writeClipboard)
- text&str
- 쓸 글.Text to write.
짝Counterpart: vanilla.js Engine.writeClipboardText
시스템 클립보드 글 읽기. (데스크탑만 그 자리에서 읽는다. 웹은 비동기라 None 이고 read_clipboard_text_with_callback 으로 읽는다)
Reads text from the system clipboard. (only desktop reads on the spot. The web is asynchronous so it is None, read with read_clipboard_text_with_callback)
반환ReturnsOption<String> 클립보드 글. (웹, 또는 클립보드를 못 읽으면 None)Clipboard text. (None on the web or if the clipboard cannot be read)
짝Counterpart: vanilla.js Engine.readClipboardText
시스템 클립보드 글을 읽어 콜백에 넘기기. (원본 UIInputField.readClipboard 가 돌려주는 Promise 의 then 자리, 못 읽거나 거부되면 빈 글)
- 웹은 navigator.clipboard.readText 가 끝난 뒤 부르고, 데스크탑은 그 자리에서 읽어 바로 부른다.
Reads text from the system clipboard and passes it to a callback. (in place of then on the Promise returned by the original UIInputField.readClipboard, empty string if it cannot be read or is denied)
- The web calls it after navigator.clipboard.readText finishes, desktop reads on the spot and calls it right away.
- callbackimpl FnOnce(String) + 'static
- 읽은 글을 받는 함수. (못 읽거나 거부되면 빈 글)Function that receives the read text. (empty string if it cannot be read or is denied)
use vanilla::Engine;
fn paste_text(engine: &Engine) {
engine.read_clipboard_text_with_callback(|clipboard_text| {
println!("{}", clipboard_text);
});
}시스템 클립보드 글 읽기. (원본 await engine.readClipboardText(), 클립보드가 없거나 거부되면 원본 null 자리의 None)
- 웹은 navigator.clipboard.readText 가 끝난 뒤, 데스크탑은 그 자리에서 읽어 풀린다.
Reads text from the system clipboard. (the original await engine.readClipboardText(), None in place of the original null if there is no clipboard or it is denied)
- The web resolves after navigator.clipboard.readText finishes, desktop reads on the spot and resolves.
반환ReturnsPromise<Option<String>> 클립보드 글로 풀리는 Promise. (클립보드가 없거나 거부되면 None)Promise that resolves with the clipboard text. (None if there is no clipboard or it is denied)
짝Counterpart: vanilla.js Engine.readClipboardText
use vanilla::Engine;
fn paste_text(engine: &Engine) {
engine.spawn_task(|mut engine_context| async move {
let clipboard_text = engine_context.with(|engine| engine.read_clipboard_text_async()).await;
println!("{}", clipboard_text.unwrap_or_default());
});
}3D 색 공간 반환. (원본 getColorSpace, EngineConfiguration::color_space, 생성 때 정한 값이라 바뀌지 않는다)
Returns the 3D color space. (original getColorSpace, EngineConfiguration::color_space, fixed at creation so it does not change)
반환ReturnsColorSpace ColorSpace::Gamma 나 ColorSpace::Linear.ColorSpace::Gamma or ColorSpace::Linear.
짝Counterpart: vanilla.js Engine.getColorSpace
use vanilla::{ColorSpace, Engine, EngineConfiguration, ToonRenderer};
let mut engine_configuration = EngineConfiguration::new();
engine_configuration.color_space = ColorSpace::Linear;
let engine = Engine::new(engine_configuration);
assert_eq!(engine.get_color_space(), ColorSpace::Linear);
if let Some(graphic) = engine.get_graphic() {
assert_eq!(graphic.get_color_space(), ColorSpace::Linear);
let renderer = ToonRenderer::new(graphic.get_gl()).unwrap();
assert_eq!(renderer.get_color_space(), ColorSpace::Linear);
}엔진 설정 반환.
Returns the engine configuration.
반환ReturnsRef<'_, EngineConfiguration> Engine::new 에 넘긴 설정. (set_maximum_frame_per_second 가 바꾼 최대 FPS 도 여기에 있다)The configuration passed to Engine::new. (the maximum FPS changed by set_maximum_frame_per_second is also here)
짝Counterpart: vanilla.js Engine.getEngineConfiguration
최대 FPS 설정. (실행 중에 바꿀 수 있다, 0 이면 제한하지 않는다. 0 보다 작거나 유한하지 않으면 0)
- EngineConfiguration.maximum_frame_per_second 에 적는다. 플랫폼이 프레임마다 그 값을 읽어 다음 프레임부터 따른다.
Sets the maximum FPS. (can be changed at runtime, no limit if 0. 0 if less than 0 or not finite)
- Written to EngineConfiguration.maximum_frame_per_second. The platform reads that value every frame and follows it from the next frame.
- maximum_frame_per_secondf64
- 초당 최대 프레임 수. (0 이면 제한 없음)Maximum frames per second. (no limit if 0)
짝Counterpart: vanilla.js Engine.setMaximumFramePerSecond
use vanilla::{Engine, EngineConfiguration};
let engine = Engine::new(EngineConfiguration::new());
engine.set_maximum_frame_per_second(30.0);
assert_eq!(engine.get_maximum_frame_per_second(), 30.0);
engine.set_maximum_frame_per_second(-5.0);
assert_eq!(engine.get_maximum_frame_per_second(), 0.0);최대 FPS 반환. (0 이면 제한하지 않음)
Returns the maximum FPS. (0 means no limit)
반환Returnsf64 초당 최대 프레임 수. (기본 0)Maximum frames per second. (default 0)
짝Counterpart: vanilla.js Engine.getMaximumFramePerSecond
시간 관리자.
Time manager.
반환ReturnsRef<'_, TimeManager> 엔진의 시간 관리자. (프레임 간격, 누적 시간, 초당 프레임 수)The engine's time manager. (frame interval, accumulated time, frames per second)
짝Counterpart: vanilla.js Engine.getTimeManager
시간 관리자. (변경용)
Time manager. (mutable)
반환ReturnsRefMut<'_, TimeManager> 엔진의 시간 관리자. (시간 배율, 프레임 간격 상한을 바꾼다)The engine's time manager. (changes the time scale and the frame interval upper limit)
짝Counterpart: vanilla.js Engine.getTimeManager
뷰 매니저.
View manager.
반환ReturnsRef<'_, ViewManager> 엔진의 뷰 매니저. (뷰 크기, 뷰 영역, 세이프 에어리어)The engine's view manager. (view size, view area, safe area)
짝Counterpart: vanilla.js Engine.getViewManager
뷰 매니저. (변경용)
View manager. (mutable)
반환ReturnsRefMut<'_, ViewManager> 엔진의 뷰 매니저. (뷰 스케일 모드, 렌더 배율 상한 같은 설정을 바꾼다)The engine's view manager. (changes settings such as the view scale mode and render scale upper limit)
짝Counterpart: vanilla.js Engine.getViewManager
입력 매니저.
Input manager.
반환ReturnsRef<'_, InputManager> 엔진의 입력 매니저. (키, 마우스, 터치, 휠)The engine's input manager. (keys, mouse, touch, wheel)
짝Counterpart: vanilla.js Engine.getInputManager
입력 매니저. (변경용)
Input manager. (mutable)
반환ReturnsRefMut<'_, InputManager> 엔진의 입력 매니저.The engine's input manager.
짝Counterpart: vanilla.js Engine.getInputManager
마우스 커서. (켜면 프레임 끝마다 창이나 캔버스의 커서를 정한다)
Mouse cursor. (when on, sets the window or canvas cursor at the end of every frame)
반환ReturnsRef<'_, PointerCursor> 엔진의 마우스 커서. (단추는 &Engine 으로 mark_over_button 을 부른다)The engine's mouse cursor. (buttons call mark_over_button with &Engine)
마우스 커서. (변경용)
Mouse cursor. (mutable)
반환ReturnsRefMut<'_, PointerCursor> 엔진의 마우스 커서. (켜기, 화면 커서, 그림 커서를 정한다)The engine's mouse cursor. (sets on/off, the screen cursor and image cursors)
주된 손이 손가락인지. (CSS 의 pointer: coarse, 데스크탑은 크로미엄처럼 윈도우 태블릿과 리눅스 터치스크린 기기에서 참)
Whether the primary pointer is a finger. (CSS pointer: coarse, on desktop true on Windows tablets and Linux touchscreen devices, like Chromium)
반환Returnsbool 주된 손이 손가락이면 true. (맥은 늘 false)true if the primary pointer is a finger. (always false on Mac)
짝Counterpart: vanilla.js Engine.isCoarsePointer
오디오 매니저. (메서드가 &self 라 컴포넌트가 받는 &Engine 으로도 플레이어를 만들 수 있다)
Audio manager. (its methods take &self, so players can be created even with the &Engine a component receives)
반환ReturnsRef<'_, AudioManager> 엔진의 오디오 매니저.The engine's audio manager.
짝Counterpart: vanilla.js Engine.getAudioManager
오디오 매니저. (가변)
Audio manager. (mutable)
반환ReturnsRefMut<'_, AudioManager> 엔진의 오디오 매니저.The engine's audio manager.
짝Counterpart: vanilla.js Engine.getAudioManager
플랫폼 정보. (원본 Platform, 운영체제와 브라우저 종류)
Platform info. (the original Platform, operating system and browser kind)
반환ReturnsRef<'_, Platform> 엔진을 만들 때 읽은 플랫폼 정보.Platform info read when the engine was created.
짝Counterpart: vanilla.js Engine.getPlatform
페이지 이벤트 리스너 더하기. (리스너를 버리면 더 부르지 않는다, &Engine 으로도 더할 수 있다)
Adds a page event listener. (dropping the listener stops it from being called, can also be added with &Engine)
- page_event_listener&PageEventListener
- 더할 리스너. (엔진은 약한 참조로 든다, 부른 쪽이 살려 둔다)Listener to add. (the engine holds it by weak reference, the caller keeps it alive)
짝Counterpart: vanilla.js Engine.addPageEventListener
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Engine, EngineConfiguration, PageEvent, PageEventListener};
let engine = Engine::new(EngineConfiguration::new());
let received_list: Rc<RefCell<Vec<PageEvent>>> = Rc::new(RefCell::new(Vec::new()));
let listener_received_list = received_list.clone();
let page_event_listener: PageEventListener = Rc::new(RefCell::new(move |page_event: PageEvent| {
listener_received_list.borrow_mut().push(page_event);
}));
engine.add_page_event_listener(&page_event_listener);
engine.dispatch_page_event(PageEvent::Hidden);
assert!(engine.is_page_hidden());
engine.dispatch_page_event(PageEvent::Visible);
assert_eq!(*received_list.borrow(), vec![PageEvent::Hidden, PageEvent::Visible]);
engine.remove_page_event_listener(&page_event_listener);
engine.dispatch_page_event(PageEvent::Focused);
assert_eq!(received_list.borrow().len(), 2);페이지 이벤트 리스너 빼기. (같은 리스너를 더 부르지 않는다, 버린 리스너도 빠진다)
Removes a page event listener. (the same listener is no longer called, dropped listeners are also removed)
- page_event_listener&PageEventListener
- 뺄 리스너. (add_page_event_listener 에 넘긴 것)Listener to remove. (the one passed to add_page_event_listener)
짝Counterpart: vanilla.js Engine.removePageEventListener
페이지 이벤트 알리기. (플랫폼이 부르고, 원본처럼 게임이 불러도 된다. 가려짐을 적고 살아 있는 리스너에 그 자리에서 넘긴다)
- 리스너가 다른 일로 빌려져 있으면 그 리스너는 이번 이벤트를 건너뛴다.
Dispatches a page event. (called by the platform, and games may call it too as in the original. Records hidden state and passes it on the spot to the live listeners)
- If a listener is borrowed for something else, that listener skips this event.
- page_eventPageEvent
- 알릴 이벤트. (Hidden 이면 가려짐을 적고 Visible 이면 지운다)Event to dispatch. (Hidden records hidden state, Visible clears it)
짝Counterpart: vanilla.js Engine.dispatchPageEvent
pub fn add_graphic_context_event_listener(&self, graphic_context_event_listener: &GraphicContextEventListener)#그래픽 컨텍스트 이벤트 리스너 더하기. (원본 addGraphicContextEventListener, 리스너를 버리면 더 부르지 않는다)
- 컨텍스트를 잃으면 Lost, 되살아나 엔진이 기본 자원을 다시 지으면 Restored 를 넘긴다. 잃은 동안 엔진은 그리지 않고 씬 갱신만 한다.
Adds a graphic context event listener. (The original's addGraphicContextEventListener, dropping the listener stops further calls)
- Passes Lost when the context is lost, and Restored once it is back and the engine has rebuilt its base resources. While lost, the engine does not draw and only updates scenes.
- graphic_context_event_listener&GraphicContextEventListener
- 더할 리스너. (엔진은 약한 참조로 든다, 부른 쪽이 살려 둔다)Listener to add. (the engine holds it by weak reference, the caller keeps it alive)
짝Counterpart: vanilla.js Engine.addGraphicContextEventListener
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Engine, EngineConfiguration, GraphicContextEvent, GraphicContextEventListener};
let engine = Engine::new(EngineConfiguration::new());
let received_list: Rc<RefCell<Vec<GraphicContextEvent>>> = Rc::new(RefCell::new(Vec::new()));
let listener_received_list = received_list.clone();
let graphic_context_event_listener: GraphicContextEventListener = Rc::new(RefCell::new(move |graphic_context_event: GraphicContextEvent| {
listener_received_list.borrow_mut().push(graphic_context_event);
}));
engine.add_graphic_context_event_listener(&graphic_context_event_listener);
engine.dispatch_graphic_context_event(GraphicContextEvent::Lost);
engine.dispatch_graphic_context_event(GraphicContextEvent::Restored);
assert_eq!(*received_list.borrow(), vec![GraphicContextEvent::Lost, GraphicContextEvent::Restored]);pub fn remove_graphic_context_event_listener(&self, graphic_context_event_listener: &GraphicContextEventListener)#그래픽 컨텍스트 이벤트 리스너 빼기. (원본 removeGraphicContextEventListener, 버린 리스너도 빠진다)
Removes a graphic context event listener. (The original's removeGraphicContextEventListener, a dropped listener is removed too)
- graphic_context_event_listener&GraphicContextEventListener
- 뺄 리스너. (add_graphic_context_event_listener 에 넘긴 것)The listener to remove. (the one passed to add_graphic_context_event_listener)
짝Counterpart: vanilla.js Engine.removeGraphicContextEventListener
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Engine, EngineConfiguration, GraphicContextEvent, GraphicContextEventListener};
let engine = Engine::new(EngineConfiguration::new());
let count = Rc::new(RefCell::new(0));
let listener_count = count.clone();
let graphic_context_event_listener: GraphicContextEventListener = Rc::new(RefCell::new(move |_graphic_context_event: GraphicContextEvent| {
*listener_count.borrow_mut() += 1;
}));
engine.add_graphic_context_event_listener(&graphic_context_event_listener);
engine.remove_graphic_context_event_listener(&graphic_context_event_listener);
engine.dispatch_graphic_context_event(GraphicContextEvent::Lost);
assert_eq!(*count.borrow(), 0);그래픽 컨텍스트 이벤트 알리기. (플랫폼이 부른다, 살아 있는 리스너에 그 자리에서 넘긴다)
- 리스너가 다른 일로 빌려져 있으면 그 리스너는 이번 이벤트를 건너뛴다.
Notifies a graphic context event. (Called by the platform, passed on the spot to the live listeners)
- A listener that is borrowed for something else skips this event.
- graphic_context_eventGraphicContextEvent
- 알릴 이벤트.The event to notify.
짝Counterpart: vanilla.js Engine.dispatchGraphicContextEvent
그래픽 오류 리스너 더하기. (원본 addGraphicErrorListener, 리스너를 버리면 더 부르지 않는다)
- 엔진이 셰이더 프로그램을 짓지 못했을 때(툰 렌더러의 머티리얼, 화면 효과의 패스, resolve_shader_program 의 프로그램) 한 번 알린다. 짓지 못한 프로그램은 다시 짓지 않고 건너뛰어 그리므로, 게임은 이 알림으로 대체 그리기나 오류 보고를 정한다. 컨텍스트를 잃은 탓의 실패는 셰이더 탓이 아니라 알리지 않고, 기억하지도 않는다.
Adds a graphic error listener. (The original's addGraphicErrorListener, dropping the listener stops further calls)
- Reports once when the engine cannot build a shader program (a toon renderer material, a screen effect pass, a resolve_shader_program program). A program that failed to build is not rebuilt and is skipped when drawing, so the game uses this notification to decide a fallback drawing or an error report. A failure caused by losing the context is not the shader's fault, so it is neither reported nor remembered.
- graphic_error_listener&GraphicErrorListener
- 더할 리스너. (엔진은 약한 참조로 든다, 부른 쪽이 살려 둔다)Listener to add. (the engine holds it by weak reference, the caller keeps it alive)
짝Counterpart: vanilla.js Engine.addGraphicErrorListener
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Engine, EngineConfiguration, GraphicError, GraphicErrorKind, GraphicErrorListener};
let engine = Engine::new(EngineConfiguration::new());
let failed_name_list: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
let listener_failed_name_list = failed_name_list.clone();
let graphic_error_listener: GraphicErrorListener = Rc::new(RefCell::new(move |graphic_error: &GraphicError| {
if graphic_error.kind == GraphicErrorKind::ShaderBuildFailed {
listener_failed_name_list.borrow_mut().push(graphic_error.name.clone());
}
}));
engine.add_graphic_error_listener(&graphic_error_listener);
engine.dispatch_graphic_error(&GraphicError { kind: GraphicErrorKind::ShaderBuildFailed, name: String::from("stripe"), error: String::from("compile failed") });
assert_eq!(*failed_name_list.borrow(), vec![String::from("stripe")]);pub fn remove_graphic_error_listener(&self, graphic_error_listener: &GraphicErrorListener)#그래픽 오류 리스너 빼기. (원본 removeGraphicErrorListener, 버린 리스너도 빠진다)
Removes a graphic error listener. (The original's removeGraphicErrorListener, a dropped listener is removed too)
- graphic_error_listener&GraphicErrorListener
- 뺄 리스너. (add_graphic_error_listener 에 넘긴 것)The listener to remove. (the one passed to add_graphic_error_listener)
짝Counterpart: vanilla.js Engine.removeGraphicErrorListener
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Engine, EngineConfiguration, GraphicError, GraphicErrorKind, GraphicErrorListener};
let engine = Engine::new(EngineConfiguration::new());
let count = Rc::new(RefCell::new(0));
let listener_count = count.clone();
let graphic_error_listener: GraphicErrorListener = Rc::new(RefCell::new(move |_graphic_error: &GraphicError| {
*listener_count.borrow_mut() += 1;
}));
engine.add_graphic_error_listener(&graphic_error_listener);
engine.remove_graphic_error_listener(&graphic_error_listener);
engine.dispatch_graphic_error(&GraphicError { kind: GraphicErrorKind::ShaderBuildFailed, name: String::from("stripe"), error: String::new() });
assert_eq!(*count.borrow(), 0);그래픽 오류 알리기. (엔진이 부른다, 살아 있는 리스너에 그 자리에서 넘긴다)
- 리스너가 다른 일로 빌려져 있으면 그 리스너는 이번 오류를 건너뛴다.
Notifies a graphic error. (Called by the engine, passed on the spot to the live listeners)
- A listener that is borrowed for something else skips this error.
- graphic_error&GraphicError
- 알릴 오류. (kind, name, error)The error to notify. (kind, name, error)
짝Counterpart: vanilla.js Engine.dispatchGraphicError
지금 프레임의 번호. (원본처럼 첫 프레임이 1, 검증용 화면 저장의 프레임 번호도 이것)
Number of the current frame. (the first frame is 1 as in the original, also the frame number for verification screen captures)
반환Returnsu64 지금 프레임 번호. (프레임이 끝날 때마다 1 씩 는다)Current frame number. (increases by 1 at the end of each frame)
짝Counterpart: vanilla.js Engine.getFrameNumber
엔진 판 글.
Engine version string.
반환ReturnsString 엔진 판. ("0.3.2" 꼴)Engine version. ("0.3.2" form)
짝Counterpart: vanilla.js Engine.getVersionString
pub fn request_frame_capture(&self, frame_number: u64, capture_handler: FrameCaptureHandler)#검증용 화면 저장 요청. (그 프레임을 다 그린 뒤 화면의 PNG 바이트를 넘긴다, 원본 requestFrameCapture 는 PNG data URL 을 프로미스로 넘긴다)
- 이미 지난 번호면 이번(프레임 사이에 부르면 다음) 프레임을 저장한다.
- 주소 쿼리(웹 ?capture=120,240&captureName=shot_{frame}.png&captureExit=1)와 환경 변수(데스크탑 VANILLA_CAPTURE_*)로도 건다.
Requests a verification screen capture. (passes the PNG bytes of the screen after that frame is fully drawn, the original requestFrameCapture passes a PNG data URL through a promise)
- If the number has already passed, captures this frame (the next one if called between frames).
- Can also be set with URL queries (web ?capture=120,240&captureName=shot_{frame}.png&captureExit=1) and environment variables (desktop VANILLA_CAPTURE_*).
- frame_numberu64
- 저장할 프레임 번호. (지난 번호면 지금 프레임)Frame number to capture. (the current frame if already passed)
- capture_handlerFrameCaptureHandler
- 그 프레임 화면의 PNG 바이트를 받는 함수.Function that receives the PNG bytes of that frame's screen.
짝Counterpart: vanilla.js Engine.requestFrameCapture
use vanilla::Engine;
fn capture_frame(engine: &Engine) {
engine.request_frame_capture(120, Box::new(|png_bytes: &[u8]| {
std::fs::write("capture_120.png", png_bytes).unwrap();
}));
}검증용 화면 저장 요청. (원본 await engine.requestFrameCapture(번호), 그 프레임을 다 그린 화면의 PNG 바이트로 풀리는 Promise. 원본은 PNG data URL)
Requests a verification screen capture. (the original await engine.requestFrameCapture(number), a Promise that resolves with the PNG bytes of the fully drawn screen of that frame. A PNG data URL in the original)
- frame_numberu64
- 저장할 프레임 번호. (지난 번호면 지금 프레임)Frame number to capture. (the current frame if already passed)
반환ReturnsPromise<Vec<u8>> 그 프레임 화면의 PNG 바이트로 풀리는 Promise.Promise that resolves with the PNG bytes of that frame's screen.
짝Counterpart: vanilla.js Engine.requestFrameCapture
pub fn measure_gpu_throughput(&self, frame_count: u32) -> Promise<Result<GpuThroughput, String>>#GPU 처리량 재기. (원본 measureGpuThroughput, 지금 장면을 갱신 없이 그리기만 잇달아 하고 GPU 가 다 그리길 기다린 프레임당 시간)
- 지금 장면을 씬 갱신(tick) 없이 엔진 프레임과 같은 그리기 길로 frame_count 번 잇달아 그리고, 1 화소 읽기로 GPU 가 다 그리길 기다린 벽시계 시간을 프레임 수로 나눈다. 그리는 쪽(CPU 의 GL 명령 쓰기), 드라이버, GPU 실행 가운데 가장 느린 단의 몫이다. GPU 가 가장 느리면 GPU 가 실제로 한 프레임을 그리는 시간이다.
- 다음 엔진 갱신부터 시작한다. 데움 10 프레임 뒤 30 프레임씩 덩이로 나눠 갱신 하나에 한 덩이를 그리고 덩이마다 GPU 를 기다린다. (한 번에 길게 막지 않는다, 덩이 사이는 재지 않는다)
- 재는 동안 엔진 시간, 입력, 프레임 번호, 화면 크기 맞추기, 찍기는 서 있고 씬의 tick 을 부르지 않는다. 씬의 draw 가 게임 상태를 바꾸지 않으면 게임 상태는 그대로다. 다 재면 엔진 루프가 그대로 이어 돈다.
- 같은 상태를 되풀이해 그리므로 바뀐 것만 다시 그리는 캐시(그림자 OnChange 같은)는 다시 굽지 않는다. 화면에 내는 것(합성)은 덩이마다 마지막 프레임만 한다.
- 재는 중에 또 부르거나, 엔진 루프가 돌기 전이거나, frame_count 가 0 이면 Err 로 풀린다.
GPU throughput measurement. (Original measureGpuThroughput; draws the current scene back to back without updating and returns the time per frame after waiting for the GPU to finish)
- Draws the current scene frame_count times back to back through the same draw path as an engine frame, without a scene update (tick), and divides the wall-clock time until a 1-pixel read shows the GPU has finished by the frame count. It is the share of the slowest of the drawing side (CPU writing GL commands), the driver and GPU execution. When the GPU is the slowest, it is the time the GPU really takes to draw one frame.
- Starts from the next engine update. After 10 warm-up frames it draws one chunk of 30 frames per update and waits for the GPU after every chunk. (It does not block for long at once; the gaps between chunks are not measured)
- While measuring, engine time, input, frame number, canvas size fitting and capture stand still and the scene's tick is not called. If the scene's draw does not change game state, game state stays as it is. When done, the engine loop continues as before.
- Because it draws the same state repeatedly, caches that redraw only what changed (such as shadow OnChange) do not re-bake. Presenting to the screen (compositing) happens only for the last frame of each chunk.
- Resolves with Err when called again while measuring, before the engine loop has run, or when frame_count is 0.
- frame_countu32
- 잴 프레임 수. (1 이상, 데움은 빼고 센다)Number of frames to measure. (1 or more, warm-up frames are not counted)
반환ReturnsPromise<Result<GpuThroughput, String>> GpuThroughput 으로 풀리는 Promise. (실패하면 Err(까닭))A Promise that resolves with a GpuThroughput. (Err(reason) on failure)
짝Counterpart: vanilla.js Engine.measureGpuThroughput
use vanilla::{Engine, GpuThroughput};
fn measure(engine: &'static Engine) {
engine.spawn_task(|mut engine_context| async move {
let result: Result<GpuThroughput, String> = engine_context.with(|engine| engine.measure_gpu_throughput(60)).await;
if let Ok(throughput) = result {
println!("{} frames, {} ms per frame", throughput.frame_count, throughput.milliseconds_per_frame);
}
});
}GpuThroughputstruct traits Clone, Debug, PartialEq
GPU 처리량 재기의 결과. (원본 measureGpuThroughput 이 돌려주는 { frameCount, chunkFrameCount, millisecondsPerFrame, chunkMillisecondsPerFrame })
The result of the GPU throughput measurement. (What the original measureGpuThroughput returns: { frameCount, chunkFrameCount, millisecondsPerFrame, chunkMillisecondsPerFrame })
use vanilla::GpuThroughput;
let throughput = GpuThroughput {
frame_count: 4,
chunk_frame_count: 2,
milliseconds_per_frame: 1.5,
chunk_milliseconds_per_frame: vec![1.0, 2.0],
};
let chunk_total: f64 = throughput.chunk_milliseconds_per_frame.iter().map(|value| value * throughput.chunk_frame_count as f64).sum();
assert_eq!(chunk_total / throughput.frame_count as f64, throughput.milliseconds_per_frame);잰 프레임 수. (데움은 빼고 센다)
Number of frames measured. (warm-up frames are not counted)
반환Returnsu32
프레임당 시간. (밀리초, 모든 덩이 시간의 합 / 프레임 수)
Time per frame. (milliseconds, the sum of all chunk times / the frame count)
반환Returnsf64
덩이마다 프레임당 시간. (밀리초)
Time per frame for each chunk. (milliseconds)
반환ReturnsVec<f64>
EngineRunnerstruct
엔진 실행자. (엔진, 그래픽, 씬 목록을 들고 프레임을 돈다. 플랫폼이 들고 부른다)
- 게임 코드는 직접 만들지 않는다. Engine::run 이 엔진과 첫 씬으로 만들어 플랫폼에 넘긴다.
Engine runner. (holds the engine, graphic and scene list and runs the frames. Held and called by the platform)
- Game code does not create it directly. Engine::run creates it with the engine and the first scene and hands it to the platform.
use vanilla::{Engine, EngineConfiguration, 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
}
}
let engine = Engine::new(EngineConfiguration::new());
engine.run(Box::new(MainScene { scene_base: SceneBase::new() })).unwrap();PageEventenum traits Clone, Copy, Debug, PartialEq, Eq
페이지 이벤트. (플랫폼이 엔진에 알리고, 엔진이 리스너에 그 자리에서 넘긴다)
Page event. (the platform notifies the engine, and the engine passes it on the spot to the listeners)
| 이름Name | 설명Description |
|---|---|
Hidden | 페이지가 가려짐. (다른 탭, 앱 전환, 창이 가려짐)The page was hidden. (another tab, app switching, window occluded) |
Visible | 페이지가 다시 보임.The page became visible again. |
Blurred | 창이 포커스를 잃음. (blur)The window lost focus. (blur) |
Focused | 창이 포커스를 얻음. (focus)The window gained focus. (focus) |
PointerDown | 창을 누름. (pointerdown, 포커스를 알리지 않아도 누르면 창은 포커스를 가진 것이다)The window was pressed. (pointerdown, once pressed the window has focus even without a focus notification) |
GraphicContextEventenum traits Clone, Copy, Debug, PartialEq, Eq
그래픽 컨텍스트 이벤트. (원본 GraphicContextEvent, 엔진이 리스너에 그 자리에서 넘긴다)
Graphic context event. (The original's GraphicContextEvent, passed by the engine to listeners on the spot)
| 이름Name | 설명Description |
|---|---|
Lost | GL 컨텍스트를 잃음. (GPU 메모리 부족, 드라이버 재설정, 백그라운드 회수. 잃은 동안 엔진은 그리지 않고 씬 갱신만 한다)The GL context was lost. (Out of GPU memory, driver reset, or reclaimed in the background. While lost, the engine does not draw and only updates scenes) |
Restored | 컨텍스트가 되살아나 엔진이 기본 자원을 다시 지음. (게임이 지은 GL 객체와 3D 렌더러, 렌더 타겟은 죽었으니 이때 다시 짓는다)The context was restored and the engine rebuilt its base resources. (GL objects the game made, 3D renderers and render targets are dead, rebuild them now) |
GraphicErrorKindenum traits Clone, Copy, Debug, PartialEq, Eq
그래픽 오류 갈래. (원본 GraphicErrorKind, GraphicError 의 kind)
Graphic error kinds. (The original's GraphicErrorKind, the kind of GraphicError)
| 이름Name | 설명Description |
|---|---|
ShaderBuildFailed | 셰이더 프로그램을 짓지 못함. (컴파일이나 링크 실패, 같은 프로그램은 다시 알리지 않고 짓지도 않는다. 컨텍스트를 잃은 탓의 실패는 알리지 않는다)A shader program could not be built. (A compile or link failure, the same program is neither reported again nor rebuilt. A failure caused by losing the context is not reported) |