misc/devtools
개발자 도구. (원본 misc/devtools.js 의 DEVTools)
- F2 키로 보이고 숨긴다. 패널은 뷰 스케일 모드와 상관없이 창 안쪽 논리 좌표(canvas native)로 오른쪽 아래에 붙어 나온다.
- 탭 넷: Statistics(엔진, 화면, 시간 정보), Node Hierarchy(왼쪽 트리 + 오른쪽 인스펙터), Local Storage(키와 값 보기, 더하기, 고치기, 지우기), Settings(바탕 어둡게, 모든 기즈모, 화면 비율 가이드, FPS 표시. 로컬 스토리지 "hierarchy.settings" 에 원본과 같은 JSON 으로 남긴다)
- 타이틀바를 끌어 옮기고, 모서리와 꼭짓점을 끌어 크기를 바꾸고, 가운데 구분선을 끌어 좌우 비율을 바꾼다.
- 트리: 펼치기와 접기, 액티브(A)와 기즈모(G) 칸, 고르기, 끌어 스크롤. 인스펙터: 컴포넌트 머리를 눌러 속성을 펼치고 접는다. (기본 펼침)
- 러스트 판은 씬이 DevTools 를 품고 함수마다 부른다:
tick 에서 dev_tools.tick(engine, node_tree, unscaled_time_delta), post_draw 에서 dev_tools.draw(engine, node_tree, graphic).
is_visible() && is_pointer_inside_panel(engine) 이면 씬은 그 입력을 노드에 넘기지 않는다. (원본 GameScene.isDevToolsCapturingInput)- 원본과 다른 점:
- 원본 setEngine 이 없다. (엔진은 하나라 따로 줄 엔진이 없다) tick, draw, is_pointer_inside_panel 이 엔진을 받는다.
- 노드 대신 NodeId 로 가리킨다. 루트 목록은 set_root_nodes(
Vec<NodeId>) 이고, 펼친 노드는 NodeId 집합, 접은 컴포넌트는 (NodeId, 컴포넌트 차례) 집합이다. 지운 노드는 트리와 인스펙터에서 빠지고, 고른 노드가 지워지면 고르지 않은 것으로 돌아간다. - 원본이 tick 과 눌림에서 부르는 setForceGizmosVisible 은 눌림 처리와 set_visible 이 &Engine 만 받아 Graphic 을 바꿀 수 없어, 바랄 값을 적어 두었다가 tick 끝에 엔진의 그래픽(get_graphic_mut)에 건다. 그래서 원본처럼 그 프레임의 그리기부터 보인다. (tick 밖에서 set_visible 을 부른 것은 draw 첫머리에 건다) 원본 setEngine 이 거는 false 는 첫 tick 에 건다. (DevTools::new 는 엔진을 받지 않는다)
- 노드 종류는 WorldNode 하나뿐이라 트리의 Type 칸과 인스펙터의 type 은 들고 있는 UIDocument 의 노드 종류 이름(UIDocument::get_node_type_name)이다. (원본 constructor.name 자리, 처음 문서에 등록된 FloatingText 같은 엔진 노드 종류와 게임이 등록한 종류, 그 밖은 "WorldNode")
- 인스펙터의 컴포넌트 속성은 원본 getComponentProperties 처럼 그 컴포넌트의 get*, is* 게터를 모두 불러 보인다. 원본은 실행 중에 프로토타입을 훑고, 러스트 판은
#[reflect]매크로가 컴파일 때 지은 목록을 쓴다. (core/reflection.rs, 엔진 컴포넌트는 모두 붙였다) 트리를 받는 게터(원본은 이웃 컴포넌트를 바로 쥐는 것)는 그리기에서 트리를 넘겨 부르고, &mut self 게터가 있는 컴포넌트는 tick 이 트리를 쥐고 읽어 둔 값을 보인다. 이름은 원본 formatMethodName(getTextColor → textColor, is 로 시작하면 그대로), 값은 원본 formatPropertyValue 꼴이다. (수는 toFixed(2), Vector2 는 (x, y), Rect 는 (x, y, 너비, 높이) toFixed(1), Color 는 rgba, null, 노드는[WorldNode], 배열은[Array], 그 밖은 [종류 이름]) 목록과 차례는 원본과 같다. (원본 클래스에 없는 러스트 판의 다시 정의는 빼고, 원본과 이름이 다른 게터는 원본 이름으로 보인다) 원본 getEngine 은 뺀다. (원본은 setEngine 으로 준 값이고, 러스트 판 UIView::get_engine 은 전역 엔진을 꺼내는 함수다) - 원본처럼 모든 컴포넌트가 반사된다. Reflect 가 Component 의 상위 트레이트라
#[reflect]를 빠뜨린 게임 컴포넌트는 컴파일되지 않는다. 노드 종류 이름(노드를 가리키는 값)은 UIDocument 에 등록한 이름이다. 게임이 자기 종류를 등록한 문서는 set_ui_document 로 건다. (또는 get_ui_document_mut 로 등록한다) - Local Storage 탭의 키 입력, 값 고치기, 지울지 묻기는 두 엔진 모두 엔진 질문 창 Engine::prompt, Engine::confirm 이다. (원본 engine.prompt, engine.confirm) (core/modaldialog.rs) 엔진이 그린 질문 창이 떠서 답할 때까지 씬이 멈추고, 답은 다음 tick 에 받는다. (웹과 데스크탑 같다)
- Statistics 의 clientNativeSize 는 ViewManager::get_client_native_size(웹은 페이지 전체 크기, 데스크탑은 창 안쪽 논리 크기)다. 메모리는 웹에서 원본처럼 Chrome 의 performance.memory 를 읽고, 없는 브라우저는 "(N/A)" 다. 데스크탑은 자바스크립트 힙이 없어 같은 칸에 같은 뜻의 값을 운영체제 API 로 읽어 적는다. 쓰는 중과 잡아 둔 것은 러스트가 쓰는 시스템 할당자의 힙, jsHeapSizeLimit 는 운영체제가 이 프로세스의 힙에 허락하는 상한이다. (platform/desktop.rs read_heap_usage, read_heap_size_limit) 두 엔진 모두 구하지 못한 칸은 칸마다 "(N/A)" 다. (힙을 못 읽으면 셋 다) viewScaleMode 는 러스트 열거 이름(StretchHeight 등)으로 적는다.
- 화면 비율 가이드는 원본처럼 그때의 좌표계에 기대지 않고 스스로 뷰 좌표계(apply_view_rect)를 걸고 그린다. (원본 GameScene 에서 같은 결과)
- Settings 의 Show FPS 를 켜면 패널을 닫아도 창 왼쪽 위에 지난 1 초의 프레임 수를 그린다. (원본과 같다, canvas native 좌표, 패널이 보이면 패널 위에)
- 옮기지 않은 것: 없음. (원본에서 아무도 부르지 않는 그리기 오류 무시 try/catch 는 러스트에서 필요 없다)
Developer tools. (DEVTools of the original misc/devtools.js)
- Shown and hidden with the F2 key. The panel appears docked at the bottom right in the window's inner logical coordinates (canvas native), regardless of the view scale mode.
- Four tabs: Statistics (engine, screen and time info), Node Hierarchy (tree on the left + inspector on the right), Local Storage (view, add, edit and remove keys and values), Settings (dim background, all gizmos, aspect ratio guide, FPS display. Saved to the local storage "hierarchy.settings" as the same JSON as the original)
- Drag the title bar to move, drag the edges and corners to resize, and drag the center divider to change the left and right ratio.
- Tree: expand and collapse, active (A) and gizmo (G) columns, selection, drag to scroll. Inspector: click a component header to expand and collapse its properties. (expanded by default)
- In the Rust version the scene holds DevTools and calls it in each function:
dev_tools.tick(engine, node_tree, unscaled_time_delta) in tick, dev_tools.draw(engine, node_tree, graphic) in post_draw.
If is_visible() && is_pointer_inside_panel(engine), the scene does not pass that input to the nodes. (original GameScene.isDevToolsCapturingInput)- Differences from the original:
- There is no original setEngine. (there is only one engine, so there is no separate engine to give) tick, draw and is_pointer_inside_panel take the engine.
- Nodes are referred to by NodeId. The root list is set_root_nodes(
Vec<NodeId>), expanded nodes are a set of NodeId, and collapsed components are a set of (NodeId, component index). Removed nodes drop out of the tree and the inspector, and if the selected node is removed it goes back to nothing selected. - setForceGizmosVisible, which the original calls in tick and on presses: press handling and set_visible take only &Engine and cannot change Graphic, so they record the desired value and tick applies it to the engine's graphic (get_graphic_mut) at its end. So, as in the original, it shows from that frame's drawing. (set_visible called outside tick is applied at the start of draw) The false applied by the original setEngine is applied on the first tick. (DevTools::new does not take the engine)
- The only node type is WorldNode, so the tree's Type column and the inspector's type are the node type name from the held UIDocument (UIDocument::get_node_type_name). (in place of the original constructor.name: engine node types such as FloatingText registered in the initial document and types the game registered, otherwise "WorldNode")
- The inspector's component properties call and show all get* and is* getters of the component, like the original getComponentProperties. The original scans prototypes at run time, and the Rust version uses the list built at compile time by the
#[reflect]macro. (core/reflection.rs, attached to all engine components) Getters that take the tree (the original holds neighbor components directly) are called with the tree passed in drawing, and for components with &mut self getters, tick holds the tree and the values read there are shown. Names follow the original formatMethodName (getTextColor → textColor, kept as is if it starts with is), and values follow the original formatPropertyValue form. (numbers toFixed(2), Vector2 as (x, y), Rect as (x, y, width, height) toFixed(1), Color as rgba, null, nodes as[WorldNode], arrays as[Array], others as [type name]) The list and order are the same as the original. (redefinitions in the Rust version not in the original class are left out, and getters named differently from the original are shown with the original name) The original getEngine is left out. (in the original it is the value given with setEngine, while the Rust UIView::get_engine is a function that takes the global engine) - Like the original, every component is reflected. Reflect is a supertrait of Component, so a game component without
#[reflect]does not compile. Node type names (for values that point at nodes) are the names registered in the UIDocument. A document where the game registered its own types is set with set_ui_document. (or registered through get_ui_document_mut) - Key input, value editing and the remove confirmation in the Local Storage tab use the engine question dialogs Engine::prompt and Engine::confirm in both engines. (the original engine.prompt, engine.confirm) (core/modaldialog.rs) The question dialog drawn by the engine appears, the scene pauses until it is answered, and the answer is received on the next tick. (the same on the web and the desktop)
- clientNativeSize in Statistics is ViewManager::get_client_native_size (the whole page size on the web, the window's inner logical size on desktop). Memory reads Chrome's performance.memory on the web like the original, and is "(N/A)" in browsers without it. The desktop has no JavaScript heap, so the same fields show values with the same meaning read through operating system APIs. In use and reserved are the heap of the system allocator Rust uses, and jsHeapSizeLimit is the upper bound the operating system allows for this process's heap. (platform/desktop.rs read_heap_usage, read_heap_size_limit) In both engines each field that cannot be obtained is "(N/A)". (All three if the heap cannot be read) viewScaleMode is written with the Rust enum name (StretchHeight and so on).
- The aspect ratio guide does not rely on the coordinate system at the time like the original, but applies the view coordinate system (apply_view_rect) itself and draws. (same result as in the original GameScene)
- Turning on Show FPS in Settings draws the frame count of the last second at the top left of the window even when the panel is closed. (same as the original, canvas native coordinates, over the panel if the panel is visible)
- Not ported: none. (the try/catch ignoring draw errors, which nobody calls in the original, is not needed in Rust)
use vanilla::{DevTools, Engine, EngineConfiguration, Graphic, Scene, SceneBase};
struct MainScene {
scene_base: SceneBase,
dev_tools: DevTools,
}
impl Scene for MainScene {
fn get_scene_base(&self) -> &SceneBase {
&self.scene_base
}
fn get_scene_base_mut(&mut self) -> &mut SceneBase {
&mut self.scene_base
}
fn load(&mut self, _engine: &Engine) {
self.dev_tools.set_root_nodes(vec![self.scene_base.get_root_id()]);
}
fn tick(&mut self, time_delta: f64) {
let engine = Engine::get_engine().unwrap();
let is_capturing_input = self.dev_tools.is_visible() && self.dev_tools.is_pointer_inside_panel(engine);
self.scene_base.get_node_tree_mut().tick(engine, time_delta);
if !is_capturing_input {
self.scene_base.tick_touch(time_delta);
}
self.scene_base.tick_tweens(time_delta);
let unscaled_time_delta = engine.get_time_manager().get_unscale_delta_time();
self.dev_tools.tick(engine, self.scene_base.get_node_tree_mut(), unscaled_time_delta);
}
fn post_draw(&mut self, graphic: &mut Graphic) {
let engine = Engine::get_engine().unwrap();
self.dev_tools.draw(engine, self.scene_base.get_node_tree(), graphic);
}
}
let engine = Engine::new(EngineConfiguration::new());
let main_scene = MainScene {
scene_base: SceneBase::new(),
dev_tools: DevTools::new(),
};
engine.run(Box::new(main_scene)).unwrap();
DevToolsstruct traits Default
개발자 도구 패널.
- 씬이 들고 tick, draw 를 부른다. 패널 좌표는 창 안쪽 논리 좌표(canvas native)다.
Developer tools panel.
- The scene holds it and calls tick, draw. Panel coordinates are the window's inner logical coordinates (canvas native).
use vanilla::{DevTools, Engine, EngineConfiguration, NodeTree};
let engine = Engine::new(EngineConfiguration::new());
engine.get_view_manager_mut().calculate_view_rect(1280, 720, 1.0);
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let group_id = node_tree.create_child(root_id, "group");
let hero_id = node_tree.create_child(group_id, "hero");
let mut dev_tools = DevTools::new();
dev_tools.set_root_nodes(vec![root_id]);
dev_tools.inspect_node(&engine, &node_tree, hero_id);
assert!(dev_tools.is_visible());
assert_eq!(dev_tools.get_active_tab(), 1);
assert_eq!(dev_tools.get_selected_node(), Some(hero_id));
assert!(dev_tools.is_node_expanded(group_id));
let panel_rect = dev_tools.get_panel_rect();
assert_eq!(panel_rect.position.x + panel_rect.size.x, 1280.0);
assert_eq!(panel_rect.position.y + panel_rect.size.y, 720.0);생성. (숨긴 채, Node Hierarchy 탭, 저장한 설정을 읽는다)
- 패널 810x520, 왼쪽 칸 너비 405. 설정은 로컬 스토리지 "hierarchy.settings" 에서 읽고, 없거나 JSON 이 깨졌으면 기본값이다.
Constructor. (hidden, Node Hierarchy tab, reads the saved settings)
- Panel 810x520, left column width 405. Settings are read from local storage "hierarchy.settings", and are the defaults if missing or the JSON is broken.
반환ReturnsDevTools 루트가 없는 새 개발자 도구. (set_root_nodes 로 트리 루트를 건다)New developer tools with no roots. (set the tree roots with set_root_nodes)
짝Counterpart: vanilla.js DevTools.constructor
루트 노드 목록 설정. (루트는 펼친 채로 둔다)
Sets the root node list. (roots stay expanded)
- root_idsVec<NodeId>
- 트리 맨 위에 보일 노드 목록. (차례대로)List of nodes shown at the top of the tree. (in order)
짝Counterpart: vanilla.js DevTools.setRootNodes
표시 여부 반환.
Returns the visibility.
반환Returnsbool 패널이 보이면 true.true if the panel is visible.
짝Counterpart: vanilla.js DevTools.isVisible
보이기와 숨기기. (F2 와 같다. 보일 때 패널을 창 오른쪽 아래에 붙이고, 모든 기즈모 설정을 건다)
- 모든 기즈모 강제 표시는 tick 끝이나 다음 draw 첫머리 가운데 먼저 오는 때에 Graphic 에 건다. 숨길 때는 기다리던 로컬 스토리지 질문을 닫는다.
Shows and hides. (same as F2. When shown, docks the panel at the bottom right of the window and applies the all-gizmos setting)
- Forced display of all gizmos is applied to Graphic at the end of tick or at the start of the next draw, whichever comes first. When hiding, closes a pending local storage question.
- engine&Engine
- 창 안쪽 논리 크기를 읽을 엔진.Engine to read the window's inner logical size from.
- is_visiblebool
- 참이면 보이고, 거짓이면 숨긴다.Shows if true, hides if false.
짝Counterpart: vanilla.js DevTools.setVisible
지금 탭 반환. (0 Statistics, 1 Node Hierarchy, 2 Local Storage, 3 Settings)
Returns the current tab. (0 Statistics, 1 Node Hierarchy, 2 Local Storage, 3 Settings)
반환Returnsusize 탭 번호. (0 ~ 3, 처음 1)Tab number. (0 ~ 3, initially 1)
짝Counterpart: vanilla.js DevTools.getActiveTab
탭 설정. (없는 탭이면 무시)
Sets the tab. (ignored if no such tab)
- tab_indexusize
- 탭 번호. (0 Statistics, 1 Node Hierarchy, 2 Local Storage, 3 Settings, 4 이상은 무시)Tab number. (0 Statistics, 1 Node Hierarchy, 2 Local Storage, 3 Settings, 4 or more is ignored)
짝Counterpart: vanilla.js DevTools.setActiveTab
고른 노드 반환.
Returns the selected node.
반환ReturnsOption<NodeId> 인스펙터에 보이는 노드. 고른 것이 없으면 None. (고른 노드가 지워지면 다음 tick 에 None 이 된다)The node shown in the inspector. None if nothing is selected. (becomes None on the next tick if the selected node is deleted)
짝Counterpart: vanilla.js DevTools.getSelectedNode
노드 고르기. (인스펙터 스크롤은 맨 위로)
Selects a node. (inspector scroll goes to the top)
- node_idOption<NodeId>
- 고를 노드. None 이면 고르지 않은 것으로 돌린다. (조상을 펼치지는 않는다, 펼치려면 inspect_node)Node to select. None returns to no selection. (does not expand ancestors, use inspect_node to expand)
짝Counterpart: vanilla.js DevTools.setSelectedNode
트리에서 노드를 펼쳤는지.
Whether a node is expanded in the tree.
- node_idNodeId
- 볼 노드.Node to look at.
반환Returnsbool 펼쳤으면 true. (set_root_nodes 로 건 루트는 처음부터 펼쳐 있다)true if expanded. (roots set with set_root_nodes start expanded)
짝Counterpart: vanilla.js DevTools.isNodeExpanded
트리에서 노드 펼치기와 접기.
Expands and collapses a node in the tree.
- node_idNodeId
- 펼치거나 접을 노드.Node to expand or collapse.
- is_expandedbool
- 참이면 펼치고, 거짓이면 접는다.Expands if true, collapses if false.
짝Counterpart: vanilla.js DevTools.setNodeExpanded
인스펙터가 컴포넌트 속성을 읽을 문서 설정. (게임이 자기 컴포넌트를 등록한 UIDocument 를 걸면 그 컴포넌트의 속성도 보인다)
Sets the document the inspector reads component properties from. (setting a UIDocument in which the game registered its own components shows those components' properties too)
- ui_documentUIDocument
- 컴포넌트 종류를 등록한 문서. (들고 있던 문서를 바꾼다)Document with component types registered. (replaces the held document)
인스펙터가 컴포넌트 속성을 읽는 문서. (변경용, 컴포넌트 종류를 더 등록할 때)
The document the inspector reads component properties from. (mutable, for registering more component types)
반환Returns&mut UIDocument 들고 있는 문서의 가변 참조. (처음은 UIDocument::new() 에 register_editor_types 를 부른 것)Mutable reference to the held document. (at first UIDocument::new() with register_editor_types called)
패널 영역 반환. (창 안쪽 논리 좌표)
Returns the panel area. (window inner logical coordinates)
반환ReturnsRect 패널 사각형. (창 안쪽 논리 픽셀, 숨겨 있어도 마지막 자리)Panel rectangle. (window inner logical pixels, the last position even when hidden)
짝Counterpart: vanilla.js DevTools.getPanelRect
현재 터치 위치가 패널 내부에 있는지 반환.
Returns whether the current touch position is inside the panel.
- engine&Engine
- 입력 위치(창 안쪽 논리 좌표)를 읽을 엔진.Engine to read the input position (window inner logical coordinates) from.
반환Returnsbool 패널이 보이고 입력 위치가 패널 안(경계 포함)이면 true. 숨겨 있으면 늘 false.true if the panel is visible and the input position is inside the panel (boundary included). Always false when hidden.
짝Counterpart: vanilla.js DevTools.isPointerInsidePanel
갱신. (F2 토글, 트리 목록, 터치)
- 검사 부탁(입력 필드 문맥 메뉴의 검사)이 있으면 먼저 그 노드를 검사한다. 숨겨 있으면 F2 만 본다.
- 보일 때는 지운 노드를 고른 것에서 빼고, 트리 목록과 &mut self 게터 값을 다시 읽고, 로컬 스토리지 질문의 답을 받고, 누름, 끌기, 뗌을 처리한다.
- 끝에 바뀐 모든 기즈모 강제 표시를 엔진의 그래픽에 건다. (원본처럼 그 프레임의 그리기부터 보인다, 그래픽이 없으면 다음 draw 첫머리에 건다)
Update. (F2 toggle, tree list, touch)
- If there is an inspect request (Inspect in the input field context menu), inspects that node first. When hidden, only checks F2.
- When visible, removes deleted nodes from the selection, rereads the tree list and the &mut self getter values, receives the answer to the local storage question, and handles press, drag, and release.
- At the end, applies a changed forced display of all gizmos to the engine's graphic. (as in the original it shows from that frame's drawing; without a graphic it is applied at the start of the next draw)
- engine&Engine
- 입력과 뷰를 읽고 질문 창을 띄울 엔진.Engine to read input and view from and to open question dialogs with.
- node_tree&mut NodeTree
- 트리에 보일 노드 트리. (A, G 칸을 누르면 노드의 액티브와 기즈모를 바꾼다)Node tree to show in the tree. (clicking the A, G columns toggles the node's active and gizmo)
- _time_deltaf64
- 지난 프레임부터 흐른 시간. (초, 쓰지 않는다. 원본처럼 시간 배율을 거치지 않은 값을 넘긴다)Time elapsed since the last frame. (seconds, unused. As in the original, pass the value not scaled by the time scale)
짝Counterpart: vanilla.js DevTools.tick
노드 검사. (보이고, Node Hierarchy 탭으로, 조상을 펼치고 그 노드를 고른다)
Inspects a node. (shows the panel, switches to the Node Hierarchy tab, expands the ancestors, and selects that node)
- engine&Engine
- 패널을 처음 보일 때 창 크기를 읽을 엔진.Engine to read the window size from when the panel is first shown.
- node_tree&NodeTree
- 조상을 찾을 노드 트리.Node tree to find the ancestors in.
- node_idNodeId
- 검사할 노드. (그 노드 자신은 펼치지 않는다)Node to inspect. (the node itself is not expanded)
짝Counterpart: vanilla.js DevTools.inspectNode
출력. (창 안쪽 논리 좌표로 그리고, 끝나면 들어올 때의 그리기 상태로 돌린다)
- tick 밖에서 바꿔 아직 걸지 않은 모든 기즈모 강제 표시 값을 먼저 Graphic 에 건다. 숨겨 있으면 FPS 표시만 그리고 돌아간다.
Draws. (draws in the window's inner logical coordinates, and when done restores the drawing state it came in with)
- First applies to Graphic a forced display of all gizmos that was changed outside tick and not applied yet. If hidden, draws only the FPS display and returns.
- engine&Engine
- 통계와 뷰 정보를 읽을 엔진.Engine to read statistics and view info from.
- node_tree&NodeTree
- 트리와 인스펙터에 보일 노드 트리.Node tree to show in the tree and the inspector.
- graphic&mut Graphic
- 그릴 그래픽. (씬의 post_draw 처럼 다른 것을 다 그린 뒤)Graphic to draw to. (after everything else is drawn, like the scene's post_draw)
짝Counterpart: vanilla.js DevTools.draw
FPS 표시 여부 반환. (Settings 의 Show FPS, 켜지면 draw 가 패널을 닫아도 창 왼쪽 위에 FPS 를 그린다)
Returns whether FPS is shown. (Show FPS in Settings, when on, draw draws the FPS at the top left of the window even when the panel is closed)
반환Returnsbool Settings 탭의 FPS 표시가 켜져 있으면 true. (DevTools 는 스스로 그리지 않는다, 씬이 보고 그린다)true if the FPS display in the Settings tab is on. (DevTools does not draw it itself, the scene checks this and draws it)
짝Counterpart: vanilla.js DevTools.isFramePerSecondVisible