ui/uidocument
UI 문서. (vanilla.js ui/uidocument.js 의 UIDocument)
- 노드 트리를 JSON 문서(.scene.json)로 내보내고 읽는다. vanilla.js 비주얼 에디터(tools/visualeditor)가 이 꼴로 씬을 저장하고, 게임은 같은 파일을 읽어 NodeTree 에 노드와 컴포넌트를 짓는다. 러스트에서 지은 트리도 같은 꼴로 내보낸다.
- 문서는 { "version": 1, "root": 노드 } 이고, 노드는 type, name, active, position, scale, rotation, opacity, pivot, anchor, contentSize, interactable, components, children 이다. 위젯(content 노드를 만드는 컴포넌트)이 있으면 content 안의 자식만 contentChildren 으로 따로 둔다. 에디터가 얹는 frameSize 같은 모르는 키는 무시한다. 키 차례와 들여쓰기(탭)는 원본 JSON.stringify 와 같게 쓴다. (serde_json preserve_order)
- 원본과 다른 것:
- 원본은 정적 클래스와 모듈 전역 표다. 러스트 판은 표를 든 UIDocument 값을 만들어 쓴다. (엔진처럼 전역 상태를 두지 않는다) new 가 엔진 컴포넌트를 등록해 둔다.
- 원본처럼 쓰기, 읽기 함수(원본 COMPONENT_PROPERTY_TABLE 의 propertyHandler)가 없는 종류는 반사로 쓰고 읽는다. (saveByReflection, loadByReflection) 원본은 실행 중에 객체의 get, is, set 함수를 훑고, 러스트 판은
#[reflect]매크로가 컴파일 때 지은 목록을 쓴다. (core/reflection.rs) 반사로 다루는 종류는#[reflect]를 붙인 컴포넌트뿐이다. (엔진 컴포넌트는 모두 붙였다) 원본은 모든 객체가 반사된다. 원본 표에서 반사로 저장하는 Outline, SoftShade, ShadowText, UIProgressRing 도 반사로 쓰고 읽는다. 원본 반사 결과와 같은 키(머리 대문자: Color, LineWidth, GizmoVisible, Enable, ComponentType 등)와 차례다. 원본 ShadowText 의 FontFace 는 글꼴 객체라 적히지 않는다. 러스트 판의 글꼴 이름 글(get_font_family)은#[reflect(unsaved)]로 속성 목록에는 두고 저장에서 뺐다. - 트리를 받는 반사 세터(UISnapScrollView 의 SnapCurrentIndex 같은 것)도 원본처럼 읽는 그 자리에서 부른다. 읽는 컴포넌트를 트리에서 잠깐 꺼내 읽기 문맥에 트리를 쥐여 준다.
- &mut self 게터가 있는 컴포넌트도 to_json_text, serialize_node 가 &mut 갈래로 미리 읽어 적는다. (원본 게터에는 &self, &mut self 구별이 없어 원본 toJsonText, serializeNode 처럼 한 함수다. 트리는 가변으로 받는다)
- 종류 등록: register_component_type(이름, 짓는 함수)은 원본 registerComponentType 이다. (반사로 쓰고 읽는다) 쓰기, 읽기 함수가 따로 있는 종류는 register_component_type_with_handler 로, 위젯(content 노드를 만드는 컴포넌트)은 register_widget_type, register_widget_type_with_handler 로 등록한다.
- 등록하지 않은 종류는 원본처럼 읽을 때 건너뛰고(노드 종류는 WorldNode 로 읽고) 경고를 낸다. 쓸 때 type 은 원본처럼 등록한 이름이고, 등록하지 않은 종류는 반사로 적고 type 은 타입 이름이다. (원본 constructor.name) 원본처럼 모든 컴포넌트가 반사된다. (Reflect 가 Component 의 상위 트레이트라
#[reflect]를 빠뜨린 컴포넌트는 컴파일되지 않는다) - 쓰기, 읽기 함수가 있는 종류도 원본처럼 노드를 가리키는 반사 속성은 따로 { "$nodeRef": 경로 } 로 얹고 읽는다. (saveNodeReferences, loadNodeReferences)
- ShadowImage 는 원본 표의 끝에도 같은 꼴(imagePath 뒤에 반사 저장 꼴)로 넣어 두 엔진이 같다.
- 원본 UIImageView 는 붙을 때 호스트에 Sprite 를 붙여 문서에 UIImageView 다음 Sprite 가 적힌다. 러스트 판은 Sprite 를 품어서, 품은 Sprite 를 그 자리에 Sprite 로 적고 읽을 때는 뒤따르는 Sprite 를 품은 Sprite 에 읽는다. (set_component_companions, 원본은 UIImageView 가 붙을 때 붙인 Sprite 에 읽는다)
- 원본 노드 종류(WorldNode 하위 클래스, registerNodeType)는 러스트 판에서 노드에 붙는 컴포넌트다. register_node_type 으로 등록하면 원본 문서와 같은 꼴로 쓰고 읽는다: 그 컴포넌트가 붙은 노드의 type 이 그 이름이고 컴포넌트 목록에는 적지 않는다.
- 원본 노드 생성자처럼 붙을 때 자식과 컴포넌트를 실제로 짓는 종류(UIWindow, UIConfirmWindow, UIDialog, UIDropdown, UIToast, UISpinner, UIContextMenu 등)는 지은 것이 그대로 적힌다.
- 스스로 그리는 종류(UIInputField, UIScrollBar)는 UIDocumentNode 가 원본 생성자의 몫을 원본 꼴로 적고, 읽을 때는 그 몫을 설정으로 읽는다.
- 원본은 숨을 때 노드를 끄지만 러스트 판은 tick 이 돌아야 해서 숨기기만 하는 종류(UIToast)는 UIDocumentNode 가 active 를 원본 뜻으로 바꿔 쓰고 읽는다.
- 읽을 때 노드에 이미 있는 컴포넌트와 자식(노드 종류나 위젯이 붙을 때 지은 것, require 로 함께 붙은 것)은 문서의 앞에서부터 차례와 종류(자식은 이름)가 맞으면 그것에 문서 값을 넣고 다시 짓지 않는다. (원본 fillNode 와 같다) 다시 쓰면 같은 문서다.
- 원본 에디터(tools/uieditor)는 엔진이 내보내는 모든 Component 와 WorldNode 하위 클래스를 등록해 문서에 적는다. 원본처럼 기본 표에는 없고, 게임이 register_editor_types(원본 registerEditorTypes) 한 줄로 같은 종류(컴포넌트 35, 노드 종류 12)를 등록한다. (종류마다 한 줄로도 된다)
- 러스트 판의 노드는 WorldNode 하나다. 노드 종류로 등록한 컴포넌트가 없는 노드의 type 은 늘 "WorldNode" 로 적고, 등록하지 않은 type 은 WorldNode 로 읽는다.
- 원본 getComponentType(이름 → 생성자)은 생성자를 값으로 돌려줄 수 없어(노드 트리는 구체 타입으로 붙인다) create_component(트리, 노드, 이름)가 그 이름의 컴포넌트를 지어 노드에 붙이고 컴포넌트 차례 번호를 돌려준다. (원본에서 생성자를 받아 addComponent 하는 자리)
- 그림 경로(imagePath)는 원본처럼 이미지 해석기(set_image_resolver)로 찾는다. 해석기를 주지 않으면 문서가 든 애셋 창고에서 찾는다. load_images 가 문서의 imagePath 를 ImageAsset 으로 요청하고(받은 읽기 손잡이는 씬이 track_load_handle 로 맡길 수 있다), 아직 읽히지 않은 그림은 bind_pending_images 가 다 읽힌 뒤 붙인다. (러스트 애셋은 요청 뒤 나중에 다 읽힌다)
- 노드 참조($nodeRef)의 기준 뿌리는 to_json_text, from_json_text 의 뿌리다. serialize_node, deserialize_node 를 바로 부르면 그 노드가 뿌리다. (원본은 serializeNode 만 부르면 참조를 적지 않고, deserializeNode 만 부르면 참조를 잇지 않는다)
- 수는 f64 를 가장 짧은 십진으로 적는다. (0.22 는 0.22, 정수는 소수점 없이, 원본 JSON.stringify 와 같다)
- Sprite 의 nineSlice 는 원본이 쓰는 꼴([왼쪽, 위, 왼쪽 + 오른쪽, 위 + 아래], Rect 의 left, top, right, bottom)을 원본처럼 거꾸로 풀어 읽는다.
UI document. (UIDocument of vanilla.js ui/uidocument.js)
- Exports and reads a node tree as a JSON document (.scene.json). The vanilla.js visual editor (tools/visualeditor) saves scenes in this form, and games read the same file and build nodes and components in a NodeTree. Trees built in Rust are exported in the same form too.
- A document is { "version": 1, "root": node }, and a node has type, name, active, position, scale, rotation, opacity, pivot, anchor, contentSize, interactable, components, children. If there is a widget (a component that creates a content node), only the children inside content are kept separately as contentChildren. Unknown keys added by the editor, like frameSize, are ignored. Key order and indentation (tabs) are written the same as the original JSON.stringify. (serde_json preserve_order)
- Differences from the original:
- The original is a static class and module global tables. The Rust version creates and uses a UIDocument value that holds the tables. (no global state, like the engine) new registers the engine components.
- As in the original, types without write and read functions (propertyHandler of the original COMPONENT_PROPERTY_TABLE) are written and read through reflection. (saveByReflection, loadByReflection) The original scans an object's get, is, set functions at run time, while the Rust version uses the list built at compile time by the
#[reflect]macro. (core/reflection.rs) The only types handled through reflection are components with#[reflect]attached. (attached to every engine component) In the original, every object is reflected. Outline, SoftShade, ShadowText, UIProgressRing, which the original table saves through reflection, are also written and read through reflection. Same keys as the original reflection result (capitalized: Color, LineWidth, GizmoVisible, Enable, ComponentType, etc.) and order. FontFace of the original ShadowText is a font object, so it is not written. The Rust version's font name text (get_font_family) is kept in the property list but left out of saving with#[reflect(unsaved)]. - Reflection setters that take the tree (like SnapCurrentIndex of UISnapScrollView) are also called on the spot while reading, as in the original. The component being read is briefly taken out of the tree and the read context is handed the tree.
- Components with &mut self getters are also read ahead through the &mut branch and written by to_json_text and serialize_node. (the original getters make no &self, &mut self distinction, so like the original toJsonText and serializeNode they are single functions. The tree is taken as mutable)
- Type registration: register_component_type(name, builder function) is the original registerComponentType. (written and read through reflection) Types with their own write and read functions are registered with register_component_type_with_handler, and widgets (components that create a content node) with register_widget_type, register_widget_type_with_handler.
- Unregistered types are skipped when reading (node types are read as WorldNode) with a warning, as in the original. When writing, type is the registered name as in the original, and unregistered types are written by reflection with the type name as type. (the original constructor.name) Like the original, every component is reflected. (Reflect is a supertrait of Component, so a component without
#[reflect]does not compile) - Even for types with write and read functions, reflection properties that point to nodes are added and read separately as { "$nodeRef": path }, as in the original. (saveNodeReferences, loadNodeReferences)
- ShadowImage is also added at the end of the original table in the same form (the reflection save form after imagePath), so both engines are the same.
- The original UIImageView attaches a Sprite to the host on attach, so the document has a Sprite after UIImageView. The Rust version embeds the Sprite, so it writes the embedded Sprite there as a Sprite and when reading, it reads the following Sprite into the embedded Sprite. (set_component_companions, the original reads into the Sprite that UIImageView attached when it was attached)
- Original node types (WorldNode subclasses, registerNodeType) are components attached to nodes in the Rust version. Registered with register_node_type, they are written and read in the same form as the original document: the type of a node with that component attached is that name, and it is not listed in the component list.
- Types that actually build children and components on attach like the original node constructor (UIWindow, UIConfirmWindow, UIDialog, UIDropdown, UIToast, UISpinner, UIContextMenu, etc.) have what they built written as is.
- For self-drawing types (UIInputField, UIScrollBar), UIDocumentNode writes the original constructor's share in the original form, and reads that share back as settings.
- The original turns the node off when hiding, but for types that only hide because tick must keep running in the Rust version (UIToast), UIDocumentNode converts active to the original meaning when writing and reading.
- When reading, components and children already on the node (built when a node type or widget was attached, or attached together through require) are matched from the front of the document by order and type (name for children), and if they match, the document values are put into them without building them again. (same as the original fillNode) Writing again gives the same document.
- The original editor (tools/uieditor) registers every Component and WorldNode subclass the engine exports and writes them to documents. As in the original, they are not in the default table, and the game registers the same types (35 components, 12 node types) with one line, register_editor_types (the original registerEditorTypes). (one line per type also works)
- Nodes in the Rust version are just WorldNode. The type of a node without a component registered as a node type is always written as "WorldNode", and unregistered types are read as WorldNode.
- The original getComponentType (name → constructor) cannot return a constructor as a value (the node tree attaches by concrete type), so create_component(tree, node, name) builds the component of that name, attaches it to the node, and returns the component order index. (in place of taking a constructor and calling addComponent in the original)
- The image path (imagePath) is resolved with the image resolver (set_image_resolver) as in the original. Without a resolver, it is looked up in the asset store the document holds. load_images requests the document's imagePath values as ImageAsset (the scene can hand over the received load handles with track_load_handle), and images not loaded yet are attached by bind_pending_images once fully loaded. (Rust assets finish loading some time after the request)
- The base root of node references ($nodeRef) is the root of to_json_text, from_json_text. When serialize_node, deserialize_node are called directly, that node is the root. (in the original, calling only serializeNode does not write references, and calling only deserializeNode does not connect them)
- Numbers are written as the shortest decimal of f64. (0.22 as 0.22, integers without a decimal point, the same as the original JSON.stringify)
- Sprite nineSlice is read by reversing the form the original writes ([left, top, left + right, top + bottom], Rect's left, top, right, bottom), as in the original.
UIDocumentNodePartsstruct traits Default
원본 노드 생성자가 만드는 컴포넌트와 자식의 문서 값. (그 노드의 components, children 앞에 들어간다)
- UIDocumentNode::save_node_parts 가 돌려주고, UIDocument 가 노드 문서 값의 앞머리에 그대로 넣는다.
Document values of the components and children that the original node constructor creates. (placed at the front of that node's components and children)
- Returned by UIDocumentNode::save_node_parts, and UIDocument puts them as is at the head of the node's document value.
use serde_json::{Map, Value};
use vanilla::ui::uidocument::UIDocumentNodeParts;
let mut node_parts = UIDocumentNodeParts::new();
let mut paint_data = Map::new();
paint_data.insert(String::from("roundSize"), Value::from(4));
paint_data.insert(String::from("type"), Value::from("Paint"));
node_parts.component_data_list.push(paint_data);
node_parts.child_data_list.push(serde_json::json!({ "type": "WorldNode", "name": "thumb" }));
assert_eq!(node_parts.component_data_list[0]["type"], "Paint");
assert_eq!(node_parts.child_data_list[0]["name"], "thumb");빈 몫. (생성자가 아무것도 만들지 않는 노드 종류)
Empty parts. (node kinds whose constructor creates nothing)
반환ReturnsUIDocumentNodeParts 두 목록이 다 빈 몫.Parts with both lists empty.
노드의 components 앞에 들어갈 컴포넌트 문서 값. (값마다 "type" 키를 스스로 담는다)
Component document values placed at the front of the node's components. (each value carries its own "type" key)
반환ReturnsVec<Map<String, Value>>
노드의 children 앞에 들어갈 자식 노드 문서 값.
Child node document values placed at the front of the node's children.
반환ReturnsVec<Value>
UIDocumentNodetrait
원본 노드 종류(WorldNode 하위 클래스)를 맡은 컴포넌트. (register_node_type 으로 등록한다)
- 원본은 그 노드의 생성자가 스스로 컴포넌트와 자식을 만들고, 문서에는 그것들이 보통 컴포넌트와 자식으로 적힌다. 러스트 판의 컴포넌트는 그것을 스스로 그리거나 품으므로, 쓸 때는 원본이 적을 꼴로 적고 읽을 때는 그 몫을 설정으로 읽고 다시 짓지 않는다.
- 생성자가 아무것도 만들지 않는 종류는 빈 구현(impl UIDocumentNode for 타입 {})으로 된다.
A component that stands in for an original node kind (a WorldNode subclass). (registered with register_node_type)
- In the original, that node's constructor creates its components and children itself, and the document records them as ordinary components and children. The Rust version's component draws or holds them itself, so when writing it writes them in the form the original would, and when reading it reads those parts as settings and does not build it again.
- Kinds whose constructor creates nothing get an empty implementation (impl UIDocumentNode for Type {}).
use serde_json::{Map, Value};
use vanilla::{Color, Component, ComponentBase, NodeId, NodeTree, Paint, UIDocument, UIDocumentSaveContext};
use vanilla::ui::uidocument::{UIDocumentNode, UIDocumentNodeParts};
struct Badge {
component_base: ComponentBase,
color: Color,
}
#[vanilla::reflect]
impl Badge {}
#[vanilla::reflect]
impl Component for Badge {
fn get_component_base(&self) -> &ComponentBase {
&self.component_base
}
fn get_component_base_mut(&mut self) -> &mut ComponentBase {
&mut self.component_base
}
fn get_component_type(&self) -> &'static str {
"Badge"
}
}
impl UIDocumentNode for Badge {
fn save_node_parts(&self, _save_context: &UIDocumentSaveContext, _node_id: NodeId) -> UIDocumentNodeParts {
let mut paint_data = Map::new();
paint_data.insert(String::from("color"), UIDocument::color_to_array(self.color));
paint_data.insert(String::from("type"), Value::from("Paint"));
let mut node_parts = UIDocumentNodeParts::new();
node_parts.component_data_list.push(paint_data);
node_parts
}
fn load_node_parts(&mut self, component_data_list: &[Value], _child_data_list: &[Value]) -> (usize, usize) {
match component_data_list.first().and_then(|component_data| UIDocument::array_to_color(&component_data["color"])) {
Some(color) => {
self.color = color;
(1, 0)
}
None => {
(0, 0)
}
}
}
}
fn create_badge() -> Badge {
Badge {
component_base: ComponentBase::new(),
color: Color::create(1.0, 1.0, 1.0, 1.0),
}
}
let mut document = UIDocument::new();
document.register_node_type("Badge", create_badge);
let mut node_tree = NodeTree::new();
let badge_id = node_tree.create_node("badge");
node_tree[badge_id].add_component(create_badge()).color = Color::create(1.0, 0.0, 0.0, 1.0);
let json_text = document.to_json_text(&mut node_tree, badge_id, false);
let document_data: Value = serde_json::from_str(&json_text).expect("json");
assert_eq!(document_data["root"]["type"], "Badge");
assert_eq!(document_data["root"]["components"][0]["type"], "Paint");
let loaded_id = document.from_json_text(&mut node_tree, &json_text).expect("document");
assert_eq!(node_tree[loaded_id].get_component::<Badge>().expect("badge").color, Color::create(1.0, 0.0, 0.0, 1.0));
assert!(node_tree[loaded_id].get_component::<Paint>().is_none());fn save_node_parts(&self, _save_context: &UIDocumentSaveContext, _node_id: NodeId) -> UIDocumentNodeParts#원본 노드 생성자가 만드는 컴포넌트와 자식을 문서 꼴로. (node_id 는 이 컴포넌트가 붙은 노드)
The components and children that the original node constructor creates, in document form. (node_id is the node this component is attached to)
- _save_context&UIDocumentSaveContext
- 쓰기 문맥. (몫의 컴포넌트 값을 쓸 때 노드 참조 경로의 기준이 된다)Write context. (the base of node reference paths when writing the parts' component values)
- _node_idNodeId
- 이 컴포넌트가 붙은 노드.The node this component is attached to.
반환ReturnsUIDocumentNodeParts 원본 생성자가 만들었을 컴포넌트와 자식의 문서 값. (기본은 빈 몫)Document values of the components and children the original constructor would have created. (default is empty parts)
fn load_node_parts(&mut self, _component_data_list: &[Value], _child_data_list: &[Value]) -> (usize, usize)#문서의 컴포넌트와 자식 목록 앞머리에서 원본 노드 생성자가 만든 몫을 읽어 넣는다. (읽은 컴포넌트 수와 자식 수, 그 몫은 짓지 않는다)
Reads in the parts that the original node constructor created from the head of the document's component and child lists. (the number of components and children read, those parts are not built)
- _component_data_list&[Value]
- 문서 노드의 components 전체.All components of the document node.
- _child_data_list&[Value]
- 문서 노드의 children 전체.All children of the document node.
반환Returns(usize, usize) (앞에서부터 읽은 컴포넌트 수, 읽은 자식 수). UIDocument 는 그만큼을 짓지 않고 건너뛴다. (기본 (0, 0))(number of components read from the front, number of children read). UIDocument skips building that many. (default (0, 0))
문서에 적지 않는 content 노드. (러스트 판이 위젯처럼 만드는 것, 원본 노드에는 없다. 그 안의 자식은 contentChildren 으로 적는다)
A content node not written to the document. (something the Rust version creates like a widget, not in the original node. Its children are written as contentChildren)
반환ReturnsOption<NodeId> 문서에 적지 않을 content 노드. 없으면 None. (기본 None)The content node not to write to the document. None if none. (default None)
원본 노드의 active. (원본은 숨을 때 노드를 끄고, 러스트 판은 tick 이 돌아야 해서 끄는 대신 숨기는 종류가 있다. 기본은 노드의 active)
The original node's active. (the original turns the node off when hiding, and some kinds in the Rust version hide instead of turning off because tick has to run. Default is the node's active)
- is_node_activebool
- 노드의 active.The node's active.
- _is_node_visiblebool
- 노드의 보임.The node's visibility.
반환Returnsbool 문서에 적을 active.The active to write to the document.
원본 active 를 이 종류의 노드 상태로. (노드의 active 와 바꿀 보임, 기본은 그대로이고 보임은 두다)
The original active as this kind's node state. (the node's active and the visibility to change, default is unchanged and visibility is left alone)
- is_activebool
- 문서에 적힌 active.The active written in the document.
반환Returns(bool, Option<bool>) (노드에 넣을 active, 노드에 넣을 보임). 보임이 None 이면 보임을 바꾸지 않는다. (기본 (is_active, None))(active to set on the node, visibility to set on the node). If visibility is None, visibility is not changed. (default (is_active, None))
UIDocumentSaveContextstruct
쓰기 문맥. (컴포넌트 쓰기 함수가 받는다. 노드 참조를 뿌리 기준 경로로 적는다)
- 바깥에서 짓지 않는다. register_component_type_with_handler 로 등록한 쓰기 함수와 UIDocumentNode::save_node_parts 가 받는다.
Write context. (received by component write functions. Writes node references as paths from the root)
- Not built from outside. Received by write functions registered with register_component_type_with_handler and by UIDocumentNode::save_node_parts.
use serde_json::{Map, Value};
use vanilla::{Component, ComponentBase, NodeId, NodeTree, UIDocument, UIDocumentLoadContext, UIDocumentSaveContext};
struct Follow {
component_base: ComponentBase,
target: Option<NodeId>,
}
#[vanilla::reflect]
impl Follow {}
#[vanilla::reflect]
impl Component for Follow {
fn get_component_base(&self) -> &ComponentBase {
&self.component_base
}
fn get_component_base_mut(&mut self) -> &mut ComponentBase {
&mut self.component_base
}
fn get_component_type(&self) -> &'static str {
"Follow"
}
}
fn create_follow() -> Follow {
Follow {
component_base: ComponentBase::new(),
target: None,
}
}
fn save_follow(follow: &Follow, save_context: &UIDocumentSaveContext) -> Map<String, Value> {
let mut component_data = Map::new();
save_context.write_node_reference(&mut component_data, "target", follow.target);
component_data
}
fn load_follow(_follow: &mut Follow, _component_data: &Map<String, Value>, _load_context: &mut UIDocumentLoadContext) {
}
let mut document = UIDocument::new();
document.register_component_type_with_handler("Follow", create_follow, save_follow, load_follow);
let mut node_tree = NodeTree::new();
let root_id = node_tree.create_node("root");
let leader_id = node_tree.create_child(root_id, "leader");
let follower_id = node_tree.create_child(root_id, "follower");
node_tree[follower_id].add_component(create_follow()).target = Some(leader_id);
let json_text = document.to_json_text(&mut node_tree, root_id, false);
let document_data: Value = serde_json::from_str(&json_text).expect("json");
let component_data = &document_data["root"]["children"][1]["components"][0];
assert_eq!(component_data["target"]["$nodeRef"], "/leader");
assert_eq!(component_data["type"], "Follow");노드 트리.
Node tree.
반환Returns&NodeTree 쓰는 중인 노드 트리.The node tree being written.
쓰는 중인 노드.
The node being written.
반환ReturnsNodeId 쓰는 중인 노드. (serialize_component 로 부르면 root_id)The node being written. (root_id when called via serialize_component)
pub fn write_node_reference(&self, component_data: &mut Map<String, Value>, property_name: &str, node_id: Option<NodeId>)#노드 참조 적기. ({ "$nodeRef": 뿌리 기준 경로 }, None 이거나 뿌리 밖의 노드면 적지 않는다. 원본 saveNodeReferences)
Writes a node reference. ({ "$nodeRef": path from the root }, not written if None or a node outside the root. Original saveNodeReferences)
- component_data&mut Map<String, Value>
- 값을 넣을 컴포넌트 문서 값.Component document value to put the value into.
- property_name&str
- 넣을 키.Key to put.
- node_idOption<NodeId>
- 가리킬 노드. None 이거나 뿌리 밖이면 키를 넣지 않는다.Node to point to. If None or outside the root, the key is not put.
pub fn write_image_path(&self, component_data: &mut Map<String, Value>, image_path: &str, image: Option<&Rc<Image>>)#그림 경로 적기. ("imagePath" 에 경로를 적고, 경로가 비지 않았고 그림이 있으면 그 그림을 경로로 기억한다. 원본 serializeNode 의 #rememberSerializedImage)
- 기억한 그림은 같은 문서로 다시 읽을 때 해석기나 load_images 가 찾지 못하면 넣는다. (UIListView::set_template_node 처럼 같은 문서로 적고 읽어 복제하면 본의 그림을 그대로 쓴다)
Writes an image path. (writes the path to "imagePath", and when the path is not empty and there is an image, remembers that image by path. The original serializeNode #rememberSerializedImage)
- A remembered image is put in when the same document reads it back and the resolver or load_images does not find one. (a copy written and read with the same document, as UIListView::set_template_node does, uses the original's image)
- component_data&mut Map<String, Value>
- 값을 넣을 컴포넌트 문서 값.Component document value to put the value into.
- image_path&str
- 그림 경로. (빈 글도 적는다)Image path. (an empty string is also written)
- imageOption<&Rc<Image>>
- 컴포넌트에 든 그림. (None 이면 기억하지 않는다)Image in the component. (not remembered if None)
UIDocumentLoadContextstruct
읽기 문맥. (컴포넌트 읽기 함수가 받는다. 그림과 노드 참조는 여기에 맡겨 두고 트리를 다 지은 뒤에 넣는다)
- 바깥에서 짓지 않는다. register_component_type_with_handler 로 등록한 읽기 함수가 받는다.
Read context. (received by component read functions. Images and node references are left here and put in after the whole tree is built)
- Not built from outside. Received by read functions registered with register_component_type_with_handler.
use serde_json::{Map, Value};
use vanilla::{Component, ComponentBase, NodeId, NodeTree, UIDocument, UIDocumentLoadContext, UIDocumentSaveContext};
struct Follow {
component_base: ComponentBase,
target: Option<NodeId>,
}
#[vanilla::reflect]
impl Follow {}
#[vanilla::reflect]
impl Component for Follow {
fn get_component_base(&self) -> &ComponentBase {
&self.component_base
}
fn get_component_base_mut(&mut self) -> &mut ComponentBase {
&mut self.component_base
}
fn get_component_type(&self) -> &'static str {
"Follow"
}
}
fn create_follow() -> Follow {
Follow {
component_base: ComponentBase::new(),
target: None,
}
}
fn save_follow(follow: &Follow, save_context: &UIDocumentSaveContext) -> Map<String, Value> {
let mut component_data = Map::new();
save_context.write_node_reference(&mut component_data, "target", follow.target);
component_data
}
fn load_follow(_follow: &mut Follow, component_data: &Map<String, Value>, load_context: &mut UIDocumentLoadContext) {
load_context.bind_node_reference(component_data.get("target"), |follow: &mut Follow, node_id: NodeId| {
follow.target = Some(node_id);
});
}
let mut document = UIDocument::new();
document.register_component_type_with_handler("Follow", create_follow, save_follow, load_follow);
let json_text = r#"{"version":1,"root":{"name":"root","children":[
{"name":"leader"},
{"name":"follower","components":[{"target":{"$nodeRef":"/leader"},"type":"Follow"}]}
]}}"#;
let mut node_tree = NodeTree::new();
let root_id = document.from_json_text(&mut node_tree, json_text).expect("document");
let leader_id = node_tree.find_child_by_name(root_id, "leader").expect("leader");
let follower_id = node_tree.find_child_by_name(root_id, "follower").expect("follower");
assert_eq!(node_tree[follower_id].get_component::<Follow>().expect("follow").target, Some(leader_id));노드 트리. (읽는 컴포넌트는 트리에서 잠깐 꺼낸 채다. 그 자리에는 빈 자리표가 있다)
Node tree. (the component being read is temporarily taken out of the tree. An empty placeholder sits in its place)
반환Returns&mut NodeTree 노드 트리의 가변 참조. (읽는 컴포넌트는 get_component 로 찾을 수 없다)Mutable reference to the node tree. (the component being read cannot be found with get_component)
짓는 중인 노드.
The node being built.
반환ReturnsNodeId 읽는 컴포넌트가 붙은 노드.The node the component being read is attached to.
pub fn bind_image<T: Component + 'static>(&mut self, image_path: &str, read_image_path: fn(&T) -> &str, read_image: fn(&T) -> Option<&Rc<Image>>, apply_image: fn(&mut T, Rc<Image>))#그림 맡기기. (경로의 그림을 찾으면 apply_image 로 이 컴포넌트에 넣는다. 원본 UIDocument.resolveImage + setImage)
- 지금 찾을 수 있는 그림은 트리를 다 지은 자리에서, 아직 읽히는 그림은 bind_pending_images 에서 넣는다.
- 넣기 전에 read_image_path, read_image 로 그 자리를 본다. 그사이 게임이 그림을 넣었거나 경로를 바꿨으면 넣지 않고 버린다. (원본 bindPendingImages)
Leaves an image. (when the image at the path is found, puts it into this component with apply_image. Original UIDocument.resolveImage + setImage)
- Images that can be found now are put in once the whole tree is built, and images still loading are put in by bind_pending_images.
- Before putting it in, checks that slot with read_image_path and read_image. If the game set an image or changed the path in the meantime, it is dropped without being put in. (original bindPendingImages)
- image_path&str
- 그림 경로. (빈 글이면 맡기지 않는다)Image path. (not left if an empty string)
- read_image_pathfn(&T) -> &str
- 컴포넌트의 지금 그림 경로를 읽는 함수. (예: Sprite::get_image_path)Function that reads the component's current image path. (for example Sprite::get_image_path)
- read_imagefn(&T) -> Option<&Rc<Image>>
- 컴포넌트의 지금 그림을 읽는 함수. (예: Sprite::get_image)Function that reads the component's current image. (for example Sprite::get_image)
- apply_imagefn(&mut T, Rc<Image>)
- 찾은 그림을 컴포넌트에 넣는 함수. (그 자리의 컴포넌트가 T 가 아니면 부르지 않는다)Function that puts the found image into the component. (not called if the component in that slot is not T)
pub fn bind_node_reference<T: Component + 'static>(&mut self, stored_value: Option<&Value>, apply_node: fn(&mut T, NodeId))#노드 참조 맡기기. (값이 { "$nodeRef": 경로 } 면 트리를 다 지은 뒤 그 노드를 apply_node 로 넣는다. 원본 loadNodeReferences)
Leaves a node reference. (if the value is { "$nodeRef": path }, puts that node in with apply_node after the whole tree is built. Original loadNodeReferences)
- stored_valueOption<&Value>
- 문서의 그 키 값. None 이거나 { "$nodeRef": 경로 } 꼴이 아니면 맡기지 않는다.The document's value for that key. Not left if None or not in { "$nodeRef": path } form.
- apply_nodefn(&mut T, NodeId)
- 찾은 노드를 컴포넌트에 넣는 함수. (경로의 노드를 찾지 못하거나 그 자리의 컴포넌트가 T 가 아니면 부르지 않는다)Function that puts the found node into the component. (not called if the node at the path is not found or the component in that slot is not T)
UIDocumentstruct traits Default
UI 문서. (WorldNode 트리 ↔ JSON 상호 변환)
- 종류 표(컴포넌트 종류, 노드 종류)와 그림 찾기 상태를 든다. 쓸 때는 &self, 읽을 때는 &mut self 다.
UI document. (WorldNode tree ↔ JSON conversion)
- Holds the kind tables (component kinds, node kinds) and the image lookup state. Writing takes &self, reading takes &mut self.
use vanilla::{Color, NodeTree, Paint, UIDocument, Vector2};
let mut node_tree = NodeTree::new();
let panel_id = node_tree.create_node("panel");
node_tree[panel_id].set_content_size(Vector2::create(320.0, 200.0));
node_tree[panel_id].add_component(Paint::new()).set_color(Color::create(0.2, 0.4, 0.8, 1.0));
node_tree.create_child(panel_id, "title");
let mut document = UIDocument::new();
let json_text = document.to_json_text(&mut node_tree, panel_id, true);
let loaded_id = document.from_json_text(&mut node_tree, &json_text).expect("document");
assert_eq!(node_tree[loaded_id].get_content_size(), Vector2::create(320.0, 200.0));
assert_eq!(node_tree[loaded_id].get_component::<Paint>().expect("paint").get_color(), Color::create(0.2, 0.4, 0.8, 1.0));
assert!(node_tree.find_child_by_name(loaded_id, "title").is_some());
assert_eq!(document.to_json_text(&mut node_tree, loaded_id, true), json_text);use vanilla::{NodeTree, UIDocument};
let json_text = std::fs::read_to_string("examples/assets/scenedocument.scene.json").expect("scene file");
let mut node_tree = NodeTree::new();
let mut document = UIDocument::new();
let scene_root_id = document.from_json_text(&mut node_tree, &json_text).expect("document");
let root_id = node_tree.get_root_id();
node_tree.add_child(root_id, scene_root_id);
assert_eq!(node_tree.get_parent_id(scene_root_id), Some(root_id));
assert!(node_tree.find_child_by_name(scene_root_id, "Panel").is_some());생성. (원본 표의 엔진 컴포넌트를 등록해 둔다)
Constructor. (registers the engine components of the original table)
반환ReturnsUIDocument 엔진 컴포넌트(Paint, Sprite, Text, RichText, Mask, Outline, SoftShade, ShadowText, UIProgressRing, UILabel, UIImageView, UIButton, UIToggleButton, UIProgressView, UISlider, UIScrollView, ShadowImage)를 등록한 새 문서. 노드 종류는 없고 이미지 해석기도 없다.A new document with the engine components (Paint, Sprite, Text, RichText, Mask, Outline, SoftShade, ShadowText, UIProgressRing, UILabel, UIImageView, UIButton, UIToggleButton, UIProgressView, UISlider, UIScrollView, ShadowImage) registered. No node kinds and no image resolver.
짝Counterpart: vanilla.js UIDocument.constructor
컴포넌트의 편집할 수 있는 속성 목록. (원본 getReflectedProperties, 짝이 맞는 get 또는 is 와 set. 다른 객체를 가리키는 이름은 뺀다)
List of the component's editable properties. (original getReflectedProperties, matching get or is and set pairs. Names pointing to other objects are excluded)
- component&dyn Component
- 속성을 볼 컴포넌트.Component whose properties to view.
반환ReturnsVec<ReflectedProperty> 반사 속성 목록. (반사 매크로가 지은 차례 뒤에 Component 공통 속성 GizmoVisible, Enable, ComponentType. 게터가 없는 컴포넌트는 공통 속성만)Reflected property list. (The order the reflection macro built, followed by the Component common properties GizmoVisible, Enable, ComponentType. A component without getters has only the common properties)
짝Counterpart: vanilla.js UIDocument.getReflectedProperties
pub fn save_by_reflection(component: &dyn Component, save_context: &UIDocumentSaveContext) -> Map<String, Value>#짝이 맞는 get / set 속성으로 컴포넌트 저장. (원본 saveByReflection, 옮길 수 있는 값만 담는다: 수, 불, 글, Color, Vector2, 노드)
Saves a component through matching get / set properties. (original saveByReflection, holds only transferable values: number, bool, string, Color, Vector2, node)
- component&dyn Component
- 쓸 컴포넌트.Component to write.
- save_context&UIDocumentSaveContext
- 쓰기 문맥. (노드 참조 경로의 기준)Write context. (base of node reference paths)
반환ReturnsMap<String, Value> 속성 이름(머리 대문자) → 문서 값. ("type" 없음, 저장하지 않는 속성과 옮길 수 없는 값은 뺀다)Property name (capitalized) → document value. (no "type", properties that are not saved and values that cannot be transferred are excluded)
짝Counterpart: vanilla.js UIDocument.saveByReflection
pub fn load_by_reflection(component: &mut dyn Component, component_data: &Map<String, Value>, load_context: &mut UIDocumentLoadContext)#짝이 맞는 get / set 속성으로 컴포넌트 복원. (원본 loadByReflection, 노드 참조는 트리를 다 지은 뒤 잇는다)
- 원본은 지금 값의 꼴로 받을지 가린다. 러스트 판은 세터의 꼴로 가린다. (core/reflection.rs)
- 트리를 받는 세터(set_snap_current_index(트리, 칸) 같은 것)도 읽기 문맥의 트리로 원본처럼 그 자리에서 부른다.
Restores a component through matching get / set properties. (original loadByReflection, node references are wired after the whole tree is built)
- The original decides by the form of the current value whether to accept it. The Rust version decides by the setter's form. (core/reflection.rs)
- Setters that take the tree (like set_snap_current_index(tree, slot)) are also called on the spot with the read context's tree, as in the original.
- component&mut dyn Component
- 값을 넣을 컴포넌트.Component to put the values into.
- component_data&Map<String, Value>
- 컴포넌트 문서 값. (속성 이름 키)Component document value. (property name keys)
- load_context&mut UIDocumentLoadContext
- 읽기 문맥. (노드 참조는 여기에 맡긴다)Read context. (node references are left here)
짝Counterpart: vanilla.js UIDocument.loadByReflection
pub fn find_node_path(node_tree: &NodeTree, root_id: NodeId, node_id: NodeId) -> Option<String>#뿌리 기준 절대 경로 계산. (원본 findNodePath, "/" + 이름들. 뿌리 밖의 노드면 None)
Computes the absolute path from the root. (original findNodePath, "/" + names. None if the node is outside the root)
- node_tree&NodeTree
- 노드가 든 트리.Tree holding the node.
- root_idNodeId
- 경로의 기준 뿌리.Base root of the path.
- node_idNodeId
- 경로를 셀 노드.Node to compute the path for.
반환ReturnsOption<String> "/" 로 시작하는 이름 경로. (뿌리 자신은 "/") 뿌리의 자손이 아니면 None.Name path starting with "/". (the root itself is "/") None if not a descendant of the root.
짝Counterpart: vanilla.js UIDocument.findNodePath
use vanilla::{NodeTree, UIDocument};
let mut node_tree = NodeTree::new();
let root_id = node_tree.create_node("root");
let panel_id = node_tree.create_child(root_id, "panel");
let button_id = node_tree.create_child(panel_id, "button");
let outside_id = node_tree.create_node("outside");
assert_eq!(UIDocument::find_node_path(&node_tree, root_id, button_id).as_deref(), Some("/panel/button"));
assert_eq!(UIDocument::find_node_path(&node_tree, root_id, root_id).as_deref(), Some("/"));
assert_eq!(UIDocument::find_node_path(&node_tree, root_id, outside_id), None);
assert_eq!(UIDocument::find_node_by_path(&node_tree, root_id, "/panel/button"), Some(button_id));
assert_eq!(UIDocument::find_node_by_path(&node_tree, root_id, "/panel/missing"), None);pub fn find_node_by_path(node_tree: &NodeTree, root_id: NodeId, path_text: &str) -> Option<NodeId>#뿌리 기준 절대 경로로 노드 찾기. (원본 findNodeByPath, 같은 이름이면 앞의 자식)
Finds a node by its absolute path from the root. (original findNodeByPath, the earlier child on the same name)
- node_tree&NodeTree
- 노드가 든 트리.Tree holding the node.
- root_idNodeId
- 경로의 기준 뿌리.Base root of the path.
- path_text&str
- "/이름/이름" 꼴 경로. (앞의 "/" 는 없어도 된다. 빈 글이나 "/" 면 뿌리)Path in "/name/name" form. (the leading "/" is optional. The root if an empty string or "/")
반환ReturnsOption<NodeId> 찾은 노드. 이름이 맞는 자식이 없는 조각이 있으면 None.The found node. None if any segment has no child with a matching name.
짝Counterpart: vanilla.js UIDocument.findNodeByPath
수 → 문서 값. (f64 를 가장 짧은 십진으로, 정수면 소수점 없이. 원본 JSON.stringify 와 같은 글이 나온다. 수가 아니면 null)
Number → document value. (f64 as the shortest decimal, without a decimal point if an integer. Produces the same text as the original JSON.stringify. null if not a number)
- numberf64
- 적을 수.Number to write.
반환ReturnsValue JSON 수. (NaN, 무한이면 null)JSON number. (null if NaN or infinite)
use serde_json::Value;
use vanilla::UIDocument;
assert_eq!(UIDocument::number_to_value(0.22).to_string(), "0.22");
assert_eq!(UIDocument::number_to_value(24.0).to_string(), "24");
assert_eq!(UIDocument::number_to_value(f64::NAN), Value::Null);색 → 배열. (원본 colorToArray, [r, g, b, a])
Color → array. (original colorToArray, [r, g, b, a])
- colorColor
- 적을 색.Color to write.
반환ReturnsValue [r, g, b, a] 배열. (0 ~ 1 값을 가장 짧은 십진으로)[r, g, b, a] array. (0 ~ 1 values as the shortest decimal)
배열 → 색. (원본 arrayToColor, 원소가 넷보다 적거나 앞 넷 가운데 수가 아닌 것이 있으면 None)
Array → color. (the original arrayToColor, None if there are fewer than four elements or any of the first four is not a number)
- value&Value
- [r, g, b, a] 꼴 문서 값.Document value in [r, g, b, a] form.
반환ReturnsOption<Color> 색. 배열이 아니거나 원소가 넷보다 적거나 앞 넷 가운데 수가 아닌 것이 있으면 None. (다섯째부터는 보지 않는다)Color. None if not an array, if it has fewer than four elements, or if any of the first four is not a number. (from the fifth on is not checked)
use vanilla::{Color, UIDocument};
let color = Color::create(1.0, 0.5, 0.0, 1.0);
let color_value = UIDocument::color_to_array(color);
assert_eq!(color_value, serde_json::json!([1, 0.5, 0, 1]));
assert_eq!(UIDocument::array_to_color(&color_value), Some(color));
assert_eq!(UIDocument::array_to_color(&serde_json::json!([1, 0.5])), None);벡터 → 배열. ([x, y])
Vector → array. ([x, y])
- vectorVector2
- 적을 벡터.Vector to write.
반환ReturnsValue [x, y] 배열.[x, y] array.
배열 → 벡터. (원소가 둘보다 적거나 앞 둘 가운데 수가 아닌 것이 있으면 None)
Array → vector. (None if there are fewer than two elements or either of the first two is not a number)
- value&Value
- [x, y] 꼴 문서 값.Document value in [x, y] form.
반환ReturnsOption<Vector2> 벡터. 배열이 아니거나 원소가 둘보다 적거나 앞 둘 가운데 수가 아닌 것이 있으면 None. (셋째부터는 보지 않는다)Vector. None if not an array, if it has fewer than two elements, or if any of the first two is not a number. (from the third on is not checked)
원본 에디터가 등록하는 종류 모두 등록. (원본 registerEditorTypes, 원본 tools/uieditor/uieditor.js 는 엔진이 내보내는 모든 Component 를 registerComponentType, WorldNode 하위 클래스를 registerNodeType 한다)
- 원본처럼 내보낸 이름 차례(abc)로 등록한다. 이미 등록한 이름(원본 기본 표)은 원본처럼 쓰기, 읽기 함수를 그대로 둔다.
- 원본도 기본 표에는 없어 게임이 등록해야 읽는다. 에디터가 저장한 문서를 읽는 게임은 이것을 한 번 부른다.
Registers all the types the original editor registers. (the original registerEditorTypes, the original tools/uieditor/uieditor.js registers every Component the engine exports with registerComponentType and every WorldNode subclass with registerNodeType)
- Registers in exported name order (abc) as in the original. Names already registered (the original default table) keep their write and read functions as in the original.
- In the original too they are not in the default table, so the game must register them to read them. A game reading documents saved by the editor calls this once.
짝Counterpart: vanilla.js UIDocument.registerEditorTypes
pub fn register_component_type<T: Component + 'static>(&mut self, type_name: &str, create_component: fn() -> T)#컴포넌트 종류 등록. (원본 registerComponentType, 같은 이름이면 바꾼다)
- 쓰기, 읽기 함수가 없어 원본처럼 반사로 쓰고 읽는다. (
#[reflect]를 붙인 컴포넌트, 붙이지 않았으면 Component 공통 속성만) - create_component 로 짓고 node_tree.add_component 로 붙인 뒤 문서 값을 넣는다. (원본처럼 붙인 다음 읽는다) 쓸 때는 값 끝에 "type" 을 더한다.
Registers a component kind. (original registerComponentType, replaces on the same name)
- Without write and read functions, it writes and reads by reflection as in the original. (components with
#[reflect], or only the common Component properties if not) - Builds with create_component, attaches with node_tree.add_component, then puts in the document value. (attaches first, then reads, as in the original) When writing, "type" is added at the end of the value.
- type_name&str
- 문서의 "type" 이름. (같은 이름이 있으면 바꾼다)The document's "type" name. (replaces if the same name exists)
- create_componentfn() -> T
- 읽을 때 컴포넌트를 짓는 함수.Function that builds the component when reading.
짝Counterpart: vanilla.js UIDocument.registerComponentType
use vanilla::{Component, ComponentBase, NodeTree, UIDocument};
struct Spin {
component_base: ComponentBase,
degrees_per_second: f64,
}
#[vanilla::reflect]
impl Spin {
pub fn new() -> Spin {
Spin {
component_base: ComponentBase::new(),
degrees_per_second: 0.0,
}
}
pub fn set_degrees_per_second(&mut self, degrees_per_second: f64) {
self.degrees_per_second = degrees_per_second;
}
pub fn get_degrees_per_second(&self) -> f64 {
self.degrees_per_second
}
}
#[vanilla::reflect]
impl Component for Spin {
fn get_component_base(&self) -> &ComponentBase {
&self.component_base
}
fn get_component_base_mut(&mut self) -> &mut ComponentBase {
&mut self.component_base
}
fn get_component_type(&self) -> &'static str {
"Spin"
}
}
let mut document = UIDocument::new();
document.register_component_type("Spin", Spin::new);
let mut node_tree = NodeTree::new();
let root_id = node_tree.create_node("root");
node_tree[root_id].add_component(Spin::new()).set_degrees_per_second(90.0);
let json_text = document.to_json_text(&mut node_tree, root_id, false);
assert!(json_text.contains("\"DegreesPerSecond\":90"));
let loaded_id = document.from_json_text(&mut node_tree, &json_text).expect("document");
assert_eq!(node_tree[loaded_id].get_component::<Spin>().expect("spin").get_degrees_per_second(), 90.0);pub fn register_component_type_with_handler<T: Component + 'static>(&mut self, type_name: &str, create_component: fn() -> T, save_component: fn(&T, &UIDocumentSaveContext) -> Map<String, Value>, load_component: fn(&mut T, &Map<String, Value>, &mut UIDocumentLoadContext))#쓰기, 읽기 함수가 있는 컴포넌트 종류 등록. (원본 COMPONENT_TYPE_TABLE 과 COMPONENT_PROPERTY_TABLE 의 한 줄, 같은 이름이면 바꾼다)
- save_component 가 돌려준 값 끝에 "type" 을 더해 적는다. 노드를 가리키는 반사 속성은 원본처럼 따로 얹고 읽는다.
Registers a component kind with write and read functions. (one row of the original COMPONENT_TYPE_TABLE and COMPONENT_PROPERTY_TABLE, replaces on the same name)
- Writes the value returned by save_component with "type" added at the end. Reflection properties pointing to nodes are added and read separately as in the original.
- type_name&str
- 문서의 "type" 이름. (같은 이름이 있으면 바꾼다)The document's "type" name. (replaces if the same name exists)
- create_componentfn() -> T
- 읽을 때 컴포넌트를 짓는 함수.Function that builds the component when reading.
- save_componentfn(&T, &UIDocumentSaveContext) -> Map<String, Value>
- 컴포넌트를 문서 값(키 → 값)으로 쓰는 함수. ("type" 은 넣지 않는다)Function that writes the component as a document value (key → value). ("type" is not included)
- load_componentfn(&mut T, &Map<String, Value>, &mut UIDocumentLoadContext)
- 붙인 컴포넌트에 문서 값을 읽어 넣는 함수. (그림과 노드 참조는 읽기 문맥에 맡긴다)Function that reads the document value into the attached component. (images and node references are left to the read context)
use serde_json::{Map, Value};
use vanilla::{Component, ComponentBase, NodeTree, UIDocument, UIDocumentLoadContext, UIDocumentSaveContext};
struct Spin {
component_base: ComponentBase,
degrees_per_second: f64,
}
#[vanilla::reflect]
impl Spin {}
#[vanilla::reflect]
impl Component for Spin {
fn get_component_base(&self) -> &ComponentBase {
&self.component_base
}
fn get_component_base_mut(&mut self) -> &mut ComponentBase {
&mut self.component_base
}
fn get_component_type(&self) -> &'static str {
"Spin"
}
}
fn create_spin() -> Spin {
Spin {
component_base: ComponentBase::new(),
degrees_per_second: 0.0,
}
}
fn save_spin(spin: &Spin, _save_context: &UIDocumentSaveContext) -> Map<String, Value> {
let mut component_data = Map::new();
component_data.insert(String::from("degreesPerSecond"), UIDocument::number_to_value(spin.degrees_per_second));
component_data
}
fn load_spin(spin: &mut Spin, component_data: &Map<String, Value>, _load_context: &mut UIDocumentLoadContext) {
if let Some(degrees_per_second) = component_data.get("degreesPerSecond").and_then(|value| value.as_f64()) {
spin.degrees_per_second = degrees_per_second as f64;
}
}
let mut document = UIDocument::new();
document.register_component_type_with_handler("Spin", create_spin, save_spin, load_spin);
let json_text = r#"{"version":1,"root":{"name":"root","components":[{"degreesPerSecond":90,"type":"Spin"}]}}"#;
let mut node_tree = NodeTree::new();
let root_id = document.from_json_text(&mut node_tree, json_text).expect("document");
assert_eq!(node_tree[root_id].get_component::<Spin>().expect("spin").degrees_per_second, 90.0);
assert!(document.to_json_text(&mut node_tree, root_id, false).contains("{\"degreesPerSecond\":90,\"type\":\"Spin\"}"));pub fn register_widget_type<T: Component + 'static>(&mut self, type_name: &str, create_component: fn() -> T, read_content: fn(&T) -> Option<NodeId>, generated_type_names: &[&str])#위젯 종류 등록. (원본의 UIView 계열, 붙을 때 content 노드를 만드는 컴포넌트. 반사로 쓰고 읽는다)
- read_content 가 돌려준 content 노드는 문서에 적지 않고, 그 안의 자식만 contentChildren 으로 적는다. 읽을 때 위젯이 다시 만든 content 에 붙인다.
- generated_type_names 는 위젯이 붙을 때 호스트에 스스로 붙이는 컴포넌트 종류다. (원본 require, 문서에 적지 않는다)
Registers a widget kind. (the original UIView family, components that create a content node when attached. Written and read by reflection)
- The content node returned by read_content is not written to the document, and only its children are written as contentChildren. When reading, they are attached to the content the widget recreated.
- generated_type_names are the component kinds the widget attaches to its host by itself when attached. (original require, not written to the document)
- type_name&str
- 문서의 "type" 이름. (같은 이름이 있으면 바꾼다)The document's "type" name. (replaces if the same name exists)
- create_componentfn() -> T
- 읽을 때 위젯을 짓는 함수.Function that builds the widget when reading.
- read_contentfn(&T) -> Option<NodeId>
- 위젯의 content 노드를 돌려주는 함수.Function that returns the widget's content node.
- generated_type_names&[&str]
- 위젯이 붙을 때 호스트에 스스로 붙이는 컴포넌트 종류 이름. (없으면 빈 목록, UIScrollView 는 ["Mask"])Names of the component kinds the widget attaches to its host by itself when attached. (empty list if none, ["Mask"] for UIScrollView)
use serde_json::Value;
use vanilla::{NodeTree, UIDocument, UIView};
let mut document = UIDocument::new();
document.register_widget_type("UIView", UIView::new, UIView::get_content, &[]);
let mut node_tree = NodeTree::new();
let view_id = node_tree.create_node("view");
let content_id = node_tree.add_component(view_id, UIView::new()).expect("view").get_content().expect("content");
node_tree.create_child(content_id, "item");
let json_text = document.to_json_text(&mut node_tree, view_id, false);
let document_data: Value = serde_json::from_str(&json_text).expect("json");
assert_eq!(document_data["root"]["children"], serde_json::json!([]));
assert_eq!(document_data["root"]["contentChildren"][0]["name"], "item");
let loaded_id = document.from_json_text(&mut node_tree, &json_text).expect("document");
let loaded_content_id = node_tree[loaded_id].get_component::<UIView>().expect("view").get_content().expect("content");
assert!(node_tree.find_child_by_name(loaded_content_id, "item").is_some());pub fn register_widget_type_with_handler<T: Component + 'static>(&mut self, type_name: &str, create_component: fn() -> T, save_component: fn(&T, &UIDocumentSaveContext) -> Map<String, Value>, load_component: fn(&mut T, &Map<String, Value>, &mut UIDocumentLoadContext), read_content: fn(&T) -> Option<NodeId>, generated_type_names: &[&str])#쓰기, 읽기 함수가 있는 위젯 종류 등록.
- register_widget_type 과 같되 반사 대신 save_component, load_component 로 쓰고 읽는다.
Registers a widget kind with write and read functions.
- Same as register_widget_type, but writes and reads with save_component and load_component instead of reflection.
- type_name&str
- 문서의 "type" 이름. (같은 이름이 있으면 바꾼다)The document's "type" name. (replaces if the same name exists)
- create_componentfn() -> T
- 읽을 때 위젯을 짓는 함수.Function that builds the widget when reading.
- save_componentfn(&T, &UIDocumentSaveContext) -> Map<String, Value>
- 위젯을 문서 값으로 쓰는 함수. ("type" 은 넣지 않는다)Function that writes the widget as a document value. ("type" is not included)
- load_componentfn(&mut T, &Map<String, Value>, &mut UIDocumentLoadContext)
- 붙인 위젯에 문서 값을 읽어 넣는 함수.Function that reads the document value into the attached widget.
- read_contentfn(&T) -> Option<NodeId>
- 위젯의 content 노드를 돌려주는 함수.Function that returns the widget's content node.
- generated_type_names&[&str]
- 위젯이 붙을 때 호스트에 스스로 붙이는 컴포넌트 종류 이름.Names of the component kinds the widget attaches to its host by itself when attached.
pub fn register_node_type<T: Component + UIDocumentNode + 'static>(&mut self, type_name: &str, create_component: fn() -> T)#노드 종류 등록. (원본 registerNodeType, 원본 WorldNode 하위 클래스를 맡은 러스트 컴포넌트, 같은 이름이면 바꾼다)
- 그 컴포넌트가 붙은 노드는 type 을 이 이름으로 적고 컴포넌트 목록에는 그 컴포넌트를 적지 않는다. 읽을 때는 노드를 짓자마자(문서의 노드 값을 넣기 전에) 붙인다. (원본은 그 종류의 생성자로 노드를 짓고 노드 값을 넣는다)
- 원본 생성자가 만드는 컴포넌트와 자식은 UIDocumentNode 가 쓰고 읽는다.
Registers a node kind. (original registerNodeType, a Rust component standing in for an original WorldNode subclass, replaces on the same name)
- A node with that component attached writes its type as this name and does not list that component among its components. When reading, it is attached right after the node is built (before the document's node values are put in). (the original builds the node with that kind's constructor and puts in the node values)
- The components and children the original constructor creates are written and read by UIDocumentNode.
- type_name&str
- 문서 노드의 "type" 이름. (같은 이름이 있으면 바꾼다)The document node's "type" name. (replaces if the same name exists)
- create_componentfn() -> T
- 읽을 때 노드를 짓자마자 붙일 컴포넌트를 짓는 함수.Function that builds the component to attach right after the node is built when reading.
짝Counterpart: vanilla.js UIDocument.registerNodeType
use serde_json::Value;
use vanilla::{NodeTree, UIDocument, UIScrollBar};
let mut document = UIDocument::new();
document.register_node_type("UIScrollBar", UIScrollBar::new);
let mut node_tree = NodeTree::new();
let scroll_bar_id = node_tree.create_node("scrollBar");
node_tree.add_component(scroll_bar_id, UIScrollBar::new());
let json_text = document.to_json_text(&mut node_tree, scroll_bar_id, false);
let document_data: Value = serde_json::from_str(&json_text).expect("json");
assert_eq!(document_data["root"]["type"], "UIScrollBar");
assert_eq!(document_data["root"]["components"][0]["type"], "Paint");
assert_eq!(document_data["root"]["children"][0]["name"], "thumb");
let loaded_id = document.from_json_text(&mut node_tree, &json_text).expect("document");
assert!(node_tree[loaded_id].get_component::<UIScrollBar>().is_some());
assert!(node_tree.get_child_ids(loaded_id).is_empty());pub fn register_node_type_with_match<T: Component + UIDocumentNode + 'static>(&mut self, type_name: &str, create_component: fn() -> T, matches: fn(&T) -> bool)#노드 종류 등록. (컴포넌트 종류만으로 가리지 못할 때 matches 가 참인 것만 이 노드 종류다. UIConfirmWindow 는 UIWindow 이고 behavior 로 가린다)
- 가리는 함수가 있는 등록이 없는 등록보다 먼저 맞춰 본다.
Registers a node kind. (when the component kind alone cannot tell, only those for which matches is true are this node kind. UIConfirmWindow is a UIWindow and is told apart by behavior)
- Registrations with a telling function are matched before those without.
- type_name&str
- 문서 노드의 "type" 이름. (같은 이름이 있으면 바꾼다)The document node's "type" name. (replaces if the same name exists)
- create_componentfn() -> T
- 읽을 때 노드를 짓자마자 붙일 컴포넌트를 짓는 함수.Function that builds the component to attach right after the node is built when reading.
- matchesfn(&T) -> bool
- 노드에 붙은 그 타입의 컴포넌트가 이 노드 종류인지 가리는 함수.Function that tells whether the component of that type attached to the node is this node kind.
노드 종류 이름. (원본 node.constructor.name 자리, 저장할 때 적는 type 과 같다)
- 등록한 노드 종류(register_node_type, 엔진 종류는 register_editor_types 가 등록)의 컴포넌트가 붙은 노드면 그 이름(앞에 붙은 것), 아니면 "WorldNode".
Node type name. (in place of the original node.constructor.name, the same as the type written when saving)
- The name of a registered node type (register_node_type; register_editor_types registers the engine types) if its component is on the node (the earlier one), otherwise "WorldNode".
- node&WorldNode
- 볼 노드.Node to look at.
반환Returns&str 노드 종류 이름.Node type name.
짝Counterpart: vanilla.js UIDocument.getNodeTypeName
use vanilla::{FloatingText, UIDocument, WorldNode};
let mut ui_document = UIDocument::new();
ui_document.register_editor_types();
let mut node = WorldNode::new("node");
assert_eq!(ui_document.get_node_type_name(&node), "WorldNode");
node.add_component(FloatingText::new());
assert_eq!(ui_document.get_node_type_name(&node), "FloatingText");지원 컴포넌트 종류 이름 목록. (원본 getComponentTypeNames, 등록 차례)
List of supported component kind names. (original getComponentTypeNames, registration order)
반환ReturnsVec<&str> 등록한 컴포넌트 종류 이름. (등록 차례, 노드 종류 이름은 들지 않는다)Registered component kind names. (registration order, node kind names are not included)
짝Counterpart: vanilla.js UIDocument.getComponentTypeNames
pub fn create_component(&self, node_tree: &mut NodeTree, node_id: NodeId, type_name: &str) -> Option<usize>#이름으로 컴포넌트를 지어 노드에 붙인다. (원본 getComponentType 으로 받은 생성자로 짓고 붙이는 자리, 등록하지 않은 이름이면 None)
Builds a component by name and attaches it to the node. (where the original builds and attaches with the constructor from getComponentType, None if the name is not registered)
- node_tree&mut NodeTree
- 노드가 든 트리.Tree holding the node.
- node_idNodeId
- 컴포넌트를 붙일 노드.Node to attach the component to.
- type_name&str
- 등록한 컴포넌트 종류 이름.Registered component kind name.
반환ReturnsOption<usize> 붙인 컴포넌트의 차례 번호. (그 노드의 컴포넌트 목록 안) 등록하지 않은 이름이거나 노드가 없으면 None.Index of the attached component. (within that node's component list) None if the name is not registered or the node does not exist.
짝Counterpart: vanilla.js UIDocument.createComponent
use vanilla::{NodeTree, Paint, UIDocument};
let document = UIDocument::new();
let mut node_tree = NodeTree::new();
let node_id = node_tree.create_node("node");
assert_eq!(document.create_component(&mut node_tree, node_id, "Paint"), Some(0));
assert!(node_tree[node_id].get_component::<Paint>().is_some());
assert_eq!(document.create_component(&mut node_tree, node_id, "Unknown"), None);pub fn set_image_resolver(&mut self, image_resolver: impl FnMut(&str) -> Option<Rc<Image>> + 'static)#이미지 경로 해석기 등록. (원본 setImageResolver, 경로 → 그림. 등록하면 애셋 창고 대신 이것으로 찾는다)
Registers an image path resolver. (original setImageResolver, path → image. When registered, images are looked up with it instead of the asset store)
- image_resolverimpl FnMut(&str) -> Option<Rc<Image>> + 'static
- 그림 경로를 받아 그림을 돌려주는 함수. None 을 돌려주면 그 그림은 찾지 못한 것이다.Function that takes an image path and returns the image. Returning None means that image was not found.
짝Counterpart: vanilla.js UIDocument.setImageResolver
use std::rc::Rc;
use vanilla::{Image, NodeTree, Sprite, UIDocument};
let star_image = Image::create_from_pixels(1, 1, vec![255, 255, 255, 255]);
let resolved_image = star_image.clone();
let mut document = UIDocument::new();
document.set_image_resolver(move |image_path: &str| {
if image_path == "star.png" {
Some(resolved_image.clone())
}
else {
None
}
});
let json_text = r#"{"version":1,"root":{"name":"star","components":[{"imagePath":"star.png","type":"Sprite"}]}}"#;
let mut node_tree = NodeTree::new();
let star_id = document.from_json_text(&mut node_tree, json_text).expect("document");
let sprite = node_tree[star_id].get_component::<Sprite>().expect("sprite");
assert!(sprite.get_image().is_some_and(|image| Rc::ptr_eq(image, &star_image)));
assert!(document.resolve_image("missing.png").is_none());이미지 경로 해석. (원본 resolveImage, 찾지 못했거나 아직 읽히는 중이면 None)
Resolves an image path. (original resolveImage, None if not found or still loading)
- image_path&str
- 찾을 그림 경로.Image path to look up.
반환ReturnsOption<Rc<Image>> 찾은 그림. 해석기가 None 을 주었거나, 해석기가 없고 load_images 로 요청하지 않았거나 아직 읽히는 중이거나 읽기에 실패했으면 None.The found image. None if the resolver returned None, or if there is no resolver and it was not requested with load_images, is still loading, or failed to load.
짝Counterpart: vanilla.js UIDocument.resolveImage
문서의 그림 읽기 요청. (imagePath 마다 ImageAsset 을 요청해 창고에 든다. 이미 요청한 경로는 건너뛰고, 읽지 못한 경로는 다시 요청한다)
- 새로 요청한 애셋의 읽기 손잡이를 돌려준다. 씬이 load 에서 부르면 track_load_handle 로 맡겨 initialize 를 기다리게 할 수 있다.
- 데스크탑은 그 자리에서 읽히고, 웹은 나중에 읽힌다. 읽히기 전에 지은 노드의 그림은 bind_pending_images 가 붙인다.
Requests loading the document's images. (requests an ImageAsset for each imagePath and holds it in the store. Paths already requested are skipped, and paths that failed to load are requested again)
- Returns the load handles of newly requested assets. If a scene calls this in load, it can hand them to track_load_handle to make initialize wait.
- On desktop they load on the spot, on the web later. Images of nodes built before loading are attached by bind_pending_images.
- engine&Engine
- 애셋을 읽을 엔진. (데스크탑은 EngineConfiguration 의 asset_directory_paths 에서 찾는다)Engine to load assets with. (on desktop, looked up in EngineConfiguration's asset_directory_paths)
- json_text&str
- 문서 글.Document text.
반환ReturnsVec<AssetLoadHandle> 새로 요청한 애셋의 읽기 손잡이 목록. JSON 이 아니거나 새로 요청할 경로가 없으면 빈 목록.List of load handles of newly requested assets. Empty list if not JSON or there are no new paths to request.
짝Counterpart: vanilla.js UIDocument.loadImages
use std::path::PathBuf;
use vanilla::{Engine, EngineConfiguration, NodeTree, Sprite, UIDocument};
let mut engine_configuration = EngineConfiguration::new();
engine_configuration.asset_directory_paths = vec![PathBuf::from("examples/assets")];
let engine = Engine::new(engine_configuration);
let json_text = r#"{"version":1,"root":{"name":"icons","components":[{"imagePath":"atlas/icons.png","type":"Sprite"}]}}"#;
let mut document = UIDocument::new();
let load_handle_list = document.load_images(&engine, json_text);
assert_eq!(load_handle_list.len(), 1);
let mut node_tree = NodeTree::new();
let icons_id = document.from_json_text(&mut node_tree, json_text).expect("document");
assert_eq!(document.bind_pending_images(&mut node_tree), 0);
assert!(node_tree[icons_id].get_component::<Sprite>().expect("sprite").get_image().is_some());맡아 둔 그림 붙이기. (찾은 그림은 넣고, 아직 읽히는 그림은 남긴다. 남은 수를 돌려준다)
- from_json_text, deserialize_node 가 끝에 한 번 부른다. 웹처럼 그림이 나중에 읽히면 씬의 tick 에서 남은 수가 0 이 될 때까지 부른다.
- 찾지 못한 그림(해석기가 None, 애셋이 없거나 실패)은 경고를 내고 버린다. 그 컴포넌트는 원본처럼 그림 없이 남는다.
- 그사이 게임이 그림을 넣었거나(그림이 None 이 아님) 경로를 바꾼 컴포넌트는 건드리지 않고 버린다.
Attaches the held images. (puts in found images, keeps images still loading. Returns the remaining count)
- from_json_text and deserialize_node call this once at the end. If images load later, as on the web, call it in the scene's tick until the remaining count becomes 0.
- Images not found (resolver gave None, asset missing or failed) log a warning and are dropped. That component stays without an image as in the original.
- A component whose image the game set (the image is not None) or whose path it changed in the meantime is left untouched and the image is dropped.
- node_tree&mut NodeTree
- 그림을 넣을 노드 트리. (맡긴 노드가 지워졌으면 그 그림은 버린다)Node tree to put the images into. (if the node they were left for has been removed, the image is dropped)
반환Returnsusize 아직 읽히는 중이라 남은 그림 수. (0 이면 다 붙였거나 버렸다)Number of images remaining because they are still loading. (0 means all were attached or dropped)
짝Counterpart: vanilla.js UIDocument.bindPendingImages
노드 트리 → 문서 데이터. (원본 serializeNode, 노드 참조는 이 노드 기준 경로로 적는다)
- &mut self 게터가 있는 컴포넌트도 읽는다. (원본 게터에는 &self, &mut self 구별이 없어 한 함수로 둔다. 그래서 트리를 가변으로 받는다)
- imagePath 를 적은 컴포넌트에 그림이 들었으면 그 그림을 경로로 기억한다. 같은 문서로 다시 읽으면 해석기나 load_images 없이도 그 그림을 넣는다.
- 노드 참조가 이름이 같은 앞 형제가 있는 노드를 가리키면 경고를 낸다. (경로는 이름으로만 적어 다시 읽으면 앞 형제에 이어진다)
- 숨긴 노드(set_visible(false))는 visible: false 를 적는다. (보이면 적지 않는다. 보임을 active 로 쓰는 노드 종류는 active 로만 적는다)
Node tree → document data. (the original serializeNode, node references are written as paths relative to this node)
- Also reads components with &mut self getters. (the original getters make no &self, &mut self distinction, so it is a single function. That is why the tree is taken as mutable)
- When a component that writes an imagePath holds an image, remembers that image by path. Reading it back with the same document puts that image in without a resolver or load_images.
- Warns when a node reference points to a node that has an earlier sibling with the same name. (paths are names only, so reading back links to the earlier sibling)
- A hidden node (set_visible(false)) writes visible: false. (not written when visible; a node type that uses visibility as active writes only active)
- node_tree&mut NodeTree
- 노드가 든 트리. (&mut 게터를 부르려고 가변으로 받는다)Tree holding the node. (taken as mutable to call &mut getters)
- node_idNodeId
- 문서 값으로 쓸 노드. (자손까지)Node to write as a document value. (including descendants)
반환ReturnsValue 노드 문서 값. ("version" 머리 없는 노드 객체) 노드가 없으면 Value::Null.Node document value. (node object without the "version" header) Value::Null if the node does not exist.
짝Counterpart: vanilla.js UIDocument.serializeNode
use vanilla::{NodeTree, UIDocument, Vector2};
let mut node_tree = NodeTree::new();
let card_id = node_tree.create_node("card");
node_tree[card_id].set_content_size(Vector2::create(120.0, 80.0));
node_tree.create_child(card_id, "icon");
let mut document = UIDocument::new();
let card_data = document.serialize_node(&mut node_tree, card_id);
assert_eq!(card_data["name"], "card");
let copy_id = document.deserialize_node(&mut node_tree, &card_data);
assert_ne!(copy_id, card_id);
assert_eq!(node_tree[copy_id].get_content_size(), Vector2::create(120.0, 80.0));
assert!(node_tree.find_child_by_name(copy_id, "icon").is_some());
assert_eq!(node_tree.get_parent_id(copy_id), None);pub fn serialize_component(&self, node_tree: &NodeTree, root_id: NodeId, component: &dyn Component) -> Map<String, Value>#컴포넌트 하나 → 문서 데이터. ("type" 은 더하지 않는다. 등록한 종류면 그 꼴로, 등록하지 않았으면 반사로. 원본처럼 모든 컴포넌트가 반사된다)
- 노드 참조는 root_id 기준 경로로 적는다.
One component to document data. ("type" is not added. A registered type uses its own form, an unregistered one uses reflection. Like the original, every component is reflected)
- Node references are written as paths from root_id.
- node_tree&NodeTree
- 노드 참조를 찾을 트리.Tree to look up node references in.
- root_idNodeId
- 노드 참조 경로의 기준 뿌리.Base root of node reference paths.
- component&dyn Component
- 쓸 컴포넌트.Component to write.
반환ReturnsMap<String, Value> 컴포넌트 문서 값. ("type" 없음)The component's document value. (no "type")
use vanilla::{NodeTree, Paint, UIDocument};
let node_tree = NodeTree::new();
let mut paint = Paint::new();
paint.set_round_size(8.0);
let document = UIDocument::new();
let paint_data = document.serialize_component(&node_tree, node_tree.get_root_id(), &paint);
assert_eq!(paint_data["roundSize"], 8);
assert!(paint_data.get("type").is_none());pub fn collect_generated_component_types(&self, component_list: &[Box<dyn Component>]) -> HashSet<String>#위젯이 붙인 컴포넌트 종류 이름 모으기. (원본 collectGeneratedComponentTypes, 원본 require 자리는 등록할 때 준 목록)
Collects the component kind names attached by widgets. (original collectGeneratedComponentTypes, the original require slot is the list given at registration)
- component_list&[Box<dyn Component>]
- 노드의 컴포넌트 목록.The node's component list.
반환ReturnsHashSet<String> 목록 안의 등록한 위젯들이 스스로 붙이는 컴포넌트 종류 이름 모음.Set of component kind names that the registered widgets in the list attach by themselves.
짝Counterpart: vanilla.js UIDocument.collectGeneratedComponentTypes
문서 데이터 → 노드 트리. (원본 deserializeNode, 어느 부모에도 붙지 않은 노드를 돌려준다)
- 노드 참조는 이 노드 기준 경로로 잇고, 찾을 수 있는 그림을 넣는다.
Document data → node tree. (original deserializeNode, returns a node not attached to any parent)
- Node references are wired as paths from this node, and images that can be found are put in.
- node_tree&mut NodeTree
- 노드를 지을 트리.Tree to build the node in.
- node_data&Value
- 노드 문서 값. (serialize_node 꼴, 객체가 아니면 빈 노드 하나를 짓는다)Node document value. (serialize_node form, builds one empty node if not an object)
반환ReturnsNodeId 지은 노드. (어느 부모에도 붙지 않았다)The built node. (not attached to any parent)
짝Counterpart: vanilla.js UIDocument.deserializeNode
pub fn to_json_text(&self, node_tree: &mut NodeTree, root_id: NodeId, is_pretty: bool) -> String#노드 트리 → JSON 글. (원본 toJsonText, is_pretty 면 탭으로 들여 쓴다)
- serialize_node 처럼 &mut self 게터가 있는 컴포넌트도 읽는다. (그래서 트리를 가변으로 받는다)
Node tree → JSON text. (original toJsonText, indents with tabs if is_pretty)
- Like serialize_node, also reads components with &mut self getters. (that is why the tree is taken as mutable)
- node_tree&mut NodeTree
- 노드가 든 트리. (&mut 게터를 부르려고 가변으로 받는다)Tree holding the node. (taken as mutable to call &mut getters)
- root_idNodeId
- 문서의 뿌리 노드. (노드 참조 경로의 기준)Root node of the document. (base for node reference paths)
- is_prettybool
- true 면 탭으로 들여 쓴 여러 줄, false 면 한 줄.If true, multiple lines indented with tabs, if false, one line.
반환ReturnsString 문서 글. ({ "version": 1, "root": 노드 })Document text. ({ "version": 1, "root": node })
짝Counterpart: vanilla.js UIDocument.toJsonText
pub fn from_json_text(&mut self, node_tree: &mut NodeTree, json_text: &str) -> Result<NodeId, String>#JSON 글 → 노드 트리. (원본 fromJsonText, 어느 부모에도 붙지 않은 뿌리를 돌려준다. 씬에 보이려면 add_child 로 붙인다)
JSON text → node tree. (original fromJsonText, returns a root not attached to any parent. Attach it with add_child to show it in the scene)
- node_tree&mut NodeTree
- 노드를 지을 트리.Tree to build the node in.
- json_text&str
- 문서 글.Document text.
반환ReturnsResult<NodeId, String> 지은 뿌리 노드. JSON 이 아니거나 "root" 객체가 없으면 Err(까닭 글).The built root node. Err(reason text) if not JSON or there is no "root" object.
짝Counterpart: vanilla.js UIDocument.fromJsonText
use vanilla::{NodeTree, UIDocument};
let mut node_tree = NodeTree::new();
let mut document = UIDocument::new();
assert!(document.from_json_text(&mut node_tree, "{\"version\":1}").is_err());
assert!(document.from_json_text(&mut node_tree, "not json").is_err());
let root_id = document.from_json_text(&mut node_tree, r#"{"version":1,"root":{"name":"panel"}}"#).expect("document");
assert_eq!(node_tree[root_id].get_name(), "panel");상수Constants
UI 문서 포맷 버전.
UI document format version.
반환Returnsu32