API / macros
macros
바닐라엔진 절차 매크로. (원본 vanilla.js 의 실행 중 반사 자리)
- 원본은 자바스크립트라 실행 중에 객체의 프로토타입을 훑어 get, is, set 함수를 찾는다. (ui/uidocument.js 의 collectReflectedProperties, misc/devtools.js 의 getComponentProperties) 러스트에는 실행 중 반사가 없어, 언리얼의 UHT(UPROPERTY), Qt 의 moc 처럼 컴파일 때 코드를 지어 같은 일을 한다.
#[reflect]를 컴포넌트의 impl 블록에 붙이면 블록 안의pub fn get_*(&self) -> T,pub fn is_*(&self) -> T와 그 짝pub fn set_*(&mut self, value)를 모아 vanilla::core::reflection::Reflect 구현을 짓는다.#[reflect]를 impl Component 블록에 붙이면 그 블록에서 다시 정의한 게터(원본 하위 클래스가 덮어쓴 isTickNeeded 같은 것)를 인스펙터용으로 모은다. 그 블록에 fn draw 가 없으면 Component::is_draw_overridden 을 false 로 짓는다. (그리지 않는 컴포넌트, 원본 draw === Component.prototype.draw) 두 블록 모두 붙여야 한다. Reflect 가 Component 의 상위 트레이트라 어느 쪽을 빠뜨려도 컴파일 에러다. (원본처럼 모든 컴포넌트가 반사된다) 게터가 없는 타입은 빈 블록#[reflect] impl 타입 {}에 붙인다.- 원본 규칙을 그대로 따른다:
- 게터는 인자 없는
get*,is*함수다. (원본getterFunction.length === 0) 저장 속성은 같은 키의set*이 있는 게터만이다. (원본"set" + baseName) &mut self 게터도 게터다. (원본 함수에는 &self, &mut self 구별이 없다) 반사가 &mut 를 받는 갈래(get_reflected_value_mut, collect_reflected_getters_mut)로 부른다. 러스트의 _mut 접근자(get_uiview_mut 같은 것)와 &mut 를 돌려주는 함수는 원본 게터가 아니라 뺀다. - 세터는 값 하나를 받는
set*이다. 트리를 받고 값을 받는 세터(set_snap_current_index(트리, 칸) 같은 것)도 알아보고, 트리를 쥔 쪽(UIDocument 읽기)이 set_reflected_value_in_tree 로 원본처럼 부른다. - 트리만 받는 게터(get_target_button(&self, 트리) 같은 것)도 원본 게터다. 원본은 이웃 컴포넌트를 바로 쥐지만 러스트 판은 트리에서 꺼낸다. 트리를 쥔 쪽(DevTools 인스펙터)이 collect_reflected_getters_in_tree 로 부른다. 저장 속성은 아니다.
- 키는 접두어(get, is)를 뗀 원본 이름이다. 러스트 snake_case 를 원본 camelCase 로 되돌린다. (get_line_width → getLineWidth → LineWidth)
- 차례는 정의 차례, 같은 키는 먼저 나온 것이다.
- 값으로 바꿀 수 없는 꼴의 게터도 컴파일 에러를 내지 않는다. 자동 참조 특수화(autoref specialization)로 바꿀 수 있는 꼴만 값으로 읽고, 나머지는 원본처럼 저장에서 건너뛰고 인스펙터에는
[종류 이름]으로 보인다. - 함수에 붙이는 것:
#[reflect(skip)]반사에서 뺀다.#[reflect(transient)]인스펙터에는 보이되 속성 목록에서 뺀다.#[reflect(unsaved)]속성 목록에는 두되 반사 저장과 읽기에서 뺀다. (원본에서 값이 객체라 saveByReflection 이 적지 않는 속성, ShadowText 의 FontFace)#[reflect(name = "UIScale")]원본 키 이름을 정한다. (원본 이름의 머리글자 낱말처럼 snake_case 에서 되돌릴 수 없는 이름, 원본과 이름이 다른 게터)#[reflect(after = "getFittedFontSize")]impl Component 블록의 게터를 인스펙터 목록에서 그 원본 게터 뒤에 둔다. (원본 클래스 몸통의 차례, 없으면 맨 앞) - 블록에 붙이는 것:
#[reflect(base = 필드)]품은 값의 반사를 원본 상위 클래스처럼 뒤에 잇는다.#[reflect(crate = 경로)]엔진 경로. (기본 ::vanilla, 엔진 크레이트 안에서는 lib.rs 의 extern crate self as vanilla 로 같은 경로가 통한다)
vanilla-engine procedural macros. (in place of the runtime reflection of the original vanilla.js)
- The original is JavaScript, so at runtime it walks an object's prototype to find get, is, set functions. (collectReflectedProperties in ui/uidocument.js, getComponentProperties in misc/devtools.js) 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 job.
- Putting
#[reflect]on a component's impl block gathers the block'spub fn get_*(&self) -> T,pub fn is_*(&self) -> Tand their pairedpub fn set_*(&mut self, value)to build a vanilla::core::reflection::Reflect implementation. #[reflect]on an impl Component block collects the getters redefined in that block (like isTickNeeded overridden by an original subclass) for the inspector. When that block has no fn draw, it generates Component::is_draw_overridden returning false. (a component that draws nothing, original draw === Component.prototype.draw) Both blocks must have it. Reflect is a supertrait of Component, so leaving out either one is a compile error. (Like the original, every component is reflected) A type without getters takes it on an empty block,#[reflect] impl Type {}.- Follows the original rules as is:
- Getters are argumentless
get*,is*functions. (originalgetterFunction.length === 0) Saved properties are only getters with aset*of the same key. (original"set" + baseName) &mut self getters are getters too. (the original functions make no &self, &mut self distinction) Reflection calls them through the branches that take &mut (get_reflected_value_mut, collect_reflected_getters_mut). Rust _mut accessors (like get_uiview_mut) and functions returning &mut are not original getters, so they are excluded. - Setters are
set*taking one value. Setters taking the tree and a value (like set_snap_current_index(tree, slot)) are also recognized, and the side holding the tree (UIDocument reading) calls them with set_reflected_value_in_tree as in the original. - Getters taking only the tree (like get_target_button(&self, tree)) are original getters too. The original holds neighbor components directly, but the Rust version takes them out of the tree. The side holding the tree (the DevTools inspector) calls them with collect_reflected_getters_in_tree. They are not saved properties.
- The key is the original name with the prefix (get, is) removed. Rust snake_case is turned back into the original camelCase. (get_line_width → getLineWidth → LineWidth)
- The order is definition order, and on the same key the first one wins.
- Getters of types that cannot be turned into values do not cause compile errors either. Through autoref specialization (autoref specialization) only convertible types are read as values, and the rest are skipped in saving as in the original and shown in the inspector as
[kind name]. - Put on functions:
#[reflect(skip)]excludes from reflection.#[reflect(transient)]shows in the inspector but excludes from the property list.#[reflect(unsaved)]keeps it in the property list but excludes it from reflection saving and reading. (properties saveByReflection does not write because the value is an object in the original, ShadowText's FontFace)#[reflect(name = "UIScale")]sets the original key name. (names that cannot be recovered from snake_case, like acronym words in original names, and getters whose names differ from the original)#[reflect(after = "getFittedFontSize")]places an impl Component block getter after that original getter in the inspector list. (the order in the original class body, at the front if absent) - Put on blocks:
#[reflect(base = field)]chains the reflection of a held value afterwards, like an original superclass.#[reflect(crate = path)]engine path. (default ::vanilla, inside the engine crate the same path works through extern crate self as vanilla in lib.rs)
예제Exampleimpl 블록과 impl Component 블록에 붙이기 (ignore: 절차 매크로 크레이트의 doctest 는 엔진을 의존하지 못한다. 같은 예제를 엔진의 core::reflection 모듈 예제가 돌린다)Putting it on an impl block and an impl Component block (ignore: doctests of the procedural macro crate cannot depend on the engine. The engine's core::reflection module example runs the same example)
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);함수Functions
반사 매크로. (impl 블록에 붙인다. 트레이트 impl 이면 impl Component 블록으로 본다)
- 게임은 엔진이 다시 내보낸 vanilla::reflect 로 쓴다. (
use vanilla::reflect;뒤#[reflect], 또는#[vanilla::reflect]) - 컴포넌트의 impl 블록과 impl Component 블록 둘 다에 붙인다. 한쪽만 붙이면 컴파일 에러가 붙일 곳을 알려 준다.
- 블록 옵션은
base = 필드,crate = 경로이고, 함수 옵션은skip,transient,unsaved,name = "...",after = "..."이다. (impl Component 블록에는 base 를 쓰지 않는다)
Reflection macro. (put on an impl block. A trait impl is treated as an impl Component block)
- Games use vanilla::reflect re-exported by the engine. (
#[reflect]afteruse vanilla::reflect;, or#[vanilla::reflect]) - Put it on both the component's impl block and the impl Component block. If only one has it, the compile error tells where to put it.
- Block options are
base = field,crate = path, and function options areskip,transient,unsaved,name = "...",after = "...". (base is not used on impl Component blocks)
예제Example함수 옵션과 품은 값 (ignore: 절차 매크로 크레이트의 doctest 는 엔진을 의존하지 못한다. 같은 예제를 엔진의 core::reflection 모듈 예제가 돌린다)Function options and held values (ignore: doctests of the procedural macro crate cannot depend on the engine. The engine's core::reflection module example runs the same example)
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).expect("reflection").iter().map(|getter| getter.name).collect();
assert_eq!(getter_names, ["getCaption", "getLabelLength", "getValue"]);