mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-28 17:19:31 +01:00
Merge origin/main into the outside pull request batch (M8)
# Conflicts: # CHANGELOG.md
This commit is contained in:
commit
da82dc71ea
88 files changed
+6494
-1223
No files matched your search
@@ -87,6 +87,7 @@ OR Apache-2.0) is noted in the table.
|
||||
| Hairlines: coverage falling off with the distance from the pixel centre to the line | `crates/render/src/hairline.rs`, `crates/gpu/src/fine.wgsl` | S. Gupta and R. F. Sproull, *Filtering Edges for Gray-Scale Displays* (SIGGRAPH 1981): anti-aliased lines by distance; standard | Public method; a one-pixel tent filter of the distance (ADR 0048). |
|
||||
| Plural categories for whole numbers (zero, one, two, few, many, other) | `src/i18n/plural.rs` | Unicode CLDR, *Language Plural Rules* (`common/supplemental/plurals.xml`), <https://cldr.unicode.org>, Unicode License v3 (Unicode-3.0) | The integer rules rewritten as Rust `match`es from the published rules; no CLDR data file is bundled. |
|
||||
| Stage elements as a multi-select list box; menu bar keyboard model (Alt/F10, arrows, access keys) | `src/stage_a11y.rs`, `src/menus.rs` | W3C *WAI-ARIA Authoring Practices Guide*, Listbox and Menubar patterns, <https://www.w3.org/WAI/ARIA/apg/> (W3C Software and Document License) | Keyboard behaviour learned from the published patterns; no code or text copied. |
|
||||
| Superscript and subscript size and offset; underline position and thickness | `crates/text/src/rich.rs` | Microsoft and Adobe, *OpenType specification*, `OS/2` table (`ySuperscriptYSize`, `ySuperscriptYOffset`, `ySubscriptYSize`, `ySubscriptYOffset`) and `post` table (`underlinePosition`, `underlineThickness`), <https://learn.microsoft.com/typography/opentype/spec/> | Metrics read from the font as the specification describes them; no code copied. |
|
||||
| Desktop integration of an AppImage: desktop entry `Exec` quoting and string escapes, MIME packages, hicolor icons, the user's data folder | `crates/engine/src/cmds_desktop.rs`, `src/platform.rs` | freedesktop.org *Desktop Entry Specification* 1.5, *Shared MIME-info Database*, *Icon Theme Specification*, *XDG Base Directory Specification*, <https://specifications.freedesktop.org/>; AppImage documentation on `$APPIMAGE` (public docs) | Written from the specifications (ADR 0094); no code copied. |
|
||||
| Reading the desktop's contrast setting | `src/platform.rs` | *XDG Desktop Portal*, Settings interface, `org.freedesktop.appearance` `contrast` key, <https://flatpak.github.io/xdg-desktop-portal/> (LGPL documentation, read only; nothing bundled or linked) | One value read through the `gdbus` tool. |
|
||||
| Interface catalog format (TSV keyed by English, `@plural`/`@id` rows, fallback order) | `src/i18n/catalog.rs`, `build.rs` | storytold/craft-i18n `docs/catalog-format.md` and `docs/integration.md` (MIT OR Apache-2.0, same project family) | Our own parser written from those documents; the craft-libs `craft-i18n` crate is not used (ADR 0040). |
|
||||
|
||||
@@ -38,6 +38,37 @@
|
||||
* **Camera** (Kushagra Kumar): with the camera layer hidden, Preview Through Camera no longer
|
||||
blocks drawing on the stage (fixes #126).
|
||||
|
||||
* **Mixed armatures: symbols and shapes in one armature** (ADR 0098, M7).
|
||||
* A body drawn as a shape that bends can carry a head, hands or props that are symbol
|
||||
instances, and an instance's bone can end on a shape that then gets bones of its own. One
|
||||
armature can hold several shapes with bones.
|
||||
* With the **Bone tool**, drag from a shape's bone end onto a symbol instance, or from an
|
||||
instance onto a shape and on inside it. The **Selection tool** poses the whole chain by IK;
|
||||
poses tween, and springs and joint translation act across both kinds.
|
||||
* The **Bind tool** binds and paints the points of the shape the picked bone is inside.
|
||||
* **Remove Bone** frees the instances and shapes the bone moved, as they look.
|
||||
* Headless: `bone.add` takes `parent` (a bone to continue from) and shapes as `to`;
|
||||
`bone.info` lists `members`, `shapes` and whether the armature is `mixed`.
|
||||
* Files: a document with a mixed armature is saved as format version 4, which earlier
|
||||
versions refuse with a clear message. Every other document is saved exactly as before.
|
||||
* Fixed: duplicating a symbol that holds a shape armature kept the copy's shape from bending.
|
||||
* **Styled text: per-character and paragraph styles** (ADR 0085, M5).
|
||||
* Select characters while typing on the stage and set their **font, size, colour, bold,
|
||||
italic, letter spacing, superscript or subscript, underline and link** in Properties; the
|
||||
section shows what the selection shares and marks the rest **mixed**.
|
||||
* **Paragraph styles**: alignment, first-line indent, left and right margins and line spacing
|
||||
per paragraph.
|
||||
* Typing continues the style before the caret; copy and paste inside AniCraft keeps styles,
|
||||
text from other apps pastes plain.
|
||||
* Each run is shaped on its own and lines wrap across runs; outlines are stored as before, so
|
||||
older files open and save unchanged. Every export draws each colour; SVG writes links.
|
||||
Break Apart gives one shape per colour.
|
||||
* **Animate files** keep their `DOMTextRun` styles in one block per field (they were split into
|
||||
a block per style before), with superscripts, indents, margins and links.
|
||||
* Headless: `text.style`, `text.paragraph`, `text.styles`; `text.create` and `text.edit` take
|
||||
`runs` and `paragraphs`.
|
||||
* **Floating windows open below the menu bar**: no dialog (the Custom Ease window among them) can
|
||||
cover File, Edit and View any more.
|
||||
* **Security: safer reads and temp files.** Import to Library checks an image's size (256 MiB) before reading it, and saves, audio exports and the video soundtrack write their temporary files under unguessable names, created exclusively.
|
||||
* **Saved commands (command macros)** (ADR 0097, M6).
|
||||
* In the **History** panel, **Ctrl+click** steps (Shift+click a range) and choose **Save As
|
||||
|
||||
Generated
+1
@@ -421,6 +421,7 @@ dependencies = [
|
||||
"craft-video",
|
||||
"craft-xfl",
|
||||
"miniz_oxide 0.8.9",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
|
||||
+176
-54
@@ -24,11 +24,18 @@
|
||||
//! angle, forward kinematics moves the joint (and what hangs from it) by it, and the solver
|
||||
//! slides joints only where turning them can't reach. **Springs** (per-bone strength and
|
||||
//! damping) add secondary motion on top of the keyed pose; see [`crate::spring`].
|
||||
//!
|
||||
//! An armature may be **mixed** (ADR 0098): its bones move symbol instances and whole shapes
|
||||
//! rigidly (their transforms), and bones *inside* a shape ([`Bone::shape`]) bend its outline
|
||||
//! through that shape's [`Skin`]. The two kinds join freely: a bone inside a shape may carry an
|
||||
//! instance on its end, and an instance's bone may end in a shape that has bones of its own.
|
||||
//! One pose, one solver and one tween serve all of it.
|
||||
|
||||
use crate::skin::{self, Skin};
|
||||
use crate::{Element, ElementId, Keyframe, Layer};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -140,12 +147,25 @@ pub struct Bone {
|
||||
/// The bone's spring (ADR 0084); `None`: none.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub spring: Option<Spring>,
|
||||
/// The shape this bone is inside (ADR 0071, ADR 0098): the bone bends that shape's outline
|
||||
/// through its [`Skin`], its `child` is a **joint node** (an id that is no element), and its
|
||||
/// `parent` is the shape itself or the node of another bone inside it. `None`: the bone
|
||||
/// moves an element (a symbol instance, or a whole shape) rigidly.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub shape: Option<ElementId>,
|
||||
}
|
||||
|
||||
impl Bone {
|
||||
/// A bone as drawn: turning freely, not sliding, no spring, not pinned.
|
||||
pub fn new(id: BoneId, parent: ElementId, child: ElementId, head: Vec2, tail: Vec2, rest: Affine) -> Bone {
|
||||
Bone { id, name: String::new(), parent, child, head, tail, rest, limits: None, pinned: false, slide_x: None, slide_y: None, spring: None }
|
||||
Bone { id, name: String::new(), parent, child, head, tail, rest, limits: None, pinned: false, slide_x: None, slide_y: None, spring: None, shape: None }
|
||||
}
|
||||
|
||||
/// A bone inside `shape` as drawn (ADR 0071): from `parent` (the shape, or the joint node of
|
||||
/// another bone inside it) to a new joint node `child`, `head` and `tail` in the shape's
|
||||
/// space.
|
||||
pub fn in_shape(id: BoneId, shape: ElementId, parent: ElementId, child: ElementId, head: Vec2, tail: Vec2) -> Bone {
|
||||
Bone { shape: Some(shape), ..Bone::new(id, parent, child, head, tail, Affine::IDENTITY) }
|
||||
}
|
||||
|
||||
/// Whether the joint may slide at all.
|
||||
@@ -181,30 +201,112 @@ impl Bone {
|
||||
}
|
||||
|
||||
/// The bones of an armature layer, each listed after the bone it hangs from.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
|
||||
#[serde(from = "ArmatureIn")]
|
||||
pub struct Armature {
|
||||
#[serde(default)]
|
||||
pub bones: Vec<Bone>,
|
||||
/// A shape armature (ADR 0071): the bones are inside this shape and bend its outline. Its
|
||||
/// bones join joint nodes (ids that are no element) instead of instances; see
|
||||
/// [`crate::skin`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub skin: Option<Skin>,
|
||||
/// The shapes with bones inside them (ADR 0071), one [`Skin`] each: the bones marked with
|
||||
/// that shape ([`Bone::shape`]) bend its outline. Empty for an armature of instances only.
|
||||
pub skins: Vec<Skin>,
|
||||
/// The armature's springs are turned off (Properties › Bone › Springs, ADR 0084): it plays
|
||||
/// its keyed poses exactly, for posing without the swing.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub springs_off: bool,
|
||||
}
|
||||
|
||||
/// An armature as files hold it. Two forms (ADR 0098):
|
||||
///
|
||||
/// * the **first form** (format versions up to 3): `bones`, and for a shape armature its one
|
||||
/// `skin`; every bone of an armature with a `skin` is inside that shape;
|
||||
/// * the **mixed form** (format version 4): `bones` that say which shape they are inside
|
||||
/// (`shape`), and `skins`, one per shape with bones.
|
||||
///
|
||||
/// An armature the first form can say is always written in it, so documents without mixed
|
||||
/// armatures are byte for byte what earlier builds wrote, and earlier builds open them.
|
||||
#[derive(Deserialize)]
|
||||
struct ArmatureIn {
|
||||
#[serde(default)]
|
||||
bones: Vec<Bone>,
|
||||
#[serde(default)]
|
||||
skin: Option<Skin>,
|
||||
#[serde(default)]
|
||||
skins: Vec<Skin>,
|
||||
#[serde(default)]
|
||||
springs_off: bool,
|
||||
}
|
||||
|
||||
impl From<ArmatureIn> for Armature {
|
||||
fn from(a: ArmatureIn) -> Armature {
|
||||
let (mut bones, mut skins) = (a.bones, a.skins);
|
||||
if let Some(k) = a.skin {
|
||||
// The first form: every bone is inside the one shape.
|
||||
for b in &mut bones {
|
||||
b.shape.get_or_insert(k.shape);
|
||||
}
|
||||
skins.insert(0, k);
|
||||
}
|
||||
Armature { bones, skins, springs_off: a.springs_off }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ArmatureOut<'a> {
|
||||
bones: Cow<'a, [Bone]>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
skin: Option<&'a Skin>,
|
||||
#[serde(skip_serializing_if = "<[Skin]>::is_empty")]
|
||||
skins: &'a [Skin],
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
springs_off: bool,
|
||||
}
|
||||
|
||||
impl Serialize for Armature {
|
||||
fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
|
||||
let out = if self.is_mixed() {
|
||||
ArmatureOut { bones: Cow::Borrowed(&self.bones), skin: None, skins: &self.skins, springs_off: self.springs_off }
|
||||
} else {
|
||||
// The first form doesn't mark its bones: with a skin, all of them are inside it.
|
||||
let bones = if self.skins.is_empty() { Cow::Borrowed(self.bones.as_slice()) } else { Cow::Owned(self.bones.iter().map(|b| Bone { shape: None, ..b.clone() }).collect()) };
|
||||
ArmatureOut { bones, skin: self.skins.first(), skins: &[], springs_off: self.springs_off }
|
||||
};
|
||||
out.serialize(ser)
|
||||
}
|
||||
}
|
||||
|
||||
impl Armature {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.bones.is_empty()
|
||||
}
|
||||
|
||||
/// The shape a shape armature's bones are inside (ADR 0071); `None` for an armature of
|
||||
/// symbol instances.
|
||||
pub fn skin_shape(&self) -> Option<ElementId> {
|
||||
self.skin.as_ref().map(|s| s.shape)
|
||||
/// Whether the armature needs the mixed file form (ADR 0098): more than one shape with
|
||||
/// bones, or bones inside a shape next to bones that move elements. Otherwise it is an
|
||||
/// armature of instances (ADR 0043) or of one shape (ADR 0071), written as it always was.
|
||||
pub fn is_mixed(&self) -> bool {
|
||||
let only = self.skins.first().map(|k| k.shape);
|
||||
self.skins.len() > 1 || self.bones.iter().any(|b| b.shape != only)
|
||||
}
|
||||
|
||||
/// The skin of `shape`, when the armature has bones inside it.
|
||||
pub fn skin(&self, shape: ElementId) -> Option<&Skin> {
|
||||
self.skins.iter().find(|k| k.shape == shape)
|
||||
}
|
||||
|
||||
pub fn skin_mut(&mut self, shape: ElementId) -> Option<&mut Skin> {
|
||||
self.skins.iter_mut().find(|k| k.shape == shape)
|
||||
}
|
||||
|
||||
/// The skin bone `id` bends: its shape's, when the bone is inside a shape.
|
||||
pub fn skin_of(&self, id: BoneId) -> Option<&Skin> {
|
||||
self.skin(self.bone(id)?.shape?)
|
||||
}
|
||||
|
||||
/// The bones inside `shape`, in armature order.
|
||||
pub fn bones_in(&self, shape: ElementId) -> impl Iterator<Item = &Bone> {
|
||||
self.bones.iter().filter(move |b| b.shape == Some(shape))
|
||||
}
|
||||
|
||||
/// How many points of its shape bone `id` moves (0 for a bone that moves an element).
|
||||
pub fn bound_count(&self, id: BoneId) -> usize {
|
||||
self.skin_of(id).map_or(0, |k| k.points.iter().filter(|b| b.weight(id) > 0.0).count())
|
||||
}
|
||||
|
||||
pub fn bone(&self, id: BoneId) -> Option<&Bone> {
|
||||
@@ -230,15 +332,15 @@ impl Armature {
|
||||
self.bone_into(b.parent)
|
||||
}
|
||||
|
||||
/// Whether instance `el` is part of the armature.
|
||||
/// Whether `el` (an element, or a joint node) is part of the armature.
|
||||
pub fn contains(&self, el: ElementId) -> bool {
|
||||
self.bones.iter().any(|b| b.parent == el || b.child == el)
|
||||
}
|
||||
|
||||
/// Every instance in the armature, roots first.
|
||||
/// Every element in the armature (instances and shapes, never joint nodes), roots first.
|
||||
pub fn members(&self) -> Vec<ElementId> {
|
||||
let mut out: Vec<ElementId> = self.roots();
|
||||
for b in &self.bones {
|
||||
for b in self.bones.iter().filter(|b| b.shape.is_none()) {
|
||||
if !out.contains(&b.child) {
|
||||
out.push(b.child);
|
||||
}
|
||||
@@ -246,12 +348,9 @@ impl Armature {
|
||||
out
|
||||
}
|
||||
|
||||
/// The instances no bone moves (one for an armature made with the Bone tool; a shape
|
||||
/// armature's shape).
|
||||
/// The elements no bone moves (one for an armature made with the Bone tool: an instance,
|
||||
/// or a shape with bones inside it).
|
||||
pub fn roots(&self) -> Vec<ElementId> {
|
||||
if let Some(s) = self.skin_shape() {
|
||||
return vec![s];
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for b in &self.bones {
|
||||
if self.bone_into(b.parent).is_none() && !out.contains(&b.parent) {
|
||||
@@ -289,15 +388,22 @@ impl Armature {
|
||||
}
|
||||
|
||||
/// Repairs a loaded armature: drops bones with non-finite numbers, repeated ids, a second
|
||||
/// bone into one instance and bones in cycles; keeps every bone after its parent; keeps at
|
||||
/// most [`MAX_BONES`]. Returns whether anything changed.
|
||||
/// bone into one element and bones in cycles; keeps every bone after its parent; keeps at
|
||||
/// most [`MAX_BONES`]. A bone inside a shape must hang from that shape or from another bone
|
||||
/// inside it, and the shape needs a skin; a skin needs bones, an outline within the point
|
||||
/// limit and one sane binding per point. Returns whether anything changed.
|
||||
pub fn sanitize(&mut self) -> bool {
|
||||
let before = self.bones.clone();
|
||||
let before = self.clone();
|
||||
// One skin per shape, each within the point limit.
|
||||
let mut shapes = HashSet::new();
|
||||
self.skins.retain(|k| skin::anchors(&k.rest).len() <= skin::MAX_SKIN_POINTS && shapes.insert(k.shape));
|
||||
let mut seen_id = HashSet::new();
|
||||
let mut seen_child = HashSet::new();
|
||||
let mut kept: Vec<Bone> = Vec::new();
|
||||
for mut b in std::mem::take(&mut self.bones) {
|
||||
if !b.is_sane() || !seen_id.insert(b.id) || !seen_child.insert(b.child) {
|
||||
// A joint node is no element: a bone inside a shape can't end on a shape with bones.
|
||||
let node_ok = b.shape.is_none_or(|s| shapes.contains(&s) && !shapes.contains(&b.child));
|
||||
if !b.is_sane() || !node_ok || !seen_id.insert(b.id) || !seen_child.insert(b.child) {
|
||||
continue;
|
||||
}
|
||||
b.limits = b.limits.and_then(Limits::sanitized);
|
||||
@@ -310,30 +416,33 @@ impl Armature {
|
||||
}
|
||||
kept.push(b);
|
||||
}
|
||||
// Order: a bone after the bone moving its parent. What never gets placed is a cycle.
|
||||
// A shape armature's bones all hang from its shape.
|
||||
// Order: a bone after the bone moving its parent. What never gets placed is a cycle, or
|
||||
// a bone inside a shape that hangs from something outside it.
|
||||
let children: HashSet<ElementId> = kept.iter().map(|b| b.child).collect();
|
||||
let mut placed: HashSet<ElementId> = match self.skin_shape() {
|
||||
Some(s) => HashSet::from([s]),
|
||||
None => kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect(),
|
||||
};
|
||||
let mut placed: HashSet<ElementId> = kept.iter().map(|b| b.parent).filter(|p| !children.contains(p)).collect();
|
||||
let mut node_in: HashMap<ElementId, ElementId> = HashMap::new();
|
||||
let mut ordered = Vec::with_capacity(kept.len());
|
||||
let mut rest = kept;
|
||||
loop {
|
||||
let (ready, wait): (Vec<Bone>, Vec<Bone>) = rest.into_iter().partition(|b| placed.contains(&b.parent));
|
||||
let (ready, wait): (Vec<Bone>, Vec<Bone>) = rest.into_iter().partition(|b| placed.contains(&b.parent) && b.shape.is_none_or(|s| b.parent == s || node_in.get(&b.parent) == Some(&s)));
|
||||
if ready.is_empty() {
|
||||
break;
|
||||
}
|
||||
for b in ready {
|
||||
placed.insert(b.child);
|
||||
if let Some(s) = b.shape {
|
||||
node_in.insert(b.child, s);
|
||||
}
|
||||
ordered.push(b);
|
||||
}
|
||||
rest = wait;
|
||||
}
|
||||
ordered.truncate(MAX_BONES);
|
||||
self.bones = ordered;
|
||||
let skin_changed = skin::sanitize(self);
|
||||
self.bones != before || skin_changed
|
||||
let boned: HashSet<ElementId> = self.bones.iter().filter_map(|b| b.shape).collect();
|
||||
self.skins.retain(|k| boned.contains(&k.shape));
|
||||
skin::sanitize(self);
|
||||
*self != before
|
||||
}
|
||||
}
|
||||
|
||||
@@ -467,10 +576,10 @@ pub(crate) fn turn_about(j: Vec2, angle: f32) -> Affine {
|
||||
/// the same way from the shape's transform.
|
||||
pub fn place(arm: &Armature, elements: &[Arc<Element>], pose: &Pose) -> HashMap<ElementId, Affine> {
|
||||
let mut world: HashMap<ElementId, Affine> = elements.iter().map(|e| (e.id, e.transform)).collect();
|
||||
let nodes = arm.skin.is_some();
|
||||
for b in &arm.bones {
|
||||
let Some(wp) = world.get(&b.parent).copied() else { continue };
|
||||
if !nodes && !world.contains_key(&b.child) {
|
||||
// A joint node is no element: it is placed whether or not anything is on the keyframe.
|
||||
if b.shape.is_none() && !world.contains_key(&b.child) {
|
||||
continue;
|
||||
}
|
||||
let (_, wc) = joint(b, &wp, b.allow(pose.angle(b.id)), b.allow_slide(pose.slide(b.id)));
|
||||
@@ -512,29 +621,30 @@ pub fn joint(b: &Bone, wp: &Affine, a: f32, s: Vec2) -> (Vec2, Affine) {
|
||||
(j, turn_about(j, a).mul(&Affine::translate(d.x, d.y).mul(&base)))
|
||||
}
|
||||
|
||||
/// Puts the instances of `elements` where `pose` has them, and bends a shape armature's shape
|
||||
/// (copy-on-write: only what changes is cloned). Returns whether anything changed.
|
||||
/// Puts the elements a bone moves (instances, whole shapes) where `pose` has them, and bends
|
||||
/// every shape with bones inside it (copy-on-write: only what changes is cloned). Returns
|
||||
/// whether anything changed.
|
||||
pub fn apply(arm: &Armature, elements: &mut [Arc<Element>], pose: &Pose) -> bool {
|
||||
if arm.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if arm.skin.is_some() {
|
||||
return skin::apply(arm, elements, pose);
|
||||
}
|
||||
let world = place(arm, elements, pose);
|
||||
let mut moved = false;
|
||||
for e in elements.iter_mut() {
|
||||
if arm.bone_into(e.id).is_none() {
|
||||
continue;
|
||||
}
|
||||
if let Some(m) = world.get(&e.id)
|
||||
&& *m != e.transform
|
||||
{
|
||||
Arc::make_mut(e).transform = *m;
|
||||
moved = true;
|
||||
// An armature of one shape (ADR 0071) moves no element: only its outline bends.
|
||||
if arm.bones.iter().any(|b| b.shape.is_none()) {
|
||||
let world = place(arm, elements, pose);
|
||||
for e in elements.iter_mut() {
|
||||
if arm.bone_into(e.id).is_none() {
|
||||
continue;
|
||||
}
|
||||
if let Some(m) = world.get(&e.id)
|
||||
&& *m != e.transform
|
||||
{
|
||||
Arc::make_mut(e).transform = *m;
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
moved
|
||||
skin::apply(arm, elements, pose) || moved
|
||||
}
|
||||
|
||||
/// The pose layer `layer` has at `frame`: its covering keyframe's, or, inside a tween, the pose
|
||||
@@ -569,8 +679,16 @@ pub struct BoneAt {
|
||||
/// Every bone's joint and end with the instances in `elements` placed as they show (posed:
|
||||
/// what [`crate::evaluate_layer_elements`] gives on an armature layer).
|
||||
pub fn bones_at(arm: &Armature, elements: &[Arc<Element>], pose: &Pose) -> Vec<BoneAt> {
|
||||
// A shape armature's joint nodes are no elements: forward kinematics places them.
|
||||
let world: HashMap<ElementId, Affine> = if arm.skin.is_some() { place(arm, elements, pose) } else { elements.iter().map(|e| (e.id, e.transform)).collect() };
|
||||
// The elements are where they show. Joint nodes inside shapes are no elements: forward
|
||||
// kinematics places them from what they hang from.
|
||||
let mut world: HashMap<ElementId, Affine> = elements.iter().map(|e| (e.id, e.transform)).collect();
|
||||
for b in arm.bones.iter().filter(|b| b.shape.is_some()) {
|
||||
let Some(wp) = world.get(&b.parent).copied() else { continue };
|
||||
let (_, wc) = joint(b, &wp, b.allow(pose.angle(b.id)), b.allow_slide(pose.slide(b.id)));
|
||||
if wc.is_finite() {
|
||||
world.insert(b.child, wc);
|
||||
}
|
||||
}
|
||||
arm.bones
|
||||
.iter()
|
||||
.filter_map(|b| {
|
||||
@@ -741,3 +859,7 @@ fn ccd(arm: &Armature, chain: &[&Bone], effector: &Effector<'_>, mut pose: Pose,
|
||||
#[cfg(test)]
|
||||
#[path = "armature_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mixed_tests.rs"]
|
||||
mod mixed_tests;
|
||||
+25
-11
@@ -65,6 +65,9 @@ pub struct DisplayList {
|
||||
/// through each other. A group's items are one unbroken run of `items`, nested runs for
|
||||
/// nested groups; a parent always has a lower index.
|
||||
pub groups: Vec<Group>,
|
||||
/// Links on text (ADR 0085): `(item, url)` for each item drawing characters that link
|
||||
/// somewhere, in item order. Sparse: most lists have none.
|
||||
pub links: Vec<(u32, Arc<str>)>,
|
||||
}
|
||||
|
||||
/// A group that fades as one (see [`DisplayList::groups`]).
|
||||
@@ -138,6 +141,8 @@ impl DisplayList {
|
||||
self.set_clip_mode(base + i as u32, m);
|
||||
}
|
||||
self.groups.extend(other.groups.into_iter().map(|g| Group { parent: gshift(g.parent), alpha: g.alpha, blend: g.blend, filters: g.filters, clip: shift(g.clip) }));
|
||||
let ibase = self.items.len() as u32;
|
||||
self.links.extend(other.links.into_iter().map(|(i, u)| (i + ibase, u)));
|
||||
self.items.extend(other.items.into_iter().map(|mut i| {
|
||||
i.clip = shift(i.clip);
|
||||
i.masks = shift(i.masks);
|
||||
@@ -665,10 +670,11 @@ fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out:
|
||||
let live = child.as_ref().map(|c| (c.state.fields.get(&c.path), c.state.focus.as_deref() == Some(c.path.as_slice())));
|
||||
field_items(t, f, live, xf, clip, out, item);
|
||||
}
|
||||
_ => {
|
||||
let path = child.as_ref().and_then(|c| c.state.fields.get(&c.path)).and_then(|s| s.look.as_ref()).map_or_else(|| t.outline.clone(), |l| l.outline.clone());
|
||||
out.items.push(item(path, xf, Some(Paint::Solid(t.color)), None, clip, masks));
|
||||
}
|
||||
_ => match child.as_ref().and_then(|c| c.state.fields.get(&c.path)).and_then(|s| s.look.as_ref()) {
|
||||
Some(l) => out.items.push(item(l.outline.clone(), xf, Some(Paint::Solid(t.color)), None, clip, masks)),
|
||||
// One item per colour (ADR 0085), with its link.
|
||||
None => text_fills(t, out, |path, color| item(path, xf, Some(Paint::Solid(color)), None, clip, masks)),
|
||||
},
|
||||
}
|
||||
}
|
||||
ElementKind::Camera => {}
|
||||
@@ -731,6 +737,17 @@ fn eval_element(doc: &Document, cx: &Ctx, lc: &LayerCtx<'_>, el: &Element, out:
|
||||
}
|
||||
}
|
||||
|
||||
/// A text block's authored outline as items, one per colour piece (ADR 0085), recording the
|
||||
/// links of pieces that have one.
|
||||
fn text_fills(t: &crate::TextBlock, out: &mut DisplayList, item: impl Fn(Arc<Path>, Rgba) -> DisplayItem) {
|
||||
for (color, url, path) in t.fill_paths() {
|
||||
if !url.is_empty() {
|
||||
out.links.push((out.items.len() as u32, Arc::from(url)));
|
||||
}
|
||||
out.items.push(item(path, color));
|
||||
}
|
||||
}
|
||||
|
||||
/// The highlight behind selected text in a focused field.
|
||||
pub const SELECTION: Rgba = Rgba::new(0.62, 0.78, 1.0, 1.0);
|
||||
|
||||
@@ -769,13 +786,10 @@ fn field_items(t: &crate::TextBlock, f: &crate::TextField, live: Option<(Option<
|
||||
}
|
||||
// The text: laid out by the player when it changed, else the authored outline (a field whose
|
||||
// text changed but couldn't be laid out shows none).
|
||||
let outline = match (state.and_then(|s| s.text.as_ref()), look) {
|
||||
(_, Some(l)) => Some(l.outline.clone()),
|
||||
(None, None) => Some(t.outline.clone()),
|
||||
(Some(_), None) => None,
|
||||
};
|
||||
if let Some(path) = outline {
|
||||
out.items.push(item(path, text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None));
|
||||
match (state.and_then(|s| s.text.as_ref()), look) {
|
||||
(_, Some(l)) => out.items.push(item(l.outline.clone(), text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None)),
|
||||
(None, None) => text_fills(t, out, |path, color| item(path, text_xf, Some(Paint::Solid(color)), None, Some(inner), None)),
|
||||
(Some(_), None) => {}
|
||||
}
|
||||
// The caret, in an input field with the keyboard and nothing selected.
|
||||
if let (true, Some(st), crate::TextKind::Input) = (focused, state, f.kind)
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::*;
|
||||
use crate::{Rgba, TextAlign};
|
||||
|
||||
fn block(text: &str, f: TextField) -> TextBlock {
|
||||
TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 54.0, box_height: 24.0, field: Some(f), on_path: None }
|
||||
TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 54.0, box_height: 24.0, field: Some(f), on_path: None, ..Default::default() }
|
||||
}
|
||||
|
||||
/// Runs edits on a field as the player does: each change of text lays it out again (10 px per
|
||||
|
||||
@@ -29,6 +29,7 @@ pub mod width;
|
||||
pub mod stroke_style;
|
||||
pub mod player;
|
||||
pub mod publish;
|
||||
pub mod rich_text;
|
||||
pub mod sample;
|
||||
pub mod templates;
|
||||
pub mod sound;
|
||||
@@ -48,6 +49,7 @@ pub use camera::{Camera, DepthKey};
|
||||
pub use swatch::{MAX_SWATCHES, Swatch, SwatchPaint};
|
||||
pub use aids::{Aids, GUIDE_REACH, Grid, Guide, GuideAxis, MAX_GUIDES};
|
||||
pub use nine_slice::symbol_box;
|
||||
pub use rich_text::{BaselineShift, CharStyle, MAX_TEXT_RUNS, MAX_URL, ParagraphStyle, StyleSummary, TextFill, TextRun, safe_url};
|
||||
pub use armature::{Armature, Bone, BoneId, JointAngle, Limits, Pose};
|
||||
pub use eval::{DisplayItem, DisplayList, Group, MAX_SYMBOL_DEPTH, evaluate, evaluate_guided, evaluate_layer_elements, evaluate_shown, evaluate_player, evaluate_scene, evaluate_scene_camera, evaluate_timeline, evaluate_timeline_at, guide_walk, instance_start};
|
||||
pub use actions::{Action, ButtonEvent, EventHandler, FrameScript, Language, PluginScript, SourceScript};
|
||||
@@ -777,6 +779,68 @@ pub struct TextBlock {
|
||||
/// `outline` holds the glyphs set along it. Static text only.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub on_path: Option<TextPath>,
|
||||
/// The first run's baseline shift, underline and link (ADR 0085).
|
||||
#[serde(default, skip_serializing_if = "rich_text_is_normal")]
|
||||
pub shift: BaselineShift,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub underline: bool,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub url: String,
|
||||
/// The first paragraph's indent and margins (ADR 0085).
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub indent: f32,
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub left_margin: f32,
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub right_margin: f32,
|
||||
/// Styled runs covering the text, when its characters differ in style (ADR 0085; empty:
|
||||
/// all in the style above). Set with [`TextBlock::set_styles`].
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub runs: Vec<TextRun>,
|
||||
/// One style per paragraph, when they differ (empty: all as above).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub paragraphs: Vec<ParagraphStyle>,
|
||||
/// The outline cut into pieces by colour and link, in order (empty: all in `color`).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub fills: Vec<TextFill>,
|
||||
#[serde(skip)]
|
||||
pub fill_cache: rich_text::FillCache,
|
||||
}
|
||||
|
||||
fn rich_text_is_normal(s: &BaselineShift) -> bool {
|
||||
*s == BaselineShift::Normal
|
||||
}
|
||||
|
||||
impl Default for TextBlock {
|
||||
fn default() -> Self {
|
||||
TextBlock {
|
||||
text: String::new(),
|
||||
font: String::new(),
|
||||
size: 32.0,
|
||||
bold: false,
|
||||
italic: false,
|
||||
color: Rgba::BLACK,
|
||||
align: TextAlign::Left,
|
||||
letter_spacing: 0.0,
|
||||
line_spacing: 0.0,
|
||||
width: None,
|
||||
outline: Arc::new(Path::new()),
|
||||
box_width: 0.0,
|
||||
box_height: 0.0,
|
||||
field: None,
|
||||
on_path: None,
|
||||
shift: BaselineShift::Normal,
|
||||
underline: false,
|
||||
url: String::new(),
|
||||
indent: 0.0,
|
||||
left_margin: 0.0,
|
||||
right_margin: 0.0,
|
||||
runs: Vec::new(),
|
||||
paragraphs: Vec::new(),
|
||||
fills: Vec::new(),
|
||||
fill_cache: rich_text::FillCache::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The path a text block follows (ADR 0070), and where along it the text sits.
|
||||
@@ -1932,6 +1996,12 @@ impl Document {
|
||||
}
|
||||
all.into_iter()
|
||||
}
|
||||
/// Whether any armature of the document is mixed (ADR 0098): instances and shapes in one
|
||||
/// armature, or several shapes with bones. Such a document is written as format version 4,
|
||||
/// which earlier builds refuse by its number; every other document is written as before.
|
||||
pub fn has_mixed_armatures(&self) -> bool {
|
||||
self.timelines().flat_map(|tl| &tl.layers).any(|l| l.kind == LayerKind::Armature && l.armature.as_ref().is_some_and(|a| a.is_mixed()))
|
||||
}
|
||||
/// Repairs a loaded document: ids, sizes and keyframe order.
|
||||
pub fn sanitize(&mut self) {
|
||||
let s = &mut self.stage;
|
||||
|
||||
@@ -507,9 +507,14 @@ pub fn fresh_ids(tl: &Timeline, alloc: &mut dyn FnMut() -> u64) -> Timeline {
|
||||
l.id = layers.get(&l.id).copied().unwrap_or(l.id);
|
||||
l.parent = l.parent.map(|p| layers.get(&p).copied().unwrap_or(p));
|
||||
if let Some(a) = &mut l.armature {
|
||||
for b in &mut Arc::make_mut(a).bones {
|
||||
let a = Arc::make_mut(a);
|
||||
for b in &mut a.bones {
|
||||
b.parent = el(b.parent);
|
||||
b.child = el(b.child);
|
||||
b.shape = b.shape.map(el);
|
||||
}
|
||||
for k in &mut a.skins {
|
||||
k.shape = el(k.shape);
|
||||
}
|
||||
}
|
||||
for k in &mut l.keyframes {
|
||||
|
||||
@@ -0,0 +1,364 @@
|
||||
//! Mixed armatures (ADR 0098): instances and shapes in one armature. The model's own rules:
|
||||
//! forward kinematics across the kinds, the two file forms, repair of hostile files.
|
||||
|
||||
use super::*;
|
||||
use crate::skin::{Binding, Influence, anchors, rebind};
|
||||
use crate::{BlendMode, ColorEffect, ElementKind, LoopMode, Paint, Rgba, Shape, SymbolId};
|
||||
use anicraft_geom::Path;
|
||||
use std::f32::consts::FRAC_PI_2;
|
||||
|
||||
const BODY: ElementId = ElementId(10);
|
||||
const HEAD: ElementId = ElementId(11);
|
||||
const HAT: ElementId = ElementId(12);
|
||||
const N1: ElementId = ElementId(30);
|
||||
const N2: ElementId = ElementId(31);
|
||||
const N3: ElementId = ElementId(32);
|
||||
const SPINE1: BoneId = BoneId(20);
|
||||
const SPINE2: BoneId = BoneId(21);
|
||||
const NECK: BoneId = BoneId(22);
|
||||
const BRIM: BoneId = BoneId(23);
|
||||
const TIP: BoneId = BoneId(24);
|
||||
|
||||
/// A closed bar from (0, -half) to (len, half), anchors every `step` px along both edges.
|
||||
fn bar(len: f32, half: f32, step: f32) -> Path {
|
||||
let n = (len / step) as usize;
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(0.0, -half));
|
||||
for i in 1..=n {
|
||||
p.line_to(Vec2::new(step * i as f32, -half));
|
||||
}
|
||||
for i in (0..=n).rev() {
|
||||
p.line_to(Vec2::new(step * i as f32, half));
|
||||
}
|
||||
p.close();
|
||||
p
|
||||
}
|
||||
|
||||
fn shape(id: ElementId, path: Arc<Path>, at: Vec2) -> Arc<Element> {
|
||||
let shape = Shape { path, ..Shape::filled(Path::new(), Paint::Solid(Rgba::BLACK)) };
|
||||
Arc::new(Element { id, name: String::new(), transform: Affine::translate(at.x, at.y), color: ColorEffect::default(), kind: ElementKind::Shape(shape) })
|
||||
}
|
||||
|
||||
fn instance(id: ElementId, at: Vec2) -> Arc<Element> {
|
||||
let kind = ElementKind::Symbol { symbol: SymbolId(1), loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() };
|
||||
Arc::new(Element { id, name: String::new(), transform: Affine::translate(at.x, at.y), color: ColorEffect::default(), kind })
|
||||
}
|
||||
|
||||
/// A body lying along y = 100 from x = 100 to 300 with two bones inside it (joint at x = 200),
|
||||
/// a head instance at (330, 100) on a bone from the body's end, and a hat shape at (360, 100)
|
||||
/// that the head's bone carries as a whole, with one bone inside it.
|
||||
fn rig() -> (Armature, Vec<Arc<Element>>) {
|
||||
let (body, hat) = (Arc::new(bar(200.0, 10.0, 25.0)), Arc::new(bar(40.0, 5.0, 10.0)));
|
||||
let v = Vec2::new;
|
||||
let mut arm = Armature {
|
||||
bones: vec![
|
||||
Bone::in_shape(SPINE1, BODY, BODY, N1, v(0.0, 0.0), v(100.0, 0.0)),
|
||||
Bone::in_shape(SPINE2, BODY, N1, N2, v(100.0, 0.0), v(200.0, 0.0)),
|
||||
// From the joint node at the body's end (the body's space) to the head.
|
||||
Bone::new(NECK, N2, HEAD, v(200.0, 0.0), v(0.0, 0.0), Affine::translate(230.0, 0.0)),
|
||||
// From the head to the hat as a whole.
|
||||
Bone::new(BRIM, HEAD, HAT, v(0.0, 0.0), v(0.0, 0.0), Affine::translate(30.0, 0.0)),
|
||||
Bone::in_shape(TIP, HAT, HAT, N3, v(0.0, 0.0), v(40.0, 0.0)),
|
||||
],
|
||||
skins: vec![Skin::new(BODY, body.clone()), Skin::new(HAT, hat.clone())],
|
||||
springs_off: false,
|
||||
};
|
||||
rebind(&mut arm);
|
||||
(arm, vec![shape(BODY, body, v(100.0, 100.0)), instance(HEAD, v(330.0, 100.0)), shape(HAT, hat, v(360.0, 100.0))])
|
||||
}
|
||||
|
||||
fn path_of(e: &Element) -> Arc<Path> {
|
||||
match &e.kind {
|
||||
ElementKind::Shape(s) => s.path.clone(),
|
||||
_ => panic!("not a shape"),
|
||||
}
|
||||
}
|
||||
|
||||
fn turned(p: Vec2, j: Vec2, a: f32) -> Vec2 {
|
||||
let (s, c) = a.sin_cos();
|
||||
let d = p - j;
|
||||
Vec2::new(j.x + d.x * c - d.y * s, j.y + d.x * s + d.y * c)
|
||||
}
|
||||
|
||||
fn close(a: Vec2, b: Vec2) -> bool {
|
||||
a.distance(b) < 1e-3
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rest_pose_changes_nothing() {
|
||||
let (arm, els) = rig();
|
||||
assert!(arm.is_mixed());
|
||||
assert_eq!(arm.roots(), vec![BODY]);
|
||||
assert_eq!(arm.members(), vec![BODY, HEAD, HAT], "joint nodes are no members");
|
||||
let mut posed = els.clone();
|
||||
assert!(!apply(&arm, &mut posed, &Pose::default()), "nothing to move at rest");
|
||||
for (a, b) in posed.iter().zip(&els) {
|
||||
assert!(Arc::ptr_eq(a, b), "not even a copy is made");
|
||||
}
|
||||
// Bindings stay inside each shape: no point of one follows a bone of the other.
|
||||
let ids = |k: &Skin| k.points.iter().flat_map(|b| b.bones.iter().map(|i| i.0)).collect::<HashSet<_>>();
|
||||
assert_eq!(ids(&arm.skins[0]), HashSet::from([SPINE1, SPINE2]));
|
||||
assert_eq!(ids(&arm.skins[1]), HashSet::from([TIP]));
|
||||
assert_eq!((arm.bound_count(SPINE1) > 0, arm.bound_count(NECK), arm.bound_count(TIP)), (true, 0, 10));
|
||||
assert_eq!(arm.skin_of(TIP).map(|k| k.shape), Some(HAT));
|
||||
assert!(arm.skin_of(NECK).is_none() && arm.skin_of(BRIM).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_pose_places_instances_and_bends_shapes_consistently() {
|
||||
let (arm, els) = rig();
|
||||
let mut pose = Pose::default();
|
||||
pose.set(SPINE2, FRAC_PI_2);
|
||||
let joint = Vec2::new(200.0, 100.0);
|
||||
let mut posed = els.clone();
|
||||
assert!(apply(&arm, &mut posed, &pose));
|
||||
// The body's end points turn a quarter about its middle joint.
|
||||
let body = anchors(&path_of(&posed[0]));
|
||||
assert!(close(posed[0].transform.apply(body[8]), turned(Vec2::new(300.0, 90.0), joint, FRAC_PI_2)));
|
||||
assert_eq!(posed[0].transform, els[0].transform, "a root shape's transform is never touched");
|
||||
// The head and the hat turn with them, rigidly, and stay joined to the body's end.
|
||||
assert!(close(posed[1].transform.translation(), turned(Vec2::new(330.0, 100.0), joint, FRAC_PI_2)));
|
||||
assert!(close(posed[2].transform.translation(), turned(Vec2::new(360.0, 100.0), joint, FRAC_PI_2)));
|
||||
assert!(Arc::ptr_eq(&path_of(&posed[2]), &arm.skins[1].rest), "the hat's own bone is at rest: its outline is the drawn one");
|
||||
let at = bones_at(&arm, &posed, &pose);
|
||||
let of = |id: BoneId| at.iter().find(|b| b.id == id).copied().unwrap();
|
||||
assert!(close(of(NECK).head, of(SPINE2).tail), "the head's bone starts where the body's last bone ends");
|
||||
assert!(close(of(BRIM).head, of(NECK).tail));
|
||||
assert!(close(of(TIP).head, of(BRIM).tail));
|
||||
assert!(close(of(TIP).tail, turned(Vec2::new(400.0, 100.0), joint, FRAC_PI_2)));
|
||||
// Placing posed elements again gives the same places (the stage draws bones from them).
|
||||
let again = place(&arm, &posed, &pose);
|
||||
assert!(close(again[&HEAD].translation(), posed[1].transform.translation()));
|
||||
// The hat's bone bends the hat about its own foot, in the hat's space.
|
||||
pose.set(TIP, -FRAC_PI_2);
|
||||
let mut both = els.clone();
|
||||
apply(&arm, &mut both, &pose);
|
||||
assert_eq!(both[2].transform, posed[2].transform, "the hat's bone bends it; the head's bone carries it");
|
||||
let hat = anchors(&path_of(&both[2]));
|
||||
assert!(close(hat[4], turned(Vec2::new(40.0, -5.0), Vec2::new(0.0, 0.0), -FRAC_PI_2)));
|
||||
assert_eq!(path_of(&both[0]), path_of(&posed[0]), "and the body is as before");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ik_reaches_through_shape_bones_and_instances() {
|
||||
let (arm, els) = rig();
|
||||
// Drag the head's centre: the two bones inside the body and the head's bone turn.
|
||||
let target = Vec2::new(250.0, 250.0);
|
||||
let r = solve(&arm, &els, &Pose::default(), NECK, Vec2::new(0.0, 0.0), target).unwrap();
|
||||
assert_eq!(r.chain, 3);
|
||||
assert!(r.error <= IK_TOLERANCE, "{}", r.error);
|
||||
let mut posed = els.clone();
|
||||
apply(&arm, &mut posed, &r.pose);
|
||||
assert!(posed[1].transform.translation().distance(target) < 0.02);
|
||||
assert_ne!(path_of(&posed[0]), path_of(&els[0]), "the body bent to get there");
|
||||
// The grabbed point of a dragged instance follows the pointer.
|
||||
let grab = grab_point(&arm, &els, &Pose::default(), NECK, Vec2::new(335.0, 104.0)).unwrap();
|
||||
assert!(close(grab, Vec2::new(5.0, 4.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_file_forms() {
|
||||
// An armature of instances, and one of a single shape, are written as they always were.
|
||||
let (mixed, _) = rig();
|
||||
let mut one = mixed.clone();
|
||||
one.bones.truncate(2);
|
||||
one.skins.truncate(1);
|
||||
assert!(!one.is_mixed());
|
||||
let text = serde_json::to_string(&one).unwrap();
|
||||
assert!(text.contains("\"skin\":{") && !text.contains("\"skins\"") && !text.contains("\"shape\":10,\"parent\""), "{text}");
|
||||
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
assert!(v["bones"].as_array().unwrap().iter().all(|b| b.get("shape").is_none()), "the first form doesn't mark its bones");
|
||||
assert_eq!(v.as_object().unwrap().keys().collect::<Vec<_>>(), ["bones", "skin"]);
|
||||
let back: Armature = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(back, one, "read back, every bone is inside the one shape again");
|
||||
let instances = Armature { bones: vec![Bone::new(NECK, BODY, HEAD, Vec2::ZERO, Vec2::ZERO, Affine::IDENTITY)], ..Default::default() };
|
||||
let text = serde_json::to_string(&instances).unwrap();
|
||||
assert!(!text.contains("skin") && !text.contains("shape"), "{text}");
|
||||
assert_eq!(serde_json::from_str::<Armature>(&text).unwrap(), instances);
|
||||
// A mixed one says which shape each bone is inside, and lists its skins.
|
||||
let text = serde_json::to_string(&mixed).unwrap();
|
||||
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(v.as_object().unwrap().keys().collect::<Vec<_>>(), ["bones", "skins"]);
|
||||
assert_eq!(v["skins"].as_array().unwrap().len(), 2);
|
||||
let marks: Vec<Option<u64>> = v["bones"].as_array().unwrap().iter().map(|b| b.get("shape").and_then(|s| s.as_u64())).collect();
|
||||
assert_eq!(marks, vec![Some(10), Some(10), None, None, Some(12)]);
|
||||
assert_eq!(serde_json::from_str::<Armature>(&text).unwrap(), mixed);
|
||||
// A build from before mixed armatures knows `bones` and `skin` only: reading this text it
|
||||
// would see bones and no skin, which is why the envelope's version stops it first.
|
||||
assert!(v.get("skin").is_none());
|
||||
// Springs off is kept in both forms.
|
||||
for mut a in [one, mixed] {
|
||||
a.springs_off = true;
|
||||
assert!(serde_json::from_str::<Armature>(&serde_json::to_string(&a).unwrap()).unwrap().springs_off);
|
||||
}
|
||||
// A file with both fields (hand-made): the old field's skin comes first, and marks only the
|
||||
// bones that say nothing.
|
||||
let both: Armature = serde_json::from_str(r#"{"bones":[{"id":1,"parent":10,"child":30,"head":{"x":0,"y":0},"tail":{"x":9,"y":0},"rest":{"m":[1,0,0,1,0,0]}},{"id":2,"parent":12,"child":31,"head":{"x":0,"y":0},"tail":{"x":9,"y":0},"rest":{"m":[1,0,0,1,0,0]},"shape":12}],"skin":{"shape":10,"rest":"M0 0L9 0"},"skins":[{"shape":12,"rest":"M0 0L9 0"}]}"#).unwrap();
|
||||
assert_eq!(both.bones.iter().map(|b| b.shape.map(|s| s.0)).collect::<Vec<_>>(), vec![Some(10), Some(12)]);
|
||||
assert_eq!(both.skins.iter().map(|k| k.shape.0).collect::<Vec<_>>(), vec![10, 12]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_repairs_hostile_mixed_armatures() {
|
||||
let (mut arm, _) = rig();
|
||||
assert!(!arm.sanitize(), "a sound armature is left alone");
|
||||
// Bones out of order come back parent first, across the kinds.
|
||||
let (mut arm, _) = rig();
|
||||
arm.bones.reverse();
|
||||
assert!(arm.sanitize());
|
||||
assert_eq!(arm.bones.iter().map(|b| b.id).collect::<Vec<_>>(), vec![SPINE1, SPINE2, NECK, BRIM, TIP]);
|
||||
// A bone inside a shape must hang from that shape or a bone inside it: one that starts on
|
||||
// an instance, on another shape's node, or names a shape without a skin goes, with what
|
||||
// hangs from it.
|
||||
let (mut arm, _) = rig();
|
||||
arm.bones.push(Bone::in_shape(BoneId(40), BODY, HEAD, ElementId(50), Vec2::ZERO, Vec2::new(9.0, 0.0)));
|
||||
arm.bones.push(Bone::in_shape(BoneId(41), HAT, N1, ElementId(51), Vec2::ZERO, Vec2::new(9.0, 0.0)));
|
||||
arm.bones.push(Bone::in_shape(BoneId(42), ElementId(77), ElementId(77), ElementId(52), Vec2::ZERO, Vec2::new(9.0, 0.0)));
|
||||
arm.bones.push(Bone::new(BoneId(43), ElementId(51), ElementId(53), Vec2::ZERO, Vec2::ZERO, Affine::IDENTITY));
|
||||
assert!(arm.sanitize());
|
||||
assert_eq!(arm.bones.len(), 5, "{:?}", arm.bones.iter().map(|b| b.id).collect::<Vec<_>>());
|
||||
// A joint node can't be a shape with bones; a second bone into one element goes.
|
||||
let (mut arm, _) = rig();
|
||||
arm.bones.push(Bone::in_shape(BoneId(44), BODY, N2, HAT, Vec2::ZERO, Vec2::new(9.0, 0.0)));
|
||||
arm.bones.push(Bone::new(BoneId(45), BODY, HEAD, Vec2::ZERO, Vec2::ZERO, Affine::IDENTITY));
|
||||
arm.sanitize();
|
||||
assert_eq!(arm.bones.len(), 5);
|
||||
assert_eq!(arm.bone_into(HAT).map(|b| b.id), Some(BRIM));
|
||||
// A skin without bones, a second skin for one shape and one over the point limit go; the
|
||||
// bones of a shape whose skin went go with it.
|
||||
let (mut arm, _) = rig();
|
||||
arm.skins.push(Skin::new(ElementId(60), Arc::new(bar(10.0, 1.0, 5.0))));
|
||||
arm.skins.push(Skin::new(BODY, Arc::new(bar(10.0, 1.0, 5.0))));
|
||||
let mut huge = Path::new();
|
||||
huge.move_to(Vec2::ZERO);
|
||||
for i in 0..=skin::MAX_SKIN_POINTS {
|
||||
huge.line_to(Vec2::new(i as f32, 1.0));
|
||||
}
|
||||
if let Some(k) = arm.skin_mut(HAT) {
|
||||
k.rest = Arc::new(huge);
|
||||
}
|
||||
assert!(arm.sanitize());
|
||||
assert_eq!(arm.skins.iter().map(|k| k.shape).collect::<Vec<_>>(), vec![BODY]);
|
||||
assert_eq!(anchors(&arm.skins[0].rest).len(), 18, "the first skin of a shape wins");
|
||||
assert!(arm.bone(TIP).is_none() && arm.bone(BRIM).is_some(), "the hat is still carried as a whole");
|
||||
// Weights naming bones of another shape are dropped, and the point is bound again.
|
||||
let (mut arm, _) = rig();
|
||||
if let Some(k) = arm.skin_mut(HAT) {
|
||||
k.points[0] = Binding { bones: vec![Influence(SPINE1, 1.0)], manual: false };
|
||||
k.points[1] = Binding { bones: vec![Influence(NECK, 0.5), Influence(TIP, 0.25)], manual: true };
|
||||
}
|
||||
assert!(arm.sanitize());
|
||||
let hat = arm.skin(HAT).unwrap();
|
||||
assert_eq!(hat.points[0].bones, vec![Influence(TIP, 1.0)]);
|
||||
assert_eq!(hat.points[1].bones, vec![Influence(TIP, 1.0)]);
|
||||
assert!(!arm.sanitize(), "sanitizing twice changes nothing");
|
||||
// A cycle through the kinds never loops: nothing of it is placed.
|
||||
let mut arm = Armature { bones: vec![Bone::new(BoneId(1), HEAD, HAT, Vec2::ZERO, Vec2::ZERO, Affine::IDENTITY), Bone::new(BoneId(2), HAT, HEAD, Vec2::ZERO, Vec2::ZERO, Affine::IDENTITY)], ..Default::default() };
|
||||
arm.sanitize();
|
||||
assert!(arm.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_with_fresh_ids_keep_their_skins() {
|
||||
use crate::{Keyframe, Layer, LayerId, LayerKind, Timeline};
|
||||
let (arm, els) = rig();
|
||||
let mut l = Layer::new(LayerId(1), "rig");
|
||||
l.kind = LayerKind::Armature;
|
||||
l.armature = Some(Arc::new(arm));
|
||||
l.keyframes = vec![Arc::new({
|
||||
let mut k = Keyframe::new(0, 5);
|
||||
k.elements = els;
|
||||
k
|
||||
})];
|
||||
let mut next = 1000u64;
|
||||
let copy = crate::library::fresh_ids(&Timeline { layers: vec![Arc::new(l)] }, &mut || {
|
||||
next += 1;
|
||||
next
|
||||
});
|
||||
let l = ©.layers[0];
|
||||
let arm = l.armature.as_ref().unwrap();
|
||||
let ids: Vec<ElementId> = l.keyframes[0].elements.iter().map(|e| e.id).collect();
|
||||
assert!(ids.iter().all(|e| e.0 > 1000));
|
||||
assert_eq!(arm.skins.iter().map(|k| k.shape).collect::<Vec<_>>(), vec![ids[0], ids[2]], "each skin follows its shape's new id");
|
||||
assert_eq!(arm.bone(SPINE1).and_then(|b| b.shape), Some(ids[0]));
|
||||
assert_eq!(arm.bone(TIP).map(|b| (b.shape, b.parent)), Some((Some(ids[2]), ids[2])));
|
||||
let mut fixed = (**arm).clone();
|
||||
assert!(!fixed.sanitize(), "the copy is a sound armature");
|
||||
let mut pose = Pose::default();
|
||||
pose.set(SPINE2, FRAC_PI_2);
|
||||
let mut posed = l.keyframes[0].elements.clone();
|
||||
assert!(apply(arm, &mut posed, &pose));
|
||||
assert_ne!(path_of(&posed[0]), path_of(&l.keyframes[0].elements[0]), "the copy's body still bends");
|
||||
}
|
||||
|
||||
/// A mixed armature's cost: two shapes of 1,000 anchors with 8 bones each, 8 instances on
|
||||
/// bones between and after them (the test profile is optimised; release is faster still).
|
||||
#[test]
|
||||
fn a_big_mixed_armature_is_fast() {
|
||||
let v = Vec2::new;
|
||||
let (a, b) = (Arc::new(bar(1000.0, 10.0, 2.0)), Arc::new(bar(1000.0, 10.0, 2.0)));
|
||||
let (s1, s2) = (ElementId(1), ElementId(2));
|
||||
let mut bones = Vec::new();
|
||||
let mut els = vec![shape(s1, a.clone(), v(0.0, 0.0))];
|
||||
let mut id = 100u64;
|
||||
let mut fresh = || {
|
||||
id += 1;
|
||||
id
|
||||
};
|
||||
// Eight bones inside the first shape.
|
||||
let mut parent = s1;
|
||||
for i in 0..8 {
|
||||
let node = ElementId(fresh());
|
||||
bones.push(Bone::in_shape(BoneId(fresh()), s1, parent, node, v(125.0 * i as f32, 0.0), v(125.0 * (i + 1) as f32, 0.0)));
|
||||
parent = node;
|
||||
}
|
||||
// Four instances in a chain from its end, the second shape on the last, eight bones inside
|
||||
// it, and four more instances from its end.
|
||||
let chain = |parent: &mut ElementId, at: &mut f32, bones: &mut Vec<Bone>, els: &mut Vec<Arc<Element>>, fresh: &mut dyn FnMut() -> u64, first_head: Vec2| {
|
||||
for i in 0..4 {
|
||||
let e = ElementId(fresh());
|
||||
*at += 50.0;
|
||||
els.push(instance(e, v(*at, 0.0)));
|
||||
let (head, rest) = if i == 0 { (first_head, Affine::translate(first_head.x + 50.0, 0.0)) } else { (v(0.0, 0.0), Affine::translate(50.0, 0.0)) };
|
||||
bones.push(Bone::new(BoneId(fresh()), *parent, e, head, v(0.0, 0.0), rest));
|
||||
*parent = e;
|
||||
}
|
||||
};
|
||||
let mut at = 1000.0;
|
||||
chain(&mut parent, &mut at, &mut bones, &mut els, &mut fresh, v(1000.0, 0.0));
|
||||
els.push(shape(s2, b.clone(), v(at + 50.0, 0.0)));
|
||||
bones.push(Bone::new(BoneId(fresh()), parent, s2, v(0.0, 0.0), v(0.0, 0.0), Affine::translate(50.0, 0.0)));
|
||||
parent = s2;
|
||||
for i in 0..8 {
|
||||
let node = ElementId(fresh());
|
||||
bones.push(Bone::in_shape(BoneId(fresh()), s2, parent, node, v(125.0 * i as f32, 0.0), v(125.0 * (i + 1) as f32, 0.0)));
|
||||
parent = node;
|
||||
}
|
||||
at += 1050.0;
|
||||
chain(&mut parent, &mut at, &mut bones, &mut els, &mut fresh, v(1000.0, 0.0));
|
||||
let mut arm = Armature { bones, skins: vec![Skin::new(s1, a), Skin::new(s2, b)], springs_off: false };
|
||||
let t = std::time::Instant::now();
|
||||
rebind(&mut arm);
|
||||
let bind = t.elapsed();
|
||||
let mut check = arm.clone();
|
||||
assert!(!check.sanitize(), "the rig is a sound armature, and repairing it again moves no weight");
|
||||
assert_eq!(arm.bones.len(), 25);
|
||||
let pose = Pose(arm.bones.iter().map(|b| JointAngle::new(b.id, 0.05)).collect());
|
||||
let t = std::time::Instant::now();
|
||||
let n = 200;
|
||||
for _ in 0..n {
|
||||
let mut posed = els.clone();
|
||||
assert!(apply(&arm, &mut posed, &pose));
|
||||
std::hint::black_box(posed);
|
||||
}
|
||||
let per = t.elapsed().as_secs_f64() * 1e3 / f64::from(n);
|
||||
println!("mixed armature, 25 bones, 2 × 1,002 anchors, 8 instances: bind {:.2} ms, pose {per:.3} ms per frame", bind.as_secs_f64() * 1e3);
|
||||
assert!(per < 20.0, "{per} ms");
|
||||
let target = v(1800.0, 900.0);
|
||||
let t = std::time::Instant::now();
|
||||
let last = arm.bones.last().map(|b| b.id).unwrap();
|
||||
let r = solve(&arm, &els, &Pose::default(), last, v(0.0, 0.0), target).unwrap();
|
||||
println!("IK through all 25 bones: {:.2} ms, error {:.4} px", t.elapsed().as_secs_f64() * 1e3, r.error);
|
||||
assert_eq!(r.chain, 25);
|
||||
assert!(r.error <= IK_TOLERANCE, "{}", r.error);
|
||||
}
|
||||
@@ -504,6 +504,7 @@ pub fn hit_frame(len: u32) -> u32 {
|
||||
pub fn hit_area(doc: &Document, tl: &Timeline, xf: Affine) -> DisplayList {
|
||||
let mut dl = evaluate_symbol(doc, tl, hit_frame(tl.frame_count()), xf, None);
|
||||
dl.items.retain(|i| !i.guide && i.masks.is_none());
|
||||
dl.links.clear();
|
||||
for i in &mut dl.items {
|
||||
i.clip = None;
|
||||
}
|
||||
|
||||
@@ -722,7 +722,7 @@ impl ScriptHost for Mono {
|
||||
}
|
||||
|
||||
fn field(id: u64, name: &str, text: &str, kind: TextKind, x: f32, y: f32) -> Arc<Element> {
|
||||
let block = TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: crate::TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0, 8.0)), box_width: 104.0, box_height: 14.0, field: Some(TextField { border: true, ..TextField::new(kind) }), on_path: None };
|
||||
let block = TextBlock { text: text.into(), font: "Mono".into(), size: 10.0, bold: false, italic: false, color: Rgba::BLACK, align: crate::TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0, 8.0)), box_width: 104.0, box_height: 14.0, field: Some(TextField { border: true, ..TextField::new(kind) }), on_path: None, ..Default::default() };
|
||||
Arc::new(Element { id: ElementId(id), name: name.into(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) })
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
//! Styled text (ADR 0085): runs of characters with their own style, paragraphs with their own
|
||||
//! layout, and the outline cut into one filled piece per colour and link.
|
||||
//!
|
||||
//! A [`TextBlock`] with no runs is one run in the block's own style, and with no paragraph
|
||||
//! styles every paragraph has the block's alignment and line spacing: files from before styled
|
||||
//! text open unchanged and save byte for byte the same. When a block has runs, its own style
|
||||
//! fields mirror the first run (and its alignment and line spacing the first paragraph), so code
|
||||
//! that reads "the block's style" sees the style the text starts with.
|
||||
//!
|
||||
//! The run edits here are pure functions on run lists, so typing, deleting, pasting and styling
|
||||
//! a range split and merge runs the same way in the engine, the shell and the tests.
|
||||
|
||||
use crate::{Rgba, TextAlign, TextBlock};
|
||||
use anicraft_geom::Path;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// Most runs one block keeps; past it, the rest of the text takes the last run's style.
|
||||
pub const MAX_TEXT_RUNS: usize = 10_000;
|
||||
|
||||
/// Longest link a run keeps (characters).
|
||||
pub const MAX_URL: usize = 2048;
|
||||
|
||||
/// Where characters sit against the line's baseline.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum BaselineShift {
|
||||
#[default]
|
||||
Normal,
|
||||
/// Smaller and raised (the font's superscript size and offset).
|
||||
Superscript,
|
||||
/// Smaller and lowered (the font's subscript size and offset).
|
||||
Subscript,
|
||||
}
|
||||
|
||||
impl BaselineShift {
|
||||
pub const ALL: [BaselineShift; 3] = [BaselineShift::Normal, BaselineShift::Superscript, BaselineShift::Subscript];
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
BaselineShift::Normal => "normal",
|
||||
BaselineShift::Superscript => "superscript",
|
||||
BaselineShift::Subscript => "subscript",
|
||||
}
|
||||
}
|
||||
pub fn from_key(s: &str) -> Option<BaselineShift> {
|
||||
let s = s.trim().to_ascii_lowercase();
|
||||
BaselineShift::ALL.into_iter().find(|k| k.key() == s)
|
||||
}
|
||||
}
|
||||
|
||||
/// A link a run may keep: trimmed and cut to [`MAX_URL`]; `None` for schemes that run code
|
||||
/// where the link is followed (`javascript:`, `vbscript:`, `data:`), which exports must never
|
||||
/// write.
|
||||
pub fn safe_url(url: &str) -> Option<String> {
|
||||
let url: String = url.trim().chars().filter(|c| !c.is_control()).take(MAX_URL).collect();
|
||||
let scheme: String = url.chars().filter(|c| !c.is_whitespace()).take_while(|c| *c != ':').collect::<String>().to_ascii_lowercase();
|
||||
let has_scheme = url.contains(':') && !scheme.contains(['/', '?', '#']);
|
||||
(!(has_scheme && ["javascript", "vbscript", "data"].contains(&scheme.as_str()))).then_some(url)
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
fn is_zero(v: &f32) -> bool {
|
||||
*v == 0.0
|
||||
}
|
||||
fn is_normal(s: &BaselineShift) -> bool {
|
||||
*s == BaselineShift::Normal
|
||||
}
|
||||
|
||||
/// One character style: what a run of characters is drawn in.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CharStyle {
|
||||
/// Font family the outlines were laid out with.
|
||||
pub font: String,
|
||||
/// Font size in pixels.
|
||||
pub size: f32,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub bold: bool,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub italic: bool,
|
||||
pub color: Rgba,
|
||||
/// Extra space after each character, in pixels.
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub letter_spacing: f32,
|
||||
#[serde(default, skip_serializing_if = "is_normal")]
|
||||
pub shift: BaselineShift,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub underline: bool,
|
||||
/// A link the characters go to (empty: none).
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
impl Default for CharStyle {
|
||||
fn default() -> Self {
|
||||
CharStyle { font: String::new(), size: 32.0, bold: false, italic: false, color: Rgba::BLACK, letter_spacing: 0.0, shift: BaselineShift::Normal, underline: false, url: String::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl CharStyle {
|
||||
/// The style clamped to what layout accepts (sizes 1 to 2000 px, spacing within ±1000 px,
|
||||
/// names and links cut to length).
|
||||
pub fn sanitized(&self) -> CharStyle {
|
||||
let fin = |v: f32, d: f32| if v.is_finite() { v } else { d };
|
||||
CharStyle {
|
||||
font: self.font.chars().take(256).collect(),
|
||||
size: fin(self.size, 32.0).clamp(1.0, 2000.0),
|
||||
letter_spacing: fin(self.letter_spacing, 0.0).clamp(-1000.0, 1000.0),
|
||||
color: Rgba::new(fin(self.color.r, 0.0).clamp(0.0, 1.0), fin(self.color.g, 0.0).clamp(0.0, 1.0), fin(self.color.b, 0.0).clamp(0.0, 1.0), fin(self.color.a, 1.0).clamp(0.0, 1.0)),
|
||||
url: safe_url(&self.url).unwrap_or_default(),
|
||||
..self.clone()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A run: this many characters (`char`s, line breaks included) in one style.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TextRun {
|
||||
pub chars: u32,
|
||||
#[serde(flatten)]
|
||||
pub style: CharStyle,
|
||||
}
|
||||
|
||||
/// One paragraph's layout (a paragraph is a line of the text, up to a line break).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ParagraphStyle {
|
||||
#[serde(default)]
|
||||
pub align: TextAlign,
|
||||
/// The first line starts this much further in (pixels; negative hangs it out).
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub indent: f32,
|
||||
/// Space kept clear at the box's left and right (pixels).
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub left_margin: f32,
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub right_margin: f32,
|
||||
/// Extra space below each of its lines (pixels).
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
pub line_spacing: f32,
|
||||
}
|
||||
|
||||
impl ParagraphStyle {
|
||||
/// Clamped to what layout accepts (indent within ±10000 px, margins 0 to 10000 px, line
|
||||
/// spacing within ±1000 px).
|
||||
pub fn sanitized(&self) -> ParagraphStyle {
|
||||
let fin = |v: f32| if v.is_finite() { v } else { 0.0 };
|
||||
ParagraphStyle {
|
||||
align: self.align,
|
||||
indent: fin(self.indent).clamp(-10_000.0, 10_000.0),
|
||||
left_margin: fin(self.left_margin).clamp(0.0, 10_000.0),
|
||||
right_margin: fin(self.right_margin).clamp(0.0, 10_000.0),
|
||||
line_spacing: fin(self.line_spacing).clamp(-1000.0, 1000.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One filled piece of a block's outline: the next `cmds` path commands, in one colour, with a
|
||||
/// link if its characters have one. A block's fills cut its outline in order.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TextFill {
|
||||
pub color: Rgba,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub url: String,
|
||||
pub cmds: u32,
|
||||
}
|
||||
|
||||
/// The fills' outlines, cut once from the block's outline the first time they are drawn (never
|
||||
/// saved, and empty again in a copy).
|
||||
#[derive(Default)]
|
||||
pub struct FillCache(OnceLock<(usize, Vec<u32>, Vec<Arc<Path>>)>);
|
||||
|
||||
impl Clone for FillCache {
|
||||
fn clone(&self) -> Self {
|
||||
FillCache::default()
|
||||
}
|
||||
}
|
||||
impl PartialEq for FillCache {
|
||||
fn eq(&self, _: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
impl std::fmt::Debug for FillCache {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("FillCache")
|
||||
}
|
||||
}
|
||||
|
||||
impl TextBlock {
|
||||
/// The style the block's own fields hold (its first run's).
|
||||
pub fn char_style(&self) -> CharStyle {
|
||||
CharStyle {
|
||||
font: self.font.clone(),
|
||||
size: self.size,
|
||||
bold: self.bold,
|
||||
italic: self.italic,
|
||||
color: self.color,
|
||||
letter_spacing: self.letter_spacing,
|
||||
shift: self.shift,
|
||||
underline: self.underline,
|
||||
url: self.url.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The paragraph style the block's own fields hold (its first paragraph's).
|
||||
pub fn para_style(&self) -> ParagraphStyle {
|
||||
ParagraphStyle { align: self.align, indent: self.indent, left_margin: self.left_margin, right_margin: self.right_margin, line_spacing: self.line_spacing }
|
||||
}
|
||||
|
||||
/// Its characters.
|
||||
pub fn char_count(&self) -> u32 {
|
||||
self.text.chars().count() as u32
|
||||
}
|
||||
|
||||
/// Its runs, covering every character (one run in the block's style when it has none).
|
||||
pub fn styled_runs(&self) -> Vec<TextRun> {
|
||||
let n = self.char_count();
|
||||
if self.runs.is_empty() {
|
||||
return vec![TextRun { chars: n, style: self.char_style() }];
|
||||
}
|
||||
fit_runs(self.runs.clone(), n)
|
||||
}
|
||||
|
||||
/// One style per paragraph (the block's when it has none; a missing one takes the last).
|
||||
pub fn paragraph_styles(&self) -> Vec<ParagraphStyle> {
|
||||
let n = paragraph_count(&self.text);
|
||||
let own = self.para_style();
|
||||
(0..n).map(|i| self.paragraphs.get(i).or(self.paragraphs.last()).copied().unwrap_or(own)).collect()
|
||||
}
|
||||
|
||||
/// Whether characters differ in style (more than one run).
|
||||
pub fn has_runs(&self) -> bool {
|
||||
self.runs.len() > 1
|
||||
}
|
||||
|
||||
/// Sets the runs and paragraph styles (fitted to the text, merged, capped and sanitized),
|
||||
/// and the block's own style fields to the first of each. A block whose characters all share
|
||||
/// one style, and paragraphs one layout, keeps none, as text always was.
|
||||
pub fn set_styles(&mut self, runs: Vec<TextRun>, paragraphs: Vec<ParagraphStyle>) {
|
||||
let n = self.char_count();
|
||||
let runs = normalize_runs(runs.into_iter().map(|r| TextRun { chars: r.chars, style: r.style.sanitized() }).collect(), n);
|
||||
let first = runs.first().map_or_else(|| self.char_style(), |r| r.style.clone());
|
||||
self.font = first.font.clone();
|
||||
self.size = first.size;
|
||||
self.bold = first.bold;
|
||||
self.italic = first.italic;
|
||||
self.color = first.color;
|
||||
self.letter_spacing = first.letter_spacing;
|
||||
self.shift = first.shift;
|
||||
self.underline = first.underline;
|
||||
self.url = first.url.clone();
|
||||
self.runs = if runs.len() > 1 { runs } else { Vec::new() };
|
||||
let count = paragraph_count(&self.text);
|
||||
let mut paras: Vec<ParagraphStyle> = paragraphs.iter().take(count).map(ParagraphStyle::sanitized).collect();
|
||||
let fill = paras.last().copied().unwrap_or_else(|| self.para_style());
|
||||
paras.resize(count, fill);
|
||||
if let Some(p) = paras.first() {
|
||||
self.align = p.align;
|
||||
self.indent = p.indent;
|
||||
self.left_margin = p.left_margin;
|
||||
self.right_margin = p.right_margin;
|
||||
self.line_spacing = p.line_spacing;
|
||||
}
|
||||
self.paragraphs = if paras.windows(2).all(|w| matches!(w, [a, b] if a == b)) { Vec::new() } else { paras };
|
||||
}
|
||||
|
||||
/// Each fill's outline with its colour and link: the block's outline cut by its fills, or
|
||||
/// the whole outline in the block's colour when it has none.
|
||||
pub fn fill_paths(&self) -> Vec<(Rgba, &str, Arc<Path>)> {
|
||||
if self.fills.is_empty() {
|
||||
return vec![(self.color, self.url.as_str(), self.outline.clone())];
|
||||
}
|
||||
let key = Arc::as_ptr(&self.outline) as usize;
|
||||
let counts: Vec<u32> = self.fills.iter().map(|f| f.cmds).collect();
|
||||
let cut = || split_outline(&self.outline, &counts);
|
||||
let paths = match self.fill_cache.0.get() {
|
||||
Some((k, c, p)) if *k == key && *c == counts => p.clone(),
|
||||
Some(_) => cut(),
|
||||
None => self.fill_cache.0.get_or_init(|| (key, counts.clone(), cut())).2.clone(),
|
||||
};
|
||||
self.fills.iter().zip(paths).map(|(f, p)| (f.color, f.url.as_str(), p)).collect()
|
||||
}
|
||||
|
||||
/// Sets the outline from pieces in their colours and links (one after another), keeping
|
||||
/// no fills when there is one piece in the block's colour without a link.
|
||||
pub fn set_outline(&mut self, pieces: Vec<(Rgba, String, Path)>) {
|
||||
let single = matches!(pieces.as_slice(), [(c, u, _)] if *c == self.color && u.is_empty()) || pieces.is_empty();
|
||||
let mut outline = Path::new();
|
||||
let mut fills = Vec::with_capacity(pieces.len());
|
||||
for (color, url, p) in pieces {
|
||||
fills.push(TextFill { color, url, cmds: p.cmds.len() as u32 });
|
||||
outline.cmds.extend(p.cmds);
|
||||
}
|
||||
self.outline = Arc::new(outline);
|
||||
self.fills = if single { Vec::new() } else { fills };
|
||||
self.fill_cache = FillCache::default();
|
||||
}
|
||||
}
|
||||
|
||||
/// `outline` cut into pieces of `counts` commands (the last takes what is left; extra counts
|
||||
/// past the end are empty).
|
||||
fn split_outline(outline: &Path, counts: &[u32]) -> Vec<Arc<Path>> {
|
||||
let mut at = 0usize;
|
||||
let n = counts.len();
|
||||
counts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| {
|
||||
let end = if i + 1 == n { outline.cmds.len() } else { at.saturating_add(*c as usize).min(outline.cmds.len()) };
|
||||
let p = Path { cmds: outline.cmds.get(at..end).map(<[_]>::to_vec).unwrap_or_default() };
|
||||
at = end;
|
||||
Arc::new(p)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The paragraphs in `text` (one more than its line breaks).
|
||||
pub fn paragraph_count(text: &str) -> usize {
|
||||
text.bytes().filter(|b| *b == b'\n').count() + 1
|
||||
}
|
||||
|
||||
/// Runs fitted to `n` characters: the last runs cut or the last one lengthened.
|
||||
fn fit_runs(mut runs: Vec<TextRun>, n: u32) -> Vec<TextRun> {
|
||||
let mut at = 0u32;
|
||||
let mut keep = 0;
|
||||
for r in &mut runs {
|
||||
if at >= n && keep > 0 {
|
||||
break;
|
||||
}
|
||||
r.chars = r.chars.min(n - at);
|
||||
at += r.chars;
|
||||
keep += 1;
|
||||
}
|
||||
runs.truncate(keep.max(1));
|
||||
if let Some(last) = runs.last_mut() {
|
||||
last.chars += n - at.min(n);
|
||||
}
|
||||
runs
|
||||
}
|
||||
|
||||
/// Runs fitted to `n` characters, empty ones dropped, neighbours in one style joined, at most
|
||||
/// [`MAX_TEXT_RUNS`] (the rest of the text takes the last kept run's style). Always at least one.
|
||||
pub fn normalize_runs(runs: Vec<TextRun>, n: u32) -> Vec<TextRun> {
|
||||
let fallback = runs.first().map(|r| r.style.clone()).unwrap_or_default();
|
||||
let mut out: Vec<TextRun> = Vec::with_capacity(runs.len().min(MAX_TEXT_RUNS));
|
||||
for r in fit_runs(runs, n) {
|
||||
if r.chars == 0 {
|
||||
continue;
|
||||
}
|
||||
let full = out.len() >= MAX_TEXT_RUNS;
|
||||
match out.last_mut() {
|
||||
Some(last) if last.style == r.style || full => last.chars += r.chars,
|
||||
_ => out.push(r),
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
out.push(TextRun { chars: n, style: fallback });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The style typing at character boundary `at` continues: the character before it, or the
|
||||
/// first character's at the start.
|
||||
pub fn style_at(runs: &[TextRun], at: u32) -> CharStyle {
|
||||
let mut end = 0u32;
|
||||
for r in runs {
|
||||
end = end.saturating_add(r.chars);
|
||||
if at <= end && (at > end - r.chars || at == 0) {
|
||||
return r.style.clone();
|
||||
}
|
||||
}
|
||||
runs.last().map(|r| r.style.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The runs of characters `start..end`.
|
||||
pub fn slice_runs(runs: &[TextRun], start: u32, end: u32) -> Vec<TextRun> {
|
||||
let mut out = Vec::new();
|
||||
let mut at = 0u32;
|
||||
for r in runs {
|
||||
let (a, b) = (at.max(start), at.saturating_add(r.chars).min(end));
|
||||
if a < b {
|
||||
out.push(TextRun { chars: b - a, style: r.style.clone() });
|
||||
}
|
||||
at = at.saturating_add(r.chars);
|
||||
if at >= end {
|
||||
break;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Characters `start..end` replaced by `inserted` (runs of the new characters): the runs on
|
||||
/// either side are cut, the new ones go between, neighbours in one style join.
|
||||
pub fn replace_runs(runs: &[TextRun], start: u32, end: u32, inserted: Vec<TextRun>) -> Vec<TextRun> {
|
||||
let total: u32 = runs.iter().map(|r| r.chars).fold(0, u32::saturating_add);
|
||||
let (start, end) = (start.min(total), end.clamp(start.min(total), total));
|
||||
let mut out = slice_runs(runs, 0, start);
|
||||
out.extend(inserted);
|
||||
out.extend(slice_runs(runs, end, total));
|
||||
let n = out.iter().map(|r| r.chars).fold(0, u32::saturating_add);
|
||||
let style = runs.first().map(|r| r.style.clone()).unwrap_or_default();
|
||||
if out.is_empty() {
|
||||
return vec![TextRun { chars: 0, style }];
|
||||
}
|
||||
normalize_runs(out, n)
|
||||
}
|
||||
|
||||
/// Characters `start..end` replaced by `inserted` characters that continue the style before
|
||||
/// `start` (typing).
|
||||
pub fn type_into_runs(runs: &[TextRun], start: u32, end: u32, inserted: u32) -> Vec<TextRun> {
|
||||
let style = style_at(runs, start);
|
||||
replace_runs(runs, start, end, vec![TextRun { chars: inserted, style }])
|
||||
}
|
||||
|
||||
/// Characters `start..end` restyled by `f`, the runs split at both ends and joined again.
|
||||
pub fn restyle_runs(runs: &[TextRun], start: u32, end: u32, f: impl Fn(&mut CharStyle)) -> Vec<TextRun> {
|
||||
let total: u32 = runs.iter().map(|r| r.chars).fold(0, u32::saturating_add);
|
||||
let (start, end) = (start.min(total), end.clamp(start.min(total), total));
|
||||
let mut mid = slice_runs(runs, start, end);
|
||||
for r in &mut mid {
|
||||
f(&mut r.style);
|
||||
}
|
||||
replace_runs(runs, start, end, mid)
|
||||
}
|
||||
|
||||
/// Paragraph styles after characters `start..end` of `old` are replaced by `inserted`: a
|
||||
/// paragraph a line break splits gives both halves its style; paragraphs joined keep the
|
||||
/// first's.
|
||||
pub fn edit_paragraphs(paras: &[ParagraphStyle], old: &str, start: u32, end: u32, inserted: &str) -> Vec<ParagraphStyle> {
|
||||
let count = paragraph_count(old);
|
||||
let fill = paras.last().copied().unwrap_or_default();
|
||||
let full: Vec<ParagraphStyle> = (0..count).map(|i| paras.get(i).copied().unwrap_or(fill)).collect();
|
||||
let before = old.chars().take(start as usize).filter(|c| *c == '\n').count();
|
||||
let removed = old.chars().skip(start as usize).take(end.saturating_sub(start) as usize).filter(|c| *c == '\n').count();
|
||||
let added = inserted.chars().filter(|c| *c == '\n').count();
|
||||
let here = full.get(before).copied().unwrap_or(fill);
|
||||
let mut out: Vec<ParagraphStyle> = full.iter().take(before + 1).copied().collect();
|
||||
out.extend(std::iter::repeat_n(here, added));
|
||||
out.extend(full.iter().skip(before + 1 + removed).copied());
|
||||
out
|
||||
}
|
||||
|
||||
/// The one edit that turns `old` into `new`: the characters `start..old_end` of `old` became
|
||||
/// `start..new_end` of `new` (the longest common start and end kept).
|
||||
pub fn diff_chars(old: &str, new: &str) -> (u32, u32, u32) {
|
||||
let (a, b): (Vec<char>, Vec<char>) = (old.chars().collect(), new.chars().collect());
|
||||
let prefix = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
|
||||
let room = a.len().min(b.len()) - prefix;
|
||||
let suffix = a.iter().rev().zip(b.iter().rev()).take(room).take_while(|(x, y)| x == y).count();
|
||||
(prefix as u32, (a.len() - suffix) as u32, (b.len() - suffix) as u32)
|
||||
}
|
||||
|
||||
/// What characters `start..end` share, attribute by attribute (`None`: mixed). An empty range
|
||||
/// is the style typing there would use.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StyleSummary {
|
||||
pub font: Option<String>,
|
||||
pub size: Option<f32>,
|
||||
pub bold: Option<bool>,
|
||||
pub italic: Option<bool>,
|
||||
pub color: Option<Rgba>,
|
||||
pub letter_spacing: Option<f32>,
|
||||
pub shift: Option<BaselineShift>,
|
||||
pub underline: Option<bool>,
|
||||
pub url: Option<String>,
|
||||
}
|
||||
|
||||
impl StyleSummary {
|
||||
/// The summary of one style (nothing mixed).
|
||||
pub fn of(s: &CharStyle) -> StyleSummary {
|
||||
StyleSummary {
|
||||
font: Some(s.font.clone()),
|
||||
size: Some(s.size),
|
||||
bold: Some(s.bold),
|
||||
italic: Some(s.italic),
|
||||
color: Some(s.color),
|
||||
letter_spacing: Some(s.letter_spacing),
|
||||
shift: Some(s.shift),
|
||||
underline: Some(s.underline),
|
||||
url: Some(s.url.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What characters `start..end` of `runs` share ([`StyleSummary`]).
|
||||
pub fn summarize(runs: &[TextRun], start: u32, end: u32) -> StyleSummary {
|
||||
if start >= end {
|
||||
return StyleSummary::of(&style_at(runs, start));
|
||||
}
|
||||
let part = slice_runs(runs, start, end);
|
||||
let Some(first) = part.first() else { return StyleSummary::of(&style_at(runs, start)) };
|
||||
let mut s = StyleSummary::of(&first.style);
|
||||
for r in part.iter().skip(1) {
|
||||
let st = &r.style;
|
||||
fn keep<T: PartialEq>(v: &mut Option<T>, x: &T) {
|
||||
if v.as_ref().is_some_and(|v| v != x) {
|
||||
*v = None;
|
||||
}
|
||||
}
|
||||
keep(&mut s.font, &st.font);
|
||||
keep(&mut s.size, &st.size);
|
||||
keep(&mut s.bold, &st.bold);
|
||||
keep(&mut s.italic, &st.italic);
|
||||
keep(&mut s.color, &st.color);
|
||||
keep(&mut s.letter_spacing, &st.letter_spacing);
|
||||
keep(&mut s.shift, &st.shift);
|
||||
keep(&mut s.underline, &st.underline);
|
||||
keep(&mut s.url, &st.url);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The paragraphs characters `start..end` of `text` touch (indices, first to last).
|
||||
pub fn paragraphs_in(text: &str, start: u32, end: u32) -> std::ops::RangeInclusive<usize> {
|
||||
let first = text.chars().take(start as usize).filter(|c| *c == '\n').count();
|
||||
let last = text.chars().take(end.max(start) as usize).filter(|c| *c == '\n').count();
|
||||
first..=last
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rich_text_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,154 @@
|
||||
use super::*;
|
||||
use crate::{Rgba, TextAlign, TextBlock};
|
||||
|
||||
fn st(size: f32) -> CharStyle {
|
||||
CharStyle { size, ..CharStyle::default() }
|
||||
}
|
||||
fn run(chars: u32, size: f32) -> TextRun {
|
||||
TextRun { chars, style: st(size) }
|
||||
}
|
||||
fn sizes(runs: &[TextRun]) -> Vec<(u32, f32)> {
|
||||
runs.iter().map(|r| (r.chars, r.style.size)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_continues_the_style_before_the_caret() {
|
||||
let runs = vec![run(3, 10.0), run(3, 20.0)];
|
||||
// Inside a run, at its end, and at the very start (the first character's style).
|
||||
assert_eq!(sizes(&type_into_runs(&runs, 1, 1, 2)), vec![(5, 10.0), (3, 20.0)]);
|
||||
assert_eq!(sizes(&type_into_runs(&runs, 3, 3, 1)), vec![(4, 10.0), (3, 20.0)], "after the last small character: small");
|
||||
assert_eq!(sizes(&type_into_runs(&runs, 0, 0, 1)), vec![(4, 10.0), (3, 20.0)]);
|
||||
assert_eq!(sizes(&type_into_runs(&runs, 6, 6, 1)), vec![(3, 10.0), (4, 20.0)]);
|
||||
// Typing over a selection that crosses runs takes the style before it.
|
||||
assert_eq!(sizes(&type_into_runs(&runs, 2, 5, 1)), vec![(3, 10.0), (1, 20.0)]);
|
||||
// Deleting a whole run joins its neighbours when they match.
|
||||
let three = vec![run(2, 10.0), run(2, 20.0), run(2, 10.0)];
|
||||
assert_eq!(sizes(&replace_runs(&three, 2, 4, Vec::new())), vec![(4, 10.0)]);
|
||||
// Deleting everything leaves one empty run in the first style.
|
||||
assert_eq!(sizes(&replace_runs(&three, 0, 6, Vec::new())), vec![(0, 10.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styling_a_range_splits_and_merges_runs() {
|
||||
let runs = vec![run(10, 10.0)];
|
||||
let big = restyle_runs(&runs, 2, 5, |s| s.size = 30.0);
|
||||
assert_eq!(sizes(&big), vec![(2, 10.0), (3, 30.0), (5, 10.0)]);
|
||||
// Restyling it back joins the runs again.
|
||||
assert_eq!(sizes(&restyle_runs(&big, 2, 5, |s| s.size = 10.0)), vec![(10, 10.0)]);
|
||||
// A range across runs; an attribute set on a part keeps the others.
|
||||
let both = restyle_runs(&big, 4, 7, |s| s.bold = true);
|
||||
assert_eq!(both.iter().map(|r| (r.chars, r.style.size, r.style.bold)).collect::<Vec<_>>(), vec![(2, 10.0, false), (2, 30.0, false), (1, 30.0, true), (2, 10.0, true), (3, 10.0, false)]);
|
||||
// Out-of-range and backwards ranges are clamped, never a panic.
|
||||
assert_eq!(sizes(&restyle_runs(&runs, 8, 99, |s| s.size = 1.0)), vec![(8, 10.0), (2, 1.0)]);
|
||||
assert_eq!(sizes(&restyle_runs(&runs, 7, 3, |s| s.size = 1.0)), vec![(10, 10.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_reports_what_it_shares_and_what_is_mixed() {
|
||||
let mut runs = vec![run(3, 10.0), run(3, 10.0)];
|
||||
runs[1].style.bold = true;
|
||||
runs[1].style.color = Rgba::hex(0xff0000);
|
||||
let s = summarize(&runs, 1, 5);
|
||||
assert_eq!((s.size, s.bold, s.color, s.font.as_deref()), (Some(10.0), None, None, Some("")));
|
||||
let caret = summarize(&runs, 4, 4);
|
||||
assert_eq!(caret.bold, Some(true), "a caret shows the style typing there would use");
|
||||
assert_eq!(summarize(&runs, 0, 3).bold, Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_breaks_split_and_join_paragraph_styles() {
|
||||
let c = ParagraphStyle { align: TextAlign::Center, ..ParagraphStyle::default() };
|
||||
let r = ParagraphStyle { align: TextAlign::Right, indent: 4.0, ..ParagraphStyle::default() };
|
||||
let paras = vec![c, r];
|
||||
// A line break in the first paragraph: both halves centred.
|
||||
assert_eq!(edit_paragraphs(¶s, "ab\ncd", 1, 1, "\n"), vec![c, c, r]);
|
||||
// Joining the two keeps the first's style.
|
||||
assert_eq!(edit_paragraphs(¶s, "ab\ncd", 2, 3, ""), vec![c]);
|
||||
// Pasting two lines into the second.
|
||||
assert_eq!(edit_paragraphs(¶s, "ab\ncd", 4, 4, "x\ny\nz"), vec![c, r, r, r]);
|
||||
assert_eq!(paragraphs_in("ab\ncd\nef", 1, 4), 0..=1);
|
||||
assert_eq!(paragraphs_in("ab\ncd\nef", 7, 7), 2..=2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_edit_turns_old_text_into_new() {
|
||||
assert_eq!(diff_chars("hello", "help me"), (3, 5, 7));
|
||||
assert_eq!(diff_chars("abc", "abc"), (3, 3, 3));
|
||||
assert_eq!(diff_chars("aaa", "aa"), (2, 3, 2), "the common end never overlaps the common start");
|
||||
assert_eq!(diff_chars("", "é!"), (0, 0, 2));
|
||||
assert_eq!(diff_chars("xÿz", "xz"), (1, 2, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_keeps_runs_only_when_characters_differ() {
|
||||
let mut b = TextBlock { text: "Hello".into(), size: 20.0, ..TextBlock::default() };
|
||||
b.set_styles(vec![TextRun { chars: 5, style: CharStyle { size: 20.0, ..CharStyle::default() } }], vec![ParagraphStyle::default()]);
|
||||
assert!(b.runs.is_empty() && b.paragraphs.is_empty(), "one style: no runs");
|
||||
let red = CharStyle { color: Rgba::hex(0xff0000), shift: BaselineShift::Superscript, ..b.char_style() };
|
||||
b.set_styles(vec![TextRun { chars: 2, style: red.clone() }, TextRun { chars: 3, style: b.char_style() }], Vec::new());
|
||||
assert_eq!(b.runs.len(), 2);
|
||||
assert_eq!((b.color, b.shift), (red.color, BaselineShift::Superscript), "the block's fields are its first run's");
|
||||
assert_eq!(b.styled_runs().iter().map(|r| r.chars).sum::<u32>(), 5);
|
||||
// Too many runs are capped; lengths past the text are cut.
|
||||
let many: Vec<TextRun> = (0..MAX_TEXT_RUNS as u32 + 50).map(|i| TextRun { chars: 1, style: CharStyle { size: 10.0 + (i % 2) as f32, ..CharStyle::default() } }).collect();
|
||||
let mut long = TextBlock { text: "x".repeat(MAX_TEXT_RUNS + 50), ..TextBlock::default() };
|
||||
long.set_styles(many, Vec::new());
|
||||
assert_eq!(long.runs.len(), MAX_TEXT_RUNS);
|
||||
assert_eq!(long.runs.iter().map(|r| r.chars as usize).sum::<usize>(), MAX_TEXT_RUNS + 50);
|
||||
// Hostile styles are clamped.
|
||||
let mut h = TextBlock { text: "ab".into(), ..TextBlock::default() };
|
||||
h.set_styles(vec![TextRun { chars: u32::MAX, style: CharStyle { size: f32::NAN, letter_spacing: 1e9, url: "u".repeat(5000), ..CharStyle::default() } }], vec![ParagraphStyle { indent: f32::INFINITY, left_margin: -3.0, ..ParagraphStyle::default() }; 9]);
|
||||
assert_eq!((h.size, h.letter_spacing, h.url.len(), h.indent, h.left_margin), (32.0, 1000.0, MAX_URL, 0.0, 0.0));
|
||||
assert!(h.paragraphs.is_empty(), "one paragraph");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_cut_the_outline_by_colour() {
|
||||
let mut b = TextBlock { text: "ab".into(), ..TextBlock::default() };
|
||||
let red = Rgba::hex(0xff0000);
|
||||
b.set_outline(vec![(Rgba::BLACK, String::new(), Path::rect(0.0, 0.0, 1.0, 1.0)), (red, "https://example.org".into(), Path::rect(2.0, 0.0, 1.0, 1.0))]);
|
||||
assert_eq!(b.fills.len(), 2);
|
||||
assert_eq!(b.outline.cmds.len(), 10);
|
||||
let parts = b.fill_paths();
|
||||
assert_eq!(parts.len(), 2);
|
||||
assert_eq!((parts[1].0, parts[1].1), (red, "https://example.org"));
|
||||
assert_eq!(*parts[1].2, Path::rect(2.0, 0.0, 1.0, 1.0));
|
||||
// Cut once: drawing again shares the pieces.
|
||||
assert!(Arc::ptr_eq(&b.fill_paths()[0].2, &parts[0].2));
|
||||
// One piece in the block's colour keeps no fills.
|
||||
b.set_outline(vec![(Rgba::BLACK, String::new(), Path::rect(0.0, 0.0, 1.0, 1.0))]);
|
||||
assert!(b.fills.is_empty());
|
||||
assert_eq!(b.fill_paths().len(), 1);
|
||||
// Counts that don't add up never panic: the last fill takes the rest.
|
||||
let odd = TextBlock { fills: vec![TextFill { color: red, url: String::new(), cmds: 99 }, TextFill { color: red, url: String::new(), cmds: 0 }], outline: Arc::new(Path::rect(0.0, 0.0, 1.0, 1.0)), ..TextBlock::default() };
|
||||
assert_eq!(odd.fill_paths().iter().map(|p| p.2.cmds.len()).collect::<Vec<_>>(), vec![5, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_text_saves_byte_for_byte_and_runs_round_trip() {
|
||||
// A block as files before styled text wrote it: nothing new is written.
|
||||
let old = r#"{"text":"Hi","font":"Inter","size":20.0,"bold":false,"italic":false,"color":{"r":0.0,"g":0.0,"b":0.0,"a":1.0},"align":"left","letter_spacing":0.0,"line_spacing":0.0,"width":null,"outline":"","box_width":10.0,"box_height":12.0}"#;
|
||||
let b: TextBlock = serde_json::from_str(old).unwrap();
|
||||
assert!(b.runs.is_empty() && b.paragraphs.is_empty() && b.fills.is_empty());
|
||||
assert_eq!(serde_json::to_string(&b).unwrap(), old);
|
||||
// Runs, paragraphs and fills come back as they were.
|
||||
let mut rich = b.clone();
|
||||
rich.set_styles(vec![TextRun { chars: 1, style: CharStyle { underline: true, url: "a".into(), ..b.char_style() } }, TextRun { chars: 1, style: b.char_style() }], Vec::new());
|
||||
rich.text = "H\ni".into();
|
||||
rich.set_styles(rich.runs.clone(), vec![ParagraphStyle::default(), ParagraphStyle { align: TextAlign::Right, right_margin: 3.0, ..ParagraphStyle::default() }]);
|
||||
let json = serde_json::to_string(&rich).unwrap();
|
||||
let back: TextBlock = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, rich);
|
||||
assert!(json.contains("\"runs\"") && json.contains("\"paragraphs\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_that_run_code_are_dropped() {
|
||||
assert_eq!(safe_url(" https://example.org/a "), Some("https://example.org/a".into()));
|
||||
assert_eq!(safe_url("mailto:me@example.org"), Some("mailto:me@example.org".into()));
|
||||
assert_eq!(safe_url("page.html#top"), Some("page.html#top".into()));
|
||||
assert_eq!(safe_url("JavaScript:alert(1)"), None);
|
||||
assert_eq!(safe_url(" java script:alert(1)"), None, "control characters don't hide a scheme");
|
||||
assert_eq!(safe_url("data:text/html,x"), None);
|
||||
assert_eq!(safe_url("/a:b"), Some("/a:b".into()), "a colon in a path is no scheme");
|
||||
}
|
||||
+75
-73
@@ -1,8 +1,10 @@
|
||||
//! Shape armatures (ADR 0071): bones drawn inside one shape, whose outline bends with them.
|
||||
//!
|
||||
//! A shape armature is an [`Armature`] with a [`Skin`]. Its bones join *joint nodes* instead of
|
||||
//! symbol instances: the root bones start on the shape itself (its element id) and every other
|
||||
//! bone starts on the node of the bone it hangs from. A node is a frame that the bone into it
|
||||
//! A shape with bones has a [`Skin`] on its [`Armature`] (one per shape: an armature may hold
|
||||
//! several, next to bones that move instances, ADR 0098). The bones inside a shape
|
||||
//! ([`crate::armature::Bone::shape`]) join *joint nodes* instead of elements: the first bones
|
||||
//! start on the shape itself (its element id) and every other bone starts on the node of the
|
||||
//! bone it hangs from. A node is a frame that the bone into it
|
||||
//! turns; at rest every node's frame is the shape's own local space, so a bone's head and tail
|
||||
//! are points of the shape as it was drawn, and a node's transform under a pose is the bone's
|
||||
//! **skinning matrix**. Forward and inverse kinematics are ADR 0043's ([`crate::armature::place`],
|
||||
@@ -73,8 +75,12 @@ impl Binding {
|
||||
self.bones.truncate(MAX_INFLUENCES);
|
||||
let sum: f32 = self.bones.iter().map(|i| i.1).sum();
|
||||
if sum > 0.0 && sum.is_finite() {
|
||||
for i in &mut self.bones {
|
||||
i.1 /= sum;
|
||||
// Weights that already sum to 1 (to rounding) are left as they are: normalising a
|
||||
// loaded binding again must not move its numbers, or a file would change on re-save.
|
||||
if (sum - 1.0).abs() > 1e-6 {
|
||||
for i in &mut self.bones {
|
||||
i.1 /= sum;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.bones.clear();
|
||||
@@ -114,16 +120,14 @@ pub fn anchors(path: &Path) -> Vec<Vec2> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where every bone of a shape armature lies as drawn, in the shape's space: its joint and end.
|
||||
pub fn rest_segments(arm: &Armature) -> Vec<(BoneId, Vec2, Vec2)> {
|
||||
/// Where every bone inside `shape` lies as drawn, in the shape's space: its joint and end.
|
||||
pub fn rest_segments(arm: &Armature, shape: ElementId) -> Vec<(BoneId, Vec2, Vec2)> {
|
||||
// Every node's rest frame is the shape's space (`rest` is the identity for shape bones), so
|
||||
// composing the rests places each bone; a hand-edited file with other rests still works.
|
||||
let mut node: HashMap<ElementId, Affine> = HashMap::new();
|
||||
let root = arm.skin.as_ref().map(|s| s.shape);
|
||||
arm.bones
|
||||
.iter()
|
||||
arm.bones_in(shape)
|
||||
.filter_map(|b| {
|
||||
let wp = if Some(b.parent) == root { Affine::IDENTITY } else { *node.get(&b.parent)? };
|
||||
let wp = if b.parent == shape { Affine::IDENTITY } else { *node.get(&b.parent)? };
|
||||
let wc = wp.mul(&b.rest);
|
||||
node.insert(b.child, wc);
|
||||
Some((b.id, wp.apply(b.head), wc.apply(b.tail)))
|
||||
@@ -164,33 +168,35 @@ pub fn auto_binding(segments: &[(BoneId, Vec2, Vec2)], p: Vec2) -> Binding {
|
||||
|
||||
/// Binds every anchor not bound by hand afresh (after the bones changed), and repairs the hand
|
||||
/// bound ones: bones that went away leave them, and one left with none goes back to automatic
|
||||
/// (an anchor unbound by hand on purpose stays unbound). Keeps one binding per anchor.
|
||||
/// (an anchor unbound by hand on purpose stays unbound). Keeps one binding per anchor. Every
|
||||
/// skin of the armature, each against the bones inside its own shape.
|
||||
pub fn rebind(arm: &mut Armature) {
|
||||
let segments = rest_segments(arm);
|
||||
let ids: Vec<BoneId> = arm.bones.iter().map(|b| b.id).collect();
|
||||
let Some(skin) = arm.skin.as_mut() else { return };
|
||||
let pts = anchors(&skin.rest);
|
||||
skin.points.resize(pts.len(), Binding::default());
|
||||
for (b, &p) in skin.points.iter_mut().zip(&pts) {
|
||||
if b.manual {
|
||||
let had = !b.bones.is_empty();
|
||||
b.normalize(|id| ids.contains(&id));
|
||||
if !had || !b.bones.is_empty() {
|
||||
continue;
|
||||
for i in 0..arm.skins.len() {
|
||||
let Some(shape) = arm.skins.get(i).map(|k| k.shape) else { continue };
|
||||
let segments = rest_segments(arm, shape);
|
||||
let Some(skin) = arm.skins.get_mut(i) else { continue };
|
||||
let pts = anchors(&skin.rest);
|
||||
skin.points.resize(pts.len(), Binding::default());
|
||||
for (b, &p) in skin.points.iter_mut().zip(&pts) {
|
||||
if b.manual {
|
||||
let had = !b.bones.is_empty();
|
||||
b.normalize(|id| segments.iter().any(|s| s.0 == id));
|
||||
if !had || !b.bones.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
*b = auto_binding(&segments, p);
|
||||
}
|
||||
*b = auto_binding(&segments, p);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every bone's skinning matrix under `pose`: how the pose moves the shape's space near it (the
|
||||
/// identity at rest, exactly).
|
||||
pub fn matrices(arm: &Armature, pose: &Pose) -> HashMap<BoneId, Affine> {
|
||||
let Some(skin) = &arm.skin else { return HashMap::new() };
|
||||
/// The skinning matrix under `pose` of every bone inside `skin`'s shape: how the pose moves the
|
||||
/// shape's space near it (the identity at rest, exactly).
|
||||
pub fn matrices(arm: &Armature, skin: &Skin, pose: &Pose) -> HashMap<BoneId, Affine> {
|
||||
let mut node: HashMap<ElementId, Affine> = HashMap::new();
|
||||
node.insert(skin.shape, Affine::IDENTITY);
|
||||
let mut out = HashMap::with_capacity(arm.bones.len());
|
||||
for b in &arm.bones {
|
||||
let mut out = HashMap::new();
|
||||
for b in arm.bones_in(skin.shape) {
|
||||
let Some(wp) = node.get(&b.parent).copied() else { continue };
|
||||
let (a, s) = (b.allow(pose.angle(b.id)), b.allow_slide(pose.slide(b.id)));
|
||||
let wc = if a == 0.0 && s == anicraft_geom::Vec2::ZERO { wp.mul(&b.rest) } else { crate::armature::joint(b, &wp, a, s).1 };
|
||||
@@ -237,15 +243,14 @@ fn mix(a: Option<Affine>, b: Option<Affine>) -> Option<Affine> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline `pose` bends the skin's shape into (the shape's space): linear blend skinning of
|
||||
/// The outline `pose` bends `skin`'s shape into (the shape's space): linear blend skinning of
|
||||
/// every anchor, each cubic handle moving with the anchor it leaves or enters and a quadratic's
|
||||
/// control with the mean of its two ends. At rest (or where no bound bone turned) points are
|
||||
/// exactly as drawn.
|
||||
pub fn deform(arm: &Armature, pose: &Pose) -> Option<Arc<Path>> {
|
||||
let skin = arm.skin.as_ref()?;
|
||||
let m = matrices(arm, pose);
|
||||
pub fn deform(arm: &Armature, skin: &Skin, pose: &Pose) -> Arc<Path> {
|
||||
let m = matrices(arm, skin, pose);
|
||||
if m.values().all(|x| *x == Affine::IDENTITY) {
|
||||
return Some(skin.rest.clone());
|
||||
return skin.rest.clone();
|
||||
}
|
||||
let none = Binding::default();
|
||||
let mut idx = 0usize;
|
||||
@@ -271,29 +276,31 @@ pub fn deform(arm: &Armature, pose: &Pose) -> Option<Arc<Path>> {
|
||||
});
|
||||
prev = next;
|
||||
}
|
||||
Some(Arc::new(Path { cmds }))
|
||||
Arc::new(Path { cmds })
|
||||
}
|
||||
|
||||
/// Puts the skin's shape in `elements` in the outline `pose` bends it into (copy-on-write).
|
||||
/// Returns whether it changed.
|
||||
/// Puts every shape with bones in `elements` in the outline `pose` bends it into
|
||||
/// (copy-on-write). Returns whether any changed.
|
||||
pub fn apply(arm: &Armature, elements: &mut [Arc<Element>], pose: &Pose) -> bool {
|
||||
let Some(skin) = &arm.skin else { return false };
|
||||
let Some(e) = elements.iter_mut().find(|e| e.id == skin.shape) else { return false };
|
||||
let ElementKind::Shape(s) = &e.kind else { return false };
|
||||
let Some(path) = deform(arm, pose) else { return false };
|
||||
if Arc::ptr_eq(&s.path, &path) || *s.path == *path {
|
||||
return false;
|
||||
let mut changed = false;
|
||||
for skin in &arm.skins {
|
||||
let Some(e) = elements.iter_mut().find(|e| e.id == skin.shape) else { continue };
|
||||
let ElementKind::Shape(s) = &e.kind else { continue };
|
||||
let path = deform(arm, skin, pose);
|
||||
if Arc::ptr_eq(&s.path, &path) || *s.path == *path {
|
||||
continue;
|
||||
}
|
||||
if let ElementKind::Shape(s) = &mut Arc::make_mut(e).kind {
|
||||
s.path = path;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if let ElementKind::Shape(s) = &mut Arc::make_mut(e).kind {
|
||||
s.path = path;
|
||||
}
|
||||
true
|
||||
changed
|
||||
}
|
||||
|
||||
/// The points of a shape armature's shape in `elements` (evaluated: posed), in point order, in
|
||||
/// the layer's space: the anchors of its outline as it shows.
|
||||
pub fn points_shown(arm: &Armature, elements: &[Arc<Element>]) -> Vec<Vec2> {
|
||||
let Some(skin) = &arm.skin else { return Vec::new() };
|
||||
/// The points of `skin`'s shape in `elements` (evaluated: posed), in point order, in the
|
||||
/// layer's space: the anchors of its outline as it shows.
|
||||
pub fn points_shown(skin: &Skin, elements: &[Arc<Element>]) -> Vec<Vec2> {
|
||||
elements
|
||||
.iter()
|
||||
.find(|e| e.id == skin.shape)
|
||||
@@ -304,29 +311,24 @@ pub fn points_shown(arm: &Armature, elements: &[Arc<Element>]) -> Vec<Vec2> {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Repairs a loaded skin against its armature: the rest outline within [`MAX_SKIN_POINTS`]
|
||||
/// anchors (else the skin goes), one binding per anchor, weights of bones that exist, positive
|
||||
/// and summing to 1; unbound automatic anchors are bound. Returns whether anything changed.
|
||||
pub fn sanitize(arm: &mut Armature) -> bool {
|
||||
let Some(skin) = &arm.skin else { return false };
|
||||
let n = anchors(&skin.rest).len();
|
||||
if n > MAX_SKIN_POINTS || arm.bones.iter().any(|b| b.child == skin.shape) {
|
||||
arm.skin = None;
|
||||
return true;
|
||||
}
|
||||
let before = arm.skin.clone();
|
||||
let ids: Vec<BoneId> = arm.bones.iter().map(|b| b.id).collect();
|
||||
let segments = rest_segments(arm);
|
||||
let Some(skin) = arm.skin.as_mut() else { return false };
|
||||
let pts = anchors(&skin.rest);
|
||||
skin.points.resize(n, Binding::default());
|
||||
for (b, &p) in skin.points.iter_mut().zip(&pts) {
|
||||
b.normalize(|id| ids.contains(&id));
|
||||
if b.bones.is_empty() && !b.manual {
|
||||
*b = auto_binding(&segments, p);
|
||||
/// Repairs the loaded skins against their armature's bones: one binding per anchor, weights of
|
||||
/// bones inside the skin's own shape, positive and summing to 1; unbound automatic anchors are
|
||||
/// bound. ([`Armature::sanitize`] has already dropped skins that are too big or have no bones.)
|
||||
pub(crate) fn sanitize(arm: &mut Armature) {
|
||||
for i in 0..arm.skins.len() {
|
||||
let Some(shape) = arm.skins.get(i).map(|k| k.shape) else { continue };
|
||||
let segments = rest_segments(arm, shape);
|
||||
let ids: Vec<BoneId> = arm.bones_in(shape).map(|b| b.id).collect();
|
||||
let Some(skin) = arm.skins.get_mut(i) else { continue };
|
||||
let pts = anchors(&skin.rest);
|
||||
skin.points.resize(pts.len(), Binding::default());
|
||||
for (b, &p) in skin.points.iter_mut().zip(&pts) {
|
||||
b.normalize(|id| ids.contains(&id));
|
||||
if b.bones.is_empty() && !b.manual {
|
||||
*b = auto_binding(&segments, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
arm.skin != before
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -12,7 +12,7 @@ const N1: ElementId = ElementId(30);
|
||||
const N2: ElementId = ElementId(31);
|
||||
|
||||
fn bone(id: BoneId, parent: ElementId, child: ElementId, head: Vec2, tail: Vec2) -> Bone {
|
||||
Bone::new(id, parent, child, head, tail, Affine::IDENTITY)
|
||||
Bone::in_shape(id, TAIL, parent, child, head, tail)
|
||||
}
|
||||
|
||||
/// A tail 200 px long and 20 px thick along y = 0 (anchors every 25 px along both edges), with
|
||||
@@ -35,7 +35,7 @@ fn rig() -> (Armature, Vec<Arc<Element>>) {
|
||||
let path = Arc::new(outline());
|
||||
let mut arm = Armature {
|
||||
bones: vec![bone(B1, TAIL, N1, Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)), bone(B2, N1, N2, Vec2::new(100.0, 0.0), Vec2::new(200.0, 0.0))],
|
||||
skin: Some(Skin::new(TAIL, path.clone())),
|
||||
skins: vec![Skin::new(TAIL, path.clone())],
|
||||
..Default::default()
|
||||
};
|
||||
rebind(&mut arm);
|
||||
@@ -65,7 +65,7 @@ fn turned(p: Vec2, j: Vec2, a: f32) -> Vec2 {
|
||||
#[test]
|
||||
fn automatic_weights_sum_to_one_and_follow_the_nearest_bone() {
|
||||
let (arm, _) = rig();
|
||||
let skin = arm.skin.as_ref().unwrap();
|
||||
let skin = arm.skins.first().unwrap();
|
||||
let pts = anchors(&skin.rest);
|
||||
assert_eq!(skin.points.len(), pts.len(), "one binding per anchor");
|
||||
for (b, p) in skin.points.iter().zip(&pts) {
|
||||
@@ -90,14 +90,14 @@ fn the_rest_pose_reproduces_the_shape_exactly() {
|
||||
let drawn = path_of(&els);
|
||||
// No pose, and a pose that lists every bone at 0.
|
||||
for pose in [Pose::default(), Pose(vec![crate::JointAngle::new(B1, 0.0), crate::JointAngle::new(B2, 0.0)])] {
|
||||
let rest = deform(&arm, &pose).unwrap();
|
||||
let rest = deform(&arm, &arm.skins[0], &pose);
|
||||
assert!(Arc::ptr_eq(&rest, &drawn), "the very path as drawn");
|
||||
assert!(!apply(&arm, &mut els, &pose), "nothing changes");
|
||||
}
|
||||
// A pose that turns one bone leaves the anchors only the other bone moves bit for bit.
|
||||
let mut pose = Pose::default();
|
||||
pose.set(B2, 0.7);
|
||||
let bent = deform(&arm, &pose).unwrap();
|
||||
let bent = deform(&arm, &arm.skins[0], &pose);
|
||||
assert_eq!(bent.cmds[1], drawn.cmds[1], "x = 25 follows the first bone only");
|
||||
assert_eq!(bent.cmds[0], drawn.cmds[0]);
|
||||
}
|
||||
@@ -110,7 +110,7 @@ fn a_quarter_bend_turns_bound_points_about_the_joint() {
|
||||
pose.set(B2, FRAC_PI_2);
|
||||
assert!(apply(&arm, &mut els, &pose));
|
||||
let bent = path_of(&els);
|
||||
let skin = arm.skin.as_ref().unwrap();
|
||||
let skin = arm.skins.first().unwrap();
|
||||
let joint = Vec2::new(100.0, 0.0);
|
||||
let (rest, now) = (anchors(&drawn), anchors(&bent));
|
||||
for ((b, r), n) in skin.points.iter().zip(&rest).zip(&now) {
|
||||
@@ -138,7 +138,7 @@ fn a_quarter_bend_turns_bound_points_about_the_joint() {
|
||||
// Turning the first bone carries the second: the tip goes round the root joint too.
|
||||
let mut pose = Pose::default();
|
||||
pose.set(B1, FRAC_PI_2);
|
||||
let tip = anchors(&deform(&arm, &pose).unwrap())[8];
|
||||
let tip = anchors(&deform(&arm, &arm.skins[0], &pose))[8];
|
||||
assert!(close(tip, turned(Vec2::new(200.0, -10.0), Vec2::new(0.0, 0.0), FRAC_PI_2), 1e-3), "{tip:?}");
|
||||
}
|
||||
|
||||
@@ -217,25 +217,25 @@ fn every_export_sees_the_bent_shape_and_files_keep_it() {
|
||||
let json = serde_json::to_string(&d).unwrap();
|
||||
let back: Document = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, d);
|
||||
assert!(back.timeline(0).layers[0].armature.as_ref().unwrap().skin.is_some());
|
||||
assert!(back.timeline(0).layers[0].armature.as_ref().unwrap().skin(TAIL).is_some());
|
||||
// The joint nodes' ids are counted, so new ids never collide with them.
|
||||
assert!(d.next_id > N2.0);
|
||||
// An armature written before shape armatures reads as one without a skin.
|
||||
let old: Armature = serde_json::from_str(r#"{"bones": []}"#).unwrap();
|
||||
assert!(old.skin.is_none());
|
||||
assert!(old.skins.is_empty());
|
||||
assert!(!serde_json::to_string(&old).unwrap().contains("skin"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_repairs_hostile_skins() {
|
||||
let (mut arm, _) = rig();
|
||||
let skin = arm.skin.as_mut().unwrap();
|
||||
let skin = arm.skins.first_mut().unwrap();
|
||||
skin.points.truncate(3);
|
||||
skin.points[0] = Binding { bones: vec![Influence(B1, f32::NAN), Influence(BoneId(99), 1.0), Influence(B2, 3.0), Influence(B2, 1.0)], manual: true };
|
||||
skin.points[1] = Binding { bones: vec![Influence(B1, -1.0)], manual: false };
|
||||
skin.points[2] = Binding { bones: vec![], manual: true };
|
||||
assert!(arm.sanitize());
|
||||
let skin = arm.skin.as_ref().unwrap();
|
||||
let skin = arm.skins.first().unwrap();
|
||||
assert_eq!(skin.points.len(), anchors(&skin.rest).len(), "one per anchor again");
|
||||
assert_eq!(skin.points[0].bones, vec![Influence(B2, 1.0)], "unknown bones, NaN and repeats go; the rest sums to 1");
|
||||
assert!(!skin.points[1].bones.is_empty(), "an automatic anchor left with nothing is bound again");
|
||||
@@ -249,25 +249,25 @@ fn sanitize_repairs_hostile_skins() {
|
||||
let (mut arm, _) = rig();
|
||||
arm.bones.push(bone(BoneId(41), N2, TAIL, Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0)));
|
||||
arm.sanitize();
|
||||
assert!(arm.skin.is_none() || arm.bones.iter().all(|b| b.child != TAIL));
|
||||
assert!(arm.bones.iter().all(|b| b.child != TAIL), "a joint node is no shape");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hand_binding_survives_new_bones() {
|
||||
let (mut arm, _) = rig();
|
||||
let skin = arm.skin.as_mut().unwrap();
|
||||
let skin = arm.skins.first_mut().unwrap();
|
||||
skin.points[1] = Binding { bones: vec![Influence(B2, 1.0)], manual: true };
|
||||
skin.points[2] = Binding { bones: vec![], manual: true };
|
||||
arm.bones.push(bone(BoneId(22), N2, ElementId(32), Vec2::new(200.0, 0.0), Vec2::new(210.0, 0.0)));
|
||||
rebind(&mut arm);
|
||||
let skin = arm.skin.as_ref().unwrap();
|
||||
let skin = arm.skins.first().unwrap();
|
||||
assert_eq!(skin.points[1].bones, vec![Influence(B2, 1.0)], "kept as bound by hand");
|
||||
assert!(skin.points[2].bones.is_empty(), "kept unbound");
|
||||
// Taking its bone away sends a hand-bound anchor back to automatic.
|
||||
let mut arm = arm.clone();
|
||||
arm.bones.retain(|b| b.id != B2 && b.id != BoneId(22));
|
||||
rebind(&mut arm);
|
||||
assert_eq!(arm.skin.as_ref().unwrap().points[1].bones, vec![Influence(B1, 1.0)]);
|
||||
assert_eq!(arm.skins.first().unwrap().points[1].bones, vec![Influence(B1, 1.0)]);
|
||||
}
|
||||
|
||||
/// Skinning cost: a shape of 2,000 anchors on 16 bones, posed (debug builds are slower).
|
||||
@@ -287,14 +287,14 @@ fn skinning_is_fast() {
|
||||
let parent = if i == 0 { TAIL } else { ElementId(100 + i - 1) };
|
||||
bones.push(bone(BoneId(200 + i), parent, ElementId(100 + i), Vec2::new(50.0 * i as f32, 0.0), Vec2::new(50.0 * (i + 1) as f32, 0.0)));
|
||||
}
|
||||
let mut arm = Armature { bones, skin: Some(Skin::new(TAIL, Arc::new(p))), ..Default::default() };
|
||||
let mut arm = Armature { bones, skins: vec![Skin::new(TAIL, Arc::new(p))], ..Default::default() };
|
||||
let t = std::time::Instant::now();
|
||||
rebind(&mut arm);
|
||||
let bind = t.elapsed();
|
||||
let pose = Pose(arm.bones.iter().map(|b| crate::JointAngle::new(b.id, 0.1)).collect());
|
||||
let t = std::time::Instant::now();
|
||||
for _ in 0..10 {
|
||||
std::hint::black_box(deform(&arm, &pose));
|
||||
std::hint::black_box(deform(&arm, &arm.skins[0], &pose));
|
||||
}
|
||||
let per = t.elapsed() / 10;
|
||||
println!("2,000 anchors × 16 bones: bind {bind:?}, deform {per:?}");
|
||||
|
||||
@@ -132,10 +132,9 @@ pub fn sprung_pose(layer: &Layer, frame: u32, fps: f32) -> Option<Pose> {
|
||||
/// by `pose`, each sprung bone swung by its spring, which is advanced `dt` seconds with the
|
||||
/// frame's motion counting `weight` (0: the frame only records the motion).
|
||||
fn step(arm: &Armature, mut world: HashMap<ElementId, Affine>, pose: &Pose, swings: &mut [Swing], dt: f32, weight: f32) {
|
||||
let nodes = arm.skin.is_some();
|
||||
for (b, sw) in arm.bones.iter().zip(swings.iter_mut()) {
|
||||
let Some(wp) = world.get(&b.parent).copied() else { continue };
|
||||
if !nodes && !world.contains_key(&b.child) {
|
||||
if b.shape.is_none() && !world.contains_key(&b.child) {
|
||||
continue;
|
||||
}
|
||||
let (key, slide) = (b.allow(pose.angle(b.id)), b.allow_slide(pose.slide(b.id)));
|
||||
|
||||
@@ -4,7 +4,6 @@ use super::*;
|
||||
use crate::armature::{Armature, Bone, Pose};
|
||||
use crate::skin::{deform, rebind, rest_segments};
|
||||
use crate::ElementId;
|
||||
use anicraft_geom::Affine;
|
||||
|
||||
const SHAPE: ElementId = ElementId(10);
|
||||
const B1: BoneId = BoneId(20);
|
||||
@@ -23,16 +22,16 @@ fn rig() -> Armature {
|
||||
}
|
||||
p.close();
|
||||
let bones = vec![
|
||||
Bone::new(B1, SHAPE, ElementId(30), Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), Affine::IDENTITY),
|
||||
Bone::new(B2, ElementId(30), ElementId(31), Vec2::new(100.0, 0.0), Vec2::new(200.0, 0.0), Affine::IDENTITY),
|
||||
Bone::in_shape(B1, SHAPE, SHAPE, ElementId(30), Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)),
|
||||
Bone::in_shape(B2, SHAPE, ElementId(30), ElementId(31), Vec2::new(100.0, 0.0), Vec2::new(200.0, 0.0)),
|
||||
];
|
||||
let mut arm = Armature { bones, skin: Some(Skin::new(SHAPE, Arc::new(p))), ..Default::default() };
|
||||
let mut arm = Armature { bones, skins: vec![Skin::new(SHAPE, Arc::new(p))], ..Default::default() };
|
||||
rebind(&mut arm);
|
||||
arm
|
||||
}
|
||||
|
||||
fn skin(arm: &Armature) -> &Skin {
|
||||
arm.skin.as_ref().expect("a skin")
|
||||
arm.skins.first().expect("a skin")
|
||||
}
|
||||
|
||||
fn sums_to_one(b: &Binding) -> bool {
|
||||
@@ -40,9 +39,9 @@ fn sums_to_one(b: &Binding) -> bool {
|
||||
}
|
||||
|
||||
fn paint_on(arm: &mut Armature, bone: BoneId, dabs: &[Vec2], radius: f32, strength: f32, brush: Brush) -> usize {
|
||||
let segments = rest_segments(arm);
|
||||
let segments = rest_segments(arm, SHAPE);
|
||||
let shown = anchors(&skin(arm).rest);
|
||||
let k = arm.skin.as_mut().expect("a skin");
|
||||
let k = arm.skins.first_mut().expect("a skin");
|
||||
paint(k, &segments, &shown, bone, dabs, Dab { brush, radius, strength })
|
||||
}
|
||||
|
||||
@@ -158,7 +157,7 @@ fn moving_points_keeps_every_binding() {
|
||||
q.y -= 15.0;
|
||||
}
|
||||
});
|
||||
let out = reshape(skin(&arm), &p, &rest_segments(&arm));
|
||||
let out = reshape(skin(&arm), &p, &rest_segments(&arm, SHAPE));
|
||||
assert_eq!(out, skin(&arm).points);
|
||||
}
|
||||
|
||||
@@ -166,7 +165,7 @@ fn moving_points_keeps_every_binding() {
|
||||
fn an_inserted_point_blends_its_neighbours() {
|
||||
let mut arm = rig();
|
||||
// Make the neighbours different by hand: anchor 3 (x = 75) follows B1, anchor 4 (x = 100) B2.
|
||||
if let Some(k) = arm.skin.as_mut() {
|
||||
if let Some(k) = arm.skins.first_mut() {
|
||||
k.points[3] = Binding { bones: vec![Influence(B1, 1.0)], manual: true };
|
||||
k.points[4] = Binding { bones: vec![Influence(B2, 1.0)], manual: true };
|
||||
}
|
||||
@@ -174,7 +173,7 @@ fn an_inserted_point_blends_its_neighbours() {
|
||||
let p = edited(&arm, |p| {
|
||||
p.cmds.insert(4, PathCmd::LineTo(Vec2::new(81.25, -10.0)));
|
||||
});
|
||||
let out = reshape(skin(&arm), &p, &rest_segments(&arm));
|
||||
let out = reshape(skin(&arm), &p, &rest_segments(&arm, SHAPE));
|
||||
assert_eq!(out.len(), anchors(&p).len());
|
||||
let b = &out[4];
|
||||
assert!((b.weight(B1) - 0.75).abs() < 1e-5 && (b.weight(B2) - 0.25).abs() < 1e-5, "{b:?}");
|
||||
@@ -187,13 +186,13 @@ fn an_inserted_point_blends_its_neighbours() {
|
||||
#[test]
|
||||
fn a_deleted_point_drops_its_binding() {
|
||||
let mut arm = rig();
|
||||
if let Some(k) = arm.skin.as_mut() {
|
||||
if let Some(k) = arm.skins.first_mut() {
|
||||
k.points[5] = Binding { bones: vec![Influence(B1, 0.6), Influence(B2, 0.4)], manual: true };
|
||||
}
|
||||
let p = edited(&arm, |p| {
|
||||
p.cmds.remove(4);
|
||||
});
|
||||
let out = reshape(skin(&arm), &p, &rest_segments(&arm));
|
||||
let out = reshape(skin(&arm), &p, &rest_segments(&arm, SHAPE));
|
||||
let mut want = skin(&arm).points.clone();
|
||||
want.remove(4);
|
||||
assert_eq!(out, want);
|
||||
@@ -208,7 +207,7 @@ fn a_new_subpath_is_bound_automatically_and_closing_points_copy_the_start() {
|
||||
p.line_to(Vec2::new(160.0, 5.0));
|
||||
p.close();
|
||||
});
|
||||
let segments = rest_segments(&arm);
|
||||
let segments = rest_segments(&arm, SHAPE);
|
||||
let out = reshape(skin(&arm), &p, &segments);
|
||||
let n = skin(&arm).points.len();
|
||||
assert_eq!(out.len(), n + 3);
|
||||
@@ -232,13 +231,13 @@ fn the_rest_pose_is_the_reshaped_outline_bit_for_bit() {
|
||||
}
|
||||
}));
|
||||
let mut arm2 = arm.clone();
|
||||
arm2.skin = Some(reshaped(skin(&arm), p.clone(), &rest_segments(&arm)));
|
||||
let rest = deform(&arm2, &Pose::default()).expect("an outline");
|
||||
arm2.skins = vec![reshaped(skin(&arm), p.clone(), &rest_segments(&arm, SHAPE))];
|
||||
let rest = deform(&arm2, &arm2.skins[0], &Pose::default());
|
||||
assert!(Arc::ptr_eq(&rest, &p));
|
||||
// Bent, the new point moves with the bones like its neighbours: between them.
|
||||
let mut pose = Pose::default();
|
||||
pose.set(B2, std::f32::consts::FRAC_PI_2);
|
||||
let bent = anchors(&deform(&arm2, &pose).expect("an outline"));
|
||||
let bent = anchors(&deform(&arm2, &arm2.skins[0], &pose));
|
||||
assert_eq!(bent.len(), anchors(&p).len());
|
||||
assert!(bent.iter().all(|q| q.x.is_finite() && q.y.is_finite()));
|
||||
}
|
||||
@@ -251,8 +250,8 @@ fn painting_a_large_shape_is_fast() {
|
||||
for i in 1..20_000 {
|
||||
p.line_to(Vec2::new(i as f32 * 0.1, (i % 7) as f32));
|
||||
}
|
||||
let bones = vec![Bone::new(B1, SHAPE, ElementId(30), Vec2::new(0.0, 0.0), Vec2::new(1000.0, 0.0), Affine::IDENTITY), Bone::new(B2, ElementId(30), ElementId(31), Vec2::new(1000.0, 0.0), Vec2::new(2000.0, 0.0), Affine::IDENTITY)];
|
||||
let mut arm = Armature { bones, skin: Some(Skin::new(SHAPE, Arc::new(p))), ..Default::default() };
|
||||
let bones = vec![Bone::in_shape(B1, SHAPE, SHAPE, ElementId(30), Vec2::new(0.0, 0.0), Vec2::new(1000.0, 0.0)), Bone::in_shape(B2, SHAPE, ElementId(30), ElementId(31), Vec2::new(1000.0, 0.0), Vec2::new(2000.0, 0.0))];
|
||||
let mut arm = Armature { bones, skins: vec![Skin::new(SHAPE, Arc::new(p))], ..Default::default() };
|
||||
rebind(&mut arm);
|
||||
let dabs: Vec<Vec2> = (0..32).map(|i| Vec2::new(900.0 + 10.0 * i as f32, 3.0)).collect();
|
||||
let t = std::time::Instant::now();
|
||||
|
||||
+218
-102
@@ -25,21 +25,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c(
|
||||
"bone.add",
|
||||
"Add Bone",
|
||||
"{from (instance id: the bone starts on it), to (instance id: the bone moves it), head?: [x, y] (the joint on a root instance, stage px, default its registration point; from an instance that hangs from a bone the joint is always that bone's end, so chains stay joined), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both instances go to an armature layer (made for the first bone)",
|
||||
"{from? (instance or shape id: the bone starts on it) | parent? (bone id: the bone starts on its end; for a bone inside a shape, on its joint), to (instance or shape id: the bone moves it as a whole), head?: [x, y] (the joint on a root, stage px, default its registration point; from something that hangs from a bone the joint is always that bone's end, so chains stay joined), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both go to an armature layer (made for the first bone). Instances and shapes mix in one armature: a bone inside a shape can carry an instance (parent), and a bone can end on a shape that then gets bones of its own (bone.add_in_shape with parent)",
|
||||
true,
|
||||
add as crate::RunFn,
|
||||
),
|
||||
c(
|
||||
"bone.add_in_shape",
|
||||
"Add Bone in Shape",
|
||||
"{shape? (shape id: the first bone, or another bone from the shape), parent? (bone id: continue the chain from its end), head?: [x, y] (the joint, stage px; default the parent bone's end), tail: [x, y] (stage px), name?} → {bone, layer, created, points}. The first bone moves the shape to an armature layer of its own, as an object (merge drawing leaves it alone); the shape's points are bound to the nearest bones",
|
||||
"{shape? (shape id: the first bone, or another bone from the shape), parent? (bone id: continue the chain from its end; a bone that ends on a shape starts that shape's first bone inside it), head?: [x, y] (the joint, stage px; default the parent bone's end), tail: [x, y] (stage px), name?} → {bone, layer, created, points, shape}. The first bone moves the shape to an armature layer of its own, as an object (merge drawing leaves it alone), unless a bone already moves it; the shape's points are bound to the nearest bones inside it. An armature may hold several shapes with bones",
|
||||
true,
|
||||
add_in_shape,
|
||||
),
|
||||
c("bone.bind", "Bind Points", "{bone, points?: [point index…] (default every point; see bone.info with points), mode?: \"only\" (the points follow just this bone; default) | \"add\" (they share it with the bones they follow) | \"remove\" | \"auto\" (back to automatic binding)} → {bone, changed, bound (how many points the bone moves)}. A shape armature's binding: which points of the shape follow which bone", true, bind),
|
||||
c("bone.paint_weights", "Paint Weights", "{bone, at: [[x, y]…] (dab centres, stage px, at most 4096), radius? (px, 1–2000, default 20), strength? (0–100 at the centre, default 25), mode?: \"add\" (default) | \"subtract\" | \"smooth\", frame?} → {bone, changed, bound}. The Bind tool's brush: raises, lowers or evens out how much the bone moves the shape's points within the radius of each dab (a smooth falloff to the rim); each point's weights stay normalised (its other bones share what is left) and the points become hand-bound. A drag sends many in one gesture: one undo step", true, paint_weights),
|
||||
c("bone.set_weight", "Set Point Weight", "{bone, points: [point index…] (see bone.info with points), weight (0–100: the bone's share of each point)} sets exactly how much the bone moves the points; their other bones share the rest in proportion (a point that followed only this bone gives the rest to its nearest other bones). Hand-bound", true, set_weight),
|
||||
c("bone.remove", "Remove Bone", "{bone} removes it and the bones below it; the instances they moved go to a layer of their own as they look at the playhead (with the last bone, the whole armature does); asks first when the armature has more than one pose", true, remove),
|
||||
c("bone.remove", "Remove Bone", "{bone} removes it and the bones below it → {removed, freed, unbound, layer, armature_removed}; the instances and shapes they moved go to a layer of their own as they look at the playhead (with the last bone, the whole armature does); a shape left with no bones inside stays as it looks there; asks first when the armature has more than one pose", true, remove),
|
||||
c("bone.set_limits", "Joint Limits", "{bone, constrain?: bool (false: turns freely), min?, max? (°, −360…360, from where it was drawn)} limits how far the joint turns, in every pose", true, set_limits),
|
||||
c("bone.set_translation", "Joint Translation", "{bone, axis: \"x\" | \"y\" (along the axes of what the bone starts on, as it is turned), enabled?: bool (false: the joint doesn't slide that way), constrain?: bool (false: slides freely), min?, max? (px, ±10,000, from where it was drawn)} lets the joint slide, in every pose; posing (bone.solve, the Selection tool) slides it only where turning can't reach", true, set_translation),
|
||||
c("bone.set_spring", "Bone Spring", "{bone, strength? (0–100: 0 is no spring; stiffer swings faster and lags less), damping? (0–100: how quickly the swing dies down; 100 absorbs it all)} secondary motion: the bone lags behind and swings past its pose as the bones it hangs from move, then settles. Evaluated, never stored: the keyed poses don't change", true, set_spring),
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c("bone.pin", "Pin Bone", "{bone, pinned: bool} a pinned bone (and the bones it hangs from) stays put while dragging bones below it", true, pin),
|
||||
c("bone.pose", "Pose Bone", "{bone?, angle? (°, the joint angle: 0 as drawn), rotate_by? (°), slide_x?, slide_y? (px: how far the joint slides, within its translation limits), dx?, dy? (moves the whole armature), layer? (the armature layer, when no bone is given), frame?} keys the pose at the frame", true, pose),
|
||||
c("bone.solve", "Drag Bone", "{bone, x, y (stage px: where the bone's end goes), local?: [x, y] (the point dragged, in the bone's instance's space; default its end), frame?} → {reached, error (px), chain}; inverse kinematics turns the bone and the bones above it (limits respected, pinned bones kept)", true, solve),
|
||||
c("bone.info", "Armatures", "{frame?, layer?, points?: bool} → every armature on the scene at the frame: its bones with joint and end (stage px, as keyed), joint angle and limits (°), slide and translation limits (px), spring (0–100) and its swing at the frame (°, what the spring adds to the angle), pinned; whether springs are on; a shape armature's shape, how many points each bone moves, and with points the shape's points (stage px) and the bones each follows", false, info),
|
||||
c("bone.info", "Armatures", "{frame?, layer?, points?: bool} → every armature on the scene at the frame: its bones with joint and end (stage px, as keyed), joint angle and limits (°), slide and translation limits (px), spring (0–100) and its swing at the frame (°, what the spring adds to the angle), pinned; whether springs are on; the armature's members and whether it is mixed; each shape with bones (shapes: its bones, how many points, and with points every point on the stage with the bones it follows), the shape each bone is inside and how many points it moves; `shape` and `points` are the first shape's", false, info),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -160,78 +160,146 @@ fn armature_layer(s: &mut Session, from: LayerId, index: usize, elements: Vec<Ar
|
||||
Ok(lid)
|
||||
}
|
||||
|
||||
/// What a new bone starts on: an element (an instance or a shape), or the joint node at the end
|
||||
/// of a bone inside a shape (ADR 0098).
|
||||
struct Start {
|
||||
layer: LayerId,
|
||||
index: usize,
|
||||
/// The element or joint node the bone hangs from.
|
||||
node: ElementId,
|
||||
/// Its transform at the playhead (as posed).
|
||||
world: Affine,
|
||||
/// The armature it is part of already.
|
||||
arm: Option<Arc<Armature>>,
|
||||
/// The element itself, when the bone starts on one.
|
||||
el: Option<Arc<Element>>,
|
||||
/// The end of the bone it hangs from (stage px): every bone from it starts there.
|
||||
joint: Option<Vec2>,
|
||||
}
|
||||
|
||||
/// Whether a bone can move `el` as a whole: a symbol instance, or a shape (which bones inside
|
||||
/// it may then bend).
|
||||
fn rigid(el: &Element) -> bool {
|
||||
matches!(el.kind, ElementKind::Symbol { .. } | ElementKind::Shape(_))
|
||||
}
|
||||
|
||||
/// `el` as it goes onto an armature layer: a shape there is an object (merge drawing, ADR 0031,
|
||||
/// leaves it alone).
|
||||
fn as_member(el: &Arc<Element>) -> Arc<Element> {
|
||||
match &el.kind {
|
||||
ElementKind::Shape(x) if x.merge => {
|
||||
let mut e = (**el).clone();
|
||||
if let ElementKind::Shape(x) = &mut e.kind {
|
||||
x.merge = false;
|
||||
}
|
||||
Arc::new(e)
|
||||
}
|
||||
_ => el.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The start of a bone on element `x` (found at the playhead).
|
||||
fn start_on(s: &Session, x: Found) -> Result<Start> {
|
||||
let arm = (x.kind == LayerKind::Armature).then(|| s.timeline().layer(x.layer).and_then(|l| l.armature.clone()).unwrap_or_default());
|
||||
// An element that already hangs from a bone has one joint, that bone's end: every bone from
|
||||
// it starts there, wherever on it the drag began, so the chain stays joined end to start and
|
||||
// turns about the joints it shows, as in Animate (#239).
|
||||
let joint = arm.as_ref().and_then(|a| a.bone_into(x.el.id)).map(|b| x.el.transform.apply(b.tail));
|
||||
Ok(Start { layer: x.layer, index: x.index, node: x.el.id, world: x.el.transform, arm, el: Some(x.el), joint })
|
||||
}
|
||||
|
||||
/// The start of a bone on the end of bone `b`: the element it moves, or for a bone inside a
|
||||
/// shape its joint node.
|
||||
fn start_on_bone(s: &Session, b: BoneId) -> Result<Start> {
|
||||
let (lid, arm) = find_bone(s, b)?;
|
||||
let bone = arm.bone(b).ok_or_else(|| EngineError::State("no such bone".into()))?;
|
||||
let off = || EngineError::State(format!("the bone isn't on the stage at frame {}", s.frame + 1));
|
||||
if bone.shape.is_none() {
|
||||
return start_on(s, find_instance(s, bone.child).ok_or_else(off)?);
|
||||
}
|
||||
let tl = s.timeline();
|
||||
let index = tl.layers.iter().position(|l| l.id == lid).ok_or_else(off)?;
|
||||
let l = tl.layer(lid).ok_or_else(off)?;
|
||||
let (_, els) = evaluate_layer_elements(l, s.frame).ok_or_else(off)?;
|
||||
let pose = armature::pose_at(l, s.frame).unwrap_or_default();
|
||||
let world = armature::place(&arm, &els, &pose).get(&bone.child).copied().ok_or_else(off)?;
|
||||
Ok(Start { layer: lid, index, node: bone.child, world, joint: Some(world.apply(bone.tail)), arm: Some(arm), el: None })
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let req = |k: &str| opt_u64(p, k)?.map(ElementId).ok_or_else(|| EngineError::Param(format!("param '{k}' (an instance id) is required")));
|
||||
let (from, to) = (req("from")?, req("to")?);
|
||||
let from = opt_u64(p, "from")?.map(ElementId);
|
||||
let parent = opt_u64(p, "parent")?.map(BoneId);
|
||||
let to = opt_u64(p, "to")?.map(ElementId).ok_or_else(|| EngineError::Param("param 'to' (the id of the instance or shape the bone moves) is required".into()))?;
|
||||
let (head, tail) = (opt_point(p, "head")?, opt_point(p, "tail")?);
|
||||
let name = opt_str(p, "name")?.unwrap_or("").trim().to_string();
|
||||
if name.len() > MAX_NAME {
|
||||
return Err(EngineError::Param(format!("param 'name' must be at most {MAX_NAME} bytes")));
|
||||
}
|
||||
if from == to {
|
||||
return Err(EngineError::Param("a bone joins two different instances".into()));
|
||||
let missing = |id: ElementId| EngineError::State(format!("no instance or shape with id {} on the stage at frame {}", id.0, s.frame + 1));
|
||||
let f = match (parent, from) {
|
||||
(Some(_), Some(_)) => return Err(EngineError::Param("give 'from' (an instance or shape) or 'parent' (a bone to continue from its end), not both".into())),
|
||||
(Some(b), None) => start_on_bone(s, b)?,
|
||||
(None, Some(id)) => start_on(s, find_instance(s, id).ok_or_else(|| missing(id))?)?,
|
||||
(None, None) => return Err(EngineError::Param("param 'from' (the id of the instance or shape the bone starts on) or 'parent' (a bone to continue from its end) is required".into())),
|
||||
};
|
||||
if f.node == to {
|
||||
return Err(EngineError::Param("a bone joins two different things".into()));
|
||||
}
|
||||
let missing = |id: ElementId| EngineError::State(format!("no instance with id {} on the stage at frame {}", id.0, s.frame + 1));
|
||||
let f = find_instance(s, from).ok_or_else(|| missing(from))?;
|
||||
let t = find_instance(s, to).ok_or_else(|| missing(to))?;
|
||||
for x in [&f, &t] {
|
||||
if !matches!(x.el.kind, ElementKind::Symbol { .. }) {
|
||||
return Err(EngineError::State("bones join symbol instances: convert the artwork to a symbol first (Modify › Convert to Symbol, F8)".into()));
|
||||
for (el, kind, layer) in [(f.el.as_ref(), s.timeline().layer(f.layer).map_or(LayerKind::Normal, |l| l.kind), f.layer), (Some(&t.el), t.kind, t.layer)] {
|
||||
if el.is_some_and(|e| !rigid(e)) {
|
||||
return Err(EngineError::State("bones join symbol instances and shapes: convert other artwork to a symbol first (Modify › Convert to Symbol, F8)".into()));
|
||||
}
|
||||
if !matches!(x.kind, LayerKind::Normal | LayerKind::Armature) {
|
||||
return Err(EngineError::State("bones join instances on normal layers (not on guide or mask layers)".into()));
|
||||
if !matches!(kind, LayerKind::Normal | LayerKind::Armature) {
|
||||
return Err(EngineError::State("bones join artwork on normal layers (not on guide or mask layers)".into()));
|
||||
}
|
||||
unlocked(s, x.layer)?;
|
||||
unlocked(s, layer)?;
|
||||
}
|
||||
let tl = s.timeline();
|
||||
let arm_of = |x: &Found| (x.kind == LayerKind::Armature).then(|| tl.layer(x.layer).and_then(|l| l.armature.clone()).unwrap_or_default());
|
||||
let (fa, ta) = (arm_of(&f), arm_of(&t));
|
||||
match (&fa, &ta) {
|
||||
(_, Some(a)) if f.layer == t.layer && a.bone_into(to).is_some() => return Err(EngineError::State("that instance already hangs from a bone; each instance has one bone into it".into())),
|
||||
(_, Some(_)) if f.layer == t.layer => return Err(EngineError::State("that instance is the armature's root: drag from the root to the other instances instead".into())),
|
||||
(None, Some(_)) => return Err(EngineError::State("start the bone on the armature: drag from one of its instances to the new one".into())),
|
||||
(Some(_), Some(_)) => return Err(EngineError::State("those instances are in different armatures".into())),
|
||||
let ta = (t.kind == LayerKind::Armature).then(|| s.timeline().layer(t.layer).and_then(|l| l.armature.clone()).unwrap_or_default());
|
||||
match (&f.arm, &ta) {
|
||||
(_, Some(a)) if f.layer == t.layer && a.bone_into(to).is_some() => return Err(EngineError::State("that already hangs from a bone; each instance or shape has one bone into it".into())),
|
||||
(_, Some(_)) if f.layer == t.layer => return Err(EngineError::State("that is the armature's root: drag from the root to the others instead".into())),
|
||||
(None, Some(_)) => return Err(EngineError::State("start the bone on the armature: drag from one of its bones, instances or shapes to the new one".into())),
|
||||
(Some(_), Some(_)) => return Err(EngineError::State("those are in different armatures".into())),
|
||||
_ => {}
|
||||
}
|
||||
if fa.as_ref().is_some_and(|a| a.bones.len() >= MAX_BONES) {
|
||||
if f.arm.as_ref().is_some_and(|a| a.bones.len() >= MAX_BONES) {
|
||||
return Err(EngineError::State(format!("an armature has at most {MAX_BONES} bones")));
|
||||
}
|
||||
let (wf, wt) = (f.el.transform, t.el.transform);
|
||||
let singular = || EngineError::State("an instance scaled to nothing can't hold a bone".into());
|
||||
let (wf, wt) = (f.world, t.el.transform);
|
||||
let singular = || EngineError::State("artwork scaled to nothing can't hold a bone".into());
|
||||
let (inv_f, inv_t) = (wf.inverse().ok_or_else(singular)?, wt.inverse().ok_or_else(singular)?);
|
||||
// The joint. An instance that already hangs from a bone has one joint, that bone's end: every
|
||||
// bone from it starts there, wherever on the instance the drag began, so the chain stays
|
||||
// joined end to start and turns about the joints it shows, as in Animate (#239). A root's
|
||||
// The joint: the end of the bone the start hangs from, when it hangs from one; a root's
|
||||
// bones start where given (a torso's shoulders and hips), else at its registration point.
|
||||
let into_from = fa.as_ref().and_then(|a| a.bone_into(from)).map(|b| wf.apply(b.tail));
|
||||
let head = into_from.or(head).unwrap_or(wf.translation());
|
||||
let head = f.joint.or(head).unwrap_or(wf.translation());
|
||||
let tail = tail.unwrap_or(wt.translation());
|
||||
let rest = inv_f.mul(&wt);
|
||||
if !rest.is_finite() || rest.inverse().is_none() {
|
||||
return Err(singular());
|
||||
}
|
||||
let id = BoneId(s.doc.alloc_id());
|
||||
let bone = Bone { name, ..Bone::new(id, from, to, inv_f.apply(head), inv_t.apply(tail), rest) };
|
||||
let bone = Bone { name, ..Bone::new(id, f.node, to, inv_f.apply(head), inv_t.apply(tail), rest) };
|
||||
let moved = as_member(&t.el);
|
||||
take_off(s, t.layer, to)?;
|
||||
let lid = match fa {
|
||||
Some(_) => {
|
||||
// Another bone on this armature: the new instance joins every pose, at angle 0.
|
||||
let lid = match (&f.arm, &f.el) {
|
||||
(None, Some(root)) => {
|
||||
// The first bone: both go to a new armature layer above them.
|
||||
take_off(s, f.layer, f.node)?;
|
||||
let arm = Armature { bones: vec![bone], ..Default::default() };
|
||||
armature_layer(s, f.layer, f.index.min(t.index), vec![as_member(root), moved], arm)?
|
||||
}
|
||||
_ => {
|
||||
// Another bone on this armature: what it moves joins every pose, at angle 0.
|
||||
let l = s.layer_mut(Some(f.layer))?;
|
||||
let mut arm = l.armature.as_deref().cloned().unwrap_or_default();
|
||||
arm.bones.push(bone);
|
||||
l.armature = Some(Arc::new(arm));
|
||||
for k in &mut l.keyframes {
|
||||
Arc::make_mut(k).elements.push(t.el.clone());
|
||||
Arc::make_mut(k).elements.push(moved.clone());
|
||||
}
|
||||
rebake(l);
|
||||
f.layer
|
||||
}
|
||||
None => {
|
||||
// The first bone: both instances move to a new armature layer above them.
|
||||
take_off(s, f.layer, from)?;
|
||||
let arm = Armature { bones: vec![bone], ..Default::default() };
|
||||
armature_layer(s, f.layer, f.index.min(t.index), vec![f.el.clone(), t.el.clone()], arm)?
|
||||
}
|
||||
};
|
||||
s.layer = lid;
|
||||
s.selection.clear();
|
||||
@@ -252,17 +320,30 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut left = (*arm).clone();
|
||||
left.bones.retain(|b| !gone.contains(&b.id));
|
||||
let dissolve = left.is_empty();
|
||||
// A shape armature's bones move no instances: only without bones does its shape go.
|
||||
let skinned = arm.skin.is_some();
|
||||
// A shape left with no bones inside it has no skin: it stays as it looks at the playhead.
|
||||
let unbound: Vec<ElementId> = left.skins.iter().map(|k| k.shape).filter(|sh| left.bones_in(*sh).next().is_none()).collect();
|
||||
left.skins.retain(|k| !unbound.contains(&k.shape));
|
||||
skin::rebind(&mut left);
|
||||
let freed: Vec<ElementId> = if dissolve { arm.members() } else if skinned { Vec::new() } else { arm.bones.iter().filter(|b| gone.contains(&b.id)).map(|b| b.child).collect() };
|
||||
// What no bone holds any more leaves the armature: the instances and shapes the removed
|
||||
// bones moved (a bone inside a shape moves no element), and with the last bone everything.
|
||||
let stay = left.members();
|
||||
let freed: Vec<ElementId> = arm.members().into_iter().filter(|m| !stay.contains(m)).collect();
|
||||
let tl = s.timeline();
|
||||
let index = tl.layers.iter().position(|l| l.id == lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
|
||||
let layer = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
|
||||
let (start, end) = (layer.keyframes.first().map_or(0, |k| k.start), layer.end_frame());
|
||||
// The freed instances as they look at the playhead (or at the armature's first frame).
|
||||
// The freed elements as they look at the playhead (or at the armature's first frame).
|
||||
let at = s.frame.clamp(start, end.saturating_sub(1).max(start));
|
||||
let shown: Vec<Arc<Element>> = evaluate_layer_elements(layer, at).map(|(_, e)| e.iter().filter(|e| freed.contains(&e.id)).cloned().collect()).unwrap_or_default();
|
||||
let now: Vec<Arc<Element>> = evaluate_layer_elements(layer, at).map(|(_, e)| e.to_vec()).unwrap_or_default();
|
||||
let shown: Vec<Arc<Element>> = now.iter().filter(|e| freed.contains(&e.id)).cloned().collect();
|
||||
let held: Vec<(ElementId, Arc<anicraft_geom::Path>)> = now
|
||||
.iter()
|
||||
.filter(|e| unbound.contains(&e.id) && stay.contains(&e.id))
|
||||
.filter_map(|e| match &e.kind {
|
||||
ElementKind::Shape(x) => Some((e.id, x.path.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let folder = layer.parent.filter(|p| tl.layer(*p).is_some_and(|x| x.kind == LayerKind::Folder));
|
||||
let new_id = LayerId(s.doc.alloc_id());
|
||||
let mut freed_layer = Layer::new(new_id, fresh_name(s, "Layer "));
|
||||
@@ -271,6 +352,7 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
k.elements = shown;
|
||||
freed_layer.keyframes = vec![Arc::new(k)];
|
||||
let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing)?;
|
||||
let own_layer = dissolve || !freed.is_empty();
|
||||
if dissolve {
|
||||
tl.layers.retain(|l| l.id != lid);
|
||||
tl.layers.insert(index.min(tl.layers.len()), Arc::new(freed_layer));
|
||||
@@ -280,18 +362,25 @@ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let k = Arc::make_mut(k);
|
||||
k.elements.retain(|e| !freed.contains(&e.id));
|
||||
k.pose.retain(|b| !gone.contains(&b));
|
||||
for e in &mut k.elements {
|
||||
if let Some((_, path)) = held.iter().find(|h| h.0 == e.id)
|
||||
&& let ElementKind::Shape(x) = &mut Arc::make_mut(e).kind
|
||||
{
|
||||
x.path = path.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
l.armature = Some(Arc::new(left));
|
||||
rebake(l);
|
||||
if !skinned {
|
||||
if own_layer {
|
||||
tl.layers.insert((index + 1).min(tl.layers.len()), Arc::new(freed_layer));
|
||||
}
|
||||
}
|
||||
tl.repair_masks();
|
||||
s.layer = if dissolve { new_id } else { lid };
|
||||
s.selection.clear();
|
||||
let layer = if dissolve || !skinned { new_id } else { lid };
|
||||
Ok(json!({"removed": gone.iter().map(|b| b.0).collect::<Vec<_>>(), "freed": freed.iter().map(|e| e.0).collect::<Vec<_>>(), "layer": layer.0, "armature_removed": dissolve}))
|
||||
let layer = if own_layer { new_id } else { lid };
|
||||
Ok(json!({"removed": gone.iter().map(|b| b.0).collect::<Vec<_>>(), "freed": freed.iter().map(|e| e.0).collect::<Vec<_>>(), "unbound": unbound.iter().filter(|u| stay.contains(u)).map(|e| e.0).collect::<Vec<_>>(), "layer": layer.0, "armature_removed": dissolve}))
|
||||
}
|
||||
|
||||
fn set_limits(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -586,13 +675,27 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"slide_x": limits(b.slide_x), "slide_y": limits(b.slide_y),
|
||||
"spring": b.spring.map(|sp| json!({"strength": sp.strength * 100.0, "damping": sp.damping * 100.0})),
|
||||
"swing": deg(shown.angle(b.id) - b.allow(pose.angle(b.id))),
|
||||
"points": arm.skin.as_ref().map(|k| k.points.iter().filter(|x| x.weight(b.id) > 0.0).count()),
|
||||
"shape": b.shape.map(|e| e.0),
|
||||
"points": b.shape.map(|_| arm.bound_count(b.id)),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut out = json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::<Vec<_>>(), "poses": poses(l), "bones": bones, "shape": arm.skin_shape().map(|e| e.0), "springs": !arm.springs_off});
|
||||
if with_points && let Some(k) = &arm.skin {
|
||||
out["points"] = json!(skin::points_shown(arm, &els).iter().zip(&k.points).map(|(at, b)| json!({"at": pt(*at), "bones": b.bones.iter().map(|i| json!([i.0.0, i.1])).collect::<Vec<_>>(), "manual": b.manual})).collect::<Vec<_>>());
|
||||
let points = |k: &Skin| skin::points_shown(k, &els).iter().zip(&k.points).map(|(at, b)| json!({"at": pt(*at), "bones": b.bones.iter().map(|i| json!([i.0.0, i.1])).collect::<Vec<_>>(), "manual": b.manual})).collect::<Vec<_>>();
|
||||
let shapes: Vec<Value> = arm
|
||||
.skins
|
||||
.iter()
|
||||
.map(|k| {
|
||||
let mut v = json!({"shape": k.shape.0, "bones": arm.bones_in(k.shape).map(|b| b.id.0).collect::<Vec<_>>(), "count": k.points.len()});
|
||||
if with_points {
|
||||
v["points"] = json!(points(k));
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
let first = arm.skins.first();
|
||||
let mut out = json!({"layer": l.id.0, "name": l.name, "roots": arm.roots().iter().map(|e| e.0).collect::<Vec<_>>(), "members": arm.members().iter().map(|e| e.0).collect::<Vec<_>>(), "poses": poses(l), "bones": bones, "shape": first.map(|k| k.shape.0), "shapes": shapes, "mixed": arm.is_mixed(), "springs": !arm.springs_off});
|
||||
if with_points && let Some(k) = first {
|
||||
out["points"] = json!(points(k));
|
||||
}
|
||||
Some(out)
|
||||
})
|
||||
@@ -615,12 +718,20 @@ fn add_in_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (existing, found, from, head) = match (parent, shape) {
|
||||
(Some(b), _) => {
|
||||
let (lid, arm) = find_bone(s, b)?;
|
||||
let sh = arm.skin_shape().ok_or_else(|| EngineError::State("that bone joins symbol instances: continue it with bone.add".into()))?;
|
||||
let pb = arm.bone(b).ok_or_else(|| EngineError::State("no such bone".into()))?;
|
||||
// A bone inside a shape continues inside it from its joint node; a bone that ends on
|
||||
// a shape (ADR 0098) continues with that shape's first bone inside it.
|
||||
let (sh, node) = match pb.shape {
|
||||
Some(sh) => (sh, pb.child),
|
||||
None => (pb.child, pb.child),
|
||||
};
|
||||
if shape.is_some_and(|x| x != sh) {
|
||||
return Err(EngineError::Param("that bone is in another shape".into()));
|
||||
}
|
||||
let f = find_instance(s, sh).ok_or_else(|| EngineError::State(format!("the armature's shape isn't on the stage at frame {}", frame + 1)))?;
|
||||
let node = arm.bone(b).map(|x| x.child).ok_or_else(|| EngineError::State("no such bone".into()))?;
|
||||
let f = find_instance(s, sh).ok_or_else(|| EngineError::State(format!("the bone's shape isn't on the stage at frame {}", frame + 1)))?;
|
||||
if !matches!(f.el.kind, ElementKind::Shape(_)) {
|
||||
return Err(EngineError::State("that bone ends on a symbol instance: continue it to another instance or shape with bone.add".into()));
|
||||
}
|
||||
let end = s.timeline().layer(lid).and_then(|l| {
|
||||
let (_, els) = evaluate_layer_elements(l, frame)?;
|
||||
let pose = armature::pose_at(l, frame).unwrap_or_default();
|
||||
@@ -638,7 +749,7 @@ fn add_in_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let existing = match f.kind {
|
||||
LayerKind::Normal => None,
|
||||
LayerKind::Armature => {
|
||||
let arm = s.timeline().layer(f.layer).and_then(|l| l.armature.clone()).filter(|a| a.skin_shape() == Some(sh)).ok_or_else(|| EngineError::State("that shape isn't the armature's".into()))?;
|
||||
let arm = s.timeline().layer(f.layer).and_then(|l| l.armature.clone()).filter(|a| a.contains(sh)).ok_or_else(|| EngineError::State("that shape isn't the armature's".into()))?;
|
||||
Some((f.layer, arm))
|
||||
}
|
||||
_ => return Err(EngineError::State("bones go inside shapes on normal layers (not on guide or mask layers)".into())),
|
||||
@@ -658,6 +769,7 @@ fn add_in_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Param("a bone needs a length: drag from its joint to its end".into()));
|
||||
}
|
||||
let ElementKind::Shape(shp) = &found.el.kind else { return Err(EngineError::State("that isn't a shape".into())) };
|
||||
let sh = found.el.id;
|
||||
// The node the bone starts on, as placed at the playhead: the bone's points go back through
|
||||
// it to the shape as drawn (a new bone is at rest in every pose).
|
||||
let node = match &existing {
|
||||
@@ -677,16 +789,23 @@ fn add_in_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if existing.as_ref().is_some_and(|(_, a)| a.bones.len() >= MAX_BONES) {
|
||||
return Err(EngineError::State(format!("an armature has at most {MAX_BONES} bones")));
|
||||
}
|
||||
if existing.is_none() && skin::anchors(&shp.path).len() > MAX_SKIN_POINTS {
|
||||
// The shape's first bone binds its points: the outline as it is drawn is its rest outline.
|
||||
let first = existing.as_ref().is_none_or(|(_, a)| a.skin(sh).is_none());
|
||||
if first && skin::anchors(&shp.path).len() > MAX_SKIN_POINTS {
|
||||
return Err(EngineError::State(format!("bones go inside shapes of at most {MAX_SKIN_POINTS} points: simplify it first (Modify › Shape › Optimize)")));
|
||||
}
|
||||
let id = BoneId(s.doc.alloc_id());
|
||||
let child = ElementId(s.doc.alloc_id());
|
||||
let bone = Bone { name, ..Bone::new(id, from, child, h, t, Affine::IDENTITY) };
|
||||
let bone = Bone { name, ..Bone::in_shape(id, sh, from, child, h, t) };
|
||||
let (lid, created) = match existing {
|
||||
Some((lid, arm)) => {
|
||||
let mut arm = (*arm).clone();
|
||||
arm.bones.push(bone);
|
||||
if first {
|
||||
// A shape a bone already moves as a whole (ADR 0098): it has never been bent, so
|
||||
// every keyframe holds the outline as drawn.
|
||||
arm.skins.push(Skin::new(sh, shp.path.clone()));
|
||||
}
|
||||
skin::rebind(&mut arm);
|
||||
let l = s.layer_mut(Some(lid))?;
|
||||
l.armature = Some(Arc::new(arm));
|
||||
@@ -695,20 +814,21 @@ fn add_in_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
None => {
|
||||
// An armature's shape is an object: merge drawing (ADR 0031) no longer cuts it.
|
||||
let mut el = (*found.el).clone();
|
||||
if let ElementKind::Shape(x) = &mut el.kind {
|
||||
x.merge = false;
|
||||
}
|
||||
let mut arm = Armature { bones: vec![bone], skin: Some(Skin::new(found.el.id, shp.path.clone())), ..Default::default() };
|
||||
let mut arm = Armature { bones: vec![bone], skins: vec![Skin::new(sh, shp.path.clone())], ..Default::default() };
|
||||
skin::rebind(&mut arm);
|
||||
take_off(s, found.layer, found.el.id)?;
|
||||
(armature_layer(s, found.layer, found.index, vec![Arc::new(el)], arm)?, true)
|
||||
take_off(s, found.layer, sh)?;
|
||||
(armature_layer(s, found.layer, found.index, vec![as_member(&found.el)], arm)?, true)
|
||||
}
|
||||
};
|
||||
s.layer = lid;
|
||||
s.selection.clear();
|
||||
let bound = s.timeline().layer(lid).and_then(|l| l.armature.as_ref()).and_then(|a| a.skin.as_ref()).map_or(0, |k| k.points.iter().filter(|b| b.weight(id) > 0.0).count());
|
||||
Ok(json!({"bone": id.0, "layer": lid.0, "created": created, "points": bound}))
|
||||
let bound = s.timeline().layer(lid).and_then(|l| l.armature.as_ref()).map_or(0, |a| a.bound_count(id));
|
||||
Ok(json!({"bone": id.0, "layer": lid.0, "created": created, "points": bound, "shape": sh.0}))
|
||||
}
|
||||
|
||||
/// The shape bone `id` is inside; an error for a bone that moves an instance or a whole shape.
|
||||
fn shape_of(arm: &Armature, id: BoneId, what: &str) -> Result<ElementId> {
|
||||
arm.bone(id).and_then(|b| b.shape).ok_or_else(|| EngineError::State(format!("that bone joins symbol instances: only bones inside a shape {what}")))
|
||||
}
|
||||
|
||||
fn bind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -719,7 +839,8 @@ fn bind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let (lid, arm) = find_bone(s, id)?;
|
||||
unlocked(s, lid)?;
|
||||
let n = arm.skin.as_ref().map(|k| k.points.len()).ok_or_else(|| EngineError::State("that bone joins symbol instances: only bones inside a shape bind its points".into()))?;
|
||||
let sh = shape_of(&arm, id, "bind its points")?;
|
||||
let n = arm.skin(sh).map_or(0, |k| k.points.len());
|
||||
let bad = || EngineError::Param(format!("param 'points' must be a list of point indices below {n} (see bone.info with points)"));
|
||||
let points: Vec<usize> = match p.get("points") {
|
||||
None | Some(Value::Null) => (0..n).collect(),
|
||||
@@ -727,8 +848,8 @@ fn bind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(_) => return Err(bad()),
|
||||
};
|
||||
let mut arm = (*arm).clone();
|
||||
let segments = skin::rest_segments(&arm);
|
||||
let Some(k) = arm.skin.as_mut() else { return Err(EngineError::State("that bone isn't inside a shape".into())) };
|
||||
let segments = skin::rest_segments(&arm, sh);
|
||||
let Some(k) = arm.skin_mut(sh) else { return Err(EngineError::State("that bone isn't inside a shape".into())) };
|
||||
let anchors = skin::anchors(&k.rest);
|
||||
let mut changed = 0usize;
|
||||
for i in points {
|
||||
@@ -760,7 +881,7 @@ fn bind(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let l = s.layer_mut(Some(lid))?;
|
||||
l.armature = Some(Arc::new(arm));
|
||||
rebake(l);
|
||||
Ok(json!({"bone": id.0, "changed": changed, "bound": bound}))
|
||||
Ok(json!({"bone": id.0, "changed": changed, "bound": bound, "shape": sh.0}))
|
||||
}
|
||||
|
||||
/// The point indices in param `key`, each below `n`.
|
||||
@@ -772,19 +893,12 @@ fn point_list(p: &Value, key: &str, n: usize) -> Result<Vec<usize>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many points bone `id` moves.
|
||||
fn bound_count(arm: &Armature, id: BoneId) -> usize {
|
||||
arm.skin.as_ref().map_or(0, |k| k.points.iter().filter(|b| b.weight(id) > 0.0).count())
|
||||
}
|
||||
|
||||
/// A bone inside a shape, its unlocked armature layer and the armature.
|
||||
fn shape_bone(s: &Session, id: BoneId) -> Result<(LayerId, Arc<Armature>)> {
|
||||
/// A bone inside a shape, its unlocked armature layer, the armature and the shape.
|
||||
fn shape_bone(s: &Session, id: BoneId) -> Result<(LayerId, Arc<Armature>, ElementId)> {
|
||||
let (lid, arm) = find_bone(s, id)?;
|
||||
unlocked(s, lid)?;
|
||||
if arm.skin.is_none() {
|
||||
return Err(EngineError::State("that bone joins symbol instances: only bones inside a shape have weights on its points".into()));
|
||||
}
|
||||
Ok((lid, arm))
|
||||
let sh = shape_of(&arm, id, "have weights on its points")?;
|
||||
Ok((lid, arm, sh))
|
||||
}
|
||||
|
||||
fn paint_weights(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -812,19 +926,19 @@ fn paint_weights(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some(m) => Brush::parse(m).ok_or_else(|| EngineError::Param("param 'mode' must be \"add\", \"subtract\" or \"smooth\"".into()))?,
|
||||
};
|
||||
let frame = opt_u32(p, "frame")?.unwrap_or(s.frame).min(MAX_FRAME);
|
||||
let (lid, arm) = shape_bone(s, id)?;
|
||||
let (lid, arm, sh) = shape_bone(s, id)?;
|
||||
// The points where the stage shows them at the frame: the brush paints what the artist sees.
|
||||
let shown = s.timeline().layer(lid).and_then(|l| evaluate_layer_elements(l, frame)).map(|(_, els)| skin::points_shown(&arm, &els)).unwrap_or_default();
|
||||
let shown = s.timeline().layer(lid).and_then(|l| evaluate_layer_elements(l, frame)).zip(arm.skin(sh)).map(|((_, els), k)| skin::points_shown(k, &els)).unwrap_or_default();
|
||||
if shown.is_empty() {
|
||||
return Err(EngineError::State(format!("the bone's shape isn't on the stage at frame {}", frame + 1)));
|
||||
}
|
||||
let mut arm = (*arm).clone();
|
||||
let segments = skin::rest_segments(&arm);
|
||||
let changed = match arm.skin.as_mut() {
|
||||
let segments = skin::rest_segments(&arm, sh);
|
||||
let changed = match arm.skin_mut(sh) {
|
||||
Some(k) => weights::paint(k, &segments, &shown, id, &dabs, Dab { brush, radius, strength: strength / 100.0 }),
|
||||
None => 0,
|
||||
};
|
||||
let bound = bound_count(&arm, id);
|
||||
let bound = arm.bound_count(id);
|
||||
if changed > 0 {
|
||||
let l = s.layer_mut(Some(lid))?;
|
||||
l.armature = Some(Arc::new(arm));
|
||||
@@ -839,12 +953,12 @@ fn set_weight(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !(0.0..=100.0).contains(&w) {
|
||||
return Err(EngineError::Param("param 'weight' must be between 0 and 100".into()));
|
||||
}
|
||||
let (lid, arm) = shape_bone(s, id)?;
|
||||
let n = arm.skin.as_ref().map_or(0, |k| k.points.len());
|
||||
let (lid, arm, sh) = shape_bone(s, id)?;
|
||||
let n = arm.skin(sh).map_or(0, |k| k.points.len());
|
||||
let points = point_list(p, "points", n)?;
|
||||
let mut arm = (*arm).clone();
|
||||
let segments = skin::rest_segments(&arm);
|
||||
let Some(k) = arm.skin.as_mut() else { return Err(EngineError::State("that bone isn't inside a shape".into())) };
|
||||
let segments = skin::rest_segments(&arm, sh);
|
||||
let Some(k) = arm.skin_mut(sh) else { return Err(EngineError::State("that bone isn't inside a shape".into())) };
|
||||
let rest = skin::anchors(&k.rest);
|
||||
let mut changed = 0usize;
|
||||
for &i in &points {
|
||||
@@ -856,17 +970,17 @@ fn set_weight(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let shares: Vec<Value> = points.iter().map(|&i| json!(k.points.get(i).map(|b| b.bones.iter().map(|x| json!([x.0.0, x.1 * 100.0])).collect::<Vec<_>>()).unwrap_or_default())).collect();
|
||||
let bound = bound_count(&arm, id);
|
||||
let bound = arm.bound_count(id);
|
||||
let l = s.layer_mut(Some(lid))?;
|
||||
l.armature = Some(Arc::new(arm));
|
||||
rebake(l);
|
||||
Ok(json!({"bone": id.0, "changed": changed, "bound": bound, "weights": shares}))
|
||||
}
|
||||
|
||||
/// Whether element `id` is the shape of the shape armature on the active layer (so point edits
|
||||
/// reshape the skin instead of a keyframe's artwork).
|
||||
/// Whether element `id` is a shape with bones inside it on the active layer (so point edits
|
||||
/// reshape its skin instead of a keyframe's artwork).
|
||||
pub(crate) fn is_skin_shape(s: &Session, id: ElementId) -> bool {
|
||||
s.timeline().layer(s.layer).is_some_and(|l| l.kind == LayerKind::Armature && l.armature.as_ref().and_then(|a| a.skin_shape()) == Some(id))
|
||||
s.timeline().layer(s.layer).is_some_and(|l| l.kind == LayerKind::Armature && l.armature.as_ref().is_some_and(|a| a.skin(id).is_some()))
|
||||
}
|
||||
|
||||
/// Reshaping a bound shape (ADR 0090): `edit` changes the shape's outline as drawn (its rest
|
||||
@@ -880,9 +994,9 @@ pub(crate) fn reshape<T>(s: &mut Session, id: ElementId, edit: impl FnOnce(&mut
|
||||
let tl = s.timeline();
|
||||
let l = tl.layer(lid).ok_or_else(|| EngineError::State("the armature layer went away".into()))?;
|
||||
let arm = l.armature.clone().ok_or_else(|| EngineError::State("that is not an armature layer".into()))?;
|
||||
let k = arm.skin.as_ref().filter(|k| k.shape == id).ok_or_else(|| EngineError::State("that shape isn't the armature's".into()))?;
|
||||
let k = arm.skin(id).ok_or_else(|| EngineError::State("that shape isn't the armature's".into()))?;
|
||||
let pose = armature::pose_at(l, frame).ok_or_else(|| EngineError::State(format!("the armature isn't on frame {}", frame + 1)))?;
|
||||
if skin::matrices(&arm, &pose).values().any(|m| *m != Affine::IDENTITY) {
|
||||
if skin::matrices(&arm, k, &pose).values().any(|m| *m != Affine::IDENTITY) {
|
||||
return Err(EngineError::State("reshape a shape with bones at its rest pose: go to a frame where every bone is as drawn (angle 0, no slide), or pose them back".into()));
|
||||
}
|
||||
let (_, els) = evaluate_layer_elements(l, frame).ok_or_else(|| EngineError::State(format!("the armature isn't on frame {}", frame + 1)))?;
|
||||
@@ -898,9 +1012,11 @@ pub(crate) fn reshape<T>(s: &mut Session, id: ElementId, edit: impl FnOnce(&mut
|
||||
if n > MAX_SKIN_POINTS {
|
||||
return Err(EngineError::State(format!("a shape with bones has at most {MAX_SKIN_POINTS} points")));
|
||||
}
|
||||
let skin = weights::reshaped(k, shape.path.clone(), &skin::rest_segments(&arm));
|
||||
let skin = weights::reshaped(k, shape.path.clone(), &skin::rest_segments(&arm, id));
|
||||
let mut arm = (*arm).clone();
|
||||
arm.skin = Some(skin);
|
||||
if let Some(slot) = arm.skin_mut(id) {
|
||||
*slot = skin;
|
||||
}
|
||||
let l = s.layer_mut(Some(lid))?;
|
||||
l.armature = Some(Arc::new(arm));
|
||||
rebake(l);
|
||||
|
||||
@@ -953,15 +953,17 @@ fn break_apart(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
objects.push(c);
|
||||
continue;
|
||||
}
|
||||
// Text breaks apart into a shape with the same outlines.
|
||||
// Text breaks apart into shapes with the same outlines, one per colour (ADR 0085).
|
||||
if let ElementKind::Text(t) = &e.kind
|
||||
&& sel.contains(&e.id)
|
||||
{
|
||||
let mut c = (*e).clone();
|
||||
c.id = ElementId(s.doc.alloc_id());
|
||||
c.kind = ElementKind::Shape(crate::cmds_text::to_shape(t));
|
||||
fresh_ids.push(c.id);
|
||||
out.push(Arc::new(c));
|
||||
for shape in crate::cmds_text::to_shapes(t) {
|
||||
let mut c = (*e).clone();
|
||||
c.id = ElementId(s.doc.alloc_id());
|
||||
c.kind = ElementKind::Shape(shape);
|
||||
fresh_ids.push(c.id);
|
||||
out.push(Arc::new(c));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A group breaks apart into its members (Animate's Ctrl+B on a group ungroups it).
|
||||
|
||||
+540
-199
@@ -8,16 +8,24 @@
|
||||
//! Text on a path (ADR 0070): `text.attach_path` sets static text along a shape's outline (a
|
||||
//! copy of it, in the text's own space), `text.path` moves it along, flips it or releases it.
|
||||
//! The glyphs are set by arc length and stored as outlines, as all text is.
|
||||
//!
|
||||
//! Styled text (ADR 0085): a block's characters come in runs with their own font, size, style,
|
||||
//! colour, letter spacing, baseline shift, underline and link, and its paragraphs have their own
|
||||
//! alignment, indent, margins and line spacing. `text.style` styles a range of characters,
|
||||
//! `text.paragraph` the paragraphs a range touches, `text.styles` reads them back (mixed values
|
||||
//! as `null`); `text.edit` keeps the runs through a change of text (typing continues the style
|
||||
//! before it) or takes new ones. Every layout here goes through [`lay_out_block`].
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, FIELD_GUTTER, LineType, MAX_FIELD_CHARS, MAX_FIELD_NAME, MAX_PATH_OFFSET, Rgba, TextAlign, TextBlock, TextField, TextKind, TextPath};
|
||||
use anicraft_doc::rich_text::{self as rt, StyleSummary};
|
||||
use anicraft_doc::{BaselineShift, CharStyle, ColorEffect, Element, ElementId, ElementKind, FIELD_GUTTER, LineType, MAX_FIELD_CHARS, MAX_FIELD_NAME, MAX_PATH_OFFSET, MAX_TEXT_RUNS, MAX_URL, ParagraphStyle, Rgba, TextAlign, TextBlock, TextField, TextKind, TextPath, TextRun};
|
||||
use anicraft_geom::{Affine, Path, Vec2};
|
||||
use anicraft_text::{Align, Fonts};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The text style new text gets: the last one used.
|
||||
/// The text style new text gets: the last one used, as in Animate.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TextStyle {
|
||||
pub font: String,
|
||||
@@ -36,12 +44,18 @@ impl Default for TextStyle {
|
||||
}
|
||||
}
|
||||
|
||||
const CHAR_KEYS: &str = "font?, size? (px), bold?, italic?, color?, letter_spacing?, shift?: normal|superscript|subscript, underline?, url? (\"\": none)";
|
||||
const PARA_KEYS: &str = "align?: left|center|right, indent? (px, first line), left_margin?, right_margin? (px), line_spacing? (px)";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
let leak = |s: String| -> &'static str { Box::leak(s.into_boxed_str()) };
|
||||
vec![
|
||||
c("text.create", "New Text", "", None, "{text (may be empty for an input field), type?: static|dynamic|input, x?, y? (top-left; default: centred), font?, size?, bold?, italic?, color?, align?, letter_spacing?, line_spacing?, width?}", true, create as crate::RunFn),
|
||||
c("text.edit", "Edit Text", "", None, "{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text", true, |s, p| s.each_layer(false, |s| edit(s, p))),
|
||||
c("text.create", "New Text", "", None, leak(format!("{{text (may be empty for an input field), type?: static|dynamic|input, x?, y? (top-left; default: centred), width?, {CHAR_KEYS}, {PARA_KEYS}, runs?: [{{chars, …character keys}}] (styles of the text's characters in order; unset keys take the style above), paragraphs?: [{{…paragraph keys}}] (one per line of the text)}} (ADR 0085)")), true, create as crate::RunFn),
|
||||
c("text.edit", "Edit Text", "", None, leak(format!("{{text? (the runs follow the change: typed characters continue the style before them), runs?, paragraphs? (as text.create: replace the styles), width? (px, wraps; null: one line per paragraph), {CHAR_KEYS} (every character), {PARA_KEYS} (every paragraph)}} on the selected text")), true, |s, p| s.each_layer(false, |s| edit(s, p))),
|
||||
c("text.style", "Text Character Style", "", None, leak(format!("{{start?, end? (characters; default: all), {CHAR_KEYS}}} styles those characters of the selected text, splitting and joining its runs (ADR 0085)")), true, |s, p| s.each_layer(false, |s| style_range(s, p))),
|
||||
c("text.paragraph", "Text Paragraph Style", "", None, leak(format!("{{start?, end? (characters; default: all), {PARA_KEYS}}} sets the layout of the paragraphs those characters touch in the selected text (ADR 0085)")), true, |s, p| s.each_layer(false, |s| paragraph_range(s, p))),
|
||||
c("text.styles", "Text Styles", "", None, "{start?, end? (characters; default: all)} of the first selected text: its runs, paragraphs, and what those characters share (a mixed value is null) (ADR 0085)", false, styles_of),
|
||||
c("text.fonts", "Fonts", "", None, "{}", false, fonts),
|
||||
c(
|
||||
"text.attach_path",
|
||||
@@ -58,13 +72,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
]
|
||||
}
|
||||
|
||||
fn align_param(p: &Value) -> Result<Option<TextAlign>> {
|
||||
Ok(match opt_str(p, "align")? {
|
||||
fn align_of(p: &Value, key: &str) -> Result<Option<TextAlign>> {
|
||||
Ok(match opt_str(p, key)? {
|
||||
None => None,
|
||||
Some("left") => Some(TextAlign::Left),
|
||||
Some("center" | "centre") => Some(TextAlign::Center),
|
||||
Some("right") => Some(TextAlign::Right),
|
||||
Some(other) => return Err(EngineError::Param(format!("'align' is left, center or right, not '{other}'"))),
|
||||
Some(other) => return Err(EngineError::Param(format!("'{key}' is left, center or right, not '{other}'"))),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -80,102 +94,284 @@ fn width_param(p: &Value, current: Option<f32>) -> Result<Option<f32>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The style in `p` over `base`.
|
||||
fn style_param(p: &Value, base: &TextStyle) -> Result<TextStyle> {
|
||||
let size = opt_f32(p, "size")?.unwrap_or(base.size);
|
||||
if !(1.0..=2000.0).contains(&size) {
|
||||
return Err(EngineError::Param("'size' must be between 1 and 2000 px".into()));
|
||||
fn ranged(p: &Value, key: &str, lo: f32, hi: f32) -> Result<Option<f32>> {
|
||||
match opt_f32(p, key)? {
|
||||
Some(v) if !(lo..=hi).contains(&v) => Err(EngineError::Param(format!("'{key}' must be between {lo} and {hi} px"))),
|
||||
v => Ok(v),
|
||||
}
|
||||
let spacing = |key: &str, d: f32| -> Result<f32> {
|
||||
let v = opt_f32(p, key)?.unwrap_or(d);
|
||||
if (-1000.0..=1000.0).contains(&v) { Ok(v) } else { Err(EngineError::Param(format!("'{key}' must be between -1000 and 1000 px"))) }
|
||||
};
|
||||
Ok(TextStyle {
|
||||
font: opt_str(p, "font")?.map_or_else(|| base.font.clone(), |f| f.chars().take(256).collect()),
|
||||
size,
|
||||
bold: opt_bool(p, "bold")?.unwrap_or(base.bold),
|
||||
italic: opt_bool(p, "italic")?.unwrap_or(base.italic),
|
||||
color: opt_color(p, "color")?.unwrap_or(base.color),
|
||||
align: align_param(p)?.unwrap_or(base.align),
|
||||
letter_spacing: spacing("letter_spacing", base.letter_spacing)?,
|
||||
line_spacing: spacing("line_spacing", base.line_spacing)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Lays a block out with this computer's fonts. Also says when the family asked for isn't
|
||||
/// installed and another was used.
|
||||
pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option<f32>) -> Result<(TextBlock, Option<String>)> {
|
||||
/// Character style keys in a command's params: each one given changes that attribute only.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct CharPatch {
|
||||
pub font: Option<String>,
|
||||
pub size: Option<f32>,
|
||||
pub bold: Option<bool>,
|
||||
pub italic: Option<bool>,
|
||||
pub color: Option<Rgba>,
|
||||
pub letter_spacing: Option<f32>,
|
||||
pub shift: Option<BaselineShift>,
|
||||
pub underline: Option<bool>,
|
||||
pub url: Option<String>,
|
||||
}
|
||||
|
||||
impl CharPatch {
|
||||
pub fn parse(p: &Value) -> Result<CharPatch> {
|
||||
let shift = opt_str(p, "shift")?.map(|k| BaselineShift::from_key(k).ok_or_else(|| EngineError::Param(format!("'shift' is normal, superscript or subscript, not '{k}'")))).transpose()?;
|
||||
let url = match opt_str(p, "url")? {
|
||||
None => None,
|
||||
Some(u) if u.chars().count() > MAX_URL => return Err(EngineError::Param(format!("'url' is at most {MAX_URL} characters"))),
|
||||
Some(u) => Some(rt::safe_url(u).ok_or_else(|| EngineError::Param("'url' can't run script (javascript:, vbscript: and data: links aren't allowed)".into()))?),
|
||||
};
|
||||
Ok(CharPatch {
|
||||
font: opt_str(p, "font")?.map(|f| f.chars().take(256).collect()),
|
||||
size: ranged(p, "size", 1.0, 2000.0)?,
|
||||
bold: opt_bool(p, "bold")?,
|
||||
italic: opt_bool(p, "italic")?,
|
||||
color: opt_color(p, "color")?,
|
||||
letter_spacing: ranged(p, "letter_spacing", -1000.0, 1000.0)?,
|
||||
shift,
|
||||
underline: opt_bool(p, "underline")?,
|
||||
url,
|
||||
})
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
*self == CharPatch::default()
|
||||
}
|
||||
pub fn apply(&self, s: &mut CharStyle) {
|
||||
if let Some(v) = &self.font {
|
||||
s.font.clone_from(v);
|
||||
}
|
||||
if let Some(v) = self.size {
|
||||
s.size = v;
|
||||
}
|
||||
if let Some(v) = self.bold {
|
||||
s.bold = v;
|
||||
}
|
||||
if let Some(v) = self.italic {
|
||||
s.italic = v;
|
||||
}
|
||||
if let Some(v) = self.color {
|
||||
s.color = v;
|
||||
}
|
||||
if let Some(v) = self.letter_spacing {
|
||||
s.letter_spacing = v;
|
||||
}
|
||||
if let Some(v) = self.shift {
|
||||
s.shift = v;
|
||||
}
|
||||
if let Some(v) = self.underline {
|
||||
s.underline = v;
|
||||
}
|
||||
if let Some(v) = &self.url {
|
||||
s.url.clone_from(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Paragraph style keys in a command's params.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ParaPatch {
|
||||
pub align: Option<TextAlign>,
|
||||
pub indent: Option<f32>,
|
||||
pub left_margin: Option<f32>,
|
||||
pub right_margin: Option<f32>,
|
||||
pub line_spacing: Option<f32>,
|
||||
}
|
||||
|
||||
impl ParaPatch {
|
||||
pub fn parse(p: &Value) -> Result<ParaPatch> {
|
||||
Ok(ParaPatch {
|
||||
align: align_of(p, "align")?,
|
||||
indent: ranged(p, "indent", -1000.0, 1000.0)?,
|
||||
left_margin: ranged(p, "left_margin", 0.0, 1000.0)?,
|
||||
right_margin: ranged(p, "right_margin", 0.0, 1000.0)?,
|
||||
line_spacing: ranged(p, "line_spacing", -1000.0, 1000.0)?,
|
||||
})
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
*self == ParaPatch::default()
|
||||
}
|
||||
pub fn apply(&self, s: &mut ParagraphStyle) {
|
||||
s.align = self.align.unwrap_or(s.align);
|
||||
s.indent = self.indent.unwrap_or(s.indent);
|
||||
s.left_margin = self.left_margin.unwrap_or(s.left_margin);
|
||||
s.right_margin = self.right_margin.unwrap_or(s.right_margin);
|
||||
s.line_spacing = self.line_spacing.unwrap_or(s.line_spacing);
|
||||
}
|
||||
}
|
||||
|
||||
/// `runs: [{chars, …character keys}]` over `base` (unset keys take it), at most
|
||||
/// [`MAX_TEXT_RUNS`] of them.
|
||||
fn runs_param(p: &Value, base: &CharStyle) -> Result<Option<Vec<TextRun>>> {
|
||||
let Some(v) = p.get("runs").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let list = v.as_array().ok_or_else(|| EngineError::Param("'runs' must be a list of {chars, …style}".into()))?;
|
||||
if list.len() > MAX_TEXT_RUNS {
|
||||
return Err(EngineError::Param(format!("'runs' has at most {MAX_TEXT_RUNS} runs")));
|
||||
}
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
for r in list {
|
||||
let chars = opt_u32(r, "chars")?.ok_or_else(|| EngineError::Param("each run needs 'chars' (how many characters it styles)".into()))?;
|
||||
let mut style = base.clone();
|
||||
CharPatch::parse(r)?.apply(&mut style);
|
||||
out.push(TextRun { chars, style });
|
||||
}
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// `paragraphs: [{…paragraph keys}]` over `base`.
|
||||
fn paragraphs_param(p: &Value, base: &ParagraphStyle) -> Result<Option<Vec<ParagraphStyle>>> {
|
||||
let Some(v) = p.get("paragraphs").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
let list = v.as_array().ok_or_else(|| EngineError::Param("'paragraphs' must be a list of {align?, indent?, …}".into()))?;
|
||||
if list.len() > anicraft_text::MAX_CHARS + 1 {
|
||||
return Err(EngineError::Param("'paragraphs' has more entries than a block has lines".into()));
|
||||
}
|
||||
list.iter()
|
||||
.map(|q| {
|
||||
let mut s = *base;
|
||||
ParaPatch::parse(q)?.apply(&mut s);
|
||||
Ok(s)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
/// `start`, `end` (characters, default the whole text), clamped to `n`.
|
||||
fn range_param(p: &Value, n: u32) -> Result<(u32, u32)> {
|
||||
let start = opt_u32(p, "start")?.unwrap_or(0).min(n);
|
||||
let end = opt_u32(p, "end")?.unwrap_or(n).min(n);
|
||||
if end < start {
|
||||
return Err(EngineError::Param("'end' comes before 'start'".into()));
|
||||
}
|
||||
Ok((start, end))
|
||||
}
|
||||
|
||||
fn align_text(a: TextAlign) -> Align {
|
||||
match a {
|
||||
TextAlign::Left => Align::Left,
|
||||
TextAlign::Center => Align::Center,
|
||||
TextAlign::Right => Align::Right,
|
||||
}
|
||||
}
|
||||
|
||||
/// `d`'s runs and paragraphs as the text engine takes them, and the paints (colour, link) the
|
||||
/// runs' `paint` numbers stand for.
|
||||
fn rich_parts(d: &TextBlock) -> (Vec<anicraft_text::Run>, Vec<anicraft_text::ParaStyle>, Vec<(Rgba, String)>) {
|
||||
let mut paints: Vec<(Rgba, String)> = Vec::new();
|
||||
let runs = d
|
||||
.styled_runs()
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let key = (r.style.color, r.style.url.clone());
|
||||
let paint = match paints.iter().position(|k| *k == key) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
paints.push(key);
|
||||
paints.len() - 1
|
||||
}
|
||||
} as u32;
|
||||
let shift = match r.style.shift {
|
||||
BaselineShift::Normal => anicraft_text::Shift::Normal,
|
||||
BaselineShift::Superscript => anicraft_text::Shift::Superscript,
|
||||
BaselineShift::Subscript => anicraft_text::Shift::Subscript,
|
||||
};
|
||||
anicraft_text::Run {
|
||||
chars: r.chars as usize,
|
||||
style: anicraft_text::RunStyle { family: r.style.font, size: r.style.size, bold: r.style.bold, italic: r.style.italic, letter_spacing: r.style.letter_spacing, shift, underline: r.style.underline, paint },
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let paras = d
|
||||
.paragraph_styles()
|
||||
.into_iter()
|
||||
.map(|p| anicraft_text::ParaStyle { align: align_text(p.align), indent: p.indent, left_margin: p.left_margin, right_margin: p.right_margin, line_spacing: p.line_spacing })
|
||||
.collect();
|
||||
(runs, paras, paints)
|
||||
}
|
||||
|
||||
/// The block with its outline from laid-out pieces and its runs' fonts the families actually
|
||||
/// used; with a note when a family asked for isn't installed.
|
||||
fn finish(mut d: TextBlock, pieces: Vec<(u32, Path)>, families: &[String], paints: &[(Rgba, String)]) -> (TextBlock, Option<String>) {
|
||||
let mut note = None;
|
||||
let mut runs = d.styled_runs();
|
||||
for (r, used) in runs.iter_mut().zip(families) {
|
||||
let asked = r.style.font.trim();
|
||||
if note.is_none() && !asked.is_empty() && !used.eq_ignore_ascii_case(asked) {
|
||||
note = Some(format!("“{asked}” isn't installed on this computer; used {used}"));
|
||||
}
|
||||
r.style.font.clone_from(used);
|
||||
}
|
||||
let paras = d.paragraph_styles();
|
||||
d.set_styles(runs, paras);
|
||||
let pieces = pieces.into_iter().map(|(k, p)| paints.get(k as usize).map_or((d.color, String::new(), p.clone()), |(c, u)| (*c, u.clone(), p))).collect();
|
||||
d.set_outline(pieces);
|
||||
(d, note)
|
||||
}
|
||||
|
||||
fn layout_err(e: anicraft_text::TextError) -> EngineError {
|
||||
EngineError::State(format!("can't lay out text: {e}"))
|
||||
}
|
||||
|
||||
/// Lays out a block from its text, runs, paragraphs and width, as static text, a field (in its
|
||||
/// box) or text on a path, with the fonts on this computer. Returns the laid-out block, a note
|
||||
/// when a family wasn't installed, and (text on a path) where the block's origin moved to,
|
||||
/// which the element's transform must move by for nothing to move (`transform ×
|
||||
/// translate(shift)`; zero otherwise).
|
||||
pub(crate) fn lay_out_block(d: &TextBlock) -> Result<(TextBlock, Option<String>, Vec2)> {
|
||||
let fonts = Fonts::get();
|
||||
let layout = fonts
|
||||
.layout(
|
||||
text,
|
||||
&anicraft_text::Style {
|
||||
family: style.font.clone(),
|
||||
size: style.size,
|
||||
bold: style.bold,
|
||||
italic: style.italic,
|
||||
align: match style.align {
|
||||
TextAlign::Left => Align::Left,
|
||||
TextAlign::Center => Align::Center,
|
||||
TextAlign::Right => Align::Right,
|
||||
},
|
||||
letter_spacing: style.letter_spacing,
|
||||
line_spacing: style.line_spacing,
|
||||
width,
|
||||
},
|
||||
)
|
||||
.map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?;
|
||||
let note = (!style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family));
|
||||
let block = TextBlock {
|
||||
text: text.to_string(),
|
||||
font: layout.family,
|
||||
size: style.size,
|
||||
bold: style.bold,
|
||||
italic: style.italic,
|
||||
color: style.color,
|
||||
align: style.align,
|
||||
letter_spacing: style.letter_spacing,
|
||||
line_spacing: style.line_spacing,
|
||||
width,
|
||||
outline: Arc::new(layout.outline),
|
||||
box_width: layout.width,
|
||||
box_height: layout.height,
|
||||
field: None,
|
||||
on_path: None,
|
||||
};
|
||||
Ok((block, note))
|
||||
let mut d = d.clone();
|
||||
let (runs, paras, paints) = rich_parts(&d);
|
||||
match (d.field.clone(), d.on_path.clone()) {
|
||||
(_, Some(on)) => {
|
||||
// One line along the path (line breaks become spaces), anchored by the alignment.
|
||||
let line: String = d.text.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect();
|
||||
let l = fonts.layout_rich(&anicraft_text::RichText { text: &line, runs: &runs, paragraphs: &[anicraft_text::ParaStyle::default()], width: None }, true).map_err(layout_err)?;
|
||||
let offset = if on.offset.is_finite() { on.offset.clamp(-MAX_PATH_OFFSET, MAX_PATH_OFFSET) } else { 0.0 };
|
||||
let set = anicraft_text::on_path_boxed(&l.glyphs, &on.path, anicraft_text::PathPlacement { offset, flip: on.flip, align: align_text(d.align) }).ok_or_else(|| EngineError::State("the path has no length to set text along".into()))?;
|
||||
d.width = None;
|
||||
d.field = None;
|
||||
d.box_width = set.width;
|
||||
d.box_height = set.height;
|
||||
d.on_path = Some(TextPath { path: set.path, offset, flip: on.flip });
|
||||
let shift = set.shift;
|
||||
let (b, n) = finish(d, set.pieces, &l.families, &paints);
|
||||
Ok((b, n, shift))
|
||||
}
|
||||
(Some(f), None) => {
|
||||
d.text = d.text.chars().take(MAX_FIELD_CHARS).collect();
|
||||
let (runs, paras, paints) = rich_parts(&d);
|
||||
let shown = f.shown(&d.text);
|
||||
let l = field_lay(fonts, &anicraft_text::RichText { text: &shown, runs: &runs, paragraphs: ¶s, width: f.wrap_width(d.box_width) }, d.align, &f, d.box_width).map_err(layout_err)?;
|
||||
d.width = f.wrap_width(d.box_width);
|
||||
let (b, n) = finish(d, l.pieces, &l.families, &paints);
|
||||
Ok((b, n, Vec2::ZERO))
|
||||
}
|
||||
(None, None) => {
|
||||
let l = fonts.layout_rich(&anicraft_text::RichText { text: &d.text, runs: &runs, paragraphs: ¶s, width: d.width }, false).map_err(layout_err)?;
|
||||
d.box_width = l.width;
|
||||
d.box_height = l.height;
|
||||
let (b, n) = finish(d, l.pieces, &l.families, &paints);
|
||||
Ok((b, n, Vec2::ZERO))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A field's text laid out (ADR 0066): `shown` in the block's style, wrapped at the box less its
|
||||
/// gutters when it is multiline, aligned in the box, with the outline moved into the gutter.
|
||||
/// The carets are from the text's left edge (the alignment applied, not the gutter).
|
||||
pub fn field_layout(fonts: &Fonts, style: &TextStyle, field: &TextField, box_width: f32, shown: &str) -> std::result::Result<anicraft_text::Layout, anicraft_text::TextError> {
|
||||
let wrap = field.wrap_width(box_width);
|
||||
let mut l = fonts.layout(
|
||||
shown,
|
||||
&anicraft_text::Style {
|
||||
family: style.font.clone(),
|
||||
size: style.size,
|
||||
bold: style.bold,
|
||||
italic: style.italic,
|
||||
align: match style.align {
|
||||
TextAlign::Left => Align::Left,
|
||||
TextAlign::Center => Align::Center,
|
||||
TextAlign::Right => Align::Right,
|
||||
},
|
||||
letter_spacing: style.letter_spacing,
|
||||
line_spacing: style.line_spacing,
|
||||
width: wrap,
|
||||
},
|
||||
)?;
|
||||
// Lines that don't wrap align against the widest; the widest aligns in the box.
|
||||
/// A field's rich text laid out in its box (ADR 0066): wrapped at the box less its gutters
|
||||
/// when multiline, the widest line aligned in the box when it doesn't wrap, and the outline
|
||||
/// (and its pieces) moved into the gutter. The carets are from the text's left edge.
|
||||
fn field_lay(fonts: &Fonts, rich: &anicraft_text::RichText, align: TextAlign, field: &TextField, box_width: f32) -> std::result::Result<anicraft_text::Layout, anicraft_text::TextError> {
|
||||
let mut l = fonts.layout_rich(rich, false)?;
|
||||
let inner = (box_width - 2.0 * FIELD_GUTTER).max(0.0);
|
||||
let shift = match (wrap, style.align) {
|
||||
let shift = match (field.wrap_width(box_width), align) {
|
||||
(Some(_), _) | (None, TextAlign::Left) => 0.0,
|
||||
(None, TextAlign::Center) => ((inner - l.width) * 0.5).max(0.0),
|
||||
(None, TextAlign::Right) => (inner - l.width).max(0.0),
|
||||
};
|
||||
l.outline = l.outline.transformed(&Affine::translate(FIELD_GUTTER + shift, FIELD_GUTTER));
|
||||
let to = Affine::translate(FIELD_GUTTER + shift, FIELD_GUTTER);
|
||||
l.outline = l.outline.transformed(&to);
|
||||
for (_, p) in &mut l.pieces {
|
||||
*p = p.transformed(&to);
|
||||
}
|
||||
if shift != 0.0 {
|
||||
for line in &mut l.carets {
|
||||
for s in &mut line.stops {
|
||||
@@ -187,89 +383,46 @@ pub fn field_layout(fonts: &Fonts, style: &TextStyle, field: &TextField, box_wid
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
/// A field block for `text`: laid out in its box (`box_width` × `box_height`).
|
||||
pub(crate) fn lay_out_field(text: &str, style: &TextStyle, field: &TextField, box_width: f32, box_height: f32) -> Result<(TextBlock, Option<String>)> {
|
||||
let fonts = Fonts::get();
|
||||
let text: String = text.chars().take(MAX_FIELD_CHARS).collect();
|
||||
let l = field_layout(fonts, style, field, box_width, &field.shown(&text)).map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?;
|
||||
let note = (!style.font.trim().is_empty() && !l.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), l.family));
|
||||
let block = TextBlock {
|
||||
text,
|
||||
font: l.family,
|
||||
size: style.size,
|
||||
bold: style.bold,
|
||||
italic: style.italic,
|
||||
color: style.color,
|
||||
align: style.align,
|
||||
letter_spacing: style.letter_spacing,
|
||||
line_spacing: style.line_spacing,
|
||||
width: field.wrap_width(box_width),
|
||||
outline: Arc::new(l.outline),
|
||||
box_width,
|
||||
box_height,
|
||||
field: Some(field.clone()),
|
||||
on_path: None,
|
||||
};
|
||||
Ok((block, note))
|
||||
/// A field's text laid out in one style, as the player lays out text a script set or a viewer
|
||||
/// typed (ADR 0066).
|
||||
pub fn field_layout(fonts: &Fonts, style: &TextStyle, field: &TextField, box_width: f32, shown: &str) -> std::result::Result<anicraft_text::Layout, anicraft_text::TextError> {
|
||||
let run = anicraft_text::Run { chars: usize::MAX, style: anicraft_text::RunStyle { family: style.font.clone(), size: style.size, bold: style.bold, italic: style.italic, letter_spacing: style.letter_spacing, ..anicraft_text::RunStyle::default() } };
|
||||
let para = anicraft_text::ParaStyle { align: align_text(style.align), line_spacing: style.line_spacing, ..anicraft_text::ParaStyle::default() };
|
||||
field_lay(fonts, &anicraft_text::RichText { text: shown, runs: &[run], paragraphs: &[para], width: field.wrap_width(box_width) }, style.align, field, box_width)
|
||||
}
|
||||
|
||||
/// Text on a path (ADR 0070): `text` on one line (line breaks become spaces) set along `on`'s
|
||||
/// path. The block's space is moved so its box (the path and the glyphs together) starts at
|
||||
/// the origin, as every text box does: the second value is where that origin was, which the
|
||||
/// element's transform must move by (`transform × translate(shift)`) for nothing to move.
|
||||
pub(crate) fn lay_out_on_path(text: &str, style: &TextStyle, on: &TextPath) -> Result<(TextBlock, Option<String>, Vec2)> {
|
||||
let fonts = Fonts::get();
|
||||
let line: String = text.chars().map(|c| if c == '\n' || c == '\r' { ' ' } else { c }).collect();
|
||||
let layout = fonts
|
||||
.layout_glyphs(&line, &anicraft_text::Style { family: style.font.clone(), size: style.size, bold: style.bold, italic: style.italic, align: Align::Left, letter_spacing: style.letter_spacing, line_spacing: 0.0, width: None })
|
||||
.map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?;
|
||||
let note = (!style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family));
|
||||
let align = match style.align {
|
||||
TextAlign::Left => Align::Left,
|
||||
TextAlign::Center => Align::Center,
|
||||
TextAlign::Right => Align::Right,
|
||||
};
|
||||
let offset = if on.offset.is_finite() { on.offset.clamp(-MAX_PATH_OFFSET, MAX_PATH_OFFSET) } else { 0.0 };
|
||||
let set = anicraft_text::on_path_boxed(&layout.glyphs, &on.path, anicraft_text::PathPlacement { offset, flip: on.flip, align }).ok_or_else(|| EngineError::State("the path has no length to set text along".into()))?;
|
||||
let shift = set.shift;
|
||||
let block = TextBlock {
|
||||
text: text.to_string(),
|
||||
font: layout.family,
|
||||
size: style.size,
|
||||
bold: style.bold,
|
||||
italic: style.italic,
|
||||
color: style.color,
|
||||
align: style.align,
|
||||
letter_spacing: style.letter_spacing,
|
||||
line_spacing: style.line_spacing,
|
||||
width: None,
|
||||
outline: Arc::new(set.outline),
|
||||
box_width: set.width,
|
||||
box_height: set.height,
|
||||
field: None,
|
||||
on_path: Some(TextPath { path: set.path, offset, flip: on.flip }),
|
||||
};
|
||||
Ok((block, note, shift))
|
||||
}
|
||||
|
||||
/// The block `t` with new text or style: a field keeps its box (or takes `width` as its new
|
||||
/// width); static text wraps at `width`; text on a path stays on it. With where the block's
|
||||
/// origin moved to ([`lay_out_on_path`]; zero for the others).
|
||||
pub(crate) fn relay(t: &TextBlock, text: &str, style: &TextStyle, width: Option<f32>) -> Result<(TextBlock, Option<String>, Vec2)> {
|
||||
match (&t.field, &t.on_path) {
|
||||
(_, Some(on)) => lay_out_on_path(text, style, on),
|
||||
(Some(f), None) => lay_out_field(text, style, f, width.unwrap_or(t.box_width), t.box_height).map(|(b, n)| (b, n, Vec2::ZERO)),
|
||||
(None, None) => lay_out(text, style, width).map(|(b, n)| (b, n, Vec2::ZERO)),
|
||||
/// `t` with its text changed to `text`, its runs and paragraphs following the change (one
|
||||
/// edit: what was typed continues the style before it).
|
||||
pub(crate) fn retext(t: &TextBlock, text: &str) -> TextBlock {
|
||||
let mut d = t.clone();
|
||||
if d.text == text {
|
||||
return d;
|
||||
}
|
||||
let (start, old_end, new_end) = rt::diff_chars(&t.text, text);
|
||||
let runs = rt::type_into_runs(&t.styled_runs(), start, old_end, new_end - start);
|
||||
let inserted: String = text.chars().skip(start as usize).take((new_end - start) as usize).collect();
|
||||
let paras = rt::edit_paragraphs(&t.paragraph_styles(), &t.text, start, old_end, &inserted);
|
||||
d.text = text.to_string();
|
||||
d.set_styles(runs, paras);
|
||||
d
|
||||
}
|
||||
|
||||
/// What Find and Replace lays text out with: as before (static text, its fields' boxes
|
||||
/// dropped), except that text on a path stays on its path.
|
||||
pub(crate) fn relay_static(t: &TextBlock, text: &str, style: &TextStyle) -> Result<(TextBlock, Option<String>, Vec2)> {
|
||||
match &t.on_path {
|
||||
Some(on) => lay_out_on_path(text, style, on),
|
||||
None => lay_out(text, style, t.width).map(|(b, n)| (b, n, Vec2::ZERO)),
|
||||
}
|
||||
/// What Find and Replace lays text out with: the runs following the change, as static text
|
||||
/// (its fields' boxes dropped), except that text on a path stays on its path.
|
||||
pub(crate) fn relay_static(t: &TextBlock, text: &str) -> Result<(TextBlock, Option<String>, Vec2)> {
|
||||
let mut d = retext(t, text);
|
||||
d.field = None;
|
||||
lay_out_block(&d)
|
||||
}
|
||||
|
||||
/// `t` with every run's font set to `family`, laid out as [`relay_static`] does.
|
||||
pub(crate) fn refont_static(t: &TextBlock, family: &str) -> Result<(TextBlock, Option<String>, Vec2)> {
|
||||
let mut d = t.clone();
|
||||
let runs = rt::restyle_runs(&t.styled_runs(), 0, t.char_count(), |s| s.font = family.to_string());
|
||||
let paras = d.paragraph_styles();
|
||||
d.set_styles(runs, paras);
|
||||
d.field = None;
|
||||
lay_out_block(&d)
|
||||
}
|
||||
|
||||
/// The selected static text, along a copy of a shape's outline (ADR 0070).
|
||||
@@ -326,13 +479,12 @@ fn attach_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
continue;
|
||||
}
|
||||
let ElementKind::Text(t) = &e.kind else { continue };
|
||||
let style = style_of(t);
|
||||
let offset = offset.unwrap_or(match t.align {
|
||||
TextAlign::Left => 0.0,
|
||||
TextAlign::Center => length * 0.5,
|
||||
TextAlign::Right => length,
|
||||
});
|
||||
let (block, note, shift) = lay_out_on_path(&t.text, &style, &TextPath { path: first.clone(), offset, flip })?;
|
||||
let (block, note, shift) = lay_out_block(&TextBlock { field: None, width: None, on_path: Some(TextPath { path: first.clone(), offset, flip }), ..(**t).clone() })?;
|
||||
// The path is in stage space; the text's new space is the path's, moved to its box.
|
||||
e.transform = Affine::translate(shift.x, shift.y);
|
||||
out = json!({"element": e.id.0, "length": length, "offset": offset, "flip": flip, "note": note});
|
||||
@@ -354,17 +506,16 @@ fn set_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for e in s.selected_elements_mut()? {
|
||||
let ElementKind::Text(t) = &e.kind else { continue };
|
||||
let Some(on) = &t.on_path else { continue };
|
||||
let style = style_of(t);
|
||||
if release {
|
||||
// Back to a line of text, its box where the text started along the path.
|
||||
let start = t.outline.bounds();
|
||||
let (block, _) = lay_out(&t.text, &style, None)?;
|
||||
let (block, _, _) = lay_out_block(&TextBlock { on_path: None, width: None, ..(**t).clone() })?;
|
||||
let at = if start.min.x.is_finite() { start.min } else { Vec2::ZERO };
|
||||
e.transform = e.transform.mul(&Affine::translate(at.x, at.y));
|
||||
e.kind = ElementKind::Text(Arc::new(block));
|
||||
} else {
|
||||
let on = TextPath { offset: offset.unwrap_or(on.offset), flip: flip.unwrap_or(on.flip), ..on.clone() };
|
||||
let (block, _, shift) = lay_out_on_path(&t.text, &style, &on)?;
|
||||
let (block, _, shift) = lay_out_block(&TextBlock { on_path: Some(on), ..(**t).clone() })?;
|
||||
e.transform = e.transform.mul(&Affine::translate(shift.x, shift.y));
|
||||
e.kind = ElementKind::Text(Arc::new(block));
|
||||
}
|
||||
@@ -411,7 +562,6 @@ fn set_field(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::State("text on a path is static text (release it from the path first)".into()));
|
||||
}
|
||||
let to = kind.unwrap_or(t.kind());
|
||||
let style = style_of(t);
|
||||
let (block, note) = if to == TextKind::Static {
|
||||
if t.field.is_none() {
|
||||
continue;
|
||||
@@ -419,7 +569,8 @@ fn set_field(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Back to static text: laid out as before fields, the words where they were.
|
||||
e.transform = e.transform.mul(&Affine::translate(FIELD_GUTTER, FIELD_GUTTER));
|
||||
e.name.clear();
|
||||
lay_out(&t.text, &style, t.field.as_ref().and_then(|f| f.wrap_width(t.box_width)))?
|
||||
let (b, n, _) = lay_out_block(&TextBlock { field: None, width: t.field.as_ref().and_then(|f| f.wrap_width(t.box_width)), ..(**t).clone() })?;
|
||||
(b, n)
|
||||
} else {
|
||||
let (bw, bh) = if t.field.is_some() { (t.box_width, t.box_height) } else { field_box(t) };
|
||||
// Wrapped text becomes a multiline field, text with line breaks a multiline one
|
||||
@@ -455,7 +606,8 @@ fn set_field(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(v) = &variable {
|
||||
f.variable.clone_from(v);
|
||||
}
|
||||
lay_out_field(&t.text, &style, &f.sanitized(), width.unwrap_or(bw), height.unwrap_or(bh))?
|
||||
let (b, n, _) = lay_out_block(&TextBlock { field: Some(f.sanitized()), box_width: width.unwrap_or(bw), box_height: height.unwrap_or(bh), ..(**t).clone() })?;
|
||||
(b, n)
|
||||
};
|
||||
notes.extend(note);
|
||||
e.kind = ElementKind::Text(Arc::new(block));
|
||||
@@ -468,8 +620,19 @@ fn set_field(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"changed": changed, "note": notes.first()}))
|
||||
}
|
||||
|
||||
pub(crate) fn style_of(t: &TextBlock) -> TextStyle {
|
||||
TextStyle { font: t.font.clone(), size: t.size, bold: t.bold, italic: t.italic, color: t.color, align: t.align, letter_spacing: t.letter_spacing, line_spacing: t.line_spacing }
|
||||
|
||||
/// The style a block starts with: `base`, with the params' character and paragraph keys.
|
||||
fn new_style(p: &Value, base: &TextStyle) -> Result<(CharStyle, ParagraphStyle)> {
|
||||
let mut c = CharStyle { font: base.font.clone(), size: base.size, bold: base.bold, italic: base.italic, color: base.color, letter_spacing: base.letter_spacing, ..CharStyle::default() };
|
||||
CharPatch::parse(p)?.apply(&mut c);
|
||||
let mut q = ParagraphStyle { align: base.align, line_spacing: base.line_spacing, ..ParagraphStyle::default() };
|
||||
ParaPatch::parse(p)?.apply(&mut q);
|
||||
Ok((c, q))
|
||||
}
|
||||
|
||||
/// The last style used, from a block (what new text gets next).
|
||||
fn remember(s: &mut Session, b: &TextBlock) {
|
||||
s.text_style = TextStyle { font: b.font.clone(), size: b.size, bold: b.bold, italic: b.italic, color: b.color, align: b.align, letter_spacing: b.letter_spacing, line_spacing: b.line_spacing };
|
||||
}
|
||||
|
||||
fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -479,65 +642,243 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if text.trim().is_empty() && kind == TextKind::Static {
|
||||
return Err(EngineError::Param("'text' is empty".into()));
|
||||
}
|
||||
let style = style_param(p, &s.text_style)?;
|
||||
if text.chars().count() > anicraft_text::MAX_CHARS {
|
||||
return Err(EngineError::Param(format!("text is limited to {} characters per block", anicraft_text::MAX_CHARS)));
|
||||
}
|
||||
let (cs, ps) = new_style(p, &s.text_style)?;
|
||||
let width = width_param(p, None)?;
|
||||
let (block, note) = lay_out(&text, &style, width)?;
|
||||
let mut d = TextBlock { text: text.clone(), width, ..TextBlock::default() };
|
||||
let runs = runs_param(p, &cs)?.unwrap_or_else(|| vec![TextRun { chars: u32::MAX, style: cs.clone() }]);
|
||||
let paras = paragraphs_param(p, &ps)?.unwrap_or_else(|| vec![ps]);
|
||||
d.set_styles(runs, paras);
|
||||
let (block, note, _) = lay_out_block(&d)?;
|
||||
let (block, note) = if kind == TextKind::Static {
|
||||
(block, note)
|
||||
} else {
|
||||
let (bw, bh) = field_box(&block);
|
||||
let f = TextField { lines: if width.is_some() { LineType::Multiline } else if text.contains('\n') { LineType::MultilineNoWrap } else { LineType::Single }, ..TextField::new(kind) };
|
||||
lay_out_field(&text, &style, &f, bw, bh)?
|
||||
let lines = if width.is_some() {
|
||||
LineType::Multiline
|
||||
} else if text.contains('\n') {
|
||||
LineType::MultilineNoWrap
|
||||
} else {
|
||||
LineType::Single
|
||||
};
|
||||
let f = TextField { lines, ..TextField::new(kind) };
|
||||
let (b, n, _) = lay_out_block(&TextBlock { field: Some(f), box_width: bw, box_height: bh, ..block })?;
|
||||
(b, n)
|
||||
};
|
||||
let x = opt_f32(p, "x")?.unwrap_or((s.doc.stage.width as f32 - block.box_width) * 0.5);
|
||||
let y = opt_f32(p, "y")?.unwrap_or((s.doc.stage.height as f32 - block.box_height) * 0.5);
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let out = json!({"element": id.0, "font": block.font, "width": block.box_width, "height": block.box_height, "note": note});
|
||||
s.text_style = TextStyle { font: block.font.clone(), ..style };
|
||||
let out = json!({"element": id.0, "font": block.font, "width": block.box_width, "height": block.box_height, "runs": block.runs.len().max(1), "note": note});
|
||||
remember(s, &block);
|
||||
let el = Element { id, name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) };
|
||||
s.editable_keyframe()?.elements.push(Arc::new(el));
|
||||
s.select_only([id]);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Lays `d` out where `e` stands (text on a path keeps its place) and puts it in.
|
||||
fn put(e: &mut Element, d: &TextBlock) -> Result<(TextBlock, Option<String>)> {
|
||||
let (block, note, shift) = lay_out_block(d)?;
|
||||
e.transform = e.transform.mul(&Affine::translate(shift.x, shift.y));
|
||||
e.kind = ElementKind::Text(Arc::new(block.clone()));
|
||||
Ok((block, note))
|
||||
}
|
||||
|
||||
fn edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let new_text = opt_str(p, "text")?.map(str::to_string);
|
||||
if new_text.as_ref().is_some_and(|t| t.chars().count() > anicraft_text::MAX_CHARS) {
|
||||
return Err(EngineError::Param(format!("text is limited to {} characters per block", anicraft_text::MAX_CHARS)));
|
||||
}
|
||||
let (cp, pp) = (CharPatch::parse(p)?, ParaPatch::parse(p)?);
|
||||
let mut notes = Vec::new();
|
||||
let mut edited = 0;
|
||||
let mut last_style = None;
|
||||
let mut last = None;
|
||||
for e in s.selected_elements_mut()? {
|
||||
let ElementKind::Text(t) = &e.kind else { continue };
|
||||
let style = style_param(p, &style_of(t))?;
|
||||
let text = new_text.clone().unwrap_or_else(|| t.text.clone());
|
||||
// Fields may be empty (a script or the viewer fills them); static text may not.
|
||||
if text.trim().is_empty() && t.field.is_none() {
|
||||
return Err(EngineError::Param("'text' is empty (delete the text instead)".into()));
|
||||
}
|
||||
let width = if t.field.is_some() { width_param(p, Some(t.box_width))?.or(Some(t.box_width)).map(|w| w.max(1.0)) } else { width_param(p, t.width)? };
|
||||
let (block, note, shift) = relay(t, &text, &style, width)?;
|
||||
// The text changed: the runs follow; then new runs and paragraphs, if given.
|
||||
let mut d = retext(t, &text);
|
||||
let runs = runs_param(p, &d.char_style())?.unwrap_or_else(|| d.styled_runs());
|
||||
let paras = paragraphs_param(p, &d.para_style())?.unwrap_or_else(|| d.paragraph_styles());
|
||||
// Style keys apply to every character and paragraph.
|
||||
let n = d.char_count();
|
||||
let runs = if cp.is_empty() { runs } else { rt::restyle_runs(&runs, 0, n, |st| cp.apply(st)) };
|
||||
let paras: Vec<ParagraphStyle> = paras
|
||||
.into_iter()
|
||||
.map(|mut q| {
|
||||
pp.apply(&mut q);
|
||||
q
|
||||
})
|
||||
.collect();
|
||||
d.set_styles(runs, paras);
|
||||
if t.field.is_some() {
|
||||
d.box_width = width_param(p, Some(t.box_width))?.unwrap_or(t.box_width).max(1.0);
|
||||
} else {
|
||||
d.width = width_param(p, t.width)?;
|
||||
}
|
||||
let (block, note) = put(e, &d)?;
|
||||
notes.extend(note);
|
||||
last_style = Some(TextStyle { font: block.font.clone(), ..style });
|
||||
e.transform = e.transform.mul(&Affine::translate(shift.x, shift.y));
|
||||
e.kind = ElementKind::Text(Arc::new(block));
|
||||
last = Some(block);
|
||||
edited += 1;
|
||||
}
|
||||
if edited == 0 {
|
||||
return Err(EngineError::State("the selection has no text".into()));
|
||||
}
|
||||
if let Some(st) = last_style {
|
||||
s.text_style = st;
|
||||
if let Some(b) = last {
|
||||
remember(s, &b);
|
||||
}
|
||||
notes.dedup();
|
||||
Ok(json!({"edited": edited, "note": notes.first()}))
|
||||
}
|
||||
|
||||
/// `text.style`: characters `start..end` of the selected text restyled.
|
||||
fn style_range(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let cp = CharPatch::parse(p)?;
|
||||
if cp.is_empty() {
|
||||
return Err(EngineError::Param(format!("give a style to set: {CHAR_KEYS}")));
|
||||
}
|
||||
let mut changed = 0;
|
||||
let mut notes = Vec::new();
|
||||
for e in s.selected_elements_mut()? {
|
||||
let ElementKind::Text(t) = &e.kind else { continue };
|
||||
let (start, end) = range_param(p, t.char_count())?;
|
||||
let mut d = (**t).clone();
|
||||
let runs = rt::restyle_runs(&t.styled_runs(), start, end, |st| cp.apply(st));
|
||||
d.set_styles(runs, t.paragraph_styles());
|
||||
let (_, note) = put(e, &d)?;
|
||||
notes.extend(note);
|
||||
changed += 1;
|
||||
}
|
||||
if changed == 0 {
|
||||
return Err(EngineError::State("the selection has no text".into()));
|
||||
}
|
||||
Ok(json!({"changed": changed, "note": notes.first()}))
|
||||
}
|
||||
|
||||
/// `text.paragraph`: the paragraphs characters `start..end` touch, laid out anew.
|
||||
fn paragraph_range(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pp = ParaPatch::parse(p)?;
|
||||
if pp.is_empty() {
|
||||
return Err(EngineError::Param(format!("give a paragraph setting: {PARA_KEYS}")));
|
||||
}
|
||||
let mut changed = 0;
|
||||
for e in s.selected_elements_mut()? {
|
||||
let ElementKind::Text(t) = &e.kind else { continue };
|
||||
let (start, end) = range_param(p, t.char_count())?;
|
||||
let range = rt::paragraphs_in(&t.text, start, end);
|
||||
let mut paras = t.paragraph_styles();
|
||||
for (i, q) in paras.iter_mut().enumerate() {
|
||||
if range.contains(&i) {
|
||||
pp.apply(q);
|
||||
}
|
||||
}
|
||||
let mut d = (**t).clone();
|
||||
d.set_styles(t.styled_runs(), paras);
|
||||
put(e, &d)?;
|
||||
changed += 1;
|
||||
}
|
||||
if changed == 0 {
|
||||
return Err(EngineError::State("the selection has no text".into()));
|
||||
}
|
||||
Ok(json!({"changed": changed}))
|
||||
}
|
||||
|
||||
fn hex_of(c: Rgba) -> String {
|
||||
let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
format!("#{:02x}{:02x}{:02x}", b(c.r), b(c.g), b(c.b))
|
||||
}
|
||||
|
||||
fn style_json(c: &CharStyle) -> Value {
|
||||
json!({"font": c.font, "size": c.size, "bold": c.bold, "italic": c.italic, "color": hex_of(c.color), "letter_spacing": c.letter_spacing, "shift": c.shift.key(), "underline": c.underline, "url": c.url})
|
||||
}
|
||||
|
||||
fn align_key(a: TextAlign) -> &'static str {
|
||||
match a {
|
||||
TextAlign::Left => "left",
|
||||
TextAlign::Center => "center",
|
||||
TextAlign::Right => "right",
|
||||
}
|
||||
}
|
||||
|
||||
fn para_json(q: &ParagraphStyle) -> Value {
|
||||
json!({"align": align_key(q.align), "indent": q.indent, "left_margin": q.left_margin, "right_margin": q.right_margin, "line_spacing": q.line_spacing})
|
||||
}
|
||||
|
||||
/// What a summary shares (a mixed attribute is `null`).
|
||||
pub fn summary_json(m: &StyleSummary) -> Value {
|
||||
json!({
|
||||
"font": m.font, "size": m.size, "bold": m.bold, "italic": m.italic, "color": m.color.map(hex_of),
|
||||
"letter_spacing": m.letter_spacing, "shift": m.shift.map(BaselineShift::key), "underline": m.underline, "url": m.url,
|
||||
})
|
||||
}
|
||||
|
||||
/// `text.styles`: the first selected text's runs, paragraphs, and what a range shares.
|
||||
fn styles_of(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let t = s
|
||||
.selected_elements()
|
||||
.into_iter()
|
||||
.find_map(|(_, e)| match &e.kind {
|
||||
ElementKind::Text(t) => Some(t.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or_else(|| EngineError::State("select a text block".into()))?;
|
||||
let (start, end) = range_param(p, t.char_count())?;
|
||||
let runs: Vec<Value> = t
|
||||
.styled_runs()
|
||||
.iter()
|
||||
.map(|r| {
|
||||
let mut v = style_json(&r.style);
|
||||
v["chars"] = json!(r.chars);
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
let range = rt::paragraphs_in(&t.text, start, end);
|
||||
let paras = t.paragraph_styles();
|
||||
let shared = |f: &dyn Fn(&ParagraphStyle) -> Value| -> Value {
|
||||
let mut it = paras.iter().enumerate().filter(|(i, _)| range.contains(i)).map(|(_, q)| f(q));
|
||||
let first = it.next().unwrap_or(Value::Null);
|
||||
if it.all(|v| v == first) { first } else { Value::Null }
|
||||
};
|
||||
let paragraph = json!({
|
||||
"align": shared(&|q| json!(align_key(q.align))),
|
||||
"indent": shared(&|q| json!(q.indent)),
|
||||
"left_margin": shared(&|q| json!(q.left_margin)),
|
||||
"right_margin": shared(&|q| json!(q.right_margin)),
|
||||
"line_spacing": shared(&|q| json!(q.line_spacing)),
|
||||
});
|
||||
Ok(json!({
|
||||
"text": t.text,
|
||||
"runs": runs,
|
||||
"paragraphs": paras.iter().map(para_json).collect::<Vec<_>>(),
|
||||
"start": start,
|
||||
"end": end,
|
||||
"selection": summary_json(&rt::summarize(&t.styled_runs(), start, end)),
|
||||
"paragraph": paragraph,
|
||||
}))
|
||||
}
|
||||
|
||||
fn fonts(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let f = Fonts::get();
|
||||
Ok(json!({"families": f.families(), "default": f.resolve("")}))
|
||||
}
|
||||
|
||||
/// A text block as a plain shape with the same outlines (Break Apart).
|
||||
pub(crate) fn to_shape(t: &TextBlock) -> anicraft_doc::Shape {
|
||||
let path: Arc<Path> = t.outline.clone();
|
||||
anicraft_doc::Shape { path, fill: Some(anicraft_doc::Paint::Solid(t.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, warp: None }
|
||||
/// A text block as plain shapes with the same outlines, one per colour (Break Apart).
|
||||
pub(crate) fn to_shapes(t: &TextBlock) -> Vec<anicraft_doc::Shape> {
|
||||
t.fill_paths()
|
||||
.into_iter()
|
||||
.filter(|(_, _, p)| !p.cmds.is_empty() || t.fills.is_empty())
|
||||
.map(|(color, _, path)| anicraft_doc::Shape { path, fill: Some(anicraft_doc::Paint::Solid(color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, merge: false, warp: None })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The one style a block's runtime text is laid out in (its first run's), for fields a script
|
||||
/// or the viewer changes (ADR 0066).
|
||||
pub(crate) fn style_of(t: &TextBlock) -> TextStyle {
|
||||
TextStyle { font: t.font.clone(), size: t.size, bold: t.bold, italic: t.italic, color: t.color, align: t.align, letter_spacing: t.letter_spacing, line_spacing: t.line_spacing }
|
||||
}
|
||||
@@ -347,7 +347,7 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option<Confirmation> {
|
||||
(n > 1).then(|| Confirmation {
|
||||
title: "Remove bone?".into(),
|
||||
message: format!(
|
||||
"{name}{} {} posed over {}; removing takes {} out of every pose. The instances stay where they are now, on a layer of their own. You can undo this.",
|
||||
"{name}{} {} posed over {}; removing takes {} out of every pose. What the bones moved stays as it looks now (instances and whole shapes on a layer of their own). You can undo this.",
|
||||
if below > 0 { format!(" and the {} below it", plural(below, "bone")) } else { String::new() },
|
||||
if below > 0 { "are" } else { "is" },
|
||||
plural(n, "keyframe"),
|
||||
|
||||
@@ -891,7 +891,7 @@ fn apply_element(e: &mut anicraft_doc::Element, f: Field, q: &Query, with: &With
|
||||
t.note("a text field can't be left empty (delete it instead)".into());
|
||||
} else {
|
||||
// Laid out again as it is: text on a path stays on it (ADR 0070).
|
||||
let (block, note, shift) = crate::cmds_text::relay_static(tb, &n, &crate::cmds_text::style_of(tb))?;
|
||||
let (block, note, shift) = crate::cmds_text::relay_static(tb, &n)?;
|
||||
t.note_opt(note);
|
||||
*tb = Arc::new(block);
|
||||
e.transform = e.transform.mul(&anicraft_geom::Affine::translate(shift.x, shift.y));
|
||||
@@ -900,16 +900,23 @@ fn apply_element(e: &mut anicraft_doc::Element, f: Field, q: &Query, with: &With
|
||||
}
|
||||
}
|
||||
(Field::Font, ElementKind::Text(tb), With::Font(family)) => {
|
||||
let style = crate::cmds_text::TextStyle { font: family.clone(), ..crate::cmds_text::style_of(tb) };
|
||||
let (block, note, shift) = crate::cmds_text::relay_static(tb, &tb.text, &style)?;
|
||||
let (block, note, shift) = crate::cmds_text::refont_static(tb, family)?;
|
||||
t.note_opt(note);
|
||||
*tb = Arc::new(block);
|
||||
e.transform = e.transform.mul(&anicraft_geom::Affine::translate(shift.x, shift.y));
|
||||
t.replaced += 1;
|
||||
}
|
||||
(Field::TextColor, ElementKind::Text(tb), With::Color(c)) => {
|
||||
// Every run and colour piece takes the colour, keeping its own opacity (ADR 0085).
|
||||
let tb = Arc::make_mut(tb);
|
||||
tb.color = Rgba { a: tb.color.a, ..*c };
|
||||
let n = tb.char_count();
|
||||
let runs = anicraft_doc::rich_text::restyle_runs(&tb.styled_runs(), 0, n, |st| st.color = Rgba { a: st.color.a, ..*c });
|
||||
let paras = tb.paragraph_styles();
|
||||
tb.set_styles(runs, paras);
|
||||
for f in &mut tb.fills {
|
||||
f.color = Rgba { a: f.color.a, ..*c };
|
||||
}
|
||||
tb.fill_cache = Default::default();
|
||||
t.replaced += 1;
|
||||
}
|
||||
(Field::Fill | Field::Stroke, ElementKind::Shape(sh), With::Color(c)) => {
|
||||
|
||||
@@ -38,7 +38,7 @@ impl Build {
|
||||
self.doc.alloc_id()
|
||||
}
|
||||
pub fn text(&mut self, t: &str, color: Rgba) -> Element {
|
||||
let block = TextBlock { text: t.into(), font: "Test Sans".into(), size: 20.0, bold: false, italic: false, color, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 10.0, box_height: 10.0, field: None, on_path: None };
|
||||
let block = TextBlock { text: t.into(), font: "Test Sans".into(), size: 20.0, bold: false, italic: false, color, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, width: None, outline: Arc::new(Path::new()), box_width: 10.0, box_height: 10.0, field: None, on_path: None, ..Default::default() };
|
||||
Element { id: ElementId(self.id()), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(block)) }
|
||||
}
|
||||
pub fn rect(&mut self, fill: Paint, stroke: Option<Rgba>) -> Element {
|
||||
|
||||
@@ -4,10 +4,46 @@ use crate::EngineError;
|
||||
use anicraft_doc::{Document, path_table};
|
||||
use anicraft_geom::Path;
|
||||
use craft_anicraft_format::PayloadDecoder;
|
||||
pub use craft_anicraft_format::{FORMAT_NAME, FORMAT_VERSION, MAX_FILE_BYTES};
|
||||
use serde::Deserialize;
|
||||
pub use craft_anicraft_format::{FORMAT_NAME, MAX_FILE_BYTES};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The newest envelope version this build reads (v1 inline paths; v2 shared path table; v3
|
||||
/// named scene timelines; v4 mixed armatures, ADR 0098).
|
||||
pub const FORMAT_VERSION: u32 = 4;
|
||||
/// The version a document is written as unless it needs a later one: the shared envelope's.
|
||||
/// Builds from before ADR 0098 read up to this.
|
||||
pub const BASE_VERSION: u32 = craft_anicraft_format::FORMAT_VERSION;
|
||||
/// The first version that may hold mixed armatures.
|
||||
pub const MIXED_ARMATURES_VERSION: u32 = 4;
|
||||
|
||||
/// The version `doc` is written as: the lowest that can say everything in it, so a document
|
||||
/// that uses nothing new still opens in earlier builds, and one that does is refused by them
|
||||
/// with a message naming the version instead of opening with parts missing.
|
||||
pub fn version_for(doc: &Document) -> u32 {
|
||||
if doc.has_mixed_armatures() { MIXED_ARMATURES_VERSION } else { BASE_VERSION }
|
||||
}
|
||||
|
||||
/// The envelope for versions past the shared crate's own: the same fields in the same order,
|
||||
/// and the same compact-or-pretty rule, with the version the document needs.
|
||||
#[derive(Serialize)]
|
||||
struct EnvelopeOut<'a> {
|
||||
format: &'a str,
|
||||
version: u32,
|
||||
generator: &'a str,
|
||||
paths: &'a [Arc<Path>],
|
||||
document: &'a Document,
|
||||
}
|
||||
|
||||
fn write_as(version: u32, generator: &str, paths: &[Arc<Path>], doc: &Document) -> Result<String, serde_json::Error> {
|
||||
if version <= BASE_VERSION {
|
||||
return craft_anicraft_format::write(generator, paths, doc);
|
||||
}
|
||||
let envelope = EnvelopeOut { format: FORMAT_NAME, version, generator, paths, document: doc };
|
||||
let compact = serde_json::to_string(&envelope)?;
|
||||
if compact.len() < craft_anicraft_format::PRETTY_LIMIT { serde_json::to_string_pretty(&envelope) } else { Ok(compact) }
|
||||
}
|
||||
|
||||
/// AniCraft document deserialization uses its own path-table scope while the shared format crate
|
||||
/// controls when a payload is decoded in the envelope stream.
|
||||
struct DocumentDecoder;
|
||||
@@ -27,7 +63,8 @@ impl PayloadDecoder<Arc<Path>> for DocumentDecoder {
|
||||
pub fn to_json(doc: &Document) -> Result<String, EngineError> {
|
||||
let paths = path_table::build_table(doc);
|
||||
let generator = format!("AniCraft {}", env!("CARGO_PKG_VERSION"));
|
||||
path_table::write_with_paths(&paths, || craft_anicraft_format::write(&generator, &paths, doc)).map_err(|e| EngineError::Format(e.to_string()))
|
||||
let version = version_for(doc);
|
||||
path_table::write_with_paths(&paths, || write_as(version, &generator, &paths, doc)).map_err(|e| EngineError::Format(e.to_string()))
|
||||
}
|
||||
|
||||
pub fn from_json(text: &str) -> Result<Document, EngineError> {
|
||||
@@ -37,7 +74,7 @@ pub fn from_json(text: &str) -> Result<Document, EngineError> {
|
||||
return Err(EngineError::Format(format!("unexpected format '{}'", env.format)));
|
||||
}
|
||||
if env.version > FORMAT_VERSION {
|
||||
return Err(EngineError::Format(format!("file version {} is newer than this AniCraft (supports {FORMAT_VERSION})", env.version)));
|
||||
return Err(EngineError::Format(format!("file version {} is newer than this AniCraft (supports {FORMAT_VERSION}): open it with the AniCraft that saved it, or a newer one", env.version)));
|
||||
}
|
||||
let mut doc = env.document.ok_or_else(|| EngineError::Format("the file has no document".into()))?;
|
||||
doc.sanitize();
|
||||
|
||||
@@ -1257,10 +1257,14 @@ mod timeline_key_tests;
|
||||
#[cfg(test)]
|
||||
mod tests_bone_chain;
|
||||
#[cfg(test)]
|
||||
mod tests_mixed_bone;
|
||||
#[cfg(test)]
|
||||
mod view_tests;
|
||||
#[cfg(test)]
|
||||
mod path_text_tests;
|
||||
#[cfg(test)]
|
||||
mod rich_text_tests;
|
||||
#[cfg(test)]
|
||||
mod group_tests;
|
||||
#[cfg(test)]
|
||||
mod swatch_tests;
|
||||
|
||||
@@ -285,6 +285,7 @@ pub fn multi_frames(tl: &Timeline, playhead: u32, first: u32, last: u32) -> Vec<
|
||||
fn keep_layers(dl: &mut DisplayList, layers: &[LayerId]) {
|
||||
let set: HashSet<LayerId> = layers.iter().copied().collect();
|
||||
dl.items.retain(|i| set.contains(&i.layer) || (i.masks.is_some() && i.group.is_none()));
|
||||
dl.links.clear();
|
||||
}
|
||||
|
||||
/// The parts as one list, layer by layer: each layer's items from every part, in part order,
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Styled text (ADR 0085): runs set on a range, typing that continues a style, paragraphs, mixed
|
||||
//! selections, fields and paths keeping runs, Break Apart by colour, the file, the renderer.
|
||||
|
||||
use crate::Session;
|
||||
use anicraft_doc::{BaselineShift, ElementId, ElementKind, TextAlign, TextBlock};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
fn fonts() -> bool {
|
||||
let ok = !anicraft_text::Fonts::get().families().is_empty();
|
||||
if !ok {
|
||||
eprintln!("no fonts on this computer: styled text tests skipped");
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
fn text_of(s: &Session, id: ElementId) -> Arc<TextBlock> {
|
||||
let e = s.visible_elements().into_iter().find(|e| e.id == id).unwrap();
|
||||
match &e.kind {
|
||||
ElementKind::Text(t) => t.clone(),
|
||||
other => panic!("not text: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn hello(s: &mut Session) -> ElementId {
|
||||
ElementId(run(s, "text.create", json!({"text": "Hello world", "x": 20, "y": 20, "size": 40, "color": "#000000"}))["element"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styling_a_range_splits_runs_and_colours_the_outline() {
|
||||
if !fonts() {
|
||||
return;
|
||||
}
|
||||
let mut s = Session::default();
|
||||
let id = hello(&mut s);
|
||||
let plain = text_of(&s, id);
|
||||
assert!(plain.runs.is_empty() && plain.fills.is_empty(), "one style: as text always was");
|
||||
let steps = s.history().undo_len();
|
||||
run(&mut s, "text.style", json!({"start": 0, "end": 5, "bold": true, "color": "#cc0000"}));
|
||||
assert_eq!(s.history().undo_len(), steps + 1, "one undo step");
|
||||
let t = text_of(&s, id);
|
||||
assert_eq!(t.runs.iter().map(|r| (r.chars, r.style.bold)).collect::<Vec<_>>(), vec![(5, true), (6, false)]);
|
||||
assert_eq!(t.fills.len(), 2, "a piece per colour");
|
||||
assert_eq!(t.fills.iter().map(|f| f.cmds as usize).sum::<usize>(), t.outline.cmds.len());
|
||||
assert_eq!(t.fill_paths()[0].0, anicraft_doc::Rgba::hex(0xcc0000));
|
||||
// The block's own style is its first run's.
|
||||
assert!(t.bold && t.color == anicraft_doc::Rgba::hex(0xcc0000));
|
||||
// The renderer draws the first word red and the second black.
|
||||
let px = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap();
|
||||
let count = |want: fn(u8, u8, u8) -> bool| {
|
||||
let raw = px.to_rgba8();
|
||||
raw.as_chunks::<4>().0.iter().filter(|p| want(p[0], p[1], p[2])).count()
|
||||
};
|
||||
assert!(count(|r, g, b| r > 150 && g < 60 && b < 60) > 50, "red glyphs drawn");
|
||||
assert!(count(|r, g, b| r < 40 && g < 40 && b < 40) > 50, "black glyphs drawn");
|
||||
// Restyling it back joins the runs again.
|
||||
run(&mut s, "text.style", json!({"start": 0, "end": 5, "bold": false, "color": "#000000"}));
|
||||
let back = text_of(&s, id);
|
||||
assert!(back.runs.is_empty() && back.fills.is_empty());
|
||||
assert_eq!(back.outline, plain.outline, "laid out exactly as before");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn styles_report_mixed_values_and_typing_continues_the_style_before() {
|
||||
if !fonts() {
|
||||
return;
|
||||
}
|
||||
let mut s = Session::default();
|
||||
let id = hello(&mut s);
|
||||
run(&mut s, "text.style", json!({"start": 6, "end": 11, "size": 20, "italic": true}));
|
||||
let v = run(&mut s, "text.styles", json!({"start": 3, "end": 8}));
|
||||
assert_eq!(v["selection"]["size"], Value::Null, "mixed");
|
||||
assert_eq!(v["selection"]["bold"], json!(false), "shared");
|
||||
assert_eq!(v["runs"].as_array().unwrap().len(), 2);
|
||||
assert_eq!(run(&mut s, "text.styles", json!({"start": 9, "end": 9}))["selection"]["italic"], json!(true), "a caret: the style typing there gets");
|
||||
// Typing at the end continues the small italic run; typing at the start the first run.
|
||||
run(&mut s, "text.edit", json!({"text": "Hello world!"}));
|
||||
run(&mut s, "text.edit", json!({"text": ">Hello world!"}));
|
||||
let t = text_of(&s, id);
|
||||
assert_eq!(t.runs.iter().map(|r| (r.chars, r.style.size)).collect::<Vec<_>>(), vec![(7, 40.0), (6, 20.0)]);
|
||||
// Deleting the small word joins nothing it shouldn't; deleting all of it leaves one run.
|
||||
run(&mut s, "text.edit", json!({"text": ">Hello "}));
|
||||
assert!(text_of(&s, id).runs.is_empty());
|
||||
// Hostile ranges and junk styles are errors or clamps, never a panic.
|
||||
assert!(s.execute("text.style", &json!({"start": 4, "end": 2, "bold": true})).is_err());
|
||||
assert!(s.execute("text.style", &json!({"start": 0})).is_err(), "no style given");
|
||||
assert!(s.execute("text.style", &json!({"shift": "sideways"})).is_err());
|
||||
assert!(s.execute("text.style", &json!({"url": "javascript:alert(1)"})).is_err());
|
||||
run(&mut s, "text.style", json!({"start": 3, "end": 999_999, "underline": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_superscript_sits_above_the_line_and_runs_wrap_across() {
|
||||
if !fonts() {
|
||||
return;
|
||||
}
|
||||
let mut s = Session::default();
|
||||
let id = ElementId(run(&mut s, "text.create", json!({"text": "E = mc2", "x": 0, "y": 0, "size": 60}))["element"].as_u64().unwrap());
|
||||
let before = text_of(&s, id);
|
||||
run(&mut s, "text.style", json!({"start": 6, "end": 7, "shift": "superscript"}));
|
||||
let t = text_of(&s, id);
|
||||
assert_eq!(t.runs.last().map(|r| r.style.shift), Some(BaselineShift::Superscript));
|
||||
// The "2" moved up and got smaller: the outline's top is no lower, the text narrower.
|
||||
assert!(t.box_width < before.box_width - 5.0, "{} vs {}", t.box_width, before.box_width);
|
||||
assert!(t.outline.bounds().min.y <= before.outline.bounds().min.y + 0.5);
|
||||
// Wrapping across runs: a width that fits two words per line.
|
||||
run(&mut s, "text.edit", json!({"text": "one two three four five", "width": 180, "runs": [{"chars": 8, "size": 30}, {"chars": 15, "size": 60, "color": "#0000ff"}]}));
|
||||
let w = text_of(&s, id);
|
||||
assert!(w.box_height > 150.0, "several lines: {}", w.box_height);
|
||||
assert!(w.outline.bounds().max.x <= 182.0, "{:?}", w.outline.bounds());
|
||||
assert_eq!(w.runs.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraphs_take_their_own_alignment_indent_and_margins() {
|
||||
if !fonts() {
|
||||
return;
|
||||
}
|
||||
let mut s = Session::default();
|
||||
let id = ElementId(run(&mut s, "text.create", json!({"text": "Title\nbody text", "x": 0, "y": 0, "size": 30, "width": 400}))["element"].as_u64().unwrap());
|
||||
run(&mut s, "text.paragraph", json!({"start": 0, "end": 0, "align": "center"}));
|
||||
let t = text_of(&s, id);
|
||||
assert_eq!(t.paragraphs.iter().map(|p| p.align).collect::<Vec<_>>(), vec![TextAlign::Center, TextAlign::Left]);
|
||||
let v = run(&mut s, "text.styles", json!({"start": 2, "end": 9}));
|
||||
assert_eq!(v["paragraph"]["align"], Value::Null, "two paragraphs, two alignments");
|
||||
run(&mut s, "text.paragraph", json!({"start": 7, "end": 7, "indent": 40, "left_margin": 10}));
|
||||
let t = text_of(&s, id);
|
||||
assert_eq!((t.paragraphs[1].indent, t.paragraphs[1].left_margin), (40.0, 10.0));
|
||||
// A line break typed in the centred title gives both halves its alignment.
|
||||
run(&mut s, "text.edit", json!({"text": "Ti\ntle\nbody text"}));
|
||||
assert_eq!(text_of(&s, id).paragraphs.iter().map(|p| p.align).collect::<Vec<_>>(), vec![TextAlign::Center, TextAlign::Center, TextAlign::Left]);
|
||||
assert!(s.execute("text.paragraph", &json!({"indent": 1e6})).is_err());
|
||||
assert!(s.execute("text.paragraph", &json!({"align": "justify"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_survive_the_file_fields_paths_and_break_apart() {
|
||||
if !fonts() {
|
||||
return;
|
||||
}
|
||||
let mut s = Session::default();
|
||||
let id = hello(&mut s);
|
||||
run(&mut s, "text.style", json!({"start": 0, "end": 5, "color": "#00aa00", "url": "https://example.org"}));
|
||||
// The file keeps runs, paragraphs and fills.
|
||||
let json = crate::format::to_json(&s.doc).unwrap();
|
||||
let back = crate::format::from_json(&json).unwrap();
|
||||
let mut s2 = Session::new(back);
|
||||
s2.frame = 0;
|
||||
let t2 = text_of(&s2, id);
|
||||
let t = text_of(&s, id);
|
||||
assert_eq!((&t2.runs, &t2.fills, &t2.outline), (&t.runs, &t.fills, &t.outline));
|
||||
// Links reach the display list for exports.
|
||||
let dl = anicraft_doc::evaluate(&s.doc, 0);
|
||||
assert_eq!(dl.links.len(), 1);
|
||||
assert_eq!(&*dl.links[0].1, "https://example.org");
|
||||
// A field keeps its runs inside its box.
|
||||
run(&mut s, "text.field", json!({"type": "dynamic"}));
|
||||
let f = text_of(&s, id);
|
||||
assert!(f.field.is_some() && f.runs.len() == 2 && f.fills.len() == 2);
|
||||
run(&mut s, "text.field", json!({"type": "static"}));
|
||||
// On a path, the colours stay.
|
||||
let line = ElementId(run(&mut s, "draw.line", json!({"x0": 100, "y0": 300, "x1": 600, "y1": 300}))["element"].as_u64().unwrap());
|
||||
run(&mut s, "element.select", json!({"ids": [id.0, line.0]}));
|
||||
run(&mut s, "text.attach_path", json!({}));
|
||||
let p = text_of(&s, id);
|
||||
assert!(p.on_path.is_some() && p.fills.len() == 2);
|
||||
run(&mut s, "text.release_path", json!({}));
|
||||
// Break Apart: one shape per colour.
|
||||
run(&mut s, "element.select", json!({"ids": [id.0]}));
|
||||
let shapes_before = s.visible_elements().iter().filter(|e| matches!(e.kind, ElementKind::Shape(_))).count();
|
||||
run(&mut s, "modify.break_apart", json!({}));
|
||||
let shapes = s.visible_elements().iter().filter(|e| matches!(e.kind, ElementKind::Shape(_))).count();
|
||||
assert_eq!(shapes, shapes_before + 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_block_keys_restyle_every_run_and_hostile_runs_are_capped() {
|
||||
if !fonts() {
|
||||
return;
|
||||
}
|
||||
let mut s = Session::default();
|
||||
let id = hello(&mut s);
|
||||
run(&mut s, "text.style", json!({"start": 0, "end": 5, "bold": true}));
|
||||
// A size for the whole block keeps the bold run bold.
|
||||
run(&mut s, "text.edit", json!({"size": 24}));
|
||||
let t = text_of(&s, id);
|
||||
assert_eq!(t.runs.iter().map(|r| (r.style.size, r.style.bold)).collect::<Vec<_>>(), vec![(24.0, true), (24.0, false)]);
|
||||
// Thousands of one-character runs, alternating: capped at the limit, laid out.
|
||||
let text = "ab".repeat(6000);
|
||||
let runs: Vec<Value> = (0..anicraft_doc::MAX_TEXT_RUNS).map(|i| json!({"chars": 1, "bold": i % 2 == 0})).collect();
|
||||
let t0 = std::time::Instant::now();
|
||||
run(&mut s, "text.edit", json!({"text": text, "runs": runs, "width": 800}));
|
||||
eprintln!("{} runs edited in {:?}", anicraft_doc::MAX_TEXT_RUNS, t0.elapsed());
|
||||
let t = text_of(&s, id);
|
||||
assert_eq!(t.runs.len(), anicraft_doc::MAX_TEXT_RUNS);
|
||||
assert_eq!(t.styled_runs().iter().map(|r| r.chars).sum::<u32>(), 12_000);
|
||||
let too_many: Vec<Value> = (0..anicraft_doc::MAX_TEXT_RUNS + 1).map(|_| json!({"chars": 1})).collect();
|
||||
assert!(s.execute("text.edit", &json!({"runs": too_many})).is_err());
|
||||
assert!(s.execute("text.edit", &json!({"runs": [{"size": 3}]})).is_err(), "a run needs its length");
|
||||
assert!(s.execute("text.edit", &json!({"runs": [{"chars": 1, "size": 1e9}]})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_export_draws_each_colour_and_svg_keeps_the_link() {
|
||||
if !fonts() {
|
||||
return;
|
||||
}
|
||||
let mut s = Session::default();
|
||||
let id = hello(&mut s);
|
||||
run(&mut s, "text.style", json!({"start": 0, "end": 5, "color": "#00aa00", "url": "https://example.org/?a=1&b=2"}));
|
||||
let dl = anicraft_doc::evaluate(&s.doc, 0);
|
||||
let svg = anicraft_render::svg::to_svg(&dl, &s.doc.stage);
|
||||
assert!(svg.contains("<a href=\"https://example.org/?a=1&b=2\">"), "the linked word is a link");
|
||||
assert_eq!(svg.matches("</a>").count(), 1);
|
||||
assert!(svg.contains("#00aa00") || svg.contains("rgb(0,170,0)"), "green piece");
|
||||
let html = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap().html;
|
||||
assert!(html.matches("{\"s\":").count() >= 2, "the page draws a paint per colour");
|
||||
let lottie = anicraft_render::lottie::to_lottie(&s.doc, "t", 0, 0, false).json;
|
||||
assert!(lottie.matches("\"ty\":\"fl\"").count() >= 2, "a fill per colour");
|
||||
// A field's authored text keeps its colours in the page, as pieces.
|
||||
run(&mut s, "element.select", json!({"ids": [id.0]}));
|
||||
run(&mut s, "text.field", json!({"type": "dynamic"}));
|
||||
let html = anicraft_render::html::to_html(&s.doc, &anicraft_render::html::HtmlOptions::default()).unwrap().html;
|
||||
assert!(html.contains("\"pp\":"), "field pieces");
|
||||
}
|
||||
@@ -684,6 +684,12 @@ fn panic_hunt_every_command() {
|
||||
json!({"id": 3, "cmd": 1, "slot": 2, "dx": 1e30, "dy": 0, "x": 30, "y": 30, "to_x": 31, "to_y": 30, "with": [[30, 30], [1e30, 0]]}),
|
||||
json!({"id": 5, "cmd": u64::MAX, "slot": 9, "dx": 1, "dy": 1, "with": "x", "x0": 0, "y0": 0, "x1": 1e9, "y1": 1e9}),
|
||||
json!({"id": 4, "cmd": 2, "slot": 1, "dx": -3, "dy": 2, "x": 60, "y": 60, "to_x": 61, "to_y": 61, "with": [[60, 60], [30, 90], [90, 30]], "merge": false}),
|
||||
// Styled text (ADR 0085): thousands of runs, hostile sizes, ranges and links.
|
||||
json!({"text": "ab
|
||||
cd", "start": 1, "end": 99_999, "runs": (0..12_000).map(|i| json!({"chars": i % 3, "size": 10 + i % 5})).collect::<Vec<_>>(), "paragraphs": [{"indent": 1e9}], "shift": "superscript", "url": "javascript:x", "underline": "y"}),
|
||||
json!({"start": u64::MAX, "end": 0, "size": 12, "shift": "sub", "runs": "x", "paragraphs": 3}),
|
||||
json!({"text": "Hi
|
||||
there", "runs": [{"chars": 1, "bold": true, "shift": "superscript", "color": "#ff0000", "url": "https://a.b"}, {"chars": u32::MAX, "size": 2000, "letter_spacing": -1000}], "paragraphs": [{"align": "right", "left_margin": 1000, "right_margin": 1000}, {"indent": -1000}, {}], "start": 0, "end": 1, "underline": true, "indent": -1000}),
|
||||
// Kept scripts (ADR 0013 tier 1): odd text, unknown languages, class names that aren't.
|
||||
json!({"text": "\u{0}\r\n]]>\u{202e}stop();", "language": "other", "class": "a.b", "base": "c", "symbol": 1}),
|
||||
json!({"text": "x".repeat(1 << 20), "language": 3, "class": "not a class", "base": ""}),
|
||||
@@ -796,6 +802,22 @@ Exec=evil", "data_home": "relative/share", "refresh": false}),
|
||||
}
|
||||
assert_eq!((tail, sb1, sb2), (3, 100, 103), "the hostile params name these");
|
||||
shaped.set_frame(4);
|
||||
// A mixed armature (ADR 0098): bones inside a body shape, an instance head on its neck
|
||||
// joint, a plume shape on the head with a bone of its own; posed at frame 8.
|
||||
let (mut mixed, mr) = crate::tests_mixed_bone::character();
|
||||
for (id, p) in [("bone.pose", json!({"bone": mr.spine2, "angle": 40, "frame": 8})), ("bone.set_spring", json!({"bone": mr.neck, "strength": 60, "damping": 10})), ("bone.set_translation", json!({"bone": mr.neck, "axis": "y", "enabled": true}))] {
|
||||
mixed.execute(id, &p).unwrap();
|
||||
}
|
||||
assert_eq!((mr.spine1, mr.spine2, mr.neck, mr.crest, mr.feather), (100, 103, 105, 106, 107), "the hostile params name these");
|
||||
mixed.set_frame(4);
|
||||
let (body, head, plume) = (crate::tests_mixed_bone::BODY, crate::tests_mixed_bone::HEAD, crate::tests_mixed_bone::PLUME);
|
||||
hostile.extend([
|
||||
json!({"parent": 103, "to": head, "from": plume, "bone": 105, "shape": plume, "head": [200, 90], "tail": [1e30, -1e30], "points": [0, 9, 10, 17], "at": [[200, 140]], "weight": 50, "angle": 720, "x": 260, "y": 150, "frame": 3}),
|
||||
json!({"bone": 107, "parent": 106, "to": body, "tail": [200, 40], "head": [200, 60], "mode": "auto", "confirm": true, "dx": 1e6, "x": -1e6, "y": 1e6}),
|
||||
json!({"bone": 106, "parent": 107, "to": 108, "shape": body, "head": [200, 200], "tail": [200, 201.5], "confirm": true, "points": [0], "weight": 100, "at": [[200, 60], [200, 300]], "radius": 2000, "strength": 100, "mode": "subtract"}),
|
||||
json!({"bone": 100, "from": 104, "to": plume, "parent": u64::MAX, "confirm": true, "axis": "x", "slide_x": 1e9, "strength": 100, "damping": 0, "local": [1e9, -1e9]}),
|
||||
json!({"bone": 103, "from": head, "to": 101, "confirm": true, "layer": 102, "enabled": false, "pinned": true, "points": "all"}),
|
||||
]);
|
||||
// Asset Warp (ADR 0079): a warped rectangle and bitmap, a pin moved at frame 8 inside a
|
||||
// tween, the playhead mid-tween, the rectangle selected.
|
||||
let (mut warped, wr, wb) = crate::tests_warp::warped();
|
||||
@@ -955,7 +977,7 @@ Exec=evil", "data_home": "relative/share", "refresh": false}),
|
||||
let inner = grouped.visible_elements().into_iter().find(|e| matches!(e.kind, anicraft_doc::ElementKind::Group { .. })).map(|e| e.id.0).unwrap();
|
||||
grouped.execute("symbol.edit", &json!({"id": inner})).unwrap();
|
||||
assert_eq!(grouped.editing.len(), 2, "the fuzz starts inside a group inside a group");
|
||||
for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, shaped, warped, layered, in_symbol, keyed, library, button, grouped, eased] {
|
||||
for start in [Session::default(), Session::new(sample::demo()), Session::new(with_sound), on_path, raw, rig, shaped, mixed, warped, layered, in_symbol, keyed, library, button, grouped, eased] {
|
||||
let mut s = start;
|
||||
for spec in commands().iter().filter(|c| !skip(c.id)) {
|
||||
for p in &hostile {
|
||||
|
||||
@@ -94,7 +94,6 @@ fn bone_add_refuses_what_cant_be_joined() {
|
||||
let mut s = three_bars();
|
||||
let bad = |s: &mut Session, p: Value| s.execute("bone.add", &p).unwrap_err().to_string();
|
||||
assert!(bad(&mut s, json!({"from": ROOT, "to": ROOT})).contains("two different"));
|
||||
assert!(bad(&mut s, json!({"from": ROOT, "to": SHAPE})).contains("symbol"));
|
||||
assert!(bad(&mut s, json!({"from": ROOT, "to": 999})).contains("no instance"));
|
||||
assert!(bad(&mut s, json!({"from": ROOT})).contains("required"));
|
||||
assert!(bad(&mut s, json!({"from": ROOT, "to": ARM, "head": [1, "x"]})).contains("[x, y]"));
|
||||
|
||||
@@ -0,0 +1,564 @@
|
||||
//! Mixed armatures end to end (ADR 0098): symbol instances and shapes in one armature. A chain
|
||||
//! that runs shape → instance → shape, posed by angle and by IK as one pose, tweened, with
|
||||
//! springs and joint translation across it; binding per shape; what removing a bone frees;
|
||||
//! the versioned file format (old files unchanged, mixed ones version 4); refusals; renders.
|
||||
|
||||
use super::*;
|
||||
use anicraft_doc::{BlendMode, BoneId, ColorEffect, Document, ElementKind, LoopMode, Paint, Rgba, Shape, Stage, Symbol, SymbolId, SymbolKind, Timeline, evaluate_guided, evaluate_shown};
|
||||
use anicraft_geom::{Affine, Path};
|
||||
use anicraft_render::render_frame;
|
||||
use serde_json::json;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
match s.execute(id, &p) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{id} {p}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const BODY: u64 = 10;
|
||||
pub(crate) const HEAD: u64 = 11;
|
||||
pub(crate) const PLUME: u64 = 12;
|
||||
|
||||
/// A bar `2 × half` px wide and `steps × step` px tall, standing on the origin (anchors every
|
||||
/// `step` px up both sides).
|
||||
fn bar(half: f32, step: f32, steps: usize) -> Path {
|
||||
let mut p = Path::new();
|
||||
p.move_to(Vec2::new(-half, 0.0));
|
||||
for i in 1..=steps {
|
||||
p.line_to(Vec2::new(-half, -step * i as f32));
|
||||
}
|
||||
for i in (0..=steps).rev() {
|
||||
p.line_to(Vec2::new(half, -step * i as f32));
|
||||
}
|
||||
p.close();
|
||||
p
|
||||
}
|
||||
|
||||
/// A 400 × 400 stage, 20 frames, one layer with a character in three parts: a black **body**
|
||||
/// (a raw shape 40 × 160 px standing on (200, 300), its neck at (200, 140)), a red **head** (a
|
||||
/// symbol instance 40 × 40 px centred on (200, 110)) and a blue **plume** on the head (a raw
|
||||
/// shape 8 × 40 px standing on (200, 90)).
|
||||
pub(crate) fn parts() -> Session {
|
||||
let mut d = Document { stage: Stage { width: 400, height: 400, ..Stage::default() }, ..Document::default() };
|
||||
let head = SymbolId(1);
|
||||
let mut inner = Layer::new(LayerId(2), "head");
|
||||
inner.keyframes[0] = Arc::new({
|
||||
let mut k = Keyframe::new(0, 1);
|
||||
k.elements.push(Arc::new(Element { id: ElementId(3), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(-20.0, -20.0, 40.0, 40.0), Paint::Solid(Rgba::hex(0xff0000)))) }));
|
||||
k
|
||||
});
|
||||
d.library.push(Arc::new(Symbol { id: head, name: "Head".into(), kind: SymbolKind::Graphic, linkage: None, scale_grid_kept: None, scale_grid: None, timeline: Timeline { layers: vec![Arc::new(inner)] } }));
|
||||
let shape = |id: u64, path: Path, color: u32, x: f32, y: f32| {
|
||||
let shape = Shape { merge: true, ..Shape::filled(path, Paint::Solid(Rgba::hex(color))) };
|
||||
Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::translate(x, y), color: ColorEffect::default(), kind: ElementKind::Shape(shape) })
|
||||
};
|
||||
let inst = Arc::new(Element { id: ElementId(HEAD), name: String::new(), transform: Affine::translate(200.0, 110.0), color: ColorEffect::default(), kind: ElementKind::Symbol { symbol: head, loop_mode: LoopMode::Loop, first_frame: 0, blend: BlendMode::Normal, filters: Vec::new(), events: Vec::new() } });
|
||||
let l = Arc::make_mut(&mut d.timeline_mut(0).layers[0]);
|
||||
l.keyframes = vec![Arc::new({
|
||||
let mut k = Keyframe::new(0, 20);
|
||||
k.elements = vec![shape(BODY, bar(20.0, 20.0, 8), 0x000000, 200.0, 300.0), inst, shape(PLUME, bar(4.0, 10.0, 4), 0x0000ff, 200.0, 90.0)];
|
||||
k
|
||||
})];
|
||||
d.next_id = 100;
|
||||
Session::new(d)
|
||||
}
|
||||
|
||||
/// The bones of [`character`], from the hips up.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Rig {
|
||||
/// Inside the body: hips (200, 300) → waist (200, 220) → neck (200, 140).
|
||||
pub spine1: u64,
|
||||
pub spine2: u64,
|
||||
/// From the body's neck joint to the head instance, ending at its centre (200, 110).
|
||||
pub neck: u64,
|
||||
/// From the head to the plume shape as a whole, ending at its foot (200, 90).
|
||||
pub crest: u64,
|
||||
/// Inside the plume: foot (200, 90) → tip (200, 50).
|
||||
pub feather: u64,
|
||||
}
|
||||
|
||||
/// [`parts`] rigged as one armature: two bones inside the body, a bone from the neck joint to
|
||||
/// the head instance, a bone from the head to the plume, and a bone inside the plume.
|
||||
pub(crate) fn character() -> (Session, Rig) {
|
||||
let mut s = parts();
|
||||
let bone = |v: Value| v["bone"].as_u64().unwrap();
|
||||
let spine1 = bone(run(&mut s, "bone.add_in_shape", json!({"shape": BODY, "head": [200, 300], "tail": [200, 220]})));
|
||||
let spine2 = bone(run(&mut s, "bone.add_in_shape", json!({"parent": spine1, "tail": [200, 140]})));
|
||||
let neck = bone(run(&mut s, "bone.add", json!({"parent": spine2, "to": HEAD, "tail": [200, 110]})));
|
||||
let crest = bone(run(&mut s, "bone.add", json!({"from": HEAD, "to": PLUME, "tail": [200, 90]})));
|
||||
let feather = bone(run(&mut s, "bone.add_in_shape", json!({"parent": crest, "tail": [200, 50]})));
|
||||
(s, Rig { spine1, spine2, neck, crest, feather })
|
||||
}
|
||||
|
||||
fn armature_layer(s: &Session) -> &Layer {
|
||||
s.doc.timeline(s.scene).layers.iter().find(|l| l.kind == LayerKind::Armature).expect("an armature layer")
|
||||
}
|
||||
|
||||
/// Element `id` as the armature layer shows it at `frame` (keyed pose, no springs).
|
||||
fn shown(s: &Session, id: u64, frame: u32) -> Arc<Element> {
|
||||
let (_, els) = evaluate_layer_elements(armature_layer(s), frame).expect("the armature is on the frame");
|
||||
els.iter().find(|e| e.id.0 == id).expect("the element is on the armature layer").clone()
|
||||
}
|
||||
|
||||
/// The anchors of shape `id` on the stage at `frame`.
|
||||
fn points(s: &Session, id: u64, frame: u32) -> Vec<Vec2> {
|
||||
let e = shown(s, id, frame);
|
||||
match &e.kind {
|
||||
ElementKind::Shape(sh) => anicraft_doc::skin::anchors(&sh.path).into_iter().map(|a| e.transform.apply(a)).collect(),
|
||||
_ => panic!("not a shape"),
|
||||
}
|
||||
}
|
||||
|
||||
fn turned(p: Vec2, j: Vec2, deg: f32) -> Vec2 {
|
||||
let (sn, c) = deg.to_radians().sin_cos();
|
||||
let d = p - j;
|
||||
Vec2::new(j.x + d.x * c - d.y * sn, j.y + d.x * sn + d.y * c)
|
||||
}
|
||||
|
||||
fn close(a: Vec2, b: Vec2) -> bool {
|
||||
a.distance(b) < 2e-3
|
||||
}
|
||||
|
||||
fn bone_info(s: &mut Session, frame: u32, bone: u64) -> Value {
|
||||
let v = run(s, "bone.info", json!({"frame": frame}));
|
||||
v["armatures"][0]["bones"].as_array().unwrap().iter().find(|b| b["id"] == bone).cloned().unwrap()
|
||||
}
|
||||
|
||||
fn pt(v: &Value) -> Vec2 {
|
||||
Vec2::new(v[0].as_f64().unwrap() as f32, v[1].as_f64().unwrap() as f32)
|
||||
}
|
||||
|
||||
const WAIST: Vec2 = Vec2 { x: 200.0, y: 220.0 };
|
||||
|
||||
#[test]
|
||||
fn instances_and_shapes_join_one_armature_as_drawn() {
|
||||
let before = render_frame(&parts().doc, 0, 1.0).unwrap().data;
|
||||
let body_drawn: Vec<Vec2> = anicraft_doc::skin::anchors(&bar(20.0, 20.0, 8)).into_iter().map(|p| p + Vec2::new(200.0, 300.0)).collect();
|
||||
let (mut s, r) = character();
|
||||
let tl = s.doc.timeline(0);
|
||||
assert_eq!(tl.layers.len(), 2, "one armature layer above the layer the parts were on");
|
||||
assert!(tl.layers[1].keyframes[0].elements.is_empty(), "every part left its layer");
|
||||
let l = armature_layer(&s);
|
||||
assert_eq!(s.layer, l.id);
|
||||
assert_eq!(l.keyframes[0].elements.iter().map(|e| e.id.0).collect::<Vec<_>>(), vec![BODY, HEAD, PLUME]);
|
||||
let arm = l.armature.as_ref().unwrap();
|
||||
assert!(arm.is_mixed());
|
||||
assert_eq!(arm.skins.iter().map(|k| k.shape.0).collect::<Vec<_>>(), vec![BODY, PLUME], "several shapes with bones in one armature");
|
||||
// The rest pose is the drawing, exactly: outlines bit for bit, transforms unchanged.
|
||||
assert_eq!(render_frame(&s.doc, 0, 1.0).unwrap().data, before);
|
||||
assert_eq!(points(&s, BODY, 0), body_drawn);
|
||||
for (id, at) in [(BODY, (200.0, 300.0)), (HEAD, (200.0, 110.0)), (PLUME, (200.0, 90.0))] {
|
||||
let e = shown(&s, id, 0);
|
||||
assert_eq!(e.transform, Affine::translate(at.0, at.1), "{id} is where it was drawn");
|
||||
if let ElementKind::Shape(sh) = &e.kind {
|
||||
assert!(!sh.merge, "an armature's shape is an object");
|
||||
assert!(Arc::ptr_eq(&sh.path, &arm.skin(e.id).unwrap().rest), "at rest the outline is the drawn path itself");
|
||||
}
|
||||
}
|
||||
let v = run(&mut s, "bone.info", json!({"points": true}));
|
||||
let a = &v["armatures"][0];
|
||||
assert_eq!(a["mixed"], true);
|
||||
assert_eq!(a["roots"], json!([BODY]));
|
||||
assert_eq!(a["members"], json!([BODY, HEAD, PLUME]));
|
||||
assert_eq!(a["shape"], BODY);
|
||||
let shapes = a["shapes"].as_array().unwrap();
|
||||
assert_eq!((shapes[0]["shape"].as_u64(), shapes[1]["shape"].as_u64()), (Some(BODY), Some(PLUME)));
|
||||
assert_eq!(shapes[0]["bones"], json!([r.spine1, r.spine2]));
|
||||
assert_eq!(shapes[1]["bones"], json!([r.feather]));
|
||||
assert_eq!((shapes[0]["points"].as_array().unwrap().len(), shapes[1]["points"].as_array().unwrap().len()), (18, 10));
|
||||
let bones = a["bones"].as_array().unwrap();
|
||||
let of = |id: u64| bones.iter().find(|b| b["id"] == id).unwrap();
|
||||
assert_eq!((of(r.spine2)["shape"].as_u64(), of(r.feather)["shape"].as_u64()), (Some(BODY), Some(PLUME)));
|
||||
assert_eq!((&of(r.neck)["shape"], &of(r.crest)["shape"]), (&Value::Null, &Value::Null));
|
||||
assert_eq!((of(r.neck)["to"].as_u64(), of(r.crest)["to"].as_u64()), (Some(HEAD), Some(PLUME)));
|
||||
// The chain joins end to start across the kinds.
|
||||
assert_eq!(of(r.neck)["parent_bone"], r.spine2);
|
||||
assert_eq!(of(r.crest)["parent_bone"], r.neck);
|
||||
assert_eq!(of(r.feather)["parent_bone"], r.crest);
|
||||
assert_eq!(of(r.neck)["head"], json!([200.0, 140.0]), "the head's bone starts on the body's neck joint");
|
||||
assert_eq!(of(r.crest)["head"], json!([200.0, 110.0]));
|
||||
assert_eq!(of(r.feather)["head"], json!([200.0, 90.0]));
|
||||
assert_eq!(of(r.feather)["tail"], json!([200.0, 50.0]));
|
||||
// Each bone was one undo step; undoing them all puts the parts back on their layer.
|
||||
for _ in 0..5 {
|
||||
s.undo().unwrap();
|
||||
}
|
||||
assert_eq!(s.doc, parts().doc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_pose_moves_both_kinds_together() {
|
||||
let (mut s, r) = character();
|
||||
run(&mut s, "bone.pose", json!({"bone": r.spine2, "angle": 30}));
|
||||
// The body's neck points follow the bone (they are bound to it alone)...
|
||||
let body = points(&s, BODY, 0);
|
||||
assert!(close(body[8], turned(Vec2::new(180.0, 140.0), WAIST, 30.0)), "{:?}", body[8]);
|
||||
assert!(close(body[9], turned(Vec2::new(220.0, 140.0), WAIST, 30.0)));
|
||||
assert_eq!(body[0], Vec2::new(180.0, 300.0), "the hips stay");
|
||||
// ...the head instance turns rigidly about the same joint, still sitting on the neck...
|
||||
let head = shown(&s, HEAD, 0);
|
||||
assert!(close(head.transform.translation(), turned(Vec2::new(200.0, 110.0), WAIST, 30.0)));
|
||||
assert!(close(head.transform.apply(Vec2::new(0.0, 30.0)), turned(Vec2::new(200.0, 140.0), WAIST, 30.0)), "the head's joint is the body's neck");
|
||||
assert!(close(pt(&bone_info(&mut s, 0, r.neck)["head"]), pt(&bone_info(&mut s, 0, r.spine2)["tail"])));
|
||||
// ...and the plume rides the head, its outline untouched (its own bone is at rest).
|
||||
let plume = shown(&s, PLUME, 0);
|
||||
assert!(close(plume.transform.translation(), turned(Vec2::new(200.0, 90.0), WAIST, 30.0)));
|
||||
let arm = armature_layer(&s).armature.clone().unwrap();
|
||||
assert!(matches!(&plume.kind, ElementKind::Shape(sh) if Arc::ptr_eq(&sh.path, &arm.skin(ElementId(PLUME)).unwrap().rest)));
|
||||
// The plume's own bone bends it on top of that.
|
||||
run(&mut s, "bone.pose", json!({"bone": r.feather, "angle": 45}));
|
||||
let tip = points(&s, PLUME, 0)[4];
|
||||
assert!(close(tip, turned(turned(Vec2::new(196.0, 50.0), Vec2::new(200.0, 90.0), 45.0), WAIST, 30.0)), "{tip:?}");
|
||||
assert_eq!(shown(&s, HEAD, 0).transform, head.transform, "bending the plume leaves the head");
|
||||
// The keyframe holds what shows (ADR 0043): the file needs no evaluation to draw the pose.
|
||||
let stored = armature_layer(&s).keyframes[0].elements.clone();
|
||||
assert_eq!(stored.iter().find(|e| e.id.0 == HEAD).unwrap().transform, head.transform);
|
||||
// The render shows the head where the pose put it, and nothing where it was.
|
||||
let img = render_frame(&s.doc, 0, 1.0).unwrap();
|
||||
let at = turned(Vec2::new(200.0, 110.0), WAIST, 30.0);
|
||||
let px = img.pixel(at.x as u32, at.y as u32).unwrap();
|
||||
assert!(px[0] > 0.9 && px[1] < 0.1, "the head is red at {at:?}: {px:?}");
|
||||
assert!(img.pixel(200, 110).unwrap()[1] > 0.9, "nothing is left where the head was drawn");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ik_runs_through_shape_bones_and_instances_as_one_chain() {
|
||||
let (mut s, r) = character();
|
||||
let steps = s.history_len();
|
||||
let rest = points(&s, BODY, 0);
|
||||
s.begin_gesture("Pose Armature");
|
||||
for x in [220.0, 240.0, 260.0] {
|
||||
run(&mut s, "bone.solve", json!({"bone": r.neck, "x": x, "y": 150}));
|
||||
}
|
||||
s.end_gesture();
|
||||
assert_eq!(s.history_len(), steps + 1, "one drag is one undo step");
|
||||
let v = run(&mut s, "bone.solve", json!({"bone": r.neck, "x": 260, "y": 150}));
|
||||
assert_eq!((v["reached"].as_bool(), v["chain"].as_u64()), (Some(true), Some(3)), "the head's bone, then the two inside the body: {v}");
|
||||
assert!(pt(&bone_info(&mut s, 0, r.neck)["tail"]).distance(Vec2::new(260.0, 150.0)) < 0.5);
|
||||
assert!(shown(&s, HEAD, 0).transform.translation().distance(Vec2::new(260.0, 150.0)) < 0.5, "the head's centre is where it was dragged");
|
||||
assert_ne!(points(&s, BODY, 0), rest, "the body bent to get it there");
|
||||
// Dragging the plume's tip turns the whole chain, bending the body and the plume.
|
||||
let v = run(&mut s, "bone.solve", json!({"bone": r.feather, "x": 150, "y": 120}));
|
||||
assert_eq!(v["chain"], 5);
|
||||
assert_eq!(v["reached"], true, "{v}");
|
||||
// A pin on the head's bone holds everything it hangs from: only the plume moves.
|
||||
run(&mut s, "bone.pin", json!({"bone": r.neck, "pinned": true}));
|
||||
let (body, head) = (points(&s, BODY, 0), shown(&s, HEAD, 0).transform);
|
||||
let v = run(&mut s, "bone.solve", json!({"bone": r.feather, "x": 400, "y": 0}));
|
||||
assert_eq!(v["chain"], 2, "the plume's bone and the bone that carries the plume");
|
||||
assert_eq!((points(&s, BODY, 0), shown(&s, HEAD, 0).transform), (body, head));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mixed_pose_tweens_as_one() {
|
||||
let (mut s, r) = character();
|
||||
run(&mut s, "bone.pose", json!({"bone": r.spine2, "angle": 40, "frame": 10}));
|
||||
run(&mut s, "bone.pose", json!({"bone": r.feather, "angle": -60, "frame": 10}));
|
||||
assert_eq!(shown(&s, HEAD, 0).transform, Affine::translate(200.0, 110.0), "the first pose is untouched");
|
||||
for (frame, deg) in [(5, 20.0), (10, 40.0), (15, 40.0)] {
|
||||
let head = shown(&s, HEAD, frame).transform;
|
||||
assert!(close(head.translation(), turned(Vec2::new(200.0, 110.0), WAIST, deg)), "frame {frame}");
|
||||
assert!(close(points(&s, BODY, frame)[8], turned(Vec2::new(180.0, 140.0), WAIST, deg)), "frame {frame}");
|
||||
// The plume: bent by its own bone (half way at frame 5), carried by the head.
|
||||
let own = if frame == 5 { -30.0 } else { -60.0 };
|
||||
assert!(close(points(&s, PLUME, frame)[4], turned(turned(Vec2::new(196.0, 50.0), Vec2::new(200.0, 90.0), own), WAIST, deg)), "frame {frame}");
|
||||
}
|
||||
// The display list every export draws sees the same thing.
|
||||
let dl = anicraft_doc::evaluate(&s.doc, 5);
|
||||
let item = dl.items.iter().find(|i| i.element.0 == BODY).unwrap();
|
||||
assert!(close(item.transform.apply(anicraft_doc::skin::anchors(&item.path)[8]), turned(Vec2::new(180.0, 140.0), WAIST, 20.0)));
|
||||
assert!(dl.items.iter().any(|i| i.element.0 == HEAD && close(i.transform.apply(Vec2::new(0.0, 0.0)), turned(Vec2::new(200.0, 110.0), WAIST, 20.0))), "the head's artwork is drawn posed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translation_and_springs_act_across_the_kinds() {
|
||||
let (mut s, r) = character();
|
||||
// The neck stretches: the head and the plume on it move, the body doesn't.
|
||||
run(&mut s, "bone.set_translation", json!({"bone": r.neck, "axis": "y", "min": -20, "max": 20}));
|
||||
run(&mut s, "bone.pose", json!({"bone": r.neck, "slide_y": -10}));
|
||||
assert!(close(shown(&s, HEAD, 0).transform.translation(), Vec2::new(200.0, 100.0)));
|
||||
assert!(close(shown(&s, PLUME, 0).transform.translation(), Vec2::new(200.0, 80.0)));
|
||||
assert_eq!(points(&s, BODY, 0), points(&character().0, BODY, 0));
|
||||
// A joint inside the body slides: its points, the head and the plume all go with it.
|
||||
run(&mut s, "bone.set_translation", json!({"bone": r.spine2, "axis": "x", "min": -30, "max": 30}));
|
||||
run(&mut s, "bone.pose", json!({"bone": r.spine2, "slide_x": 15}));
|
||||
assert!(close(points(&s, BODY, 0)[8], Vec2::new(195.0, 140.0)));
|
||||
assert!(close(shown(&s, HEAD, 0).transform.translation(), Vec2::new(215.0, 100.0)));
|
||||
// IK stretches the neck only where turning can't reach.
|
||||
let v = run(&mut s, "bone.solve", json!({"bone": r.neck, "x": 200, "y": 95}));
|
||||
assert_eq!(v["reached"], true, "{v}");
|
||||
// Springs: the head and the plume lag behind the body's swing, on every evaluation alike.
|
||||
let (mut s, r) = character();
|
||||
run(&mut s, "bone.set_spring", json!({"bone": r.neck, "strength": 30, "damping": 5}));
|
||||
run(&mut s, "bone.set_spring", json!({"bone": r.feather, "strength": 30, "damping": 5}));
|
||||
run(&mut s, "bone.pose", json!({"bone": r.spine1, "angle": 50, "frame": 6}));
|
||||
let fps = s.doc.stage.fps;
|
||||
let l = armature_layer(&s);
|
||||
let at = |id: u64, els: &[Arc<Element>]| els.iter().find(|e| e.id.0 == id).unwrap().clone();
|
||||
let mut swung = 0;
|
||||
for frame in 1..14 {
|
||||
let (_, sprung) = evaluate_shown(l, frame, None, fps).unwrap();
|
||||
let (_, keyed) = evaluate_guided(l, frame, None).unwrap();
|
||||
assert_eq!(at(BODY, &sprung), at(BODY, &keyed), "the body's bones have no spring: frame {frame}");
|
||||
swung += usize::from(at(HEAD, &sprung).transform != at(HEAD, &keyed).transform && at(PLUME, &sprung) != at(PLUME, &keyed));
|
||||
let (_, again) = evaluate_shown(l, frame, None, fps).unwrap();
|
||||
assert_eq!(sprung.to_vec(), again.to_vec(), "seeking gives the same bits");
|
||||
assert!(sprung.iter().all(|e| e.transform.is_finite()));
|
||||
}
|
||||
assert!(swung >= 6, "the head and the plume swing while the body moves and after: {swung} frames");
|
||||
assert!(bone_info(&mut s, 8, r.neck)["swing"].as_f64().unwrap().abs() > 0.01);
|
||||
// Springs off: the keyed poses, exactly.
|
||||
run(&mut s, "bone.enable_springs", json!({"bone": r.neck, "enabled": false}));
|
||||
let l = armature_layer(&s);
|
||||
assert_eq!(evaluate_shown(l, 8, None, fps).unwrap().1.to_vec(), evaluate_guided(l, 8, None).unwrap().1.to_vec());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_bone_binds_the_points_of_its_own_shape() {
|
||||
let (mut s, r) = character();
|
||||
let skins = |s: &Session| armature_layer(s).armature.as_ref().unwrap().skins.clone();
|
||||
let before = skins(&s);
|
||||
assert!(before[1].points.iter().all(|b| b.bones == vec![anicraft_doc::skin::Influence(BoneId(r.feather), 1.0)]), "the plume's points follow its one bone, not the body's");
|
||||
assert!(before[0].points.iter().all(|b| b.bones.iter().all(|i| i.0.0 == r.spine1 || i.0.0 == r.spine2)));
|
||||
// Point indices are those of the bone's shape.
|
||||
let v = run(&mut s, "bone.bind", json!({"bone": r.feather, "points": [0, 9], "mode": "remove"}));
|
||||
assert_eq!((v["changed"].as_u64(), v["bound"].as_u64(), v["shape"].as_u64()), (Some(2), Some(8), Some(PLUME)));
|
||||
assert_eq!(skins(&s)[0], before[0], "the body's binding is untouched");
|
||||
assert!(s.execute("bone.bind", &json!({"bone": r.feather, "points": [10]})).unwrap_err().to_string().contains("below 10"));
|
||||
// The weight brush paints the picked bone's shape only, even where shapes are close.
|
||||
let v = run(&mut s, "bone.paint_weights", json!({"bone": r.spine2, "at": [[200, 140]], "radius": 400, "strength": 100}));
|
||||
assert_eq!(v["bound"], 18);
|
||||
assert_eq!(skins(&s)[1].points[1], before[1].points[1], "the plume is inside the brush but isn't the bone's shape");
|
||||
let v = run(&mut s, "bone.set_weight", json!({"bone": r.feather, "points": [0], "weight": 100}));
|
||||
assert_eq!(v["weights"], json!([[[r.feather, 100.0]]]));
|
||||
// Bones that move an instance or a whole shape have no points.
|
||||
for b in [r.neck, r.crest] {
|
||||
for id in ["bone.bind", "bone.paint_weights", "bone.set_weight"] {
|
||||
let e = s.execute(id, &json!({"bone": b, "at": [[0, 0]], "points": [0], "weight": 50})).unwrap_err().to_string();
|
||||
assert!(e.contains("only bones inside a shape"), "{id}: {e}");
|
||||
}
|
||||
}
|
||||
// Adding a bone inside one shape rebinds that shape; a hand-bound point elsewhere stays.
|
||||
run(&mut s, "bone.bind", json!({"bone": r.spine1, "points": [17], "mode": "only"}));
|
||||
run(&mut s, "bone.add_in_shape", json!({"parent": r.feather, "tail": [200, 40]}));
|
||||
assert!(skins(&s)[0].points[17].manual);
|
||||
assert_eq!(skins(&s)[0].points[17].bones, vec![anicraft_doc::skin::Influence(BoneId(r.spine1), 1.0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_bone_frees_what_it_moved() {
|
||||
// A bone inside a shape: the shape stays in the armature, as it looked, without a skin.
|
||||
let (mut s, r) = character();
|
||||
run(&mut s, "bone.pose", json!({"bone": r.feather, "angle": 45}));
|
||||
let bent = points(&s, PLUME, 0);
|
||||
let v = run(&mut s, "bone.remove", json!({"bone": r.feather}));
|
||||
assert_eq!((&v["removed"], &v["freed"], &v["unbound"], &v["armature_removed"]), (&json!([r.feather]), &json!([]), &json!([PLUME]), &json!(false)));
|
||||
let l = armature_layer(&s);
|
||||
assert_eq!(v["layer"], l.id.0);
|
||||
let arm = l.armature.as_ref().unwrap();
|
||||
assert_eq!(arm.skins.len(), 1);
|
||||
assert_eq!(arm.members().iter().map(|e| e.0).collect::<Vec<_>>(), vec![BODY, HEAD, PLUME], "the plume still rides the head");
|
||||
assert_eq!(points(&s, PLUME, 0), bent, "it keeps the outline it showed");
|
||||
run(&mut s, "bone.pose", json!({"bone": r.spine2, "angle": 30}));
|
||||
assert!(close(shown(&s, PLUME, 0).transform.translation(), turned(Vec2::new(200.0, 90.0), WAIST, 30.0)));
|
||||
s.undo().unwrap();
|
||||
s.undo().unwrap();
|
||||
assert_eq!(s.doc, {
|
||||
let (mut again, r) = character();
|
||||
run(&mut again, "bone.pose", json!({"bone": r.feather, "angle": 45}));
|
||||
again.doc
|
||||
});
|
||||
// The bone that carries the head: the head, the plume on it and the plume's bone go; they
|
||||
// land on a layer of their own as they looked, and what is left is a shape armature again.
|
||||
let (mut s, r) = character();
|
||||
run(&mut s, "bone.pose", json!({"bone": r.spine2, "angle": 30}));
|
||||
run(&mut s, "bone.pose", json!({"bone": r.feather, "angle": 45}));
|
||||
let (head, plume) = (shown(&s, HEAD, 0), shown(&s, PLUME, 0));
|
||||
let v = run(&mut s, "bone.remove", json!({"bone": r.neck}));
|
||||
assert_eq!((&v["removed"], &v["freed"], &v["armature_removed"]), (&json!([r.neck, r.crest, r.feather]), &json!([HEAD, PLUME]), &json!(false)));
|
||||
let tl = s.doc.timeline(0);
|
||||
assert_eq!(tl.layers.len(), 3);
|
||||
let freed = &tl.layers[1];
|
||||
assert_eq!((freed.id.0, freed.kind), (v["layer"].as_u64().unwrap(), LayerKind::Normal));
|
||||
assert_eq!(freed.keyframes[0].elements, vec![head, plume], "posed and bent as they showed");
|
||||
let arm = tl.layers[0].armature.as_ref().unwrap();
|
||||
assert!(!arm.is_mixed());
|
||||
assert_eq!(arm.bones.len(), 2);
|
||||
assert!(!s.doc.has_mixed_armatures());
|
||||
assert!(close(points(&s, BODY, 0)[8], turned(Vec2::new(180.0, 140.0), WAIST, 30.0)), "the body keeps its pose");
|
||||
// The first bone: the whole armature goes, everything where it showed.
|
||||
let (mut s, r) = character();
|
||||
run(&mut s, "bone.pose", json!({"bone": r.spine2, "angle": 30}));
|
||||
let all = [shown(&s, BODY, 0), shown(&s, HEAD, 0), shown(&s, PLUME, 0)];
|
||||
let v = run(&mut s, "bone.remove", json!({"bone": r.spine1}));
|
||||
assert_eq!((&v["freed"], &v["armature_removed"]), (&json!([BODY, HEAD, PLUME]), &json!(true)));
|
||||
let tl = s.doc.timeline(0);
|
||||
assert!(tl.layers.iter().all(|l| l.kind == LayerKind::Normal && l.armature.is_none()));
|
||||
assert_eq!(tl.layers[0].keyframes[0].elements, all.to_vec());
|
||||
// More than one pose: it asks first (ADR 0004).
|
||||
let (mut s, r) = character();
|
||||
run(&mut s, "bone.pose", json!({"bone": r.spine2, "angle": 30, "frame": 10}));
|
||||
assert!(crate::confirm::confirmation(&s, "bone.remove", &json!({"bone": r.neck})).is_some());
|
||||
}
|
||||
|
||||
/// The same text but for the generator line (the version of the AniCraft that wrote it) and
|
||||
/// line endings (a checkout may rewrite them).
|
||||
fn comparable(text: &str) -> String {
|
||||
text.lines().filter(|l| !l.contains("\"generator\"")).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_before_mixed_armatures_load_and_save_unchanged() {
|
||||
for (name, text) in [("instances", include_str!("../tests/fixtures/armature-v3-instances.anicraft")), ("shape", include_str!("../tests/fixtures/armature-v3-shape.anicraft"))] {
|
||||
let doc = crate::format::from_json(text).unwrap();
|
||||
let arm = doc.timeline(0).layers.iter().find_map(|l| l.armature.clone()).unwrap();
|
||||
assert!(!arm.is_mixed() && !doc.has_mixed_armatures(), "{name}");
|
||||
assert_eq!(arm.skins.len(), usize::from(name == "shape"), "{name}");
|
||||
assert!(arm.bones.iter().all(|b| b.shape == arm.skins.first().map(|k| k.shape)), "{name}: a shape armature's bones are all inside its shape");
|
||||
assert_eq!(crate::format::version_for(&doc), 3, "{name}");
|
||||
// Saved again it is the file an earlier AniCraft wrote, byte for byte.
|
||||
let again = crate::format::to_json(&doc).unwrap();
|
||||
assert_eq!(comparable(&again), comparable(text), "{name}");
|
||||
// And it still plays: the poses it holds evaluate to the outlines and transforms it holds.
|
||||
let l = doc.timeline(0).layers.iter().find(|l| l.kind == LayerKind::Armature).unwrap();
|
||||
for k in &l.keyframes {
|
||||
let (_, els) = evaluate_layer_elements(l, k.start).unwrap();
|
||||
assert_eq!(els.to_vec(), k.elements, "{name}: frame {}", k.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_armatures_are_written_as_version_4() {
|
||||
let (mut s, r) = character();
|
||||
run(&mut s, "bone.pose", json!({"bone": r.spine2, "angle": 30, "frame": 10}));
|
||||
run(&mut s, "bone.bind", json!({"bone": r.feather, "points": [0], "mode": "remove"}));
|
||||
let text = crate::format::to_json(&s.doc).unwrap();
|
||||
let env: Value = serde_json::from_str(&text).unwrap();
|
||||
// Builds from before ADR 0098 read up to version 3 and refuse this file by its number.
|
||||
assert_eq!(env["version"], 4);
|
||||
assert_eq!(crate::format::BASE_VERSION, 3, "the version earlier builds stop at");
|
||||
let arm = &env["document"]["scenes"][0]["timeline"]["layers"][0]["armature"];
|
||||
assert!(arm["skin"].is_null() && arm["skins"].as_array().is_some_and(|k| k.len() == 2), "the mixed form: {arm}");
|
||||
assert_eq!(arm["bones"][0]["shape"], BODY);
|
||||
assert!(arm["bones"][2].get("shape").is_none(), "a bone that moves an element says nothing");
|
||||
let back = crate::format::from_json(&text).unwrap();
|
||||
assert_eq!(back, s.doc);
|
||||
assert_eq!(crate::format::to_json(&back).unwrap(), text);
|
||||
// Without the bones that mix the kinds the document is version 3 again.
|
||||
run(&mut s, "bone.remove", json!({"bone": r.neck, "confirm": true}));
|
||||
let env: Value = serde_json::from_str(&crate::format::to_json(&s.doc).unwrap()).unwrap();
|
||||
assert_eq!(env["version"], 3);
|
||||
let arm = &env["document"]["scenes"][0]["timeline"]["layers"][0]["armature"];
|
||||
assert!(arm["skin"].is_object() && arm.get("skins").is_none(), "the first form: {arm}");
|
||||
assert!(arm["bones"].as_array().unwrap().iter().all(|b| b.get("shape").is_none()));
|
||||
// A file from a later AniCraft is refused with a message that says why.
|
||||
let later = text.replacen("\"version\": 4", "\"version\": 5", 1);
|
||||
let e = crate::format::from_json(&later).unwrap_err().to_string();
|
||||
assert!(e.contains("file version 5 is newer than this AniCraft"), "{e}");
|
||||
// A mixed armature inside a symbol counts too.
|
||||
let (s, _) = character();
|
||||
let mut d = s.doc.clone();
|
||||
let layers = std::mem::take(&mut d.timeline_mut(0).layers);
|
||||
assert!(!d.has_mixed_armatures());
|
||||
Arc::make_mut(&mut d.library[0]).timeline.layers = layers;
|
||||
assert!(d.has_mixed_armatures());
|
||||
assert_eq!(crate::format::version_for(&d), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_bones_refuse_what_cant_be_joined() {
|
||||
let (mut s, r) = character();
|
||||
let steps = s.history_len();
|
||||
for (id, p, want) in [
|
||||
("bone.add", json!({"parent": r.spine2, "from": BODY, "to": HEAD}), "not both"),
|
||||
("bone.add", json!({"to": HEAD}), "required"),
|
||||
("bone.add", json!({"parent": r.spine2}), "required"),
|
||||
("bone.add", json!({"parent": 9999, "to": HEAD}), "no bone"),
|
||||
("bone.add", json!({"parent": r.spine2, "to": PLUME}), "already"),
|
||||
("bone.add", json!({"parent": r.feather, "to": BODY}), "root"),
|
||||
("bone.add", json!({"parent": r.neck, "to": HEAD}), "two different"),
|
||||
("bone.add", json!({"from": PLUME, "to": 999}), "no instance or shape"),
|
||||
("bone.add_in_shape", json!({"parent": r.neck, "tail": [0, 0]}), "symbol instance"),
|
||||
("bone.add_in_shape", json!({"parent": r.crest, "shape": BODY, "tail": [0, 0]}), "another shape"),
|
||||
("bone.add_in_shape", json!({"shape": HEAD, "head": [200, 110], "tail": [220, 110]}), "need a shape"),
|
||||
] {
|
||||
let e = s.execute(id, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{id} {p}: {e}");
|
||||
}
|
||||
assert_eq!(s.history_len(), steps, "refusals leave no undo steps");
|
||||
// Two armatures don't join.
|
||||
let mut s = parts();
|
||||
run(&mut s, "bone.add_in_shape", json!({"shape": BODY, "head": [200, 300], "tail": [200, 140]}));
|
||||
run(&mut s, "bone.add_in_shape", json!({"shape": PLUME, "head": [200, 90], "tail": [200, 50]}));
|
||||
let e = s.execute("bone.add", &json!({"from": BODY, "to": PLUME})).unwrap_err().to_string();
|
||||
assert!(e.contains("different armatures"), "{e}");
|
||||
// Artwork edits are still refused on the armature layer, whatever the member.
|
||||
let (mut s, _) = character();
|
||||
for el in [BODY, HEAD, PLUME] {
|
||||
s.select_only([ElementId(el)]);
|
||||
let e = s.execute("element.translate", &json!({"dx": 5, "dy": 0})).unwrap_err().to_string();
|
||||
assert!(e.contains("armature"), "{el}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_starts_a_chain_that_continues_into_a_shape() {
|
||||
// The other way round: the head is the root, the body hangs from it and bends.
|
||||
let mut s = parts();
|
||||
let bone = |v: Value| v["bone"].as_u64().unwrap();
|
||||
let v = run(&mut s, "bone.add", json!({"from": HEAD, "to": BODY, "head": [200, 130], "tail": [200, 140]}));
|
||||
assert_eq!(v["created"], true);
|
||||
let hold = bone(v);
|
||||
let arm = armature_layer(&s).armature.clone().unwrap();
|
||||
assert!(arm.skins.is_empty() && !arm.is_mixed(), "a shape moved as a whole needs no skin: the first file form holds it");
|
||||
assert_eq!(crate::format::version_for(&s.doc), 3);
|
||||
assert!(matches!(&shown(&s, BODY, 0).kind, ElementKind::Shape(sh) if !sh.merge));
|
||||
// Turning it swings the whole body about the joint, outline untouched.
|
||||
run(&mut s, "bone.pose", json!({"bone": hold, "angle": 90}));
|
||||
assert!(close(points(&s, BODY, 0)[0], turned(Vec2::new(180.0, 300.0), Vec2::new(200.0, 130.0), 90.0)));
|
||||
run(&mut s, "bone.pose", json!({"bone": hold, "angle": 0}));
|
||||
// From that bone's end, bones inside the body: now its outline bends too.
|
||||
let v = run(&mut s, "bone.add_in_shape", json!({"parent": hold, "tail": [200, 220]}));
|
||||
assert_eq!((v["shape"].as_u64(), v["created"].as_bool()), (Some(BODY), Some(false)));
|
||||
let b1 = bone(v);
|
||||
let b2 = bone(run(&mut s, "bone.add_in_shape", json!({"parent": b1, "tail": [200, 300]})));
|
||||
assert_eq!(bone_info(&mut s, 0, b1)["head"], json!([200.0, 140.0]), "it starts on the end of the bone into the shape");
|
||||
assert!(armature_layer(&s).armature.as_ref().unwrap().is_mixed());
|
||||
assert_eq!(crate::format::version_for(&s.doc), 4);
|
||||
run(&mut s, "bone.pose", json!({"bone": hold, "angle": 20}));
|
||||
run(&mut s, "bone.pose", json!({"bone": b2, "angle": 30}));
|
||||
let neck = Vec2::new(200.0, 130.0);
|
||||
assert!(close(points(&s, BODY, 0)[0], turned(turned(Vec2::new(180.0, 300.0), WAIST, 30.0), neck, 20.0)), "bent by its own bone, carried by the head's: {:?}", points(&s, BODY, 0)[0]);
|
||||
assert_eq!(shown(&s, HEAD, 0).transform, Affine::translate(200.0, 110.0), "the root stays");
|
||||
// Reshaping at rest still works on a shape that hangs from a bone (ADR 0090).
|
||||
run(&mut s, "bone.pose", json!({"bone": b2, "angle": 0}));
|
||||
s.select_only([ElementId(BODY)]);
|
||||
assert!(crate::cmds_bone::is_skin_shape(&s, ElementId(BODY)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plug_ins_may_build_mixed_armatures() {
|
||||
for id in ["bone.add", "bone.add_in_shape", "bone.remove", "bone.bind", "bone.info"] {
|
||||
assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluation cost of a mixed armature (the test profile is optimised; a release build is
|
||||
/// faster still).
|
||||
#[test]
|
||||
fn evaluating_a_mixed_armature_is_fast() {
|
||||
let (mut s, r) = character();
|
||||
run(&mut s, "bone.pose", json!({"bone": r.spine2, "angle": 40, "frame": 10}));
|
||||
run(&mut s, "bone.pose", json!({"bone": r.feather, "angle": -60, "frame": 10}));
|
||||
let l = armature_layer(&s).clone();
|
||||
let t = std::time::Instant::now();
|
||||
let n = 2000;
|
||||
for i in 0..n {
|
||||
std::hint::black_box(evaluate_layer_elements(&l, 1 + (i % 9)));
|
||||
}
|
||||
let per = t.elapsed().as_secs_f64() * 1e3 / f64::from(n);
|
||||
println!("mixed armature (5 bones, 2 skinned shapes of 18 and 10 points, 1 instance): {per:.4} ms per evaluated frame");
|
||||
assert!(per < 2.0, "{per} ms");
|
||||
}
|
||||
@@ -225,10 +225,10 @@ fn shape_bones_refuse_what_cant_be_done() {
|
||||
let e = s.execute(id, &p).unwrap_err().to_string();
|
||||
assert!(e.contains("armature"), "{id}: {e}");
|
||||
}
|
||||
// Bones of symbol instances bind nothing; instances don't join a shape's armature.
|
||||
// Bones of symbol instances bind nothing, and no bone goes inside an instance.
|
||||
let (mut inst, ib1, _) = crate::tests_bone::rigged();
|
||||
assert!(inst.execute("bone.bind", &json!({"bone": ib1})).unwrap_err().to_string().contains("instances"));
|
||||
assert!(inst.execute("bone.add_in_shape", &json!({"parent": ib1, "tail": [0, 0]})).unwrap_err().to_string().contains("instances"));
|
||||
assert!(inst.execute("bone.add_in_shape", &json!({"parent": ib1, "tail": [0, 0]})).unwrap_err().to_string().contains("instance"));
|
||||
let e = inst.execute("bone.add_in_shape", &json!({"shape": crate::tests_bone::ROOT, "head": [150, 100], "tail": [190, 100]})).unwrap_err().to_string();
|
||||
assert!(e.contains("shape"), "{e}");
|
||||
}
|
||||
@@ -252,7 +252,7 @@ fn removing_shape_bones_rebinds_and_the_last_frees_the_shape_as_it_looks() {
|
||||
let tl = s.doc.timeline(0);
|
||||
assert_eq!(tl.layers.len(), 2, "no layer for freed instances: a shape's bones move none");
|
||||
let arm = tl.layers[0].armature.as_ref().unwrap();
|
||||
assert!(arm.skin.as_ref().unwrap().points.iter().all(|p| p.bones == vec![anicraft_doc::skin::Influence(anicraft_doc::BoneId(b1), 1.0)]), "every point follows the bone that's left");
|
||||
assert!(arm.skins.first().unwrap().points.iter().all(|p| p.bones == vec![anicraft_doc::skin::Influence(anicraft_doc::BoneId(b1), 1.0)]), "every point follows the bone that's left");
|
||||
let shown = points(&s, 0);
|
||||
run(&mut s, "bone.remove", json!({"bone": b1}));
|
||||
let tl = s.doc.timeline(0);
|
||||
@@ -276,7 +276,7 @@ fn shape_armatures_survive_a_file_round_trip_and_render_the_same() {
|
||||
assert_eq!(render_frame(&back, f, 1.0).unwrap().data, render_frame(&s.doc, f, 1.0).unwrap().data, "frame {f}");
|
||||
}
|
||||
// The file stores the outline as drawn, so a keyframe's bent outline never drifts.
|
||||
let skin = back.timeline(0).layers[0].armature.as_ref().unwrap().skin.clone().unwrap();
|
||||
let skin = back.timeline(0).layers[0].armature.as_ref().unwrap().skins.first().cloned().unwrap();
|
||||
assert_eq!(skin.rest.cmds.first(), Some(&PathCmd::MoveTo(Vec2::new(0.0, -10.0))));
|
||||
// New ids never collide with the bones' joint nodes.
|
||||
let mut back = Session::new(back);
|
||||
|
||||
@@ -49,7 +49,7 @@ fn rigged() -> (Session, u64, u64) {
|
||||
}
|
||||
|
||||
fn skin(s: &Session) -> anicraft_doc::skin::Skin {
|
||||
s.timeline().layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skin.clone())).unwrap()
|
||||
s.timeline().layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skins.first().cloned())).unwrap()
|
||||
}
|
||||
|
||||
fn weight(s: &Session, point: usize, bone: u64) -> f32 {
|
||||
@@ -203,7 +203,7 @@ fn files_keep_painted_and_reshaped_bindings() {
|
||||
run(&mut s, "path.add_point", json!({"id": TAIL, "x": 181.25, "y": 140.0}));
|
||||
let text = crate::format::to_json(&s.doc).unwrap();
|
||||
let back = crate::format::from_json(&text).unwrap();
|
||||
let k = back.timeline(0).layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skin.clone())).unwrap();
|
||||
let k = back.timeline(0).layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skins.first().cloned())).unwrap();
|
||||
assert_eq!(k, skin(&s));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,465 @@
|
||||
{
|
||||
"format": "anicraft",
|
||||
"version": 3,
|
||||
"generator": "AniCraft 0.3.0",
|
||||
"paths": [
|
||||
"M0 0L20 0L20 20L0 20Z",
|
||||
"M0 -5L100 -5L100 5L0 5Z"
|
||||
],
|
||||
"document": {
|
||||
"stage": {
|
||||
"width": 500,
|
||||
"height": 300,
|
||||
"fps": 24.0,
|
||||
"background": {
|
||||
"r": 1.0,
|
||||
"g": 1.0,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
}
|
||||
},
|
||||
"scenes": [
|
||||
{
|
||||
"name": "Scene 1",
|
||||
"timeline": {
|
||||
"layers": [
|
||||
{
|
||||
"id": 101,
|
||||
"name": "Armature_1",
|
||||
"kind": "Armature",
|
||||
"visible": true,
|
||||
"locked": false,
|
||||
"outline": false,
|
||||
"color": {
|
||||
"r": 0.18431373,
|
||||
"g": 0.7137255,
|
||||
"b": 0.4862745,
|
||||
"a": 1.0
|
||||
},
|
||||
"keyframes": [
|
||||
{
|
||||
"start": 0,
|
||||
"duration": 12,
|
||||
"elements": [
|
||||
{
|
||||
"id": 10,
|
||||
"name": "",
|
||||
"transform": {
|
||||
"m": [
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
100.0,
|
||||
100.0
|
||||
]
|
||||
},
|
||||
"color": {
|
||||
"alpha": 1.0,
|
||||
"tint": {
|
||||
"r": 1.0,
|
||||
"g": 1.0,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"tint_amount": 0.0
|
||||
},
|
||||
"kind": {
|
||||
"Symbol": {
|
||||
"symbol": 1,
|
||||
"loop_mode": "Loop",
|
||||
"first_frame": 0
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"name": "",
|
||||
"transform": {
|
||||
"m": [
|
||||
0.8660254,
|
||||
0.5,
|
||||
-0.5,
|
||||
0.8660254,
|
||||
200.0,
|
||||
100.0
|
||||
]
|
||||
},
|
||||
"color": {
|
||||
"alpha": 1.0,
|
||||
"tint": {
|
||||
"r": 1.0,
|
||||
"g": 1.0,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"tint_amount": 0.0
|
||||
},
|
||||
"kind": {
|
||||
"Symbol": {
|
||||
"symbol": 1,
|
||||
"loop_mode": "Loop",
|
||||
"first_frame": 0
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"name": "",
|
||||
"transform": {
|
||||
"m": [
|
||||
0.8660254,
|
||||
0.5,
|
||||
-0.5,
|
||||
0.8660254,
|
||||
286.60254,
|
||||
150.0
|
||||
]
|
||||
},
|
||||
"color": {
|
||||
"alpha": 1.0,
|
||||
"tint": {
|
||||
"r": 1.0,
|
||||
"g": 1.0,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"tint_amount": 0.0
|
||||
},
|
||||
"kind": {
|
||||
"Symbol": {
|
||||
"symbol": 1,
|
||||
"loop_mode": "Loop",
|
||||
"first_frame": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"tween": {
|
||||
"easing": "Linear"
|
||||
},
|
||||
"label": "",
|
||||
"pose": [
|
||||
{
|
||||
"bone": 100,
|
||||
"angle": 0.5235988
|
||||
},
|
||||
{
|
||||
"bone": 102,
|
||||
"angle": 0.0
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"start": 12,
|
||||
"duration": 8,
|
||||
"elements": [
|
||||
{
|
||||
"id": 10,
|
||||
"name": "",
|
||||
"transform": {
|
||||
"m": [
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
100.0,
|
||||
100.0
|
||||
]
|
||||
},
|
||||
"color": {
|
||||
"alpha": 1.0,
|
||||
"tint": {
|
||||
"r": 1.0,
|
||||
"g": 1.0,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"tint_amount": 0.0
|
||||
},
|
||||
"kind": {
|
||||
"Symbol": {
|
||||
"symbol": 1,
|
||||
"loop_mode": "Loop",
|
||||
"first_frame": 0
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"name": "",
|
||||
"transform": {
|
||||
"m": [
|
||||
0.8660254,
|
||||
0.5,
|
||||
-0.5,
|
||||
0.8660254,
|
||||
200.0,
|
||||
100.0
|
||||
]
|
||||
},
|
||||
"color": {
|
||||
"alpha": 1.0,
|
||||
"tint": {
|
||||
"r": 1.0,
|
||||
"g": 1.0,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"tint_amount": 0.0
|
||||
},
|
||||
"kind": {
|
||||
"Symbol": {
|
||||
"symbol": 1,
|
||||
"loop_mode": "Loop",
|
||||
"first_frame": 0
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"name": "",
|
||||
"transform": {
|
||||
"m": [
|
||||
0.9659258,
|
||||
-0.258819,
|
||||
0.258819,
|
||||
0.9659258,
|
||||
286.60254,
|
||||
150.0
|
||||
]
|
||||
},
|
||||
"color": {
|
||||
"alpha": 1.0,
|
||||
"tint": {
|
||||
"r": 1.0,
|
||||
"g": 1.0,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"tint_amount": 0.0
|
||||
},
|
||||
"kind": {
|
||||
"Symbol": {
|
||||
"symbol": 1,
|
||||
"loop_mode": "Loop",
|
||||
"first_frame": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"tween": {
|
||||
"easing": "Linear"
|
||||
},
|
||||
"label": "",
|
||||
"pose": [
|
||||
{
|
||||
"bone": 100,
|
||||
"angle": 0.5235988
|
||||
},
|
||||
{
|
||||
"bone": 102,
|
||||
"angle": -0.7853982
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"armature": {
|
||||
"bones": [
|
||||
{
|
||||
"id": 100,
|
||||
"parent": 10,
|
||||
"child": 11,
|
||||
"head": {
|
||||
"x": 100.0,
|
||||
"y": 0.0
|
||||
},
|
||||
"tail": {
|
||||
"x": 100.0,
|
||||
"y": 0.0
|
||||
},
|
||||
"rest": {
|
||||
"m": [
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
100.0,
|
||||
0.0
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 102,
|
||||
"parent": 11,
|
||||
"child": 12,
|
||||
"head": {
|
||||
"x": 100.0,
|
||||
"y": 0.0
|
||||
},
|
||||
"tail": {
|
||||
"x": 100.0,
|
||||
"y": 0.0
|
||||
},
|
||||
"rest": {
|
||||
"m": [
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
100.0,
|
||||
0.0
|
||||
]
|
||||
},
|
||||
"limits": {
|
||||
"min": -1.5707964,
|
||||
"max": 1.5707964
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Layer 1",
|
||||
"kind": "Normal",
|
||||
"visible": true,
|
||||
"locked": false,
|
||||
"outline": false,
|
||||
"color": {
|
||||
"r": 0.30980393,
|
||||
"g": 0.6392157,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"keyframes": [
|
||||
{
|
||||
"start": 0,
|
||||
"duration": 20,
|
||||
"elements": [
|
||||
{
|
||||
"id": 13,
|
||||
"name": "",
|
||||
"transform": {
|
||||
"m": [
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
100.0,
|
||||
250.0
|
||||
]
|
||||
},
|
||||
"color": {
|
||||
"alpha": 1.0,
|
||||
"tint": {
|
||||
"r": 1.0,
|
||||
"g": 1.0,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"tint_amount": 0.0
|
||||
},
|
||||
"kind": {
|
||||
"Shape": {
|
||||
"path": 0,
|
||||
"fill": {
|
||||
"Solid": {
|
||||
"r": 0.0,
|
||||
"g": 0.0,
|
||||
"b": 0.0,
|
||||
"a": 1.0
|
||||
}
|
||||
},
|
||||
"stroke": null,
|
||||
"fill_rule": "NonZero"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"tween": null,
|
||||
"label": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"library": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Bar",
|
||||
"kind": "Graphic",
|
||||
"timeline": {
|
||||
"layers": [
|
||||
{
|
||||
"id": 2,
|
||||
"name": "bar",
|
||||
"kind": "Normal",
|
||||
"visible": true,
|
||||
"locked": false,
|
||||
"outline": false,
|
||||
"color": {
|
||||
"r": 0.30980393,
|
||||
"g": 0.6392157,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"keyframes": [
|
||||
{
|
||||
"start": 0,
|
||||
"duration": 1,
|
||||
"elements": [
|
||||
{
|
||||
"id": 3,
|
||||
"name": "",
|
||||
"transform": {
|
||||
"m": [
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
0.0,
|
||||
0.0
|
||||
]
|
||||
},
|
||||
"color": {
|
||||
"alpha": 1.0,
|
||||
"tint": {
|
||||
"r": 1.0,
|
||||
"g": 1.0,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"tint_amount": 0.0
|
||||
},
|
||||
"kind": {
|
||||
"Shape": {
|
||||
"path": 1,
|
||||
"fill": {
|
||||
"Solid": {
|
||||
"r": 0.0,
|
||||
"g": 0.0,
|
||||
"b": 0.0,
|
||||
"a": 1.0
|
||||
}
|
||||
},
|
||||
"stroke": null,
|
||||
"fill_rule": "NonZero"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"tween": null,
|
||||
"label": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"next_id": 103
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
{
|
||||
"format": "anicraft",
|
||||
"version": 3,
|
||||
"generator": "AniCraft 0.3.0",
|
||||
"paths": [
|
||||
"M23.820557 -65.549164L44.29936 -51.209755L50 -10L75.1915 -10.23395L102.86788 -9.09576L126.19189 5.846409L146.69337 20.487305L167.17216 34.826714L187.65097 49.166122L176.17944 65.549164L155.70064 51.209755L135.22183 36.870346L114.93453 22.296982L97.13212 9.09576L74.977325 9.698523L50 10L25 10L0 10Z",
|
||||
"M18.944572 -95.2564L40.595207 -82.7564L43.56443 -26.497932L67.37114 -35.47239L98.048096 -44.42767L126.95212 -33.118465L148.84839 -20.256401L170.49902 -7.756401L192.14966 4.743599L182.14966 22.06411L160.49902 9.56411L138.84839 -2.9358902L117.266525 -15.770447L96.46829 -26.37049L73.89714 -16.706043L50.40483 -7.7040796L26.912518 0.84642315L3.4202013 9.396926Z"
|
||||
],
|
||||
"document": {
|
||||
"stage": {
|
||||
"width": 400,
|
||||
"height": 300,
|
||||
"fps": 24.0,
|
||||
"background": {
|
||||
"r": 1.0,
|
||||
"g": 1.0,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
}
|
||||
},
|
||||
"scenes": [
|
||||
{
|
||||
"name": "Scene 1",
|
||||
"timeline": {
|
||||
"layers": [
|
||||
{
|
||||
"id": 102,
|
||||
"name": "Armature_1",
|
||||
"kind": "Armature",
|
||||
"visible": true,
|
||||
"locked": false,
|
||||
"outline": false,
|
||||
"color": {
|
||||
"r": 0.18431373,
|
||||
"g": 0.7137255,
|
||||
"b": 0.4862745,
|
||||
"a": 1.0
|
||||
},
|
||||
"keyframes": [
|
||||
{
|
||||
"start": 0,
|
||||
"duration": 10,
|
||||
"elements": [
|
||||
{
|
||||
"id": 10,
|
||||
"name": "",
|
||||
"transform": {
|
||||
"m": [
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
100.0,
|
||||
150.0
|
||||
]
|
||||
},
|
||||
"color": {
|
||||
"alpha": 1.0,
|
||||
"tint": {
|
||||
"r": 1.0,
|
||||
"g": 1.0,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"tint_amount": 0.0
|
||||
},
|
||||
"kind": {
|
||||
"Shape": {
|
||||
"path": 0,
|
||||
"fill": {
|
||||
"Solid": {
|
||||
"r": 0.0,
|
||||
"g": 0.0,
|
||||
"b": 0.0,
|
||||
"a": 1.0
|
||||
}
|
||||
},
|
||||
"stroke": null,
|
||||
"fill_rule": "NonZero"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"tween": {
|
||||
"easing": "Linear"
|
||||
},
|
||||
"label": "",
|
||||
"pose": [
|
||||
{
|
||||
"bone": 100,
|
||||
"angle": 0.0
|
||||
},
|
||||
{
|
||||
"bone": 103,
|
||||
"angle": 0.61086524
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"start": 10,
|
||||
"duration": 10,
|
||||
"elements": [
|
||||
{
|
||||
"id": 10,
|
||||
"name": "",
|
||||
"transform": {
|
||||
"m": [
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
100.0,
|
||||
150.0
|
||||
]
|
||||
},
|
||||
"color": {
|
||||
"alpha": 1.0,
|
||||
"tint": {
|
||||
"r": 1.0,
|
||||
"g": 1.0,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"tint_amount": 0.0
|
||||
},
|
||||
"kind": {
|
||||
"Shape": {
|
||||
"path": 1,
|
||||
"fill": {
|
||||
"Solid": {
|
||||
"r": 0.0,
|
||||
"g": 0.0,
|
||||
"b": 0.0,
|
||||
"a": 1.0
|
||||
}
|
||||
},
|
||||
"stroke": null,
|
||||
"fill_rule": "NonZero"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"tween": {
|
||||
"easing": "Linear"
|
||||
},
|
||||
"label": "",
|
||||
"pose": [
|
||||
{
|
||||
"bone": 100,
|
||||
"angle": -0.34906584
|
||||
},
|
||||
{
|
||||
"bone": 103,
|
||||
"angle": 0.87266463,
|
||||
"x": 7.0
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"armature": {
|
||||
"bones": [
|
||||
{
|
||||
"id": 100,
|
||||
"parent": 10,
|
||||
"child": 101,
|
||||
"head": {
|
||||
"x": 0.0,
|
||||
"y": 0.0
|
||||
},
|
||||
"tail": {
|
||||
"x": 100.0,
|
||||
"y": 0.0
|
||||
},
|
||||
"rest": {
|
||||
"m": [
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
0.0,
|
||||
0.0
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 103,
|
||||
"parent": 101,
|
||||
"child": 104,
|
||||
"head": {
|
||||
"x": 100.0,
|
||||
"y": 0.0
|
||||
},
|
||||
"tail": {
|
||||
"x": 200.0,
|
||||
"y": 0.0
|
||||
},
|
||||
"rest": {
|
||||
"m": [
|
||||
1.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
0.0,
|
||||
0.0
|
||||
]
|
||||
},
|
||||
"slide_x": {
|
||||
"min": -20.0,
|
||||
"max": 20.0
|
||||
},
|
||||
"spring": {
|
||||
"strength": 0.4,
|
||||
"damping": 0.2
|
||||
}
|
||||
}
|
||||
],
|
||||
"skin": {
|
||||
"shape": 10,
|
||||
"rest": "M0 -10L25 -10L50 -10L75 -10L100 -10L125 -10L150 -10L175 -10L200 -10L200 10L175 10L150 10L125 10L100 10L75 10L50 10L25 10L0 10Z",
|
||||
"points": [
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
103,
|
||||
1.0
|
||||
]
|
||||
],
|
||||
"manual": true
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
103,
|
||||
1.0
|
||||
]
|
||||
],
|
||||
"manual": true
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
100,
|
||||
1.0
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
100,
|
||||
0.9813302
|
||||
],
|
||||
[
|
||||
103,
|
||||
0.018669782
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
100,
|
||||
0.5
|
||||
],
|
||||
[
|
||||
103,
|
||||
0.5
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
103,
|
||||
0.9813302
|
||||
],
|
||||
[
|
||||
100,
|
||||
0.018669782
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
103,
|
||||
1.0
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
103,
|
||||
1.0
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
103,
|
||||
1.0
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
103,
|
||||
1.0
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
103,
|
||||
1.0
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
103,
|
||||
1.0
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
103,
|
||||
0.9813302
|
||||
],
|
||||
[
|
||||
100,
|
||||
0.018669782
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
100,
|
||||
0.5
|
||||
],
|
||||
[
|
||||
103,
|
||||
0.5
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
100,
|
||||
0.9813302
|
||||
],
|
||||
[
|
||||
103,
|
||||
0.018669782
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
100,
|
||||
1.0
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
100,
|
||||
1.0
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"bones": [
|
||||
[
|
||||
100,
|
||||
1.0
|
||||
]
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Layer 1",
|
||||
"kind": "Normal",
|
||||
"visible": true,
|
||||
"locked": false,
|
||||
"outline": false,
|
||||
"color": {
|
||||
"r": 0.30980393,
|
||||
"g": 0.6392157,
|
||||
"b": 1.0,
|
||||
"a": 1.0
|
||||
},
|
||||
"keyframes": [
|
||||
{
|
||||
"start": 0,
|
||||
"duration": 20,
|
||||
"elements": [],
|
||||
"tween": null,
|
||||
"label": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"library": [],
|
||||
"next_id": 105
|
||||
}
|
||||
}
|
||||
+17
-17
@@ -190,7 +190,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
let grad = || Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(120.0, 40.0), stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)]));
|
||||
let mut out = Vec::new();
|
||||
// A mask: a gradient seen through a circle, an unclipped shape over it, and one under it.
|
||||
let dl = DisplayList {
|
||||
let dl = DisplayList { links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![item(Path::rect(70.0, 0.0, 50.0, 100.0), Paint::Solid(green)), clipped(item(Path::rect(0.0, 0.0, 120.0, 100.0), grad()), 0), mask(Path::ellipse(50.0, 50.0, 37.3, 33.1), 0), item(Path::rect(10.0, 60.0, 30.0, 30.0), Paint::Solid(blue))],
|
||||
clip_parents: vec![None],
|
||||
@@ -213,10 +213,10 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
}
|
||||
let mut items = stripes;
|
||||
items.extend([eo, mask(Path::ellipse(95.0, 20.0, 30.0, 18.0), 0), star]);
|
||||
out.push(("nested masks", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0)))));
|
||||
out.push(("nested masks", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None, Some(0)], groups: Vec::new() }, view(130, 110, Some(Rgba::new(0.95, 0.95, 0.9, 1.0)))));
|
||||
// Group alpha: overlapping shapes fade as one; nested groups multiply; a group spans tiles
|
||||
// and the render bands; a top-level shape between two groups.
|
||||
let dl = DisplayList {
|
||||
let dl = DisplayList { links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![
|
||||
in_group(item(Path::rect(5.0, 5.0, 60.0, 50.0), Paint::Solid(red)), 0),
|
||||
@@ -244,9 +244,9 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
items.push(in_group(item(Path::ellipse(x + 12.0, 30.0, 11.0, 28.0), grad()), g));
|
||||
items.push(in_group(item(Path::rect(x + 2.0, 60.0, 20.0, 30.0), Paint::Solid(Rgba::new(0.9, 0.5, 0.2, 0.7))), g));
|
||||
}
|
||||
out.push(("blend modes", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8)))));
|
||||
out.push(("blend modes", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups }, view(14 * 24, 96, Some(Rgba::new(0.3, 0.3, 0.5, 0.8)))));
|
||||
// Masks inside groups and groups inside masks, with a blend mode, on transparent.
|
||||
let dl = DisplayList {
|
||||
let dl = DisplayList { links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![
|
||||
in_group(clipped(item(Path::rect(0.0, 0.0, 100.0, 60.0), grad()), 0), 0),
|
||||
@@ -262,7 +262,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
out.push(("masks and groups", dl, view(110, 90, None)));
|
||||
// Malformed links, as the oracle treats them: a clip whose parent is later (empty, hides
|
||||
// what it clips), a group whose parent is later (top-level), a clip index past the list.
|
||||
let dl = DisplayList {
|
||||
let dl = DisplayList { links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![
|
||||
clipped(item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Solid(red)), 0),
|
||||
@@ -648,7 +648,7 @@ fn binning_shapes_the_scene_into_tiles() {
|
||||
assert!(b.index.iter().all(|&v| v == 0));
|
||||
// A group in one tile: open, the fill, close; a clipped fill: the clip's level first. In
|
||||
// the middle tile the mask has no artwork, so the clipped fill is left out there.
|
||||
let dl = DisplayList {
|
||||
let dl = DisplayList { links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![
|
||||
in_group(item(Path::rect(1.0, 1.0, 4.0, 4.0), Paint::Solid(Rgba::BLACK)), 0),
|
||||
@@ -677,7 +677,7 @@ fn binning_shapes_the_scene_into_tiles() {
|
||||
|
||||
#[test]
|
||||
fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() {
|
||||
let deep = |n: usize| DisplayList {
|
||||
let deep = |n: usize| DisplayList { links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![in_group(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1)],
|
||||
clip_parents: Vec::new(),
|
||||
@@ -690,7 +690,7 @@ fn nesting_deeper_than_the_shader_holds_goes_to_the_cpu() {
|
||||
let masks = |n: usize| {
|
||||
let mut items: Vec<DisplayItem> = (0..n).map(|c| mask(Path::rect(0.0, 0.0, 8.0, 8.0), c as u32)).collect();
|
||||
items.push(clipped(item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), n as u32 - 1));
|
||||
DisplayList { clip_modes: Vec::new(), items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() }
|
||||
DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: (0..n).map(|i| i.checked_sub(1).map(|p| p as u32)).collect(), groups: Vec::new() }
|
||||
};
|
||||
assert!(bin(&masks(bn::MAX_CLIP_DEPTH)).is_ok());
|
||||
assert_eq!(bin(&masks(bn::MAX_CLIP_DEPTH + 1)).err(), Some(NeedsFull::Clips));
|
||||
@@ -861,7 +861,7 @@ fn gpu_hands_back_what_it_does_not_draw_and_stays_usable() {
|
||||
.collect();
|
||||
let mut it = in_group(item(Path::rect(2.0, 2.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK)), depth as u32 - 1);
|
||||
it.color = ColorTransform::alpha(0.5);
|
||||
DisplayList { clip_modes: Vec::new(), items: vec![it], clip_parents: Vec::new(), groups }
|
||||
DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![it], clip_parents: Vec::new(), groups }
|
||||
};
|
||||
let deep = nested(MAX_FILTER_DEPTH + 1);
|
||||
assert!(matches!(g.render(&deep, &view(12, 12, None), Output::Premul8), Err(GpuError::NeedsFull(NeedsFull::Filters))));
|
||||
@@ -972,7 +972,7 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
// Inside a mask and a faded group, over a gradient.
|
||||
let grad = item(Path::rect(0.0, 0.0, 80.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(80.0, 60.0), stops(&[(0.0, Rgba::BLACK), (1.0, Rgba::new(1.0, 0.8, 0.0, 1.0))])));
|
||||
let inside = in_group(clipped(bitmap_item(Path::rect(4.0, 4.0, 72.0, 52.0), &a, true, turned), 0), 0);
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] };
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] };
|
||||
out.push(("bitmap masked and multiplied", dl, view(80, 60, white)));
|
||||
// Without smoothing (ADR 0050): the nearest pixel, magnified, turned and repeated.
|
||||
let mut hard = bitmap_item(Path::rect(2.0, 3.0, 90.0, 70.0), &a, false, turned);
|
||||
@@ -1065,7 +1065,7 @@ fn gpu_matches_the_oracle_on_every_filter() {
|
||||
for (name, f) in filters_to_test() {
|
||||
let mut items = vec![backdrop.clone()];
|
||||
items.extend(symbol_items(0));
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] };
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![f])] };
|
||||
// At 1:1; zoomed, so sizes scale; and panned so the layer reaches past the surface.
|
||||
for v in [view(70, 60, Some(Rgba::WHITE)), View { transform: Affine::scale(1.5, 1.5), width: 105, height: 90, background: None }, View { transform: Affine::translate(-20.0, -15.0), width: 40, height: 33, background: Some(Rgba::WHITE) }] {
|
||||
let d = assert_parity(g, name, &dl, &v);
|
||||
@@ -1090,7 +1090,7 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() {
|
||||
(grp.alpha, grp.blend) = (0.7, BlendMode::Multiply);
|
||||
let mut items = vec![bg.clone()];
|
||||
items.extend(symbol_items(0));
|
||||
scenes.push(("filters in a row, faded and multiplied", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![grp] }));
|
||||
scenes.push(("filters in a row, faded and multiplied", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![grp] }));
|
||||
// A filtered symbol inside a filtered symbol, inside a faded one.
|
||||
let mut outer = filtered_group(vec![shadow.clone()]);
|
||||
outer.parent = Some(0);
|
||||
@@ -1098,22 +1098,22 @@ fn gpu_matches_the_oracle_on_filtered_symbols_in_context() {
|
||||
inner.parent = Some(1);
|
||||
let mut items = vec![bg.clone(), in_group(item(Path::rect(4.0, 40.0, 30.0, 16.0), Paint::Solid(Rgba::new(0.9, 0.6, 0.0, 1.0))), 1)];
|
||||
items.extend(symbol_items(2));
|
||||
scenes.push(("nested filtered symbols", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] }));
|
||||
scenes.push(("nested filtered symbols", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![group(None, 0.8, BlendMode::Normal), outer, inner] }));
|
||||
// Masked from outside (after filtering) and inside (before).
|
||||
let mut clipped_grp = filtered_group(vec![glow.clone()]);
|
||||
clipped_grp.clip = Some(0);
|
||||
let mut items = vec![bg.clone()];
|
||||
items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0)));
|
||||
items.push(mask(Path::ellipse(36.0, 30.0, 24.0, 20.0), 0));
|
||||
scenes.push(("masked after filtering", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![clipped_grp] }));
|
||||
scenes.push(("masked after filtering", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![clipped_grp] }));
|
||||
let mut items = vec![bg.clone()];
|
||||
items.extend(symbol_items(0).into_iter().map(|i| clipped(i, 0)));
|
||||
items.push(in_group(mask(Path::rect(20.0, 10.0, 16.0, 40.0), 0), 0));
|
||||
scenes.push(("masked inside the symbol", DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] }));
|
||||
scenes.push(("masked inside the symbol", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![None], groups: vec![filtered_group(vec![shadow.clone()])] }));
|
||||
// A bitmap inside a filtered symbol.
|
||||
let px = pixels(9, 7, 4);
|
||||
let items = vec![bg.clone(), in_group(bitmap_item(Path::ellipse(40.0, 32.0, 26.0, 20.0), &px, true, Affine::scale(4.0, 4.0)), 0)];
|
||||
scenes.push(("filtered bitmap", DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] }));
|
||||
scenes.push(("filtered bitmap", DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: vec![filtered_group(vec![blur, glow])] }));
|
||||
for (name, dl) in scenes {
|
||||
for v in [view(80, 64, white), View { transform: Affine::translate(-37.0, -5.0).mul(&Affine::scale(1.3, 1.3)), width: 48, height: 48, background: white }] {
|
||||
let d = assert_parity(g, name, &dl, &v);
|
||||
|
||||
@@ -563,6 +563,11 @@ impl<'a> Bake<'a> {
|
||||
if f.max_chars > 0 {
|
||||
o["mx"] = json!(f.max_chars.min(MAX_FIELD_CHARS as u32));
|
||||
}
|
||||
// Authored text in several colours: its pieces, each in its colour (ADR 0085).
|
||||
if !t.fills.is_empty() {
|
||||
let pieces: Vec<Value> = t.fill_paths().iter().map(|(c, _, p)| json!([self.path(p), self.paint(&Paint::Solid(*c))])).collect();
|
||||
o["pp"] = json!(pieces);
|
||||
}
|
||||
if f.background {
|
||||
o["bg"] = json!(self.paint(&Paint::Solid(f.background_color)));
|
||||
}
|
||||
@@ -631,9 +636,12 @@ impl<'a> Bake<'a> {
|
||||
let item = self.field(el, t, f);
|
||||
out.push(item);
|
||||
}
|
||||
// One shape per colour piece (ADR 0085).
|
||||
None => {
|
||||
let fill = Paint::Solid(t.color);
|
||||
out.push(self.shape(&t.outline, &el.transform, &el.color.transform(), Some(&fill), None, FillRule::NonZero));
|
||||
for (color, _, path) in t.fill_paths() {
|
||||
let fill = Paint::Solid(color);
|
||||
out.push(self.shape(&path, &el.transform, &el.color.transform(), Some(&fill), None, FillRule::NonZero));
|
||||
}
|
||||
}
|
||||
},
|
||||
ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters, events } => {
|
||||
|
||||
@@ -419,7 +419,11 @@ var AniCraft = (function () {
|
||||
dl.clips.push(clip);
|
||||
items.push(mk(tf.r, tf.kp, null, null, clip, inner));
|
||||
// Changed text has no outline here (it isn't laid out): the page draws it.
|
||||
if (text === null) items.push(mk(tf.p, tf.f, null, null, inner, null));
|
||||
// Authored text in several colours comes in pieces (ADR 0085).
|
||||
if (text === null) {
|
||||
if (tf.pp) for (const [pp, pf] of tf.pp) items.push(mk(pp, pf, null, null, inner, null));
|
||||
else items.push(mk(tf.p, tf.f, null, null, inner, null));
|
||||
}
|
||||
if (focused && fs && tf.k === "input" && fs.caret === fs.anchor) items.push(mk(tf.cr, tf.f, null, null, inner, null));
|
||||
if (tf.bd) items.push(mk(tf.r, -1, tf.bd, tf.bk || null, clip, null));
|
||||
for (const it of items) dl.items.push(it);
|
||||
|
||||
@@ -893,7 +893,7 @@ fn the_js_player_draws_random_numbers_like_the_rust_player() {
|
||||
/// (layout isn't compared: neither player lays text out here).
|
||||
fn field_el(id: u64, name: &str, at: Vec2, (w, h): (f32, f32), text: &str, f: Option<anicraft_doc::TextField>) -> Arc<Element> {
|
||||
let n = text.chars().count() as f32;
|
||||
let t = anicraft_doc::TextBlock { text: text.into(), font: "Inter".into(), size: 14.0, bold: true, italic: false, color: Rgba::hex(0x112233), align: anicraft_doc::TextAlign::Center, letter_spacing: 0.5, line_spacing: 2.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0 * n, 12.0)), box_width: w, box_height: h, field: f, on_path: None };
|
||||
let t = anicraft_doc::TextBlock { text: text.into(), font: "Inter".into(), size: 14.0, bold: true, italic: false, color: Rgba::hex(0x112233), align: anicraft_doc::TextAlign::Center, letter_spacing: 0.5, line_spacing: 2.0, width: None, outline: Arc::new(Path::rect(2.0, 2.0, 8.0 * n, 12.0)), box_width: w, box_height: h, field: f, on_path: None, ..Default::default() };
|
||||
Arc::new(Element { id: ElementId(id), name: name.into(), transform: Affine::translate(at.x, at.y), color: ColorEffect::default(), kind: ElementKind::Text(Arc::new(t)) })
|
||||
}
|
||||
|
||||
@@ -1250,7 +1250,7 @@ fn filters_and_soft_masks_compose_in_the_page_as_in_the_renderer() {
|
||||
// A mask over the symbol: its artwork drawn as it looks on its own, read as the
|
||||
// page reads it (canvas.js `maskEnd`).
|
||||
let reveal: Option<Vec<f32>> = (!inside).then(|| {
|
||||
let art = anicraft_doc::DisplayList { items: dl.items.iter().filter(|i| i.masks.is_some()).map(|i| anicraft_doc::DisplayItem { masks: None, clip: None, group: None, ..i.clone() }).collect(), clip_parents: Vec::new(), clip_modes: Vec::new(), groups: Vec::new() };
|
||||
let art = anicraft_doc::DisplayList { links: Vec::new(), items: dl.items.iter().filter(|i| i.masks.is_some()).map(|i| anicraft_doc::DisplayItem { masks: None, clip: None, group: None, ..i.clone() }).collect(), clip_parents: Vec::new(), clip_modes: Vec::new(), groups: Vec::new() };
|
||||
let (mp, _) = crate::render(&art, &crate::View { background: None, ..view }).unwrap();
|
||||
mp.data.iter().map(|p| mode.reveal(*p)).collect()
|
||||
});
|
||||
|
||||
+12
-11
@@ -531,6 +531,7 @@ fn filter_setup(dl: &DisplayList, run: &FilteredRun, view: &View, surface: IRect
|
||||
clip_parents: dl.clip_parents.iter().map(|p| p.filter(|c| inner.contains(c))).collect(),
|
||||
clip_modes: dl.clip_modes.clone(),
|
||||
groups,
|
||||
links: Vec::new(),
|
||||
};
|
||||
let sub_view = View { transform: Affine::translate(-b.x0 as f32, -b.y0 as f32).mul(&view.transform), width: b.width() as u32, height: b.height() as u32, background: None };
|
||||
let filters = group.filters.iter().map(|f| filters::resolve(f, scale)).collect();
|
||||
@@ -979,7 +980,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn list(items: Vec<DisplayItem>) -> DisplayList {
|
||||
DisplayList { clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: Vec::new() }
|
||||
DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: Vec::new(), groups: Vec::new() }
|
||||
}
|
||||
|
||||
/// A 40 × 40 opaque blue square masked by `art` in `mode`, on transparent.
|
||||
@@ -1074,7 +1075,7 @@ mod tests {
|
||||
let mut mask = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 0.2)));
|
||||
mask.masks = Some(0);
|
||||
mask.stroke = Some(anicraft_doc::Stroke::new(Rgba::BLACK, 8.0));
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![square, mask], clip_parents: vec![None], groups: Vec::new() };
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![square, mask], clip_parents: vec![None], groups: Vec::new() };
|
||||
let (pm, _) = render(&dl, &view(40, 40)).unwrap();
|
||||
// Pixel for pixel, the same as the circle drawn in the square's colour.
|
||||
let circle = item(Path::ellipse(20.0, 20.0, 10.0, 10.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0)));
|
||||
@@ -1142,7 +1143,7 @@ mod tests {
|
||||
let mut blue = item(Path::rect(4.0, 0.0, 8.0, 4.0), Paint::Solid(Rgba::new(0.0, 0.0, 1.0, 1.0)));
|
||||
red.group = Some(0);
|
||||
blue.group = Some(0);
|
||||
let grouped = DisplayList { clip_modes: Vec::new(), items: vec![red.clone(), blue.clone()], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }] };
|
||||
let grouped = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![red.clone(), blue.clone()], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }] };
|
||||
let (pm, _) = render(&grouped, &white).unwrap();
|
||||
let near = |p: Premul, q: [f32; 4]| p.iter().zip(q).all(|(a, b)| (a - b).abs() < 1e-4);
|
||||
// In the overlap only the top square shows through: half blue, half white, no red.
|
||||
@@ -1158,7 +1159,7 @@ mod tests {
|
||||
// Nested groups multiply; a group with a bad parent link is a top-level group.
|
||||
let mut inner = item(Path::rect(0.0, 0.0, 12.0, 4.0), Paint::Solid(Rgba::BLACK));
|
||||
inner.group = Some(1);
|
||||
let nested = DisplayList {
|
||||
let nested = DisplayList { links: Vec::new(),
|
||||
clip_modes: Vec::new(),
|
||||
items: vec![inner],
|
||||
clip_parents: vec![],
|
||||
@@ -1173,7 +1174,7 @@ mod tests {
|
||||
// Spanning several render bands changes nothing.
|
||||
let mut tall = item(Path::rect(0.0, 0.0, 4.0, 100.0), Paint::Solid(Rgba::BLACK));
|
||||
tall.group = Some(0);
|
||||
let (t, _) = render(&DisplayList { clip_modes: Vec::new(), items: vec![tall], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }, &View { background: Some(Rgba::WHITE), ..view(4, 100) }).unwrap();
|
||||
let (t, _) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![tall], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] }, &View { background: Some(Rgba::WHITE), ..view(4, 100) }).unwrap();
|
||||
assert!((0..100).all(|y| near(t.pixel(1, y).unwrap(), [0.75, 0.75, 0.75, 1.0])));
|
||||
}
|
||||
|
||||
@@ -1203,7 +1204,7 @@ mod tests {
|
||||
inner.masks = Some(1);
|
||||
let mut lost = clipped.clone();
|
||||
lost.clip = Some(2);
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() };
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![clipped, outer, inner, lost], clip_parents: vec![None, Some(0), Some(9)], groups: Vec::new() };
|
||||
let (scene, st) = prepare_scene(&dl, &view(16, 16)).unwrap();
|
||||
let (_, rst) = render(&dl, &view(16, 16)).unwrap();
|
||||
assert_eq!((st.drawn, st.edges, st.pixels_touched), (rst.drawn, rst.edges, rst.pixels_touched));
|
||||
@@ -1216,7 +1217,7 @@ mod tests {
|
||||
let mut grouped = sq.clone();
|
||||
grouped.group = Some(1);
|
||||
let g = |parent, alpha| anicraft_doc::Group { parent, alpha, blend: BlendMode::Multiply, filters: Default::default(), clip: None };
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] };
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![grouped], clip_parents: vec![], groups: vec![g(None, 2.0), g(Some(0), f32::NAN)] };
|
||||
let (scene, _) = prepare_scene(&dl, &view(16, 16)).unwrap();
|
||||
assert!(scene.fills.iter().all(|f| f.group == Some(1)));
|
||||
assert_eq!((scene.groups[1].chain.clone(), scene.groups[0].alpha, scene.groups[1].alpha, scene.groups[1].blend), (vec![0, 1], 1.0, 1.0, BlendMode::Multiply));
|
||||
@@ -1258,7 +1259,7 @@ mod tests {
|
||||
let mut clipped = item(Path::rect(0.0, 0.0, 8.0, 8.0), Paint::Solid(Rgba::BLACK));
|
||||
clipped.clip = Some(0);
|
||||
let free = item(Path::rect(0.0, 0.0, 2.0, 2.0), Paint::Solid(Rgba::BLACK));
|
||||
let (pm, st) = render(&DisplayList { clip_modes: Vec::new(), items: vec![clipped, free.clone()], clip_parents: vec![None], groups: Vec::new() }, &view(8, 8)).unwrap();
|
||||
let (pm, st) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![clipped, free.clone()], clip_parents: vec![None], groups: Vec::new() }, &view(8, 8)).unwrap();
|
||||
assert_eq!(st.drawn, 1);
|
||||
assert_eq!(pm, render(&list(vec![free]), &view(8, 8)).unwrap().0);
|
||||
}
|
||||
@@ -1273,11 +1274,11 @@ mod tests {
|
||||
inner.masks = Some(1);
|
||||
let items = vec![fill, outer, inner];
|
||||
// Clip 1 lies inside clip 0: a 32 × 32 square across two render bands survives.
|
||||
let (pm, _) = render(&DisplayList { clip_modes: Vec::new(), items: items.clone(), clip_parents: vec![None, Some(0)], groups: Vec::new() }, &view(64, 64)).unwrap();
|
||||
let (pm, _) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: items.clone(), clip_parents: vec![None, Some(0)], groups: Vec::new() }, &view(64, 64)).unwrap();
|
||||
assert!((alpha_sum(&pm) - 32.0 * 32.0).abs() < 1e-2, "{}", alpha_sum(&pm));
|
||||
// A parent link pointing forward (malformed) or out of range masks everything out.
|
||||
for parents in [vec![Some(1), Some(1)], vec![None, Some(9)]] {
|
||||
let (pm, _) = render(&DisplayList { clip_modes: Vec::new(), items: items.clone(), clip_parents: parents, groups: Vec::new() }, &view(64, 64)).unwrap();
|
||||
let (pm, _) = render(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: items.clone(), clip_parents: parents, groups: Vec::new() }, &view(64, 64)).unwrap();
|
||||
assert_eq!(alpha_sum(&pm), 0.0);
|
||||
}
|
||||
}
|
||||
@@ -1499,7 +1500,7 @@ mod tests {
|
||||
let bg = item(Path::rect(0.0, 0.0, 20.0, 10.0), Paint::Solid(Rgba::new(0.5, 0.5, 1.0, 1.0)));
|
||||
let mut top = item(Path::rect(0.0, 0.0, 10.0, 10.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 1.0)));
|
||||
top.group = Some(0);
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![bg, top], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 1.0, blend: BlendMode::Multiply, filters: Default::default(), clip: None }] };
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![bg, top], clip_parents: vec![], groups: vec![anicraft_doc::Group { parent: None, alpha: 1.0, blend: BlendMode::Multiply, filters: Default::default(), clip: None }] };
|
||||
let (pm, _) = render(&dl, &View { background: Some(Rgba::WHITE), ..view(20, 10) }).unwrap();
|
||||
let p = pm.pixel(5, 5).unwrap();
|
||||
assert!((p[0] - 0.5).abs() < 1e-3 && p[1].abs() < 1e-3 && p[2].abs() < 1e-3, "red × lavender: {p:?}");
|
||||
|
||||
@@ -656,7 +656,7 @@ pub fn outline_variable_strokes(dl: &DisplayList) -> std::borrow::Cow<'_, Displa
|
||||
items.push(DisplayItem { path: std::sync::Arc::new(outline), transform: Affine::IDENTITY, fill: Some(anicraft_doc::Paint::Solid(st.color)), stroke: None, fill_rule: anicraft_geom::FillRule::NonZero, image: None, ..it.clone() });
|
||||
}
|
||||
}
|
||||
std::borrow::Cow::Owned(DisplayList { clip_modes: dl.clip_modes.clone(), items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone() })
|
||||
std::borrow::Cow::Owned(DisplayList { links: Vec::new(), clip_modes: dl.clip_modes.clone(), items, clip_parents: dl.clip_parents.clone(), groups: dl.groups.clone() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -79,8 +79,9 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String {
|
||||
// Groups that fade as one become `<g opacity>` around their run of items.
|
||||
let chains = crate::group_chains(&dl.groups);
|
||||
let mut open: Vec<u32> = Vec::new();
|
||||
for item in dl.items.iter().filter(|it| it.masks.is_none() && !it.guide) {
|
||||
for (index, item) in dl.items.iter().enumerate().filter(|(_, it)| it.masks.is_none() && !it.guide) {
|
||||
let Some(d) = stage_path(item) else { continue };
|
||||
let link = dl.links.binary_search_by_key(&(index as u32), |l| l.0).ok().and_then(|i| dl.links.get(i)).and_then(|l| anicraft_doc::safe_url(&l.1));
|
||||
let want = item.group.and_then(|g| chains.get(g as usize)).map_or(&[][..], Vec::as_slice);
|
||||
let keep = open.iter().zip(want).take_while(|(o, g)| o == g).count();
|
||||
while open.len() > keep {
|
||||
@@ -103,7 +104,14 @@ pub fn to_svg(dl: &DisplayList, stage: &Stage) -> String {
|
||||
open.push(g);
|
||||
}
|
||||
let clip = item.clip.filter(|&c| (c as usize) < dl.clip_parents.len()).map(|c| clip_attrs(dl, c)).unwrap_or_default();
|
||||
// Characters with a link (ADR 0085) are a link in the SVG.
|
||||
if let Some(url) = &link {
|
||||
let _ = write!(body, "<a href=\"{}\">", attr_escape(url));
|
||||
}
|
||||
draw(item, &d, &clip, &mut body, &mut defs, &mut grad, &mut images);
|
||||
if link.is_some() {
|
||||
body.push_str("</a>");
|
||||
}
|
||||
}
|
||||
for _ in open {
|
||||
body.push_str("</g>");
|
||||
@@ -583,7 +591,7 @@ mod tests {
|
||||
*spread = anicraft_doc::Spread::Reflect;
|
||||
}
|
||||
let items = vec![item(Path::rect(0.0, 0.0, 60.0, 60.0), Some(rad)), item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(lin))];
|
||||
let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items, clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
assert!(svg.contains("spreadMethod=\"repeat\"") && svg.contains("spreadMethod=\"reflect\""), "{svg}");
|
||||
assert!(svg.contains("color-interpolation=\"linearRGB\""), "{svg}");
|
||||
assert!(svg.contains("fx=\"40\" fy=\"30\""), "focal point half way along the ring's x axis: {svg}");
|
||||
@@ -612,7 +620,7 @@ mod tests {
|
||||
a.stroke = Some(Stroke::new(Rgba::BLACK, 3.0));
|
||||
a.color = ColorTransform::alpha(0.5);
|
||||
a.fill_rule = FillRule::EvenOdd;
|
||||
let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
assert!(svg.starts_with("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"50\" viewBox=\"0 0 100 50\">"));
|
||||
assert!(svg.contains("<rect width=\"100\" height=\"50\" fill=\"#ffffff\"/>"), "background");
|
||||
assert!(svg.contains("d=\"M5 7L25 7L25 27L5 27Z\" fill=\"#ff0000\" fill-opacity=\"0.5\" fill-rule=\"evenodd\""), "{svg}");
|
||||
@@ -627,7 +635,7 @@ mod tests {
|
||||
let mut a = item(Path::line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), None);
|
||||
a.transform = Affine::scale(2.0, 2.0);
|
||||
a.stroke = Some(st);
|
||||
to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage())
|
||||
to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage())
|
||||
};
|
||||
// The default style is written as before: round, no dashes.
|
||||
let svg = svg_of(Stroke::new(Rgba::BLACK, 3.0));
|
||||
@@ -647,7 +655,7 @@ mod tests {
|
||||
fn variable_width_strokes_are_written_as_filled_outlines() {
|
||||
let mut a = item(Path::line(Vec2::new(0.0, 10.0), Vec2::new(80.0, 10.0)), Some(Paint::Solid(Rgba::hex(0xff0000))));
|
||||
a.stroke = Some(Stroke::new(Rgba::hex(0x0000ff), 6.0).with_profile(anicraft_doc::ProfilePreset::TaperBoth.profile()));
|
||||
let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![a], clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
assert!(!svg.contains("stroke-width"), "no SVG stroke: {svg}");
|
||||
assert!(svg.contains("fill=\"#0000ff\""), "the outline is filled in the stroke colour");
|
||||
assert!(svg.contains("fill=\"#ff0000\""), "the shape's own fill stays");
|
||||
@@ -664,7 +672,7 @@ mod tests {
|
||||
outer.masks = Some(0);
|
||||
let mut inner = item(Path::ellipse(25.0, 25.0, 10.0, 10.0), Some(Paint::Solid(Rgba::BLACK)));
|
||||
inner.masks = Some(1);
|
||||
let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![g, outer, inner], clip_parents: vec![None, Some(0)], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![g, outer, inner], clip_parents: vec![None, Some(0)], groups: Vec::new() }, &stage());
|
||||
assert!(svg.contains("gradientTransform=\"matrix(1 0 0 1 20 0)\" x1=\"0\" y1=\"0\" x2=\"10\" y2=\"0\""), "{svg}");
|
||||
assert!(svg.contains("<stop offset=\"1\" stop-color=\"#ffffff\" stop-opacity=\"0.25\"/>"));
|
||||
assert!(svg.contains("<clipPath id=\"c1\" clipPathUnits=\"userSpaceOnUse\" clip-path=\"url(#c0)\">"), "nested clip");
|
||||
@@ -717,7 +725,7 @@ mod tests {
|
||||
let clear = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::TRANSPARENT)));
|
||||
let mut lost = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::BLACK)));
|
||||
lost.clip = Some(7);
|
||||
let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items: vec![bad, empty, clear, lost], clip_parents: vec![Some(3)], groups: Vec::new() }, &stage());
|
||||
let svg = to_svg(&DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![bad, empty, clear, lost], clip_parents: vec![Some(3)], groups: Vec::new() }, &stage());
|
||||
assert_eq!(svg.matches("<path").count(), 1, "{svg}");
|
||||
assert!(svg.contains("<clipPath id=\"c0\" clipPathUnits=\"userSpaceOnUse\"></clipPath>"), "a malformed clip clips everything");
|
||||
assert!(!svg.contains("NaN") && !svg.contains("inf"));
|
||||
@@ -751,7 +759,7 @@ mod group_tests {
|
||||
smooth: true,
|
||||
warp: None,
|
||||
};
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![it(None), it(Some(0)), it(Some(1)), it(Some(0)), it(None)], clip_parents: vec![], groups: vec![Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, Group { parent: Some(0), alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] };
|
||||
let dl = DisplayList { links: Vec::new(), clip_modes: Vec::new(), items: vec![it(None), it(Some(0)), it(Some(1)), it(Some(0)), it(None)], clip_parents: vec![], groups: vec![Group { parent: None, alpha: 0.5, blend: Default::default(), filters: Default::default(), clip: None }, Group { parent: Some(0), alpha: 0.25, blend: Default::default(), filters: Default::default(), clip: None }] };
|
||||
let svg = to_svg(&dl, &Stage { width: 4, height: 4, fps: 24.0, background: Rgba::WHITE });
|
||||
assert!(svg.contains("<g opacity=\"0.5\">") && svg.contains("<g opacity=\"0.25\">"), "{svg}");
|
||||
assert_eq!(svg.matches("<g ").count(), svg.matches("</g>").count(), "balanced");
|
||||
@@ -760,3 +768,20 @@ mod group_tests {
|
||||
assert_eq!(order, ["path", "g", "path", "g", "path", "/g", "path", "/g", "path"], "{svg}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `s` safe inside a double-quoted XML attribute.
|
||||
fn attr_escape(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
c if c.is_control() => {}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -539,6 +539,7 @@ impl<'a> Builder<'a> {
|
||||
box_height: layout.height,
|
||||
field: None,
|
||||
on_path: None,
|
||||
..TextBlock::default()
|
||||
};
|
||||
Ok(Some((block, ascent)))
|
||||
}
|
||||
|
||||
+43
-205
@@ -11,9 +11,11 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use anicraft_geom::{Path, PathCmd, Vec2};
|
||||
use skrifa::MetadataProvider as _;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
mod rich;
|
||||
pub use rich::{MAX_FACES, MAX_RUNS, ParaStyle, RichText, Run, RunStyle, Shift, sanitize_para, sanitize_run};
|
||||
|
||||
/// Families tried, in order, when none is asked for or the one asked for isn't installed.
|
||||
pub const DEFAULT_FAMILIES: &[&str] = &["Inter", "Arial", "Helvetica", "Helvetica Neue", "Segoe UI", "DejaVu Sans", "Liberation Sans", "Noto Sans", "Roboto", "Ubuntu"];
|
||||
|
||||
@@ -83,6 +85,11 @@ pub struct Layout {
|
||||
/// Each glyph on its own, in drawing order: only from [`Fonts::layout_glyphs`] (empty
|
||||
/// otherwise).
|
||||
pub glyphs: Vec<PlacedGlyph>,
|
||||
/// The outline cut by the runs' paints ([`RunStyle::paint`]), in the order paints first
|
||||
/// appear: `outline` is these pieces one after another (ADR 0085).
|
||||
pub pieces: Vec<(u32, Path)>,
|
||||
/// The family each run was laid out in (the one asked for, or the fallback).
|
||||
pub families: Vec<String>,
|
||||
}
|
||||
|
||||
/// One laid-out glyph on its own.
|
||||
@@ -98,6 +105,8 @@ pub struct PlacedGlyph {
|
||||
pub advance: f32,
|
||||
/// The character it starts at (`char`s of the whole text, line breaks included).
|
||||
pub index: u32,
|
||||
/// Its run's paint ([`RunStyle::paint`]).
|
||||
pub paint: u32,
|
||||
}
|
||||
|
||||
/// How text follows a path (ADR 0070).
|
||||
@@ -114,8 +123,10 @@ pub struct PathPlacement {
|
||||
/// Glyphs set along a path.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PathText {
|
||||
/// Every glyph shown, in the path's space.
|
||||
/// Every glyph shown, in the path's space: `pieces` one after another.
|
||||
pub outline: Path,
|
||||
/// The glyphs by paint, in the order paints first appear.
|
||||
pub pieces: Vec<(u32, Path)>,
|
||||
/// The path's length.
|
||||
pub length: f32,
|
||||
/// Each shown glyph's character, the point on the path under its middle and its angle
|
||||
@@ -144,7 +155,7 @@ pub fn on_path(glyphs: &[PlacedGlyph], path: &Path, how: PathPlacement) -> Optio
|
||||
Align::Center => width * 0.5,
|
||||
Align::Right => width,
|
||||
};
|
||||
let mut out = PathText { outline: Path::new(), length, placed: Vec::with_capacity(glyphs.len()), hidden: 0 };
|
||||
let mut out = PathText { outline: Path::new(), pieces: Vec::new(), length, placed: Vec::with_capacity(glyphs.len()), hidden: 0 };
|
||||
for g in glyphs {
|
||||
let mid = start + g.x + g.advance * 0.5;
|
||||
if !mid.is_finite() {
|
||||
@@ -162,9 +173,21 @@ pub fn on_path(glyphs: &[PlacedGlyph], path: &Path, how: PathPlacement) -> Optio
|
||||
let (p, t) = if how.flip { (walk.at(length - s), walk.tangent(length - s) * -1.0) } else { (walk.at(s), walk.tangent(s)) };
|
||||
let angle = t.y.atan2(t.x);
|
||||
let m = anicraft_geom::Affine::translate(p.x, p.y).mul(&anicraft_geom::Affine::rotate(angle)).mul(&anicraft_geom::Affine::translate(-g.advance * 0.5, 0.0));
|
||||
out.outline.cmds.extend(g.outline.transformed(&m).cmds);
|
||||
let k = match out.pieces.iter().position(|(paint, _)| *paint == g.paint) {
|
||||
Some(k) => k,
|
||||
None => {
|
||||
out.pieces.push((g.paint, Path::new()));
|
||||
out.pieces.len() - 1
|
||||
}
|
||||
};
|
||||
if let Some((_, piece)) = out.pieces.get_mut(k) {
|
||||
piece.cmds.extend(g.outline.transformed(&m).cmds);
|
||||
}
|
||||
out.placed.push((g.index, p, angle));
|
||||
}
|
||||
for (_, piece) in &out.pieces {
|
||||
out.outline.cmds.extend_from_slice(&piece.cmds);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -173,6 +196,8 @@ pub fn on_path(glyphs: &[PlacedGlyph], path: &Path, how: PathPlacement) -> Optio
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BoxedPathText {
|
||||
pub outline: Path,
|
||||
/// The glyphs by paint (see [`PathText::pieces`]).
|
||||
pub pieces: Vec<(u32, Path)>,
|
||||
pub path: Path,
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
@@ -188,7 +213,8 @@ pub fn on_path_boxed(glyphs: &[PlacedGlyph], path: &Path, how: PathPlacement) ->
|
||||
let shift = if b.min.x.is_finite() && b.min.y.is_finite() { b.min } else { Vec2::ZERO };
|
||||
let back = anicraft_geom::Affine::translate(-shift.x, -shift.y);
|
||||
let size = |v: f32| if v.is_finite() { v.max(0.0) } else { 0.0 };
|
||||
Some(BoxedPathText { outline: set.outline.transformed(&back), path: path.transformed(&back), width: size(b.width()), height: size(b.height()), shift, hidden: set.hidden })
|
||||
let pieces = set.pieces.iter().map(|(k, p)| (*k, p.transformed(&back))).collect();
|
||||
Some(BoxedPathText { outline: set.outline.transformed(&back), pieces, path: path.transformed(&back), width: size(b.width()), height: size(b.height()), shift, hidden: set.hidden })
|
||||
}
|
||||
|
||||
/// Whether a path's first subpath ends with a close.
|
||||
@@ -213,6 +239,11 @@ pub struct CaretLine {
|
||||
pub end: u32,
|
||||
/// `(index, x)` of the boundaries glyphs start at and of the line's end, ascending.
|
||||
pub stops: Vec<(u32, f32)>,
|
||||
/// The line's top and height (to the next line's top, its line spacing included) and its
|
||||
/// baseline, from the box's top (pixels).
|
||||
pub top: f32,
|
||||
pub height: f32,
|
||||
pub baseline: f32,
|
||||
}
|
||||
|
||||
impl CaretLine {
|
||||
@@ -395,19 +426,10 @@ impl Fonts {
|
||||
}
|
||||
|
||||
fn lay_out_with(&self, text: &str, style: &Style, glyphs: bool) -> Result<Layout, TextError> {
|
||||
if text.chars().count() > MAX_CHARS {
|
||||
return Err(TextError::TooLong);
|
||||
}
|
||||
let family = self.resolve(&style.family).ok_or(TextError::NoFonts)?;
|
||||
let q = fontdb::Query {
|
||||
families: &[fontdb::Family::Name(&family)],
|
||||
weight: if style.bold { fontdb::Weight::BOLD } else { fontdb::Weight::NORMAL },
|
||||
stretch: fontdb::Stretch::Normal,
|
||||
style: if style.italic { fontdb::Style::Italic } else { fontdb::Style::Normal },
|
||||
};
|
||||
let id = self.db.query(&q).ok_or(TextError::NoFonts)?;
|
||||
let laid = self.db.with_face_data(id, |data, index| lay_out(data, index, text, style, glyphs)).flatten().ok_or(TextError::NoFonts)?;
|
||||
Ok(Layout { family, ..laid })
|
||||
let style = sanitize(style);
|
||||
let run = Run { chars: usize::MAX, style: RunStyle { family: style.family.clone(), size: style.size, bold: style.bold, italic: style.italic, letter_spacing: style.letter_spacing, ..RunStyle::default() } };
|
||||
let para = ParaStyle { align: style.align, line_spacing: style.line_spacing, ..ParaStyle::default() };
|
||||
self.layout_rich(&RichText { text, runs: &[run], paragraphs: &[para], width: style.width }, glyphs)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -449,192 +471,8 @@ pub fn sanitize(style: &Style) -> Style {
|
||||
}
|
||||
}
|
||||
|
||||
/// One shaped glyph: id, where its pen position starts, its offsets and advance (pixels).
|
||||
struct Glyph {
|
||||
id: skrifa::GlyphId,
|
||||
cluster: usize,
|
||||
x_offset: f32,
|
||||
y_offset: f32,
|
||||
advance: f32,
|
||||
}
|
||||
|
||||
fn lay_out(data: &[u8], index: u32, text: &str, style: &Style, want_glyphs: bool) -> Option<Layout> {
|
||||
let style = sanitize(style);
|
||||
let font = skrifa::FontRef::from_index(data, index).ok()?;
|
||||
let size = skrifa::instance::Size::new(style.size);
|
||||
let metrics = font.metrics(size, skrifa::instance::LocationRef::default());
|
||||
let upem = f32::from(metrics.units_per_em.max(1));
|
||||
let scale = style.size / upem;
|
||||
let ascent = metrics.ascent;
|
||||
let line_height = (metrics.ascent - metrics.descent + metrics.leading).max(style.size * 0.5) + style.line_spacing;
|
||||
let shaper_data = harfrust::ShaperData::new(&font);
|
||||
let shaper = shaper_data.shaper(&font).build();
|
||||
let glyphs = font.outline_glyphs();
|
||||
let charmap = font.charmap();
|
||||
let missing = text.chars().filter(|c| !c.is_control() && !c.is_whitespace() && charmap.map(*c).is_none()).count();
|
||||
|
||||
// Lines: paragraphs at line breaks, each wrapped at spaces to the width if there is one.
|
||||
let mut lines: Vec<(f32, Vec<(Glyph, f32)>)> = Vec::new();
|
||||
// Per line: the character index its paragraph starts at, the paragraph's length in
|
||||
// characters, and the byte → character map of the paragraph (shared by its lines).
|
||||
let mut spans: Vec<(u32, u32, Arc<Vec<u32>>)> = Vec::new();
|
||||
let mut para_start = 0u32;
|
||||
for raw in text.split('\n') {
|
||||
let para = raw.strip_suffix('\r').unwrap_or(raw);
|
||||
let mut to_char = vec![0u32; para.len() + 1];
|
||||
let mut n = 0u32;
|
||||
for (b, _) in para.char_indices() {
|
||||
if let Some(slot) = to_char.get_mut(b) {
|
||||
*slot = n;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
if let Some(last) = to_char.last_mut() {
|
||||
*last = n;
|
||||
}
|
||||
let to_char = Arc::new(to_char);
|
||||
let lines_before = lines.len();
|
||||
let mut buffer = harfrust::UnicodeBuffer::new();
|
||||
buffer.push_str(para);
|
||||
buffer.guess_segment_properties();
|
||||
let shaped = shaper.shape(buffer, harfrust::ShapeOptions::new());
|
||||
let run: Vec<Glyph> = shaped
|
||||
.glyph_infos()
|
||||
.iter()
|
||||
.zip(shaped.glyph_positions())
|
||||
.map(|(info, pos)| Glyph {
|
||||
id: skrifa::GlyphId::new(info.glyph_id),
|
||||
cluster: info.cluster as usize,
|
||||
x_offset: pos.x_offset as f32 * scale,
|
||||
y_offset: pos.y_offset as f32 * scale,
|
||||
advance: pos.x_advance as f32 * scale + style.letter_spacing,
|
||||
})
|
||||
.collect();
|
||||
let is_space = |g: &Glyph| para.get(g.cluster..).and_then(|s| s.chars().next()).is_some_and(char::is_whitespace);
|
||||
let mut line: Vec<(Glyph, f32)> = Vec::new();
|
||||
let mut x = 0.0f32;
|
||||
// Where the current line could break: after its last space.
|
||||
let mut break_at: Option<usize> = None;
|
||||
for g in run {
|
||||
let space = is_space(&g);
|
||||
if let Some(w) = style.width
|
||||
&& !space
|
||||
&& x + g.advance > w
|
||||
&& !line.is_empty()
|
||||
{
|
||||
// Wrap: at the last space if there is one (dropping trailing spaces), else here.
|
||||
let rest = match break_at {
|
||||
Some(b) => line.split_off(b),
|
||||
None => Vec::new(),
|
||||
};
|
||||
while line.last().is_some_and(|(g, _)| is_space(g)) {
|
||||
line.pop();
|
||||
}
|
||||
let width = line.last().map_or(0.0, |(g, gx)| gx + g.advance);
|
||||
lines.push((width, std::mem::take(&mut line)));
|
||||
let shift = rest.first().map_or(0.0, |(_, gx)| *gx);
|
||||
line = rest.into_iter().map(|(g, gx)| (g, gx - shift)).collect();
|
||||
x = line.last().map_or(0.0, |(g, gx)| gx + g.advance);
|
||||
break_at = None;
|
||||
}
|
||||
line.push((g, x));
|
||||
x += line.last().map_or(0.0, |(g, _)| g.advance);
|
||||
if space {
|
||||
break_at = Some(line.len());
|
||||
}
|
||||
}
|
||||
while line.last().is_some_and(|(g, _)| is_space(g)) {
|
||||
line.pop();
|
||||
}
|
||||
let width = line.last().map_or(0.0, |(g, gx)| gx + g.advance);
|
||||
lines.push((width, line));
|
||||
for _ in lines_before..lines.len() {
|
||||
spans.push((para_start, n, to_char.clone()));
|
||||
}
|
||||
para_start += raw.chars().count() as u32 + 1;
|
||||
}
|
||||
|
||||
let box_width = style.width.unwrap_or_else(|| lines.iter().map(|(w, _)| *w).fold(0.0, f32::max));
|
||||
let mut outline = Path::new();
|
||||
let mut placed: Vec<PlacedGlyph> = Vec::new();
|
||||
for (row, (width, line)) in lines.iter().enumerate() {
|
||||
let shift = match style.align {
|
||||
Align::Left => 0.0,
|
||||
Align::Center => (box_width - width) * 0.5,
|
||||
Align::Right => box_width - width,
|
||||
};
|
||||
let baseline = ascent + row as f32 * line_height;
|
||||
let span = spans.get(row);
|
||||
for (g, gx) in line {
|
||||
let Some(glyph) = glyphs.get(g.id) else { continue };
|
||||
if want_glyphs {
|
||||
let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default());
|
||||
let mut own = Path::new();
|
||||
let mut pen = Pen { cmds: &mut own.cmds, x: g.x_offset, y: -g.y_offset };
|
||||
let _ = glyph.draw(settings, &mut pen);
|
||||
let index = span.map_or(0, |(pstart, plen, to_char)| pstart + to_char.get(g.cluster).copied().unwrap_or(*plen).min(*plen));
|
||||
placed.push(PlacedGlyph { outline: own, x: shift + gx, baseline, advance: g.advance, index });
|
||||
}
|
||||
let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default());
|
||||
let mut pen = Pen { cmds: &mut outline.cmds, x: shift + gx + g.x_offset, y: baseline - g.y_offset };
|
||||
let _ = glyph.draw(settings, &mut pen);
|
||||
}
|
||||
}
|
||||
let height = (lines.len().max(1) as f32 - 1.0) * line_height + (metrics.ascent - metrics.descent);
|
||||
let carets = caret_lines(&lines, &spans, box_width, style.align);
|
||||
Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing, lines: lines.len().max(1), line_height, ascent, carets, glyphs: placed })
|
||||
}
|
||||
|
||||
/// The caret positions of laid-out lines (see [`CaretLine`]).
|
||||
fn caret_lines(lines: &[(f32, Vec<(Glyph, f32)>)], spans: &[(u32, u32, Arc<Vec<u32>>)], box_width: f32, align: Align) -> Vec<CaretLine> {
|
||||
let mut out: Vec<CaretLine> = Vec::with_capacity(lines.len());
|
||||
for (row, ((width, line), (pstart, plen, to_char))) in lines.iter().zip(spans).enumerate() {
|
||||
let shift = match align {
|
||||
Align::Left => 0.0,
|
||||
Align::Center => (box_width - width) * 0.5,
|
||||
Align::Right => box_width - width,
|
||||
};
|
||||
let ch = |cluster: usize| pstart + to_char.get(cluster).copied().unwrap_or(*plen).min(*plen);
|
||||
// A paragraph's first line starts with it; a wrapped line at its first glyph.
|
||||
let first_of_para = row == 0 || spans.get(row - 1).is_none_or(|p| p.0 != *pstart);
|
||||
let start = if first_of_para { *pstart } else { line.first().map_or(*pstart, |(g, _)| ch(g.cluster)) };
|
||||
let mut stops: Vec<(u32, f32)> = line.iter().map(|(g, gx)| (ch(g.cluster), shift + gx)).collect();
|
||||
stops.sort_by_key(|s| s.0);
|
||||
stops.dedup_by_key(|s| s.0);
|
||||
if first_of_para && stops.first().is_none_or(|s| s.0 > start) {
|
||||
stops.insert(0, (start, shift));
|
||||
}
|
||||
// The boundary after the last glyph (its trailing spaces, if any, follow it).
|
||||
if let Some(&(c, _)) = stops.last() {
|
||||
stops.push((c + 1, shift + width));
|
||||
}
|
||||
out.push(CaretLine { start, end: start, stops });
|
||||
// The previous line of the same paragraph ends where this one starts.
|
||||
if !first_of_para && let Some(prev) = out.len().checked_sub(2).and_then(|i| out.get_mut(i)) {
|
||||
prev.end = start;
|
||||
}
|
||||
}
|
||||
// The last line of each paragraph ends with it.
|
||||
for (row, (pstart, plen, _)) in spans.iter().enumerate() {
|
||||
let last_of_para = spans.get(row + 1).is_none_or(|p| p.0 != *pstart);
|
||||
if last_of_para && let Some(l) = out.get_mut(row) {
|
||||
l.end = pstart + plen;
|
||||
}
|
||||
}
|
||||
for l in &mut out {
|
||||
l.end = l.end.max(l.start);
|
||||
let end = l.end;
|
||||
l.stops.retain(|s| s.0 <= end);
|
||||
if l.stops.last().is_none_or(|s| s.0 < end) {
|
||||
let x = l.stops.last().map_or(0.0, |s| s.1);
|
||||
l.stops.push((end, x));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Draws glyph outlines (font space, y up) into a path (pixels, y down) at a pen position.
|
||||
struct Pen<'a> {
|
||||
pub(crate) struct Pen<'a> {
|
||||
cmds: &'a mut Vec<PathCmd>,
|
||||
x: f32,
|
||||
y: f32,
|
||||
@@ -808,7 +646,7 @@ mod tests {
|
||||
|
||||
/// Synthetic glyphs: a 10 × 20 box standing on the baseline, `n` of them 10 apart.
|
||||
fn boxes(n: u32) -> Vec<PlacedGlyph> {
|
||||
(0..n).map(|i| PlacedGlyph { outline: Path::rect(0.0, -20.0, 10.0, 20.0), x: i as f32 * 10.0, baseline: 20.0, advance: 10.0, index: i }).collect()
|
||||
(0..n).map(|i| PlacedGlyph { outline: Path::rect(0.0, -20.0, 10.0, 20.0), x: i as f32 * 10.0, baseline: 20.0, advance: 10.0, index: i, paint: 0 }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -884,7 +722,7 @@ cd", &style(20.0)).unwrap();
|
||||
assert_eq!((w.carets[0].start, w.carets[0].end, w.carets[1].start, w.carets[1].end), (0, 4, 4, 7));
|
||||
// Empty text has one line with one place for the caret; centred text starts mid-box.
|
||||
let e = fonts.layout("", &style(20.0)).unwrap();
|
||||
assert_eq!(e.carets, vec![CaretLine { start: 0, end: 0, stops: vec![(0, 0.0)] }]);
|
||||
assert_eq!((e.carets.len(), e.carets[0].start, e.carets[0].end, e.carets[0].stops.clone()), (1, 0, 0, vec![(0, 0.0)]));
|
||||
let c = fonts.layout("", &Style { width: Some(100.0), align: Align::Center, ..style(20.0) }).unwrap();
|
||||
assert_eq!(c.carets[0].x_at(0), 50.0);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,636 @@
|
||||
//! Styled text (ADR 0085): runs of characters, each in its own face, size, spacing, baseline
|
||||
//! shift and underline, in paragraphs with their own alignment, indent, margins and line
|
||||
//! spacing. Each run is shaped on its own with `harfrust`, lines break across runs, and the
|
||||
//! glyphs come out grouped by the run's `paint` (the caller's colour and link), so a block with
|
||||
//! several colours draws as one filled path per colour.
|
||||
//!
|
||||
//! One run in one paragraph lays out exactly as [`crate::Fonts::layout`] always has: the same
|
||||
//! outline, box, lines and carets.
|
||||
|
||||
use crate::{Align, CaretLine, Fonts, Layout, MAX_CHARS, Pen, PlacedGlyph, TextError};
|
||||
use anicraft_geom::{Path, PathCmd, Vec2};
|
||||
use skrifa::MetadataProvider as _;
|
||||
use skrifa::raw::TableProvider as _;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Most runs laid out in one block; more are joined into the last.
|
||||
pub const MAX_RUNS: usize = 10_000;
|
||||
|
||||
/// Most different faces (family, bold, italic) in one block; runs past it use the first face.
|
||||
pub const MAX_FACES: usize = 64;
|
||||
|
||||
/// Where a run sits against the line's baseline.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum Shift {
|
||||
#[default]
|
||||
Normal,
|
||||
/// Smaller and raised, by the font's own superscript size and offset.
|
||||
Superscript,
|
||||
/// Smaller and lowered, by the font's own subscript size and offset.
|
||||
Subscript,
|
||||
}
|
||||
|
||||
/// One run's character style.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RunStyle {
|
||||
pub family: String,
|
||||
/// The em size in pixels (before a superscript or subscript makes it smaller).
|
||||
pub size: f32,
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
/// Extra space after each character, in pixels.
|
||||
pub letter_spacing: f32,
|
||||
pub shift: Shift,
|
||||
pub underline: bool,
|
||||
/// The caller's paint for these glyphs (a colour and link): glyphs come out grouped by it.
|
||||
pub paint: u32,
|
||||
}
|
||||
|
||||
impl Default for RunStyle {
|
||||
fn default() -> Self {
|
||||
RunStyle { family: String::new(), size: 32.0, bold: false, italic: false, letter_spacing: 0.0, shift: Shift::Normal, underline: false, paint: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// A run: this many characters (`char`s, line breaks included) in this style.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Run {
|
||||
pub chars: usize,
|
||||
pub style: RunStyle,
|
||||
}
|
||||
|
||||
/// One paragraph's layout.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct ParaStyle {
|
||||
pub align: Align,
|
||||
/// The first line starts this much further in (pixels; negative hangs it out).
|
||||
pub indent: f32,
|
||||
/// Space kept clear at the box's left and right (pixels).
|
||||
pub left_margin: f32,
|
||||
pub right_margin: f32,
|
||||
/// Extra space below each of its lines (pixels), added to the font's line height.
|
||||
pub line_spacing: f32,
|
||||
}
|
||||
|
||||
/// Text with its runs and paragraphs. Runs cover the text from its start (a shorter list leaves
|
||||
/// the rest in the last run's style; a longer one is cut at the text's end); paragraphs are the
|
||||
/// text's lines (split at `\n`), in order (missing ones take the last one's style).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct RichText<'a> {
|
||||
pub text: &'a str,
|
||||
pub runs: &'a [Run],
|
||||
pub paragraphs: &'a [ParaStyle],
|
||||
/// Lines wrap to this width (pixels); `None` keeps each paragraph on one line.
|
||||
pub width: Option<f32>,
|
||||
}
|
||||
|
||||
fn fin(v: f32, d: f32) -> f32 {
|
||||
if v.is_finite() { v } else { d }
|
||||
}
|
||||
|
||||
/// A run style clamped to sane ranges (sizes from 1 to 2000 px, spacing within ±1000 px).
|
||||
pub fn sanitize_run(s: &RunStyle) -> RunStyle {
|
||||
RunStyle { size: fin(s.size, 32.0).clamp(1.0, 2000.0), letter_spacing: fin(s.letter_spacing, 0.0).clamp(-1000.0, 1000.0), ..s.clone() }
|
||||
}
|
||||
|
||||
/// A paragraph style clamped to sane ranges (indent within ±10000 px, margins 0 to 10000 px,
|
||||
/// line spacing within ±1000 px).
|
||||
pub fn sanitize_para(p: &ParaStyle) -> ParaStyle {
|
||||
ParaStyle {
|
||||
align: p.align,
|
||||
indent: fin(p.indent, 0.0).clamp(-10_000.0, 10_000.0),
|
||||
left_margin: fin(p.left_margin, 0.0).clamp(0.0, 10_000.0),
|
||||
right_margin: fin(p.right_margin, 0.0).clamp(0.0, 10_000.0),
|
||||
line_spacing: fin(p.line_spacing, 0.0).clamp(-1000.0, 1000.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// A run's vertical metrics at its own size (pixels): what a line it is on must make room for.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
struct RunMetrics {
|
||||
ascent: f32,
|
||||
/// Below the baseline, positive.
|
||||
descent: f32,
|
||||
/// The font's line height ((ascent − descent + leading), at least half the size).
|
||||
height: f32,
|
||||
/// The underline's top above the baseline (negative: below) and its thickness.
|
||||
underline: (f32, f32),
|
||||
/// How far a superscript or subscript moves the baseline (pixels, y down) and the size its
|
||||
/// glyphs are drawn at.
|
||||
shift_y: f32,
|
||||
glyph_size: f32,
|
||||
}
|
||||
|
||||
/// One shaped glyph, ready to place.
|
||||
struct Shaped {
|
||||
outline: Option<Arc<Path>>,
|
||||
/// Character it starts at (of the whole text).
|
||||
index: u32,
|
||||
run: u32,
|
||||
x_offset: f32,
|
||||
y_offset: f32,
|
||||
advance: f32,
|
||||
space: bool,
|
||||
}
|
||||
|
||||
/// A stretch of one paragraph in one run: what is shaped on its own.
|
||||
struct Segment {
|
||||
run: usize,
|
||||
/// Byte range in the text, and the character its start is.
|
||||
bytes: (usize, usize),
|
||||
first_char: u32,
|
||||
}
|
||||
|
||||
/// A laid-out line: its paragraph, whether it is the paragraph's first, its width, its glyphs
|
||||
/// with their pen x (from the line's start).
|
||||
struct Line {
|
||||
para: usize,
|
||||
first: bool,
|
||||
width: f32,
|
||||
glyphs: Vec<(Shaped, f32)>,
|
||||
}
|
||||
|
||||
/// One paragraph: its first character, its length in characters, and its byte range (without
|
||||
/// a trailing `\r`).
|
||||
struct Para {
|
||||
start: u32,
|
||||
len: u32,
|
||||
bytes: (usize, usize),
|
||||
}
|
||||
|
||||
impl Fonts {
|
||||
/// Lays styled text out ([`RichText`]). `glyphs` also hands back each glyph on its own.
|
||||
pub fn layout_rich(&self, rich: &RichText, glyphs: bool) -> Result<Layout, TextError> {
|
||||
let text = rich.text;
|
||||
let n_chars = text.chars().count();
|
||||
if n_chars > MAX_CHARS {
|
||||
return Err(TextError::TooLong);
|
||||
}
|
||||
// Runs as character ranges over the whole text, sanitized.
|
||||
let mut runs: Vec<(u32, u32, RunStyle)> = Vec::new();
|
||||
let mut at = 0usize;
|
||||
for r in rich.runs.iter().take(MAX_RUNS) {
|
||||
if at >= n_chars && !runs.is_empty() {
|
||||
break;
|
||||
}
|
||||
let end = at.saturating_add(r.chars).min(n_chars);
|
||||
runs.push((at as u32, end as u32, sanitize_run(&r.style)));
|
||||
at = end;
|
||||
}
|
||||
if runs.is_empty() {
|
||||
runs.push((0, n_chars as u32, RunStyle::default()));
|
||||
}
|
||||
if let Some(last) = runs.last_mut() {
|
||||
last.1 = n_chars as u32;
|
||||
}
|
||||
// Faces: one per family, weight and slant.
|
||||
let mut faces: Vec<(fontdb::ID, String)> = Vec::new();
|
||||
let mut face_of_run: Vec<usize> = Vec::with_capacity(runs.len());
|
||||
let mut families: Vec<String> = Vec::with_capacity(runs.len());
|
||||
let mut keys: HashMap<(String, bool, bool), usize> = HashMap::new();
|
||||
for (_, _, st) in &runs {
|
||||
let family = self.resolve(&st.family).ok_or(TextError::NoFonts)?;
|
||||
let key = (family.clone(), st.bold, st.italic);
|
||||
let face = match keys.get(&key) {
|
||||
Some(&f) => f,
|
||||
None if faces.len() >= MAX_FACES => 0,
|
||||
None => {
|
||||
let q = fontdb::Query {
|
||||
families: &[fontdb::Family::Name(&family)],
|
||||
weight: if st.bold { fontdb::Weight::BOLD } else { fontdb::Weight::NORMAL },
|
||||
stretch: fontdb::Stretch::Normal,
|
||||
style: if st.italic { fontdb::Style::Italic } else { fontdb::Style::Normal },
|
||||
};
|
||||
let id = self.db.query(&q).ok_or(TextError::NoFonts)?;
|
||||
faces.push((id, family.clone()));
|
||||
keys.insert(key, faces.len() - 1);
|
||||
faces.len() - 1
|
||||
}
|
||||
};
|
||||
face_of_run.push(face);
|
||||
families.push(faces.get(face).map_or(family, |f| f.1.clone()));
|
||||
}
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
|
||||
// Paragraphs at line breaks.
|
||||
let mut paras: Vec<Para> = Vec::new();
|
||||
let (mut byte, mut ch) = (0usize, 0u32);
|
||||
for raw in text.split('\n') {
|
||||
let body = raw.strip_suffix('\r').unwrap_or(raw);
|
||||
let len = body.chars().count() as u32;
|
||||
paras.push(Para { start: ch, len, bytes: (byte, byte + body.len()) });
|
||||
byte += raw.len() + 1;
|
||||
ch += raw.chars().count() as u32 + 1;
|
||||
}
|
||||
// Byte offset of every character (and of the end).
|
||||
let mut byte_of: Vec<usize> = text.char_indices().map(|(b, _)| b).collect();
|
||||
byte_of.push(text.len());
|
||||
// Segments: each paragraph cut at run boundaries (both in order: one pass over each).
|
||||
let mut segs: Vec<(usize, Segment)> = Vec::new();
|
||||
let mut ri = 0usize;
|
||||
for (pi, p) in paras.iter().enumerate() {
|
||||
let (s, e) = (p.start, p.start + p.len);
|
||||
while runs.get(ri).is_some_and(|r| r.1 <= s) && ri + 1 < runs.len() {
|
||||
ri += 1;
|
||||
}
|
||||
let mut k = ri;
|
||||
while let Some((rs, re, _)) = runs.get(k) {
|
||||
if *rs >= e {
|
||||
break;
|
||||
}
|
||||
let (a, b) = (s.max(*rs), e.min(*re));
|
||||
if a < b {
|
||||
let bytes = (byte_of.get(a as usize).copied().unwrap_or(p.bytes.1), byte_of.get(b as usize).copied().unwrap_or(p.bytes.1));
|
||||
segs.push((pi, Segment { run: k, bytes, first_char: a }));
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
// The segments of each run.
|
||||
let mut segs_of_run: Vec<Vec<usize>> = vec![Vec::new(); runs.len()];
|
||||
for (si, (_, seg)) in segs.iter().enumerate() {
|
||||
if let Some(list) = segs_of_run.get_mut(seg.run) {
|
||||
list.push(si);
|
||||
}
|
||||
}
|
||||
// Shape every segment and read every run's metrics, face by face.
|
||||
let mut runs_of_face: Vec<Vec<usize>> = vec![Vec::new(); faces.len()];
|
||||
for (ri, f) in face_of_run.iter().enumerate() {
|
||||
if let Some(list) = runs_of_face.get_mut(*f) {
|
||||
list.push(ri);
|
||||
}
|
||||
}
|
||||
let mut shaped: Vec<Vec<Shaped>> = (0..segs.len()).map(|_| Vec::new()).collect();
|
||||
let mut metrics: Vec<RunMetrics> = vec![RunMetrics::default(); runs.len()];
|
||||
let mut missing = 0usize;
|
||||
for (fi, (id, _)) in faces.iter().enumerate() {
|
||||
let ok = self.db.with_face_data(*id, |data, index| {
|
||||
let font = skrifa::FontRef::from_index(data, index).ok()?;
|
||||
let shaper_data = harfrust::ShaperData::new(&font);
|
||||
let shaper = shaper_data.shaper(&font).build();
|
||||
let outlines = font.outline_glyphs();
|
||||
let charmap = font.charmap();
|
||||
let os2 = font.os2().ok();
|
||||
let mut cache: HashMap<(u32, u32), Option<Arc<Path>>> = HashMap::new();
|
||||
for &ri in runs_of_face.get(fi).map_or(&[][..], Vec::as_slice) {
|
||||
let Some((rs, re, st)) = runs.get(ri) else { continue };
|
||||
let m = run_metrics(&font, os2.as_ref(), st);
|
||||
if let Some(slot) = metrics.get_mut(ri) {
|
||||
*slot = m;
|
||||
}
|
||||
missing += chars.get(*rs as usize..*re as usize).unwrap_or(&[]).iter().filter(|c| !c.is_control() && !c.is_whitespace() && charmap.map(**c).is_none()).count();
|
||||
let size = skrifa::instance::Size::new(m.glyph_size);
|
||||
let upem = f32::from(skrifa::MetadataProvider::metrics(&font, size, skrifa::instance::LocationRef::default()).units_per_em.max(1));
|
||||
let scale = m.glyph_size / upem;
|
||||
for &si in segs_of_run.get(ri).map_or(&[][..], Vec::as_slice) {
|
||||
let Some((_, seg)) = segs.get(si) else { continue };
|
||||
let Some(piece) = text.get(seg.bytes.0..seg.bytes.1) else { continue };
|
||||
let mut to_char = vec![0u32; piece.len() + 1];
|
||||
let mut n = 0u32;
|
||||
for (b, _) in piece.char_indices() {
|
||||
if let Some(slot) = to_char.get_mut(b) {
|
||||
*slot = n;
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
if let Some(last) = to_char.last_mut() {
|
||||
*last = n;
|
||||
}
|
||||
let mut buffer = harfrust::UnicodeBuffer::new();
|
||||
buffer.push_str(piece);
|
||||
buffer.guess_segment_properties();
|
||||
let out = shaper.shape(buffer, harfrust::ShapeOptions::new());
|
||||
let mut list: Vec<Shaped> = Vec::with_capacity(out.glyph_infos().len());
|
||||
for (info, pos) in out.glyph_infos().iter().zip(out.glyph_positions()) {
|
||||
let local = to_char.get(info.cluster as usize).copied().unwrap_or(n).min(n);
|
||||
let index = seg.first_char + local;
|
||||
let outline = cache
|
||||
.entry((info.glyph_id, m.glyph_size.to_bits()))
|
||||
.or_insert_with(|| {
|
||||
let g = outlines.get(skrifa::GlyphId::new(info.glyph_id))?;
|
||||
let mut p = Path::new();
|
||||
let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default());
|
||||
let mut pen = Pen { cmds: &mut p.cmds, x: 0.0, y: 0.0 };
|
||||
let _ = g.draw(settings, &mut pen);
|
||||
Some(Arc::new(p))
|
||||
})
|
||||
.clone();
|
||||
list.push(Shaped {
|
||||
outline,
|
||||
index,
|
||||
run: ri as u32,
|
||||
x_offset: pos.x_offset as f32 * scale,
|
||||
y_offset: pos.y_offset as f32 * scale,
|
||||
advance: pos.x_advance as f32 * scale + st.letter_spacing,
|
||||
space: chars.get(index as usize).is_some_and(|c| c.is_whitespace()),
|
||||
});
|
||||
}
|
||||
if let Some(slot) = shaped.get_mut(si) {
|
||||
*slot = list;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
});
|
||||
if ok.flatten().is_none() {
|
||||
return Err(TextError::NoFonts);
|
||||
}
|
||||
}
|
||||
|
||||
// Paragraph styles, sanitized; missing ones take the last one's.
|
||||
let para_style = |pi: usize| -> ParaStyle { rich.paragraphs.get(pi).or(rich.paragraphs.last()).map(sanitize_para).unwrap_or_default() };
|
||||
let width = rich.width.filter(|w| w.is_finite() && *w > 0.0).map(|w| w.min(100_000.0));
|
||||
|
||||
// Lines: each paragraph's glyphs, wrapped at spaces to its room if there is a width.
|
||||
let mut lines: Vec<Line> = Vec::new();
|
||||
let mut seg_iter = segs.into_iter().zip(shaped).peekable();
|
||||
for (pi, _) in paras.iter().enumerate() {
|
||||
let ps = para_style(pi);
|
||||
let mut run_glyphs: Vec<Shaped> = Vec::new();
|
||||
while let Some(((p, _), _)) = seg_iter.peek() {
|
||||
if *p != pi {
|
||||
break;
|
||||
}
|
||||
if let Some((_, g)) = seg_iter.next() {
|
||||
run_glyphs.extend(g);
|
||||
}
|
||||
}
|
||||
let room = |first: bool| width.map(|w| w - ps.left_margin - ps.right_margin - if first { ps.indent } else { 0.0 });
|
||||
let mut first = true;
|
||||
let mut line: Vec<(Shaped, f32)> = Vec::new();
|
||||
let mut x = 0.0f32;
|
||||
// Where the current line could break: after its last space.
|
||||
let mut break_at: Option<usize> = None;
|
||||
for g in run_glyphs {
|
||||
if let Some(w) = room(first)
|
||||
&& !g.space
|
||||
&& x + g.advance > w
|
||||
&& !line.is_empty()
|
||||
{
|
||||
// Wrap: at the last space if there is one (dropping trailing spaces), else here.
|
||||
let rest = match break_at {
|
||||
Some(b) => line.split_off(b),
|
||||
None => Vec::new(),
|
||||
};
|
||||
while line.last().is_some_and(|(g, _)| g.space) {
|
||||
line.pop();
|
||||
}
|
||||
let lw = line.last().map_or(0.0, |(g, gx)| gx + g.advance);
|
||||
lines.push(Line { para: pi, first, width: lw, glyphs: std::mem::take(&mut line) });
|
||||
first = false;
|
||||
let shift = rest.first().map_or(0.0, |(_, gx)| *gx);
|
||||
line = rest.into_iter().map(|(g, gx)| (g, gx - shift)).collect();
|
||||
x = line.last().map_or(0.0, |(g, gx)| gx + g.advance);
|
||||
break_at = None;
|
||||
}
|
||||
line.push((g, x));
|
||||
x += line.last().map_or(0.0, |(g, _)| g.advance);
|
||||
if line.last().is_some_and(|(g, _)| g.space) {
|
||||
break_at = Some(line.len());
|
||||
}
|
||||
}
|
||||
while line.last().is_some_and(|(g, _)| g.space) {
|
||||
line.pop();
|
||||
}
|
||||
let lw = line.last().map_or(0.0, |(g, gx)| gx + g.advance);
|
||||
lines.push(Line { para: pi, first, width: lw, glyphs: line });
|
||||
}
|
||||
|
||||
// Each line's room above and below its baseline: the most any run on it needs (an
|
||||
// empty line: the run its paragraph starts in). `(ascent, descent, line height)`, the
|
||||
// height with the paragraph's line spacing.
|
||||
let run_at = |c: u32| runs.partition_point(|r| r.0 <= c).saturating_sub(1);
|
||||
let line_metrics = |l: &Line| -> (f32, f32, f32) {
|
||||
let mut list: Vec<usize> = l.glyphs.iter().map(|(g, _)| g.run as usize).collect();
|
||||
if list.is_empty() {
|
||||
let start = paras.get(l.para).map_or(0, |p| p.start);
|
||||
list.push(run_at(if start > 0 && start as usize >= n_chars { start - 1 } else { start }));
|
||||
}
|
||||
list.sort_unstable();
|
||||
list.dedup();
|
||||
let ls = para_style(l.para).line_spacing;
|
||||
if let [one] = list.as_slice() {
|
||||
let m = metrics.get(*one).copied().unwrap_or_default();
|
||||
return (m.ascent, m.descent, m.height + ls);
|
||||
}
|
||||
let (mut asc, mut below, mut desc) = (f32::MIN, f32::MIN, f32::MIN);
|
||||
for r in list {
|
||||
let m = metrics.get(r).copied().unwrap_or_default();
|
||||
asc = asc.max(m.ascent);
|
||||
below = below.max(m.height - m.ascent);
|
||||
desc = desc.max(m.descent);
|
||||
}
|
||||
(asc, desc, asc + below + ls)
|
||||
};
|
||||
let lm: Vec<(f32, f32, f32)> = lines.iter().map(line_metrics).collect();
|
||||
// Every line alike (one style): baselines a line height apart, as text always was.
|
||||
let uniform = lm.windows(2).all(|w| matches!(w, [a, b] if a == b));
|
||||
let mut tops: Vec<f32> = Vec::with_capacity(lines.len());
|
||||
let first = lm.first().copied().unwrap_or((0.0, 0.0, 0.0));
|
||||
let line_height = first.2;
|
||||
let height = if uniform {
|
||||
for row in 0..lines.len() {
|
||||
tops.push(row as f32 * line_height);
|
||||
}
|
||||
(lines.len().max(1) as f32 - 1.0) * line_height + (first.0 - -first.1)
|
||||
} else {
|
||||
let mut top = 0.0f32;
|
||||
for m in &lm {
|
||||
tops.push(top);
|
||||
top += m.2;
|
||||
}
|
||||
let last = lm.last().copied().unwrap_or(first);
|
||||
tops.last().copied().unwrap_or(0.0) + last.0 + last.1
|
||||
};
|
||||
|
||||
let box_width = width.unwrap_or_else(|| {
|
||||
lines
|
||||
.iter()
|
||||
.map(|l| {
|
||||
let ps = para_style(l.para);
|
||||
ps.left_margin + if l.first { ps.indent } else { 0.0 } + l.width + ps.right_margin
|
||||
})
|
||||
.fold(0.0, f32::max)
|
||||
});
|
||||
let shift_of = |l: &Line| -> f32 {
|
||||
let ps = para_style(l.para);
|
||||
let start = ps.left_margin + if l.first { ps.indent } else { 0.0 };
|
||||
match ps.align {
|
||||
Align::Left => start,
|
||||
Align::Center => start + ((box_width - ps.right_margin - start) - l.width) * 0.5,
|
||||
Align::Right => box_width - ps.right_margin - l.width,
|
||||
}
|
||||
};
|
||||
|
||||
// Draw: glyphs grouped by paint, in the order paints first appear.
|
||||
let mut pieces: Vec<(u32, Path)> = Vec::new();
|
||||
let mut piece_of: HashMap<u32, usize> = HashMap::new();
|
||||
let mut placed: Vec<PlacedGlyph> = Vec::new();
|
||||
let paint_of = |r: u32| runs.get(r as usize).map_or(0, |x| x.2.paint);
|
||||
for (row, l) in lines.iter().enumerate() {
|
||||
let shift = shift_of(l);
|
||||
let top = tops.get(row).copied().unwrap_or(0.0);
|
||||
let base = if uniform { first.0 + top } else { top + lm.get(row).map_or(0.0, |m| m.0) };
|
||||
let mut underline: Option<(u32, f32, f32)> = None;
|
||||
let flush = |u: Option<(u32, f32, f32)>, pieces: &mut Vec<(u32, Path)>, piece_of: &mut HashMap<u32, usize>| {
|
||||
let Some((r, x0, x1)) = u else { return };
|
||||
let m = metrics.get(r as usize).copied().unwrap_or_default();
|
||||
let (top, thick) = m.underline;
|
||||
let rect = Path::rect(x0, base + m.shift_y - top, (x1 - x0).max(0.0), thick);
|
||||
let k = *piece_of.entry(paint_of(r)).or_insert_with(|| {
|
||||
pieces.push((paint_of(r), Path::new()));
|
||||
pieces.len() - 1
|
||||
});
|
||||
if let Some(p) = pieces.get_mut(k) {
|
||||
p.1.cmds.extend(rect.cmds);
|
||||
}
|
||||
};
|
||||
for (g, gx) in &l.glyphs {
|
||||
let st = runs.get(g.run as usize).map(|r| &r.2);
|
||||
let m = metrics.get(g.run as usize).copied().unwrap_or_default();
|
||||
// Underlines: one bar per stretch of an underlined run on the line.
|
||||
let under = st.is_some_and(|s| s.underline);
|
||||
match underline {
|
||||
Some((r, x0, _)) if under && r == g.run => underline = Some((r, x0, shift + gx + g.advance)),
|
||||
_ => {
|
||||
flush(underline.take(), &mut pieces, &mut piece_of);
|
||||
if under {
|
||||
underline = Some((g.run, shift + gx, shift + gx + g.advance));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(outline) = &g.outline else { continue };
|
||||
let paint = paint_of(g.run);
|
||||
let k = *piece_of.entry(paint).or_insert_with(|| {
|
||||
pieces.push((paint, Path::new()));
|
||||
pieces.len() - 1
|
||||
});
|
||||
let (px, py) = (shift + gx + g.x_offset, base + m.shift_y - g.y_offset);
|
||||
if let Some(p) = pieces.get_mut(k) {
|
||||
p.1.cmds.extend(outline.cmds.iter().map(|c| moved(c, px, py)));
|
||||
}
|
||||
if glyphs {
|
||||
let (ox, oy) = (g.x_offset, m.shift_y - g.y_offset);
|
||||
let own = Path { cmds: outline.cmds.iter().map(|c| moved(c, ox, oy)).collect() };
|
||||
placed.push(PlacedGlyph { outline: own, x: shift + gx, baseline: base, advance: g.advance, index: g.index, paint });
|
||||
}
|
||||
}
|
||||
flush(underline.take(), &mut pieces, &mut piece_of);
|
||||
}
|
||||
let mut outline = Path::new();
|
||||
for (_, p) in &pieces {
|
||||
outline.cmds.extend_from_slice(&p.cmds);
|
||||
}
|
||||
let carets = caret_lines(&lines, ¶s, &tops, &lm, uniform, first.0, &shift_of);
|
||||
Ok(Layout {
|
||||
outline,
|
||||
width: box_width.max(0.0),
|
||||
height: height.max(0.0),
|
||||
family: families.first().cloned().unwrap_or_default(),
|
||||
missing,
|
||||
lines: lines.len().max(1),
|
||||
line_height,
|
||||
ascent: first.0,
|
||||
carets,
|
||||
glyphs: placed,
|
||||
pieces,
|
||||
families,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A path command moved by `(dx, dy)`, added the way a pen at that position draws it.
|
||||
fn moved(c: &PathCmd, dx: f32, dy: f32) -> PathCmd {
|
||||
let m = |p: Vec2| Vec2::new(dx + p.x, dy + p.y);
|
||||
match *c {
|
||||
PathCmd::MoveTo(p) => PathCmd::MoveTo(m(p)),
|
||||
PathCmd::LineTo(p) => PathCmd::LineTo(m(p)),
|
||||
PathCmd::QuadTo(a, p) => PathCmd::QuadTo(m(a), m(p)),
|
||||
PathCmd::CubicTo(a, b, p) => PathCmd::CubicTo(m(a), m(b), m(p)),
|
||||
PathCmd::Close => PathCmd::Close,
|
||||
}
|
||||
}
|
||||
|
||||
/// A run's metrics in its face at its size.
|
||||
fn run_metrics(font: &skrifa::FontRef, os2: Option<&skrifa::raw::tables::os2::Os2>, st: &RunStyle) -> RunMetrics {
|
||||
let size = skrifa::instance::Size::new(st.size);
|
||||
let m = skrifa::MetadataProvider::metrics(font, size, skrifa::instance::LocationRef::default());
|
||||
let em = f32::from(m.units_per_em.max(1));
|
||||
// The font's superscript and subscript size and offset (OS/2), else the usual ones.
|
||||
let (scale, raise) = match st.shift {
|
||||
Shift::Normal => (1.0, 0.0),
|
||||
Shift::Superscript => {
|
||||
let s = os2.map_or(0.0, |o| f32::from(o.y_superscript_y_size()) / em);
|
||||
let o = os2.map_or(0.0, |o| f32::from(o.y_superscript_y_offset()) / em);
|
||||
(if (0.3..=1.0).contains(&s) { s } else { 0.65 }, if (0.05..=1.0).contains(&o) { o } else { 0.35 })
|
||||
}
|
||||
Shift::Subscript => {
|
||||
let s = os2.map_or(0.0, |o| f32::from(o.y_subscript_y_size()) / em);
|
||||
let o = os2.map_or(0.0, |o| f32::from(o.y_subscript_y_offset()) / em);
|
||||
(if (0.3..=1.0).contains(&s) { s } else { 0.65 }, -(if (0.0..=1.0).contains(&o) && o > 0.0 { o } else { 0.15 }))
|
||||
}
|
||||
};
|
||||
let glyph_size = (st.size * scale).max(0.5);
|
||||
let underline = m.underline.filter(|d| d.thickness.is_finite() && d.thickness > 0.0 && d.offset.is_finite()).map_or((-0.1 * st.size, (0.05 * st.size).max(1.0)), |d| (d.offset, d.thickness));
|
||||
// A smaller underline for smaller glyphs.
|
||||
let underline = if scale < 1.0 { (underline.0 * scale, underline.1 * scale) } else { underline };
|
||||
RunMetrics {
|
||||
ascent: m.ascent,
|
||||
descent: -m.descent,
|
||||
height: (m.ascent - m.descent + m.leading).max(st.size * 0.5),
|
||||
underline,
|
||||
shift_y: -raise * st.size,
|
||||
glyph_size,
|
||||
}
|
||||
}
|
||||
|
||||
/// The caret positions of laid-out lines (see [`CaretLine`]).
|
||||
fn caret_lines(lines: &[Line], paras: &[Para], tops: &[f32], lm: &[(f32, f32, f32)], uniform: bool, first_ascent: f32, shift_of: &dyn Fn(&Line) -> f32) -> Vec<CaretLine> {
|
||||
let mut out: Vec<CaretLine> = Vec::with_capacity(lines.len());
|
||||
for (row, l) in lines.iter().enumerate() {
|
||||
let shift = shift_of(l);
|
||||
let (pstart, plen) = paras.get(l.para).map_or((0, 0), |p| (p.start, p.len));
|
||||
let ch = |i: u32| i.clamp(pstart, pstart + plen);
|
||||
let start = if l.first { pstart } else { l.glyphs.first().map_or(pstart, |(g, _)| ch(g.index)) };
|
||||
let mut stops: Vec<(u32, f32)> = l.glyphs.iter().map(|(g, gx)| (ch(g.index), shift + gx)).collect();
|
||||
stops.sort_by_key(|s| s.0);
|
||||
stops.dedup_by_key(|s| s.0);
|
||||
if l.first && stops.first().is_none_or(|s| s.0 > start) {
|
||||
stops.insert(0, (start, shift));
|
||||
}
|
||||
// The boundary after the last glyph (its trailing spaces, if any, follow it).
|
||||
if let Some(&(c, _)) = stops.last() {
|
||||
stops.push((c + 1, shift + l.width));
|
||||
}
|
||||
let m = lm.get(row).copied().unwrap_or_default();
|
||||
let top = tops.get(row).copied().unwrap_or(0.0);
|
||||
let baseline = if uniform { first_ascent + top } else { top + m.0 };
|
||||
out.push(CaretLine { start, end: start, stops, top, height: m.2, baseline });
|
||||
// The previous line of the same paragraph ends where this one starts.
|
||||
if !l.first && let Some(prev) = out.len().checked_sub(2).and_then(|i| out.get_mut(i)) {
|
||||
prev.end = start;
|
||||
}
|
||||
}
|
||||
// The last line of each paragraph ends with it.
|
||||
for (row, l) in lines.iter().enumerate() {
|
||||
let last_of_para = lines.get(row + 1).is_none_or(|n| n.para != l.para);
|
||||
if last_of_para && let (Some(c), Some(p)) = (out.get_mut(row), paras.get(l.para)) {
|
||||
c.end = p.start + p.len;
|
||||
}
|
||||
}
|
||||
for l in &mut out {
|
||||
l.end = l.end.max(l.start);
|
||||
let end = l.end;
|
||||
l.stops.retain(|s| s.0 <= end);
|
||||
if l.stops.last().is_none_or(|s| s.0 < end) {
|
||||
let x = l.stops.last().map_or(0.0, |s| s.1);
|
||||
l.stops.push((end, x));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rich_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,181 @@
|
||||
use super::*;
|
||||
use crate::Style;
|
||||
|
||||
fn fonts() -> Option<&'static Fonts> {
|
||||
let f = Fonts::get();
|
||||
if f.families().is_empty() {
|
||||
eprintln!("no fonts on this computer: rich text layout tests skipped");
|
||||
return None;
|
||||
}
|
||||
Some(f)
|
||||
}
|
||||
|
||||
fn run(chars: usize, size: f32, paint: u32) -> Run {
|
||||
Run { chars, style: RunStyle { size, paint, ..RunStyle::default() } }
|
||||
}
|
||||
|
||||
fn lay(f: &Fonts, text: &str, runs: &[Run], paras: &[ParaStyle], width: Option<f32>) -> Layout {
|
||||
f.layout_rich(&RichText { text, runs, paragraphs: paras, width }, true).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_run_is_the_plain_layout() {
|
||||
let Some(f) = fonts() else { return };
|
||||
let plain = f.layout_glyphs("Hello there\nworld", &Style { size: 24.0, letter_spacing: 1.0, line_spacing: 3.0, width: Some(90.0), ..Style::default() }).unwrap();
|
||||
let runs = [Run { chars: 17, style: RunStyle { size: 24.0, letter_spacing: 1.0, ..RunStyle::default() } }];
|
||||
let rich = lay(f, "Hello there\nworld", &runs, &[ParaStyle { line_spacing: 3.0, ..ParaStyle::default() }], Some(90.0));
|
||||
assert_eq!(rich, plain);
|
||||
assert_eq!(rich.pieces.len(), 1);
|
||||
assert_eq!(rich.pieces[0].1, rich.outline);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paints_cut_the_outline_into_pieces() {
|
||||
let Some(f) = fonts() else { return };
|
||||
let l = lay(f, "abcdef", &[run(2, 20.0, 7), run(2, 20.0, 3), run(2, 20.0, 7)], &[], None);
|
||||
assert_eq!(l.pieces.iter().map(|p| p.0).collect::<Vec<_>>(), vec![7, 3], "in the order paints first appear");
|
||||
let joined: Vec<PathCmd> = l.pieces.iter().flat_map(|p| p.1.cmds.clone()).collect();
|
||||
assert_eq!(joined, l.outline.cmds, "the outline is the pieces one after another");
|
||||
assert_eq!(l.glyphs.iter().map(|g| g.paint).collect::<Vec<_>>(), vec![7, 7, 3, 3, 7, 7]);
|
||||
// The same glyphs as one run: paints don't move anything.
|
||||
let one = lay(f, "abcdef", &[run(6, 20.0, 0)], &[], None);
|
||||
assert_eq!((one.width, one.height), (l.width, l.height));
|
||||
assert_eq!(one.glyphs.iter().map(|g| g.x).collect::<Vec<_>>(), l.glyphs.iter().map(|g| g.x).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
/// What the default face says a superscript is raised by at `size` (pixels).
|
||||
fn expected_superscript_raise(f: &Fonts, size: f32) -> f32 {
|
||||
let family = f.resolve("").unwrap();
|
||||
let q = fontdb::Query { families: &[fontdb::Family::Name(&family)], ..fontdb::Query::default() };
|
||||
let id = f.db.query(&q).unwrap();
|
||||
f.db.with_face_data(id, |d, i| {
|
||||
let font = skrifa::FontRef::from_index(d, i).unwrap();
|
||||
let em = f32::from(skrifa::MetadataProvider::metrics(&font, skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()).units_per_em);
|
||||
let o = font.os2().map(|o| f32::from(o.y_superscript_y_offset()) / em).unwrap_or(0.0);
|
||||
if (0.05..=1.0).contains(&o) { o * size } else { 0.35 * size }
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_superscript_is_smaller_and_raised_by_the_fonts_offset() {
|
||||
let Some(f) = fonts() else { return };
|
||||
let sup = RunStyle { size: 40.0, shift: Shift::Superscript, ..RunStyle::default() };
|
||||
let sub = RunStyle { shift: Shift::Subscript, ..sup.clone() };
|
||||
let l = lay(f, "x2y2", &[run(1, 40.0, 0), Run { chars: 1, style: sup }, run(1, 40.0, 0), Run { chars: 1, style: sub }], &[], None);
|
||||
let plain = lay(f, "x2y2", &[run(4, 40.0, 0)], &[], None);
|
||||
let b = |l: &Layout, i: usize| l.glyphs[i].outline.bounds();
|
||||
// Every glyph shares the line's baseline; the shift is in the glyph's own outline.
|
||||
assert!(l.glyphs.iter().all(|g| g.baseline == l.ascent));
|
||||
let (up, down, normal) = (b(&l, 1), b(&l, 3), b(&plain, 1));
|
||||
assert!(up.height() < normal.height() * 0.9 && up.height() > normal.height() * 0.3, "smaller: {up:?} vs {normal:?}");
|
||||
// Raised by the font's offset: the digit's bottom (on its own baseline, within the
|
||||
// outline's overshoot) is that far above the line's.
|
||||
let raise = -up.max.y;
|
||||
let want = expected_superscript_raise(f, 40.0);
|
||||
assert!((raise - want).abs() < 1.0, "raised {raise}, the font says {want}");
|
||||
assert!(down.max.y > 0.5, "a subscript drops below the baseline: {down:?}");
|
||||
// Its advance is smaller too.
|
||||
assert!(l.glyphs[1].advance < plain.glyphs[1].advance * 0.9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_wrap_across_runs_and_make_room_for_the_tallest() {
|
||||
let Some(f) = fonts() else { return };
|
||||
// "aaa " small, "BBB ccc" big: the wrap falls inside the big run.
|
||||
let text = "aaa BBB ccc";
|
||||
let small = lay(f, "aaa ", &[run(4, 20.0, 0)], &[], None);
|
||||
let big_word = lay(f, "BBB", &[run(3, 40.0, 0)], &[], None);
|
||||
let space = lay(f, "a a", &[run(3, 20.0, 0)], &[], None);
|
||||
let w = small.width + (space.width - 2.0 * lay(f, "a", &[run(1, 20.0, 0)], &[], None).width) + big_word.width + 2.0;
|
||||
let l = lay(f, text, &[run(4, 20.0, 0), run(7, 40.0, 1)], &[], Some(w));
|
||||
assert_eq!(l.lines, 2, "{w}");
|
||||
assert_eq!((l.carets[0].start, l.carets[0].end, l.carets[1].start, l.carets[1].end), (0, 8, 8, 11));
|
||||
// The first line's baseline is the big run's ascent (the tallest on it), not the small one's.
|
||||
let big = lay(f, "B", &[run(1, 40.0, 0)], &[], None);
|
||||
assert!((l.ascent - big.ascent).abs() < 1e-3, "{} vs {}", l.ascent, big.ascent);
|
||||
assert!(l.carets[1].baseline > l.carets[0].baseline + big.line_height * 0.9);
|
||||
// A line of only small text after a big one keeps its own height.
|
||||
let two = lay(f, "BIG\nsmall\nsmall", &[run(4, 60.0, 0), run(11, 15.0, 0)], &[], None);
|
||||
let (a, b, c) = (&two.carets[0], &two.carets[1], &two.carets[2]);
|
||||
assert!((b.top - a.height).abs() < 1e-3 && (c.top - b.top - b.height).abs() < 1e-3);
|
||||
assert!(a.height > b.height * 3.0 && (b.height - c.height).abs() < 1e-3, "{} {} {}", a.height, b.height, c.height);
|
||||
let s = lay(f, "s", &[run(1, 15.0, 0)], &[], None);
|
||||
assert!((two.height - (c.baseline + s.height - s.ascent)).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraphs_align_indent_and_keep_their_margins() {
|
||||
let Some(f) = fonts() else { return };
|
||||
let p = |align, indent, left, right| ParaStyle { align, indent, left_margin: left, right_margin: right, line_spacing: 0.0 };
|
||||
let l = lay(f, "a\nb\nc", &[run(5, 20.0, 0)], &[p(Align::Left, 30.0, 10.0, 0.0), p(Align::Right, 0.0, 0.0, 25.0), p(Align::Center, 0.0, 40.0, 0.0)], Some(200.0));
|
||||
let x = |i: usize| l.glyphs[i].x;
|
||||
assert!((x(0) - 40.0).abs() < 1e-3, "indent and left margin: {}", x(0));
|
||||
let bw = l.glyphs[1].advance;
|
||||
assert!((x(1) - (200.0 - 25.0 - bw)).abs() < 1e-3, "right margin: {}", x(1));
|
||||
let cw = l.glyphs[2].advance;
|
||||
assert!((x(2) - (40.0 + (160.0 - cw) * 0.5)).abs() < 1e-3, "centred in what the margins leave: {}", x(2));
|
||||
// An indent only moves a paragraph's first line, and the margins narrow its wrap.
|
||||
let words = "one two three four five six seven eight";
|
||||
let wrapped = lay(f, words, &[run(words.chars().count(), 20.0, 0)], &[p(Align::Left, 20.0, 15.0, 15.0)], Some(160.0));
|
||||
assert!(wrapped.lines >= 3);
|
||||
let starts: Vec<f32> = wrapped.carets.iter().map(|c| c.stops[0].1).collect();
|
||||
assert!((starts[0] - 35.0).abs() < 1e-3 && starts[1..].iter().all(|s| (s - 15.0).abs() < 1e-3), "{starts:?}");
|
||||
assert!(wrapped.outline.bounds().max.x <= 160.0 - 15.0 + 1.0, "{:?}", wrapped.outline.bounds());
|
||||
// Without a width, the box is the widest line with its margins.
|
||||
let free = lay(f, "ab", &[run(2, 20.0, 0)], &[p(Align::Left, 5.0, 10.0, 20.0)], None);
|
||||
let line = free.glyphs[1].x + free.glyphs[1].advance - free.glyphs[0].x;
|
||||
assert!((free.width - (35.0 + line)).abs() < 1e-3, "{}", free.width);
|
||||
// Per-paragraph line spacing.
|
||||
let spaced = lay(f, "a\nb\nc", &[run(5, 20.0, 0)], &[ParaStyle { line_spacing: 30.0, ..ParaStyle::default() }, ParaStyle::default()], None);
|
||||
let tight = lay(f, "a\nb\nc", &[run(5, 20.0, 0)], &[], None);
|
||||
assert!((spaced.height - tight.height - 30.0).abs() < 0.01, "only the first line is spaced: {} vs {}", spaced.height, tight.height);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn underlines_run_under_their_glyphs_in_their_paint() {
|
||||
let Some(f) = fonts() else { return };
|
||||
let u = RunStyle { size: 30.0, underline: true, paint: 1, ..RunStyle::default() };
|
||||
let l = lay(f, "ab cd", &[run(3, 30.0, 0), Run { chars: 2, style: u }], &[], None);
|
||||
let plain = lay(f, "ab cd", &[run(3, 30.0, 0), run(2, 30.0, 1)], &[], None);
|
||||
let (with, without) = (&l.pieces[1].1, &plain.pieces[1].1);
|
||||
assert_eq!(with.cmds.len(), without.cmds.len() + 5, "one bar: a rectangle");
|
||||
let bar = Path { cmds: with.cmds[without.cmds.len()..].to_vec() }.bounds();
|
||||
assert!(bar.min.y > l.ascent - 1.0 && bar.max.y < l.height + 1.0, "under the baseline: {bar:?}");
|
||||
assert!((bar.min.x - l.glyphs[3].x).abs() < 1e-3 && (bar.max.x - l.width).abs() < 1e-3, "{bar:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_runs_are_capped_and_sanitized() {
|
||||
let Some(f) = fonts() else { return };
|
||||
// Thousands of runs: capped, the rest joins the last.
|
||||
let text = "x".repeat(MAX_RUNS + 500);
|
||||
let runs: Vec<Run> = (0..MAX_RUNS + 500).map(|i| run(1, 10.0 + (i % 7) as f32, i as u32 % 3)).collect();
|
||||
let t = std::time::Instant::now();
|
||||
let l = f.layout_rich(&RichText { text: &text, runs: &runs, paragraphs: &[], width: Some(400.0) }, false).unwrap();
|
||||
eprintln!("{} runs laid out in {:?}", MAX_RUNS, t.elapsed());
|
||||
assert_eq!(l.families.len(), MAX_RUNS);
|
||||
assert!(l.width.is_finite() && l.height.is_finite());
|
||||
// As many paragraphs as runs, empty ones included: linear, not paragraphs × runs.
|
||||
let text = "y
|
||||
|
||||
".repeat(MAX_RUNS / 2);
|
||||
let t = std::time::Instant::now();
|
||||
let l = f.layout_rich(&RichText { text: &text, runs: &runs, paragraphs: &[], width: None }, false).unwrap();
|
||||
eprintln!("{} paragraphs laid out in {:?}", MAX_RUNS, t.elapsed());
|
||||
assert_eq!(l.lines, MAX_RUNS + 1);
|
||||
// Hostile sizes, spacing, margins and lengths: clamped, never a panic.
|
||||
let bad = [
|
||||
Run { chars: usize::MAX, style: RunStyle { size: f32::NAN, letter_spacing: f32::INFINITY, ..RunStyle::default() } },
|
||||
Run { chars: 0, style: RunStyle { size: 1e30, ..RunStyle::default() } },
|
||||
];
|
||||
let p = [ParaStyle { indent: f32::NEG_INFINITY, left_margin: -5.0, right_margin: 1e20, line_spacing: f32::NAN, align: Align::Center }];
|
||||
let l = f.layout_rich(&RichText { text: "a b\nc", runs: &bad, paragraphs: &p, width: Some(f32::NAN) }, true).unwrap();
|
||||
assert!(l.width.is_finite() && l.height.is_finite());
|
||||
// Runs longer than the text, shorter than it, or none.
|
||||
for runs in [vec![run(100, 20.0, 0)], vec![run(1, 20.0, 0)], vec![]] {
|
||||
let l = f.layout_rich(&RichText { text: "abc", runs: &runs, paragraphs: &[], width: None }, true).unwrap();
|
||||
assert_eq!(l.glyphs.len(), 3);
|
||||
}
|
||||
assert_eq!(f.layout_rich(&RichText { text: &"x".repeat(MAX_CHARS + 1), runs: &[], paragraphs: &[], width: None }, false), Err(TextError::TooLong));
|
||||
}
|
||||
@@ -21,6 +21,7 @@ thiserror.workspace = true
|
||||
# Synthetic Screen Video key-frame fixture compression only.
|
||||
miniz_oxide = "0.8"
|
||||
craft-image-codecs.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+209
-284
@@ -1,21 +1,22 @@
|
||||
//! Text fields (`DOMStaticText`, `DOMDynamicText`, `DOMInputText`) → text blocks laid out by
|
||||
//! `anicraft-text` (ADR 0014).
|
||||
//! `anicraft-text` (ADR 0014, ADR 0085).
|
||||
//!
|
||||
//! A field holds text runs (`<textRuns><DOMTextRun><characters>…</characters><textAttrs>
|
||||
//! <DOMTextAttrs face="Arial-BoldMT" size="24" fillColor="#FF0000" alignment="center"
|
||||
//! letterSpacing="1" lineSpacing="2"/>`). An AniCraft text block has one style, so a field
|
||||
//! becomes one block per run of consecutive lines that share a style, stacked as Animate
|
||||
//! stacks them; a line that mixes styles takes the style most of its characters have, and the
|
||||
//! report says so.
|
||||
//! letterSpacing="1" lineSpacing="2"/>`). A field becomes one block with the same runs: each
|
||||
//! `DOMTextRun`'s face, size, bold, italic, colour, letter spacing, character position
|
||||
//! (superscript, subscript) and link are its characters' style, and each paragraph takes its
|
||||
//! alignment, indent, margins and line spacing from the run it starts in, as Animate's
|
||||
//! paragraph attributes do.
|
||||
//!
|
||||
//! Dynamic and input fields (ADR 0066) become one field each, whatever their runs: a field is one
|
||||
//! instance that scripts and the viewer use, so it takes its main style, keeps its instance name,
|
||||
//! line type, border, selectability and maximum length, and the report counts them as running.
|
||||
//! Dynamic and input fields (ADR 0066) are one field each, with the same runs for their authored
|
||||
//! text, their instance name, line type, border, selectability and maximum length; text a script
|
||||
//! or a viewer changes is laid out in the field's first style.
|
||||
|
||||
use crate::import::Report;
|
||||
use crate::xml::Element as X;
|
||||
use anicraft_doc::{LineType, Rgba, TextAlign, TextBlock, TextField, TextKind};
|
||||
use anicraft_geom::Vec2;
|
||||
use anicraft_doc::{BaselineShift, CharStyle, LineType, ParagraphStyle, Rgba, TextAlign, TextBlock, TextField, TextKind, TextRun};
|
||||
use anicraft_geom::{Affine, Path, Vec2};
|
||||
use anicraft_text::{Align, FaceMatch, Fonts, TextError};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -25,22 +26,7 @@ use std::sync::Arc;
|
||||
pub const GUTTER: f32 = 2.0;
|
||||
|
||||
/// Most runs read from one field.
|
||||
const MAX_RUNS: usize = 10_000;
|
||||
|
||||
/// One run's style, as `DOMTextAttrs` gives it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct RunStyle {
|
||||
face: String,
|
||||
size: f32,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
color: Rgba,
|
||||
align: TextAlign,
|
||||
letter_spacing: f32,
|
||||
line_spacing: f32,
|
||||
left_margin: f32,
|
||||
right_margin: f32,
|
||||
}
|
||||
const MAX_RUNS: usize = anicraft_doc::MAX_TEXT_RUNS;
|
||||
|
||||
/// A laid-out block and where its box's top-left goes, in the field's coordinates.
|
||||
pub struct Placed {
|
||||
@@ -48,9 +34,17 @@ pub struct Placed {
|
||||
pub offset: Vec2,
|
||||
}
|
||||
|
||||
fn run_style(attrs: Option<craft_xfl::text::TextStyle<'_, X>>, flags: &mut Flags) -> RunStyle {
|
||||
/// What a field used that AniCraft draws differently, reported once per field.
|
||||
#[derive(Default)]
|
||||
struct Flags {
|
||||
justified: bool,
|
||||
}
|
||||
|
||||
/// One run's character and paragraph style, as `DOMTextAttrs` gives it (the face still a
|
||||
/// PostScript name).
|
||||
fn run_style(attrs: Option<craft_xfl::text::TextStyle<'_, X>>, url: &str, flags: &mut Flags) -> (CharStyle, ParagraphStyle) {
|
||||
let Some(a) = attrs else {
|
||||
return RunStyle { face: String::new(), size: 12.0, bold: false, italic: false, color: Rgba::BLACK, align: TextAlign::Left, letter_spacing: 0.0, line_spacing: 0.0, left_margin: 0.0, right_margin: 0.0 };
|
||||
return (CharStyle { size: 12.0, ..CharStyle::default() }, ParagraphStyle::default());
|
||||
};
|
||||
let clamp = |number: Option<f32>, lo: f32, hi: f32| number.unwrap_or(0.0).clamp(lo, hi);
|
||||
let align = match a.alignment() {
|
||||
@@ -62,116 +56,77 @@ fn run_style(attrs: Option<craft_xfl::text::TextStyle<'_, X>>, flags: &mut Flags
|
||||
}
|
||||
_ => TextAlign::Left,
|
||||
};
|
||||
if a.indent().is_some_and(|i| i != 0.0) {
|
||||
flags.indented = true;
|
||||
}
|
||||
if a.character_position().is_some_and(|p| p != "normal") {
|
||||
flags.shifted = true;
|
||||
}
|
||||
let shift = match a.character_position() {
|
||||
Some("superscript") => BaselineShift::Superscript,
|
||||
Some("subscript") => BaselineShift::Subscript,
|
||||
_ => BaselineShift::Normal,
|
||||
};
|
||||
let color = a.color();
|
||||
RunStyle {
|
||||
face: a.face().unwrap_or("").chars().take(256).collect(),
|
||||
let c = CharStyle {
|
||||
font: a.face().unwrap_or("").chars().take(256).collect(),
|
||||
size: a.size().unwrap_or(12.0).clamp(1.0, 2000.0),
|
||||
bold: a.bold().unwrap_or(false),
|
||||
italic: a.italic().unwrap_or(false),
|
||||
color: Rgba::hex(color.rgb).with_alpha(color.alpha),
|
||||
align,
|
||||
letter_spacing: clamp(a.letter_spacing(), -1000.0, 1000.0),
|
||||
shift,
|
||||
underline: false,
|
||||
url: anicraft_doc::safe_url(url).unwrap_or_default(),
|
||||
};
|
||||
let p = ParagraphStyle {
|
||||
align,
|
||||
indent: clamp(a.indent(), -1000.0, 1000.0),
|
||||
left_margin: clamp(a.left_margin(), 0.0, 1000.0),
|
||||
right_margin: clamp(a.right_margin(), 0.0, 1000.0),
|
||||
line_spacing: clamp(a.line_spacing(), -1000.0, 1000.0),
|
||||
left_margin: clamp(a.left_margin(), 0.0, 10_000.0),
|
||||
right_margin: clamp(a.right_margin(), 0.0, 10_000.0),
|
||||
}
|
||||
};
|
||||
(c, p)
|
||||
}
|
||||
|
||||
/// What a field used that AniCraft draws differently, reported once per field.
|
||||
#[derive(Default)]
|
||||
struct Flags {
|
||||
justified: bool,
|
||||
indented: bool,
|
||||
shifted: bool,
|
||||
/// A field's text with its runs (faces resolved to installed families) and one style per
|
||||
/// paragraph.
|
||||
struct Styled {
|
||||
text: String,
|
||||
runs: Vec<TextRun>,
|
||||
paragraphs: Vec<ParagraphStyle>,
|
||||
/// Faces asked for that aren't installed (reported once the text is laid out).
|
||||
missing: Vec<String>,
|
||||
}
|
||||
|
||||
impl Flags {
|
||||
fn report(&self, report: &mut Report) {
|
||||
if self.justified {
|
||||
report.skip("justified text (drawn left-aligned)");
|
||||
}
|
||||
if self.indented {
|
||||
report.skip("first-line indents");
|
||||
}
|
||||
if self.shifted {
|
||||
report.skip("superscript and subscript (drawn on the line)");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A line of the field: its pieces, each with the style of the run it came from.
|
||||
type Line = Vec<(String, usize)>;
|
||||
|
||||
/// The style a line is drawn in: that of the most visible characters (the first on a tie), or
|
||||
/// of its first piece when it is empty.
|
||||
fn main_style(line: &Line) -> (usize, bool) {
|
||||
// Visible characters per style, in the order the styles first appear.
|
||||
let mut totals: Vec<(usize, usize)> = Vec::new();
|
||||
for (t, s) in line {
|
||||
let n = t.chars().filter(|c| !c.is_whitespace()).count();
|
||||
match totals.iter_mut().find(|(x, _)| x == s) {
|
||||
Some(e) => e.1 += n,
|
||||
None => totals.push((*s, n)),
|
||||
}
|
||||
}
|
||||
let mut best: Option<(usize, usize)> = None;
|
||||
for &(s, n) in &totals {
|
||||
if best.is_none_or(|(_, b)| n > b) {
|
||||
best = Some((s, n));
|
||||
}
|
||||
}
|
||||
(best.map_or(0, |(s, _)| s), totals.iter().filter(|(_, n)| *n > 0).count() > 1)
|
||||
}
|
||||
|
||||
/// Lays out one text field. Fonts are looked up once per face name (`faces`); missing ones go
|
||||
/// into the report.
|
||||
pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap<String, FaceMatch>, report: &mut Report) -> Vec<Placed> {
|
||||
let Some(field) = craft_xfl::text::TextField::new(el) else { return Vec::new() };
|
||||
if field.orientation().is_some_and(|o| o != "horizontal") {
|
||||
report.skip("vertical text (drawn horizontal)");
|
||||
}
|
||||
if field.has_filters() {
|
||||
report.skip("filters on text");
|
||||
}
|
||||
let mut flags = Flags::default();
|
||||
let mut styles: Vec<RunStyle> = Vec::new();
|
||||
let mut lines: Vec<Line> = vec![Vec::new()];
|
||||
/// Reads a field's runs. Fonts are looked up once per face name (`faces`); missing ones go into
|
||||
/// the report.
|
||||
fn read_runs(el: &X, native: &craft_xfl::text::TextField<'_, X>, fonts: &Fonts, faces: &mut HashMap<String, FaceMatch>, report: &mut Report, flags: &mut Flags) -> Styled {
|
||||
// Links aren't in the shared schema view: read them from the runs' attributes directly.
|
||||
let urls: Vec<String> = el.list("textRuns").iter().filter(|r| r.name == "DOMTextRun").map(|r| r.child("textAttrs").and_then(|t| t.child("DOMTextAttrs")).and_then(|a| a.attr("url")).unwrap_or("").to_string()).collect();
|
||||
let mut text = String::new();
|
||||
let mut runs: Vec<TextRun> = Vec::new();
|
||||
let mut para_of_run: Vec<ParagraphStyle> = Vec::new();
|
||||
let mut chars = 0usize;
|
||||
let mut cut = field.run_entries_count() > MAX_RUNS;
|
||||
for run in field.runs().take(MAX_RUNS) {
|
||||
let style = run_style(run.style(), &mut flags);
|
||||
let s = match styles.iter().position(|x| *x == style) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
styles.push(style);
|
||||
styles.len() - 1
|
||||
}
|
||||
};
|
||||
let text = run.characters();
|
||||
// Animate ends lines with a carriage return; any line break starts a new line here.
|
||||
let text = text.replace("\r\n", "\n").replace(['\r', '\u{2028}', '\u{2029}'], "\n");
|
||||
for (i, piece) in text.split('\n').enumerate() {
|
||||
if i > 0 {
|
||||
lines.push(Vec::new());
|
||||
chars += 1;
|
||||
}
|
||||
let room = anicraft_text::MAX_CHARS.saturating_sub(chars);
|
||||
let n = piece.chars().count();
|
||||
if n > room {
|
||||
cut = true;
|
||||
}
|
||||
let piece: String = piece.chars().take(room).collect();
|
||||
chars += n.min(room);
|
||||
if let Some(l) = lines.last_mut() {
|
||||
l.push((piece, s));
|
||||
}
|
||||
let mut missing: Vec<String> = Vec::new();
|
||||
let mut cut = native.run_entries_count() > MAX_RUNS;
|
||||
for (i, run) in native.runs().take(MAX_RUNS).enumerate() {
|
||||
let (mut c, p) = run_style(run.style(), urls.get(i).map_or("", String::as_str), flags);
|
||||
// The face: a PostScript name, a family or a device font; bold and italic faces count.
|
||||
let face = faces.entry(c.font.clone()).or_insert_with(|| fonts.find_face(&c.font)).clone();
|
||||
if face.family.is_none() && !face.wanted.is_empty() && !missing.contains(&face.wanted) {
|
||||
missing.push(face.wanted.clone());
|
||||
}
|
||||
c.font = face.family.clone().unwrap_or_default();
|
||||
c.bold |= face.bold;
|
||||
c.italic |= face.italic;
|
||||
// Animate ends lines with a carriage return; any line break starts a new line here.
|
||||
let piece = run.characters().replace("\r\n", "\n").replace(['\r', '\u{2028}', '\u{2029}'], "\n");
|
||||
let room = anicraft_text::MAX_CHARS.saturating_sub(chars);
|
||||
let n = piece.chars().count();
|
||||
if n > room {
|
||||
cut = true;
|
||||
}
|
||||
let piece: String = piece.chars().take(room).collect();
|
||||
let n = n.min(room);
|
||||
chars += n;
|
||||
text.push_str(&piece);
|
||||
runs.push(TextRun { chars: n as u32, style: c });
|
||||
para_of_run.push(p);
|
||||
if chars >= anicraft_text::MAX_CHARS {
|
||||
break;
|
||||
}
|
||||
@@ -179,132 +134,124 @@ pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap<String, FaceMatch>, repo
|
||||
if cut {
|
||||
report.skip("text cut to 100,000 characters per field");
|
||||
}
|
||||
if field.kind() != craft_xfl::text::TextFieldKind::Static {
|
||||
flags.report(report);
|
||||
return text_field(field, fonts, faces, report, &lines, &styles).into_iter().collect();
|
||||
// Each paragraph takes the paragraph attributes of the run its first character is in.
|
||||
let mut paragraphs = Vec::new();
|
||||
let mut starts = vec![0usize];
|
||||
starts.extend(text.chars().enumerate().filter(|(_, c)| *c == '\n').map(|(i, _)| i + 1));
|
||||
let mut ends: Vec<usize> = Vec::with_capacity(runs.len());
|
||||
let mut at = 0usize;
|
||||
for r in &runs {
|
||||
at += r.chars as usize;
|
||||
ends.push(at);
|
||||
}
|
||||
// Trailing empty lines draw nothing.
|
||||
while lines.last().is_some_and(|l| l.iter().all(|(t, _)| t.trim().is_empty())) {
|
||||
lines.pop();
|
||||
for s in starts {
|
||||
let k = ends.partition_point(|e| *e <= s).min(para_of_run.len().saturating_sub(1));
|
||||
paragraphs.push(para_of_run.get(k).copied().unwrap_or_default());
|
||||
}
|
||||
if lines.is_empty() || styles.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
flags.report(report);
|
||||
|
||||
// Consecutive lines in the same style make one block.
|
||||
let mut blocks: Vec<(usize, String)> = Vec::new();
|
||||
for line in &lines {
|
||||
let (s, mixed) = main_style(line);
|
||||
if mixed {
|
||||
report.skip("lines with mixed text styles (drawn in their main style)");
|
||||
}
|
||||
let text: String = line.iter().map(|(t, _)| t.as_str()).collect();
|
||||
match blocks.last_mut() {
|
||||
Some((ls, t)) if *ls == s => {
|
||||
t.push('\n');
|
||||
t.push_str(&text);
|
||||
}
|
||||
_ => blocks.push((s, text)),
|
||||
}
|
||||
}
|
||||
|
||||
let auto = field.auto_expand().unwrap_or(false);
|
||||
let field_width = field.width().filter(|w| *w > 0.0).map(|w| w.min(100_000.0));
|
||||
let origin = Vec2::new(field.left().unwrap_or(0.0) + GUTTER, field.top().unwrap_or(0.0) + GUTTER);
|
||||
let mut out: Vec<Placed> = Vec::new();
|
||||
let mut y = 0.0f32;
|
||||
for (s, text) in blocks {
|
||||
let Some(st) = styles.get(s) else { continue };
|
||||
let face = faces.entry(st.face.clone()).or_insert_with(|| fonts.find_face(&st.face)).clone();
|
||||
// A fixed-width field wraps inside its margins; an auto-size one never wraps.
|
||||
let width = if auto { None } else { field_width.map(|w| (w - st.left_margin - st.right_margin).max(1.0)) };
|
||||
let style = anicraft_text::Style {
|
||||
family: face.family.clone().unwrap_or_default(),
|
||||
size: st.size,
|
||||
bold: st.bold || face.bold,
|
||||
italic: st.italic || face.italic,
|
||||
align: match st.align {
|
||||
TextAlign::Left => Align::Left,
|
||||
TextAlign::Center => Align::Center,
|
||||
TextAlign::Right => Align::Right,
|
||||
},
|
||||
letter_spacing: st.letter_spacing,
|
||||
line_spacing: st.line_spacing,
|
||||
width,
|
||||
};
|
||||
let layout = match fonts.layout(&text, &style) {
|
||||
Ok(l) => l,
|
||||
Err(TextError::NoFonts) => {
|
||||
report.skip("text fields (no fonts on this computer)");
|
||||
return Vec::new();
|
||||
}
|
||||
Err(TextError::TooLong) => {
|
||||
report.skip("text cut to 100,000 characters per field");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
// A family that isn't installed falls back to the default, as the text engine does
|
||||
// (ADR 0012), and the report names it.
|
||||
if face.family.is_none() && !face.wanted.is_empty() {
|
||||
report.missing_fonts.insert(face.wanted.clone());
|
||||
report.fallback_font.get_or_insert_with(|| layout.family.clone());
|
||||
}
|
||||
let block = TextBlock {
|
||||
text,
|
||||
font: layout.family,
|
||||
size: style.size,
|
||||
bold: style.bold,
|
||||
italic: style.italic,
|
||||
color: st.color,
|
||||
align: st.align,
|
||||
letter_spacing: st.letter_spacing,
|
||||
line_spacing: st.line_spacing,
|
||||
width,
|
||||
outline: Arc::new(layout.outline),
|
||||
box_width: layout.width,
|
||||
box_height: layout.height,
|
||||
field: None,
|
||||
on_path: None,
|
||||
};
|
||||
out.push(Placed { block, offset: Vec2::new(origin.x + st.left_margin, origin.y + y) });
|
||||
y += layout.lines as f32 * layout.line_height;
|
||||
}
|
||||
// Auto-size blocks align against the widest one, as lines of one field do.
|
||||
if auto {
|
||||
let widest = out.iter().map(|p| p.block.box_width).fold(0.0, f32::max);
|
||||
for p in &mut out {
|
||||
p.offset.x += match p.block.align {
|
||||
TextAlign::Left => 0.0,
|
||||
TextAlign::Center => (widest - p.block.box_width) * 0.5,
|
||||
TextAlign::Right => widest - p.block.box_width,
|
||||
};
|
||||
}
|
||||
}
|
||||
out
|
||||
Styled { text, runs, paragraphs, missing }
|
||||
}
|
||||
|
||||
/// A dynamic or input field (ADR 0066): one block in the field's main style, its box from the
|
||||
/// Lays a block out from its text, runs, paragraphs and width (the engine's text layout does
|
||||
/// the same for edits; the importer sits below it, so this is its own copy of the few lines
|
||||
/// that hand runs to the text engine).
|
||||
fn lay_out(fonts: &Fonts, block: &mut TextBlock, shown: &str, wrap: Option<f32>) -> Result<anicraft_text::Layout, TextError> {
|
||||
let mut paints: Vec<(Rgba, String)> = Vec::new();
|
||||
let align = |a: TextAlign| match a {
|
||||
TextAlign::Left => Align::Left,
|
||||
TextAlign::Center => Align::Center,
|
||||
TextAlign::Right => Align::Right,
|
||||
};
|
||||
let runs: Vec<anicraft_text::Run> = block
|
||||
.styled_runs()
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let key = (r.style.color, r.style.url.clone());
|
||||
let paint = paints.iter().position(|k| *k == key).unwrap_or_else(|| {
|
||||
paints.push(key);
|
||||
paints.len() - 1
|
||||
}) as u32;
|
||||
let shift = match r.style.shift {
|
||||
BaselineShift::Normal => anicraft_text::Shift::Normal,
|
||||
BaselineShift::Superscript => anicraft_text::Shift::Superscript,
|
||||
BaselineShift::Subscript => anicraft_text::Shift::Subscript,
|
||||
};
|
||||
anicraft_text::Run { chars: r.chars as usize, style: anicraft_text::RunStyle { family: r.style.font, size: r.style.size, bold: r.style.bold, italic: r.style.italic, letter_spacing: r.style.letter_spacing, shift, underline: r.style.underline, paint } }
|
||||
})
|
||||
.collect();
|
||||
let paras: Vec<anicraft_text::ParaStyle> = block.paragraph_styles().into_iter().map(|p| anicraft_text::ParaStyle { align: align(p.align), indent: p.indent, left_margin: p.left_margin, right_margin: p.right_margin, line_spacing: p.line_spacing }).collect();
|
||||
let l = fonts.layout_rich(&anicraft_text::RichText { text: shown, runs: &runs, paragraphs: ¶s, width: wrap }, false)?;
|
||||
// The runs record the families actually used.
|
||||
let mut styled = block.styled_runs();
|
||||
for (r, used) in styled.iter_mut().zip(&l.families) {
|
||||
r.style.font.clone_from(used);
|
||||
}
|
||||
let p = block.paragraph_styles();
|
||||
block.set_styles(styled, p);
|
||||
let pieces = l.pieces.iter().map(|(k, p)| paints.get(*k as usize).map_or((block.color, String::new(), p.clone()), |(c, u)| (*c, u.clone(), p.clone()))).collect();
|
||||
block.set_outline(pieces);
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
/// Lays out one text field: one block with the field's runs.
|
||||
pub fn field(el: &X, fonts: &Fonts, faces: &mut HashMap<String, FaceMatch>, report: &mut Report) -> Vec<Placed> {
|
||||
let Some(native) = craft_xfl::text::TextField::new(el) else { return Vec::new() };
|
||||
if native.orientation().is_some_and(|o| o != "horizontal") {
|
||||
report.skip("vertical text (drawn horizontal)");
|
||||
}
|
||||
if native.has_filters() {
|
||||
report.skip("filters on text");
|
||||
}
|
||||
let mut flags = Flags::default();
|
||||
let styled = read_runs(el, &native, fonts, faces, report, &mut flags);
|
||||
if flags.justified {
|
||||
report.skip("justified text (drawn left-aligned)");
|
||||
}
|
||||
if native.kind() != craft_xfl::text::TextFieldKind::Static {
|
||||
return text_field(native, fonts, report, styled).into_iter().collect();
|
||||
}
|
||||
// Trailing empty lines draw nothing.
|
||||
let keep = styled.text.trim_end().chars().count();
|
||||
if keep == 0 || styled.runs.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let text: String = styled.text.chars().take(keep).collect();
|
||||
let auto = native.auto_expand().unwrap_or(false);
|
||||
// A fixed-width field wraps inside its margins; an auto-size one never wraps.
|
||||
let width = if auto { None } else { native.width().filter(|w| *w > 0.0).map(|w| w.min(100_000.0)) };
|
||||
let mut block = TextBlock { text: text.clone(), width, ..TextBlock::default() };
|
||||
block.set_styles(styled.runs, styled.paragraphs);
|
||||
match lay_out(fonts, &mut block, &text, width) {
|
||||
Ok(l) => {
|
||||
// A family that isn't installed falls back to the default, as the text engine does
|
||||
// (ADR 0012), and the report names it.
|
||||
report.missing_fonts.extend(styled.missing);
|
||||
if !report.missing_fonts.is_empty() {
|
||||
report.fallback_font.get_or_insert_with(|| l.family.clone());
|
||||
}
|
||||
block.box_width = l.width;
|
||||
block.box_height = l.height;
|
||||
}
|
||||
Err(TextError::NoFonts) => {
|
||||
report.skip("text fields (no fonts on this computer)");
|
||||
return Vec::new();
|
||||
}
|
||||
Err(TextError::TooLong) => {
|
||||
report.skip("text cut to 100,000 characters per field");
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
let origin = Vec2::new(native.left().unwrap_or(0.0) + GUTTER, native.top().unwrap_or(0.0) + GUTTER);
|
||||
vec![Placed { block, offset: origin }]
|
||||
}
|
||||
|
||||
/// A dynamic or input field (ADR 0066): one block with the field's runs, its box from the
|
||||
/// field's `width` and `height` (or the text's size, for an auto-size field), its text laid out
|
||||
/// inside the gutter. Empty fields are kept (an empty input field is the usual kind).
|
||||
fn text_field(
|
||||
native: craft_xfl::text::TextField<'_, X>,
|
||||
fonts: &Fonts,
|
||||
faces: &mut HashMap<String, FaceMatch>,
|
||||
report: &mut Report,
|
||||
lines: &[Line],
|
||||
styles: &[RunStyle],
|
||||
) -> Option<Placed> {
|
||||
fn text_field(native: craft_xfl::text::TextField<'_, X>, fonts: &Fonts, report: &mut Report, styled: Styled) -> Option<Placed> {
|
||||
let kind = if native.kind() == craft_xfl::text::TextFieldKind::Input { TextKind::Input } else { TextKind::Dynamic };
|
||||
report.run(if kind == TextKind::Input { "input text fields" } else { "dynamic text fields" });
|
||||
let all: Line = lines.iter().flatten().cloned().collect();
|
||||
let (s, mixed) = main_style(&all);
|
||||
if mixed {
|
||||
report.skip("text fields with mixed text styles (drawn in their main style)");
|
||||
}
|
||||
let st = styles.get(s).cloned().unwrap_or_else(|| run_style(None, &mut Flags::default()));
|
||||
let text: String = lines.iter().map(|l| l.iter().map(|(t, _)| t.as_str()).collect::<String>()).collect::<Vec<_>>().join("\n");
|
||||
let text = text.trim_end_matches('\n').to_string();
|
||||
let keep = styled.text.trim_end_matches('\n').chars().count();
|
||||
let text: String = styled.text.chars().take(keep).collect();
|
||||
let line_type = match native.line_type() {
|
||||
Some("multiline") => LineType::Multiline,
|
||||
Some("multiline no wrap") => LineType::MultilineNoWrap,
|
||||
@@ -324,59 +271,37 @@ fn text_field(
|
||||
let field = TextField { lines: line_type, selectable: native.is_selectable().unwrap_or(true), border, background: border, max_chars, variable, ..TextField::new(kind) };
|
||||
let auto = native.auto_expand().unwrap_or(false);
|
||||
let width = native.width().filter(|w| *w > 0.0).map(|w| w.min(100_000.0));
|
||||
let face = faces.entry(st.face.clone()).or_insert_with(|| fonts.find_face(&st.face)).clone();
|
||||
let wrap = width.and_then(|w| field.wrap_width(w - st.left_margin - st.right_margin));
|
||||
let style = anicraft_text::Style {
|
||||
family: face.family.clone().unwrap_or_default(),
|
||||
size: st.size,
|
||||
bold: st.bold || face.bold,
|
||||
italic: st.italic || face.italic,
|
||||
align: match st.align {
|
||||
TextAlign::Left => Align::Left,
|
||||
TextAlign::Center => Align::Center,
|
||||
TextAlign::Right => Align::Right,
|
||||
},
|
||||
letter_spacing: st.letter_spacing,
|
||||
line_spacing: st.line_spacing,
|
||||
width: wrap.or(if auto { None } else { width.map(|w| (w - 2.0 * GUTTER - st.left_margin - st.right_margin).max(1.0)).filter(|_| st.align != TextAlign::Left) }),
|
||||
};
|
||||
let mut block = TextBlock { text: text.clone(), ..TextBlock::default() };
|
||||
block.set_styles(styled.runs, styled.paragraphs);
|
||||
let missing = styled.missing;
|
||||
let wrap = width.and_then(|w| field.wrap_width(w));
|
||||
// A fixed box that doesn't wrap still aligns its lines in the box.
|
||||
let lay_width = wrap.or(if auto { None } else { width.map(|w| (w - 2.0 * GUTTER).max(1.0)).filter(|_| block.align != TextAlign::Left) });
|
||||
let shown = field.shown(&text);
|
||||
let (outline, family, tw, th) = match fonts.layout(&shown, &style) {
|
||||
let (tw, th) = match lay_out(fonts, &mut block, &shown, lay_width) {
|
||||
Ok(l) => {
|
||||
if face.family.is_none() && !face.wanted.is_empty() {
|
||||
report.missing_fonts.insert(face.wanted.clone());
|
||||
report.missing_fonts.extend(missing);
|
||||
if !report.missing_fonts.is_empty() {
|
||||
report.fallback_font.get_or_insert_with(|| l.family.clone());
|
||||
}
|
||||
let moved = l.outline.transformed(&anicraft_geom::Affine::translate(GUTTER + st.left_margin, GUTTER));
|
||||
(moved, l.family, l.width, l.height)
|
||||
let to = Affine::translate(GUTTER, GUTTER);
|
||||
let pieces: Vec<(Rgba, String, Path)> = block.fill_paths().into_iter().map(|(c, u, p)| (c, u.to_string(), p.transformed(&to))).collect();
|
||||
block.set_outline(pieces);
|
||||
(l.width, l.height)
|
||||
}
|
||||
Err(e) => {
|
||||
report.skip(if e == TextError::NoFonts { "text fields (no fonts on this computer)" } else { "text cut to 100,000 characters per field" });
|
||||
(anicraft_geom::Path::new(), face.wanted.clone(), 0.0, st.size * 1.2)
|
||||
block.outline = Arc::new(Path::new());
|
||||
(0.0, block.size * 1.2)
|
||||
}
|
||||
};
|
||||
let box_width = match (width, auto) {
|
||||
block.box_width = match (width, auto) {
|
||||
(Some(w), false) => w,
|
||||
(Some(w), true) => w.max(tw + 2.0 * GUTTER),
|
||||
(None, _) => tw + 2.0 * GUTTER,
|
||||
};
|
||||
let box_height = native.height().filter(|h| *h > 0.0).map_or(th + 2.0 * GUTTER, |h| h.min(100_000.0));
|
||||
let block = TextBlock {
|
||||
text,
|
||||
font: family,
|
||||
size: style.size,
|
||||
bold: style.bold,
|
||||
italic: style.italic,
|
||||
color: st.color,
|
||||
align: st.align,
|
||||
letter_spacing: st.letter_spacing,
|
||||
line_spacing: st.line_spacing,
|
||||
width: wrap,
|
||||
outline: Arc::new(outline),
|
||||
box_width,
|
||||
box_height,
|
||||
field: Some(field),
|
||||
on_path: None,
|
||||
};
|
||||
block.box_height = native.height().filter(|h| *h > 0.0).map_or(th + 2.0 * GUTTER, |h| h.min(100_000.0));
|
||||
block.width = wrap;
|
||||
block.field = Some(field);
|
||||
Some(Placed { block, offset: Vec2::new(native.left().unwrap_or(0.0), native.top().unwrap_or(0.0)) })
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::import::{Report, XflError, import_with, import_with_fonts};
|
||||
use crate::text::GUTTER;
|
||||
use anicraft_doc::{Document, Element, ElementKind, LineType, Paint, Rgba, TextAlign, TextBlock, TextKind, evaluate};
|
||||
use anicraft_doc::{BaselineShift, Document, Element, ElementKind, LineType, Paint, Rgba, TextAlign, TextBlock, TextKind, evaluate};
|
||||
use anicraft_text::Fonts;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -75,38 +75,61 @@ fn fixed_width_fields_wrap_and_auto_size_ones_do_not() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_in_different_styles_become_blocks_stacked_line_by_line() {
|
||||
fn runs_keep_their_styles_in_one_block() {
|
||||
let Some((fonts, family)) = fonts() else { return };
|
||||
let title = format!(r##"face="{family}" size="30" bold="true" fillColor="#112233""##);
|
||||
let body = format!(r##"face="{family}" size="12" fillColor="#445566""##);
|
||||
// A title line, two body lines (the second continues in a separate run of the same style),
|
||||
// then a line that mixes both styles: most of its characters are body text.
|
||||
let runs = [run("Title
", &title), run("line one
line ", &body), run("two
", &body), run("Big", &title), run(" and mostly small", &body), run("

", &body)].concat();
|
||||
let title = format!(r##"face="{family}" size="30" bold="true" fillColor="#112233" alignment="center""##);
|
||||
let body = format!(r##"face="{family}" size="12" fillColor="#445566" indent="8" leftMargin="4""##);
|
||||
let sup = format!(r##"face="{family}" size="12" fillColor="#445566" characterPosition="superscript" url="https://example.org""##);
|
||||
// A title line, body lines (the second continues in a separate run of the same style), a
|
||||
// line that mixes both styles and a superscript, then trailing empty lines.
|
||||
let runs = [run("Title
", &title), run("line one
line ", &body), run("two
", &body), run("Big", &title), run(" and small", &body), run("2", &sup), run("

", &body)].concat();
|
||||
let field = format!(r#"<DOMStaticText autoExpand="true"><matrix><Matrix tx="10" ty="20"/></matrix><textRuns>{runs}</textRuns></DOMStaticText>"#);
|
||||
let (doc, report) = import_doc(&doc_with(&field), fonts);
|
||||
let t = texts(&doc);
|
||||
let blocks: Vec<(&str, f32, bool)> = t.iter().map(|(_, b)| (b.text.as_str(), b.size, b.bold)).collect();
|
||||
assert_eq!(blocks, [("Title", 30.0, true), ("line one\nline two\nBig and mostly small", 12.0, false)], "trailing empty lines are dropped");
|
||||
assert_eq!(t[1].1.color, Rgba::hex(0x445566));
|
||||
// The body starts where the title's next line would.
|
||||
let title_layout = fonts.layout("Title", &anicraft_text::Style { family: family.clone(), size: 30.0, bold: true, ..Default::default() }).unwrap();
|
||||
let (y0, y1) = (t[0].0.transform.translation().y, t[1].0.transform.translation().y);
|
||||
assert!((y0 - (20.0 + GUTTER)).abs() < 1e-4);
|
||||
assert!((y1 - y0 - title_layout.line_height).abs() < 1e-3, "{y0} → {y1}, line height {}", title_layout.line_height);
|
||||
assert_eq!(t[0].0.transform.translation().x, t[1].0.transform.translation().x, "left-aligned blocks share the left edge");
|
||||
assert_eq!(report.skipped.get("lines with mixed text styles (drawn in their main style)"), Some(&1));
|
||||
assert_eq!(t.len(), 1, "one field, one block");
|
||||
let b = &t[0].1;
|
||||
assert_eq!(b.text, "Title\nline one\nline two\nBig and small2", "trailing empty lines are dropped");
|
||||
let runs: Vec<(u32, f32, bool, BaselineShift)> = b.styled_runs().iter().map(|r| (r.chars, r.style.size, r.style.bold, r.style.shift)).collect();
|
||||
assert_eq!(runs, [(6, 30.0, true, BaselineShift::Normal), (18, 12.0, false, BaselineShift::Normal), (3, 30.0, true, BaselineShift::Normal), (10, 12.0, false, BaselineShift::Normal), (1, 12.0, false, BaselineShift::Superscript)]);
|
||||
assert_eq!(b.styled_runs()[1].style.color, Rgba::hex(0x445566));
|
||||
assert_eq!(b.styled_runs()[4].style.url, "https://example.org");
|
||||
// Paragraphs take their layout from the run they start in.
|
||||
let aligns: Vec<TextAlign> = b.paragraph_styles().iter().map(|p| p.align).collect();
|
||||
assert_eq!(aligns, [TextAlign::Center, TextAlign::Left, TextAlign::Left, TextAlign::Center]);
|
||||
assert_eq!((b.paragraph_styles()[1].indent, b.paragraph_styles()[1].left_margin), (8.0, 4.0));
|
||||
// Colours become fill pieces; the element sits at the field's matrix plus the gutter.
|
||||
assert_eq!(b.fills.len(), 3, "two colours, one with a link");
|
||||
assert!((t[0].0.transform.translation().y - (20.0 + GUTTER)).abs() < 1e-4);
|
||||
assert!(report.skipped.is_empty(), "{report:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn centred_auto_size_blocks_centre_on_each_other() {
|
||||
fn xfl_runs_round_trip_through_the_file() {
|
||||
let Some((fonts, family)) = fonts() else { return };
|
||||
let a = format!(r##"face="{family}" size="20" fillColor="#ff0000""##);
|
||||
let b = format!(r##"face="{family}" size="10" italic="true" characterPosition="subscript""##);
|
||||
let field = format!(r#"<DOMStaticText><textRuns>{}{}</textRuns></DOMStaticText>"#, run("H", &a), run("2O", &b));
|
||||
let (doc, _) = import_doc(&doc_with(&field), fonts);
|
||||
let json = serde_json::to_string(&doc).unwrap();
|
||||
let back: Document = serde_json::from_str(&json).unwrap();
|
||||
let (x, y) = (texts(&doc), texts(&back));
|
||||
assert_eq!((&x[0].1.runs, &x[0].1.fills, &x[0].1.outline), (&y[0].1.runs, &y[0].1.fills, &y[0].1.outline));
|
||||
assert_eq!(y[0].1.runs.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn centred_lines_centre_on_each_other() {
|
||||
let Some((fonts, family)) = fonts() else { return };
|
||||
let a = format!(r#"face="{family}" size="40" alignment="center""#);
|
||||
let b = format!(r#"face="{family}" size="12" alignment="center""#);
|
||||
let field = format!(r#"<DOMStaticText autoExpand="true"><textRuns>{}{}</textRuns></DOMStaticText>"#, run("WIDE HEADLINE
", &a), run("small", &b));
|
||||
let (doc, _) = import_doc(&doc_with(&field), fonts);
|
||||
let t = texts(&doc);
|
||||
let centre = |i: usize| t[i].0.transform.translation().x + t[i].1.box_width * 0.5;
|
||||
assert!((centre(0) - centre(1)).abs() < 0.01, "{} vs {}", centre(0), centre(1));
|
||||
let b = &t[0].1;
|
||||
let (head, small) = (b.fill_paths()[0].2.bounds(), b.outline.bounds());
|
||||
// The block is as wide as the headline, and the small line sits in its middle.
|
||||
assert!((head.center().x - b.box_width * 0.5).abs() < 2.0, "{head:?} in {}", b.box_width);
|
||||
assert!((small.center().x - b.box_width * 0.5).abs() < 2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -120,7 +143,7 @@ fn missing_fonts_fall_back_and_are_reported() {
|
||||
);
|
||||
let (doc, report) = import_doc(&doc_with(&field), fonts);
|
||||
let t = texts(&doc);
|
||||
assert_eq!(t.len(), 3);
|
||||
assert_eq!(t.len(), 2, "one block per field");
|
||||
assert_eq!((t[0].1.bold, t[0].1.italic), (true, true), "the face name says bold italic");
|
||||
assert!(fonts.families().contains(&t[0].1.font), "laid out in an installed family: {}", t[0].1.font);
|
||||
assert_eq!(report.missing_fonts.iter().map(String::as_str).collect::<Vec<_>>(), ["No Such Face", "Zz Missing Mono"]);
|
||||
@@ -157,10 +180,13 @@ fn dynamic_and_input_text_become_fields_with_their_names() {
|
||||
assert_eq!(report.runs.get("dynamic text fields"), Some(&1));
|
||||
assert_eq!(report.runs.get("input text fields"), Some(&2));
|
||||
assert_eq!(report.kept.get("text field variables (ActionScript 1.0 and 2.0)"), Some(&1));
|
||||
for (what, n) in [("justified text (drawn left-aligned)", 1), ("vertical text (drawn horizontal)", 1), ("first-line indents", 1), ("superscript and subscript (drawn on the line)", 1)] {
|
||||
for (what, n) in [("justified text (drawn left-aligned)", 1), ("vertical text (drawn horizontal)", 1)] {
|
||||
assert_eq!(report.skipped.get(what), Some(&n), "{what}: {report:?}");
|
||||
}
|
||||
assert!(report.missing_fonts.is_empty(), "no face asks for the default family");
|
||||
// Indents and superscripts are kept now (ADR 0085).
|
||||
let st = &t[3].1;
|
||||
assert_eq!((st.indent, st.shift), (5.0, anicraft_doc::BaselineShift::Superscript));
|
||||
// Every non-interactive render draws the authored text in its box, with its border.
|
||||
let dl = evaluate(&doc, 0);
|
||||
assert!(dl.items.iter().any(|i| i.stroke.is_some()), "the border");
|
||||
|
||||
@@ -444,7 +444,9 @@ fn text_fields_become_blocks_with_this_computers_fonts() {
|
||||
.iter()
|
||||
.filter_map(|e| if let ElementKind::Text(t) = &e.kind { Some((e.name.clone(), t.text.clone(), t.size, t.bold)) } else { None })
|
||||
.collect();
|
||||
let want = [("", "Corpus", 28.0, true), ("", "self-authored, line two", 12.0, false), ("", "A fixed-width field wraps its words onto lines.", 11.0, false), ("score", "Score 0042", 18.0, false), ("answer", "type here", 14.0, false)];
|
||||
// One block per field, its runs kept (ADR 0085): the title's style is the block's first.
|
||||
let want = [("", "Corpus
|
||||
self-authored, line two", 28.0, true), ("", "A fixed-width field wraps its words onto lines.", 11.0, false), ("score", "Score 0042", 18.0, false), ("answer", "type here", 14.0, false)];
|
||||
assert_eq!(blocks.iter().map(|(n, t, s, b)| (n.as_str(), t.as_str(), *s, *b)).collect::<Vec<_>>(), want);
|
||||
assert_eq!(report.runs.get("dynamic text fields"), Some(&1), "fields run in Test Movie (ADR 0066)");
|
||||
assert!(!report.skipped.contains_key("text fields (no fonts on this computer)"));
|
||||
|
||||
@@ -105,7 +105,7 @@ keeping `evaluate` pure and drawing the same shape everywhere.
|
||||
|
||||
## Not yet
|
||||
|
||||
* Instances and shapes in one armature; more than one shape per armature; reshaping the
|
||||
* ~~Instances and shapes in one armature; more than one shape per armature~~ (ADR 0098); reshaping the
|
||||
outline after binding (Animate allows Subselection edits on the rest pose).
|
||||
* Dragging points onto a bone with the Bind tool (only clicks and boxes for now), painting
|
||||
weights, and a falloff setting.
|
||||
|
||||
@@ -103,7 +103,7 @@ tool allowed to drag from a shape's bone end onto an instance. It is its own ADR
|
||||
|
||||
## Not yet
|
||||
|
||||
* Instances and shapes in one armature (above); gravity, wind and per-armature spring presets;
|
||||
* ~~Instances and shapes in one armature (above)~~ (ADR 0098); gravity, wind and per-armature spring presets;
|
||||
springs on the root's own motion of a shape armature's outline points (only bones swing).
|
||||
* An IK drag that slides joints by preference rather than only to reach; translation limits
|
||||
drawn on the stage.
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
# ADR 0085: Per-character and paragraph styles in text
|
||||
|
||||
* Status: accepted (2026-11-16), first slice built
|
||||
* Relates to: ADR 0012 (text), ADR 0014 (text from Animate documents), ADR 0066 (dynamic and
|
||||
input fields), ADR 0070 (text on a path), ADR 0004 (destructive actions), roadmap M5
|
||||
|
||||
## Context
|
||||
|
||||
ADR 0012 gave a text block one style. Animate's static text mixes styles freely: a bold word, a
|
||||
coloured name, a superscript in "mc²", a centred title above left-aligned body text. Animate
|
||||
documents store this as `DOMTextRun`s, each with its own `DOMTextAttrs`, and our XFL import split
|
||||
such a field into one block per style, losing anything mixed within a line. The constraints of
|
||||
ADR 0012 still hold: rendering and every export use only stored outlines (no fonts at render
|
||||
time), `evaluate` stays pure, older files must open and save unchanged.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Runs and paragraphs on the block.** `TextBlock` gains `runs: Vec<TextRun>` (a character
|
||||
count and a `CharStyle`: font, size, bold, italic, colour, letter spacing, baseline shift,
|
||||
underline, link) and `paragraphs: Vec<ParagraphStyle>` (alignment, first-line indent, left
|
||||
and right margins, line spacing), both `#[serde(default, skip_serializing_if = "Vec::is_empty")]`.
|
||||
**Empty means "all in the block's own style"**, so every older file opens unchanged and a
|
||||
block whose characters share one style saves byte for byte as before (a test pins the JSON).
|
||||
When there are runs, the block's own style fields mirror the first run and first paragraph,
|
||||
so code that asks "the block's style" (the player laying out a script's text, Find, exports
|
||||
of fields) keeps working. `TextBlock::set_styles` is the one way to set them: it fits runs to
|
||||
the text, joins neighbours in one style, caps them at 10,000 (`MAX_TEXT_RUNS`; the rest takes
|
||||
the last style), sanitizes values, and drops runs and paragraphs that add nothing.
|
||||
2. **Run edits are pure functions** in `anicraft_doc::rich_text` (`type_into_runs`,
|
||||
`replace_runs`, `restyle_runs`, `slice_runs`, `edit_paragraphs`, `summarize`, `diff_chars`),
|
||||
shared by the engine, the shell and the tests. **Typing continues the style of the character
|
||||
before the caret** (the first character's at the start), as Animate and word processors do. A
|
||||
line break splits a paragraph into two with its style; joining keeps the first's. A change of
|
||||
text given as a whole (`text.edit {text}`, Find and Replace) is taken as one edit: the longest
|
||||
common start and end are kept and the middle replaced.
|
||||
3. **Layout per run** in `anicraft-text` (`Fonts::layout_rich`): each stretch of a paragraph in
|
||||
one run is shaped on its own with `harfrust` in its own face (faces read once per layout,
|
||||
glyph outlines cached per face, glyph and size), lines break greedily at spaces across runs,
|
||||
a line makes room for its tallest run, and paragraphs are aligned, indented and narrowed by
|
||||
their margins. **One run in one paragraph lays out exactly as before**: the old layout's
|
||||
outline, box, lines, carets and glyphs were compared bit for bit on 288 inputs (sizes,
|
||||
spacing, widths, alignments, line breaks, ligatures) before the old code was removed.
|
||||
Kerning across a run boundary is not applied (each run is shaped alone).
|
||||
4. **Superscript and subscript use the font's own OS/2 metrics** (`ySuperscriptYSize`,
|
||||
`ySuperscriptYOffset`, and the subscript pair, per the OpenType specification), falling back
|
||||
to 0.65 em raised 0.35 em (lowered 0.15 em) when a font leaves them out. The glyphs are drawn
|
||||
smaller and shifted; the line keeps the run's full-size height so a superscript doesn't push
|
||||
lines apart. Underlines use the font's `post` underline position and thickness.
|
||||
5. **Colour pieces without duplicating outlines.** The outline is still one path, now laid out
|
||||
as one piece per paint (colour and link) one after another; `fills: Vec<TextFill>` records each
|
||||
piece's colour, link and command count. `evaluate` emits one display item per piece; the
|
||||
pieces are cut from the outline once and cached in memory (never saved, invalidated on copy
|
||||
or when the outline changes), so a frame costs what it did. A single piece in the block's
|
||||
colour keeps no fills (files unchanged). Every renderer and export (CPU oracle, GPU stage,
|
||||
PNG, GIF, video, SVG, Lottie, HTML canvas, sprite sheets) therefore draws each colour with no
|
||||
change. Break Apart gives one shape per colour.
|
||||
6. **Links.** A run's `url` is kept (unsafe schemes — `javascript:`, `vbscript:`, `data:` — are
|
||||
refused by the commands and dropped on import). The display list carries a sparse
|
||||
`links: Vec<(item, url)>`; SVG export wraps those items in `<a href>`. We chose outlines with
|
||||
links over SVG `<text>`/`<tspan>` output: tspans would make the SVG depend on the viewer's
|
||||
fonts and break ADR 0012's "looks the same everywhere"; selectable SVG text, if wanted, will
|
||||
be an export option.
|
||||
7. **Fields and paths keep runs.** A dynamic or input field's authored text is laid out with its
|
||||
runs (ADR 0066 allows authored styles); the HTML page draws its pieces (`pp`). Text a script
|
||||
or viewer sets uses the field's first style; `htmlText` is later. Text on a path keeps its
|
||||
runs' faces, sizes, colours and shifts; underlines aren't drawn on a path yet.
|
||||
8. **Commands.** `text.style {start?, end?, …character keys}`, `text.paragraph {start?, end?,
|
||||
…paragraph keys}` (the paragraphs the range touches), `text.styles {start?, end?}` (runs,
|
||||
paragraphs, and what the range shares, a mixed value as `null`), and `runs`/`paragraphs` on
|
||||
`text.create` and `text.edit` (character keys on `text.edit` restyle every run, keeping the
|
||||
rest). All live in the `text` namespace, which plug-ins may already call. Each change is one
|
||||
undo step; the panic hunt covers hostile runs, ranges, sizes and links.
|
||||
9. **The shell.** While typing on the stage, the editor keeps the runs and paragraphs with the
|
||||
text and shows each run's colour, size (at the zoom), italic, underline and baseline shift in
|
||||
the interface font (egui can't show the document's faces; the stage, updated by each style
|
||||
change in the same frame, shows the real result). Properties gains a section named after the
|
||||
selection ("Text: 6 characters selected") with the character and paragraph rows; values the
|
||||
selection doesn't share show the first one's and say **mixed**; at a caret, a style picked
|
||||
applies to what is typed next. A click in that section keeps the editor open and its
|
||||
selection. Copy and Cut remember the selection's runs; a paste of exactly that text gets
|
||||
them back, anything else pastes plain in the style before it (the system clipboard keeps
|
||||
plain text, so other apps are unaffected).
|
||||
10. **XFL import** reads every `DOMTextRun` into one block per field: face (PostScript name to
|
||||
family, bold and italic), size, colour and alpha, letter spacing, `characterPosition` and
|
||||
`url` per run; `alignment`, `indent`, `leftMargin`, `rightMargin` and `lineSpacing` per
|
||||
paragraph from the run the paragraph starts in. Justified text is still drawn left-aligned
|
||||
and reported. The corpus test now expects one block for the two-style title field.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Text with mixed styles round-trips through `.anicraft`, XFL import and every export, edits
|
||||
stay live and undoable, and documents without mixed styles are unchanged on disk.
|
||||
* A block costs one display item per colour instead of one.
|
||||
* Fields from Animate show their authored styles; scripts still set text in one style.
|
||||
* Not yet: justified alignment, kerning across runs, underlines on a path, `htmlText`, links
|
||||
that click in Test Movie and the HTML page, SVG `<text>` output, the stage editor showing the
|
||||
real faces, bold and paragraph alignment while typing, and tab stops.
|
||||
@@ -111,7 +111,7 @@ PR. Nothing in this ADR makes it harder: weights and reshaping are per skin.
|
||||
|
||||
## Not yet
|
||||
|
||||
* Instances and shapes in one armature (above); more than one shape per armature.
|
||||
* ~~Instances and shapes in one armature (above); more than one shape per armature~~: ADR 0098.
|
||||
* Reshaping at a posed frame (the Pen's Alt-click to add a point works, as it is
|
||||
`path.add_point`); drawing new subpaths into a bound shape; a weight brush that paints across several bones at once (normalise-locked bones, mirror).
|
||||
* A filled heat mesh across the shape's interior (the overlay is on its outline and points),
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
# ADR 0098: Mixed armatures (symbol instances and shapes in one armature)
|
||||
|
||||
* Status: accepted (2026-11-16)
|
||||
* Relates to: roadmap M7 (Bone/IK tool), ADR 0043 (instance armatures), ADR 0071 (shape
|
||||
armatures), ADR 0084 (springs, translation; first proposal of this), ADR 0090 (painted
|
||||
weights, reshaping; second proposal), ADR 0003 (file format), ADR 0004 (destructive actions)
|
||||
|
||||
## Context
|
||||
|
||||
An armature was one of two things: symbol instances joined by bones (ADR 0043), or one shape
|
||||
with bones inside it (ADR 0071). A character is usually both: a body drawn as a shape that
|
||||
bends, with a head, hands or props that are symbols. Animate keeps the two apart, and artists
|
||||
work around it with separate armatures that never quite stay joined. ADR 0084 and ADR 0090 each
|
||||
proposed joining them and left it out, because `Armature.skin` was *the* shape and half the
|
||||
model branched on "skinned or not". Behaviour of the two kinds was learned from Adobe's public
|
||||
help pages and from watching the program. The mixed form is our own design; nothing was copied.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **A bone says what it is.** `Bone.shape: Option<ElementId>`: `Some(s)` is a bone **inside
|
||||
shape `s`**. Its `child` is a joint node (an id that is no element), its `parent` is `s` or
|
||||
the node of another bone inside `s`, and it bends `s`'s outline through `s`'s skin. `None`
|
||||
is a bone that **moves an element as a whole**: a symbol instance (ADR 0043), or a shape. Its
|
||||
`parent` may be any element or any joint node. `Armature.skins: Vec<Skin>` holds one skin per
|
||||
shape with bones. Nothing else is new. A skin's bindings name only bones inside its own
|
||||
shape, and automatic binding weighs only those.
|
||||
2. **Why this and not ADR 0090's sketch.** That sketch had "a bone's parent/child naming an
|
||||
instance, a shape, or a node of one", which leaves the kind to be inferred from what is on a
|
||||
keyframe. `evaluate` must not depend on a lookup that a missing element changes, and
|
||||
`sanitize` can't check a file without the elements. A mark on the bone makes every rule
|
||||
local: which skin a bone bends, whether its child needs an element, what a hostile file may
|
||||
say.
|
||||
3. **A shape can be moved as a whole.** This is what lets a chain run instance → shape: the
|
||||
bone from the instance ends on the shape (it turns rigidly, as an instance does), and the
|
||||
shape's own bones start there. A shape that a bone moves and that has no bones inside is
|
||||
allowed and has no skin. On an armature layer every shape is an object (merge drawing leaves
|
||||
it alone, as ADR 0071 decided for the first shape).
|
||||
4. **One pose, one solver, one tween.** `armature::place` is ADR 0043's, unchanged in its
|
||||
arithmetic: it walks the bones parent first and places each child, element or node, from its
|
||||
parent. `armature::apply` sets the transform of every element a bone moves and then bends
|
||||
every skinned shape (`skin::deform`, ADR 0071's linear blend skinning, per skin). `solve`
|
||||
(CCD, limits, pins, slides), `pose_at` (tweens with easing) and `spring::sprung_pose` never
|
||||
knew what a bone moved and still don't: IK from a head instance turns the bones inside the
|
||||
body, a spring on the head's bone swings the plume on it, a sliding joint inside the body
|
||||
carries the head. `evaluate` stays pure, and every export sees posed instances and bent
|
||||
outlines through it, as before.
|
||||
5. **Bit-exactness.** At rest a skinned shape's outline is the drawn path itself (the same
|
||||
`Arc`), and instances are placed by ADR 0043's formula, so an armature of instances or of one
|
||||
shape evaluates to the bits it did before this change. A skin's matrices are computed in
|
||||
the shape's own space exactly as ADR 0071 did. Loading no longer rescales bindings whose
|
||||
weights already sum to 1 within 1e-6, so a file's weights don't drift when it is saved again.
|
||||
6. **The file format is versioned by need.** Two forms of an armature:
|
||||
* the **first form** (envelope versions up to 3): `bones` and, for a shape armature, its one
|
||||
`skin`. Every bone of an armature with a `skin` is inside that shape, which is how it is
|
||||
read: the marks are filled in on load.
|
||||
* the **mixed form** (envelope version 4): `bones` with `shape` on those inside a shape, and
|
||||
`skins`.
|
||||
|
||||
An armature the first form can say is always written in it, and a document is written as
|
||||
version 4 only if some armature in it (in a scene or a symbol) is mixed
|
||||
(`format::version_for`). So older files load unchanged, a document without mixed armatures
|
||||
is byte for byte what earlier builds wrote and opens in them, and a document with one is
|
||||
refused by earlier builds with their existing message ("file version 4 is newer than this
|
||||
AniCraft (supports 3)") instead of opening with bones that move nothing. Removing the bones
|
||||
that mix the kinds takes a document back to version 3. The alternative, bumping the version
|
||||
for every document, would have locked users of the released build out of files that use
|
||||
nothing new. The envelope lives in the shared `craft-anicraft-format` crate, which writes one
|
||||
fixed version. For version 4 the engine writes the same envelope itself (same fields, order
|
||||
and compact-or-pretty rule) until that crate takes a version argument.
|
||||
7. **Repair on load** (`Armature::sanitize`). On top of ADR 0043's rules: one skin per shape
|
||||
(the first wins), within the point limit; a bone inside a shape needs that shape's skin, a
|
||||
parent that is the shape or a node inside it, and a child that is no skinned shape; a skin
|
||||
with no bones goes; bindings keep only bones of their own shape. Bones are ordered parent
|
||||
first across the kinds, and what can't be placed (cycles, bones hanging from dropped ones)
|
||||
goes. `library::fresh_ids` now renames skins' shapes and bones' marks with the elements (a
|
||||
duplicated symbol's shape armature lost its skin before).
|
||||
8. **Commands** (the `bone.*` namespace, which plug-ins may already call):
|
||||
* `bone.add {from | parent, to, …}`: `to` may be an instance or a shape. `parent` (a bone)
|
||||
starts the new bone on that bone's end: for a bone inside a shape, on its joint node. A
|
||||
bone from something that hangs from a bone always starts at that bone's end (#239).
|
||||
* `bone.add_in_shape {parent, tail}`: when `parent` ends on a shape, this is that shape's
|
||||
first bone inside it, starting at the parent's end; the shape gets its skin then.
|
||||
* `bone.remove`: the removed bones' elements (instances and whole shapes, with everything
|
||||
below them) go to a layer of their own as they look at the playhead. A shape left with no
|
||||
bones inside it loses its skin and keeps the outline it showed there, in every pose. With
|
||||
the last bone the armature dissolves. It still asks first when the armature has more than
|
||||
one pose (ADR 0004).
|
||||
* `bone.bind`, `bone.paint_weights`, `bone.set_weight` act on the shape their bone is
|
||||
inside. Point indices are that shape's.
|
||||
* `bone.info` adds `members`, `mixed`, `shapes` (each with its bones and points) and each
|
||||
bone's `shape`. `shape` and `points` stay, naming the first shape.
|
||||
9. **The shell.** The Bone tool decides by where a drag begins and ends:
|
||||
* from an instance (or the end of a bone that moves one): the bone moves the instance or
|
||||
shape under the release;
|
||||
* from inside a shape: a bone inside it, as before;
|
||||
* from a bone's end that is in or on a shape: released over a symbol instance that is in no
|
||||
armature, the bone carries that instance; anywhere else it continues inside the shape.
|
||||
|
||||
Shapes are joined as a whole only from an instance's side. From a shape's bone, a release
|
||||
over another loose shape draws a bone inside the first shape, because artists draw bones
|
||||
across overlapping artwork all the time. `bone.add` joins it headlessly. The Bind tool shows
|
||||
the points of every shape with bones and binds the points of the picked bone's shape. The
|
||||
Selection tool poses the whole armature by dragging any bone or member.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Renderers, exporters and the GPU stage did not change.
|
||||
* Measured (optimised test profile, this machine): a mixed armature of 25 bones, two shapes of
|
||||
1,002 points and 8 instances binds in 1.6 ms and poses in 0.066 ms per frame; IK through all
|
||||
25 bones takes 0.07 ms. The 5-bone test character evaluates in 0.0024 ms per frame.
|
||||
* A skin's matrices live in the shape's space and elements are placed in the layer's. They
|
||||
agree when the shape's own transform is a move, a turn or an even scale. On a shape that was
|
||||
skewed or scaled unevenly before rigging, an instance on its bones follows the bones as the
|
||||
stage draws them, while the outline bends in the shape's skewed space, so they can part
|
||||
slightly. ADR 0071 already drew bones this way.
|
||||
* Instance placement at rest is ADR 0043's product of transforms: exact for moved artwork, and
|
||||
within float rounding for rotated or scaled parents, as it always was.
|
||||
|
||||
## Not yet
|
||||
|
||||
* Joining two existing armatures into one, and re-parenting a bone.
|
||||
* Joining a whole shape from a shape's bone with the Bone tool (the command does it).
|
||||
* Skinning that keeps instances exactly on a skewed shape's outline; an instance that follows
|
||||
several bones (weights on an instance).
|
||||
* XFL import of armatures; runtime armatures.
|
||||
@@ -66,7 +66,7 @@ Document
|
||||
├── timeline: Timeline (main scene; scenes list arrives in M2)
|
||||
│ └── layers: [Layer] (index 0 = top of the stack, as in the timeline panel)
|
||||
│ ├── name, visible, locked, outline, depth, volume, muted, kind (Normal | Guide | Mask | Folder | Camera | Armature),
|
||||
│ │ armature?: bones joining symbol instances (armature layer; ADR 0043)
|
||||
│ │ armature?: bones joining symbol instances and shapes (armature layer; ADR 0043, 0098)
|
||||
│ └── keyframes: [Keyframe] (sorted by start, spans do not overlap)
|
||||
│ ├── start, duration (frames covered by this keyframe)
|
||||
│ ├── elements: [Element]
|
||||
@@ -105,7 +105,11 @@ parent, the child turning about it) and each keyframe's `pose` holds joint angle
|
||||
the span's eased time. `evaluate_layer_elements` places the instances by forward kinematics
|
||||
(`W_child = R_joint(angle) · W_parent · rest`), so every export and the player see poses;
|
||||
`armature::solve` finds a pose from a dragged bone end by cyclic coordinate descent with joint
|
||||
limits and pins.
|
||||
limits and pins. An armature may be **mixed** (ADR 0098): a bone marked with a shape
|
||||
(`Bone.shape`) is inside it and bends its outline through that shape's skin (`Armature.skins`,
|
||||
ADR 0071); any other bone moves an element, an instance or a whole shape. One pose, solver and
|
||||
tween serve both. A document with a mixed armature is written as format version 4; every other
|
||||
document as version 3, as before.
|
||||
|
||||
**The camera** (ADR 0027): a scene's top layer may be its camera layer. `evaluate` (every
|
||||
export), `evaluate_player` and `evaluate_scene_camera` draw each top-level layer through
|
||||
|
||||
@@ -227,8 +227,8 @@ Select a bone to see **Properties › Bone**:
|
||||
* **Springs: Enable** turns every spring of the armature on or off. Turn them off while you
|
||||
pose, to see exactly the poses you key; Test Movie and every export play them while they
|
||||
are on.
|
||||
* **Remove Bone** (or **Delete**): removes the bone and those below it. Their instances stay
|
||||
where they are, on a layer of their own. If the armature has more than one pose, AniCraft asks
|
||||
* **Remove Bone** (or **Delete**): removes the bone and those below it. What they moved stays
|
||||
where it is, on a layer of its own. If the armature has more than one pose, AniCraft asks
|
||||
first.
|
||||
|
||||
Selecting a bone also selects the instance it moves. Properties then shows that instance's
|
||||
@@ -299,8 +299,35 @@ to the rest pose first.
|
||||
|
||||
Bones inside a shape take joint translation and springs too.
|
||||
|
||||
Not there yet: symbols and shapes in one armature, reshaping at a posed frame, armatures
|
||||
that scripts pose while the movie plays, and armatures from Animate files.
|
||||
### Symbols and shapes in one armature
|
||||
|
||||
One armature can hold both: a body drawn as a shape that bends, with a head, hands or props
|
||||
that are symbol instances, and more than one shape with bones. They pose, tween, spring and
|
||||
slide as one armature, on one armature layer.
|
||||
|
||||
* **A symbol on a shape's bone.** With the **Bone** tool, drag from the end of a bone inside
|
||||
the shape (the neck joint, say) and release over a symbol instance. The instance joins the
|
||||
armature and follows that joint.
|
||||
* **A shape on a symbol's bone.** Drag from an instance and release over a shape. The bone
|
||||
moves the shape as a whole. To make it bend as well, drag from that bone's end inside the
|
||||
shape: this draws the shape's first bone, and its points are bound to it.
|
||||
* From the end of any bone you can go on either way, so a chain can run body, head, then a
|
||||
feather on the head that bends.
|
||||
|
||||
Drag any bone or part with the **Selection** tool, and the whole chain follows: pulling the
|
||||
head bends the body under it. The **Bind** tool shows the points of every shape with bones.
|
||||
Pick a bone, and you bind or paint the points of the shape that bone is inside.
|
||||
|
||||
**Remove Bone** frees what the bone and the bones below it moved: instances and whole shapes
|
||||
go to a layer of their own, as they look at that moment. A shape that loses its last inside
|
||||
bone, but still hangs from a bone, stays in the armature and keeps the outline it showed.
|
||||
|
||||
Files with such an armature need this version of AniCraft or a later one. An earlier version
|
||||
says the file is newer rather than opening it with parts missing. Documents without one are
|
||||
saved as before and open everywhere.
|
||||
|
||||
Not there yet: joining two armatures into one, reshaping at a posed frame, armatures that
|
||||
scripts pose while the movie plays, and armatures from Animate files.
|
||||
|
||||
## Asset Warp
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Command reference
|
||||
|
||||
Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 360 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md).
|
||||
Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 363 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md).
|
||||
|
||||
This page is generated from the command registry, so it always matches the version of AniCraft it came with.
|
||||
|
||||
@@ -362,9 +362,9 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
- **Layer Depths** `layer.depths`
|
||||
Parameters: `{frame?} → {camera: bool, layers: [{layer, name, depth, keyed, key_here, attached}]} the layers that can have a depth, nearest first (ties in timeline order), at the frame`
|
||||
- **Add Bone** `bone.add` · changes the document
|
||||
Parameters: ``{from (instance id: the bone starts on it), to (instance id: the bone moves it), head?: [x, y] (the joint on a root instance, stage px, default its registration point; from an instance that hangs from a bone the joint is always that bone's end, so chains stay joined), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both instances go to an armature layer (made for the first bone)``
|
||||
Parameters: ``{from? (instance or shape id: the bone starts on it) | parent? (bone id: the bone starts on its end; for a bone inside a shape, on its joint), to (instance or shape id: the bone moves it as a whole), head?: [x, y] (the joint on a root, stage px, default its registration point; from something that hangs from a bone the joint is always that bone's end, so chains stay joined), tail?: [x, y] (default `to`'s registration point), name?} → {bone, layer}. Both go to an armature layer (made for the first bone). Instances and shapes mix in one armature: a bone inside a shape can carry an instance (parent), and a bone can end on a shape that then gets bones of its own (bone.add_in_shape with parent)``
|
||||
- **Add Bone in Shape** `bone.add_in_shape` · changes the document
|
||||
Parameters: `{shape? (shape id: the first bone, or another bone from the shape), parent? (bone id: continue the chain from its end), head?: [x, y] (the joint, stage px; default the parent bone's end), tail: [x, y] (stage px), name?} → {bone, layer, created, points}. The first bone moves the shape to an armature layer of its own, as an object (merge drawing leaves it alone); the shape's points are bound to the nearest bones`
|
||||
Parameters: `{shape? (shape id: the first bone, or another bone from the shape), parent? (bone id: continue the chain from its end; a bone that ends on a shape starts that shape's first bone inside it), head?: [x, y] (the joint, stage px; default the parent bone's end), tail: [x, y] (stage px), name?} → {bone, layer, created, points, shape}. The first bone moves the shape to an armature layer of its own, as an object (merge drawing leaves it alone), unless a bone already moves it; the shape's points are bound to the nearest bones inside it. An armature may hold several shapes with bones`
|
||||
- **Bind Points** `bone.bind` · changes the document
|
||||
Parameters: `{bone, points?: [point index…] (default every point; see bone.info with points), mode?: "only" (the points follow just this bone; default) | "add" (they share it with the bones they follow) | "remove" | "auto" (back to automatic binding)} → {bone, changed, bound (how many points the bone moves)}. A shape armature's binding: which points of the shape follow which bone`
|
||||
- **Paint Weights** `bone.paint_weights` · changes the document
|
||||
@@ -372,7 +372,7 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
- **Set Point Weight** `bone.set_weight` · changes the document
|
||||
Parameters: `{bone, points: [point index…] (see bone.info with points), weight (0–100: the bone's share of each point)} sets exactly how much the bone moves the points; their other bones share the rest in proportion (a point that followed only this bone gives the rest to its nearest other bones). Hand-bound`
|
||||
- **Remove Bone** `bone.remove` · changes the document
|
||||
Parameters: `{bone} removes it and the bones below it; the instances they moved go to a layer of their own as they look at the playhead (with the last bone, the whole armature does); asks first when the armature has more than one pose`
|
||||
Parameters: `{bone} removes it and the bones below it → {removed, freed, unbound, layer, armature_removed}; the instances and shapes they moved go to a layer of their own as they look at the playhead (with the last bone, the whole armature does); a shape left with no bones inside stays as it looks there; asks first when the armature has more than one pose`
|
||||
- **Joint Limits** `bone.set_limits` · changes the document
|
||||
Parameters: `{bone, constrain?: bool (false: turns freely), min?, max? (°, −360…360, from where it was drawn)} limits how far the joint turns, in every pose`
|
||||
- **Joint Translation** `bone.set_translation` · changes the document
|
||||
@@ -388,7 +388,7 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
- **Drag Bone** `bone.solve` · changes the document
|
||||
Parameters: `{bone, x, y (stage px: where the bone's end goes), local?: [x, y] (the point dragged, in the bone's instance's space; default its end), frame?} → {reached, error (px), chain}; inverse kinematics turns the bone and the bones above it (limits respected, pinned bones kept)`
|
||||
- **Armatures** `bone.info`
|
||||
Parameters: `{frame?, layer?, points?: bool} → every armature on the scene at the frame: its bones with joint and end (stage px, as keyed), joint angle and limits (°), slide and translation limits (px), spring (0–100) and its swing at the frame (°, what the spring adds to the angle), pinned; whether springs are on; a shape armature's shape, how many points each bone moves, and with points the shape's points (stage px) and the bones each follows`
|
||||
Parameters: ``{frame?, layer?, points?: bool} → every armature on the scene at the frame: its bones with joint and end (stage px, as keyed), joint angle and limits (°), slide and translation limits (px), spring (0–100) and its swing at the frame (°, what the spring adds to the angle), pinned; whether springs are on; the armature's members and whether it is mixed; each shape with bones (shapes: its bones, how many points, and with points every point on the stage with the bones it follows), the shape each bone is inside and how many points it moves; `shape` and `points` are the first shape's``
|
||||
- **Add Warp Pin** `warp.pin_add` · changes the document
|
||||
Parameters: `{element?, x, y (stage px, on the artwork)} → {element, pin, created}. Pins the artwork there (adding the mesh first if it has none), on every keyframe that bends the same mesh; nothing moves`
|
||||
- **Move Warp Pin** `warp.pin_move` · changes the document
|
||||
@@ -682,9 +682,15 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
- **Export Swatches** `swatch.export`
|
||||
Parameters: `{path} writes the document's swatches to a swatch file (JSON) → {written, swatches}`
|
||||
- **New Text** `text.create` · changes the document
|
||||
Parameters: `{text (may be empty for an input field), type?: static|dynamic|input, x?, y? (top-left; default: centred), font?, size?, bold?, italic?, color?, align?, letter_spacing?, line_spacing?, width?}`
|
||||
Parameters: `{text (may be empty for an input field), type?: static|dynamic|input, x?, y? (top-left; default: centred), width?, font?, size? (px), bold?, italic?, color?, letter_spacing?, shift?: normal|superscript|subscript, underline?, url? ("": none), align?: left|center|right, indent? (px, first line), left_margin?, right_margin? (px), line_spacing? (px), runs?: [{chars, …character keys}] (styles of the text's characters in order; unset keys take the style above), paragraphs?: [{…paragraph keys}] (one per line of the text)} (ADR 0085)`
|
||||
- **Edit Text** `text.edit` · changes the document
|
||||
Parameters: `{text?, font?, size? (px), bold?, italic?, color?, align?: left|center|right, letter_spacing?, line_spacing?, width? (px, wraps; null: one line per paragraph)} on the selected text`
|
||||
Parameters: `{text? (the runs follow the change: typed characters continue the style before them), runs?, paragraphs? (as text.create: replace the styles), width? (px, wraps; null: one line per paragraph), font?, size? (px), bold?, italic?, color?, letter_spacing?, shift?: normal|superscript|subscript, underline?, url? ("": none) (every character), align?: left|center|right, indent? (px, first line), left_margin?, right_margin? (px), line_spacing? (px) (every paragraph)} on the selected text`
|
||||
- **Text Character Style** `text.style` · changes the document
|
||||
Parameters: `{start?, end? (characters; default: all), font?, size? (px), bold?, italic?, color?, letter_spacing?, shift?: normal|superscript|subscript, underline?, url? ("": none)} styles those characters of the selected text, splitting and joining its runs (ADR 0085)`
|
||||
- **Text Paragraph Style** `text.paragraph` · changes the document
|
||||
Parameters: `{start?, end? (characters; default: all), align?: left|center|right, indent? (px, first line), left_margin?, right_margin? (px), line_spacing? (px)} sets the layout of the paragraphs those characters touch in the selected text (ADR 0085)`
|
||||
- **Text Styles** `text.styles`
|
||||
Parameters: `{start?, end? (characters; default: all)} of the first selected text: its runs, paragraphs, and what those characters share (a mixed value is null) (ADR 0085)`
|
||||
- **Fonts** `text.fonts`
|
||||
Parameters: `{}`
|
||||
- **Text on Path** `text.path` · changes the document
|
||||
|
||||
+38
-8
@@ -31,12 +31,40 @@ Animate.
|
||||
| **Style** | **B** for bold and **I** for italic, then **Left**, **Centre** or **Right** alignment. |
|
||||
| **Spacing** | **Letters** (letter spacing) and **Lines** (line spacing), in pixels. |
|
||||
| **Width** | Turn on **Wrap** to wrap lines at a fixed width, and set the width. With Wrap off, each paragraph stays on one line. |
|
||||
| **Position** | **Normal**, **Superscript** or **Subscript**, then **U** for underline. |
|
||||
| **Link** | A web address the characters link to in SVG exports. |
|
||||
| **Indent** | How far the first line of a paragraph starts in (negative hangs it out). |
|
||||
| **Margins** | Space kept clear at the left and right of each line, in pixels. |
|
||||
|
||||
Bold and italic use the matching face of the font (for example, its Bold or Italic file). If a
|
||||
font has no bold or italic face, AniCraft doesn't fake one.
|
||||
|
||||
A style applies to the whole text block. Different styles for single words in one block aren't
|
||||
there yet; use a separate block for each style.
|
||||
With the text selected (not being typed in), a change applies to the whole block. Where the
|
||||
characters differ, the row shows the first one's value and says **mixed**.
|
||||
|
||||
## Styling words and characters
|
||||
|
||||
One block can mix styles, as in Animate:
|
||||
|
||||
1. Click into the text with the **Text** tool (or double-click it).
|
||||
2. Select the characters: drag across them, or hold **Shift** with the arrow keys.
|
||||
3. Set their style in **Properties**: the section at the top is named after your selection, for
|
||||
example **Text: 6 characters selected**. Font, size, colour, bold, italic, letter spacing,
|
||||
superscript and subscript, underline and link all apply to just those characters, and the
|
||||
stage shows the change at once (each change is one undo step).
|
||||
|
||||
Things to know:
|
||||
|
||||
* **Typing continues the style before the caret.** Type after a red word and the new letters
|
||||
are red. To start a new style, set it in Properties with nothing selected, then type.
|
||||
* **Paragraph settings** (alignment, indent, margins and line spacing) apply to every paragraph
|
||||
your selection touches. Press **Enter** inside a paragraph and both halves keep its settings.
|
||||
* **Copy and paste keeps the styles inside AniCraft.** Text pasted from other apps comes in
|
||||
plain, in the style of the text before it.
|
||||
* While you type, the box over the stage shows the colours, sizes, italics, underlines and
|
||||
superscripts in AniCraft's interface font; the stage shows the real fonts and alignment.
|
||||
* **Superscript and subscript** use the size and offset the font itself suggests.
|
||||
* Text set by a script in a dynamic or input field uses the field's first style.
|
||||
|
||||
## Fonts on your computer
|
||||
|
||||
@@ -131,14 +159,15 @@ outlines like all text, so it looks the same on every computer.
|
||||
|
||||
To reshape the letters themselves, select the text and choose **Modify › Break Apart**
|
||||
(**Ctrl+B**). The text becomes an ordinary shape that you can edit with the Subselection tool,
|
||||
recolour and morph. It is no longer editable as text, so keep a copy if you might want to change
|
||||
the words.
|
||||
recolour and morph. Text in several colours becomes one shape per colour. It is no longer
|
||||
editable as text, so keep a copy if you might want to change the words.
|
||||
|
||||
## Text in exports
|
||||
|
||||
Because the letter shapes are saved with the document, text comes out exactly as you see it on
|
||||
the stage in every picture export: PNG, PNG sequences, GIF, animated PNG and WebP, video, sprite
|
||||
sheets, SVG and Lottie. Fields show their authored text, box and border there.
|
||||
sheets, SVG and Lottie. Fields show their authored text, box and border there. Each colour in a
|
||||
block is drawn in its colour, and in SVG, characters with a link are a link.
|
||||
|
||||
In the **HTML canvas** export, the movie plays in a web browser:
|
||||
|
||||
@@ -158,9 +187,10 @@ See [Exporting and Publish](exporting-and-publish.md) for every format.
|
||||
## Text in Animate files
|
||||
|
||||
When you open an Animate document, its text comes across as text you can edit, with its font,
|
||||
size, colour, bold and italic, alignment, spacing, position and wrapping. Dynamic and input
|
||||
fields come across as fields, with their names, boxes, borders and line types. A block whose
|
||||
lines use different styles becomes one block per style, stacked as before. Fonts that aren't on
|
||||
size, colour, bold and italic, superscript and subscript, links, alignment, indents, margins,
|
||||
spacing, position and wrapping. Each Animate text block stays one block, with every run's style
|
||||
kept. Dynamic and input fields come across as fields, with their names, boxes, borders and line
|
||||
types. Fonts that aren't on
|
||||
your computer use the default font, and the status bar names them. See
|
||||
[Opening Animate files](opening-animate-files.md).
|
||||
|
||||
|
||||
+3
-3
@@ -42,9 +42,9 @@ This integration depends on craft-libs #1962 and still requires hosted parity va
|
||||
| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016; the ease presets, saved and custom eases of ADR 0081 per segment); ~~Motion Editor and timeline retiming, Split/Join Motion~~ ✅ (ADR 0083); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: a colour picker for the Motion Editor's tint colour); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). |
|
||||
| **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); ~~surviving GPU failures mid-session~~ ✅ (ADR 0092: the stage drops to the CPU at once and retries the GPU after 3, 15, 60 and 300 s or on a resize; the window's device gets an error handler and a loss callback instead of wgpu's panic, a failing surface is reconfigured then recreated, and a lost window device autosaves, reopens the window a safer way and makes the next 3 starts try it late; not yet: recreating the window's device in place, which eframe doesn't offer); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. |
|
||||
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); ~~sound and video items, self-extracting and top-folder `.fla` archives~~ ✅ (ADR 0086: sound effects and custom envelopes, every sound and video that doesn't come across named with its format, Screen Video stills, zipped XFL folders and self-extracting stubs; not yet: sound in/out points, AIFF and compressed WAV, video playback); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (~~easing curves instead of per-frame keys~~ ✅, ADR 0089: keyframes with Bézier eases, moving artwork under group transforms, playback parity at every frame; not yet: motion along curved guides as spatial tangents, orient to path, nested tweens as nested transforms); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). |
|
||||
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles later); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~audio output polish (latency-aware clock, event tails, monitor volume and mute, scrubbing preference, device recovery, Web Audio)~~ ✅ (ADR 0095); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import), ~~filter presets, reordering, on/off and tweened filter values~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters), ~~motion-tween tracks per filter property in the Motion Editor~~ ✅ (ADR 0092: blur, strength, angle, distance and Adjust Color's four, by filter slot, with curves, eases and retiming, auto-keyed from Properties › Filters, following reorders and removals; not yet: filter colours, quality and switches as tracks, Animate's filter tracks from XFL; filters on text fields and built-in presets later) and ~~blend modes~~ ✅ on Movie Clips. |
|
||||
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text); ~~per-character and paragraph styles~~ ✅ first slice (ADR 0085: styled runs (font, size, bold, italic, colour, letter spacing, superscript/subscript by the font's OS/2 metrics, underline, link) set on the selected characters while typing, mixed values in Properties, paragraph alignment, indent, margins and line spacing, runs shaped one by one and wrapped across, one fill per colour in every export, SVG links, XFL `DOMTextRun`s kept in one block, `text.style`/`text.paragraph`/`text.styles`; not yet: justified text, runs on a path's underlines, `htmlText` in fields, links that click in Test Movie and the HTML page, SVG `<text>`/`<tspan>` output, the editor showing the real faces and alignment); ~~text on a path~~ ✅ first slice (ADR 0070: a copy of a shape's outline in the block, glyphs set by arc length and stored as outlines, offset, flip and alignment, Attach to Path by picking a shape, SVG `textPath`; editing the path in place and several lines on a path later); ~~dynamic and input text fields~~ ✅ first slice (ADR 0066: Text type in Properties, instance names, `field.text`/`appendText`/`length` in scripts, typing with caret, selection, max chars and passwords in Test Movie, native inputs in the HTML export, XFL fields kept; `htmlText`, change events, embedded fonts in HTML and other `TextField` API later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output); ~~effect envelopes, layer volume and mute, sounds inside symbols~~ ✅ (ADR 0039); ~~audio output polish (latency-aware clock, event tails, monitor volume and mute, scrubbing preference, device recovery, Web Audio)~~ ✅ (ADR 0095); ~~button sounds and hit-area editing~~ ✅ (ADR 0057: state sounds in Test Movie and HTML, state names on the timeline, the Hit area over the other states, Show hit areas in Test Movie, XFL sounds in the package); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import), ~~filter presets, reordering, on/off and tweened filter values~~ ✅ (ADR 0091: drag or Alt+arrows to reorder, an eye per filter that keeps its settings, Copy/Paste Filters, presets in your preferences with a JSON file to move them; classic tweens pair lists with switched-off filters), ~~motion-tween tracks per filter property in the Motion Editor~~ ✅ (ADR 0092: blur, strength, angle, distance and Adjust Color's four, by filter slot, with curves, eases and retiming, auto-keyed from Properties › Filters, following reorders and removals; not yet: filter colours, quality and switches as tracks, Animate's filter tracks from XFL; filters on text fields and built-in presets later) and ~~blend modes~~ ✅ on Movie Clips. |
|
||||
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it; ~~filters, Subtract and Invert in the page~~ ✅, ADR 0072); ~~command macros~~ ✅ first slice (ADR 0097: every undo step records its commands; History › Save As Command with steps rewritten to act on the selection or refused with the step named; saved commands at the end of the Commands menu with shortcuts; Manage Saved Commands; Run Command…; one transactional undo step; small JSON files in the settings folder; `macro.*` headless, CLI and MCP; macros call only what plug-ins may. Not yet: Replay Steps without saving, editing a macro's steps, macros that ask for values, the browser build and the command palette). **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: ~~tier 1 keeps scripts~~ ✅ (XFL frame scripts and class names stored verbatim, the Actions panel's Script view, `script.*` commands); ~~tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts~~ ✅; ~~tier 2.5 small logic (typed variables, expressions, `if` and loops, property reads, functions across frames, enter-frame and keyboard listeners, seeded random, ADR 0052)~~ ✅. The full language, the `flash.*` API and SWF bytecode are not planned. |
|
||||
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool); ~~painted weights and reshaping a bound shape~~ ✅ second slice (ADR 0090; not yet: instances and shapes in one armature, reshaping at a posed frame); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles) and brush library; ~~tilt, textured brushes, erasing inside symbols, gradients and width profiles in the merge~~ ✅ second slice (ADR 0093: tilt turns and widens the tip per sample, paper-grain texture and scatter as vector paint, Charcoal and Spatter, the Eraser's hint for symbols and objects, width profiles carried into each merged piece; not yet: reading tilt on desktop systems (winit 0.30 reports it only on iOS), bitmap, art and pattern brushes, eraser pressure and presets, the live preview through texture and tilt); ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL). |
|
||||
| **M7** | Advanced animation | ~~Bone/IK tool~~ ✅ first slice (ADR 0043: symbol-instance armatures on an armature layer, Bone tool, joint-angle poses tweened with easing, CCD inverse kinematics with joint limits and pins, posing with the Selection tool, Bone properties, every export; not yet: outline-following ARAP meshes, symbols, pins bound to bones, a GPU textured path, bent bitmaps in HTML/Lottie); ~~springs, joint translation, editing members in place~~ ✅ second slice (ADR 0084); not yet: runtime armatures, XFL armature import); ~~shape armatures~~ ✅ first slice (ADR 0071: bones inside one shape, automatic binding, linear blend skinning, Bind tool); ~~painted weights and reshaping a bound shape~~ ✅ second slice (ADR 0090; not yet: reshaping at a posed frame); ~~mixed armatures: symbol instances and shapes in one armature~~ ✅ (ADR 0098: bones inside a shape and bones that move instances or whole shapes in one armature, several skinned shapes, chains across the kinds with the Bone tool, one pose for IK, tweens, springs and translation, file format version 4 only for documents that use it; not yet: joining two armatures, joining a whole shape from a shape's bone by dragging, XFL import of armatures); ~~asset warp~~ ✅ first slice (ADR 0079: warp meshes on shapes and bitmaps, pins, rigid MLS, pin poses tweened, Asset Warp tool, ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export); ~~layer depth in perspective, keyed over time, Layer Depth panel, attaching layers, camera colour effects, editing while previewing~~ ✅ second slice (ADR 0082; not yet: tools other than Selection while previewing, depth inside symbols, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~brush library, pressure curves and the Paint Brush~~ ✅ first slice (ADR 0068: parameter presets, user brushes and brush sets, curve editor, velocity, stroke mode); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles) and brush library; ~~tilt, textured brushes, erasing inside symbols, gradients and width profiles in the merge~~ ✅ second slice (ADR 0093: tilt turns and widens the tip per sample, paper-grain texture and scatter as vector paint, Charcoal and Spatter, the Eraser's hint for symbols and objects, width profiles carried into each merged piece; not yet: reading tilt on desktop systems (winit 0.30 reports it only on iOS), bitmap, art and pattern brushes, eraser pressure and presets, the live preview through texture and tilt); ~~graph-based easing presets library~~ ✅ first slice (ADR 0081: presets, custom multi-segment eases, saved eases, per-group classic eases, Motion Editor properties, XFL import; not yet: updating every tween that uses a saved ease, a user ease library shared between documents, Lottie-native eases instead of baked frames, motion-tween eases from XFL). |
|
||||
| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; ~~opening documents from Finder~~ ✅ (ADR 0062, to be checked on a Mac); ~~AppImage desktop integration, portable mode, store readiness checks~~ ✅ (ADR 0094); next: store submissions); ~~web build (wasm) of the editor~~ ✅ first slice (ADR 0036: browser file picker and downloads, autosave in browser storage, CPU stage, CI wasm build and tests in Node, the release zip made by `packaging/web/package.sh` and checked in CI (#210); next: releases carrying it and a hosted copy, once the team decides where, Web Audio, WebGPU stage, verified in browsers); ~~localisation~~ ✅ first slice (ADR 0040: `tr!` everywhere in the shell, craft-i18n catalogs, Preferences language, pseudo-locale; next: AniCraft's catalog in craft-i18n, engine messages, right to left once egui can lay it out); accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), second pass ✅ (ADR 0064: stage elements and timeline frames for screen readers, keyboard selection on the stage, keyboard menu bar, following the system's contrast setting), ~~a light theme~~ ✅ (ADR 0077: Light palette, Follow system for light or dark, #227), next: live screen-reader passes on each platform, a light high-contrast palette; ~~crash-recovery autosave~~ ✅ (ADR 0015); ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058: `find.search`/`find.replace`/`find.goto` over text, fonts, colours, symbols, sounds and bitmaps, scene or document, linear-time patterns, Replace All as one undo step asking above 100 places, going there opens symbols in place; `explorer.tree` paged, Show filters and search, the Movie Explorer tab beside the Library, lists drawing only the rows in view; not yet: action parameters and ActionScript strings apart from code, font size and style, colour tolerance, renaming in the Movie Explorer); ~~files from the desktop, recent files and a start screen~~ ✅ first slice (ADR 0059: drops route by type and target in one undo step, Open Recent with pins and missing files, start screen with presets and thumbnails); ~~templates, SVG into the Library, drops on the timeline~~ ✅ first slice (ADR 0065: six built-in templates built in code, Save as Template with category and picture, SVG as a graphic symbol, sounds onto a frame's keyframe and media into a keyframe made there; next: exact desktop drop positions once eframe moves to winit 0.31, user template descriptions and renaming); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060: the publish profile in the document, every format with its export options and an output relative to the document's folder with `{name}`, Shift+F12 publishing in the background with progress, Cancel and one report, overwriting asked once per session, presets in Preferences, the browser's downloads as one ZIP; not yet: Animate's PublishSettings.xml from XFL, more placeholders, outputs outside the document's folder, progress inside HTML, Lottie and audio); ~~documentation book~~ ✅ first slice (ADR 0069: the user guide in `docs/guide/`, generated command and shortcut references, Help › User Guide offline), ~~search and context help~~ ✅ (ADR 0096: a prebuilt index and an offline search page with the same ranking as `anicraft-cli guide search`; F1, Help › Help for This and each panel menu open the guide at the section for the dialog, panel or tool, through a map checked against the guide's headings; F1 moves from the shortcut editor, which keeps Ctrl+Alt+Shift+K); next: translated guides, a print edition (PDF through the browser; a native PDF proposed in ADR 0096), help for single fields; ~~dockable panels and workspaces~~ ✅ first slice (ADR 0075, #249: every panel docks on any side of the stage, stacks as tabs, resizes, folds, floats in a window of its own with ADR 0062's fallback, closes and reopens where it was from the Window menu; Essentials, Animator, Designer and your own workspaces with Reset, kept in the preferences; new Colour and Output panels; Ctrl+F6 follows the layout), second slice ✅ (ADR 0087: the tools move like any panel, as a slim bar on any side or a tab laid out in columns; floating windows hold several tabs and drag back into a dock by their grip or title bar with the drop targets shown; docks collapse to strips of panel icons with flyouts over the stage (Esc or a click outside closes them); Manage Workspaces renames and deletes your own (built-in ones reset only); every panel fits the narrowest dock (200 pt), form rows wrapping under their label, checked by test in English and the pseudo-locale; not yet: dragging between two windows of their own on mixed-DPI screens verified by hand, panels side by side inside a floating window, columns of groLine truncated
|
||||
|
||||
## Releases
|
||||
@@ -65,7 +65,7 @@ titled with its milestone.
|
||||
| M4 | Text from Animate files | XFL import, text engine (M5 first slice) |
|
||||
| M5 | Audio layers: import, waveform, playback sync | timeline, layers |
|
||||
| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); ~~ActionScript tier 1: keep scripts~~ ✅ (ADR 0013); ~~ActionScript tier 2: run the timeline subset~~ ✅ (ADR 0013); ~~ActionScript tier 2.5: small logic~~ ✅ (ADR 0052); ~~exporter and easing plug-ins~~ ✅ (ADR 0088); ~~command macros~~ ✅ first slice (ADR 0097); next: growing the ActionScript subset (`switch`, arrays, event bubbling) | command registry, plug-in host, action IR and player |
|
||||
| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~camera depth, attaching and colour~~ ✅ (ADR 0082), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~painted weights and reshaping~~ ✅ (ADR 0090), ~~bone springs and joint translation~~ ✅ (ADR 0084), ~~Asset Warp~~ ✅ first slice (ADR 0079), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068), ~~tilt, texture, profiles in the merge~~ ✅ (ADR 0093); next: reading pen tilt from the toolkit, art brushes | strokes, Pen and Pencil, width profiles, timeline evaluation |
|
||||
| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~camera depth, attaching and colour~~ ✅ (ADR 0082), ~~Bone tool and IK~~ ✅ first slice (ADR 0043), ~~shape armatures and the Bind tool~~ ✅ first slice (ADR 0071), ~~painted weights and reshaping~~ ✅ (ADR 0090), ~~mixed armatures (instances and shapes together)~~ ✅ (ADR 0098), ~~bone springs and joint translation~~ ✅ (ADR 0084), ~~Asset Warp~~ ✅ first slice (ADR 0079), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); ~~brush library and pressure curves~~ ✅ first slice (ADR 0068), ~~tilt, texture, profiles in the merge~~ ✅ (ADR 0093); next: reading pen tilt from the toolkit, art brushes | strokes, Pen and Pencil, width profiles, timeline evaluation |
|
||||
| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026), ~~portable mode and AppImage desktop integration~~ ✅ (ADR 0094), ~~web build~~ ✅ first slice (ADR 0036), ~~localisation~~ ✅ first slice (ADR 0040), ~~Find and Replace and the Movie Explorer~~ ✅ first slice (ADR 0058), ~~drops, recent files and the start screen~~ ✅ first slice (ADR 0059); ~~templates and drops on the timeline~~ ✅ first slice (ADR 0065); ~~Publish Settings and Publish~~ ✅ first slice (ADR 0060); ~~Test Movie in its own window and macOS document opening~~ ✅ first slice (ADR 0062); ~~accessibility second pass~~ ✅ (ADR 0064); ~~a light theme~~ ✅ (ADR 0077); ~~CI on macOS and Windows~~ ✅ (ADR 0067); ~~guide search and context help~~ ✅ (ADR 0096); ~~dockable panels and workspaces~~ ✅ first and second slices (ADR 0075, ADR 0087); next: live screen-reader passes | `.anicraft` format, session, AccessKit in eframe |
|
||||
|
||||
Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and
|
||||
|
||||
+1
-1
@@ -443,7 +443,7 @@ mod tests {
|
||||
for tool in [Tool::Bone, Tool::Bind, Tool::Warp, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] {
|
||||
found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool));
|
||||
}
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "springbones", "shapebones", "shapeweights", "warp", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush"] {
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "springbones", "shapebones", "shapeweights", "mixedbones", "warp", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "richtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "swatchpanel", "brushlibrary", "brushcurve", "paintbrush"] {
|
||||
found.extend(check(panel, |a, _| a.open_panel(Some(panel))));
|
||||
}
|
||||
// Every panel in front where it docks, and floating (ADR 0075); the other workspaces.
|
||||
|
||||
+2
-2
@@ -137,7 +137,7 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
|
||||
fn grid_window(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(d) = &mut app.aids_dialogs.grid else { return };
|
||||
let (mut ok, mut cancel) = (false, false);
|
||||
egui::Window::new(tr!("Edit Grid")).id(egui::Id::new("edit_grid")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
crate::windows::new(ctx, tr!("Edit Grid")).id(egui::Id::new("edit_grid")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
ui.set_min_width(380.0);
|
||||
form_row(ui, FORM_LABEL_DIALOG, tr!("Colour"), |ui| {
|
||||
crate::colour::button_alpha(ui, &mut d.color).named(tr!("Grid colour"));
|
||||
@@ -171,7 +171,7 @@ pub fn accept_grid(app: &mut App) {
|
||||
fn guides_window(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(d) = &mut app.aids_dialogs.guides else { return };
|
||||
let (mut ok, mut cancel) = (false, false);
|
||||
egui::Window::new(tr!("Edit Guides")).id(egui::Id::new("edit_guides")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
crate::windows::new(ctx, tr!("Edit Guides")).id(egui::Id::new("edit_guides")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
ui.set_min_width(420.0);
|
||||
form_row(ui, FORM_LABEL_DIALOG, tr!("Colour"), |ui| {
|
||||
crate::colour::button_alpha(ui, &mut d.color).named(tr!("Guide colour"));
|
||||
|
||||
+112
-9
@@ -142,7 +142,7 @@ impl Tool {
|
||||
Tool::PaintBrush => tr_noop!("Drag to draw a line in the stroke colour whose width follows the pen's pressure and the brush's tapers. Shape it afterwards with the Width tool. [ and ] change the size; the options set the brush and its pressure curve."),
|
||||
Tool::Eraser => tr_noop!("Drag to erase lines and fills drawn with Object Drawing off (drawing objects and symbols are kept). [ and ] change the size; the options set the shape and erase mode, and the Faucet deletes a whole fill or line with a click. Double-click the tool to erase everything on the stage."),
|
||||
Tool::Width => tr_noop!("Hover a stroke to see its width points. Drag a point's handle to widen or narrow the stroke there (Alt: one side only), drag its dot to slide it along, or drag anywhere on the stroke to add a point. Click a point and press Delete to remove it."),
|
||||
Tool::Bone => tr_noop!("Drag from one symbol instance to another to join them with a bone (they move to an armature layer), or drag inside a shape to draw a bone in it (the shape bends with its bones); start on a bone's end to continue the chain. Click a bone to select it. Pose the armature by dragging bones or instances with the Selection tool."),
|
||||
Tool::Bone => tr_noop!("Drag from one symbol instance to another to join them with a bone (they move to an armature layer), or drag inside a shape to draw a bone in it (the shape bends with its bones); start on a bone's end to continue the chain. Instances and shapes mix: from a shape's bone end, release over an instance to carry it; from an instance, release over a shape, then draw bones inside it from that bone's end. Click a bone to select it. Pose the armature by dragging bones or instances with the Selection tool."),
|
||||
Tool::Bind => tr_noop!("Shows the points of shapes with bones: a square follows one bone, a triangle several. Click a bone to see the points it moves (filled). Click a point, or drag a box around points, to make them follow only that bone; Shift shares the bone with the ones they follow, Ctrl takes them from it. Turn on Paint Weights in Properties to brush the bone's influence on, off or smooth, shown as a heat map."),
|
||||
Tool::Warp => tr_noop!("Click a shape or a bitmap to pin it (the first pin covers it with a warp mesh). Drag a pin to bend the artwork around the other pins; with one pin it moves. Click a pin and press Delete to remove it. A pin moved at another frame keys it, and pins tween."),
|
||||
Tool::GradientTransform => tr_noop!("Click a shape with a gradient or bitmap fill to show its handles. Drag the centre to move the fill, the square to change its width, the circle to change its size, the knob to rotate it (Shift: 15° steps) and, on a radial gradient, the triangle to move its focal point. A bitmap fill also has a square for its height and diamonds to skew it. Each drag is one undo step."),
|
||||
@@ -168,9 +168,21 @@ pub struct TextEditing {
|
||||
/// The text element being edited, or `None` for new text.
|
||||
pub element: Option<anicraft_engine::doc::ElementId>,
|
||||
pub text: String,
|
||||
/// The text when editing started (unchanged text commits nothing).
|
||||
/// The text when editing started, or when its styles were last applied (unchanged text
|
||||
/// commits nothing).
|
||||
pub original: String,
|
||||
/// Focus the field on its first frame.
|
||||
/// The text as the runs last saw it (a change since is followed by [`TextEditing::sync`]).
|
||||
pub last: String,
|
||||
/// Its styled runs and one style per paragraph (ADR 0085).
|
||||
pub runs: Vec<anicraft_engine::doc::TextRun>,
|
||||
pub paras: Vec<anicraft_engine::doc::ParagraphStyle>,
|
||||
/// The selected characters (anchor, caret), as the editor last reported them.
|
||||
pub sel: (u32, u32),
|
||||
/// A style picked at a caret, for what is typed there next.
|
||||
pub pending: Option<anicraft_engine::doc::CharStyle>,
|
||||
/// Styled text being pasted this frame (copied from this editor).
|
||||
pub paste: Option<crate::rich_edit::StyledClip>,
|
||||
/// Focus the field on its next frame.
|
||||
pub focus: bool,
|
||||
}
|
||||
|
||||
@@ -253,8 +265,9 @@ pub enum Drag {
|
||||
CameraRotate { last: f32 },
|
||||
CameraWheel { until: f64 },
|
||||
/// Bone tool (ADR 0043): drawing a bone from instance `from` (or inside shape `from`, or on
|
||||
/// from a shape bone's joint node, ADR 0071), joint `head` to `cur` (stage).
|
||||
Bone { from: anicraft_engine::doc::ElementId, head: egui::Pos2, cur: egui::Pos2 },
|
||||
/// from a shape bone's joint node, ADR 0071), joint `head` to `cur` (stage). `parent`: the
|
||||
/// bone whose end the drag began on (ADR 0098).
|
||||
Bone { from: anicraft_engine::doc::ElementId, parent: Option<anicraft_engine::doc::BoneId>, head: egui::Pos2, cur: egui::Pos2 },
|
||||
/// Bind tool (ADR 0071): a box from `start` to `cur` (stage) binding the points inside it.
|
||||
BindMarquee { start: egui::Pos2, cur: egui::Pos2 },
|
||||
/// Bind tool, Paint Weights (ADR 0090): a brush stroke whose last dab was at `last` (stage).
|
||||
@@ -389,6 +402,11 @@ pub struct App {
|
||||
pub library: crate::library::LibraryView,
|
||||
/// Text being typed on the stage.
|
||||
pub text_edit: Option<TextEditing>,
|
||||
/// Styled text last copied from the stage editor (ADR 0085).
|
||||
pub text_clip: Option<crate::rich_edit::StyledClip>,
|
||||
/// Where Properties showed the styles of the text being typed (last frame): a click there
|
||||
/// keeps the editor open.
|
||||
pub text_props_rect: Option<egui::Rect>,
|
||||
/// Attach to Path is waiting for a click on a shape (ADR 0070): the text to set along it.
|
||||
pub path_pick: Option<anicraft_engine::doc::ElementId>,
|
||||
/// Font families on this computer, listed once on first need.
|
||||
@@ -710,6 +728,8 @@ impl App {
|
||||
library_sel,
|
||||
library: Default::default(),
|
||||
text_edit: None,
|
||||
text_clip: None,
|
||||
text_props_rect: None,
|
||||
path_pick: None,
|
||||
font_families: None,
|
||||
polystar: PolyStarOptions::default(),
|
||||
@@ -1744,6 +1764,31 @@ impl App {
|
||||
crate::layer_props::open(self, Some(anicraft_engine::doc::LayerId(m)));
|
||||
}
|
||||
}
|
||||
Some("richtext") => {
|
||||
// Styled text (ADR 0085): a title with bold, coloured and superscript runs and a
|
||||
// centred paragraph, open for typing with a word selected, its style in
|
||||
// Properties.
|
||||
self.perform("file.new", json!({"width": 640, "height": 400}));
|
||||
// i18n-exempt: document content
|
||||
let made = self.run("text.create", json!({"text": "Energy E = mc2\nStyled runs in one block", "x": 60, "y": 90, "size": 44, "color": "#264653", "width": 520}));
|
||||
if let Some(id) = made.and_then(|v| v["element"].as_u64()) {
|
||||
self.run("text.style", json!({"start": 0, "end": 6, "bold": true, "color": "#e76f51"}));
|
||||
self.run("text.style", json!({"start": 13, "end": 14, "shift": "superscript"}));
|
||||
self.run("text.style", json!({"start": 15, "end": 39, "size": 26, "italic": true, "color": "#2a9d8f"}));
|
||||
self.run("text.style", json!({"start": 22, "end": 26, "underline": true, "url": "https://example.org"}));
|
||||
self.run("text.paragraph", json!({"start": 15, "end": 39, "align": "center"}));
|
||||
let block = self.s.visible_elements().into_iter().find(|e| e.id.0 == id).and_then(|e| match &e.kind {
|
||||
anicraft_engine::doc::ElementKind::Text(t) => Some((e.transform.apply(anicraft_engine::geom::Vec2::ZERO), t.clone())),
|
||||
_ => None,
|
||||
});
|
||||
if let Some((at, t)) = block {
|
||||
self.tool = Tool::Text;
|
||||
let mut te = TextEditing::new(egui::pos2(at.x, at.y), Some(anicraft_engine::doc::ElementId(id)), Some(&t), &self.s.text_style);
|
||||
te.sel = (0, 6);
|
||||
self.text_edit = Some(te);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(which @ ("textfields" | "testtext")) => {
|
||||
// Dynamic and input text fields (ADR 0066): a score a script sets, a name field
|
||||
// and a multiline notes field. `textfields` selects the name field for its
|
||||
@@ -2460,6 +2505,62 @@ impl App {
|
||||
self.bone_sel = bones.get(1).copied().map(anicraft_engine::doc::BoneId);
|
||||
self.tool = Tool::Bind;
|
||||
}
|
||||
Some("mixedbones") => {
|
||||
// A mixed armature (ADR 0098): a character whose body is a shape with three
|
||||
// bones inside it, its head a symbol instance on the body's neck joint, and a
|
||||
// plume shape on the head with two bones of its own. Leaning at frame 1, the
|
||||
// other way at frame 24; the head's bone picked.
|
||||
self.run("layer.new", json!({"name": "Character"}));
|
||||
let id = |v: Option<Value>, k: &str| v.and_then(|v| v[k].as_u64()).unwrap_or(0);
|
||||
// The body: hips at y = 500, neck at y = 250, a point every 25 px up both sides.
|
||||
let half = |y: f32| 34.0 + 14.0 * ((y - 250.0) / 250.0);
|
||||
let ys: Vec<f32> = (0..=10).map(|i| 500.0 - 25.0 * i as f32).collect();
|
||||
let mut d = String::new();
|
||||
for (i, y) in ys.iter().enumerate() {
|
||||
d.push_str(&format!("{}{} {y} ", if i == 0 { "M" } else { "L" }, 540.0 - half(*y)));
|
||||
}
|
||||
for y in ys.iter().rev() {
|
||||
d.push_str(&format!("L{} {y} ", 540.0 + half(*y)));
|
||||
}
|
||||
d.push('Z');
|
||||
let body = id(self.run("draw.path", json!({"d": d, "fill": "#5f8dd3", "stroke": "#1b2a4a", "stroke_width": 3, "object": true})), "element");
|
||||
// The plume: a leaf from the top of the head up, a point every 10 px.
|
||||
let wide = |y: f32| 3.0 + 9.0 * (1.0 - ((y - 105.0) / 45.0).powi(2)).max(0.0);
|
||||
let ys: Vec<f32> = (0..=9).map(|i| 150.0 - 10.0 * i as f32).collect();
|
||||
let mut d = String::new();
|
||||
for (i, y) in ys.iter().enumerate() {
|
||||
d.push_str(&format!("{}{} {y} ", if i == 0 { "M" } else { "L" }, 540.0 - wide(*y)));
|
||||
}
|
||||
for y in ys.iter().rev() {
|
||||
d.push_str(&format!("L{} {y} ", 540.0 + wide(*y)));
|
||||
}
|
||||
d.push('Z');
|
||||
let plume = id(self.run("draw.path", json!({"d": d, "fill": "#e8833a", "stroke": "#4a2c14", "stroke_width": 2, "object": true})), "element");
|
||||
self.run("draw.rect", json!({"x": 496, "y": 150, "w": 88, "h": 96, "radius": 42, "fill": "#ffd9a8", "stroke": "#1b2a4a", "stroke_width": 3}));
|
||||
let head = id(self.run("modify.convert_to_symbol", json!({"name": "Head"})), "instance");
|
||||
self.run("timeline.insert_frame", json!({"frame": 23}));
|
||||
self.run("timeline.goto", json!({"frame": 0}));
|
||||
// Bones inside the body, from the hips up...
|
||||
let mut bone = id(self.run("bone.add_in_shape", json!({"shape": body, "head": [540, 498], "tail": [540, 415]})), "bone");
|
||||
let mut spine = vec![bone];
|
||||
for y in [330, 252] {
|
||||
bone = id(self.run("bone.add_in_shape", json!({"parent": bone, "tail": [540, y]})), "bone");
|
||||
spine.push(bone);
|
||||
}
|
||||
// ...on from the neck joint to the head instance, from the head to the plume as
|
||||
// a whole, and on inside the plume.
|
||||
let neck = id(self.run("bone.add", json!({"parent": bone, "to": head, "tail": [540, 198]})), "bone");
|
||||
let crest = id(self.run("bone.add", json!({"from": head, "to": plume, "tail": [540, 150]})), "bone");
|
||||
let f1 = id(self.run("bone.add_in_shape", json!({"parent": crest, "tail": [540, 105]})), "bone");
|
||||
let f2 = id(self.run("bone.add_in_shape", json!({"parent": f1, "tail": [540, 62]})), "bone");
|
||||
for (b, (a, z)) in spine.iter().chain([&neck, &crest, &f1, &f2]).zip([(4, -3), (9, -8), (11, -10), (14, -12), (6, -4), (22, -18), (30, -26)]) {
|
||||
self.run("bone.pose", json!({"bone": b, "angle": a, "frame": 0}));
|
||||
self.run("bone.pose", json!({"bone": b, "angle": z, "frame": 23}));
|
||||
}
|
||||
self.run("timeline.goto", json!({"frame": 0}));
|
||||
self.tool = Tool::Select;
|
||||
crate::bone_tool::select(self, self.s.layer, Some(anicraft_engine::doc::BoneId(neck)));
|
||||
}
|
||||
Some("shapeweights") => {
|
||||
// Painted weights (ADR 0090): the tail of `shapebones` at rest, a point added to
|
||||
// its outline with Subselection, and the second bone's weights mid-stroke with
|
||||
@@ -3546,7 +3647,7 @@ impl App {
|
||||
let mut submit = false;
|
||||
let mut cancel = false;
|
||||
let title = crate::i18n::t(p.title);
|
||||
egui::Window::new(title).id(egui::Id::new(("prompt", p.title))).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
crate::windows::new(ctx, title).id(egui::Id::new(("prompt", p.title))).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
ui.set_min_width(360.0);
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut p.text).desired_width(f32::INFINITY)).named(title);
|
||||
if p.focus {
|
||||
@@ -3584,7 +3685,7 @@ impl App {
|
||||
|
||||
fn about_window(&mut self, ctx: &egui::Context) {
|
||||
let mut open = self.show_about;
|
||||
let shown = egui::Window::new(tr!("About AniCraft")).id(egui::Id::new("about_window")).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| {
|
||||
let shown = crate::windows::new(ctx, tr!("About AniCraft")).id(egui::Id::new("about_window")).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| {
|
||||
ui.add(egui::Image::new((app_mark(ctx).id(), egui::vec2(64.0, 64.0))));
|
||||
ui.heading("AniCraft");
|
||||
ui.label(tr!("Version {version} · {stage}", version = env!("CARGO_PKG_VERSION"), stage = crate::i18n::t(RELEASE_STAGE)));
|
||||
@@ -3616,7 +3717,7 @@ impl App {
|
||||
(tr!("Screenshots"), root.join("shots")),
|
||||
];
|
||||
let mut opened: Option<Result<(), String>> = None;
|
||||
let shown = egui::Window::new(tr!("Project Files")).id(egui::Id::new("files_window")).open(&mut open).collapsible(false).resizable(false).default_width(620.0).show(ctx, |ui| {
|
||||
let shown = crate::windows::new(ctx, tr!("Project Files")).id(egui::Id::new("files_window")).open(&mut open).collapsible(false).resizable(false).default_width(620.0).show(ctx, |ui| {
|
||||
ui.label(theme::text(theme::Type::Label, tr!("Where AniCraft's documents and files are on this computer")));
|
||||
ui.add_space(4.0);
|
||||
egui::Grid::new("files").num_columns(3).spacing([10.0, 6.0]).striped(true).show(ui, |ui| {
|
||||
@@ -3861,7 +3962,9 @@ impl App {
|
||||
|
||||
let bar = |fill| egui::Frame::NONE.fill(fill).inner_margin(egui::Margin::symmetric(8, 2));
|
||||
crate::drop::begin_frame(self);
|
||||
egui::Panel::top("menu_bar").frame(bar(T.chrome)).show(ui, |ui| menus::bar(self, ui));
|
||||
let menu = egui::Panel::top("menu_bar").frame(bar(T.chrome)).show(ui, |ui| menus::bar(self, ui));
|
||||
// Floating windows stay below the menu bar (crate::windows).
|
||||
crate::windows::set_work_area(&ctx, menu.response.rect.max.y);
|
||||
if self.start.is_some() {
|
||||
// The start screen takes the workspace's place (ADR 0059); the menus stay.
|
||||
egui::Panel::bottom("status_bar").exact_size(28.0).frame(bar(T.chrome)).show(ui, |ui| panels::status_bar(self, ui));
|
||||
|
||||
+1
-1
@@ -360,7 +360,7 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
|
||||
let confirm = app.recovery.confirm_discard.clone();
|
||||
let btn = egui::vec2(96.0, crate::theme::TARGET + 4.0);
|
||||
let title = tr!("Recover unsaved work");
|
||||
let shown = egui::Window::new(title)
|
||||
let shown = crate::windows::new(ctx, title)
|
||||
.id(egui::Id::new("recover_window"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
|
||||
+31
-24
@@ -1,7 +1,9 @@
|
||||
//! The Bind tool (ADR 0071, ADR 0090): which points of a shape follow which of its bones, and
|
||||
//! how much.
|
||||
//!
|
||||
//! With the tool in hand, every shape armature on the stage shows its points: a square for a
|
||||
//! With the tool in hand, every shape with bones on the stage shows its points (an armature may
|
||||
//! hold several such shapes, next to instances: ADR 0098; a bone binds the points of the shape
|
||||
//! it is inside): a square for a
|
||||
//! point that follows one bone, a triangle for one that several bones share (as in Animate).
|
||||
//! Click a bone to pick it: the points it moves fill in the selection colour. Then a click on a
|
||||
//! point makes it follow only that bone, Shift-click shares it with the bones it follows,
|
||||
@@ -22,7 +24,7 @@ use crate::pathtools::Xf;
|
||||
use crate::theme::{T, to_color32};
|
||||
use anicraft_engine::doc::skin::points_shown;
|
||||
use anicraft_engine::doc::weights::Brush;
|
||||
use anicraft_engine::doc::{BoneId, ElementKind, LayerId, LayerKind, evaluate_layer_elements};
|
||||
use anicraft_engine::doc::{BoneId, ElementId, ElementKind, LayerId, LayerKind, evaluate_layer_elements};
|
||||
use anicraft_engine::geom::{PathCmd, Vec2};
|
||||
use egui::{Color32, Pos2, Rect, Stroke, StrokeKind, pos2, vec2};
|
||||
use serde_json::json;
|
||||
@@ -67,9 +69,10 @@ pub fn brush_label(b: Brush) -> (&'static str, &'static str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// One shape armature's points as the stage shows them at the playhead.
|
||||
/// The points of one shape with bones as the stage shows them at the playhead.
|
||||
struct Points {
|
||||
layer: LayerId,
|
||||
shape: ElementId,
|
||||
color: Color32,
|
||||
locked: bool,
|
||||
/// Stage position, the bones it follows with their weights.
|
||||
@@ -102,11 +105,10 @@ fn shown(app: &App) -> Vec<Points> {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, l)| l.kind == LayerKind::Armature && l.visible && !tl.hidden_by_folder(*i))
|
||||
.filter_map(|(_, l)| {
|
||||
let arm = l.armature.as_deref()?;
|
||||
let skin = arm.skin.as_ref()?;
|
||||
let (_, els) = evaluate_layer_elements(l, app.s.frame)?;
|
||||
let at = points_shown(arm, &els);
|
||||
.filter_map(|(_, l)| Some((l, l.armature.as_deref()?, evaluate_layer_elements(l, app.s.frame)?.1)))
|
||||
.flat_map(|(l, arm, els)| arm.skins.iter().map(move |skin| (l, skin, els.clone())).collect::<Vec<_>>())
|
||||
.map(|(l, skin, els)| {
|
||||
let at = points_shown(skin, &els);
|
||||
let points = at.into_iter().zip(&skin.points).map(|(p, b)| (p, b.bones.iter().map(|i| (i.0, i.1)).collect())).collect();
|
||||
// The outline as it shows, segment by segment, with the anchors at its ends.
|
||||
let mut outline = Vec::new();
|
||||
@@ -135,7 +137,7 @@ fn shown(app: &App) -> Vec<Points> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Points { layer: l.id, color: to_color32(l.color), locked: l.locked || tl.locked_by_folder(l.id), points, outline })
|
||||
Points { layer: l.id, shape: skin.shape, color: to_color32(l.color), locked: l.locked || tl.locked_by_folder(l.id), points, outline }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -152,16 +154,16 @@ fn mode(shift: bool, command: bool) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// The picked bone, when it is inside a shape on layer `layer`.
|
||||
fn picked_in(app: &App, layer: LayerId) -> Option<BoneId> {
|
||||
/// The picked bone, when it is inside shape `shape` on layer `layer`.
|
||||
fn picked_in(app: &App, layer: LayerId, shape: ElementId) -> Option<BoneId> {
|
||||
let id = app.bone_sel?;
|
||||
app.s.timeline().layer(layer)?.armature.as_ref().filter(|a| a.skin.is_some() && a.bone(id).is_some()).map(|_| id)
|
||||
app.s.timeline().layer(layer)?.armature.as_ref().filter(|a| a.bone(id).is_some_and(|b| b.shape == Some(shape))).map(|_| id)
|
||||
}
|
||||
|
||||
/// The picked bone when it is inside a shape (any layer).
|
||||
fn picked_shape_bone(app: &App) -> Option<BoneId> {
|
||||
let id = app.bone_sel?;
|
||||
app.s.timeline().layers.iter().any(|l| l.armature.as_ref().is_some_and(|a| a.skin.is_some() && a.bone(id).is_some())).then_some(id)
|
||||
app.s.timeline().layers.iter().any(|l| l.armature.as_ref().is_some_and(|a| a.skin_of(id).is_some())).then_some(id)
|
||||
}
|
||||
|
||||
fn bind(app: &mut App, bone: BoneId, points: Vec<usize>, shift: bool, command: bool) {
|
||||
@@ -178,9 +180,12 @@ fn bind(app: &mut App, bone: BoneId, points: Vec<usize>, shift: bool, command: b
|
||||
}
|
||||
}
|
||||
|
||||
/// The nearest unlocked shape point within grabbing reach of screen point `p`: its layer and index.
|
||||
fn point_at(app: &App, xf: Xf, p: Pos2) -> Option<(LayerId, usize)> {
|
||||
shown(app).into_iter().rev().filter(|s| !s.locked).find_map(|s| s.points.iter().position(|(at, _)| xf.to_screen(*at).distance(p) <= GRAB).map(|i| (s.layer, i)))
|
||||
/// The nearest unlocked shape point within grabbing reach of screen point `p`: its layer, its
|
||||
/// shape and its index there. The picked bone's shape wins where shapes overlap.
|
||||
fn point_at(app: &App, xf: Xf, p: Pos2) -> Option<(LayerId, ElementId, usize)> {
|
||||
let mut all: Vec<Points> = shown(app).into_iter().filter(|s| !s.locked).collect();
|
||||
all.sort_by_key(|s| picked_in(app, s.layer, s.shape).is_some());
|
||||
all.into_iter().rev().find_map(|s| s.points.iter().position(|(at, _)| xf.to_screen(*at).distance(p) <= GRAB).map(|i| (s.layer, s.shape, i)))
|
||||
}
|
||||
|
||||
/// Sends dabs at stage points `at` with the brush in hand (inside the stroke's gesture).
|
||||
@@ -206,7 +211,9 @@ pub fn click(app: &mut App, xf: Xf, p: Pos2, shift: bool, command: bool) {
|
||||
app.status_ok(tr!("Pick a bone of a shape first (click it), then paint its weights."));
|
||||
return;
|
||||
};
|
||||
if let Some((_, i)) = hit {
|
||||
if let Some((layer, shape, i)) = hit
|
||||
&& picked_in(app, layer, shape).is_some()
|
||||
{
|
||||
app.bind.point = Some(i);
|
||||
}
|
||||
app.s.begin_gesture(tr_noop!("Paint Weights"));
|
||||
@@ -214,8 +221,8 @@ pub fn click(app: &mut App, xf: Xf, p: Pos2, shift: bool, command: bool) {
|
||||
app.s.end_gesture();
|
||||
return;
|
||||
}
|
||||
if let Some((layer, i)) = hit {
|
||||
match picked_in(app, layer) {
|
||||
if let Some((layer, shape, i)) = hit {
|
||||
match picked_in(app, layer, shape) {
|
||||
Some(bone) => {
|
||||
app.bind.point = Some(i);
|
||||
bind(app, bone, vec![i], shift, command);
|
||||
@@ -270,7 +277,7 @@ pub fn paint_to(app: &mut App, last: Pos2, cur: Pos2) -> Pos2 {
|
||||
pub fn paint_end(app: &mut App) {
|
||||
app.s.end_gesture();
|
||||
if let Some(bone) = picked_shape_bone(app) {
|
||||
let n = app.s.timeline().layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skin.as_ref()).filter(|_| l.armature.as_ref().is_some_and(|a| a.bone(bone).is_some())).map(|k| k.points.iter().filter(|b| b.weight(bone) > 0.0).count()));
|
||||
let n = app.s.timeline().layers.iter().find_map(|l| l.armature.as_ref().filter(|a| a.skin_of(bone).is_some()).map(|a| a.bound_count(bone)));
|
||||
if let Some(n) = n {
|
||||
app.status_ok(trn!("The bone moves {n} point. {undo} to undo the stroke.", "The bone moves {n} points. {undo} to undo the stroke.", n, undo = app.undo_key()));
|
||||
}
|
||||
@@ -281,7 +288,7 @@ pub fn paint_end(app: &mut App) {
|
||||
pub fn drag_end(app: &mut App, start: Pos2, cur: Pos2, shift: bool, command: bool) {
|
||||
let r = Rect::from_two_pos(start, cur);
|
||||
for s in shown(app).into_iter().filter(|s| !s.locked) {
|
||||
let Some(bone) = picked_in(app, s.layer) else { continue };
|
||||
let Some(bone) = picked_in(app, s.layer, s.shape) else { continue };
|
||||
let inside: Vec<usize> = s.points.iter().enumerate().filter(|(_, (at, _))| r.contains(pos2(at.x, at.y))).map(|(i, _)| i).collect();
|
||||
if inside.is_empty() {
|
||||
app.status_ok(tr!("No points of the bone's shape inside the box."));
|
||||
@@ -292,14 +299,14 @@ pub fn drag_end(app: &mut App, start: Pos2, cur: Pos2, shift: bool, command: boo
|
||||
}
|
||||
}
|
||||
|
||||
/// Every shape armature's points (with the Bind tool in hand), and the box being dragged; with
|
||||
/// The points of every shape with bones (with the Bind tool in hand), and the box being dragged; with
|
||||
/// Paint Weights on, the picked bone's weights as a heat map and the brush under the pointer.
|
||||
pub fn draw(app: &App, painter: &egui::Painter, xf: Xf) {
|
||||
if app.tool != Tool::Bind {
|
||||
return;
|
||||
}
|
||||
for s in shown(app) {
|
||||
let picked = picked_in(app, s.layer);
|
||||
let picked = picked_in(app, s.layer, s.shape);
|
||||
let fade = |c: Color32| if s.locked { c.gamma_multiply(0.5) } else { c };
|
||||
if let (true, Some(bone)) = (app.bind.paint, picked) {
|
||||
let w = |i: usize| s.points.get(i).and_then(|(_, b)| b.iter().find(|x| x.0 == bone)).map_or(0.0, |x| x.1);
|
||||
@@ -380,7 +387,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn weights(app: &App, bone: BoneId) -> Vec<f32> {
|
||||
app.s.timeline().layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skin.as_ref())).map(|k| k.points.iter().map(|b| b.weight(bone)).collect()).unwrap_or_default()
|
||||
app.s.timeline().layers.iter().find_map(|l| l.armature.as_ref().and_then(|a| a.skin_of(bone))).map(|k| k.points.iter().map(|b| b.weight(bone)).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+164
-49
@@ -1,11 +1,12 @@
|
||||
//! The Bone tool and armatures on the stage (ADR 0043, ADR 0071).
|
||||
//! The Bone tool and armatures on the stage (ADR 0043, ADR 0071, ADR 0098).
|
||||
//!
|
||||
//! Bones show over the artwork of every visible armature layer as wedges, wide at the round
|
||||
//! joint they turn about and narrowing to a smaller round end, in the layer's colour; the
|
||||
//! selected bone in the selection colour. With the **Bone tool** a drag from one symbol
|
||||
//! instance to another adds a bone; a drag inside a shape draws a bone inside it (the shape
|
||||
//! bends with it: a shape armature); a drag starting on a bone's end continues the chain from
|
||||
//! it, and a click picks a bone. With the **Selection tool** a drag on a bone, or on an
|
||||
//! it (onto a symbol instance from a shape's bone, or into a shape from an instance's: the two
|
||||
//! mix in one armature), and a click picks a bone. With the **Selection tool** a drag on a bone, or on an
|
||||
//! instance a bone moves, poses the armature by inverse kinematics (the point grabbed follows the
|
||||
//! pointer); a drag on the root instance, the root's joints (or a shape armature's shape) moves
|
||||
//! the whole armature. Each drag is one undo step, and the
|
||||
@@ -86,18 +87,12 @@ fn segment_distance(p: Pos2, a: Pos2, b: Pos2) -> f32 {
|
||||
(a + ab * t).distance(p)
|
||||
}
|
||||
|
||||
/// The topmost symbol instance under stage point `sp` other than `skip`, on an unlocked layer:
|
||||
/// its layer and id.
|
||||
fn instance_at(app: &App, sp: Vec2, slop: f32, skip: Option<ElementId>) -> Option<(LayerId, ElementId)> {
|
||||
item_at(app, sp, slop, skip, |_, e| matches!(e.kind, ElementKind::Symbol { .. }))
|
||||
}
|
||||
|
||||
/// What a Bone tool press can start a bone on: an instance, a shape on a normal layer, or a
|
||||
/// shape armature's shape.
|
||||
/// shape of an armature.
|
||||
fn rig_target(l: &Layer, e: &Element) -> bool {
|
||||
match e.kind {
|
||||
ElementKind::Symbol { .. } => true,
|
||||
ElementKind::Shape(_) => l.kind == LayerKind::Normal || l.armature.as_ref().and_then(|a| a.skin_shape()) == Some(e.id),
|
||||
ElementKind::Shape(_) => l.kind == LayerKind::Normal || l.armature.as_ref().is_some_and(|a| a.contains(e.id)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -136,14 +131,15 @@ pub fn select(app: &mut App, layer: LayerId, bone: Option<BoneId>) {
|
||||
if bone.is_some() && app.s.layer != layer {
|
||||
app.run("layer.select", json!({"layer": layer.0}));
|
||||
}
|
||||
let child = bone.and_then(|b| app.s.timeline().layer(layer).and_then(|l| l.armature.as_ref()).filter(|a| a.skin.is_none()).and_then(|a| a.bone(b)).map(|b| b.child));
|
||||
if let Some(child) = child {
|
||||
// (A bone inside a shape moves points, and a bone into a whole shape has no such look.)
|
||||
let child = bone.and_then(|b| app.s.timeline().layer(layer).and_then(|l| l.armature.as_ref()).and_then(|a| a.bone(b)).filter(|b| b.shape.is_none()).map(|b| b.child));
|
||||
if let Some(child) = child.filter(|c| is_shape(app, *c) == Some(false)) {
|
||||
app.run("element.select", json!({"ids": [child.0], "layer": layer.0}));
|
||||
}
|
||||
}
|
||||
|
||||
/// A Bone tool drag starting at screen point `press`: a new bone from the instance there (or
|
||||
/// from the end of the bone there).
|
||||
/// A Bone tool drag starting at screen point `press`: a new bone from the instance or shape
|
||||
/// there, or from the end of the bone there.
|
||||
pub fn drag_start(app: &mut App, xf: Xf, press: Pos2) -> Drag {
|
||||
let sp = xf.to_stage(press);
|
||||
if let Some((layer, id, Part::End)) = hit(app, xf, press)
|
||||
@@ -152,61 +148,91 @@ pub fn drag_start(app: &mut App, xf: Xf, press: Pos2) -> Drag {
|
||||
{
|
||||
// A chain joins end to start.
|
||||
let head = pos2(b.tail.x, b.tail.y);
|
||||
return Drag::Bone { from: child, head, cur: head };
|
||||
return Drag::Bone { from: child, parent: Some(id), head, cur: head };
|
||||
}
|
||||
match item_at(app, sp, 3.0 / xf.zoom.max(1e-3), None, rig_target) {
|
||||
Some((_, from)) => Drag::Bone { from, head: pos2(sp.x, sp.y), cur: pos2(sp.x, sp.y) },
|
||||
Some((_, from)) => Drag::Bone { from, parent: None, head: pos2(sp.x, sp.y), cur: pos2(sp.x, sp.y) },
|
||||
None => {
|
||||
app.status_ok(tr!("Start a bone inside a shape, or on a symbol instance and drag to the instance it moves."));
|
||||
app.status_ok(tr!("Start a bone inside a shape, or on a symbol instance and drag to the instance or shape it moves."));
|
||||
Drag::None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a bone drawn from `from` goes into: a shape armature's bone it continues, or a shape.
|
||||
enum InShape {
|
||||
Parent(BoneId),
|
||||
Shape(ElementId),
|
||||
}
|
||||
|
||||
fn in_shape(app: &App, from: ElementId) -> Option<InShape> {
|
||||
let tl = app.s.timeline();
|
||||
for l in tl.layers.iter().filter(|l| l.kind == LayerKind::Armature) {
|
||||
let Some(a) = l.armature.as_deref().filter(|a| a.skin.is_some()) else { continue };
|
||||
if let Some(b) = a.bone_into(from) {
|
||||
return Some(InShape::Parent(b.id));
|
||||
}
|
||||
}
|
||||
tl.layers.iter().find_map(|l| {
|
||||
/// What kind of element `id` is at the playhead: `Some(true)` a shape, `Some(false)` a symbol
|
||||
/// instance, `None` neither (a joint node inside a shape is no element).
|
||||
fn is_shape(app: &App, id: ElementId) -> Option<bool> {
|
||||
app.s.timeline().layers.iter().find_map(|l| {
|
||||
let (_, els) = evaluate_layer_elements(l, app.s.frame)?;
|
||||
els.iter().find(|e| e.id == from && matches!(e.kind, ElementKind::Shape(_))).map(|_| InShape::Shape(from))
|
||||
els.iter().find(|e| e.id == id).and_then(|e| match e.kind {
|
||||
ElementKind::Shape(_) => Some(true),
|
||||
ElementKind::Symbol { .. } => Some(false),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Ends a Bone tool drag: adds the bone if it ends on another instance, or inside a shape
|
||||
/// where it was released.
|
||||
pub fn drag_end(app: &mut App, xf: Xf, from: ElementId, head: Pos2, cur: Pos2) {
|
||||
/// Selects the new bone a command made and says what to do next.
|
||||
fn added(app: &mut App, v: &serde_json::Value, hint: String) {
|
||||
let (layer, bone) = (LayerId(v["layer"].as_u64().unwrap_or(0)), v["bone"].as_u64().map(BoneId));
|
||||
select(app, layer, bone);
|
||||
app.status_ok(hint);
|
||||
}
|
||||
|
||||
/// Ends a Bone tool drag that began on `from` (an instance, a shape, or with `parent` the end
|
||||
/// of that bone) at joint `head`: the bone goes to the instance or shape under the release, or
|
||||
/// stays inside the shape it began in. Instances and shapes mix in one armature (ADR 0098):
|
||||
///
|
||||
/// * from an instance (or the end of a bone that moves one): the bone moves the instance or
|
||||
/// shape it is released over;
|
||||
/// * from inside a shape: the bone is drawn inside it, ending where it is released;
|
||||
/// * from the end of a bone inside a shape, or of a bone that ends on a shape: released over a
|
||||
/// symbol instance that is in no armature yet, the bone carries that instance; anywhere else
|
||||
/// it continues inside the shape.
|
||||
pub fn drag_end(app: &mut App, xf: Xf, from: ElementId, parent: Option<BoneId>, head: Pos2, cur: Pos2) {
|
||||
let tail = Vec2::new(cur.x, cur.y);
|
||||
if let Some(target) = in_shape(app, from) {
|
||||
let p = match target {
|
||||
InShape::Parent(b) => json!({"parent": b.0, "tail": [tail.x, tail.y]}),
|
||||
InShape::Shape(id) => json!({"shape": id.0, "head": [head.x, head.y], "tail": [tail.x, tail.y]}),
|
||||
let slop = 3.0 / xf.zoom.max(1e-3);
|
||||
let undo = app.undo_key();
|
||||
// Whether the bone can go on inside a shape: it began in one, or on the end of a bone that
|
||||
// is inside one or ends on one.
|
||||
let node = parent.is_some() && is_shape(app, from).is_none();
|
||||
let shape = node || is_shape(app, from) == Some(true);
|
||||
let inside_hint = tr!("Added a bone inside the shape; its points follow the nearest bones. Drag a bone with the Selection tool to bend it, or adjust the points with the Bind tool. {undo} to undo.", undo = undo);
|
||||
if shape {
|
||||
// An instance on a normal layer under the release joins the armature on this bone.
|
||||
let free = |l: &Layer, e: &Element| l.kind == LayerKind::Normal && matches!(e.kind, ElementKind::Symbol { .. });
|
||||
if let Some(p) = parent
|
||||
&& let Some((_, to)) = item_at(app, tail, slop, Some(from), |_, e| matches!(e.kind, ElementKind::Symbol { .. } | ElementKind::Shape(_))).filter(|(l, id)| app.s.timeline().layer(*l).is_some_and(|l| evaluate_layer_elements(l, app.s.frame).is_some_and(|(_, els)| els.iter().any(|e| e.id == *id && free(l, e)))))
|
||||
{
|
||||
if let Some(v) = app.run("bone.add", json!({"parent": p.0, "to": to.0, "tail": [tail.x, tail.y]})) {
|
||||
added(app, &v, tr!("Added a bone from the shape to the instance: it follows the shape's bones. Drag bones or the instance with the Selection tool to pose them together. {undo} to undo.", undo = undo));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let p = match parent {
|
||||
Some(b) => json!({"parent": b.0, "tail": [tail.x, tail.y]}),
|
||||
None => json!({"shape": from.0, "head": [head.x, head.y], "tail": [tail.x, tail.y]}),
|
||||
};
|
||||
if let Some(v) = app.run("bone.add_in_shape", p) {
|
||||
let (layer, bone) = (LayerId(v["layer"].as_u64().unwrap_or(0)), v["bone"].as_u64().map(BoneId));
|
||||
select(app, layer, bone);
|
||||
app.status_ok(tr!("Added a bone inside the shape; its points follow the nearest bones. Drag a bone with the Selection tool to bend it, or adjust the points with the Bind tool. {undo} to undo.", undo = app.undo_key()));
|
||||
added(app, &v, inside_hint);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some((_, to)) = instance_at(app, tail, 3.0 / xf.zoom.max(1e-3), Some(from)) else {
|
||||
app.status_ok(tr!("A bone ends on another symbol instance: release over the instance it should move."));
|
||||
let Some((_, to)) = item_at(app, tail, slop, Some(from), |_, e| matches!(e.kind, ElementKind::Symbol { .. } | ElementKind::Shape(_))) else {
|
||||
app.status_ok(tr!("A bone ends on another symbol instance or a shape: release over the one it should move."));
|
||||
return;
|
||||
};
|
||||
if let Some(v) = app.run("bone.add", json!({"from": from.0, "to": to.0, "head": [head.x, head.y], "tail": [tail.x, tail.y]})) {
|
||||
let (layer, bone) = (LayerId(v["layer"].as_u64().unwrap_or(0)), v["bone"].as_u64().map(BoneId));
|
||||
select(app, layer, bone);
|
||||
app.status_ok("Added a bone. Drag a bone or an instance with the Selection tool to pose the armature. Ctrl+Z to undo.");
|
||||
let p = match parent {
|
||||
Some(b) => json!({"parent": b.0, "to": to.0, "tail": [tail.x, tail.y]}),
|
||||
None => json!({"from": from.0, "to": to.0, "head": [head.x, head.y], "tail": [tail.x, tail.y]}),
|
||||
};
|
||||
if let Some(v) = app.run("bone.add", p) {
|
||||
let hint = if is_shape(app, to) == Some(true) {
|
||||
tr!("Added a bone to the shape: it moves as a whole. Drag from this bone's end inside the shape to give it bones of its own. {undo} to undo.", undo = undo)
|
||||
} else {
|
||||
tr!("Added a bone. Drag a bone or an instance with the Selection tool to pose the armature. {undo} to undo.", undo = undo)
|
||||
};
|
||||
added(app, &v, hint);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,3 +374,92 @@ fn wedge(painter: &egui::Painter, a: Pos2, b: Pos2, color: Color32, strong: bool
|
||||
painter.circle(a, JOINT, Color32::WHITE, edge);
|
||||
painter.circle(b, END, Color32::WHITE, edge);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anicraft_engine::Session;
|
||||
use anicraft_engine::doc::Document;
|
||||
|
||||
const XF: Xf = Xf { origin: Pos2::ZERO, zoom: 1.0 };
|
||||
|
||||
/// An app with a body shape standing on (300, 400) up to (300, 200) and a head instance
|
||||
/// centred on (300, 160), both on a normal layer: the body's and the head's ids.
|
||||
fn app() -> (App, u64, u64) {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = App::with_context(&ctx, Session::new(Document::default()), Some(std::path::PathBuf::from("unused.png")));
|
||||
let id = |v: Option<serde_json::Value>, k: &str| v.and_then(|v| v[k].as_u64()).expect("an id");
|
||||
let body = id(app.run("draw.path", json!({"d": "M280 400 L280 300 L280 200 L320 200 L320 300 L320 400 Z", "fill": "#335577", "object": true})), "element");
|
||||
app.run("draw.rect", json!({"x": 270, "y": 130, "w": 60, "h": 60, "fill": "#ffcc99"}));
|
||||
let head = id(app.run("modify.convert_to_symbol", json!({"name": "Head"})), "instance");
|
||||
app.tool = Tool::Bone;
|
||||
(app, body, head)
|
||||
}
|
||||
|
||||
/// Drags the Bone tool from stage point `a` to `b`.
|
||||
fn drag(app: &mut App, a: (f32, f32), b: (f32, f32)) {
|
||||
let d = drag_start(app, XF, pos2(a.0, a.1));
|
||||
let Drag::Bone { from, parent, head, .. } = d else { panic!("no bone starts at {a:?}: {d:?}") };
|
||||
drag_end(app, XF, from, parent, head, pos2(b.0, b.1));
|
||||
}
|
||||
|
||||
fn armature(app: &App) -> std::sync::Arc<anicraft_engine::doc::Armature> {
|
||||
app.s.timeline().layers.iter().find_map(|l| l.armature.clone()).expect("an armature")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chain_runs_from_a_shapes_bones_onto_an_instance() {
|
||||
let (mut app, body, head) = app();
|
||||
drag(&mut app, (300.0, 395.0), (300.0, 300.0));
|
||||
drag(&mut app, (300.0, 300.0), (300.0, 205.0));
|
||||
let arm = armature(&app);
|
||||
assert_eq!(arm.bones.len(), 2);
|
||||
assert!(arm.bones.iter().all(|b| b.shape.map(|s| s.0) == Some(body)), "both bones are inside the body");
|
||||
// From the neck joint, released over the head: the head joins on that joint.
|
||||
drag(&mut app, (300.0, 205.0), (300.0, 160.0));
|
||||
let arm = armature(&app);
|
||||
assert_eq!(arm.bones.len(), 3);
|
||||
let neck = &arm.bones[2];
|
||||
assert_eq!((neck.shape, neck.child.0, neck.parent), (None, head, arm.bones[1].child), "it starts on the joint node and moves the head");
|
||||
assert!(arm.is_mixed());
|
||||
assert_eq!(app.bone_sel, Some(neck.id), "the new bone is picked");
|
||||
assert!(app.s.selection.contains(app.s.layer, ElementId(head)), "and the instance it moves, for its look in Properties");
|
||||
// Dragging the head with the Selection tool bends the body under it.
|
||||
app.tool = Tool::Select;
|
||||
let before = app.s.doc.clone();
|
||||
let mut d = select_drag_start(&mut app, XF, pos2(300.0, 160.0)).expect("a pose drag");
|
||||
assert!(matches!(d, Drag::BonePose { .. }));
|
||||
drag_to(&mut app, &mut d, pos2(360.0, 200.0));
|
||||
app.s.end_gesture();
|
||||
assert_ne!(app.s.doc, before);
|
||||
app.s.undo().expect("one step");
|
||||
assert_eq!(app.s.doc, before);
|
||||
// From the neck joint again, released on the empty stage: a bone inside the body.
|
||||
app.tool = Tool::Bone;
|
||||
drag(&mut app, (300.0, 205.0), (340.0, 230.0));
|
||||
let arm = armature(&app);
|
||||
assert_eq!(arm.bones.last().and_then(|b| b.shape).map(|s| s.0), Some(body));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chain_runs_from_an_instance_into_a_shape() {
|
||||
let (mut app, body, head) = app();
|
||||
// From the head, released over the body: the body hangs from the head as a whole.
|
||||
drag(&mut app, (300.0, 160.0), (300.0, 210.0));
|
||||
let arm = armature(&app);
|
||||
assert_eq!(arm.bones.len(), 1);
|
||||
assert_eq!((arm.bones[0].parent.0, arm.bones[0].child.0, arm.bones[0].shape), (head, body, None));
|
||||
assert!(arm.skins.is_empty());
|
||||
// From that bone's end, on inside the body: the body's first bone, and its skin.
|
||||
drag(&mut app, (300.0, 210.0), (300.0, 300.0));
|
||||
let arm = armature(&app);
|
||||
assert_eq!(arm.bones.len(), 2);
|
||||
assert_eq!((arm.bones[1].shape.map(|s| s.0), arm.bones[1].parent.0), (Some(body), body));
|
||||
assert_eq!(arm.skins.len(), 1);
|
||||
assert!(arm.is_mixed());
|
||||
// A drag that begins inside the body draws a bone inside it, wherever it ends.
|
||||
drag(&mut app, (300.0, 380.0), (300.0, 160.0));
|
||||
assert_eq!(armature(&app).bones.len(), 3);
|
||||
assert_eq!(armature(&app).bones[2].shape.map(|s| s.0), Some(body));
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -127,7 +127,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
}
|
||||
let mut open = true;
|
||||
let at = ctx.content_rect().right_top() + vec2(-620.0, 90.0);
|
||||
let shown = egui::Window::new(tr!("Brush Library")).id(egui::Id::new("brush_library")).open(&mut open).default_pos(at).default_width(300.0).resizable(true).collapsible(false).show(ctx, |ui| panel(app, ui));
|
||||
let shown = crate::windows::new(ctx, tr!("Brush Library")).id(egui::Id::new("brush_library")).open(&mut open).default_pos(at).default_width(300.0).resizable(true).collapsible(false).show(ctx, |ui| panel(app, ui));
|
||||
a11y::name_title_bar(&shown, tr!("Brush Library"));
|
||||
app.brush_lib.open &= open;
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
|
||||
folders.sort_by_key(|(_, p)| p.to_lowercase());
|
||||
let (mut submit, mut cancel) = (false, false);
|
||||
let title = tr!("Convert to Symbol");
|
||||
egui::Window::new(title).id(egui::Id::new("convert_symbol")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
crate::windows::new(ctx, title).id(egui::Id::new("convert_symbol")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
ui.set_min_width(380.0);
|
||||
form_row(ui, FORM_LABEL_DOCK, tr!("Name"), |ui| {
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(f32::INFINITY)).named(tr!("Symbol name"));
|
||||
|
||||
+3
-3
@@ -390,7 +390,7 @@ fn preferences(app: &mut App, ctx: &egui::Context) {
|
||||
let mut about_act: Option<crate::desktop_ui::Act> = None;
|
||||
let to_about = std::mem::take(&mut app.prefs_to_about);
|
||||
let title = if crate::platform::OS == crate::platform::Os::Mac { tr!("Settings") } else { tr!("Preferences") };
|
||||
let shown = egui::Window::new(title)
|
||||
let shown = crate::windows::new(ctx, title)
|
||||
// An id of its own: the window keeps its place when the language changes.
|
||||
.id(egui::Id::new("prefs_window"))
|
||||
.open(&mut open)
|
||||
@@ -697,7 +697,7 @@ fn licenses(app: &mut App, ctx: &egui::Context) {
|
||||
}
|
||||
let mut open = true;
|
||||
let title = tr!("Licenses & Notices");
|
||||
let shown = egui::Window::new(title)
|
||||
let shown = crate::windows::new(ctx, title)
|
||||
.id(egui::Id::new("licenses_window"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
@@ -904,7 +904,7 @@ fn shortcut_sheet(app: &mut App, ctx: &egui::Context) {
|
||||
let capture = app.key_capture;
|
||||
let changed = app.prefs.shortcuts.len();
|
||||
let title = tr!("Keyboard Shortcuts");
|
||||
let shown = egui::Window::new(title)
|
||||
let shown = crate::windows::new(ctx, title)
|
||||
.id(egui::Id::new("shortcuts_window"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
|
||||
+1
-1
@@ -112,7 +112,7 @@ fn inside(app: &mut App, ctx: &egui::Context, f: &Float, layout: &Layout, acts:
|
||||
let title = crate::i18n::t(p.label());
|
||||
let mut open = true;
|
||||
let size = vec2(f.size[0], f.size[1]);
|
||||
let mut w = egui::Window::new(title).id(id).open(&mut open).collapsible(false).resizable(true).default_size(size).min_size([crate::dock::MIN_FLOAT, 120.0]);
|
||||
let mut w = crate::windows::new(ctx, title).id(id).open(&mut open).collapsible(false).resizable(true).default_size(size).min_size([crate::dock::MIN_FLOAT, 120.0]);
|
||||
let at = f.at.map_or_else(|| ctx.content_rect().center() - size * 0.5, |a| pos2(a[0], a[1]));
|
||||
w = if app.dock_view.placed.insert(f.id) { w.current_pos(at) } else { w.default_pos(at) };
|
||||
let shown = w.show(ctx, |ui| {
|
||||
|
||||
+1
-1
@@ -304,7 +304,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(ease) = ease_now(app, &ed) else { return };
|
||||
let mut open = true;
|
||||
let title = tr!("Custom Ease");
|
||||
let shown = egui::Window::new(title)
|
||||
let shown = crate::windows::new(ctx, title)
|
||||
.id(egui::Id::new("ease_editor"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
|
||||
+1
-1
@@ -88,7 +88,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
let Some(t) = target(app, &ed) else { return };
|
||||
let mut open = true;
|
||||
let title = tr!("Edit Envelope — {name}", name = t.sound.name);
|
||||
let shown = egui::Window::new(title.clone())
|
||||
let shown = crate::windows::new(ctx, title.clone())
|
||||
.id(egui::Id::new("envelope_editor"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
|
||||
+1
-1
@@ -243,7 +243,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
}
|
||||
let mut open = app.find.open;
|
||||
let at = ctx.content_rect().right_top() + vec2(-720.0, 110.0);
|
||||
let shown = egui::Window::new(tr!("Find and Replace")).id(egui::Id::new("find_replace")).open(&mut open).default_pos(at).default_width(400.0).resizable(true).collapsible(false).show(ctx, |ui| panel(app, ui));
|
||||
let shown = crate::windows::new(ctx, tr!("Find and Replace")).id(egui::Id::new("find_replace")).open(&mut open).default_pos(at).default_width(400.0).resizable(true).collapsible(false).show(ctx, |ui| panel(app, ui));
|
||||
a11y::name_title_bar(&shown, tr!("Find and Replace"));
|
||||
app.find.open = open;
|
||||
}
|
||||
|
||||
+33
-1
@@ -1,6 +1,8 @@
|
||||
//! Enforces docs/ui-guidelines.md: typography and colour come from `theme`, never raw values.
|
||||
|
||||
const SOURCES: [(&str, &str); 31] = [
|
||||
const SOURCES: [(&str, &str); 33] = [
|
||||
("rich_edit.rs", include_str!("rich_edit.rs")),
|
||||
("windows.rs", include_str!("windows.rs")),
|
||||
("ease_editor.rs", include_str!("ease_editor.rs")),
|
||||
("colour.rs", include_str!("colour.rs")),
|
||||
("drop.rs", include_str!("drop.rs")),
|
||||
@@ -196,3 +198,33 @@ fn data_roles_are_monospace_and_prose_roles_are_not() {
|
||||
assert_eq!(font(t).family, FontFamily::Proportional, "{t:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every floating window comes from `crate::windows::new`, which keeps it below the menu bar
|
||||
/// (a dialog's title bar must never cover File, Edit, View).
|
||||
#[test]
|
||||
fn floating_windows_stay_below_the_menu_bar() {
|
||||
fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
|
||||
for e in std::fs::read_dir(dir).unwrap().flatten() {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
walk(&p, out);
|
||||
} else if p.extension().is_some_and(|x| x == "rs") {
|
||||
out.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
walk(&std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut files);
|
||||
assert!(files.len() > 40);
|
||||
let opened = ["egui::Window::new(", concat!("Window", "::new(")];
|
||||
for f in files {
|
||||
let name = f.file_name().unwrap().to_string_lossy().to_string();
|
||||
if name == "windows.rs" || name.ends_with("tests.rs") {
|
||||
continue;
|
||||
}
|
||||
let src = std::fs::read_to_string(&f).unwrap();
|
||||
for o in opened {
|
||||
assert!(!src.contains(o), "{name} opens a window with {o}; use crate::windows::new (kept below the menu bar)");
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -98,7 +98,7 @@ pub fn window(app: &mut App, ctx: &egui::Context) {
|
||||
};
|
||||
let fixed = matches!(kind, LayerKind::Folder | LayerKind::Camera | LayerKind::Armature);
|
||||
let (mut submit, mut cancel) = (false, false);
|
||||
egui::Window::new(tr!("Layer Properties")).id(egui::Id::new("layer_props")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
crate::windows::new(ctx, tr!("Layer Properties")).id(egui::Id::new("layer_props")).collapsible(false).resizable(false).anchor(egui::Align2::CENTER_CENTER, [0.0, -80.0]).show(ctx, |ui| {
|
||||
ui.set_min_width(420.0);
|
||||
form_row(ui, FORM_LABEL_DIALOG, tr!("Name"), |ui| {
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut d.name).desired_width(f32::INFINITY)).named(tr!("Layer name"));
|
||||
|
||||
+2
-2
@@ -176,7 +176,7 @@ fn save_window(app: &mut App, ctx: &egui::Context) {
|
||||
let mut save = false;
|
||||
let mut cancel = false;
|
||||
let title = tr!("Save As Command");
|
||||
let shown = egui::Window::new(title).id(egui::Id::new("save_as_command")).open(&mut open).collapsible(false).resizable(false).pivot(egui::Align2::CENTER_CENTER).default_pos(ctx.content_rect().center()).show(ctx, |ui| {
|
||||
let shown = crate::windows::new(ctx, title).id(egui::Id::new("save_as_command")).open(&mut open).collapsible(false).resizable(false).pivot(egui::Align2::CENTER_CENTER).default_pos(ctx.content_rect().center()).show(ctx, |ui| {
|
||||
ui.set_min_width(380.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(text(Type::Label, tr!("Name")));
|
||||
@@ -300,7 +300,7 @@ fn manage_window(app: &mut App, ctx: &egui::Context) {
|
||||
let mut open = true;
|
||||
let mut acts: Vec<Act> = Vec::new();
|
||||
let title = tr!("Manage Saved Commands");
|
||||
let shown = egui::Window::new(title).id(egui::Id::new("manage_saved_commands")).open(&mut open).collapsible(false).resizable(false).default_width(760.0).show(ctx, |ui| {
|
||||
let shown = crate::windows::new(ctx, title).id(egui::Id::new("manage_saved_commands")).open(&mut open).collapsible(false).resizable(false).default_width(760.0).show(ctx, |ui| {
|
||||
ui.set_min_width(720.0);
|
||||
let list = app.macros.list.clone();
|
||||
if list.is_empty() {
|
||||
|
||||
+3
-1
@@ -78,6 +78,7 @@ mod macros_ui;
|
||||
mod plugins_ui;
|
||||
mod prefs;
|
||||
mod recent;
|
||||
mod rich_edit;
|
||||
mod rulers;
|
||||
mod scale_grid;
|
||||
mod shape_envelope;
|
||||
@@ -95,6 +96,7 @@ mod timeline;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod web;
|
||||
mod widthtool;
|
||||
mod windows;
|
||||
mod workspaces_window;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -270,7 +272,7 @@ fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
|
||||
/// `--help` (the console's text, in English).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// i18n-exempt: the --help console text
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme graphite|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|helpbone|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|rulers|editguides|editgrid|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|polystar|paintinside|drawingedit|shapeenvelope|brushlibrary|brushcurve|paintbrush|eraser|erasing|erasemerge|tiltbrush|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|bones|springbones|shapebones|shapeweights|mixedbones|layerdepth|layerdepthview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|richtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|ease|easepreset|plugineases|pluginexport|pluginexportwindow|library|librarymenu|libraryfolders|colour|layerprops|frameview|layercolour|timelinepolish|dock|dockicons|floattabs|docknarrow|workspaces|animator|designer|gradient|gradientbucket|swatches|swatchpanel]\n\
|
||||
--renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\
|
||||
--open shows a panel at start (handy with --screenshot for visual checks)\n\
|
||||
--shot-width scales the screenshot down to this width (the user guide's pictures)\n\
|
||||
|
||||
+131
-9
@@ -747,8 +747,15 @@ pub(crate) fn properties(app: &mut App, ui: &mut egui::Ui) {
|
||||
// The selection on every layer (ADR 0044).
|
||||
let sel: Vec<_> = app.s.selected_elements().into_iter().map(|(_, e)| e).collect();
|
||||
|
||||
// ---- while typing on the stage: the selected characters' style (ADR 0085) ----
|
||||
app.text_props_rect = None;
|
||||
if let Some(title) = app.text_edit.as_ref().map(crate::rich_edit::title) {
|
||||
section(ui, "prop_text_selection", Section::Rule, &title, None, |ui| crate::rich_edit::selection_rows(app, ui));
|
||||
}
|
||||
// ---- tool options first while a drawing tool is in hand: they're what you reach for ----
|
||||
if matches!(app.tool, Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Text | Tool::Pencil | Tool::Brush | Tool::PaintBrush | Tool::Eraser | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper) {
|
||||
// (While typing, the selected characters' section above takes the Text tool's place.)
|
||||
let typing = app.text_edit.is_some();
|
||||
if (!typing || app.tool != Tool::Text) && matches!(app.tool, Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Text | Tool::Pencil | Tool::Brush | Tool::PaintBrush | Tool::Eraser | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper) {
|
||||
let title = tr!("{tool} tool", tool = crate::i18n::t(app.tool.label()));
|
||||
section(ui, "prop_tool", Section::Rule, &title, None, |ui| tool_props(app, ui));
|
||||
}
|
||||
@@ -1182,13 +1189,32 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E
|
||||
// A field's lines wrap by its line type, at its box (rows above); static text by width.
|
||||
let mut width = t.width;
|
||||
let wrap = if t.field.is_some() { None } else { Some(&mut width) };
|
||||
if let Some((label, p)) = text_style_rows(app, ui, &mut st, wrap) {
|
||||
// The whole block's characters: what they share, and "mixed" where they differ.
|
||||
let n = t.char_count();
|
||||
let sum = anicraft_engine::doc::rich_text::summarize(&t.styled_runs(), 0, n);
|
||||
let paras = t.paragraph_styles();
|
||||
let p0 = paras.first().copied().unwrap_or_default();
|
||||
let mx = TextMixed {
|
||||
font: sum.font.is_none(),
|
||||
size: sum.size.is_none(),
|
||||
color: sum.color.is_none(),
|
||||
bold: sum.bold.is_none(),
|
||||
italic: sum.italic.is_none(),
|
||||
letter_spacing: sum.letter_spacing.is_none(),
|
||||
align: paras.iter().any(|p| p.align != p0.align),
|
||||
line_spacing: paras.iter().any(|p| p.line_spacing != p0.line_spacing),
|
||||
};
|
||||
if let Some((label, p)) = text_style_rows(app, ui, &mut st, wrap, Some(&mx)) {
|
||||
live(app, label, "text.edit", p);
|
||||
}
|
||||
let mut extra = TextExtra { shift: sum.shift, underline: sum.underline, url: sum.url.clone(), indent: p0.indent, left_margin: p0.left_margin, right_margin: p0.right_margin, layout_mixed: paras.iter().any(|p| p.indent != p0.indent || p.left_margin != p0.left_margin || p.right_margin != p0.right_margin) };
|
||||
if let Some((label, p)) = text_more_rows(ui, &mut extra) {
|
||||
live(app, label, "text.edit", p);
|
||||
}
|
||||
row_prose(ui, tr!("Text"), |ui| {
|
||||
if ui.button(tr!("Edit Text")).on_hover_text(tr!("Type on the stage (or double-click the text)")).clicked() {
|
||||
if ui.button(tr!("Edit Text")).on_hover_text(tr!("Type on the stage (or double-click the text); select characters to style them on their own")).clicked() {
|
||||
let at = e.transform.apply(anicraft_engine::geom::Vec2::ZERO);
|
||||
app.text_edit = Some(crate::app::TextEditing { at: pos2(at.x, at.y), element: Some(e.id), text: t.text.clone(), original: t.text.clone(), focus: true });
|
||||
app.text_edit = Some(crate::app::TextEditing::new(pos2(at.x, at.y), Some(e.id), Some(t), &app.s.text_style));
|
||||
}
|
||||
});
|
||||
text_path_rows(app, ui, e, t);
|
||||
@@ -2036,10 +2062,101 @@ fn ramp_editor(ui: &mut egui::Ui, fname: &str, stops: &mut Vec<anicraft_engine::
|
||||
ui.data_mut(|d| d.insert_temp(sel_id, sel));
|
||||
}
|
||||
|
||||
/// Which of the text style rows' values differ across the characters (or paragraphs) they show
|
||||
/// (ADR 0085): those rows show the first one's and say "mixed".
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct TextMixed {
|
||||
pub font: bool,
|
||||
pub size: bool,
|
||||
pub color: bool,
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
pub letter_spacing: bool,
|
||||
pub align: bool,
|
||||
pub line_spacing: bool,
|
||||
}
|
||||
|
||||
/// "mixed" after a text row whose characters differ.
|
||||
fn mixed_chars(ui: &mut egui::Ui, differs: bool) {
|
||||
if differs {
|
||||
ui.label(text(Type::Caption, tr!("mixed")).color(T.text_faint)).on_hover_text(tr!("The characters differ here; it shows the first one's. A change applies to all of them"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The rest of a text's character and paragraph style (ADR 0085): baseline shift, underline,
|
||||
/// link, indent and margins. `None` values are mixed.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct TextExtra {
|
||||
pub shift: Option<anicraft_engine::doc::BaselineShift>,
|
||||
pub underline: Option<bool>,
|
||||
pub url: Option<String>,
|
||||
pub indent: f32,
|
||||
pub left_margin: f32,
|
||||
pub right_margin: f32,
|
||||
/// The paragraphs' indents or margins differ.
|
||||
pub layout_mixed: bool,
|
||||
}
|
||||
|
||||
/// Baseline shift, underline, link, indent and margin rows. Returns the edit made, as params
|
||||
/// (one key per change), with an undo label.
|
||||
pub fn text_more_rows(ui: &mut egui::Ui, x: &mut TextExtra) -> Option<(&'static str, Value)> {
|
||||
use anicraft_engine::doc::BaselineShift;
|
||||
let mut out: Option<(&'static str, Value)> = None;
|
||||
row_prose(ui, tr!("Position"), |ui| {
|
||||
let label = |s: BaselineShift| match s {
|
||||
BaselineShift::Normal => tr!("Normal"),
|
||||
BaselineShift::Superscript => tr!("Superscript"),
|
||||
BaselineShift::Subscript => tr!("Subscript"),
|
||||
};
|
||||
let shown = x.shift.map_or_else(|| tr!("mixed").to_string(), |s| label(s).to_string());
|
||||
egui::ComboBox::from_id_salt("text_shift").selected_text(shown).show_ui(ui, |ui| {
|
||||
for s in BaselineShift::ALL {
|
||||
if ui.selectable_label(x.shift == Some(s), label(s)).clicked() {
|
||||
x.shift = Some(s);
|
||||
out = Some((tr_noop!("Superscript and subscript"), json!({"shift": s.key()})));
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Character position"));
|
||||
// The letter on the button is the usual underline mark.
|
||||
let on = x.underline == Some(true);
|
||||
if ui.selectable_label(on, text(Type::Body, "U").underline()).named(tr!("Underline")).on_hover_text(tr!("Underline")).clicked() {
|
||||
x.underline = Some(!on);
|
||||
out = Some((tr_noop!("Underline"), json!({"underline": !on})));
|
||||
}
|
||||
mixed_chars(ui, x.underline.is_none());
|
||||
});
|
||||
row_prose(ui, tr!("Link"), |ui| {
|
||||
let mut url = x.url.clone().unwrap_or_default();
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut url).desired_width(170.0).font(crate::theme::font(Type::Path)).hint_text(if x.url.is_none() { tr!("mixed") } else { tr!("https://…") })).named(tr!("Link")).on_hover_text(tr!("Where the characters link to in SVG and other exports; empty for no link"));
|
||||
if r.lost_focus() && x.url.as_deref() != Some(url.trim()) {
|
||||
x.url = Some(url.trim().to_string());
|
||||
out = Some((tr_noop!("Text link"), json!({"url": url.trim()})));
|
||||
}
|
||||
});
|
||||
row(ui, tr!("Indent"), |ui| {
|
||||
if ui.add(egui::DragValue::new(&mut x.indent).suffix(" px").speed(0.5).range(-1000.0..=1000.0).max_decimals(1)).named(tr!("First-line indent")).on_hover_text(tr!("First-line indent")).changed() {
|
||||
out = Some((tr_noop!("Indent"), json!({"indent": x.indent})));
|
||||
}
|
||||
mixed_chars(ui, x.layout_mixed);
|
||||
});
|
||||
row(ui, tr!("Margins"), |ui| {
|
||||
if ui.add(egui::DragValue::new(&mut x.left_margin).prefix(format!("{} ", tr!("Left"))).suffix(" px").speed(0.5).range(0.0..=1000.0).max_decimals(1)).named(tr!("Left margin")).changed() {
|
||||
out = Some((tr_noop!("Margins"), json!({"left_margin": x.left_margin})));
|
||||
}
|
||||
if ui.add(egui::DragValue::new(&mut x.right_margin).prefix(format!("{} ", tr!("Right"))).suffix(" px").speed(0.5).range(0.0..=1000.0).max_decimals(1)).named(tr!("Right margin")).changed() {
|
||||
out = Some((tr_noop!("Margins"), json!({"right_margin": x.right_margin})));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Font, size, style, colour, alignment and spacing rows for text. Returns the edit made, as
|
||||
/// `text.edit` params (one key per change), with an undo label.
|
||||
pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engine::cmds_text::TextStyle, width: Option<&mut Option<f32>>) -> Option<(&'static str, Value)> {
|
||||
pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engine::cmds_text::TextStyle, width: Option<&mut Option<f32>>, mx: Option<&TextMixed>) -> Option<(&'static str, Value)> {
|
||||
use anicraft_engine::doc::TextAlign;
|
||||
let mx = mx.copied().unwrap_or_default();
|
||||
let families = app.font_families.get_or_insert_with(|| anicraft_engine::text::Fonts::get().families().to_vec()).clone();
|
||||
let mut out: Option<(&'static str, Value)> = None;
|
||||
row_prose(ui, tr!("Font"), |ui| {
|
||||
@@ -2057,6 +2174,7 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Font"));
|
||||
mixed_chars(ui, mx.font);
|
||||
});
|
||||
row(ui, tr!("Size"), |ui| {
|
||||
if ui.add(egui::DragValue::new(&mut st.size).suffix(" px").speed(0.25).range(1.0..=2000.0).max_decimals(1)).named(tr!("Font size")).changed() {
|
||||
@@ -2067,6 +2185,7 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin
|
||||
st.color = Rgba::hex(u32::from(c[0]) << 16 | u32::from(c[1]) << 8 | u32::from(c[2]));
|
||||
out = Some((tr_noop!("Text colour"), json!({"color": hex(c)})));
|
||||
}
|
||||
mixed_chars(ui, mx.size || mx.color);
|
||||
});
|
||||
row_prose(ui, tr!("Style"), |ui| {
|
||||
// The letters on the two buttons are the usual bold and italic marks.
|
||||
@@ -2078,6 +2197,7 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin
|
||||
st.italic = !st.italic;
|
||||
out = Some((tr_noop!("Italic"), json!({"italic": st.italic})));
|
||||
}
|
||||
mixed_chars(ui, mx.bold || mx.italic);
|
||||
ui.separator();
|
||||
for (a, label, name, key) in [(TextAlign::Left, tr!("Left"), tr!("Align left"), "left"), (TextAlign::Center, tr!("Centre"), tr!("Align centre"), "center"), (TextAlign::Right, tr!("Right"), tr!("Align right"), "right")] {
|
||||
if ui.selectable_label(st.align == a, label).named(name).on_hover_text(name).clicked() {
|
||||
@@ -2085,6 +2205,7 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin
|
||||
out = Some((tr_noop!("Text alignment"), json!({"align": key})));
|
||||
}
|
||||
}
|
||||
mixed_chars(ui, mx.align);
|
||||
});
|
||||
row(ui, tr!("Spacing"), |ui| {
|
||||
if ui.add(egui::DragValue::new(&mut st.letter_spacing).prefix(format!("{} ", tr!("Letters"))).suffix(" px").speed(0.1).range(-1000.0..=1000.0).max_decimals(1)).named(tr!("Letter spacing")).changed() {
|
||||
@@ -2093,6 +2214,7 @@ pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engin
|
||||
if ui.add(egui::DragValue::new(&mut st.line_spacing).prefix(format!("{} ", tr!("Lines"))).suffix(" px").speed(0.1).range(-1000.0..=1000.0).max_decimals(1)).named(tr!("Line spacing")).changed() {
|
||||
out = Some((tr_noop!("Line spacing"), json!({"line_spacing": st.line_spacing})));
|
||||
}
|
||||
mixed_chars(ui, mx.letter_spacing || mx.line_spacing);
|
||||
});
|
||||
if let Some(width) = width {
|
||||
row(ui, tr!("Width"), |ui| {
|
||||
@@ -2294,7 +2416,7 @@ fn bone_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::BoneId
|
||||
}
|
||||
});
|
||||
// A bone inside a shape (ADR 0071): how many of the shape's points it moves.
|
||||
let skin = layer.armature.as_ref().and_then(|a| a.skin.as_ref()).map(|k| (k.points.iter().filter(|p| p.weight(id) > 0.0).count(), k.points.len()));
|
||||
let skin = layer.armature.as_ref().and_then(|a| a.skin_of(id).map(|k| (a.bound_count(id), k.points.len())));
|
||||
if let Some((mine, total)) = skin {
|
||||
row(ui, tr!("Points"), |ui| {
|
||||
ui.label(text(Type::Data, format!("{mine} / {total}"))).on_hover_text(tr!("How many of the shape's points this bone moves. Adjust them with the Bind tool"));
|
||||
@@ -2310,7 +2432,7 @@ fn bone_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::BoneId
|
||||
app.run("bone.bind", json!({"bone": id.0, "mode": "auto"}));
|
||||
}
|
||||
}
|
||||
let hint = if skin.is_some() { tr!("Removes the bone and the bones below it; the shape's points follow the bones that are left") } else { tr!("Removes the bone and the bones below it; their instances stay where they are, on a layer of their own") };
|
||||
let hint = if skin.is_some() { tr!("Removes the bone and the bones below it; the shape's points follow the bones that are left") } else { tr!("Removes the bone and the bones below it; what they moved stays where it is, on a layer of its own") };
|
||||
if ui.button(tr!("Remove Bone")).named(tr!("Remove bone")).on_hover_text(hint).clicked() {
|
||||
app.request("bone.remove", json!({"bone": id.0}));
|
||||
}
|
||||
@@ -2360,7 +2482,7 @@ fn bind_props(app: &mut App, ui: &mut egui::Ui, id: anicraft_engine::doc::BoneId
|
||||
}
|
||||
});
|
||||
let arm = layer.armature.as_ref();
|
||||
let binding = arm.and_then(|a| a.skin.as_ref()).and_then(|k| k.points.get(point)).cloned().unwrap_or_default();
|
||||
let binding = arm.and_then(|a| a.skin_of(id)).and_then(|k| k.points.get(point)).cloned().unwrap_or_default();
|
||||
let mut w = binding.weight(id) * 100.0;
|
||||
row(ui, tr!("Weight"), |ui| {
|
||||
let r = ui.add(egui::DragValue::new(&mut w).suffix(" %").speed(0.5).range(0.0..=100.0).max_decimals(1)).named(tr!("Bone weight at the point"));
|
||||
@@ -2724,7 +2846,7 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
if app.tool == Tool::Text {
|
||||
// What new text gets (the last style used).
|
||||
let mut st = app.s.text_style.clone();
|
||||
if text_style_rows(app, ui, &mut st, None).is_some() {
|
||||
if text_style_rows(app, ui, &mut st, None, None).is_some() {
|
||||
app.s.text_style = st;
|
||||
}
|
||||
return;
|
||||
|
||||
@@ -172,7 +172,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
let (mut go, mut replace, mut close) = (false, false, false);
|
||||
let running = e.running.is_some();
|
||||
let at = ctx.content_rect().center() - egui::vec2(200.0, 180.0);
|
||||
let shown = egui::Window::new(title.clone()).id(egui::Id::new("plugin_export")).open(&mut open).default_pos(at).default_width(400.0).resizable(false).collapsible(false).show(ctx, |ui| {
|
||||
let shown = crate::windows::new(ctx, title.clone()).id(egui::Id::new("plugin_export")).open(&mut open).default_pos(at).default_width(400.0).resizable(false).collapsible(false).show(ctx, |ui| {
|
||||
let m = p.manifest();
|
||||
let by = [m.author.as_str(), m.version.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::<Vec<_>>().join(" · ");
|
||||
ui.label(text(Type::Caption, if by.is_empty() { tr!("Plug-in").to_string() } else { tr!("Plug-in · {by}", by = by) }));
|
||||
|
||||
+1
-1
@@ -288,7 +288,7 @@ fn manager(app: &mut App, ctx: &egui::Context) {
|
||||
let mut open = app.show_plugins;
|
||||
let mut action: Option<(&'static str, String)> = None;
|
||||
let title = tr!("Plug-ins");
|
||||
let shown = egui::Window::new(title).id(egui::Id::new("plugins_window")).open(&mut open).collapsible(false).resizable(false).default_width(560.0).show(ctx, |ui| {
|
||||
let shown = crate::windows::new(ctx, title).id(egui::Id::new("plugins_window")).open(&mut open).collapsible(false).resizable(false).default_width(560.0).show(ctx, |ui| {
|
||||
let list: Vec<Arc<Plugin>> = app.s.plugins.list().cloned().collect();
|
||||
if list.is_empty() {
|
||||
ui.label(text(Type::Label, tr!("No plug-ins installed yet. Plug-ins are WebAssembly (.wasm) files that add commands (generators, selection effects), export formats and eases.")));
|
||||
|
||||
@@ -287,7 +287,7 @@ fn settings_window(app: &mut App, ctx: &egui::Context) {
|
||||
}
|
||||
let mut open = true;
|
||||
let at = ctx.content_rect().center() - egui::vec2(330.0, 260.0);
|
||||
let shown = egui::Window::new(tr!("Publish Settings")).id(egui::Id::new("publish_settings")).open(&mut open).default_pos(at).default_width(660.0).resizable(true).collapsible(false).show(ctx, |ui| settings(app, ui));
|
||||
let shown = crate::windows::new(ctx, tr!("Publish Settings")).id(egui::Id::new("publish_settings")).open(&mut open).default_pos(at).default_width(660.0).resizable(true).collapsible(false).show(ctx, |ui| settings(app, ui));
|
||||
crate::a11y::name_title_bar(&shown, tr!("Publish Settings"));
|
||||
if !open {
|
||||
app.publish.open = false;
|
||||
@@ -695,7 +695,7 @@ fn progress_window(app: &mut App, ctx: &egui::Context) {
|
||||
let mut open = true;
|
||||
let title = if running { tr!("Publishing") } else { tr!("Publish report") };
|
||||
let at = ctx.content_rect().center() - egui::vec2(220.0, 160.0);
|
||||
let shown = egui::Window::new(title).id(egui::Id::new("publish_progress")).open(&mut open).default_pos(at).default_width(460.0).resizable(true).collapsible(false).show(ctx, |ui| {
|
||||
let shown = crate::windows::new(ctx, title).id(egui::Id::new("publish_progress")).open(&mut open).default_pos(at).default_width(460.0).resizable(true).collapsible(false).show(ctx, |ui| {
|
||||
if let Some(job) = &app.publish.job {
|
||||
job_rows(ui, job);
|
||||
} else if let Some(r) = &app.publish.report {
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
//! Styled text while typing on the stage (ADR 0085): the runs and paragraph styles of the text
|
||||
//! being typed, kept as the text changes (what is typed continues the style before it), shown
|
||||
//! in the editor with their colours, sizes, slant, underline and baseline shift; Properties
|
||||
//! styles the selected characters (or what is typed next, at a caret); copying and pasting
|
||||
//! inside AniCraft keeps styles, text from other apps comes in plain.
|
||||
//!
|
||||
//! Every style change on an existing block is one `text.edit` with the text, runs and
|
||||
//! paragraphs, so it shows on the stage the same frame and undoes as one step.
|
||||
|
||||
use crate::app::{App, TextEditing};
|
||||
use anicraft_engine::cmds_text::{CharPatch, ParaPatch};
|
||||
use anicraft_engine::doc::rich_text as rt;
|
||||
use anicraft_engine::doc::{BaselineShift, CharStyle, ElementId, ParagraphStyle, Rgba, TextBlock, TextRun};
|
||||
use egui::text::{LayoutJob, TextFormat};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Styled text copied from the stage editor: pasted back as the same text, it keeps its runs.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct StyledClip {
|
||||
pub text: String,
|
||||
pub runs: Vec<TextRun>,
|
||||
}
|
||||
|
||||
impl TextEditing {
|
||||
/// Editing `block` (or new text in `style`, when there is none) with its top-left at `at`.
|
||||
pub fn new(at: egui::Pos2, element: Option<ElementId>, block: Option<&TextBlock>, style: &anicraft_engine::cmds_text::TextStyle) -> TextEditing {
|
||||
let (text, runs, paras) = match block {
|
||||
Some(b) => (b.text.clone(), b.styled_runs(), b.paragraph_styles()),
|
||||
None => {
|
||||
let c = CharStyle { font: style.font.clone(), size: style.size, bold: style.bold, italic: style.italic, color: style.color, letter_spacing: style.letter_spacing, ..CharStyle::default() };
|
||||
(String::new(), vec![TextRun { chars: 0, style: c }], vec![ParagraphStyle { align: style.align, line_spacing: style.line_spacing, ..ParagraphStyle::default() }])
|
||||
}
|
||||
};
|
||||
let n = text.chars().count() as u32;
|
||||
TextEditing { at, element, original: text.clone(), last: text.clone(), text, runs, paras, sel: (n, n), pending: None, paste: None, focus: true }
|
||||
}
|
||||
|
||||
/// The selected characters, first to last.
|
||||
pub fn range(&self) -> (u32, u32) {
|
||||
(self.sel.0.min(self.sel.1), self.sel.0.max(self.sel.1))
|
||||
}
|
||||
|
||||
/// Follows a change of the text: the runs and paragraphs move with it, and a paste of
|
||||
/// styled text copied here takes its runs back.
|
||||
pub fn sync(&mut self) {
|
||||
if self.text == self.last {
|
||||
return;
|
||||
}
|
||||
let (start, old_end, new_end) = rt::diff_chars(&self.last, &self.text);
|
||||
let inserted: String = self.text.chars().skip(start as usize).take((new_end - start) as usize).collect();
|
||||
// A caret style picked before typing (Properties at a caret) styles what is typed.
|
||||
let typed = match (self.pending.take(), self.paste.take()) {
|
||||
(_, Some(clip)) if clip.text == inserted => clip.runs,
|
||||
(Some(style), _) => vec![TextRun { chars: new_end - start, style }],
|
||||
_ => vec![TextRun { chars: new_end - start, style: rt::style_at(&self.runs, start) }],
|
||||
};
|
||||
self.runs = rt::replace_runs(&self.runs, start, old_end, typed);
|
||||
self.paras = rt::edit_paragraphs(&self.paras, &self.last, start, old_end, &inserted);
|
||||
self.last = self.text.clone();
|
||||
}
|
||||
|
||||
/// What the selection shares (`None` attributes are mixed); at a caret, what typing gets.
|
||||
pub fn summary(&self) -> rt::StyleSummary {
|
||||
let (a, b) = self.range();
|
||||
match (&self.pending, a == b) {
|
||||
(Some(p), true) => rt::StyleSummary::of(p),
|
||||
_ => rt::summarize(&self.runs, a, b),
|
||||
}
|
||||
}
|
||||
|
||||
/// Restyles the selection (at a caret: what is typed next there).
|
||||
pub fn restyle(&mut self, patch: &CharPatch) {
|
||||
let (a, b) = self.range();
|
||||
if a == b {
|
||||
let mut s = self.pending.clone().unwrap_or_else(|| rt::style_at(&self.runs, a));
|
||||
patch.apply(&mut s);
|
||||
self.pending = Some(s);
|
||||
return;
|
||||
}
|
||||
self.runs = rt::restyle_runs(&self.runs, a, b, |s| patch.apply(s));
|
||||
}
|
||||
|
||||
/// Sets the layout of the paragraphs the selection touches.
|
||||
pub fn repara(&mut self, patch: &ParaPatch) {
|
||||
let (a, b) = self.range();
|
||||
let range = rt::paragraphs_in(&self.text, a, b);
|
||||
let n = rt::paragraph_count(&self.text);
|
||||
let fill = self.paras.last().copied().unwrap_or_default();
|
||||
self.paras.resize(n, fill);
|
||||
for (i, p) in self.paras.iter_mut().enumerate() {
|
||||
if range.contains(&i) {
|
||||
patch.apply(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `text.edit` params that set the block to what is being typed.
|
||||
pub fn edit_params(&self) -> Value {
|
||||
let runs: Vec<Value> = self.runs.iter().filter(|r| r.chars > 0).map(run_json).collect();
|
||||
let paras: Vec<Value> = self.paras.iter().map(para_json).collect();
|
||||
json!({"text": self.text, "runs": runs, "paragraphs": paras})
|
||||
}
|
||||
|
||||
/// The styled text of the selection (for Copy and Cut).
|
||||
pub fn clip(&self) -> Option<StyledClip> {
|
||||
let (a, b) = self.range();
|
||||
(a < b).then(|| StyledClip { text: self.text.chars().skip(a as usize).take((b - a) as usize).collect(), runs: rt::slice_runs(&self.runs, a, b) })
|
||||
}
|
||||
}
|
||||
|
||||
fn hex(c: Rgba) -> String {
|
||||
let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
format!("#{:02x}{:02x}{:02x}", b(c.r), b(c.g), b(c.b))
|
||||
}
|
||||
|
||||
fn run_json(r: &TextRun) -> Value {
|
||||
let s = &r.style;
|
||||
json!({"chars": r.chars, "font": s.font, "size": s.size, "bold": s.bold, "italic": s.italic, "color": hex(s.color), "letter_spacing": s.letter_spacing, "shift": s.shift.key(), "underline": s.underline, "url": s.url})
|
||||
}
|
||||
|
||||
fn para_json(p: &ParagraphStyle) -> Value {
|
||||
let align = match p.align {
|
||||
anicraft_engine::doc::TextAlign::Left => "left",
|
||||
anicraft_engine::doc::TextAlign::Center => "center",
|
||||
anicraft_engine::doc::TextAlign::Right => "right",
|
||||
};
|
||||
json!({"align": align, "indent": p.indent, "left_margin": p.left_margin, "right_margin": p.right_margin, "line_spacing": p.line_spacing})
|
||||
}
|
||||
|
||||
/// How the editor shows the text being typed: each run in its colour, size (at the stage's
|
||||
/// zoom, within what the editor can show), slant, underline and baseline shift. The type is
|
||||
/// the interface's (the stage itself shows the real faces).
|
||||
pub fn layout_job(runs: &[TextRun], last: &str, text: &str, zoom: f32, wrap: f32) -> LayoutJob {
|
||||
let mut job = LayoutJob { wrap: egui::text::TextWrapping { max_width: wrap, ..Default::default() }, ..LayoutJob::default() };
|
||||
// Typed this frame (before the runs follow it): laid out as typing will style it.
|
||||
let runs = if last == text {
|
||||
runs.to_vec()
|
||||
} else {
|
||||
let (start, old_end, new_end) = rt::diff_chars(last, text);
|
||||
rt::type_into_runs(runs, start, old_end, new_end - start)
|
||||
};
|
||||
let mut bytes = text.char_indices().map(|(b, _)| b).chain(std::iter::once(text.len()));
|
||||
let mut at_byte = bytes.next().unwrap_or(0);
|
||||
let total = text.chars().count() as u32;
|
||||
let mut covered = 0u32;
|
||||
for (i, r) in runs.iter().enumerate() {
|
||||
let n = if i + 1 == runs.len() { total.saturating_sub(covered) } else { r.chars.min(total.saturating_sub(covered)) };
|
||||
if n == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut end_byte = at_byte;
|
||||
for _ in 0..n {
|
||||
end_byte = bytes.next().unwrap_or(text.len());
|
||||
}
|
||||
let s = &r.style;
|
||||
let small = s.shift != BaselineShift::Normal;
|
||||
let size = s.size * zoom * if small { 0.6 } else { 1.0 };
|
||||
let mut f = TextFormat::simple(crate::theme::stage_text_run_font(size), crate::theme::stage_text_colour(s.color));
|
||||
f.italics = s.italic;
|
||||
if s.underline || !s.url.is_empty() {
|
||||
f.underline = egui::Stroke::new((size / 14.0).max(1.0), f.color);
|
||||
}
|
||||
f.valign = if s.shift == BaselineShift::Superscript { egui::Align::TOP } else { egui::Align::BOTTOM };
|
||||
if let Some(seg) = text.get(at_byte..end_byte) {
|
||||
job.append(seg, 0.0, f);
|
||||
}
|
||||
at_byte = end_byte;
|
||||
covered += n;
|
||||
}
|
||||
job
|
||||
}
|
||||
|
||||
/// Applies the editor's runs to the block on the stage (one undo step) when it exists, so the
|
||||
/// change shows there now.
|
||||
fn push(app: &mut App, label: &'static str) {
|
||||
let Some(te) = app.text_edit.as_mut() else { return };
|
||||
te.focus = true;
|
||||
let Some(id) = te.element else { return };
|
||||
if te.text.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
let p = te.edit_params();
|
||||
te.original = te.text.clone();
|
||||
app.run("element.select", json!({"ids": [id.0]}));
|
||||
crate::panels::live(app, label, "text.edit", p);
|
||||
}
|
||||
|
||||
/// Properties while typing on the stage: the selected characters' style (mixed values marked)
|
||||
/// and the layout of the paragraphs they touch.
|
||||
pub fn selection_rows(app: &mut App, ui: &mut egui::Ui) {
|
||||
let Some(te) = app.text_edit.as_ref() else { return };
|
||||
let m = te.summary();
|
||||
let (a, b) = te.range();
|
||||
let para = {
|
||||
let range = rt::paragraphs_in(&te.text, a, b);
|
||||
let list: Vec<ParagraphStyle> = te.paras.iter().enumerate().filter(|(i, _)| range.contains(i)).map(|(_, p)| *p).collect();
|
||||
let first = list.first().copied().or(te.paras.last().copied()).unwrap_or_default();
|
||||
(first, list.iter().any(|p| p.align != first.align), list.iter().any(|p| p.indent != first.indent || p.left_margin != first.left_margin || p.right_margin != first.right_margin), list.iter().any(|p| p.line_spacing != first.line_spacing))
|
||||
};
|
||||
let first = rt::style_at(&te.runs, a);
|
||||
let mut st = anicraft_engine::cmds_text::TextStyle {
|
||||
font: m.font.clone().unwrap_or(first.font.clone()),
|
||||
size: m.size.unwrap_or(first.size),
|
||||
bold: m.bold.unwrap_or(false),
|
||||
italic: m.italic.unwrap_or(false),
|
||||
color: m.color.unwrap_or(first.color),
|
||||
align: para.0.align,
|
||||
letter_spacing: m.letter_spacing.unwrap_or(first.letter_spacing),
|
||||
line_spacing: para.0.line_spacing,
|
||||
};
|
||||
let mixed = crate::panels::TextMixed { font: m.font.is_none(), size: m.size.is_none(), color: m.color.is_none(), bold: m.bold.is_none(), italic: m.italic.is_none(), letter_spacing: m.letter_spacing.is_none(), align: para.1, line_spacing: para.3 };
|
||||
let mut extra = crate::panels::TextExtra {
|
||||
shift: m.shift,
|
||||
underline: m.underline,
|
||||
url: m.url.clone(),
|
||||
indent: para.0.indent,
|
||||
left_margin: para.0.left_margin,
|
||||
right_margin: para.0.right_margin,
|
||||
layout_mixed: para.2,
|
||||
};
|
||||
// Its own ids: the block's rows may show in the same panel.
|
||||
let r = ui.push_id("text_selection_rows", |ui| {
|
||||
let edit = crate::panels::text_style_rows(app, ui, &mut st, None, Some(&mixed));
|
||||
let more = crate::panels::text_more_rows(ui, &mut extra);
|
||||
edit.or(more)
|
||||
});
|
||||
app.text_props_rect = Some(r.response.rect);
|
||||
let Some((label, p)) = r.inner else { return };
|
||||
let (cp, pp) = (CharPatch::parse(&p).unwrap_or_default(), ParaPatch::parse(&p).unwrap_or_default());
|
||||
if let Some(te) = app.text_edit.as_mut() {
|
||||
te.restyle(&cp);
|
||||
te.repara(&pp);
|
||||
}
|
||||
push(app, label);
|
||||
}
|
||||
|
||||
/// Before the editor sees this frame's input: Copy and Cut keep the selection's styles, and a
|
||||
/// paste of exactly that text takes them back.
|
||||
pub fn watch_clipboard(app: &mut App, ctx: &egui::Context, focused: bool) {
|
||||
if !focused {
|
||||
return;
|
||||
}
|
||||
let events = ctx.input(|i| i.events.clone());
|
||||
for e in events {
|
||||
match e {
|
||||
egui::Event::Copy | egui::Event::Cut => {
|
||||
if let Some(clip) = app.text_edit.as_ref().and_then(TextEditing::clip) {
|
||||
app.text_clip = Some(clip);
|
||||
}
|
||||
}
|
||||
egui::Event::Paste(s) => {
|
||||
let clip = app.text_clip.clone().filter(|c| c.text == s.replace("\r\n", "\n"));
|
||||
if let Some(te) = app.text_edit.as_mut() {
|
||||
te.paste = clip;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A short title for the Properties section while typing.
|
||||
pub fn title(te: &TextEditing) -> String {
|
||||
let (a, b) = te.range();
|
||||
if a == b { tr!("Text: at the caret").to_string() } else { trn!("Text: {n} character selected", "Text: {n} characters selected", (b - a) as usize).to_string() }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn editing(text: &str) -> TextEditing {
|
||||
let mut te = TextEditing::new(egui::Pos2::ZERO, None, None, &anicraft_engine::cmds_text::TextStyle::default());
|
||||
te.text = text.into();
|
||||
te.sync();
|
||||
te
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_after_a_styled_word_continues_its_style() {
|
||||
let mut te = editing("Hello world");
|
||||
te.sel = (0, 5);
|
||||
te.restyle(&CharPatch { bold: Some(true), ..CharPatch::default() });
|
||||
te.text = "Hello! world".into();
|
||||
te.sync();
|
||||
assert_eq!(te.runs.iter().map(|r| (r.chars, r.style.bold)).collect::<Vec<_>>(), vec![(6, true), (6, false)]);
|
||||
// At a caret, a style picked first styles what is typed next.
|
||||
te.sel = (12, 12);
|
||||
te.restyle(&CharPatch { italic: Some(true), ..CharPatch::default() });
|
||||
assert_eq!(te.summary().italic, Some(true));
|
||||
te.text = "Hello! world?".into();
|
||||
te.sync();
|
||||
assert_eq!(te.runs.last().map(|r| (r.chars, r.style.italic)), Some((1, true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_and_paste_inside_keeps_styles_and_outside_text_is_plain() {
|
||||
let mut te = editing("red blue");
|
||||
te.sel = (0, 3);
|
||||
te.restyle(&CharPatch { color: Some(Rgba::hex(0xff0000)), ..CharPatch::default() });
|
||||
let clip = te.clip().unwrap();
|
||||
assert_eq!(clip.text, "red");
|
||||
// Pasted at the end: red again.
|
||||
te.paste = Some(clip.clone());
|
||||
te.text = "red bluered".into();
|
||||
te.sync();
|
||||
assert_eq!(te.runs.last().map(|r| (r.chars, r.style.color)), Some((3, Rgba::hex(0xff0000))));
|
||||
// Other text (from another app): the style before it, plain.
|
||||
te.paste = Some(clip);
|
||||
te.text = "red bluered!!".into();
|
||||
te.sync();
|
||||
assert_eq!(te.runs.last().map(|r| (r.chars, r.style.color)), Some((5, Rgba::hex(0xff0000))), "continues the red before it");
|
||||
let mut te = editing("a b");
|
||||
te.paste = Some(StyledClip { text: "zz".into(), runs: vec![TextRun { chars: 2, style: CharStyle { bold: true, ..CharStyle::default() } }] });
|
||||
te.text = "a xyb".into();
|
||||
te.sync();
|
||||
assert!(te.runs.iter().all(|r| !r.style.bold), "a different text is plain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paragraphs_follow_line_breaks_and_selection_rows_mark_mixed() {
|
||||
let mut te = editing("one\ntwo");
|
||||
te.sel = (0, 0);
|
||||
te.repara(&ParaPatch { align: Some(anicraft_engine::doc::TextAlign::Center), ..ParaPatch::default() });
|
||||
te.text = "one\ntwo\nthree".into();
|
||||
te.sync();
|
||||
assert_eq!(te.paras.len(), 3);
|
||||
assert_eq!(te.paras[0].align, anicraft_engine::doc::TextAlign::Center);
|
||||
let p = te.edit_params();
|
||||
assert_eq!(p["paragraphs"].as_array().map(Vec::len), Some(3));
|
||||
te.sel = (0, 5);
|
||||
te.restyle(&CharPatch { size: Some(50.0), ..CharPatch::default() });
|
||||
te.sel = (3, 9);
|
||||
assert_eq!(te.summary().size, None, "mixed sizes");
|
||||
// The editor shows each run in its own format.
|
||||
let job = layout_job(&te.runs, &te.last, &te.text, 1.0, 300.0);
|
||||
assert!(job.sections.len() >= 2);
|
||||
}
|
||||
}
|
||||
+54
-15
@@ -670,7 +670,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
Drag::Bend { .. } | Drag::RawPoint { .. } | Drag::RawHandle { .. } => end_raw_drag(app),
|
||||
Drag::Transform { .. } | Drag::SliceGuide { .. } | Drag::Points { .. } | Drag::Hint { .. } | Drag::MotionMove { .. } | Drag::CameraPan { .. } | Drag::CameraRotate { .. } | Drag::BonePose { .. } | Drag::ArmatureMove { .. } | Drag::WarpPin { .. } => app.s.end_gesture(),
|
||||
Drag::Bone { from, head, cur } => crate::bone_tool::drag_end(app, xf, from, head, cur),
|
||||
Drag::Bone { from, parent, head, cur } => crate::bone_tool::drag_end(app, xf, from, parent, head, cur),
|
||||
Drag::Guide { index, .. } => crate::rulers::drag_end(app, index, geo, ui.input(|i| i.pointer.latest_pos())),
|
||||
Drag::Width { .. } => crate::widthtool::drag_end(app),
|
||||
Drag::Gradient { .. } => crate::gradient_tool::drag_end(app),
|
||||
@@ -753,7 +753,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
Tool::Text if !panning => {
|
||||
commit_text(app);
|
||||
if !open_text_at(app, sp, 3.0 / zoom.max(1e-3)) {
|
||||
app.text_edit = Some(crate::app::TextEditing { at: sp, element: None, text: String::new(), original: String::new(), focus: true });
|
||||
app.text_edit = Some(crate::app::TextEditing::new(sp, None, None, &app.s.text_style));
|
||||
}
|
||||
}
|
||||
Tool::Bone if !panning => crate::bone_tool::click(app, xf, p),
|
||||
@@ -4038,23 +4038,28 @@ mod pattern_tests {
|
||||
fn open_text_at(app: &mut App, sp: Pos2, tolerance: f32) -> bool {
|
||||
let Some((_, id)) = app.s.hit_test(to_v(sp), tolerance) else { return false };
|
||||
let found = app.s.visible_elements().into_iter().find(|e| e.id == id).and_then(|e| match &e.kind {
|
||||
anicraft_engine::doc::ElementKind::Text(t) => Some((e.transform.apply(Vec2::ZERO), t.text.clone())),
|
||||
anicraft_engine::doc::ElementKind::Text(t) => Some((e.transform.apply(Vec2::ZERO), t.clone())),
|
||||
_ => None,
|
||||
});
|
||||
let Some((at, text)) = found else { return false };
|
||||
let Some((at, block)) = found else { return false };
|
||||
app.run("element.select", json!({"ids": [id.0]}));
|
||||
app.text_edit = Some(crate::app::TextEditing { at: pos2(at.x, at.y), element: Some(id), original: text.clone(), text, focus: true });
|
||||
app.text_edit = Some(crate::app::TextEditing::new(pos2(at.x, at.y), Some(id), Some(&block), &app.s.text_style));
|
||||
true
|
||||
}
|
||||
|
||||
/// Commits the text being typed: new text is created, edited text replaced (one undo step
|
||||
/// each); emptied text is deleted, and unchanged text commits nothing.
|
||||
/// each), with its styled runs (ADR 0085); emptied text is deleted, and unchanged text commits
|
||||
/// nothing.
|
||||
pub fn commit_text(app: &mut App) {
|
||||
let Some(te) = app.text_edit.take() else { return };
|
||||
let Some(mut te) = app.text_edit.take() else { return };
|
||||
te.sync();
|
||||
match te.element {
|
||||
None if te.text.trim().is_empty() => {}
|
||||
None => {
|
||||
app.run("text.create", json!({"text": te.text, "x": te.at.x, "y": te.at.y}));
|
||||
let mut p = te.edit_params();
|
||||
p["x"] = json!(te.at.x);
|
||||
p["y"] = json!(te.at.y);
|
||||
app.run("text.create", p);
|
||||
}
|
||||
Some(_) if te.text == te.original => {}
|
||||
Some(id) => {
|
||||
@@ -4062,35 +4067,69 @@ pub fn commit_text(app: &mut App) {
|
||||
if te.text.trim().is_empty() {
|
||||
app.run("edit.delete", json!({}));
|
||||
} else {
|
||||
app.run("text.edit", json!({"text": te.text}));
|
||||
app.run("text.edit", te.edit_params());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The field text is typed in, over the stage at the text's top-left corner. Esc or a click
|
||||
/// elsewhere finishes; Enter starts a new line.
|
||||
/// The field text is typed in, over the stage at the text's top-left corner, each run shown in
|
||||
/// its own colour, size and style (ADR 0085). Esc or a click elsewhere finishes (a click in
|
||||
/// Properties' text styles keeps it open); Enter starts a new line.
|
||||
fn text_editor(app: &mut App, ui: &mut egui::Ui, stage_origin: Pos2, zoom: f32) {
|
||||
let focused_id = egui::Id::new("stage_text_edit_field");
|
||||
let had_focus = ui.ctx().memory(|m| m.has_focus(focused_id));
|
||||
crate::rich_edit::watch_clipboard(app, ui.ctx(), had_focus);
|
||||
let paper = crate::theme::stage_text_colour(anicraft_engine::doc::Rgba { a: 1.0, ..app.s.doc.stage.background });
|
||||
let held = app.text_props_rect.zip(ui.ctx().input(|i| i.pointer.interact_pos())).is_some_and(|(r, p)| r.contains(p)) || egui::Popup::is_any_open(ui.ctx());
|
||||
// As wide as the block being edited (at the zoom), so its lines break as they do.
|
||||
let block_w = app.text_edit.as_ref().and_then(|te| te.element).and_then(|id| app.s.visible_elements().into_iter().find(|e| e.id == id)).and_then(|e| match &e.kind {
|
||||
anicraft_engine::doc::ElementKind::Text(t) => Some(t.width.unwrap_or(t.box_width)),
|
||||
_ => None,
|
||||
});
|
||||
let Some(te) = app.text_edit.as_mut() else { return };
|
||||
let at = stage_origin + vec2(te.at.x * zoom, te.at.y * zoom);
|
||||
let size = (app.s.text_style.size * zoom).clamp(12.0, 64.0);
|
||||
let size = (rt_size(te) * zoom).clamp(12.0, 64.0);
|
||||
let width = 260.0f32.max(size * 8.0).max(block_w.unwrap_or(0.0) * zoom + 8.0).min(4000.0);
|
||||
let mut done = false;
|
||||
let (runs, last) = (te.runs.clone(), te.last.clone());
|
||||
egui::Area::new(egui::Id::new("stage_text_edit")).fixed_pos(at).order(egui::Order::Foreground).show(ui.ctx(), |ui| {
|
||||
egui::Frame::new().fill(T.panel).stroke(Stroke::new(1.0, T.selection)).inner_margin(4.0).show(ui, |ui| {
|
||||
let r = ui.add(egui::TextEdit::multiline(&mut te.text).font(crate::theme::stage_text_font(size)).desired_rows(1).desired_width(260.0f32.max(size * 8.0)).hint_text(tr!("Type text"))).named(tr!("Text on the stage"));
|
||||
egui::Frame::new().fill(paper).stroke(Stroke::new(1.0, T.selection)).inner_margin(4.0).show(ui, |ui| {
|
||||
let mut layouter = |ui: &egui::Ui, buf: &dyn egui::TextBuffer, wrap: f32| {
|
||||
let job = crate::rich_edit::layout_job(&runs, &last, buf.as_str(), zoom, wrap);
|
||||
ui.fonts_mut(|f| f.layout_job(job))
|
||||
};
|
||||
let r = ui
|
||||
.add(egui::TextEdit::multiline(&mut te.text).id(focused_id).font(crate::theme::stage_text_font(size)).desired_rows(1).desired_width(width).background_color(paper).hint_text(tr!("Type text")).layouter(&mut layouter))
|
||||
.named(tr!("Text on the stage"));
|
||||
if let Some(range) = egui::text_edit::TextEditState::load(ui.ctx(), r.id).and_then(|s| s.cursor.char_range()) {
|
||||
te.sel = (range.secondary.index.0 as u32, range.primary.index.0 as u32);
|
||||
}
|
||||
if te.focus {
|
||||
// Back in the editor (after a style was picked): the selection as it was.
|
||||
if let Some(mut state) = egui::text_edit::TextEditState::load(ui.ctx(), r.id) {
|
||||
let (a, b) = te.sel;
|
||||
state.cursor.set_char_range(Some(egui::text::CCursorRange::two(egui::text::CCursor::new(a as usize), egui::text::CCursor::new(b as usize))));
|
||||
state.store(ui.ctx(), r.id);
|
||||
}
|
||||
r.request_focus();
|
||||
te.focus = false;
|
||||
} else if r.lost_focus() {
|
||||
} else if r.lost_focus() && !held {
|
||||
done = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
te.sync();
|
||||
if done {
|
||||
commit_text(app);
|
||||
}
|
||||
}
|
||||
|
||||
/// The size the editor's caret line is shown at: the run at the caret's.
|
||||
fn rt_size(te: &crate::app::TextEditing) -> f32 {
|
||||
anicraft_engine::doc::rich_text::style_at(&te.runs, te.sel.1).size
|
||||
}
|
||||
|
||||
// ----- free transform ---------------------------------------------------------------------------
|
||||
|
||||
/// Screen-space handle size and the rotation zone just outside each corner.
|
||||
|
||||
+1
-1
@@ -240,7 +240,7 @@ pub fn save_window(app: &mut App, ctx: &egui::Context) {
|
||||
d.picture = Some(picture_png(doc).and_then(|png| texture(ctx, "save-preview", &png)));
|
||||
}
|
||||
let (mut submit, mut cancel) = (false, false);
|
||||
egui::Window::new(tr!("Save as Template")).id(egui::Id::new("save_template")).collapsible(false).resizable(false).anchor(Align2::CENTER_CENTER, [0.0, -60.0]).show(ctx, |ui| {
|
||||
crate::windows::new(ctx, tr!("Save as Template")).id(egui::Id::new("save_template")).collapsible(false).resizable(false).anchor(Align2::CENTER_CENTER, [0.0, -60.0]).show(ctx, |ui| {
|
||||
ui.set_min_width(420.0);
|
||||
if let Some(Some(tex)) = &d.picture {
|
||||
let s = tex.size_vec2();
|
||||
|
||||
+1
-1
@@ -386,7 +386,7 @@ fn inside(app: &mut App, ctx: &egui::Context, why: crate::platform::Inside) -> A
|
||||
let default_h = default_w * sh / sw.max(1.0) + 190.0;
|
||||
let title = title(tm);
|
||||
let note = why.note().map(crate::i18n::t);
|
||||
let win = egui::Window::new(title.clone())
|
||||
let win = crate::windows::new(ctx, title.clone())
|
||||
.id(egui::Id::new("test_movie"))
|
||||
.open(&mut shown)
|
||||
.collapsible(false)
|
||||
|
||||
@@ -512,6 +512,18 @@ pub fn stage_text_font(size: f32) -> egui::FontId {
|
||||
egui::FontId::proportional(size.clamp(12.0, 64.0))
|
||||
}
|
||||
|
||||
/// The editor's face for a run of stage text at `size` screen pixels (within what the editor
|
||||
/// can show legibly).
|
||||
pub fn stage_text_run_font(size: f32) -> egui::FontId {
|
||||
egui::FontId::proportional(if size.is_finite() { size.clamp(6.0, 96.0) } else { 14.0 })
|
||||
}
|
||||
|
||||
/// A run's own colour (document data) as the editor shows it, at least faintly visible.
|
||||
pub fn stage_text_colour(c: anicraft_engine::doc::Rgba) -> Color32 {
|
||||
let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
Color32::from_rgba_unmultiplied(b(c.r), b(c.g), b(c.b), b(c.a.max(0.25)))
|
||||
}
|
||||
|
||||
/// The typefaces embedded at build time (Inter, JetBrains Mono), for text on the stage.
|
||||
pub fn embedded_fonts() -> Vec<std::sync::Arc<[u8]>> {
|
||||
[craft_fonts::UI_FONT, craft_fonts::MONO_FONT].into_iter().flatten().map(std::sync::Arc::from).collect()
|
||||
|
||||
+5
-8
@@ -186,7 +186,7 @@ impl Updates {
|
||||
let mut open = true;
|
||||
let mut install = false;
|
||||
let mut again = false;
|
||||
egui::Window::new(tr!("Check for Updates"))
|
||||
crate::windows::new(ctx, tr!("Check for Updates"))
|
||||
.open(&mut open)
|
||||
.collapsible(false)
|
||||
.resizable(false)
|
||||
@@ -418,13 +418,10 @@ mod tests {
|
||||
let mut app = crate::app::App::with_context(&ctx, session, Some(std::path::PathBuf::from("unused.png")));
|
||||
assert!(!app.s.is_dirty());
|
||||
assert!(safe_to_install(&app));
|
||||
app.text_edit = Some(crate::app::TextEditing {
|
||||
at: egui::Pos2::ZERO,
|
||||
element: None,
|
||||
text: "Uncommitted stage text".into(),
|
||||
original: String::new(),
|
||||
focus: false,
|
||||
});
|
||||
let mut te = crate::app::TextEditing::new(egui::Pos2::ZERO, None, None, &app.s.text_style);
|
||||
te.text = "Uncommitted stage text".into();
|
||||
te.focus = false;
|
||||
app.text_edit = Some(te);
|
||||
assert!(!app.s.is_dirty(), "the edit has not reached Session yet");
|
||||
assert!(!safe_to_install(&app), "restarting would discard the text buffer");
|
||||
app.text_edit = None;
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Floating windows: every `egui::Window` the shell opens comes from [`new`], which keeps it
|
||||
//! inside the work area below the menu bar, so no dialog's title bar covers File, Edit, View
|
||||
//! (a window dragged up stops under the bar; one placed or anchored over it is moved down).
|
||||
//! `guidelines_tests` checks that no other code opens a window directly.
|
||||
|
||||
/// Where the area below the menu bar is kept for this frame.
|
||||
fn key() -> egui::Id {
|
||||
egui::Id::new("anicraft_work_area")
|
||||
}
|
||||
|
||||
/// Records the work area: the window's content below the menu bar (`bar_bottom`).
|
||||
pub fn set_work_area(ctx: &egui::Context, bar_bottom: f32) {
|
||||
let mut r = ctx.content_rect();
|
||||
if bar_bottom.is_finite() {
|
||||
r.min.y = bar_bottom.clamp(r.min.y, r.max.y);
|
||||
}
|
||||
ctx.data_mut(|d| d.insert_temp(key(), r));
|
||||
}
|
||||
|
||||
/// The area floating windows stay in (the whole window before the menu bar has been laid out).
|
||||
pub fn work_area(ctx: &egui::Context) -> egui::Rect {
|
||||
ctx.data(|d| d.get_temp::<egui::Rect>(key())).unwrap_or_else(|| ctx.content_rect())
|
||||
}
|
||||
|
||||
/// A floating window kept below the menu bar.
|
||||
pub fn new(ctx: &egui::Context, title: impl Into<egui::WidgetText>) -> egui::Window<'static> {
|
||||
egui::Window::new(title).constrain_to(work_area(ctx))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Runs one frame of a 800 × 600 window with a 24 px bar, a window asked to sit at the very
|
||||
/// top, and returns where it was drawn.
|
||||
fn frame(ctx: &egui::Context, at: egui::Pos2) -> egui::Rect {
|
||||
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() };
|
||||
let mut shown = egui::Rect::NOTHING;
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
let ctx = ui.ctx().clone();
|
||||
set_work_area(&ctx, 24.0);
|
||||
if let Some(r) = new(&ctx, "Custom Ease").id(egui::Id::new("t")).current_pos(at).show(&ctx, |ui| {
|
||||
ui.label("graph");
|
||||
}) {
|
||||
shown = r.response.rect;
|
||||
}
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
shown
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_never_open_over_the_menu_bar() {
|
||||
let ctx = egui::Context::default();
|
||||
for at in [egui::pos2(100.0, 0.0), egui::pos2(100.0, -50.0), egui::pos2(-20.0, 10.0)] {
|
||||
let r = frame(&ctx, at);
|
||||
let r = frame(&ctx, at).union(r);
|
||||
assert!(r.min.y >= 24.0 - 0.5, "{at:?} → {r:?}");
|
||||
assert!(r.min.x >= -0.5);
|
||||
}
|
||||
// Lower down, a window stays where it was put.
|
||||
let lower = egui::Context::default();
|
||||
frame(&lower, egui::pos2(100.0, 200.0));
|
||||
let r = frame(&lower, egui::pos2(100.0, 200.0));
|
||||
assert!((r.min.y - 200.0).abs() < 1.0, "{r:?}");
|
||||
// Before a bar was laid out, the whole window is the area.
|
||||
assert_eq!(work_area(&egui::Context::default()), egui::Context::default().content_rect());
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ pub fn show(app: &mut App, ctx: &egui::Context) {
|
||||
}
|
||||
let mut open = true;
|
||||
let title = tr!("Manage Workspaces");
|
||||
let shown = egui::Window::new(title).id(egui::Id::new("manage_workspaces")).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| {
|
||||
let shown = crate::windows::new(ctx, title).id(egui::Id::new("manage_workspaces")).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| {
|
||||
ui.set_min_width(380.0);
|
||||
let current = app.prefs.workspaces.current.clone();
|
||||
for key in app.prefs.workspaces.keys() {
|
||||
|
||||
Reference in new issue
Block a user