core/reflection
반사. (원본 vanilla.js 의 실행 중 반사 자리: ui/uidocument.js 의 collectReflectedProperties 와 getReflectedProperties, misc/devtools.js 의 getComponentProperties)
- 원본은 자바스크립트라 실행 중에 객체의 프로토타입을 훑어 get, is, set 함수를 찾는다. 러스트에는 실행 중 반사가 없어, 언리얼의 UHT(UPROPERTY), Qt 의 moc 처럼 컴파일 때 코드를 지어 같은 일을 한다. 러스트에서는 절차 매크로
#[reflect]가 그 일을 한다. (macros/ 크레이트, 엔진이 vanilla::reflect 로 다시 내보낸다) C++ RTTI 의 typeid, dynamic_cast 자리는 이미 AsAny(std::any::Any)다. - 이 모듈은 매크로가 지은 코드가 쓰는 값 꼴(ReflectValue)과 트레이트(Reflect), 원본 Component 기반 클래스의 공통 속성을 둔다.
- 쓰는 법: 컴포넌트의 impl 블록과 impl Component 블록 둘 다에
#[vanilla::reflect]를 붙인다.
#[vanilla::reflect]
impl Spin {
pub fn get_speed(&self) -> f32 { self.speed }
pub fn set_speed(&mut self, speed: f32) { self.speed = speed; }
}
#[vanilla::reflect]
impl Component for Spin { ... }그러면 UIDocument 가 등록된 쓰기, 읽기 함수 없이 Speed 키로 쓰고 읽고(원본 saveByReflection, loadByReflection), DevTools 인스펙터가 speed 줄로 보인다. (원본 getComponentProperties)
- 원본은 모든 객체가 반사된다. 러스트 판은 Reflect 를 Component 의 상위 트레이트로 두어 반사 없는 컴포넌트가 생길 수 없다. 어느 쪽을 빠뜨려도 컴파일 에러가 붙일 곳을 알려 준다. 게터가 없는 타입은 빈 블록
#[vanilla::reflect] impl Spin {}에 붙인다. 반사를 쓰는 쪽은&dyn Component를&dyn Reflect로 올려(트레이트 업캐스팅) 부른다. - 원본 규칙을 따른다:
- 게터는 인자 없는 pub get_*, is_* 함수, 저장 속성은 같은 이름의 set_* 이 있는 게터다. 키는 접두어를 뗀 원본 이름이다. (get_line_width → LineWidth)
- 차례는 정의 차례이고 같은 키는 먼저 나온 것이다. 원본 Component 기반 클래스의 GizmoVisible, Enable, ComponentType 이 끝에 붙는다.
- 저장하는 값은 원본 saveByReflection 이 가리는 꼴(수, 불, 글, Color, Vector2, 노드)이다. 원본에서 글인 열거(TextAlign 같은 것)는 같은 글로 바꾼다.
- 원본처럼 하는 것:
- 원본 상위 클래스의 게터는 프로토타입 사슬로 따라온다. 러스트 판은 상속이 없어 품은 값을 #[reflect(base = 필드)] 로 잇는다. 원본에서 상위 클래스 몫인 함수를 러스트 판이 편의로 다시 둔 것은
#[reflect(skip)]로 빼서 차례를 원본처럼 둔다. 읽기와 넣기는 원본component[getterName],component[setterName]처럼 따로 가장 아래 타입의 것부터 찾는다. (RichText 는 게터를 Text 에서 받고 세터는 제 것) - 짝은 원본처럼 키(baseName)로 짓는다. (get_target 의 키를 TargetNode 로 정하면 set_target(키 Target)과 짝이 아니다)
- impl Component 블록에서 다시 정의한 게터는 원본 클래스에도 있는 것만 보이고(
#[reflect(skip)]으로 빼고), 원본 클래스 몸통의 자리는 #[reflect(after = "...")] 로 맞춘다. - 원본에서 값이 객체라 저장에서 빠지는 속성은
#[reflect(unsaved)]로 목록에는 두고 저장에서 뺀다. (ShadowText 의 FontFace) - 읽을 때 꼴은 세터의 꼴로 가린다. 원본은 지금 값의 꼴로 가리고 지금 값이 없으면(null) 저장한 꼴로 받는다. (원본 saveByReflection 은 Color 만 수 넷, Vector2 만 수 둘로 적는다) 그래서 두 엔진이 같은 문서를 같게 읽는다.
- 원본과 다른 것:
- 원본은 모든 객체가 반사된다. 러스트 판은
#[reflect]를 붙인 타입만이다. 러스트에는 실행 중에 메서드 목록을 읽는 길이 없어 정말 방법이 없다. (언리얼 UCLASS, UPROPERTY 와 같은 꼴) 빠뜨린 것은 이렇게 알 수 있다: 한쪽 블록에만 붙이면 컴파일 에러가 붙일 곳을 알려 주고, 둘 다 빠뜨리면 UIDocument 가 쓸 때 경고를 내고 DevTools 인스펙터가 "반사 없음" 줄을 보인다. - &mut self 게터는 &mut 를 받는 갈래(get_reflected_value_mut, collect_reflected_getters_mut)로 부른다. &self 갈래에서는 값이 None 이다. 트리를 받는 게터(get_target_button(트리) 같은 것, 원본은 이웃 컴포넌트를 바로 쥔다)는 트리를 쥔 쪽이 collect_reflected_getters_in_tree 로 부른다. 트리를 받는 세터(set_snap_current_index(트리, 칸) 같은 것)는 트리를 쥔 쪽이 set_reflected_value_in_tree 로 부른다. 값 말고도 인자를 더 받는 세터(set_image(그림, 조각) 같은 것)는 속성 목록에는 들지만(원본처럼 set 함수가 있으면 짝이다) 넣지 않는다. 원본 setComponentType 자리는 러스트에 세터가 없어(종류는 타입이 정한다) 쓰기만 한다. 원본도 이 키는 읽어도 종류가 바뀌지 않는다.
Reflection. (in place of the runtime reflection of the original vanilla.js: collectReflectedProperties and getReflectedProperties of ui/uidocument.js, getComponentProperties of misc/devtools.js)
- The original is JavaScript, so at runtime it scans an object's prototype to find get, is, set functions. Rust has no runtime reflection, so like Unreal's UHT (UPROPERTY) and Qt's moc, it generates code at compile time to do the same. In Rust the procedural macro
#[reflect]does that. (the macros/ crate, re-exported by the engine as vanilla::reflect) The place of C++ RTTI typeid, dynamic_cast is already AsAny (std::any::Any). - This module holds the value type (ReflectValue) and trait (Reflect) used by macro-generated code, and the common properties of the original Component base class.
- Usage: put
#[vanilla::reflect]on both the component's impl block and its impl Component block.
#[vanilla::reflect]
impl Spin {
pub fn get_speed(&self) -> f32 { self.speed }
pub fn set_speed(&mut self, speed: f32) { self.speed = speed; }
}
#[vanilla::reflect]
impl Component for Spin { ... }Then UIDocument writes and reads with the Speed key without registered write and read functions (the original saveByReflection, loadByReflection), and the DevTools inspector shows a speed line. (original getComponentProperties)
- In the original every object is reflected. The Rust edition makes Reflect a supertrait of Component, so a component without reflection cannot exist. Leaving out either one gives a compile error that points at where to add it. A type without getters takes it on an empty block,
#[vanilla::reflect] impl Spin {}. The side that uses reflection upcasts&dyn Componentto&dyn Reflect(trait upcasting) and calls it. - Follows the original rules:
- Getters are argument-less pub get_*, is_* functions, and saved properties are getters with a set_* of the same name. The key is the original name with the prefix removed. (get_line_width → LineWidth)
- The order is the definition order and for the same key the first one wins. GizmoVisible, Enable, ComponentType of the original Component base class are appended at the end.
- Saved values are the types the original saveByReflection picks (number, boolean, text, Color, Vector2, node). Enums that are text in the original (such as TextAlign) are converted to the same text.
- What it does like the original:
- Getters of the original superclass come along through the prototype chain. The Rust version has no inheritance, so it links the embedded value with #[reflect(base = field)]. Functions that belong to the superclass in the original but that the Rust version redefines for convenience are excluded with
#[reflect(skip)]to keep the original order. Reading and setting look up separately starting from the most derived type, like the originalcomponent[getterName],component[setterName]. (RichText gets the getter from Text and has its own setter) - Pairs are made by key (baseName) like the original. (if the key of get_target is set to TargetNode, it is not paired with set_target (key Target))
- Getters redefined in the impl Component block show only those also in the original class (excluding the rest with
#[reflect(skip)]), and their place in the original class body is matched with #[reflect(after = "...")]. - Properties left out of saving in the original because their value is an object are kept in the list but left out of saving with
#[reflect(unsaved)]. (FontFace of ShadowText) - When reading, the type is decided by the setter's type. The original decides by the type of the current value, and takes the saved type if there is no current value (null). (the original saveByReflection writes only Color as four numbers, and only Vector2 as two numbers) So both engines read the same document the same way.
- What differs from the original:
- In the original every object is reflected. In the Rust version only types with
#[reflect]are. Rust has no way to read a method list at runtime, so there is truly no alternative. (the same form as Unreal UCLASS, UPROPERTY) Omissions can be found this way: putting it on only one block makes a compile error point to where to put it, and omitting both makes UIDocument warn when writing and the DevTools inspector show a "no reflection" row. - &mut self getters are called through the branch taking &mut (get_reflected_value_mut, collect_reflected_getters_mut). In the &self branch the value is None. Getters that take the tree (such as get_target_button(tree), the original holds the neighboring component directly) are called by the side holding the tree with collect_reflected_getters_in_tree. Setters that take the tree (such as set_snap_current_index(tree, index)) are called by the side holding the tree with set_reflected_value_in_tree. Setters that take more arguments than the value (such as set_image(image, slice)) are in the property list (paired if a set function exists, like the original) but are not set. In place of the original setComponentType, Rust has no setter (the kind is decided by the type), so it is only written. In the original too, reading this key does not change the kind.
use vanilla::core::reflection::{collect_reflected_properties, read_reflected_property, write_reflected_property};
use vanilla::{reflect, Component, ComponentBase, ReflectValue};
struct Spin {
component_base: ComponentBase,
speed: f32,
}
#[reflect]
impl Spin {
pub fn get_speed(&self) -> f32 {
self.speed
}
pub fn set_speed(&mut self, speed: f32) {
self.speed = speed;
}
}
#[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 spin = Spin {
component_base: ComponentBase::new(),
speed: 1.5,
};
let property_names: Vec<&str> = collect_reflected_properties(&spin).iter().map(|property| property.name).collect();
assert_eq!(property_names, ["Speed", "GizmoVisible", "Enable", "ComponentType"]);
assert_eq!(read_reflected_property(&spin, "Speed"), Some(ReflectValue::Number(1.5)));
assert!(write_reflected_property(&mut spin, "Speed", &ReflectValue::Number(3.0)));
assert_eq!(spin.get_speed(), 3.0);use vanilla::core::reflection::{collect_reflected_getters, collect_reflected_properties};
use vanilla::{reflect, Component, ComponentBase};
struct Meter {
component_base: ComponentBase,
value: f32,
}
#[reflect]
impl Meter {
pub fn get_value(&self) -> f32 {
self.value
}
pub fn set_value(&mut self, value: f32) {
self.value = value;
}
}
#[reflect]
impl Component for Meter {
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 {
"Meter"
}
}
struct LabeledMeter {
component_base: ComponentBase,
meter: Meter,
label: String,
}
#[reflect(base = meter)]
impl LabeledMeter {
#[reflect(name = "Caption")]
pub fn get_label(&self) -> &str {
&self.label
}
#[reflect(name = "Caption")]
pub fn set_label(&mut self, label: &str) {
self.label = String::from(label);
}
#[reflect(transient)]
pub fn get_label_length(&self) -> usize {
self.label.len()
}
#[reflect(skip)]
pub fn get_meter(&self) -> &Meter {
&self.meter
}
}
#[reflect]
impl Component for LabeledMeter {
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 {
"LabeledMeter"
}
}
let labeled_meter = LabeledMeter {
component_base: ComponentBase::new(),
meter: Meter {
component_base: ComponentBase::new(),
value: 0.5,
},
label: String::from("hp"),
};
let property_names: Vec<&str> = collect_reflected_properties(&labeled_meter).iter().map(|property| property.name).collect();
assert_eq!(property_names, ["Caption", "Value", "GizmoVisible", "Enable", "ComponentType"]);
let getter_names: Vec<&str> = collect_reflected_getters(&labeled_meter).iter().map(|getter| getter.name).collect();
assert_eq!(getter_names, ["getCaption", "getLabelLength", "getValue"]);ToReflectValuetrait
반사 값으로 바꿀 수 있는 꼴.
Type convertible to a reflection value.
use vanilla::{Color, ReflectValue, ToReflectValue, Vector2};
assert_eq!(0.25f32.to_reflect_value(), ReflectValue::Number(0.25));
assert_eq!("left".to_reflect_value(), ReflectValue::String(String::from("left")));
assert_eq!(Some(Vector2::create(1.0, 2.0)).to_reflect_value(), ReflectValue::Vector2(Vector2::create(1.0, 2.0)));
let empty_color: Option<Color> = None;
assert_eq!(empty_color.to_reflect_value(), ReflectValue::Null);반사 값으로 바꾸기.
Converts to a reflection value.
반환ReturnsReflectValue 이 값의 반사 값.Reflection value of this value.
FromReflectValuetrait traits Sized
반사 값에서 읽을 수 있는 꼴. (꼴이 맞지 않으면 None, 원본 loadByReflection 의 typeof 가 같은지 자리)
Type readable from a reflection value. (None if the type does not match, in place of the typeof equality check of the original loadByReflection)
use vanilla::{Color, FromReflectValue, ReflectValue, Vector2};
let list_value = ReflectValue::List(vec![ReflectValue::Number(1.0), ReflectValue::Number(2.0)]);
assert_eq!(Vector2::from_reflect_value(&list_value), Some(Vector2::create(1.0, 2.0)));
assert_eq!(Color::from_reflect_value(&list_value), None);
assert_eq!(Option::<f32>::from_reflect_value(&ReflectValue::Null), Some(None));
assert_eq!(f32::from_reflect_value(&ReflectValue::Boolean(true)), None);반사 값에서 읽기.
Reads from a reflection value.
- value&'a ReflectValue
- 읽을 반사 값.Reflection value to read.
반환ReturnsOption<Self> 읽은 값. 꼴이 맞지 않으면 None.The read value. None if the type does not match.
ReflectedPropertystruct traits Clone, Copy, Debug, PartialEq, Eq
저장 속성 하나. (원본 getReflectedProperties 가 돌려주는 { name, getterName, setterName })
- name 은 원본 키(접두어를 뗀 원본 이름), getter_name 과 setter_name 은 러스트 함수 이름이다. setter_name 이 None 이면 러스트에 세터가 없다.
- is_saved 가 false 면 원본에서 값이 객체라 반사 저장이 적지 않는 속성이다. (
#[reflect(unsaved)], ShadowText 의 FontFace)
One saved property. ({ name, getterName, setterName } returned by the original getReflectedProperties)
- name is the original key (the original name with the prefix removed), getter_name and setter_name are Rust function names. If setter_name is None, Rust has no setter.
- If is_saved is false, it is a property that reflection saving does not write because its value is an object in the original. (
#[reflect(unsaved)], FontFace of ShadowText)
use vanilla::core::reflection::COMPONENT_REFLECTED_PROPERTIES;
let enable_property = COMPONENT_REFLECTED_PROPERTIES[1];
assert_eq!(enable_property.name, "Enable");
assert_eq!(enable_property.getter_name, "is_enable");
assert_eq!(enable_property.setter_name, Some("set_enable"));
assert!(enable_property.is_saved);원본 키. (접두어를 뗀 원본 이름, LineWidth)
Original key. (the original name with the prefix removed, LineWidth)
반환Returns&'static str
러스트 게터 이름. (get_line_width)
Rust getter name. (get_line_width)
반환Returns&'static str
러스트 세터 이름. 러스트에 세터가 없으면 None.
Rust setter name. None if Rust has no setter.
반환ReturnsOption<&'static str>
반사 저장이 적는 속성이면 true. (#[reflect(unsaved)] 면 false)
true if it is a property reflection saving writes. (false if #[reflect(unsaved)])
반환Returnsbool
ReflectedGetterstruct traits Clone, Debug, PartialEq
게터 하나와 그 값. (원본 getComponentProperties 가 돌려주는 { name, value }, name 은 원본 함수 이름 getLineWidth, isCircle)
One getter and its value. ({ name, value } returned by the original getComponentProperties, name is the original function name getLineWidth, isCircle)
use vanilla::core::reflection::push_reflected_getter;
use vanilla::{ReflectedGetter, ReflectValue};
let mut getter_list: Vec<ReflectedGetter> = Vec::new();
push_reflected_getter(&mut getter_list, "getSpeed", ReflectValue::Number(2.0));
push_reflected_getter(&mut getter_list, "getSpeed", ReflectValue::Number(9.0));
assert_eq!(getter_list.len(), 1);
assert_eq!(getter_list[0].name, "getSpeed");
assert_eq!(getter_list[0].value, ReflectValue::Number(2.0));원본 함수 이름. (getLineWidth, isCircle)
Original function name. (getLineWidth, isCircle)
반환Returns&'static str
Reflecttrait
반사 구현. (#[reflect] 를 붙인 impl 블록에서 매크로가 짓는다)
- 직접 구현하지 않는다. 타입의 impl 블록과 impl Component 블록에 반사 매크로를 붙이면 매크로가 짓는다.
Reflection implementation. (generated by the macro from an impl block with #[reflect])
- Do not implement it directly. Putting the reflection macro on the type's impl block and impl Component block makes the macro generate it.
use vanilla::{reflect, Component, ComponentBase, Reflect, ReflectValue};
struct Gauge {
component_base: ComponentBase,
ratio: f32,
}
#[reflect]
impl Gauge {
pub fn get_ratio(&self) -> f32 {
self.ratio
}
pub fn set_ratio(&mut self, ratio: f32) {
self.ratio = ratio;
}
}
#[reflect]
impl Component for Gauge {
}
let mut gauge = Gauge {
component_base: ComponentBase::new(),
ratio: 0.5,
};
assert_eq!(gauge.get_reflected_type_name(), "Gauge");
assert_eq!(gauge.get_reflected_properties()[0].name, "Ratio");
assert!(gauge.set_reflected_value("Ratio", &ReflectValue::Number(0.75)));
assert_eq!(gauge.get_reflected_value("Ratio"), Some(ReflectValue::Number(0.75)));
assert!(!gauge.set_reflected_value("Ratio", &ReflectValue::Boolean(true)));
assert_eq!(gauge.get_reflected_value("Missing"), None);타입 이름. (원본 constructor.name 자리, 등록하지 않은 컴포넌트를 문서에 쓸 때의 type)
Type name. (in place of the original constructor.name, the type used when writing an unregistered component to a document)
반환Returns&'static str impl 대상 타입의 이름. (경로의 끝 이름)Name of the impl target type. (the last name of the path)
저장 속성 목록. (짝이 맞는 게터와 세터, 정의 차례. Component 공통 속성은 들지 않는다)
Saved property list. (paired getters and setters, definition order. Common Component properties are not included)
반환ReturnsVec<ReflectedProperty> 저장 속성 목록. (품은 값(base)의 것 가운데 없는 키가 뒤에 붙는다)Saved property list. (keys missing here from the embedded value (base) are appended)
속성 값 읽기. (원본 키, 없는 키나 &mut self 게터면 None)
Reads a property value. (original key, None for unknown keys or &mut self getters)
- property_name&str
- 원본 키. (Speed 처럼 접두어를 뗀 이름)Original key. (a name with the prefix removed, like Speed)
반환ReturnsOption<ReflectValue> 속성 값. 없는 키, &mut self 게터, 트리를 받는 게터면 None.Property value. None for unknown keys, &mut self getters, and getters taking the tree.
속성 값 읽기. (&mut self 게터까지)
Reads a property value. (including &mut self getters)
- property_name&str
- 원본 키.Original key.
반환ReturnsOption<ReflectValue> 속성 값. 없는 키나 트리를 받는 게터면 None.Property value. None for unknown keys or getters taking the tree.
속성 값 넣기. (꼴이 맞지 않거나, 없는 키거나, 트리를 받거나 값 하나로 부를 수 없는 세터면 false)
Sets a property value. (false if the type does not match, the key is unknown, or the setter takes the tree or cannot be called with a single value)
- property_name&str
- 원본 키.Original key.
- value&ReflectValue
- 넣을 값. (세터의 꼴로 바꿔 넣는다)Value to set. (converted to the setter's type)
반환Returnsbool 넣었으면 true.true if set.
fn set_reflected_value_in_tree(&mut self, node_tree: &mut NodeTree, property_name: &str, value: &ReflectValue) -> bool#속성 값 넣기. (트리를 받는 세터까지. 이 컴포넌트는 트리에서 꺼낸 채로 부른다)
Sets a property value. (including setters taking the tree. Called with this component taken out of the tree)
- node_tree&mut NodeTree
- 트리를 받는 세터에 넘길 트리.Tree to pass to setters taking the tree.
- property_name&str
- 원본 키.Original key.
- value&ReflectValue
- 넣을 값. (세터의 꼴로 바꿔 넣는다)Value to set. (converted to the setter's type)
반환Returnsbool 넣었으면 true. 꼴이 맞지 않거나, 없는 키거나, 값 하나로 부를 수 없는 세터면 false.true if set. false if the type does not match, the key is unknown, or the setter cannot be called with a single value.
&mut self 게터가 있는지. (있으면 인스펙터와 저장이 &mut 갈래로 읽는다)
Whether there are &mut self getters. (if so, the inspector and saving read through the &mut branch)
반환Returnsbool &mut self 게터가 하나라도 있으면 true. (품은 값까지 본다)true if there is at least one &mut self getter. (also checks the embedded value)
게터 값 모으기. (인스펙터용, 세터가 없는 것까지 모든 게터. impl Component 블록에서 다시 정의한 것 → impl 블록 차례. &mut self 게터는 뺀다)
Collects getter values. (for the inspector, all getters including those without setters. Those redefined in the impl Component block → impl block order. &mut self getters are excluded)
- getter_list&mut Vec<ReflectedGetter>
- 게터를 더할 목록. (같은 이름이 이미 있으면 더하지 않는다)List to add getters to. (not added if the same name already exists)
fn collect_reflected_getters_in_tree(&self, node_tree: &NodeTree, getter_list: &mut Vec<ReflectedGetter>)#게터 값 모으기. (트리를 받는 게터까지, &mut self 게터는 뺀다. 원본은 이웃 컴포넌트를 바로 쥐는 게터가 러스트 판에서는 트리를 받는다)
Collects getter values. (including getters taking the tree, &mut self getters excluded. Getters that hold a neighboring component directly in the original take the tree in the Rust version)
- node_tree&NodeTree
- 트리를 받는 게터에 넘길 트리.Tree to pass to getters taking the tree.
- getter_list&mut Vec<ReflectedGetter>
- 게터를 더할 목록. (같은 이름이 이미 있으면 더하지 않는다)List to add getters to. (not added if the same name already exists)
fn collect_reflected_getters_mut(&mut self, node_tree: &NodeTree, getter_list: &mut Vec<ReflectedGetter>)#게터 값 모으기. (&mut self 게터와 트리를 받는 게터까지, 정의 차례. 이 컴포넌트는 트리에서 꺼낸 채로 부른다)
Collects getter values. (including &mut self getters and getters taking the tree, definition order. Called with this component taken out of the tree)
- node_tree&NodeTree
- 트리를 받는 게터에 넘길 트리.Tree to pass to getters taking the tree.
- getter_list&mut Vec<ReflectedGetter>
- 게터를 더할 목록. (같은 이름이 이미 있으면 더하지 않는다)List to add getters to. (not added if the same name already exists)
ReflectComponentGetterstrait
impl Component 블록에서 다시 정의한 게터 모으기. (#[reflect] 를 붙인 impl Component 블록에서 매크로가 짓는다)
- 원본 하위 클래스가 덮어쓴 isTickNeeded, isDrawnInsideContent 같은 것이다. 원본 인스펙터는 그 클래스의 함수로 보인다.
- 직접 구현하지 않는다. impl Component 블록에 반사 매크로를 붙이면 매크로가 짓는다.
Collects getters redefined in the impl Component block. (generated by the macro from an impl Component block with #[reflect])
- Things like isTickNeeded, isDrawnInsideContent that subclasses override in the original. The original inspector shows them as functions of that class.
- Do not implement it directly. Putting the reflection macro on the impl Component block makes the macro generate it.
use vanilla::core::reflection::{collect_reflected_getters, ReflectComponentGetters};
use vanilla::{reflect, Component, ComponentBase, ReflectedGetter, ReflectValue};
struct Label {
component_base: ComponentBase,
}
#[reflect]
impl Label {
pub fn get_text(&self) -> &str {
"hello"
}
}
#[reflect]
impl Component for Label {
fn is_tick_needed(&self) -> bool {
false
}
}
let label = Label {
component_base: ComponentBase::new(),
};
let mut getter_list: Vec<ReflectedGetter> = Vec::new();
let mut anchored_getter_list = Vec::new();
label.collect_component_getters(&mut getter_list, &mut anchored_getter_list);
assert_eq!(getter_list[0].name, "isTickNeeded");
assert_eq!(getter_list[0].value, ReflectValue::Boolean(false));
let all_getter_list = collect_reflected_getters(&label);
let getter_names: Vec<&str> = all_getter_list.iter().map(|getter| getter.name).collect();
assert_eq!(getter_names, ["isTickNeeded", "getText"]);fn collect_component_getters(&self, getter_list: &mut Vec<ReflectedGetter>, anchored_getter_list: &mut Vec<(&'static str, ReflectedGetter)>)#게터 모으기. (자리를 정한 것은 anchored_getter_list 에 (앞 원본 게터 이름, 게터) 로 담고, 나머지는 getter_list 앞에 담는다)
Collects getters. (those with a set place go into anchored_getter_list as (preceding original getter name, getter), the rest go to the front of getter_list)
- getter_list&mut Vec<ReflectedGetter>
- 자리를 정하지 않은 게터를 더할 목록.List to add getters without a set place to.
- anchored_getter_list&mut Vec<(&'static str, ReflectedGetter)>
#[reflect(after = "...")]로 자리를 정한 게터를 (앞 원본 게터 이름, 게터) 로 더할 목록.List to add getters placed with#[reflect(after = "...")]to, as (preceding original getter name, getter).
ReflectGetProbestruct traits ReflectGetViaName
게터 값 읽기의 자동 참조 특수화. (매크로가 (&&&ReflectGetProbe(&값)).read_reflect_value() 로 부른다)
- 메서드를 찾을 때 참조를 하나씩 벗기며 맞는 구현을 고르는 것을 써서, 바꿀 수 있는 꼴(ToReflectValue) → 품은 꼴(Option, 배열) → 종류 이름 차례로 고른다. 바꿀 수 없는 꼴의 게터도 컴파일 에러 없이 원본처럼 저장에서 빠지고 인스펙터에는 [종류 이름] 으로 보인다.
Autoref specialization for reading getter values. (the macro calls it as (&&&ReflectGetProbe(&value)).read_reflect_value())
- Uses the way method lookup strips references one at a time to pick a matching implementation, choosing in the order convertible type (ToReflectValue) → container type (Option, array) → type name. Getters of non-convertible types are also left out of saving like the original without a compile error, and are shown as [type name] in the inspector.
use vanilla::core::reflection::{ReflectGetProbe, ReflectGetViaName as _, ReflectGetViaOpaque as _, ReflectGetViaValue as _};
use vanilla::{ReflectValue, Vector2};
let speed = 0.5f32;
assert_eq!((&&&ReflectGetProbe(&speed)).read_reflect_value(), ReflectValue::Number(0.5));
let points = vec![Vector2::zero()];
assert_eq!((&&&ReflectGetProbe(&points)).read_reflect_value(), ReflectValue::Object(String::from("Array")));
let pair = (1u8, 2u8);
assert_eq!((&&&ReflectGetProbe(&pair)).read_reflect_value(), ReflectValue::Object(String::from("(u8, u8)")));ReflectGetViaValuetrait
바꿀 수 있는 꼴. (가장 먼저 고른다)
Convertible type. (picked first)
use vanilla::core::reflection::{ReflectGetProbe, ReflectGetViaValue};
use vanilla::ReflectValue;
let is_open = true;
assert_eq!((&&ReflectGetProbe(&is_open)).read_reflect_value(), ReflectValue::Boolean(true));게터 값을 반사 값으로 읽기.
Reads a getter value as a reflection value.
반환ReturnsReflectValue ToReflectValue 로 바꾼 값.Value converted with ToReflectValue.
ReflectOpaquetrait
품은 꼴. (Option 은 None 이면 Null 이고 Some 이면 안의 종류 이름, 배열은 Array. 원본 null 과 배열 자리)
Container type. (Option is Null if None and the inner type name if Some, arrays are Array. In place of the original null and arrays)
use vanilla::core::reflection::ReflectOpaque;
use vanilla::{Color, ReflectValue};
let color: Option<Color> = Some(Color::white());
assert_eq!(color.to_opaque_reflect_value(), ReflectValue::Object(String::from("Color")));
let empty_color: Option<Color> = None;
assert_eq!(empty_color.to_opaque_reflect_value(), ReflectValue::Null);
assert_eq!(vec![1, 2].to_opaque_reflect_value(), ReflectValue::Object(String::from("Array")));품은 꼴의 반사 값.
Reflection value of a container type.
반환ReturnsReflectValue Option 은 None 이면 Null, Some 이면 안의 종류 이름. 배열은 Object("Array").Option is Null if None, the inner type name if Some. Arrays are Object("Array").
ReflectGetViaOpaquetrait
품은 꼴 고르기. (둘째로 고른다)
Picks the container type. (picked second)
use vanilla::core::reflection::{ReflectGetProbe, ReflectGetViaOpaque};
use vanilla::ReflectValue;
let empty_list: Option<Vec<u8>> = None;
assert_eq!((&ReflectGetProbe(&empty_list)).read_reflect_value(), ReflectValue::Null);품은 꼴의 게터 값 읽기.
Reads a getter value of a container type.
반환ReturnsReflectValue ReflectOpaque 로 바꾼 값.Value converted with ReflectOpaque.
ReflectGetViaNametrait
종류 이름. (마지막으로 고른다. 원본 formatPropertyValue 의 [constructor.name] 자리)
Type name. (picked last. In place of [constructor.name] of the original formatPropertyValue)
use vanilla::core::reflection::{ReflectGetProbe, ReflectGetViaName};
use vanilla::ReflectValue;
let pair = (1u8, 2u8);
assert_eq!(ReflectGetProbe(&pair).read_reflect_value(), ReflectValue::Object(String::from("(u8, u8)")));종류 이름으로 읽기.
Reads as a type name.
반환ReturnsReflectValue Object(짧은 종류 이름).Object(short type name).
ReflectSetProbestruct traits ReflectSetViaValue<T>
세터 값 읽기의 자동 참조 특수화. (매크로가 (&ReflectSetProbe::<세터 꼴>::new(값)).convert_reflect_value() 로 부른다)
- 세터 꼴이 FromReflectValue 면 바꾸고, 아니면 늘 None 이라 그 속성은 읽기를 건너뛴다. (컴파일 에러가 없다)
Autoref specialization for reading setter values. (the macro calls it as (&ReflectSetProbe::<SetterType>::new(value)).convert_reflect_value())
- If the setter type is FromReflectValue it converts, otherwise it is always None so reading that property is skipped. (no compile error)
use std::rc::Rc;
use vanilla::core::reflection::{ReflectSetProbe, ReflectSetViaNone as _, ReflectSetViaValue as _};
use vanilla::{Color, ReflectValue};
let color_list = ReflectValue::List(vec![ReflectValue::Number(1.0), ReflectValue::Number(0.0), ReflectValue::Number(0.0), ReflectValue::Number(1.0)]);
assert_eq!((&ReflectSetProbe::<Color>::new(&color_list)).convert_reflect_value(), Some(Color::create(1.0, 0.0, 0.0, 1.0)));
assert!((&ReflectSetProbe::<Rc<Vec<u8>>>::new(&color_list)).convert_reflect_value().is_none());생성.
Constructor.
- value&'a ReflectValue
- 바꿀 반사 값.Reflection value to convert.
반환ReturnsReflectSetProbe<'a, T> 세터 꼴 T 로 바꿀 탐침.Probe that converts to setter type T.
ReflectSetViaValuetrait
읽을 수 있는 꼴. (먼저 고른다)
Readable type. (picked first)
use vanilla::core::reflection::{ReflectSetProbe, ReflectSetViaValue};
use vanilla::ReflectValue;
let number = ReflectValue::Number(3.0);
assert_eq!(ReflectSetProbe::<usize>::new(&number).convert_reflect_value(), Some(3));반사 값을 세터 꼴로 바꾸기.
Converts a reflection value to the setter type.
반환ReturnsOption<T> 바꾼 값. 꼴이 맞지 않으면 None.The converted value. None if the type does not match.
ReflectSetViaNonetrait
읽을 수 없는 꼴. (늘 None)
Unreadable type. (always None)
use std::rc::Rc;
use vanilla::core::reflection::{ReflectSetProbe, ReflectSetViaNone};
use vanilla::ReflectValue;
let number = ReflectValue::Number(3.0);
assert!((&ReflectSetProbe::<Rc<Vec<u8>>>::new(&number)).convert_reflect_value().is_none());읽을 수 없는 꼴의 값.
Value of an unreadable type.
반환ReturnsOption<T> 늘 None.Always None.
함수Functions
컴포넌트의 저장 속성 목록. (원본 collectReflectedProperties: 이 타입의 것 → Component 공통 속성, 같은 키는 앞의 것)
A component's saved property list. (Original collectReflectedProperties: this type's own, then the Component common properties, the earlier one wins for the same key)
- component&dyn Component
- 볼 컴포넌트.The component to inspect.
반환ReturnsVec<ReflectedProperty> 저장 속성 목록. (이 타입의 것 뒤에 GizmoVisible, Enable, ComponentType 가운데 없는 키)Saved property list. (after this type's, those of GizmoVisible, Enable, ComponentType whose keys are missing)
pub fn read_reflected_property(component: &dyn Component, property_name: &str) -> Option<ReflectValue>#컴포넌트의 속성 값 읽기. (원본 component[getterName](), 이 타입의 것이 먼저, 없으면 Component 공통 속성)
Reads a component's property value. (the original component[getterName](), this type's first, otherwise the common Component properties)
- component&dyn Component
- 읽을 컴포넌트.Component to read.
- property_name&str
- 원본 키.Original key.
반환ReturnsOption<ReflectValue> 속성 값. 이 타입에도 공통 속성에도 없는 키면 None.Property value. None if the key is in neither this type nor the common properties.
use vanilla::core::reflection::{read_reflected_property, write_reflected_property};
use vanilla::{reflect, Component, ComponentBase, ReflectValue};
struct Plain {
component_base: ComponentBase,
}
#[reflect]
impl Plain {}
#[reflect]
impl Component for Plain {
}
let mut plain = Plain {
component_base: ComponentBase::new(),
};
assert_eq!(read_reflected_property(&plain, "Enable"), Some(ReflectValue::Boolean(true)));
assert_eq!(read_reflected_property(&plain, "ComponentType"), Some(ReflectValue::String(String::from("Plain"))));
assert_eq!(read_reflected_property(&plain, "Speed"), None);
assert!(write_reflected_property(&mut plain, "Enable", &ReflectValue::Boolean(false)));
assert!(!plain.is_enable());
assert!(!write_reflected_property(&mut plain, "ComponentType", &ReflectValue::String(String::from("Other"))));pub fn read_reflected_property_mut(component: &mut dyn Component, property_name: &str) -> Option<ReflectValue>#컴포넌트의 속성 값 읽기. (&mut self 게터까지)
Reads a component's property value. (including &mut self getters)
- component&mut dyn Component
- 읽을 컴포넌트.Component to read.
- property_name&str
- 원본 키.Original key.
반환ReturnsOption<ReflectValue> 속성 값. 이 타입에도 공통 속성에도 없는 키면 None.Property value. None if the key is in neither this type nor the common properties.
pub fn write_reflected_property(component: &mut dyn Component, property_name: &str, value: &ReflectValue) -> bool#컴포넌트의 속성 값 넣기. (원본 component[setterName](value), 넣었으면 true. ComponentType 은 러스트에 세터가 없어 false)
Sets a component's property value. (the original component[setterName](value), true if set. false for ComponentType because Rust has no setter)
- component&mut dyn Component
- 넣을 컴포넌트.Component to set.
- property_name&str
- 원본 키.Original key.
- value&ReflectValue
- 넣을 값.Value to set.
반환Returnsbool 넣었으면 true. 꼴이 맞지 않거나, 없는 키거나, 세터가 없으면 false.true if set. false if the type does not match, the key is unknown, or there is no setter.
pub fn write_reflected_property_in_tree(component: &mut dyn Component, node_tree: &mut NodeTree, property_name: &str, value: &ReflectValue) -> bool#컴포넌트의 속성 값 넣기. (트리를 받는 세터까지. 이 컴포넌트는 트리에서 꺼낸 채로 부른다, NodeTree::with_component_at_mut)
Sets a component's property value. (including setters taking the tree. Called with this component taken out of the tree, NodeTree::with_component_at_mut)
- component&mut dyn Component
- 넣을 컴포넌트. (트리에서 꺼낸 것)Component to set. (taken out of the tree)
- node_tree&mut NodeTree
- 트리를 받는 세터에 넘길 트리.Tree to pass to setters taking the tree.
- property_name&str
- 원본 키.Original key.
- value&ReflectValue
- 넣을 값.Value to set.
반환Returnsbool 넣었으면 true. 꼴이 맞지 않거나, 없는 키거나, 세터가 없으면 false.true if set. false if the type does not match, the key is unknown, or there is no setter.
use vanilla::core::reflection::write_reflected_property_in_tree;
use vanilla::{Component, NodeTree, Paint, ReflectValue};
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let node_id = node_tree.create_child(root_id, "panel");
node_tree[node_id].add_component(Paint::new());
let is_written = node_tree.with_component_at_mut(node_id, 0, |component, tree| {
write_reflected_property_in_tree(component, tree, "Enable", &ReflectValue::Boolean(false))
});
assert_eq!(is_written, Some(true));
assert!(!node_tree[node_id].get_component::<Paint>().expect("paint").is_enable());컴포넌트의 게터 값 모두. (원본 getComponentProperties, Component 기반 클래스의 것은 빼고 그 타입의 것만)
All getter values of a component. (Original getComponentProperties, only that type's own, without those of the Component base class)
- component&dyn Component
- 볼 컴포넌트.The component to inspect.
반환ReturnsVec<ReflectedGetter> 게터 이름과 값 목록. (게터가 없는 컴포넌트는 빈 목록)List of getter names and values. (An empty list for a component without getters)
pub fn collect_reflected_getters_in_tree(component: &dyn Component, node_tree: &NodeTree) -> Vec<ReflectedGetter>#컴포넌트의 게터 값 모두. (트리를 받는 게터까지)
All getter values of a component. (Including getters that take the tree)
- component&dyn Component
- 볼 컴포넌트.The component to inspect.
- node_tree&NodeTree
- 트리를 받는 게터에 넘길 트리.Tree to pass to getters taking the tree.
반환ReturnsVec<ReflectedGetter> 게터 이름과 값 목록. (게터가 없는 컴포넌트는 빈 목록)List of getter names and values. (An empty list for a component without getters)
pub fn collect_reflected_getters_mut(component: &mut dyn Component, node_tree: &NodeTree) -> Vec<ReflectedGetter>#컴포넌트의 게터 값 모두. (&mut self 게터와 트리를 받는 게터까지. 이 컴포넌트는 트리에서 꺼낸 채로 부른다, NodeTree::with_component_at_mut)
All getter values of a component. (Including &mut self getters and getters that take the tree. Call it with the component taken out of the tree, NodeTree::with_component_at_mut)
- component&mut dyn Component
- 볼 컴포넌트. (트리에서 꺼낸 것)Component to look at. (taken out of the tree)
- node_tree&NodeTree
- 트리를 받는 게터에 넘길 트리.Tree to pass to getters taking the tree.
반환ReturnsVec<ReflectedGetter> 게터 이름과 값 목록. (게터가 없는 컴포넌트는 빈 목록)List of getter names and values. (An empty list for a component without getters)
컴포넌트에 &mut self 게터가 있는지.
Whether a component has &mut self getters.
- component&dyn Component
- 볼 컴포넌트.The component to inspect.
반환Returnsbool &mut self 게터가 있으면 true.true if there is a &mut self getter.
pub fn insert_anchored_getters(getter_list: &mut Vec<ReflectedGetter>, anchored_getter_list: Vec<(&'static str, ReflectedGetter)>)#자리를 정한 게터 넣기. (앞 게터 바로 뒤, 같은 앞 게터면 담긴 차례로. 앞 게터가 없으면 끝에, 같은 이름이 이미 있으면 넣지 않는다)
Inserts getters with a set place. (right after the preceding getter, in stored order for the same preceding getter. At the end if the preceding getter is missing, not inserted if the same name already exists)
- getter_list&mut Vec<ReflectedGetter>
- 넣을 목록.List to insert into.
- anchored_getter_listVec<(&'static str, ReflectedGetter)>
- (앞 원본 게터 이름, 게터) 목록. (담긴 차례로 넣는다)List of (preceding original getter name, getter). (inserted in stored order)
use vanilla::core::reflection::{insert_anchored_getters, push_reflected_getter};
use vanilla::{ReflectedGetter, ReflectValue};
let mut getter_list: Vec<ReflectedGetter> = Vec::new();
push_reflected_getter(&mut getter_list, "getText", ReflectValue::String(String::from("hi")));
push_reflected_getter(&mut getter_list, "getFontSize", ReflectValue::Number(16.0));
let anchored_getter_list = vec![("getText", ReflectedGetter {
name: "getFittedFontSize",
value: ReflectValue::Number(12.0),
})];
insert_anchored_getters(&mut getter_list, anchored_getter_list);
let getter_names: Vec<&str> = getter_list.iter().map(|getter| getter.name).collect();
assert_eq!(getter_names, ["getText", "getFittedFontSize", "getFontSize"]);pub fn push_reflected_getter(getter_list: &mut Vec<ReflectedGetter>, name: &'static str, value: ReflectValue)#게터 하나 더하기. (같은 이름이 이미 있으면 더하지 않는다. 원본 getComponentProperties 의 seenNames, 하위 클래스의 것이 먼저다)
Adds one getter. (not added if the same name already exists. seenNames of the original getComponentProperties, the subclass's comes first)
- getter_list&mut Vec<ReflectedGetter>
- 더할 목록.List to add to.
- name&'static str
- 원본 함수 이름. (getLineWidth)Original function name. (getLineWidth)
- valueReflectValue
- 게터 값.Getter value.
f32 를 가장 짧은 십진으로 읽은 f64. (0.22 는 0.22, 원본에서 같은 값을 자바스크립트 수로 적은 것과 같다)
f64 read from the shortest decimal of an f32. (0.22 becomes 0.22, the same as writing that value as a JavaScript number in the original)
- numberf32
- 바꿀 수.Number to convert.
반환Returnsf64 가장 짧은 십진 글로 읽은 f64. (무한과 NaN 은 그대로 넓힌다)f64 read from the shortest decimal text. (infinities and NaN are widened as is)
use vanilla::core::reflection::read_shortest_number;
assert_eq!(read_shortest_number(0.22), 0.22);
assert_ne!(0.22f32 as f64, 0.22);꼴의 짧은 이름. (모듈 경로와 감싼 꼴을 벗긴다. &alloc::rc::Rc<vanilla::core::image::Image> → Image)
Short name of a type. (strips the module path and wrapper types. &alloc::rc::Rc<vanilla::core::image::Image> → Image)
반환ReturnsString 모듈 경로와 앞의 &, 감싼 꼴(Rc, Arc, Box, RefCell, Cell)을 벗긴 이름. (안쪽 제네릭 인자의 경로도 벗긴다)Name with the module path, leading &, and wrapper types (Rc, Arc, Box, RefCell, Cell) stripped. (paths of inner generic arguments are stripped too)
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::core::reflection::read_short_type_name;
use vanilla::{Color, Vector2};
assert_eq!(read_short_type_name::<Rc<RefCell<Color>>>(), "Color");
assert_eq!(read_short_type_name::<&Vector2>(), "Vector2");
assert_eq!(read_short_type_name::<Option<Color>>(), "Option<Color>");상수Constants
원본 Component 기반 클래스의 저장 속성. (isGizmoVisible / setGizmoVisible, isEnable / setEnable, getComponentType / setComponentType, 정의 차례)
Saved properties of the original Component base class. (isGizmoVisible / setGizmoVisible, isEnable / setEnable, getComponentType / setComponentType, definition order)
반환Returns[ReflectedProperty; 3]
ReflectValueenum traits Clone, Debug, PartialEq
반사 값. (원본 게터가 돌려주는 자바스크립트 값 자리)
- Null 은 원본 null(러스트 None), List 는 문서에서 읽은 배열, Object 는 옮길 수 없는 값의 종류 이름이다. (인스펙터의
[이름])
Reflection value. (in place of the JavaScript values the original getters return)
- Null is the original null (Rust None), List is an array read from a document, Object is the type name of a value that cannot be carried over. (
[name]in the inspector)
| 이름Name | 값Value | 설명Description |
|---|---|---|
Null | 값 없음. (원본 null, 러스트 None)No value. (the original null, Rust None) | |
Boolean | Boolean(bool) | 불.Boolean. |
Number | Number(f64) | 수. (f32 와 정수 꼴도 이것으로 바꾼다)Number. (f32 and integer types are converted to this too) |
String | String(String) | 글. (원본에서 글인 열거도 이것)Text. (also enums that are text in the original) |
Vector2 | Vector2(Vector2) | 2차원 벡터.2D vector. |
Color | Color(Color) | 색.Color. |
Rect | Rect(Rect) | 사각형.Rect. |
Node | Node(NodeId) | 노드 핸들.Node handle. |
List | List(Vec<ReflectValue>) | 문서에서 읽은 배열. (Vector2 는 수 둘, Color 는 수 넷으로 받는다)Array read from a document. (Vector2 is taken as two numbers, Color as four) |
Object | Object(String) | 옮길 수 없는 값의 종류 이름. (인스펙터의 [이름])Type name of a value that cannot be carried over. ([name] in the inspector) |