vanilladocs
vanillapunch.com
API / animation/timeline

animation/timeline

타임라인. (키프레임 애니메이션 문서 재생기)

  • 원본 animation/timeline.js 를 옮긴 것이다. 문서(서술)는 무대 노드 목록 + 트랙(대상 이름 / 속성 / 키) + 마커로 이루어진 JSON 이며 타임라인 편집기가 저장한다. 키의 easing 은 그 키에서 다음 키까지 구간에 걸린다.
  • 이징 곡선은 core/tween.rs 의 easing_function 을 그대로 쓴다. "bezier" 는 CSS cubic-bezier 와 같은 제어점이다.
  • 사용:
// 씬 create 에서 문서를 요청하고 맡긴다.
self.timeline_asset.load(engine, "assets/intro.timeline.json");
self.scene_base.track_asset(&self.timeline_asset);
// initialize 에서 무대를 만들고 튼다.
let mut timeline = Timeline::create_from_json_asset(&mut self.timeline_asset).unwrap_or_default();
let stage_id = self.scene_base.get_root_id();
timeline.build_stage(self.scene_base.get_node_tree_mut(), stage_id, Some(&|image_name: &str| image_table.get(image_name).cloned()));
timeline.play();
// 매 프레임 (tick):
timeline.tick(self.scene_base.get_node_tree_mut(), time_delta);
  • 원본과 다른 점:
  • 대상은 객체 참조 대신 TimelineTarget 이다. 노드는 Node(NodeId), 노드가 아닌 것(화면 효과 같은)은 External(Rc<RefCell<dyn TimelinePropertyTarget>>) 이다. 노드에 거는 함수(tick, seek, stop, evaluate, compile, build_stage, bind)는 NodeTree 를 같이 받는다.
  • External 대상에는 원본처럼 evaluate 가 그 자리에서 set_timeline_property 를 부른다. (씬은 대상을 Rc<RefCell> 로 나눠 쥔다) 넘겨받는 쪽은 TimelinePropertyTarget 트레이트를 구현한다. ScreenEffect 는 이 파일에서 구현했다. 마지막 evaluate 가 External 대상에 건 값은 get_external_properties 로 읽을 수 있다. (편집기와 시험용)
  • 값은 원본의 숫자 / 문자열 / 참거짓을 TimelineValue 열거형으로 든다. 숫자는 f64 다.
  • 핸들러는 원본처럼 마지막 인자로 타임라인 자신(&mut Timeline)을 받고, 노드에 거는 함수에 넘길 NodeTree 를 그 뒤에 같이 받는다. 부르는 동안 핸들러를 칸에서 꺼내 두므로 핸들러 안에서 pause, seek, set_*_handler 를 부를 수 있다. (새로 건 핸들러가 이긴다)
  • 글 속성(text, number, fontSize, visibleCharacters, color)은 원본 getComponent(Text) 가 Text 를 상속한 RichText 도 찾듯 RichText 노드에도 건다.
  • resolve_timeline_easing 은 함수 대신 TimelineEasing 값을 돌려준다. (evaluate(progress) 로 부른다)
  • TIMELINE_PROPERTY_DEFINITIONS 는 이름 → 정의 객체 대신 정의 배열이고 find_timeline_property_definition 으로 찾는다. TIMELINE_NODE_DEFAULTS 는 기본값을 채운 TimelineNodeDescription 이다. (원본 키 type 은 node_type)
  • 원본의 스프라이트 격자 표와 사운드 표(WeakMap)는 노드에 붙는 작은 컴포넌트 TimelineSpriteFrameGrid, TimelineSound 로 바꿨다.
  • 원본 Timeline.setAudioManager(정적)와 사운드 노드의 비동기 읽기는 load_sounds(node_tree, engine) 로 바꿨다. 무대를 만든 뒤 한 번 부르면 사운드 노드마다 오디오 애셋을 읽고 플레이어를 만든다. (돌려준 애셋을 씬이 track_audio_asset 으로 맡겨도 된다)
  • loadFromUrl(비동기 fetch)은 load_from_url(엔진, 애셋 경로)이다. 엔진의 애셋 받기로 바이트를 부탁하고, 엔진 작업 안에서 await 하면 타임라인이 나온다. (데스크탑은 애셋 폴더 후보, 웹은 asset_base_url 에서 fetch) await 없이는 JsonAsset 으로 받은 문서를 create_from_json_asset / load_from_text 로 넘긴다.
  • "data:" 주소 이미지: 웹은 원본처럼 브라우저가 풀어(fetch 와 HTMLImageElement, platform/web.rs) 다 풀리면 스프라이트에 걸고 서술의 칸을 다시 고른다. (원본 image.onload 의 applySpriteFrame, 그동안 TimelineSpriteFrameGrid 가 기다리며 갱신한다) 데스크탑은 그 자리에서 푼다. 브라우저처럼 본문의 퍼센트 꼴(%XX)을 먼저 풀고, ;base64 면 base64 를 푼다. 주소의 형이 image/svg+xml 이면 resvg 로 그린 SVG, 그 밖은 내용으로 가린 래스터(png, jpeg, webp, gif, bmp, ico, avif)다. (Image::load_from_memory_with_mime_type)
  • 이징 곡선 값은 원본과 같다. 같은 이름의 무대 노드가 둘이면 모두 붙이고 이름 표에는 뒤의 것이 남는다(원본과 같다). 부모가 자기 자신이거나 고리가 되면 무대 부모에 붙인다. load_from_text, create_from_json_asset 은 원본에도 있다.

Timeline. (keyframe animation document player)

  • A port of the original animation/timeline.js. The document (description) is JSON made of a stage node list + tracks (target name / property / keys) + markers, saved by the timeline editor. A key's easing applies to the span from that key to the next key.
  • Easing curves use easing_function from core/tween.rs as is. "bezier" uses the same control points as CSS cubic-bezier.
  • Usage:
// Request the document in the scene's create and hand it over.
self.timeline_asset.load(engine, "assets/intro.timeline.json");
self.scene_base.track_asset(&self.timeline_asset);
// Build the stage in initialize and play it.
let mut timeline = Timeline::create_from_json_asset(&mut self.timeline_asset).unwrap_or_default();
let stage_id = self.scene_base.get_root_id();
timeline.build_stage(self.scene_base.get_node_tree_mut(), stage_id, Some(&|image_name: &str| image_table.get(image_name).cloned()));
timeline.play();
// Every frame (tick):
timeline.tick(self.scene_base.get_node_tree_mut(), time_delta);
  • Differences from the original:
  • Targets are TimelineTarget instead of object references. Nodes are Node(NodeId), and things that are not nodes (such as screen effects) are External(Rc<RefCell<dyn TimelinePropertyTarget>>). Functions that act on nodes (tick, seek, stop, evaluate, compile, build_stage, bind) also take the NodeTree.
  • For External targets, evaluate calls set_timeline_property right there, as in the original. (the scene shares the target as Rc<RefCell>) The receiving side implements the TimelinePropertyTarget trait. ScreenEffect implements it in this file. Values the last evaluate applied to External targets can be read with get_external_properties. (for editors and tests)
  • Values hold the original's number / string / boolean as the TimelineValue enum. Numbers are f64.
  • Handlers take the timeline itself (&mut Timeline) as the last argument as in the original, followed by the NodeTree to pass to node functions. The handler is taken out of its slot while it is called, so pause, seek and set_*_handler can be called inside a handler. (a newly set handler wins)
  • Text properties (text, number, fontSize, visibleCharacters, color) also apply to RichText nodes, just as the original getComponent(Text) also finds RichText, which inherits Text.
  • resolve_timeline_easing returns a TimelineEasing value instead of a function. (call it with evaluate(progress))
  • TIMELINE_PROPERTY_DEFINITIONS is an array of definitions instead of a name → definition object, searched with find_timeline_property_definition. TIMELINE_NODE_DEFAULTS is a TimelineNodeDescription filled with the defaults. (the original key type is node_type)
  • The original's sprite grid table and sound table (WeakMap) became small components attached to nodes, TimelineSpriteFrameGrid and TimelineSound.
  • The original Timeline.setAudioManager (static) and the asynchronous loading of sound nodes became load_sounds(node_tree, engine). Calling it once after building the stage loads an audio asset and creates a player for each sound node. (the scene may take over the returned assets with track_audio_asset)
  • loadFromUrl (asynchronous fetch) is load_from_url(engine, asset path). It asks for the bytes through the engine's asset fetching, and awaiting it inside an engine task yields the timeline. (desktop uses the asset folder candidates, web fetches from asset_base_url) Without await, pass a document received with JsonAsset to create_from_json_asset / load_from_text.
  • "data:" URL images: on the web, as in the original, the browser decodes them (fetch and HTMLImageElement, platform/web.rs), and once decoded they are set on the sprite and the description's cell is picked again. (the original image.onload's applySpriteFrame; meanwhile TimelineSpriteFrameGrid waits and updates) On desktop they are decoded right there. Like a browser, it first decodes percent forms (%XX) in the body, and decodes base64 if ;base64. If the URL's type is image/svg+xml it is an SVG drawn with resvg, otherwise a raster identified by its content (png, jpeg, webp, gif, bmp, ico, avif). (Image::load_from_memory_with_mime_type)
  • Easing curve values are the same as the original. If two stage nodes have the same name, both are attached and the later one stays in the name table (same as the original). If a parent is itself or forms a cycle, the node is attached to the stage parent. load_from_text and create_from_json_asset also exist in the original.

TimelinePropertyDefinitionstruct traits Clone, Copy, Debug

소스source

속성 정의. (이름 → 종류 / 표시 이름 / 노드에 거는 함수)

  • TIMELINE_PROPERTY_DEFINITIONS 에 든다. 정의가 없는 속성은 노드에 걸지 않고 External 대상에만 넘긴다.

Property definition. (name → kind / display name / function applied to the node)

  • Stored in TIMELINE_PROPERTY_DEFINITIONS. Properties with no definition are not applied to nodes and are passed only to External targets.
예제Exampleopacity 정의를 찾아 노드에 걸기Find the opacity definition and apply it to a node
use vanilla::{find_timeline_property_definition, TimelinePropertyKind, TimelineValue, WorldNode};

let definition = find_timeline_property_definition("opacity").expect("opacity");
assert_eq!(definition.kind, TimelinePropertyKind::Number);
assert_eq!(definition.label, "Opacity");
let mut node = WorldNode::new("box");
if let Some(apply) = definition.apply {
	apply(&mut node, &TimelineValue::Number(1.5));
}
assert_eq!(node.get_local_opacity(), 1.0);
assert!(find_timeline_property_definition("event").is_some_and(|definition| definition.apply.is_none()));
필드fieldpub name: &'static str#0.3.2 부터since 0.3.2소스source

서술 트랙의 property 이름. (원본 이름 그대로, "scaleX" 처럼)

Property name of the description track. (the original name as is, like "scaleX")

반환Returns&'static str

필드fieldpub kind: TimelinePropertyKind#0.3.2 부터since 0.3.2소스source

값 종류. (보간 방식을 정한다)

Value kind. (decides the interpolation method)

반환ReturnsTimelinePropertyKind

필드fieldpub label: &'static str#0.3.2 부터since 0.3.2소스source

편집기에 보일 이름.

Name shown in the editor.

반환Returns&'static str

필드fieldpub apply: Option<fn(&mut WorldNode, &TimelineValue)>#0.3.2 부터since 0.3.2소스source

노드에 값을 거는 함수. None 이면 노드에 걸지 않는다. ("event")

Function that applies the value to a node. If None, it is not applied to nodes. ("event")

반환ReturnsOption<fn(&mut WorldNode, &TimelineValue)>

TimelineKeystruct traits Clone, Debug, PartialEq

소스source

키 하나. (시간, 값, 그 키에서 다음 키까지의 이징, bezier 제어점)

One key. (time, value, easing from this key to the next key, bezier control points)

예제Examplequadratic.in 으로 0 에서 100 까지 가는 두 키Two keys going from 0 to 100 with quadratic.in
use serde_json::json;
use vanilla::{Timeline, TimelineKey, TimelinePropertyKind, TimelineValue};

let mut start_key = TimelineKey::new(0.0, TimelineValue::Number(0.0));
start_key.easing = String::from("quadratic.in");
let end_key = TimelineKey::from_json(&json!({ "time": 2, "value": 100 }));
let keys = vec![start_key, end_key];
assert_eq!(Timeline::sample_keys(&keys, TimelinePropertyKind::Number, 1.0), TimelineValue::Number(25.0));
assert_eq!(Timeline::sample_keys(&keys, TimelinePropertyKind::Number, 3.0), TimelineValue::Number(100.0));
생성자constructorpub fn new(time: f64, value: TimelineValue) -> TimelineKey#0.3.2 부터since 0.3.2소스source

생성. (이징 linear)

Constructor. (easing linear)

timef64
키 시간. (초)Key time. (seconds)
valueTimelineValue
키 값.Key value.

반환ReturnsTimelineKey 이징 "linear", 제어점 없는 키.A key with easing "linear" and no control points.

정적staticpub fn from_json(key_description: &Value) -> TimelineKey#0.3.2 부터since 0.3.2소스source

JSON 키에서 만들기. ({ time, value, easing, curve })

Creates from a JSON key. ({ time, value, easing, curve })

key_description&Value
서술 키 객체. (빠진 time 은 0, value 는 None, easing 은 빈 글, curve 는 None. curve 의 숫자가 아닌 칸은 0)Description key object. (a missing time is 0, value is None, easing is an empty string, curve is None. Non-number entries of curve are 0)

반환ReturnsTimelineKey 읽은 키.The read key.

필드fieldpub time: f64#0.3.2 부터since 0.3.2소스source

키 시간. (초)

Key time. (seconds)

반환Returnsf64

필드fieldpub value: TimelineValue#0.3.2 부터since 0.3.2소스source

키 값.

Key value.

반환ReturnsTimelineValue

필드fieldpub easing: String#0.3.2 부터since 0.3.2소스source

이 키에서 다음 키까지 구간의 이징 이름. (빈 글과 모르는 이름은 linear)

Easing name of the span from this key to the next key. (empty strings and unknown names are linear)

반환ReturnsString

필드fieldpub curve: Option<Vec<f64>>#0.3.2 부터since 0.3.2소스source

easing 이 "bezier" 일 때의 제어점 [x1, y1, x2, y2]. (None 이면 ease-in-out)

Control points [x1, y1, x2, y2] when easing is "bezier". (ease-in-out if None)

반환ReturnsOption<Vec<f64>>

메서드methodpub fn resolve_easing(&self) -> TimelineEasing#0.3.2 부터since 0.3.2소스source

이 키에서 시작하는 구간의 이징.

Easing of the span starting at this key.

반환ReturnsTimelineEasing easing 과 curve 로 고른 이징. (resolve_timeline_easing 과 같다)Easing chosen from easing and curve. (same as resolve_timeline_easing)

TimelineMarkerstruct traits Clone, Debug, PartialEq

소스source

마커. (시간과 이름. 지나치면 마커 핸들러가 불린다)

Marker. (time and name. The marker handler is called when it is passed)

예제Example1초 재생하며 지난 마커 받기Play for 1 second and receive the markers passed
use std::cell::RefCell;
use std::rc::Rc;
use serde_json::json;
use vanilla::{NodeTree, Timeline, TimelineMarker};

let passed_list: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
let mut node_tree = NodeTree::new();
let mut timeline = Timeline::new(Some(json!({
	"duration": 2,
	"loop": false,
	"markers": [{ "time": 0.5, "name": "hit" }, { "time": 1.5, "name": "end" }],
})));
let recorded_list = passed_list.clone();
timeline.set_marker_handler(Some(Box::new(move |marker_name: &str, marker: &TimelineMarker, _timeline: &mut Timeline, _node_tree: &mut NodeTree| {
	recorded_list.borrow_mut().push(format!("{} {}", marker_name, marker.time));
})));
timeline.play();
timeline.tick(&mut node_tree, 1.0);
assert_eq!(*passed_list.borrow(), vec![String::from("hit 0.5")]);
필드fieldpub time: f64#0.3.2 부터since 0.3.2소스source

마커 시간. (초)

Marker time. (seconds)

반환Returnsf64

필드fieldpub name: String#0.3.2 부터since 0.3.2소스source

마커 이름.

Marker name.

반환ReturnsString

TimelinePropertyTargettrait

소스source

노드가 아닌 대상이 값을 받는 트레이트. (원본 setTimelineProperty(이름, 값))

  • Rc<RefCell<..>> 로 쥐고 TimelineTarget::External 로 등록하면 evaluate 가 그 자리에서 부른다.

Trait for targets that are not nodes to receive values. (the original setTimelineProperty(name, value))

  • Hold it as Rc<RefCell<..>> and register it as TimelineTarget::External, and evaluate calls it right there.
예제Example트랙 값을 받는 페이드 대상Fade target receiving track values
use std::cell::RefCell;
use std::rc::Rc;
use serde_json::json;
use vanilla::{NodeTree, Timeline, TimelinePropertyTarget, TimelineTarget, TimelineValue};

struct Fader {
	alpha: f64,
}

impl TimelinePropertyTarget for Fader {
	fn set_timeline_property(&mut self, property_name: &str, value: &TimelineValue) {
		if property_name == "alpha" {
			self.alpha = value.as_number();
		}
	}
}

let fader: Rc<RefCell<Fader>> = Rc::new(RefCell::new(Fader { alpha: 0.0 }));
let fader_target: Rc<RefCell<dyn TimelinePropertyTarget>> = fader.clone();
let mut node_tree = NodeTree::new();
let mut timeline = Timeline::new(Some(json!({
	"duration": 2,
	"tracks": [{ "target": "fader", "property": "alpha", "keys": [{ "time": 0, "value": 0 }, { "time": 2, "value": 1 }] }],
})));
timeline.set_target("fader", TimelineTarget::External(fader_target));
timeline.evaluate(&mut node_tree, 1.0);
assert_eq!(fader.borrow().alpha, 0.5);
메서드methodfn set_timeline_property(&mut self, property_name: &str, value: &TimelineValue)#0.3.2 부터since 0.3.2소스source

속성 값 받기.

Receives a property value.

property_name&str
서술 트랙의 property 이름.Property name of the description track.
value&TimelineValue
그 시간에 표본한 값.Value sampled at that time.

TimelineExternalPropertystruct traits Clone, Debug, PartialEq

소스source

External 대상에 건 값 하나. (get_external_properties)

One value applied to an External target. (get_external_properties)

예제Exampleevaluate 뒤 External 대상에 건 값 읽기Read the values applied to External targets after evaluate
use std::cell::RefCell;
use std::rc::Rc;
use serde_json::json;
use vanilla::{NodeTree, Timeline, TimelineExternalProperty, TimelinePropertyTarget, TimelineTarget, TimelineValue};

struct Silent;

impl TimelinePropertyTarget for Silent {
	fn set_timeline_property(&mut self, _property_name: &str, _value: &TimelineValue) {
	}
}

let screen: Rc<RefCell<dyn TimelinePropertyTarget>> = Rc::new(RefCell::new(Silent));
let mut node_tree = NodeTree::new();
let mut timeline = Timeline::new(Some(json!({
	"duration": 2,
	"tracks": [{ "target": "screen", "property": "vignette", "keys": [{ "time": 0, "value": 0 }, { "time": 2, "value": 1 }] }],
})));
timeline.set_target("screen", TimelineTarget::External(screen));
timeline.evaluate(&mut node_tree, 1.0);
let expected_property = TimelineExternalProperty {
	target_name: String::from("screen"),
	property_name: String::from("vignette"),
	value: TimelineValue::Number(0.5),
};
assert_eq!(timeline.get_external_properties(), &[expected_property]);
필드fieldpub target_name: String#0.3.2 부터since 0.3.2소스source

트랙 대상 이름.

Track target name.

반환ReturnsString

필드fieldpub property_name: String#0.3.2 부터since 0.3.2소스source

트랙 속성 이름.

Track property name.

반환ReturnsString

필드fieldpub value: TimelineValue#0.3.2 부터since 0.3.2소스source

건 값.

The applied value.

반환ReturnsTimelineValue

TimelineNodeDescriptionstruct traits Clone, Debug, PartialEq, Default

소스source

서술 노드. (원본 무대 노드 서술. TIMELINE_NODE_DEFAULTS 가 기본값)

  • 필드 이름은 snake_case 이고 서술 JSON 의 키는 원본 그대로 camelCase 다. (scale_x ← "scaleX")

Description node. (the original stage node description. TIMELINE_NODE_DEFAULTS holds the defaults)

  • Field names are snake_case, and keys of the description JSON are camelCase as in the original. (scale_x ← "scaleX")
예제Example서술 JSON 을 기본값 위에 읽기Read description JSON over the defaults
use serde_json::json;
use vanilla::{TimelineNodeDescription, TIMELINE_NODE_DEFAULTS};

let description = TimelineNodeDescription::from_json(&json!({ "name": "Box", "type": "paint", "x": 40, "scaleX": 2, "visible": false }));
assert_eq!(description.node_type, "paint");
assert_eq!(description.x, 40.0);
assert_eq!(description.scale_x, 2.0);
assert!(!description.visible);
assert_eq!(description.width, TIMELINE_NODE_DEFAULTS.width);
assert_eq!(description.color, "#ffffffff");
정적staticpub fn from_json(node_description: &Value) -> TimelineNodeDescription#0.3.2 부터since 0.3.2소스source

JSON 서술에서 만들기. (기본값 위에 준 항목을 덮는다. 원본 Object.assign({}, TIMELINE_NODE_DEFAULTS, 서술))

  • 꼴이 맞지 않는 항목은 기본값을 둔다. visible 은 원본처럼 false 일 때만 끈다.

Creates from a JSON description. (the given entries overwrite the defaults. The original Object.assign({}, TIMELINE_NODE_DEFAULTS, description))

  • Entries of the wrong shape keep the default. visible is turned off only when false, as in the original.
node_description&Value
서술 stage.nodes 의 노드 객체.Node object from the description's stage.nodes.

반환ReturnsTimelineNodeDescription 기본값을 채운 서술 노드.Description node filled with defaults.

필드fieldpub name: String#0.3.2 부터since 0.3.2소스source

노드 이름. (트랙의 target 이 이 이름을 가리킨다, 기본 빈 글)

Node name. (a track's target points to this name, default empty string)

반환ReturnsString

필드fieldpub node_type: String#0.3.2 부터since 0.3.2소스source

원본 키 type. ("group", "paint", "sprite", "text", "particle", "sound")

The original key type. ("group", "paint", "sprite", "text", "particle", "sound")

반환ReturnsString

필드fieldpub parent: Option<String>#0.3.2 부터since 0.3.2소스source

부모 노드 이름. (None 이면 무대 부모에 붙는다)

Parent node name. (if None, attached to the stage parent)

반환ReturnsOption<String>

필드fieldpub x: f64#0.3.2 부터since 0.3.2소스source

로컬 x 위치. (부모 왼쪽 위 기준, 기본 0)

Local x position. (relative to the parent's top left, default 0)

반환Returnsf64

필드fieldpub y: f64#0.3.2 부터since 0.3.2소스source

로컬 y 위치. (기본 0)

Local y position. (default 0)

반환Returnsf64

필드fieldpub width: f64#0.3.2 부터since 0.3.2소스source

컨텐츠 너비. (기본 100)

Content width. (default 100)

반환Returnsf64

필드fieldpub height: f64#0.3.2 부터since 0.3.2소스source

컨텐츠 높이. (기본 100)

Content height. (default 100)

반환Returnsf64

필드fieldpub scale_x: f64#0.3.2 부터since 0.3.2소스source

가로 배율. (JSON "scaleX", 기본 1)

Horizontal scale. (JSON "scaleX", default 1)

반환Returnsf64

필드fieldpub scale_y: f64#0.3.2 부터since 0.3.2소스source

세로 배율. (JSON "scaleY", 기본 1)

Vertical scale. (JSON "scaleY", default 1)

반환Returnsf64

필드fieldpub rotation: f64#0.3.2 부터since 0.3.2소스source

회전. (도, 기본 0)

Rotation. (degrees, default 0)

반환Returnsf64

필드fieldpub opacity: f64#0.3.2 부터since 0.3.2소스source

투명도. (0 ~ 1, 기본 1)

Opacity. (0 ~ 1, default 1)

반환Returnsf64

필드fieldpub pivot_x: f64#0.3.2 부터since 0.3.2소스source

피봇 x 비율. (JSON "pivotX", 0 ~ 1, 기본 0.5)

Pivot x ratio. (JSON "pivotX", 0 ~ 1, default 0.5)

반환Returnsf64

필드fieldpub pivot_y: f64#0.3.2 부터since 0.3.2소스source

피봇 y 비율. (JSON "pivotY", 0 ~ 1, 기본 0.5)

Pivot y ratio. (JSON "pivotY", 0 ~ 1, default 0.5)

반환Returnsf64

필드fieldpub visible: bool#0.3.2 부터since 0.3.2소스source

보이기. (JSON 이 false 일 때만 끈다, 기본 true)

Visible. (turned off only when the JSON is false, default true)

반환Returnsbool

필드fieldpub color: String#0.3.2 부터since 0.3.2소스source

색 글. (paint 의 칠하기 색, text 의 글자색, sprite 의 덧칠 색. 기본 "#ffffffff")

Color string. (fill color for paint, text color for text, tint color for sprite. default "#ffffffff")

반환ReturnsString

필드fieldpub round_size: f64#0.3.2 부터since 0.3.2소스source

paint 귀퉁이 둥근 크기. (JSON "roundSize", 기본 0)

paint corner rounding size. (JSON "roundSize", default 0)

반환Returnsf64

필드fieldpub image: String#0.3.2 부터since 0.3.2소스source

sprite 이미지 이름. (이미지 해석기에 넘긴다. "data:" 주소면 그 자리에서 푼다, 기본 빈 글)

sprite image name. (passed to the image resolver. A "data:" URL is decoded right there, default empty string)

반환ReturnsString

필드fieldpub frame_columns: f64#0.3.2 부터since 0.3.2소스source

sprite 시트 가로 칸 수. (JSON "frameColumns", 1 보다 작으면 1, 기본 1)

Number of sprite sheet columns. (JSON "frameColumns", 1 if less than 1, default 1)

반환Returnsf64

필드fieldpub frame_rows: f64#0.3.2 부터since 0.3.2소스source

sprite 시트 세로 칸 수. (JSON "frameRows", 1 보다 작으면 1, 기본 1)

Number of sprite sheet rows. (JSON "frameRows", 1 if less than 1, default 1)

반환Returnsf64

필드fieldpub frame: f64#0.3.2 부터since 0.3.2소스source

sprite 시트 처음 칸 번호. (반올림, 기본 0)

Initial sprite sheet cell index. (rounded, default 0)

반환Returnsf64

필드fieldpub effect: String#0.3.2 부터since 0.3.2소스source

sprite 의 ShaderSprite 효과 이름. (ShaderSpriteEffect::from_name, 모르는 이름은 효과 없음, 기본 "none")

sprite ShaderSprite effect name. (ShaderSpriteEffect::from_name, unknown names mean no effect, default "none")

반환ReturnsString

필드fieldpub effect_progress: f64#0.3.2 부터since 0.3.2소스source

sprite 효과 진행률. (JSON "effectProgress", 0 ~ 1, 기본 0)

sprite effect progress. (JSON "effectProgress", 0 ~ 1, default 0)

반환Returnsf64

필드fieldpub effect_color: String#0.3.2 부터since 0.3.2소스source

sprite 효과 색 글. (JSON "effectColor", 빈 글이면 효과 기본 색, 기본 빈 글)

sprite effect color string. (JSON "effectColor", the effect's default color if empty, default empty string)

반환ReturnsString

필드fieldpub blend_mode: String#0.3.2 부터since 0.3.2소스source

sprite 섞기 이름. (JSON "blendMode", 캔버스 합성 이름, 모르는 이름은 Normal, 기본 "source-over")

sprite blend name. (JSON "blendMode", canvas composite name, unknown names are Normal, default "source-over")

반환ReturnsString

필드fieldpub text: String#0.3.2 부터since 0.3.2소스source

text 글. (기본 "Text")

text string. (default "Text")

반환ReturnsString

필드fieldpub font_size: f64#0.3.2 부터since 0.3.2소스source

text 글자 크기. (JSON "fontSize", 픽셀, 기본 32)

text font size. (JSON "fontSize", pixels, default 32)

반환Returnsf64

필드fieldpub bold: bool#0.3.2 부터since 0.3.2소스source

text 굵게. (JSON 이 true 일 때만, 기본 false)

text bold. (only when the JSON is true, default false)

반환Returnsbool

필드fieldpub text_align: String#0.3.2 부터since 0.3.2소스source

text 가로 정렬 이름. (JSON "textAlign", "left", "right", "start", "end", 그 밖은 가운데. 기본 "center")

text horizontal alignment name. (JSON "textAlign", "left", "right", "start", "end", anything else is center. default "center")

반환ReturnsString

필드fieldpub particle: Option<Value>#0.3.2 부터since 0.3.2소스source

particle 서술 객체. (ParticleSystem::apply_description 에 넘긴다, null 이면 None)

particle description object. (passed to ParticleSystem::apply_description, None if null)

반환ReturnsOption<Value>

필드fieldpub audio: String#0.3.2 부터since 0.3.2소스source

sound 소리 주소. (Timeline::load_sounds 가 읽는다, 기본 빈 글)

sound audio URL. (read by Timeline::load_sounds, default empty string)

반환ReturnsString

필드fieldpub volume: f64#0.3.2 부터since 0.3.2소스source

sound 음량. (들고만 있다, 기본 1)

sound volume. (only held, default 1)

반환Returnsf64

TimelineSpriteFrameGridstruct traits Component

소스source

스프라이트 시트 격자. (노드 서술의 frame_columns / frame_rows. 원본 spriteFrameGridTable 자리)

  • 그리지 않는 표시용 컴포넌트다. frame 속성이 이것을 읽어 칸을 고른다.
  • 웹에서 "data:" 주소 그림을 브라우저가 푸는 동안만 갱신한다. 다 풀리면 스프라이트에 걸고 서술의 칸을 고른다. (원본 image.onload 의 applySpriteFrame)

Sprite sheet grid. (frame_columns / frame_rows of the node description. In place of the original spriteFrameGridTable)

  • A display component that does not draw. The frame property reads this to pick a cell.
  • Updates only while the browser decodes a "data:" URL image on the web. Once decoded, it sets it on the sprite and picks the description's cell. (the original image.onload's applySpriteFrame)
예제Example4 x 2 시트의 5 번 칸을 고른 스프라이트 노드A sprite node with cell 5 of a 4 x 2 sheet picked
use std::rc::Rc;
use serde_json::json;
use vanilla::{Image, NodeTree, Rect, ShaderSprite, Timeline, TimelineSpriteFrameGrid};

let sheet_image = Image::create_from_pixels(64, 32, vec![255u8; 64 * 32 * 4]);
let image_resolver = |image_name: &str| -> Option<Rc<Image>> {
	if image_name == "coin" {
		Some(sheet_image.clone())
	}
	else {
		None
	}
};
let mut node_tree = NodeTree::new();
let node_description = json!({ "name": "Coin", "type": "sprite", "image": "coin", "frameColumns": 4, "frameRows": 2, "frame": 5 });
let coin_id = Timeline::create_stage_node(&mut node_tree, &node_description, Some(&image_resolver));
let frame_grid = node_tree[coin_id].get_component::<TimelineSpriteFrameGrid>().expect("grid");
assert_eq!((frame_grid.get_columns(), frame_grid.get_rows()), (4, 2));
let image_rect = node_tree[coin_id].get_component::<ShaderSprite>().expect("sprite").get_sprite().get_image_rect();
assert_eq!(image_rect, Rect::create(16.0, 16.0, 16.0, 16.0));
생성자constructorpub fn new(columns: usize, rows: usize) -> TimelineSpriteFrameGrid#0.3.2 부터since 0.3.2소스source

생성. (칸 수는 1 이상)

Constructor. (cell counts are at least 1)

columnsusize
가로 칸 수. (0 이면 1)Number of columns. (1 if 0)
rowsusize
세로 칸 수. (0 이면 1)Number of rows. (1 if 0)

반환ReturnsTimelineSpriteFrameGrid 기다리는 그림이 없는 격자 컴포넌트.A grid component with no image waiting.

메서드methodpub fn set_grid(&mut self, columns: usize, rows: usize)#0.3.2 부터since 0.3.2소스source

격자 설정.

  • 걸린 칸을 다시 고르지는 않는다. 다음 frame 값부터 새 격자로 고른다.

Sets the grid.

  • Does not re-pick the current cell. The new grid is used from the next frame value.
columnsusize
가로 칸 수. (0 이면 1)Number of columns. (1 if 0)
rowsusize
세로 칸 수. (0 이면 1)Number of rows. (1 if 0)
메서드methodpub fn get_columns(&self) -> usize#0.3.2 부터since 0.3.2소스source

가로 칸 수.

Number of columns.

반환Returnsusize 가로 칸 수. (1 이상)Number of columns. (at least 1)

메서드methodpub fn get_rows(&self) -> usize#0.3.2 부터since 0.3.2소스source

세로 칸 수.

Number of rows.

반환Returnsusize 세로 칸 수. (1 이상)Number of rows. (at least 1)

TimelineSoundstruct traits Default, Component

소스source

사운드 노드 상태. (원본 soundPlayerTable 의 { audio_player, audio_asset, audio_source, volume } 자리)

  • 애셋과 플레이어는 Timeline::load_sounds 가 채운다. 이벤트 키 play / loop / stop 이 플레이어를 부린다.

Sound node state. (in place of the original soundPlayerTable's { audio_player, audio_asset, audio_source, volume })

  • The asset and player are filled by Timeline::load_sounds. The event keys play / loop / stop drive the player.
예제Example사운드 노드를 만들면 주소와 음량만 들고 있다A newly created sound node holds only the URL and volume
use serde_json::json;
use vanilla::{NodeTree, Timeline, TimelineSound};

let mut node_tree = NodeTree::new();
let node_description = json!({ "name": "Hit", "type": "sound", "audio": "tests/assets/audio/wav_s16_stereo.wav", "volume": 0.5 });
let sound_id = Timeline::create_stage_node(&mut node_tree, &node_description, None);
let sound = node_tree[sound_id].get_component::<TimelineSound>().expect("sound");
assert_eq!(sound.get_audio_source(), "tests/assets/audio/wav_s16_stereo.wav");
assert_eq!(sound.get_volume(), 0.5);
assert!(sound.get_audio_asset().is_none());
생성자constructorpub fn new() -> TimelineSound#0.3.2 부터since 0.3.2소스source

생성. (비어 있음)

Constructor. (empty)

반환ReturnsTimelineSound 주소가 빈 글, 음량 1, 애셋과 플레이어가 없는 사운드 컴포넌트.A sound component with an empty URL, volume 1, and no asset or player.

메서드methodpub fn get_audio_source(&self) -> &str#0.3.2 부터since 0.3.2소스source

소리 주소 반환.

Returns the audio URL.

반환Returns&str 서술의 audio 주소. (없으면 빈 글)The description's audio URL. (empty string if none)

메서드methodpub fn get_volume(&self) -> f64#0.3.2 부터since 0.3.2소스source

음량 반환. (원본처럼 서술 값을 들고만 있다)

Returns the volume. (only holds the description value, as in the original)

반환Returnsf64 서술의 volume. (기본 1, 플레이어에 걸지 않는다)The description's volume. (default 1, not applied to the player)

메서드methodpub fn get_audio_asset(&self) -> Option<&Rc<AudioAsset>>#0.3.2 부터since 0.3.2소스source

오디오 애셋 반환.

Returns the audio asset.

반환ReturnsOption<&Rc<AudioAsset>> 읽은 오디오 애셋. load_sounds 전이거나 읽기에 실패했으면 None.The loaded audio asset. None before load_sounds or if loading failed.

메서드methodpub fn get_audio_player_mut(&mut self) -> Option<&mut AudioPlayer>#0.3.2 부터since 0.3.2소스source

플레이어 반환.

Returns the player.

반환ReturnsOption<&mut AudioPlayer> 플레이어의 변경 참조. load_sounds 전이면 None.Mutable reference to the player. None before load_sounds.

메서드methodpub fn stop(&mut self)#0.3.2 부터since 0.3.2소스source

멈춤. (플레이어가 있으면)

Stops. (if there is a player)

TimelineEventHandlertype

소스source

이벤트 핸들러. ((대상 이름, 이벤트 이름, 키, 타임라인, 노드 트리))

Event handler. ((target name, event name, key, timeline, node tree))

pub type TimelineEventHandler = Box<dyn FnMut(&str, &str, &TimelineKey, &mut Timeline, &mut NodeTree)>

TimelineMarkerHandlertype

소스source

마커 핸들러. ((마커 이름, 마커, 타임라인, 노드 트리))

Marker handler. ((marker name, marker, timeline, node tree))

pub type TimelineMarkerHandler = Box<dyn FnMut(&str, &TimelineMarker, &mut Timeline, &mut NodeTree)>

TimelineCompleteHandlertype

소스source

완료 핸들러. ((타임라인, 노드 트리))

Completion handler. ((timeline, node tree))

pub type TimelineCompleteHandler = Box<dyn FnMut(&mut Timeline, &mut NodeTree)>

TimelineTargetResolvertype

소스source

대상 해석기. (이름 → 대상)

Target resolver. (name → target)

pub type TimelineTargetResolver = Box<dyn Fn(&str) -> Option<TimelineTarget>>

TimelineImageResolvertype

소스source

이미지 해석기. (이미지 이름 → 이미지)

Image resolver. (image name → image)

pub type TimelineImageResolver<'a> = &'a dyn Fn(&str) -> Option<Rc<Image>>

Timelinestruct traits Default

짝Counterpart: vanilla.js Timeline소스source

타임라인.

  • 서술(JSON)을 들고, 무대를 만들거나(build_stage) 이미 있는 노드에 붙인(bind) 뒤 tick 으로 재생한다.

Timeline.

  • Holds a description (JSON), and after building a stage (build_stage) or binding to existing nodes (bind), plays it with tick.
예제Example무대를 만들고 상자를 2초 동안 오른쪽으로 옮기기Build a stage and move a box to the right over 2 seconds
use serde_json::json;
use vanilla::{NodeTree, Timeline, Vector2};

let description = json!({
	"duration": 2,
	"loop": false,
	"stage": { "nodes": [{ "name": "Box", "type": "paint", "width": 40, "height": 40, "color": "#ff0000ff" }] },
	"tracks": [{ "target": "Box", "property": "x", "keys": [{ "time": 0, "value": 0 }, { "time": 2, "value": 200 }] }],
});
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let mut timeline = Timeline::new(Some(description));
let node_table = timeline.build_stage(&mut node_tree, root_id, None);
let box_id = node_table["Box"];
timeline.play();
timeline.tick(&mut node_tree, 0.5);
assert_eq!(node_tree[box_id].get_local_position(), Vector2::create(50.0, 0.0));
timeline.tick(&mut node_tree, 2.0);
assert!(!timeline.is_playing());
assert_eq!(timeline.get_time(), 2.0);
assert_eq!(node_tree[box_id].get_local_position().x, 200.0);
예제Example씬 initialize 에서 무대를 만들고 tick 에서 재생Build the stage in the scene's initialize and play it in tick
use vanilla::{Engine, EngineConfiguration, Scene, SceneBase, Timeline};

const INTRO_TIMELINE: &str = r#"{
	"duration": 3,
	"loop": true,
	"stage": { "nodes": [{ "name": "Logo", "type": "text", "text": "Vanilla" }] },
	"tracks": [{ "target": "Logo", "property": "opacity", "keys": [{ "time": 0, "value": 0 }, { "time": 1, "value": 1 }] }]
}"#;

struct IntroScene {
	scene_base: SceneBase,
	timeline: Timeline,
}

impl Scene for IntroScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}

	fn initialize(&mut self, _engine: &Engine) {
		self.timeline = Timeline::load_from_text(INTRO_TIMELINE).unwrap_or_default();
		let stage_id = self.scene_base.get_root_id();
		self.timeline.build_stage(self.scene_base.get_node_tree_mut(), stage_id, None);
		self.timeline.play();
	}

	fn tick(&mut self, time_delta: f64) {
		self.scene_base.tick(time_delta);
		self.timeline.tick(self.scene_base.get_node_tree_mut(), time_delta);
	}
}

let engine = Engine::new(EngineConfiguration::new());
let intro_scene = IntroScene {
	scene_base: SceneBase::new(),
	timeline: Timeline::default(),
};
engine.run(Box::new(intro_scene)).unwrap();
Build the stage in the scene's initialize and play it in tick
생성자constructorpub fn new(description: Option<Value>) -> Timeline#0.3.2 부터since 0.3.2소스source

생성. (서술이 없으면 빈 서술)

Constructor. (an empty description if none is given)

descriptionOption<Value>
서술 JSON. None 이거나 객체가 아니면 빈 서술(create_empty_description)이고, 빠진 stage, stage.nodes, tracks, markers 는 채운다.Description JSON. If None or not an object, an empty description (create_empty_description); missing stage, stage.nodes, tracks and markers are filled in.

반환ReturnsTimeline 멈춘 타임라인. (시간 0, 속도 1, 컴파일은 처음 쓸 때 한다)A stopped timeline. (time 0, speed 1, compiled on first use)

짝Counterpart: vanilla.js Timeline.constructor

정적staticpub fn create_empty_description() -> Value#0.3.2 부터since 0.3.2소스source

빈 서술 생성. (정적)

Creates an empty description. (static)

반환ReturnsValue 이름 "Timeline", 길이 3 초, 초당 30 프레임, 반복, 960 x 540 무대(배경 "#101114ff")에 노드, 트랙, 마커가 없는 서술.A description named "Timeline", 3 seconds long, 30 frames per second, looping, with a 960 x 540 stage (background "#101114ff") and no nodes, tracks or markers.

짝Counterpart: vanilla.js Timeline.createEmptyDescription

정적staticpub fn load_from_text(text: &str) -> Result<Timeline, String>#0.3.2 부터since 0.3.2소스source

JSON 글에서 만들기. (원본 loadFromUrl 의 response.json() 다음 자리)

Creates from a JSON string. (in place of after response.json() in the original loadFromUrl)

text&str
서술 JSON 글.Description JSON string.

반환ReturnsResult<Timeline, String> 그 서술의 타임라인. JSON 으로 읽지 못하면 까닭을 담은 Err.The timeline of that description. Err with the reason if it cannot be read as JSON.

짝Counterpart: vanilla.js Timeline.loadFromText

예제ExampleJSON 글에서 만들기와 실패Create from a JSON string, and failure
use vanilla::Timeline;

let timeline = Timeline::load_from_text(r#"{ "duration": 1.5, "loop": false }"#).expect("timeline");
assert_eq!(timeline.get_duration(), 1.5);
assert!(!timeline.is_loop());
assert!(Timeline::load_from_text("{ broken").is_err());
정적staticpub fn load_from_url(engine: &Engine, url: &str) -> impl Future<Output = Result<Timeline, String>> + 'static#0.4.0 부터since 0.4.0소스source

주소에서 읽기. (원본 정적 await Timeline.loadFromUrl(url), 애셋 경로를 받기 부탁하고 엔진 작업 안에서 await 한다)

  • 받기나 JSON 읽기에 실패하면 까닭이다. (원본은 Promise 가 거부된다)

Loads from a URL. (the original static await Timeline.loadFromUrl(url); requests the asset path and awaits inside an engine task)

  • On a fetch or JSON read failure, the reason. (the original rejects the Promise)
engine&Engine
바이트 받기를 부탁할 엔진. (부탁은 이 자리에서 바로 한다)Engine to request the bytes from. (the request is made right here)
url&str
애셋 폴더 기준 경로나 "data:" 주소.Path relative to the asset folder, or a "data:" URL.

반환Returnsimpl Future<Output = Result<Timeline, String>> + 'static await 하면 타임라인이 나오는 Future. 받기나 JSON 읽기에 실패하면 까닭을 담은 Err. (엔진 작업 안에서 await 한다)A Future that yields the timeline when awaited. Err with the reason if fetching or reading the JSON fails. (await it inside an engine task)

짝Counterpart: vanilla.js Timeline.loadFromUrl

예제Example씬 create 에서 읽기를 엔진 작업으로 맡기기Hand the loading over to an engine task in the scene's create
use vanilla::{Engine, Scene, SceneBase, Timeline};

struct IntroScene {
	scene_base: SceneBase,
	timeline: Option<Timeline>,
}

impl Scene for IntroScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}

	fn load(&mut self, engine: &Engine) {
		let timeline_future = Timeline::load_from_url(engine, "data:application/json,{\"duration\":2,\"loop\":true}");
		let load_task_handle = engine.spawn_scene_task(self, |mut scene_context| async move {
			match timeline_future.await {
				Ok(timeline) => {
					scene_context.with(move |scene, _engine| scene.timeline = Some(timeline));
				}
				Err(error) => {
					eprintln!("{}", error);
				}
			}
		});
		self.scene_base.track_task(&load_task_handle);
	}
}
정적staticpub fn create_from_json_asset(json_asset: &mut JsonAsset) -> Option<Timeline>#0.3.2 부터since 0.3.2소스source

읽은 JsonAsset 에서 만들기. (아직 안 읽혔거나 실패했으면 None)

Creates from a loaded JsonAsset. (None if not loaded yet or failed)

json_asset&mut JsonAsset
서술 JSON 을 읽은 애셋. (서술은 복제한다)Asset that loaded the description JSON. (the description is cloned)

반환ReturnsOption<Timeline> 그 서술의 타임라인. 애셋이 아직 안 읽혔거나 JSON 으로 풀지 못했으면 None.The timeline of that description. None if the asset is not loaded yet or could not be parsed as JSON.

짝Counterpart: vanilla.js Timeline.createFromJsonAsset

예제Example읽기 전에는 None, 바이트가 들어오면 타임라인None before loading, a timeline once the bytes arrive
use vanilla::{JsonAsset, Timeline};

let mut timeline_asset = JsonAsset::new();
assert!(Timeline::create_from_json_asset(&mut timeline_asset).is_none());
timeline_asset.load_from_bytes("intro.timeline.json", br#"{ "duration": 2, "loop": false }"#.to_vec());
let timeline = Timeline::create_from_json_asset(&mut timeline_asset).expect("timeline");
assert_eq!(timeline.get_duration(), 2.0);
정적staticpub fn create_stage_node(node_tree: &mut NodeTree, node_description: &Value, image_resolver: Option<TimelineImageResolver>) -> NodeId#0.3.2 부터since 0.3.2소스source

무대 노드 한 개 생성. (정적. 붙이지 않은 노드를 만든다)

Creates one stage node. (static. Creates a node that is not attached)

node_tree&mut NodeTree
노드를 만들 노드 트리.Node tree to create the nodes in.
node_description&Value
서술 stage.nodes 의 노드 객체. (parent 는 보지 않는다)Node object from the description's stage.nodes. (parent is ignored)
image_resolverOption<TimelineImageResolver>
sprite 노드의 이미지 이름을 이미지로 바꾸는 함수. None 이면 "data:" 주소 이미지만 푼다.Function that turns a sprite node's image name into an image. If None, only "data:" URL images are decoded.

반환ReturnsNodeId 만든 노드. (어느 부모에도 붙지 않았고 대상으로 등록하지도 않는다)The created node. (not attached to any parent and not registered as a target)

짝Counterpart: vanilla.js Timeline.createStageNode

정적staticpub fn apply_stage_node_description(node: &mut WorldNode, node_description: &Value, image_resolver: Option<TimelineImageResolver>)#0.3.2 부터since 0.3.2소스source

노드에 서술 반영. (정적. 편집기가 값을 고칠 때도 쓴다)

  • 변환, 보이기를 걸고 type 에 맞는 컴포넌트(paint 는 Paint, sprite 는 ShaderSprite 와 격자, text 는 Text, particle 은 ParticleSystem, sound 는 TimelineSound)를 없으면 붙여 값을 건다.

Applies a description to a node. (static. Also used when the editor changes values)

  • Applies the transform and visibility, attaches the component matching type if missing (Paint for paint, ShaderSprite and a grid for sprite, Text for text, ParticleSystem for particle, TimelineSound for sound), and applies the values.
node&mut WorldNode
값을 걸 노드.Node to apply values to.
node_description&Value
서술 노드 객체. (빠진 항목은 TIMELINE_NODE_DEFAULTS)Description node object. (missing entries come from TIMELINE_NODE_DEFAULTS)
image_resolverOption<TimelineImageResolver>
sprite 노드의 이미지 이름을 이미지로 바꾸는 함수. None 이면 "data:" 주소 이미지만 푼다.Function that turns a sprite node's image name into an image. If None, only "data:" URL images are decoded.

짝Counterpart: vanilla.js Timeline.applyStageNodeDescription

정적staticpub fn stop_sound(node: &mut WorldNode)#0.3.2 부터since 0.3.2소스source

사운드 노드 정지. (정적. 편집기가 정지 / 되감기 때 부른다)

Stops a sound node. (static. Called by the editor on stop / rewind)

node&mut WorldNode
멈출 노드. (TimelineSound 가 없거나 플레이어가 없으면 아무것도 하지 않는다)Node to stop. (does nothing if there is no TimelineSound or no player)

짝Counterpart: vanilla.js Timeline.stopSound

정적staticpub fn sample_keys(sorted_keys: &[TimelineKey], kind: TimelinePropertyKind, time: f64) -> TimelineValue#0.3.2 부터since 0.3.2소스source

키 목록에서 시간의 값 표본. (정적. 키는 시간순이어야 한다. 편집기의 커브 그리기도 쓴다)

Samples the value at a time from a key list. (static. Keys must be in time order. Also used by the editor's curve drawing)

sorted_keys&[TimelineKey]
시간순으로 정렬한 키 목록.Key list sorted by time.
kindTimelinePropertyKind
값 종류. (Number, Color 는 앞 키의 이징으로 보간, 그 밖은 앞 키 값)Value kind. (Number and Color interpolate with the previous key's easing; others take the previous key's value)
timef64
표본할 시간. (초, 첫 키 앞은 첫 키 값, 마지막 키 뒤는 마지막 키 값)Time to sample. (seconds; before the first key it is the first key's value, after the last key the last key's value)

반환ReturnsTimelineValue 그 시간의 값. 키가 없으면 Number 는 Number(0), 그 밖은 None.The value at that time. With no keys, Number(0) for Number, None otherwise.

짝Counterpart: vanilla.js Timeline.sampleKeys

정적staticpub fn sample_track(track: &Value, time: f64) -> TimelineValue#0.3.2 부터since 0.3.2소스source

서술 트랙의 시간 값 표본. (정적. 서술 트랙 그대로, 정렬은 여기서. 정의가 없는 속성은 number)

Samples a description track's value at a time. (static. The description track as is, sorted here. Properties with no definition are number)

track&Value
서술 트랙 객체. ({ property, keys })Description track object. ({ property, keys })
timef64
표본할 시간. (초)Time to sample. (seconds)

반환ReturnsTimelineValue 그 시간의 값. (sample_keys 와 같다)The value at that time. (same as sample_keys)

짝Counterpart: vanilla.js Timeline.sampleTrack

예제Example색 트랙과 글 트랙 표본Sample a color track and a text track
use serde_json::json;
use vanilla::{Timeline, TimelineValue};

let color_track = json!({ "property": "color", "keys": [{ "time": 0, "value": "#ff0000ff" }, { "time": 2, "value": "#0000ffff" }] });
assert_eq!(Timeline::sample_track(&color_track, 1.0), TimelineValue::String(String::from("#800080ff")));
let text_track = json!({ "property": "text", "keys": [{ "time": 1, "value": "B" }, { "time": 0, "value": "A" }] });
assert_eq!(Timeline::sample_track(&text_track, 0.5).to_text(), "A");
assert_eq!(Timeline::sample_track(&text_track, 1.0).to_text(), "B");
메서드methodpub fn set_description(&mut self, description: Value)#0.3.2 부터since 0.3.2소스source

서술 설정. (빠진 stage / nodes / tracks / markers 를 채우고 다시 컴파일하게 한다)

Sets the description. (fills in missing stage / nodes / tracks / markers and marks it for recompilation)

descriptionValue
새 서술 JSON. 객체가 아니면 빈 서술(create_empty_description)을 쓴다.New description JSON. If not an object, an empty description (create_empty_description) is used.

짝Counterpart: vanilla.js Timeline.setDescription

메서드methodpub fn get_description(&self) -> &Value#0.3.2 부터since 0.3.2소스source

서술 반환.

Returns the description.

반환Returns&Value 서술 JSON 의 참조.Reference to the description JSON.

짝Counterpart: vanilla.js Timeline.getDescription

메서드methodpub fn get_description_mut(&mut self) -> &mut Value#0.3.2 부터since 0.3.2소스source

서술 반환. (변경용. 트랙 / 키를 고쳤으면 invalidate 를 부른다)

Returns the description. (mutable. Call invalidate after editing tracks / keys)

반환Returns&mut Value 서술 JSON 의 변경 참조.Mutable reference to the description JSON.

짝Counterpart: vanilla.js Timeline.getDescription

메서드methodpub fn invalidate(&mut self)#0.3.2 부터since 0.3.2소스source

다시 컴파일 요청. (트랙 / 키가 바뀌었을 때)

Requests recompilation. (when tracks / keys change)

짝Counterpart: vanilla.js Timeline.invalidate

메서드methodpub fn compile(&mut self, node_tree: &mut NodeTree)#0.3.2 부터since 0.3.2소스source

컴파일. (키를 시간순으로 정렬하고 대상 / 속성 정의를 붙인 뒤 파티클을 모은다)

  • seek, tick, evaluate 가 서술이 바뀌었으면 스스로 부른다.

Compiles. (sorts keys by time, attaches targets / property definitions, then gathers particles)

  • seek, tick and evaluate call it themselves if the description changed.
node_tree&mut NodeTree
대상 노드가 든 노드 트리. (대상 노드의 파티클 시스템을 찾는다)Node tree holding the target nodes. (finds the particle systems of the target nodes)

짝Counterpart: vanilla.js Timeline.compile

메서드methodpub fn collect_particle_systems(&mut self, node_tree: &mut NodeTree)#0.3.2 부터since 0.3.2소스source

대상 노드의 파티클 시스템 수집.

  • 수동 tick 으로 바꿔 타임라인 시간으로만 진행하고, 씨앗을 줘서 되감을 때마다 같은 결과가 나오게 한다.

Gathers the particle systems of the target nodes.

  • Switches them to manual tick so they advance only by timeline time, and gives them a seed so rewinding always gives the same result.
node_tree&mut NodeTree
대상 노드가 든 노드 트리. (대상 표의 노드만 본다, 씨앗이 이미 있으면 두고 없으면 수집 차례로 준다)Node tree holding the target nodes. (looks only at nodes in the target table; keeps an existing seed, otherwise gives one in gathering order)

짝Counterpart: vanilla.js Timeline.collectParticleSystems

메서드methodpub fn simulate_particles(&mut self, node_tree: &mut NodeTree, time_delta: f64)#0.3.2 부터since 0.3.2소스source

파티클 시간 진행. (재생 중 매 프레임)

Advances particle time. (every frame during playback)

node_tree&mut NodeTree
파티클 노드가 든 노드 트리.Node tree holding the particle nodes.
time_deltaf64
진행할 시간. (초, 0 이하이면 아무것도 하지 않는다)Time to advance. (seconds, does nothing if 0 or less)

짝Counterpart: vanilla.js Timeline.simulateParticles

메서드methodpub fn resimulate_particles(&mut self, node_tree: &mut NodeTree, time: f64)#0.3.2 부터since 0.3.2소스source

파티클 재시뮬레이션. (스크럽 / 되감기. 비운 뒤 0 초부터 이벤트를 다시 밟으며 진행)

  • 한 걸음은 1/60 초와 time / 600 가운데 큰 것이다. 이벤트 트랙이 없는 파티클은 0 초에 튼 것으로 본다.

Re-simulates particles. (scrubbing / rewinding. Clears them, then advances from 0 seconds while stepping through the events again)

  • One step is the larger of 1/60 second and time / 600. Particles with no event track count as started at 0 seconds.
node_tree&mut NodeTree
파티클 노드가 든 노드 트리.Node tree holding the particle nodes.
timef64
맞출 타임라인 시간. (초)Timeline time to match. (seconds)

짝Counterpart: vanilla.js Timeline.resimulateParticles

메서드methodpub fn resolve_target(&self, target_name: &str) -> Option<TimelineTarget>#0.3.2 부터since 0.3.2소스source

대상 해석. (대상 표 → 사용자 해석기)

Resolves a target. (target table → user resolver)

target_name&str
트랙 대상 이름.Track target name.

반환ReturnsOption<TimelineTarget> 대상 표에 있으면 그것, 없으면 해석기가 준 대상. 둘 다 없으면 None.The entry in the target table if present, otherwise the target given by the resolver. None if neither.

짝Counterpart: vanilla.js Timeline.resolveTarget

메서드methodpub fn set_target_resolver(&mut self, target_resolver: Option<TimelineTargetResolver>)#0.3.2 부터since 0.3.2소스source

대상 해석기 설정. (이름 → 대상. 노드가 아닌 것은 TimelineTarget::External(객체))

Sets the target resolver. (name → target. Things that are not nodes are TimelineTarget::External(object))

target_resolverOption<TimelineTargetResolver>
대상 표에 없는 이름을 받아 대상을 주는 함수. (모르는 이름은 None) None 이면 해석기를 뗀다. 컴파일 때 부른다.Function that takes a name not in the target table and gives a target. (None for unknown names) None removes the resolver. Called during compilation.

짝Counterpart: vanilla.js Timeline.setTargetResolver

예제Example"screen" 이름을 External 대상으로 풀기Resolve the name "screen" to an External target
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{Timeline, TimelinePropertyTarget, TimelineTarget, TimelineValue};

struct Silent;

impl TimelinePropertyTarget for Silent {
	fn set_timeline_property(&mut self, _property_name: &str, _value: &TimelineValue) {
	}
}

let screen: Rc<RefCell<dyn TimelinePropertyTarget>> = Rc::new(RefCell::new(Silent));
let mut timeline = Timeline::default();
let resolved_screen = screen.clone();
timeline.set_target_resolver(Some(Box::new(move |target_name: &str| {
	if target_name == "screen" {
		Some(TimelineTarget::External(resolved_screen.clone()))
	}
	else {
		None
	}
})));
assert_eq!(timeline.resolve_target("screen"), Some(TimelineTarget::External(screen)));
assert_eq!(timeline.resolve_target("missing"), None);
assert_eq!(timeline.get_target("screen"), None);
메서드methodpub fn set_target(&mut self, target_name: &str, target: TimelineTarget)#0.3.2 부터since 0.3.2소스source

대상 직접 등록. (같은 이름이 있으면 바꾼다)

Registers a target directly. (replaces it if the same name exists)

target_name&str
트랙 대상 이름.Track target name.
targetTimelineTarget
그 이름의 대상. (노드 핸들 또는 External 객체)Target with that name. (a node handle or an External object)

짝Counterpart: vanilla.js Timeline.setTarget

메서드methodpub fn get_target(&self, target_name: &str) -> Option<TimelineTarget>#0.3.2 부터since 0.3.2소스source

대상 반환. (대상 표에 있는 것만)

Returns a target. (only those in the target table)

target_name&str
트랙 대상 이름.Track target name.

반환ReturnsOption<TimelineTarget> 대상 표에 등록된 대상의 복제. 없으면 None. (해석기는 묻지 않는다)Clone of the target registered in the target table. None if missing. (the resolver is not asked)

짝Counterpart: vanilla.js Timeline.getTarget

메서드methodpub fn bind(&mut self, node_tree: &NodeTree, root_id: NodeId)#0.3.2 부터since 0.3.2소스source

노드 트리에 이름으로 붙이기. (무대를 직접 만든 경우. 뿌리 자신, 또는 그 자손에서 트랙 대상 이름을 찾는다)

  • 대상 표에 이미 있는 이름은 건너뛰고, 못 찾은 이름은 등록하지 않는다.

Binds to a node tree by name. (when the stage was built manually. Searches the root itself or its descendants for track target names)

  • Names already in the target table are skipped, and names not found are not registered.
node_tree&NodeTree
노드를 찾을 노드 트리.Node tree to search for nodes.
root_idNodeId
찾기를 시작할 뿌리 노드.Root node to start the search from.

짝Counterpart: vanilla.js Timeline.bind

예제Example이미 있는 Hero 노드에 붙여 배율 트랙 걸기Bind to an existing Hero node and apply a scale track
use serde_json::json;
use vanilla::{NodeTree, Timeline, TimelineTarget};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let world_id = node_tree.create_child(root_id, "World");
let hero_id = node_tree.create_child(world_id, "Hero");
let mut timeline = Timeline::new(Some(json!({
	"duration": 1,
	"tracks": [{ "target": "Hero", "property": "scaleX", "keys": [{ "time": 0, "value": 1 }, { "time": 1, "value": 3 }] }],
})));
timeline.bind(&node_tree, root_id);
assert_eq!(timeline.get_target("Hero"), Some(TimelineTarget::Node(hero_id)));
timeline.seek(&mut node_tree, 0.5);
assert_eq!(node_tree[hero_id].get_local_scale().x, 2.0);
메서드methodpub fn build_stage(&mut self, node_tree: &mut NodeTree, parent_id: NodeId, image_resolver: Option<TimelineImageResolver>) -> HashMap<String, NodeId>#0.3.2 부터since 0.3.2소스source

무대 노드 생성. (서술의 stage.nodes 를 노드 트리로 만들고 대상으로 등록한다. 이름 → 노드 표를 돌려준다)

Creates the stage nodes. (builds the description's stage.nodes into the node tree and registers them as targets. Returns a name → node table)

node_tree&mut NodeTree
노드를 만들 노드 트리.Node tree to create the nodes in.
parent_idNodeId
무대 부모 노드. (서술에 parent 가 없거나, 못 찾거나, 자기 자신이나 고리가 되는 노드가 여기 붙는다)Stage parent node. (nodes whose parent is missing from the description, not found, itself or part of a cycle are attached here)
image_resolverOption<TimelineImageResolver>
sprite 노드의 이미지 이름을 이미지로 바꾸는 함수. None 이면 "data:" 주소 이미지만 푼다.Function that turns a sprite node's image name into an image. If None, only "data:" URL images are decoded.

반환ReturnsHashMap<String, NodeId> 노드 이름 → 만든 노드 표. (같은 이름이 둘이면 뒤의 것)Node name → created node table. (the later one if two share a name)

짝Counterpart: vanilla.js Timeline.buildStage

예제Example부모 관계가 있는 무대 만들기Build a stage with parent relationships
use serde_json::json;
use vanilla::{NodeTree, Timeline, TimelineTarget};

let mut timeline = Timeline::new(Some(json!({
	"duration": 1,
	"stage": { "nodes": [
		{ "name": "Group", "type": "group", "x": 100 },
		{ "name": "Box", "type": "paint", "parent": "Group" },
	] },
})));
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let node_table = timeline.build_stage(&mut node_tree, root_id, None);
assert_eq!(node_tree.get_parent_id(node_table["Box"]), Some(node_table["Group"]));
assert_eq!(node_tree.get_parent_id(node_table["Group"]), Some(root_id));
assert_eq!(timeline.get_target("Box"), Some(TimelineTarget::Node(node_table["Box"])));
메서드methodpub fn load_sounds(&mut self, node_tree: &mut NodeTree, engine: &Engine) -> Vec<Rc<AudioAsset>>#0.3.2 부터since 0.3.2소스source

사운드 노드 준비. (원본 setAudioManager + 사운드 노드의 애셋 읽기 자리)

  • 대상 노드 가운데 TimelineSound 가 붙은 것마다 아직 없는 오디오 애셋을 읽고 플레이어를 만든다. 새로 읽은 애셋을 돌려준다.

Prepares sound nodes. (in place of the original setAudioManager + asset loading of sound nodes)

  • For each target node with a TimelineSound attached, loads any missing audio asset and creates a player. Returns the newly loaded assets.
node_tree&mut NodeTree
사운드 노드가 든 노드 트리.Node tree holding the sound nodes.
engine&Engine
오디오 애셋을 읽고 플레이어를 만들 엔진.Engine to load audio assets and create players with.

반환ReturnsVec<Rc<AudioAsset>> 이번에 새로 읽은 오디오 애셋 목록. (씬이 track_audio_asset 으로 맡겨도 된다, 읽지 못한 것은 빼고 표준 오류에 까닭을 찍는다)List of audio assets newly loaded this time. (the scene may take them over with track_audio_asset; ones that failed to load are left out and the reason is printed to standard error)

예제Example무대를 만든 뒤 소리를 읽고 이벤트 키로 틀기Build the stage, then load the sounds and play them with event keys
use serde_json::json;
use vanilla::{Engine, EngineConfiguration, Scene, SceneBase, Timeline};

struct SoundScene {
	scene_base: SceneBase,
	timeline: Timeline,
}

impl Scene for SoundScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}

	fn initialize(&mut self, engine: &Engine) {
		self.timeline = Timeline::new(Some(json!({
			"duration": 2,
			"stage": { "nodes": [{ "name": "Hit", "type": "sound", "audio": "tests/assets/audio/wav_s16_stereo.wav" }] },
			"tracks": [{ "target": "Hit", "property": "event", "keys": [{ "time": 0.5, "value": "play" }] }],
		})));
		let root_id = self.scene_base.get_root_id();
		self.timeline.build_stage(self.scene_base.get_node_tree_mut(), root_id, None);
		let audio_asset_list = self.timeline.load_sounds(self.scene_base.get_node_tree_mut(), engine);
		for audio_asset in audio_asset_list.iter() {
			self.scene_base.track_audio_asset(audio_asset);
		}
		self.timeline.play();
	}

	fn tick(&mut self, time_delta: f64) {
		self.scene_base.tick(time_delta);
		self.timeline.tick(self.scene_base.get_node_tree_mut(), time_delta);
	}
}

let engine = Engine::new(EngineConfiguration::new());
let sound_scene = SoundScene {
	scene_base: SceneBase::new(),
	timeline: Timeline::default(),
};
engine.run(Box::new(sound_scene)).unwrap();
메서드methodpub fn play(&mut self)#0.3.2 부터since 0.3.2소스source

재생. (반복이 아닌데 끝에 있으면 처음부터)

Plays. (from the beginning if not looping and at the end)

짝Counterpart: vanilla.js Timeline.play

메서드methodpub fn pause(&mut self)#0.3.2 부터since 0.3.2소스source

일시 정지.

Pauses.

짝Counterpart: vanilla.js Timeline.pause

메서드methodpub fn stop(&mut self, node_tree: &mut NodeTree)#0.3.2 부터since 0.3.2소스source

정지. (소리와 파티클을 멈추고 처음으로)

Stops. (stops sounds and particles and goes back to the start)

node_tree&mut NodeTree
대상 노드가 든 노드 트리. (0 초의 값을 다시 건다)Node tree holding the target nodes. (applies the values at 0 seconds again)

짝Counterpart: vanilla.js Timeline.stop

메서드methodpub fn seek(&mut self, node_tree: &mut NodeTree, time: f64)#0.3.2 부터since 0.3.2소스source

시간 이동. (이벤트는 발생하지 않는다. 파티클은 그 시간까지 다시 진행한다)

Moves in time. (no events fire. Particles advance again up to that time)

node_tree&mut NodeTree
대상 노드가 든 노드 트리.Node tree holding the target nodes.
timef64
옮길 시간. (초, 0 ~ 길이로 자른다)Time to move to. (seconds, clamped to 0 ~ duration)

짝Counterpart: vanilla.js Timeline.seek

메서드methodpub fn tick(&mut self, node_tree: &mut NodeTree, time_delta: f64)#0.3.2 부터since 0.3.2소스source

갱신. (시간을 흘리고 값을 적용, 지나친 이벤트 / 마커를 발생)

  • 재생 중이 아니면 아무것도 하지 않는다. 반복이면 끝을 넘을 때 감아 돌고, 아니면 끝에서 멈추고 완료 핸들러를 부른다.

Update. (advances time and applies values, firing events / markers passed)

  • Does nothing if not playing. If looping, wraps around when passing the end; otherwise stops at the end and calls the completion handler.
node_tree&mut NodeTree
대상 노드가 든 노드 트리. (핸들러에도 넘긴다)Node tree holding the target nodes. (also passed to the handlers)
time_deltaf64
지난 프레임에서 흐른 시간. (초, 속도를 곱해 흘린다)Time elapsed since the last frame. (seconds, advanced after multiplying by the speed)

짝Counterpart: vanilla.js Timeline.tick

메서드methodpub fn fire_events_between(&mut self, node_tree: &mut NodeTree, from_time: f64, to_time: f64)#0.3.2 부터since 0.3.2소스source

구간 안의 이벤트 키 / 마커 발생. (from_time 초과 ~ to_time 이하. 이벤트 트랙 차례, 그다음 마커)

Fires event keys / markers in a range. (greater than from_time up to and including to_time. Event tracks in order, then markers)

node_tree&mut NodeTree
대상 노드가 든 노드 트리. (파티클, 사운드 노드가 이벤트를 받고 핸들러에도 넘긴다)Node tree holding the target nodes. (particle and sound nodes receive the events, and it is also passed to the handlers)
from_timef64
구간 시작. (초, 이 시간의 키는 뺀다. 0 초 키를 넣으려면 음수를 준다)Start of the range. (seconds, keys at this time are excluded. Pass a negative value to include keys at 0 seconds)
to_timef64
구간 끝. (초, 이 시간의 키는 넣는다)End of the range. (seconds, keys at this time are included)

짝Counterpart: vanilla.js Timeline.fireEventsBetween

메서드methodpub fn evaluate(&mut self, node_tree: &mut NodeTree, time: f64)#0.3.2 부터since 0.3.2소스source

시간의 값 적용. (연속 속성만, 이벤트는 tick 에서만 발생. External 대상에는 set_timeline_property 로 넘기고 건 값을 적어 둔다)

  • 꺼진 트랙, 키가 없는 트랙, 대상을 못 찾은 트랙은 건너뛴다. 시간은 자르지 않는다.

Applies the values at a time. (continuous properties only; events fire only in tick. For External targets, passes them with set_timeline_property and records the applied values)

  • Disabled tracks, tracks with no keys and tracks whose target is not found are skipped. The time is not clamped.
node_tree&mut NodeTree
대상 노드가 든 노드 트리.Node tree holding the target nodes.
timef64
표본할 시간. (초)Time to sample. (seconds)

짝Counterpart: vanilla.js Timeline.evaluate

메서드methodpub fn get_external_properties(&self) -> &[TimelineExternalProperty]#0.3.2 부터since 0.3.2소스source

마지막 evaluate 가 External 대상에 건 값 반환. (트랙 차례)

Returns the values the last evaluate applied to External targets. (in track order)

반환Returns&[TimelineExternalProperty] External 대상에 건 값 조각. (evaluate 전이면 비어 있다)Slice of values applied to External targets. (empty before evaluate)

메서드methodpub fn get_time(&self) -> f64#0.3.2 부터since 0.3.2소스source

시간 반환.

Returns the time.

반환Returnsf64 지금 재생 시간. (초, 0 ~ 길이)Current playback time. (seconds, 0 ~ duration)

짝Counterpart: vanilla.js Timeline.getTime

메서드methodpub fn is_playing(&self) -> bool#0.3.2 부터since 0.3.2소스source

재생 중 여부 반환.

Returns whether it is playing.

반환Returnsbool play 뒤 pause, stop, 끝 닿기 전이면 true.true after play and before pause, stop or reaching the end.

짝Counterpart: vanilla.js Timeline.isPlaying

메서드methodpub fn set_speed(&mut self, speed: f64)#0.3.2 부터since 0.3.2소스source

속도 설정. (1 = 실시간)

Sets the speed. (1 = real time)

speedf64
시간 배율. (2 는 두 배 빠르기, 음수면 거꾸로 가며 0 에서 더 가지 않고 이벤트는 나지 않는다)Time scale. (2 is double speed; if negative it runs backward, does not go past 0, and no events fire)

짝Counterpart: vanilla.js Timeline.setSpeed

메서드methodpub fn get_speed(&self) -> f64#0.3.2 부터since 0.3.2소스source

속도 반환.

Returns the speed.

반환Returnsf64 시간 배율. (기본 1)Time scale. (default 1)

짝Counterpart: vanilla.js Timeline.getSpeed

메서드methodpub fn set_loop(&mut self, is_loop: bool)#0.3.2 부터since 0.3.2소스source

반복 설정. (서술의 loop 를 바꾼다)

Sets looping. (changes the description's loop)

is_loopbool
끝을 넘으면 처음으로 감아 돌지.Whether to wrap around to the start when passing the end.

짝Counterpart: vanilla.js Timeline.setLoop

메서드methodpub fn is_loop(&self) -> bool#0.3.2 부터since 0.3.2소스source

반복 여부 반환. (서술의 loop 가 true 일 때만)

Returns whether it loops. (only when the description's loop is true)

반환Returnsbool 서술의 loop 가 참거짓 true 면 true. (없거나 다른 꼴이면 false)true if the description's loop is the boolean true. (false if missing or another type)

짝Counterpart: vanilla.js Timeline.isLoop

메서드methodpub fn get_duration(&self) -> f64#0.3.2 부터since 0.3.2소스source

길이 반환. (초, 못 읽거나 0 이하면 0)

Returns the duration. (seconds, 0 if unreadable or 0 or less)

반환Returnsf64 서술의 duration. (초, 글 "4" 처럼 숫자로 읽히는 글도 받는다. 못 읽거나 0 이하면 0)The description's duration. (seconds, also accepts strings that read as numbers like "4". 0 if unreadable or 0 or less)

짝Counterpart: vanilla.js Timeline.getDuration

메서드methodpub fn get_frame_rate(&self) -> f64#0.3.2 부터since 0.3.2소스source

초당 프레임 반환. (못 읽거나 0 이하면 30)

Returns the frames per second. (30 if unreadable or 0 or less)

반환Returnsf64 서술의 frameRate. (못 읽거나 0 이하면 30, 재생 시간 계산에는 쓰지 않는다)frameRate of the description. (30 if it cannot be read or is 0 or less, not used to compute the playback time)

짝Counterpart: vanilla.js Timeline.getFrameRate

메서드methodpub fn set_event_handler(&mut self, event_handler: Option<TimelineEventHandler>)#0.3.2 부터since 0.3.2소스source

이벤트 핸들러 설정. ((대상 이름, 이벤트 이름, 키, 타임라인, 노드 트리))

Sets the event handler. ((target name, event name, key, timeline, node tree))

event_handlerOption<TimelineEventHandler>
tick 이 지나친 event 트랙 키마다 부를 함수. (이벤트 이름은 키 값의 글, 대상을 못 찾은 트랙도 부른다) None 이면 뗀다.Function called for each event track key tick passes. (the event name is the key value's string; also called for tracks whose target is not found) None removes it.

짝Counterpart: vanilla.js Timeline.setEventHandler

예제Example이벤트를 적고 land 에서 멈추기Record events and stop at land
use std::cell::RefCell;
use std::rc::Rc;
use serde_json::json;
use vanilla::{NodeTree, Timeline, TimelineKey};

let event_list: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
let mut node_tree = NodeTree::new();
let mut timeline = Timeline::new(Some(json!({
	"duration": 2,
	"loop": true,
	"tracks": [{ "target": "hero", "property": "event", "keys": [{ "time": 0.5, "value": "jump" }, { "time": 1.5, "value": "land" }] }],
})));
let recorded_list = event_list.clone();
timeline.set_event_handler(Some(Box::new(move |target_name: &str, event_name: &str, key: &TimelineKey, timeline: &mut Timeline, _node_tree: &mut NodeTree| {
	recorded_list.borrow_mut().push(format!("{} {} {}", target_name, event_name, key.time));
	if event_name == "land" {
		timeline.pause();
	}
})));
timeline.play();
timeline.tick(&mut node_tree, 1.0);
timeline.tick(&mut node_tree, 1.0);
assert_eq!(*event_list.borrow(), vec![String::from("hero jump 0.5"), String::from("hero land 1.5")]);
assert!(!timeline.is_playing());
메서드methodpub fn set_marker_handler(&mut self, marker_handler: Option<TimelineMarkerHandler>)#0.3.2 부터since 0.3.2소스source

마커 핸들러 설정. ((마커 이름, 마커, 타임라인, 노드 트리))

Sets the marker handler. ((marker name, marker, timeline, node tree))

marker_handlerOption<TimelineMarkerHandler>
tick 이 지나친 마커마다 부를 함수. (그 구간의 이벤트 키 뒤에 시간순으로) None 이면 뗀다.Function called for each marker tick passes. (in time order after the event keys of that range) None removes it.

짝Counterpart: vanilla.js Timeline.setMarkerHandler

메서드methodpub fn set_complete_handler(&mut self, complete_handler: Option<TimelineCompleteHandler>)#0.3.2 부터since 0.3.2소스source

완료 핸들러 설정. (반복이 아닐 때 끝에 닿으면, (타임라인, 노드 트리))

Sets the completion handler. (when reaching the end while not looping, (timeline, node tree))

complete_handlerOption<TimelineCompleteHandler>
반복이 아닌 재생이 끝에 닿은 tick 에 한 번 부를 함수. (끝 값을 건 뒤) None 이면 뗀다.Function called once on the tick where non-looping playback reaches the end. (after applying the end values) None removes it.

짝Counterpart: vanilla.js Timeline.setCompleteHandler

예제Example1초 타임라인이 끝나면 세기Count when a 1-second timeline ends
use std::cell::Cell;
use std::rc::Rc;
use serde_json::json;
use vanilla::{NodeTree, Timeline};

let completed_count = Rc::new(Cell::new(0));
let mut node_tree = NodeTree::new();
let mut timeline = Timeline::new(Some(json!({ "duration": 1, "loop": false })));
let counter = completed_count.clone();
timeline.set_complete_handler(Some(Box::new(move |_timeline: &mut Timeline, _node_tree: &mut NodeTree| {
	counter.set(counter.get() + 1);
})));
timeline.play();
timeline.tick(&mut node_tree, 0.6);
timeline.tick(&mut node_tree, 0.6);
assert_eq!(completed_count.get(), 1);
assert_eq!(timeline.get_time(), 1.0);

함수Functions

함수functionpub fn create_bezier_easing(x1: f64, y1: f64, x2: f64, y2: f64) -> impl Fn(f64) -> f64 + Clone#0.3.2 부터since 0.3.2소스source

3차 베지어 이징 생성. (CSS cubic-bezier 와 같은 제어점, x 는 0 ~ 1)

Creates a cubic Bezier easing. (same control points as CSS cubic-bezier, x is 0 ~ 1)

x1f64
첫 제어점 x. (0 ~ 1 로 자른다)x of the first control point. (clamped to 0 ~ 1)
y1f64
첫 제어점 y. (자르지 않는다, 0 ~ 1 밖이면 넘쳤다 돌아온다)y of the first control point. (not clamped; outside 0 ~ 1 it overshoots and comes back)
x2f64
둘째 제어점 x. (0 ~ 1 로 자른다)x of the second control point. (clamped to 0 ~ 1)
y2f64
둘째 제어점 y. (자르지 않는다)y of the second control point. (not clamped)

반환Returnsimpl Fn(f64) -> f64 + Clone 진행률(0 ~ 1)을 받아 이징 값을 내는 함수. (진행률 0 이하는 0, 1 이상은 1)Function that takes progress (0 ~ 1) and produces the eased value. (progress 0 or less is 0, 1 or more is 1)

짝Counterpart: vanilla.js createBezierEasing

예제ExampleCSS ease-in-out 곡선CSS ease-in-out curve
use vanilla::create_bezier_easing;

let ease_in_out = create_bezier_easing(0.42, 0.0, 0.58, 1.0);
assert_eq!(ease_in_out(0.0), 0.0);
assert_eq!(ease_in_out(1.0), 1.0);
assert!((ease_in_out(0.5) - 0.5).abs() < 0.001);
assert!(ease_in_out(0.1) < 0.1);
함수functionpub fn resolve_timeline_easing(easing_name: &str, curve: Option<&[f64]>) -> TimelineEasing#0.3.2 부터since 0.3.2소스source

이징 반환. (모르는 이름은 linear, "bezier" 는 curve [x1, y1, x2, y2] 를 쓰고 없으면 ease-in-out)

Returns an easing. (unknown names are linear; "bezier" uses curve [x1, y1, x2, y2], ease-in-out if missing)

easing_name&str
이징 이름. (TIMELINE_EASING_NAMES 의 것, 빈 글은 linear)Easing name. (one of TIMELINE_EASING_NAMES, an empty string is linear)
curveOption<&[f64]>
"bezier" 의 제어점 [x1, y1, x2, y2]. 없거나 넷보다 적으면 [0.42, 0, 0.58, 1]. "bezier" 가 아니면 보지 않는다.Control points [x1, y1, x2, y2] for "bezier". If missing or fewer than four, [0.42, 0, 0.58, 1]. Ignored if not "bezier".

반환ReturnsTimelineEasing evaluate(progress) 로 부르는 이징 값.Easing value called with evaluate(progress).

짝Counterpart: vanilla.js resolveTimelineEasing

예제Example이름으로 이징 고르기Pick an easing by name
use vanilla::resolve_timeline_easing;

let quadratic_in = resolve_timeline_easing("quadratic.in", None);
assert_eq!(quadratic_in.evaluate(0.5), 0.25);
let step = resolve_timeline_easing("step", None);
assert_eq!(step.evaluate(0.9), 0.0);
let curve: [f64; 4] = [0.68, -0.55, 0.265, 1.55];
let overshoot = resolve_timeline_easing("bezier", Some(&curve));
assert!(overshoot.evaluate(0.3) < 0.0);
assert_eq!(resolve_timeline_easing("unknown", None).evaluate(0.3), 0.3);
함수functionpub fn parse_timeline_color(hex_text: &str) -> [f64; 4]#0.3.2 부터since 0.3.2소스source

색 문자열 → 채널. ("#rrggbb" 또는 "#rrggbbaa", 못 읽는 채널은 1)

Color string → channels. ("#rrggbb" or "#rrggbbaa", unreadable channels are 1)

hex_text&str
색 글. "#" 로 시작하지 않으면 흰색으로 읽는다. 채널은 두 글자씩 원본 parseInt(글, 16) 처럼 앞의 16 진 숫자만 읽는다.Color string. If it does not start with "#", it reads as white. Each channel reads two characters, taking only the leading hex digits like the original parseInt(string, 16).

반환Returns[f64; 4] [빨강, 초록, 파랑, 알파] 채널. (0 ~ 1, 알파는 여덟 글자일 때만 읽고 아니면 1)[red, green, blue, alpha] channels. (0 ~ 1, alpha is read only with eight characters, otherwise 1)

짝Counterpart: vanilla.js parseTimelineColor

예제Example색 글 읽기Read a color string
use vanilla::parse_timeline_color;

assert_eq!(parse_timeline_color("#ff000080"), [1.0, 0.0, 0.0, 128.0 / 255.0]);
assert_eq!(parse_timeline_color("#00ff00"), [0.0, 1.0, 0.0, 1.0]);
assert_eq!(parse_timeline_color("red"), [1.0, 1.0, 1.0, 1.0]);
함수functionpub fn compose_timeline_color(channels: &[f64]) -> String#0.3.2 부터since 0.3.2소스source

채널 → 색 문자열. ("#rrggbbaa", 알파가 없으면 1)

Channels → color string. ("#rrggbbaa", 1 if alpha is missing)

channels&[f64]
[빨강, 초록, 파랑, 알파] 채널. (0 ~ 1 로 자르고 반올림한다, 빠진 빨강, 초록, 파랑은 0)[red, green, blue, alpha] channels. (clamped to 0 ~ 1 and rounded; missing red, green and blue are 0)

반환ReturnsString 소문자 "#rrggbbaa" 글.Lowercase "#rrggbbaa" string.

짝Counterpart: vanilla.js composeTimelineColor

예제Example채널을 색 글로Channels to a color string
use vanilla::compose_timeline_color;

assert_eq!(compose_timeline_color(&[1.0, 0.5, 0.0, 1.0]), "#ff8000ff");
assert_eq!(compose_timeline_color(&[0.2, 0.4, 0.6]), "#336699ff");
함수functionpub fn find_timeline_property_definition(property_name: &str) -> Option<&'static TimelinePropertyDefinition>#0.3.2 부터since 0.3.2소스source

속성 정의 찾기. (원본 TIMELINE_PROPERTY_DEFINITIONS[이름])

Finds a property definition. (the original TIMELINE_PROPERTY_DEFINITIONS[name])

property_name&str
속성 이름. (대소문자를 가린다)Property name. (case-sensitive)

반환ReturnsOption<&'static TimelinePropertyDefinition> 그 이름의 정의. 없으면 None.The definition with that name. None if missing.

상수Constants

상수constantpub const TIMELINE_EASING_NAMES: [&str; 33]#0.3.2 부터since 0.3.2소스source

이징 이름 목록. ("linear" / "step" / "bezier" / "<종류>.<in|out|inOut>")

Easing name list. ("linear" / "step" / "bezier" / "<family>.<in|out|inOut>")

반환Returns[&str; 33]

짝Counterpart: vanilla.js TIMELINE_EASING_NAMES

상수constantpub const TIMELINE_PROPERTY_DEFINITIONS: [TimelinePropertyDefinition; 17]#0.3.2 부터since 0.3.2소스source

애니메이션 속성 정의 목록. (원본 TIMELINE_PROPERTY_DEFINITIONS 의 선언 차례)

List of animation property definitions. (in the declaration order of the original TIMELINE_PROPERTY_DEFINITIONS)

반환Returns[TimelinePropertyDefinition; 17]

짝Counterpart: vanilla.js TIMELINE_PROPERTY_DEFINITIONS

상수constantpub static TIMELINE_NODE_DEFAULTS: LazyLock<TimelineNodeDescription> = LazyLock::new(TimelineNodeDescription::default)#0.3.2 부터since 0.3.2소스source

서술 노드 기본값. (원본 TIMELINE_NODE_DEFAULTS)

Description node defaults. (the original TIMELINE_NODE_DEFAULTS)

반환ReturnsLazyLock<TimelineNodeDescription>

짝Counterpart: vanilla.js TIMELINE_NODE_DEFAULTS

TimelineEasingenum traits Clone, Copy, Debug

소스source

타임라인 이징. (원본에서 resolve_timeline_easing 이 돌려주는 함수 자리)

Timeline easing. (in place of the function resolve_timeline_easing returns in the original)

이름Name값Value설명Description
FunctionFunction(EasingFunction)Tween 이징 함수, linear, step.Tween easing function, linear, step.
BezierBezier(f64, f64, f64, f64)3차 베지어 (x1, y1, x2, y2).Cubic Bezier (x1, y1, x2, y2).
메서드methodpub fn evaluate(&self, progress: f64) -> f64#0.3.2 부터since 0.3.2소스source

진행률(0 ~ 1)의 이징 값.

Eased value of progress (0 ~ 1).

progressf64
구간 진행률. (0 ~ 1)Span progress. (0 ~ 1)

반환Returnsf64 이징 값. (보통 0 ~ 1, elastic, back, 베지어 y 처럼 넘치는 곡선은 밖으로 나간다. step 은 늘 0)Eased value. (usually 0 ~ 1; overshooting curves like elastic, back and Bezier y go outside. step is always 0)

TimelineValueenum traits Clone, Debug, PartialEq

소스source

타임라인 값. (원본 키 값: 숫자, 문자열, 참거짓)

Timeline value. (the original key values: number, string, boolean)

이름Name값Value설명Description
None값 없음. (원본 null)No value. (the original null)
NumberNumber(f64)숫자.Number.
StringString(String)글. (색 "#rrggbbaa", 이벤트 이름도 이것)String. (colors "#rrggbbaa" and event names are this too)
BooleanBoolean(bool)참거짓.Boolean.
정적staticpub fn from_json(value: &Value) -> TimelineValue#0.3.2 부터since 0.3.2소스source

JSON 값에서 만들기. (배열, 객체는 none)

Creates from a JSON value. (arrays and objects are none)

value&Value
서술 키의 value 칸.The value field of a description key.

반환ReturnsTimelineValue 숫자는 Number(f64), 글은 String, 참거짓은 Boolean, null 과 배열, 객체는 None.Numbers are Number(f64), strings String, booleans Boolean; null, arrays and objects are None.

예제ExampleJSON 값을 타임라인 값으로JSON value to a timeline value
use serde_json::json;
use vanilla::TimelineValue;

assert_eq!(TimelineValue::from_json(&json!(2.5)), TimelineValue::Number(2.5));
assert_eq!(TimelineValue::from_json(&json!("hit")), TimelineValue::String(String::from("hit")));
assert_eq!(TimelineValue::from_json(&json!([1, 2])), TimelineValue::None);
메서드methodpub fn to_json(&self) -> Value#0.3.2 부터since 0.3.2소스source

JSON 값으로 바꾸기.

Converts to a JSON value.

반환ReturnsValue None 은 null, 숫자는 JSON 숫자(NaN 과 무한은 null), 글과 참거짓은 그대로.None is null, numbers are JSON numbers (NaN and infinity are null), strings and booleans as is.

메서드methodpub fn as_number(&self) -> f64#0.3.2 부터since 0.3.2소스source

숫자로 읽기. (원본 Number(값). 문자열은 읽고, 참거짓은 1 / 0, 없음은 0)

Reads as a number. (the original Number(value). Strings are parsed, booleans are 1 / 0, none is 0)

반환Returnsf64 숫자. 글은 앞뒤 공백을 떼고 읽는다. (빈 글은 0, 못 읽으면 NaN)Number. Strings are parsed after trimming leading and trailing whitespace. (an empty string is 0, NaN if unreadable)

예제Example여러 값을 숫자로Several values as numbers
use vanilla::TimelineValue;

assert_eq!(TimelineValue::String(String::from(" 12.5 ")).as_number(), 12.5);
assert_eq!(TimelineValue::Boolean(true).as_number(), 1.0);
assert_eq!(TimelineValue::None.as_number(), 0.0);
assert!(TimelineValue::String(String::from("abc")).as_number().is_nan());
메서드methodpub fn to_text(&self) -> String#0.3.2 부터since 0.3.2소스source

글로 읽기. (원본 String(값))

Reads as a string. (the original String(value))

반환ReturnsString 글. None 은 "null", 숫자는 정수면 소수점 없이(-0 은 "0", 무한은 "Infinity" / "-Infinity"), 참거짓은 "true" / "false".String. None is "null", numbers without a decimal point if integral (-0 is "0", infinity is "Infinity" / "-Infinity"), booleans are "true" / "false".

예제Example값을 글로Value as a string
use vanilla::TimelineValue;

assert_eq!(TimelineValue::Number(3.0).to_text(), "3");
assert_eq!(TimelineValue::Number(0.5).to_text(), "0.5");
assert_eq!(TimelineValue::None.to_text(), "null");
assert_eq!(TimelineValue::Boolean(false).to_text(), "false");
메서드methodpub fn is_true(&self) -> bool#0.3.2 부터since 0.3.2소스source

참으로 볼지. (원본 visible 속성: true 또는 "true")

Whether to treat it as true. (the original visible property: true or "true")

반환Returnsbool Boolean(true) 이거나 글 "true" 면 true. 숫자와 None 은 false.true if Boolean(true) or the string "true". Numbers and None are false.

TimelinePropertyKindenum traits Clone, Copy, Debug, PartialEq, Eq

소스source

속성 종류. (number 는 이징 보간, color 는 채널 보간, string / boolean 은 계단)

Property kind. (number interpolates with easing, color interpolates channels, string / boolean are stepped)

이름Name설명Description
Number숫자. (키 사이를 이징으로 보간)Number. (interpolated between keys with easing)
Color색 글. (채널마다 이징으로 보간)Color string. (each channel interpolated with easing)
String글. (계단, 다음 키에서 바뀐다)String. (stepped, changes at the next key)
Boolean참거짓. (계단)Boolean. (stepped)

TimelineTargetenum traits Clone, PartialEq, std::fmt::Debug

소스source

트랙 대상. (노드, 또는 노드가 아닌 것)

Track target. (a node, or something that is not a node)

이름Name값Value설명Description
NodeNode(NodeId)노드. (정의된 속성은 노드에 바로 건다)Node. (defined properties are applied directly to the node)
ExternalExternal(Rc<RefCell<dyn TimelinePropertyTarget>>)노드가 아닌 것. (원본 setTimelineProperty 를 가진 객체, evaluate 가 그 자리에서 값을 넘긴다)Something that is not a node. (an object with the original setTimelineProperty; evaluate passes values to it right there)