#[cfg(doc)]
use f_office_drawingml::effect::OuterShadow;
use f_office_drawingml::effect::{Reflection as DrawingMlReflection, ShadowColor, ShadowOffset};
use f_office_drawingml::gradient::{ResolvedEffectGradient, ResolvedEffectGradientKind};
use f_office_effects::{
ColoredLayer, FillRule as ShadowRule, Gradient as EffectGradient,
GradientKind as EffectGradientKind, GradientStop as EffectGradientStop, MaskFormat, MaskSource,
Outline, Picture, PictureMask, PixelLength, Place, Reflection as EffectReflection,
ReflectionContent, Scene, Segment, Shadow, Share, SoftEdge, SoftEdgeBorder, SurfaceReflection,
};
use f_office_paint::{
FillRule, Image, ImageColor, ImageFormat, ImageItem, InkConversion, Item, Opacity, PathCommand,
PathItem, Point, Rect, Rgb, Turn,
};
use f_office_units::scale::DRAWING_WHOLE;
use f_office_units::{Edges, Length, div_round, div_round_i128};
use crate::params::{
GRADIENT_MAX_SIDE, SHADOW_BLUR_PIXELS, SHADOW_BLUR_SPREAD, SHADOW_BOX_ROOM, SHADOW_BOX_STEP,
SHADOW_PIXELS_PER_INCH,
};
type Filled = (Vec<PathCommand>, FillRule);
pub(super) fn items(
blur: Length,
offset: ShadowOffset,
ShadowColor { rgb, opacity }: ShadowColor,
items: &[Item],
) -> Option<Vec<Item>> {
let outlines: Vec<Filled> = items.iter().filter_map(filled).collect();
if outlines.is_empty() {
return None;
}
if blur <= Length::ZERO && opacity == Opacity::FULL {
return Some(
outlines
.into_iter()
.map(|(commands, fill_rule)| {
Item::Path(PathItem {
commands: commands.iter().map(|c| moved(*c, offset)).collect(),
color: rgb,
fill_rule,
})
})
.collect(),
);
}
let frame = picture_box(bounds(&outlines)?, offset, blur)?;
let refs: Vec<(&[PathCommand], FillRule, Length)> = outlines
.iter()
.map(|(commands, rule)| (commands.as_slice(), *rule, Length::ZERO))
.collect();
Some(vec![picture_item(
&refs,
None,
frame,
offset,
Length::ZERO,
blur,
ShadowColor { rgb, opacity },
)?])
}
pub(super) fn glow_items(radius: Length, color: ShadowColor, items: &[Item]) -> Option<Vec<Item>> {
if radius <= Length::ZERO || color.opacity.share() <= 0 {
return None;
}
let outlines: Vec<Filled> = items.iter().filter_map(filled).collect();
if outlines.is_empty() {
return None;
}
let half = radius.div_round(2);
let zero_offset = ShadowOffset {
across: Length::ZERO,
down: Length::ZERO,
};
let frame = picture_box(bounds(&outlines)?, zero_offset, radius)?;
let refs: Vec<(&[PathCommand], FillRule, Length)> = outlines
.iter()
.map(|(commands, rule)| (commands.as_slice(), *rule, Length::ZERO))
.collect();
Some(vec![picture_item(
&refs,
None,
frame,
zero_offset,
half,
half,
color,
)?])
}
pub(super) fn effect_gradient_item(
gradient: &ResolvedEffectGradient,
fill: &PathItem,
) -> Option<Item> {
let frame = bounds(&[(fill.commands.clone(), fill.fill_rule)])?;
let (width, height) = gradient_picture_size(frame)?;
let place = |pt: Point| {
Some(Place {
x: axis_pixel(pt.x, frame.left, frame.width(), width)?,
y: axis_pixel(pt.y, frame.top, frame.height(), height)?,
})
};
let outline = Outline {
segments: segments(&fill.commands, &place)?,
rule: match fill.fill_rule {
FillRule::NonZero => ShadowRule::NonZero,
FillRule::EvenOdd => ShadowRule::EvenOdd,
},
stroke: PixelLength::ZERO,
};
let kind = gradient_picture_kind(gradient.kind, frame, (width, height), &place)?;
let stops = gradient
.stops
.iter()
.map(|&(place, rgba)| EffectGradientStop { place, rgba })
.collect();
let picture = Picture {
width,
height,
scene: Scene::Gradient(EffectGradient {
outline,
kind,
stops,
}),
};
Some(Item::Image(ImageItem {
x: frame.left,
y: frame.top,
width: frame.width(),
height: frame.height(),
clip: None,
turn: None,
image: Image {
format: ImageFormat::EffectPicture,
data: picture.encode().into(),
opacity: Opacity::FULL,
color: ImageColor::Original,
inks: InkConversion::EmbeddedProfile,
},
}))
}
fn gradient_picture_size(frame: Edges<Length>) -> Option<(u32, u32)> {
if frame.width() <= Length::ZERO || frame.height() <= Length::ZERO {
return None;
}
let per_inch = i128::from(SHADOW_PIXELS_PER_INCH);
let unit_inch = i128::from(Length::UNITS_PER_INCH);
let raw_w = div_round_i128(i128::from(frame.width().units()) * per_inch, unit_inch).max(1);
let raw_h = div_round_i128(i128::from(frame.height().units()) * per_inch, unit_inch).max(1);
let parts = ((raw_w.max(raw_h) + GRADIENT_MAX_SIDE - 1) / GRADIENT_MAX_SIDE).max(1);
let inch = unit_inch * parts;
let width =
u32::try_from(div_round_i128(i128::from(frame.width().units()) * per_inch, inch).max(1))
.ok()?;
let height =
u32::try_from(div_round_i128(i128::from(frame.height().units()) * per_inch, inch).max(1))
.ok()?;
Some((width, height))
}
fn axis_pixel(coord: Length, origin: Length, span: Length, count: u32) -> Option<PixelLength> {
let delta = coord.units().checked_sub(origin.units())?;
PixelLength::ratio(delta.checked_mul(i64::from(count))?, span.units())
}
fn gradient_picture_kind(
kind: ResolvedEffectGradientKind,
frame: Edges<Length>,
(width, height): (u32, u32),
place: &impl Fn(Point) -> Option<Place>,
) -> Option<EffectGradientKind> {
Some(match kind {
ResolvedEffectGradientKind::Linear { start, end } => EffectGradientKind::Linear {
start: place(start)?,
end: place(end)?,
},
ResolvedEffectGradientKind::Radial { center, rx, ry } => EffectGradientKind::Radial {
center: place(center)?,
rx: axis_pixel(rx, Length::ZERO, frame.width(), width)?,
ry: axis_pixel(ry, Length::ZERO, frame.height(), height)?,
},
ResolvedEffectGradientKind::Rect { center, bounds } => {
let [top_left, bottom_right] = [
place(Point {
x: bounds.left,
y: bounds.top,
})?,
place(Point {
x: bounds.right,
y: bounds.bottom,
})?,
];
EffectGradientKind::Rect {
center: place(center)?,
left: top_left.x,
top: top_left.y,
right: bottom_right.x,
bottom: bottom_right.y,
}
}
ResolvedEffectGradientKind::Shape { center } => EffectGradientKind::Shape {
center: place(center)?,
},
})
}
pub(super) fn items_with_glow(
blur: Length,
offset: ShadowOffset,
color: ShadowColor,
glow_radius: Length,
items: &[Item],
) -> Option<Vec<Item>> {
if glow_radius <= Length::ZERO {
return self::items(blur, offset, color, items);
}
let outlines: Vec<Filled> = items.iter().filter_map(filled).collect();
if outlines.is_empty() {
return None;
}
let half = glow_radius.div_round(2);
let total_blur = combined_blur(half, blur);
let grow = glow_radius.checked_add(blur.max(Length::ZERO))?;
let frame = picture_box(bounds(&outlines)?, offset, grow)?;
let refs: Vec<(&[PathCommand], FillRule, Length)> = outlines
.iter()
.map(|(commands, rule)| (commands.as_slice(), *rule, Length::ZERO))
.collect();
Some(vec![picture_item(
&refs, None, frame, offset, half, total_blur, color,
)?])
}
pub(super) fn combined_blur(first: Length, second: Length) -> Length {
let a = i128::from(first.units().max(0));
let b = i128::from(second.units().max(0));
let sum = a * a + b * b;
let root = sum.isqrt();
let rounded = if sum > root * root + root {
root + 1
} else {
root
};
Length::from_units(i64::try_from(rounded).unwrap_or(i64::MAX))
}
pub(super) struct MaskPlacement {
pub(super) source: MaskSource,
pub(super) opacity: Opacity,
pub(super) corners: [Point; 3],
pub(super) crop: Edges<i64>,
}
pub(super) fn masked_picture(
covered: Edges<Length>,
line: Option<&Item>,
mask: MaskPlacement,
offset: ShadowOffset,
blur: Length,
color: ShadowColor,
) -> Option<Item> {
masked_picture_effect(
covered,
line,
mask,
offset,
(Length::ZERO, blur, blur),
color,
)
}
pub(super) fn masked_picture_glow(
covered: Edges<Length>,
line: Option<&Item>,
mask: MaskPlacement,
radius: Length,
color: ShadowColor,
) -> Option<Item> {
if radius <= Length::ZERO || color.opacity.share() <= 0 {
return None;
}
let half = radius.div_round(2);
masked_picture_effect(
covered,
line,
mask,
ShadowOffset {
across: Length::ZERO,
down: Length::ZERO,
},
(half, half, radius),
color,
)
}
pub(super) fn masked_picture_with_glow(
covered: Edges<Length>,
line: Option<&Item>,
mask: MaskPlacement,
offset: ShadowOffset,
blur: Length,
glow_radius: Length,
color: ShadowColor,
) -> Option<Item> {
if glow_radius <= Length::ZERO {
return masked_picture(covered, line, mask, offset, blur, color);
}
let half = glow_radius.div_round(2);
let total_blur = combined_blur(half, blur);
let grow = glow_radius.checked_add(blur.max(Length::ZERO))?;
masked_picture_effect(covered, line, mask, offset, (half, total_blur, grow), color)
}
fn masked_picture_effect(
covered: Edges<Length>,
line: Option<&Item>,
mask: MaskPlacement,
offset: ShadowOffset,
(dilate, blur, grow): (Length, Length, Length),
color: ShadowColor,
) -> Option<Item> {
let line_outline = line.and_then(filled);
let mut union = covered;
if let Some(ref outline) = line_outline
&& let Some(line_bounds) = bounds(std::slice::from_ref(outline))
{
union = Edges {
left: union.left.min(line_bounds.left),
top: union.top.min(line_bounds.top),
right: union.right.max(line_bounds.right),
bottom: union.bottom.max(line_bounds.bottom),
};
}
let frame = picture_box(union, offset, grow)?;
let refs: Vec<(&[PathCommand], FillRule, Length)> = line_outline
.iter()
.map(|(commands, rule)| (commands.as_slice(), *rule, Length::ZERO))
.collect();
picture_item(&refs, Some(mask), frame, offset, dilate, blur, color)
}
pub(super) fn stroked_picture(
commands: &[PathCommand],
fill_rule: FillRule,
stroke_width: Length,
offset: ShadowOffset,
blur: Length,
color: ShadowColor,
) -> Option<Item> {
stroked_effect_picture(
commands,
fill_rule,
stroke_width,
offset,
(Length::ZERO, blur, blur),
color,
)
}
pub(super) fn stroked_effect_picture(
commands: &[PathCommand],
fill_rule: FillRule,
stroke_width: Length,
offset: ShadowOffset,
(dilate, blur, grow): (Length, Length, Length),
color: ShadowColor,
) -> Option<Item> {
let ink = exact_bounds(commands)?;
let half = stroke_width.max(Length::ZERO).div_toward_zero(2);
let grown = Edges {
left: ink.left - half,
top: ink.top - half,
right: ink.right + half,
bottom: ink.bottom + half,
};
let frame = picture_box(grown, offset, grow)?;
picture_item(
&[(commands, fill_rule, stroke_width.max(Length::ZERO))],
None,
frame,
offset,
dilate,
blur,
color,
)
}
fn reflection_frame(
commands: &[PathCommand],
stroke_width: Length,
(clip_y, fade_end_y): (Length, Length),
end_opacity: Opacity,
blur: Length,
) -> Option<Edges<Length>> {
let ink = exact_bounds(commands)?;
let half = stroke_width.max(Length::ZERO).div_toward_zero(2);
let top = (ink.top - half).max(clip_y);
let bottom = if end_opacity.share() <= 0 {
(ink.bottom + half).min(fade_end_y)
} else {
ink.bottom + half
};
if top >= bottom {
return None;
}
let visible = Edges {
left: ink.left - half,
top,
right: ink.right + half,
bottom,
};
let zero_offset = ShadowOffset {
across: Length::ZERO,
down: Length::ZERO,
};
picture_box(visible, zero_offset, blur)
}
pub(super) fn reflection_picture(
commands: &[PathCommand],
fill_rule: FillRule,
stroke_width: Length,
(clip_y, fade_start_y, fade_end_y): (Length, Length, Length),
(start_opacity, end_opacity): (Opacity, Opacity),
blur: Length,
color: Rgb,
) -> Option<Item> {
let frame = reflection_frame(
commands,
stroke_width,
(clip_y, fade_end_y),
end_opacity,
blur,
)?;
let parts = blur_parts(blur);
let size = (
effect_pixels(frame.width(), parts)?,
effect_pixels(frame.height(), parts)?,
);
let at_y = |y: Length| {
let from_top = y.units() - frame.top.units();
PixelLength::ratio(
from_top.checked_mul(i64::from(size.1))?,
frame.height().units(),
)
};
let place = |point: Point| {
let from_left = point.x.units() - frame.left.units();
Some(Place {
x: PixelLength::ratio(
from_left.checked_mul(i64::from(size.0))?,
frame.width().units(),
)?,
y: at_y(point.y)?,
})
};
let inch_units = Length::UNITS_PER_INCH.checked_mul(i64::try_from(parts).ok()?)?;
let outlines = build_outlines(
&[(commands, fill_rule, stroke_width.max(Length::ZERO))],
inch_units,
&place,
)?;
let sigma = blur_sigma(blur, inch_units)?;
let picture = Picture {
width: size.0,
height: size.1,
scene: Scene::Reflection(EffectReflection {
outlines,
blur: sigma,
clip_y: at_y(clip_y)?,
fade_start_y: at_y(fade_start_y)?,
fade_end_y: at_y(fade_end_y)?,
start_opacity: Share::ratio(start_opacity.share(), DRAWING_WHOLE)?,
end_opacity: Share::ratio(end_opacity.share(), DRAWING_WHOLE)?,
color: [color.r, color.g, color.b],
}),
};
Some(effect_image_item(frame, &picture))
}
fn effect_pixels(side: Length, parts: i128) -> Option<u32> {
let per_inch = i128::from(SHADOW_PIXELS_PER_INCH);
let inch = i128::from(Length::UNITS_PER_INCH) * parts;
let count = div_round_i128(i128::from(side.units()) * per_inch, inch).max(1);
u32::try_from(count).ok()
}
fn blur_sigma(blur: Length, inch_units: i64) -> Option<PixelLength> {
let (spread, over) = SHADOW_BLUR_SPREAD;
PixelLength::ratio(
blur.units()
.checked_mul(SHADOW_PIXELS_PER_INCH)?
.checked_mul(spread)?,
inch_units.checked_mul(over)?,
)
}
fn effect_image_item(frame: Edges<Length>, picture: &Picture) -> Item {
Item::Image(ImageItem {
x: frame.left,
y: frame.top,
width: frame.width(),
height: frame.height(),
clip: None,
turn: None,
image: Image {
format: ImageFormat::EffectPicture,
data: picture.encode().into(),
opacity: Opacity::FULL,
color: ImageColor::Original,
inks: InkConversion::EmbeddedProfile,
},
})
}
pub(super) struct SoftEdgePlacement<'a> {
pub(super) format: MaskFormat,
pub(super) data: &'a [u8],
pub(super) shown: Edges<Length>,
pub(super) crop: Edges<i64>,
pub(super) border: Option<(Rgb, Length)>,
pub(super) clip: Option<(Vec<PathCommand>, FillRule)>,
pub(super) opacity: Opacity,
pub(super) color: ImageColor,
pub(super) turn: Option<Turn>,
pub(super) radius: Length,
}
fn soft_edge_pixels(w_len: Length, h_len: Length) -> Option<(u32, u32)> {
if w_len <= Length::ZERO || h_len <= Length::ZERO {
return None;
}
let ppi = i128::from(SHADOW_PIXELS_PER_INCH);
let inch = i128::from(Length::UNITS_PER_INCH);
let ceil_px = |side: Length| {
let count = ((i128::from(side.units()) * ppi + inch - 1) / inch).max(1);
u32::try_from(count).ok()
};
let (w_px, h_px) = (ceil_px(w_len)?, ceil_px(h_len)?);
let bytes_per_pixel = u64::from(u32::BITS / u8::BITS);
let bytes = u64::from(w_px)
.checked_mul(u64::from(h_px))?
.checked_mul(bytes_per_pixel)?;
(bytes <= f_office_paint::MAX_DECODED_BYTES).then_some((w_px, h_px))
}
fn soft_edge_frame(shown: Edges<Length>, bw: Length) -> Option<((u32, u32), Edges<Length>)> {
let expanded = Edges {
left: shown.left.checked_sub(bw)?,
top: shown.top.checked_sub(bw)?,
right: shown.right.checked_add(bw)?,
bottom: shown.bottom.checked_add(bw)?,
};
let (w_len, h_len) = (expanded.width(), expanded.height());
let (w_px, h_px) = soft_edge_pixels(w_len, h_len)?;
let ppi = i128::from(SHADOW_PIXELS_PER_INCH);
let inch = i128::from(Length::UNITS_PER_INCH);
let px_to_len = |px: u32| {
let units = div_round_i128(i128::from(px) * inch, ppi);
i64::try_from(units).ok().map(Length::from_units)
};
let (draw_w, draw_h) = (px_to_len(w_px)?, px_to_len(h_px)?);
let draw_left = expanded.left.checked_sub((draw_w - w_len).div_round(2))?;
let draw_top = expanded.top.checked_sub((draw_h - h_len).div_round(2))?;
let placed = Edges::placed(draw_left, draw_top, draw_w, draw_h)?;
Some(((w_px, h_px), placed))
}
fn soft_edge_crop(crop: Edges<i64>) -> Option<[i32; 4]> {
if DRAWING_WHOLE - crop.left - crop.right <= 0 || DRAWING_WHOLE - crop.top - crop.bottom <= 0 {
return None;
}
Some([
i32::try_from(crop.left).ok()?,
i32::try_from(crop.top).ok()?,
i32::try_from(crop.right).ok()?,
i32::try_from(crop.bottom).ok()?,
])
}
fn soft_edge_radii(radius: Length) -> Option<(PixelLength, PixelLength)> {
let ppi = i128::from(SHADOW_PIXELS_PER_INCH);
let inch = i128::from(Length::UNITS_PER_INCH);
let parts = blur_parts(radius);
let erode_whole = (i128::from(radius.units()) * ppi / (inch * parts)) * parts;
let erode = PixelLength::ratio(i64::try_from(erode_whole).ok()?, 1)?;
let (spread, over) = SHADOW_BLUR_SPREAD;
let blur = PixelLength::ratio(
radius
.units()
.checked_mul(SHADOW_PIXELS_PER_INCH)?
.checked_mul(spread)?,
Length::UNITS_PER_INCH.checked_mul(over)?,
)?;
Some((erode, blur))
}
pub(super) fn soft_edge_picture(spec: SoftEdgePlacement<'_>) -> Option<Item> {
if spec.radius <= Length::ZERO {
return None;
}
let crop = soft_edge_crop(spec.crop)?;
let bw = spec
.border
.map_or(Length::ZERO, |(_, w)| w.max(Length::ZERO));
let ((w_px, h_px), placed) = soft_edge_frame(spec.shown, bw)?;
let (erode, blur) = soft_edge_radii(spec.radius)?;
let border = match spec.border {
Some((rgb, _)) => Some(SoftEdgeBorder {
width: PixelLength::ratio(
bw.units().checked_mul(SHADOW_PIXELS_PER_INCH)?,
Length::UNITS_PER_INCH,
)?,
color: [rgb.r, rgb.g, rgb.b],
}),
None => None,
};
let clip = match spec.clip {
Some((commands, rule)) => Some(soft_edge_clip(&commands, rule, placed, (w_px, h_px))?),
None => None,
};
let picture = Picture {
width: w_px,
height: h_px,
scene: Scene::SoftEdge(SoftEdge {
format: spec.format,
data: spec.data.to_vec(),
crop,
border,
clip,
erode,
blur,
}),
};
Some(Item::Image(ImageItem {
x: placed.left,
y: placed.top,
width: placed.width(),
height: placed.height(),
clip: None,
turn: spec.turn,
image: Image {
format: ImageFormat::EffectPicture,
data: picture.encode().into(),
opacity: spec.opacity,
color: spec.color,
inks: InkConversion::EmbeddedProfile,
},
}))
}
fn soft_edge_clip(
commands: &[PathCommand],
rule: FillRule,
placed: Edges<Length>,
(w_px, h_px): (u32, u32),
) -> Option<Outline> {
let place = |point: Point| {
let at = |value: Length, first: Length, side: Length, count: u32| {
PixelLength::ratio(
(value.units() - first.units()).checked_mul(i64::from(count))?,
side.units(),
)
};
Some(Place {
x: at(point.x, placed.left, placed.width(), w_px)?,
y: at(point.y, placed.top, placed.height(), h_px)?,
})
};
Some(Outline {
segments: segments(commands, &place)?,
rule: match rule {
FillRule::NonZero => ShadowRule::NonZero,
FillRule::EvenOdd => ShadowRule::EvenOdd,
},
stroke: PixelLength::ZERO,
})
}
pub(super) struct PictureReflectionPlacement<'a> {
pub(super) format: MaskFormat,
pub(super) data: &'a [u8],
pub(super) shown: Edges<Length>,
pub(super) crop: Edges<i64>,
pub(super) border: Option<(Rgb, Length)>,
pub(super) clip: Option<(Vec<PathCommand>, FillRule)>,
pub(super) opacity: Opacity,
pub(super) color: ImageColor,
pub(super) turn: Option<Turn>,
pub(super) reflection: DrawingMlReflection,
}
struct SurfaceReflectionFrame {
refl_box: Edges<Length>,
padded: Edges<Length>,
size: (u32, u32),
inch_units: i64,
}
fn surface_reflection_frame(
outer: Edges<Length>,
reflection: DrawingMlReflection,
) -> Option<SurfaceReflectionFrame> {
let (w, h) = (outer.width(), outer.height());
if w <= Length::ZERO || h <= Length::ZERO {
return None;
}
let refl_top = outer.bottom.checked_add(reflection.distance)?;
let refl_box = Edges::placed(outer.left, refl_top, w, h)?;
let pad = reflection.blur.max(Length::ZERO);
let padded = Edges {
left: refl_box.left.checked_sub(pad)?,
top: refl_box.top.checked_sub(pad)?,
right: refl_box.right.checked_add(pad)?,
bottom: refl_box.bottom.checked_add(pad)?,
};
let parts = blur_parts(pad);
let (w_px, h_px) = (
effect_pixels(padded.width(), parts)?,
effect_pixels(padded.height(), parts)?,
);
let bytes_per_pixel = u64::from(u32::BITS / u8::BITS);
let bytes = u64::from(w_px)
.checked_mul(u64::from(h_px))?
.checked_mul(bytes_per_pixel)?;
if bytes > f_office_paint::MAX_DECODED_BYTES {
return None;
}
let inch_units = Length::UNITS_PER_INCH.checked_mul(i64::try_from(parts).ok()?)?;
Some(SurfaceReflectionFrame {
refl_box,
padded,
size: (w_px, h_px),
inch_units,
})
}
fn surface_reflection_fade(
frame: &SurfaceReflectionFrame,
reflection: DrawingMlReflection,
) -> Option<(PixelLength, PixelLength, Share, Share)> {
let h = frame.refl_box.height();
let fade_y = |pos: i64| {
let units = i64::try_from(div_round_i128(
i128::from(h.units()) * i128::from(pos),
i128::from(DRAWING_WHOLE),
))
.ok()?;
let y = frame.refl_box.top.checked_add(Length::from_units(units))?;
axis_pixel(y, frame.padded.top, frame.padded.height(), frame.size.1)
};
Some((
fade_y(reflection.start_pos)?,
fade_y(reflection.end_pos)?,
Share::ratio(reflection.start_alpha, DRAWING_WHOLE)?,
Share::ratio(reflection.end_alpha, DRAWING_WHOLE)?,
))
}
fn mirror_command_y(command: PathCommand, axis_sum: Length) -> Option<PathCommand> {
let flip = |p: Point| {
Some(Point {
x: p.x,
y: axis_sum.checked_sub(p.y)?,
})
};
Some(match command {
PathCommand::MoveTo(p) => PathCommand::MoveTo(flip(p)?),
PathCommand::LineTo(p) => PathCommand::LineTo(flip(p)?),
PathCommand::QuadTo(c, p) => PathCommand::QuadTo(flip(c)?, flip(p)?),
PathCommand::CubicTo(a, b, p) => PathCommand::CubicTo(flip(a)?, flip(b)?, flip(p)?),
PathCommand::Close => PathCommand::Close,
})
}
fn mirrored_picture_clip(
clip: (Vec<PathCommand>, FillRule),
outer_bottom: Length,
frame: &SurfaceReflectionFrame,
) -> Option<Outline> {
let axis_sum = frame.refl_box.top.checked_add(outer_bottom)?;
let mirrored: Vec<PathCommand> = clip
.0
.into_iter()
.map(|command| mirror_command_y(command, axis_sum))
.collect::<Option<_>>()?;
soft_edge_clip(&mirrored, clip.1, frame.padded, frame.size)
}
fn picture_reflection_content(
spec: &PictureReflectionPlacement<'_>,
outer_bottom: Length,
bw: Length,
frame: &SurfaceReflectionFrame,
clip: Option<(Vec<PathCommand>, FillRule)>,
) -> Option<ReflectionContent> {
let crop = soft_edge_crop(spec.crop)?;
let border = match spec.border {
Some((rgb, _)) => Some(SoftEdgeBorder {
width: to_pixel_length(bw, frame.inch_units)?,
color: [rgb.r, rgb.g, rgb.b],
}),
None => None,
};
let clip = match clip {
Some(shape) => Some(mirrored_picture_clip(shape, outer_bottom, frame)?),
None => None,
};
let (w_px, h_px) = frame.size;
let (refl_box, padded) = (frame.refl_box, frame.padded);
Some(ReflectionContent::Picture {
format: spec.format,
data: spec.data.to_vec(),
crop,
border,
clip,
pad_x: axis_pixel(refl_box.left, padded.left, padded.width(), w_px)?,
pad_y: axis_pixel(refl_box.top, padded.top, padded.height(), h_px)?,
content_width: axis_pixel(refl_box.right, refl_box.left, padded.width(), w_px)?,
content_height: axis_pixel(refl_box.bottom, refl_box.top, padded.height(), h_px)?,
})
}
pub(super) fn picture_reflection_item(mut spec: PictureReflectionPlacement<'_>) -> Option<Item> {
if spec.turn.is_some() {
return None;
}
let bw = spec
.border
.map_or(Length::ZERO, |(_, w)| w.max(Length::ZERO));
let outer = Edges {
left: spec.shown.left.checked_sub(bw)?,
top: spec.shown.top.checked_sub(bw)?,
right: spec.shown.right.checked_add(bw)?,
bottom: spec.shown.bottom.checked_add(bw)?,
};
let frame = surface_reflection_frame(outer, spec.reflection)?;
let (fade_start_y, fade_end_y, start_opacity, end_opacity) =
surface_reflection_fade(&frame, spec.reflection)?;
let clip = spec.clip.take();
let content = picture_reflection_content(&spec, outer.bottom, bw, &frame, clip)?;
let picture = Picture {
width: frame.size.0,
height: frame.size.1,
scene: Scene::SurfaceReflection(SurfaceReflection {
content,
blur: blur_sigma(spec.reflection.blur, frame.inch_units)?,
fade_start_y,
fade_end_y,
start_opacity,
end_opacity,
}),
};
Some(Item::Image(ImageItem {
x: frame.padded.left,
y: frame.padded.top,
width: frame.padded.width(),
height: frame.padded.height(),
clip: None,
turn: None,
image: Image {
format: ImageFormat::EffectPicture,
data: picture.encode().into(),
opacity: spec.opacity,
color: spec.color,
inks: InkConversion::EmbeddedProfile,
},
}))
}
fn colored_filled(item: &Item) -> Option<(Filled, Rgb)> {
match item {
Item::Path(path) => Some(((path.commands.clone(), path.fill_rule), path.color)),
Item::Rect(rect) => Some((filled(item)?, rect.color)),
Item::Gradient(_) | Item::Glyphs(_) | Item::Image(_) | Item::Group(_) => None,
}
}
pub(super) fn shape_reflection_item(
reflection: DrawingMlReflection,
items: &[Item],
) -> Option<Item> {
if items.is_empty() {
return None;
}
let colored: Vec<(Filled, Rgb)> = items
.iter()
.map(colored_filled)
.collect::<Option<Vec<_>>>()?;
let outlines: Vec<Filled> = colored.iter().map(|(f, _)| f.clone()).collect();
let outer = bounds(&outlines)?;
let frame = surface_reflection_frame(outer, reflection)?;
let (fade_start_y, fade_end_y, start_opacity, end_opacity) =
surface_reflection_fade(&frame, reflection)?;
let axis_sum = frame.refl_box.top.checked_add(outer.bottom)?;
let (w_px, h_px) = frame.size;
let place = |pt: Point| {
Some(Place {
x: axis_pixel(pt.x, frame.padded.left, frame.padded.width(), w_px)?,
y: axis_pixel(pt.y, frame.padded.top, frame.padded.height(), h_px)?,
})
};
let mut layers = Vec::with_capacity(colored.len());
for ((commands, rule), color) in colored {
let mirrored: Vec<PathCommand> = commands
.into_iter()
.map(|c| mirror_command_y(c, axis_sum))
.collect::<Option<_>>()?;
layers.push(ColoredLayer {
outline: Outline {
segments: segments(&mirrored, &place)?,
rule: match rule {
FillRule::NonZero => ShadowRule::NonZero,
FillRule::EvenOdd => ShadowRule::EvenOdd,
},
stroke: PixelLength::ZERO,
},
color: [color.r, color.g, color.b],
opacity: Share::ratio(DRAWING_WHOLE, DRAWING_WHOLE)?,
});
}
let picture = Picture {
width: w_px,
height: h_px,
scene: Scene::SurfaceReflection(SurfaceReflection {
content: ReflectionContent::Layers(layers),
blur: blur_sigma(reflection.blur, frame.inch_units)?,
fade_start_y,
fade_end_y,
start_opacity,
end_opacity,
}),
};
Some(effect_image_item(frame.padded, &picture))
}
fn picture_item(
outlines: &[(&[PathCommand], FillRule, Length)],
mask: Option<MaskPlacement>,
frame: Edges<Length>,
offset: ShadowOffset,
dilate: Length,
blur: Length,
ShadowColor { rgb, opacity }: ShadowColor,
) -> Option<Item> {
let parts = blur_parts(blur.max(dilate));
let size = (
effect_pixels(frame.width(), parts)?,
effect_pixels(frame.height(), parts)?,
);
let place = |point: Point| {
let at = |value: Length, moved: Length, first: Length, side: Length, count: u32| {
let from_first = value.units() + moved.units() - first.units();
PixelLength::ratio(from_first.checked_mul(i64::from(count))?, side.units())
};
Some(Place {
x: at(point.x, offset.across, frame.left, frame.width(), size.0)?,
y: at(point.y, offset.down, frame.top, frame.height(), size.1)?,
})
};
let inch_units = Length::UNITS_PER_INCH.checked_mul(i64::try_from(parts).ok()?)?;
let outlines = build_outlines(outlines, inch_units, &place)?;
let sigma = blur_sigma(blur, inch_units)?;
let dilate_px = to_pixel_length(dilate, inch_units)?;
let mask = match mask {
Some(mask) => Some(place_mask(mask, &place)?),
None => None,
};
let picture = Picture {
width: size.0,
height: size.1,
scene: Scene::Shadow(Shadow {
outlines,
mask,
blur: sigma,
dilate: dilate_px,
color: [rgb.r, rgb.g, rgb.b],
opacity: Share::ratio(opacity.share(), DRAWING_WHOLE)?,
}),
};
Some(effect_image_item(frame, &picture))
}
fn to_pixel_length(length: Length, inch_units: i64) -> Option<PixelLength> {
if length <= Length::ZERO {
return Some(PixelLength::ZERO);
}
PixelLength::ratio(
length.units().checked_mul(SHADOW_PIXELS_PER_INCH)?,
inch_units,
)
}
fn build_outlines(
outlines: &[(&[PathCommand], FillRule, Length)],
inch_units: i64,
place: &impl Fn(Point) -> Option<Place>,
) -> Option<Vec<Outline>> {
outlines
.iter()
.map(|&(commands, rule, stroke_width)| {
let stroke = to_pixel_length(stroke_width, inch_units)?;
Some(Outline {
segments: segments(commands, place)?,
rule: match rule {
FillRule::NonZero => ShadowRule::NonZero,
FillRule::EvenOdd => ShadowRule::EvenOdd,
},
stroke,
})
})
.collect()
}
fn place_mask(mask: MaskPlacement, place: &impl Fn(Point) -> Option<Place>) -> Option<PictureMask> {
let [origin, across, down] = mask.corners;
let crop_min = |share: i64| Share::ratio(share.clamp(0, DRAWING_WHOLE), DRAWING_WHOLE);
let crop_max = |share: i64| {
Share::ratio(
(DRAWING_WHOLE - share).clamp(0, DRAWING_WHOLE),
DRAWING_WHOLE,
)
};
Some(PictureMask {
source: mask.source,
opacity: Share::ratio(mask.opacity.share(), DRAWING_WHOLE)?,
origin: place(origin)?,
across: place(across)?,
down: place(down)?,
clip: [
crop_min(mask.crop.left)?,
crop_min(mask.crop.top)?,
crop_max(mask.crop.right)?,
crop_max(mask.crop.bottom)?,
],
})
}
fn filled(item: &Item) -> Option<Filled> {
match item {
Item::Path(path) => Some((path.commands.clone(), path.fill_rule)),
Item::Gradient(gradient) => Some((gradient.commands.clone(), gradient.fill_rule)),
Item::Rect(Rect {
x,
y,
width,
height,
..
}) => {
let corner = |dx: Length, dy: Length| Point {
x: *x + dx,
y: *y + dy,
};
let zero = Length::ZERO;
Some((
vec![
PathCommand::MoveTo(corner(zero, zero)),
PathCommand::LineTo(corner(*width, zero)),
PathCommand::LineTo(corner(*width, *height)),
PathCommand::LineTo(corner(zero, *height)),
PathCommand::Close,
],
FillRule::NonZero,
))
}
Item::Glyphs(_) | Item::Image(_) | Item::Group(_) => None,
}
}
fn moved(command: PathCommand, offset: ShadowOffset) -> PathCommand {
let to = |point: Point| Point {
x: point.x + offset.across,
y: point.y + offset.down,
};
match command {
PathCommand::MoveTo(point) => PathCommand::MoveTo(to(point)),
PathCommand::LineTo(point) => PathCommand::LineTo(to(point)),
PathCommand::QuadTo(control, point) => PathCommand::QuadTo(to(control), to(point)),
PathCommand::CubicTo(first, second, point) => {
PathCommand::CubicTo(to(first), to(second), to(point))
}
PathCommand::Close => PathCommand::Close,
}
}
fn points(command: &PathCommand) -> Vec<Point> {
match *command {
PathCommand::MoveTo(point) | PathCommand::LineTo(point) => vec![point],
PathCommand::QuadTo(control, point) => vec![control, point],
PathCommand::CubicTo(first, second, point) => vec![first, second, point],
PathCommand::Close => Vec::new(),
}
}
fn bounds(outlines: &[Filled]) -> Option<Edges<Length>> {
let mut all = outlines
.iter()
.flat_map(|(commands, _)| commands.iter().flat_map(points));
let first = all.next()?;
Some(all.fold(
Edges {
left: first.x,
top: first.y,
right: first.x,
bottom: first.y,
},
|edges, point| Edges {
left: edges.left.min(point.x),
top: edges.top.min(point.y),
right: edges.right.max(point.x),
bottom: edges.bottom.max(point.y),
},
))
}
fn exact_bounds(commands: &[PathCommand]) -> Option<Edges<Length>> {
let mut box_ = None::<Edges<Length>>;
let mut take = |x: Length, y: Length| {
box_ = Some(match box_ {
None => Edges {
left: x,
top: y,
right: x,
bottom: y,
},
Some(edges) => Edges {
left: edges.left.min(x),
top: edges.top.min(y),
right: edges.right.max(x),
bottom: edges.bottom.max(y),
},
});
};
let mut at = None;
for command in commands {
match *command {
PathCommand::MoveTo(p) | PathCommand::LineTo(p) => {
take(p.x, p.y);
at = Some(p);
}
PathCommand::QuadTo(control, end) => {
if let Some(start) = at {
if let Some(x) = super::text_path::curve_extreme([
start.x.units(),
control.x.units(),
end.x.units(),
]) {
take(Length::from_units(x), end.y);
}
if let Some(y) = super::text_path::curve_extreme([
start.y.units(),
control.y.units(),
end.y.units(),
]) {
take(end.x, Length::from_units(y));
}
}
take(end.x, end.y);
at = Some(end);
}
PathCommand::CubicTo(first, second, end) => {
for p in [first, second, end] {
take(p.x, p.y);
}
at = Some(end);
}
PathCommand::Close => {}
}
}
box_
}
fn picture_box(bounds: Edges<Length>, offset: ShadowOffset, blur: Length) -> Option<Edges<Length>> {
let step = SHADOW_BOX_STEP.units();
let grow = (blur.units().max(0) + step - 1) / step + SHADOW_BOX_ROOM;
let edge = |value: Length, moved: Length, out: i64| {
Length::from_units((div_round(value.units() + moved.units(), step) + out) * step)
};
let frame = Edges {
left: edge(bounds.left, offset.across, -grow),
top: edge(bounds.top, offset.down, -grow),
right: edge(bounds.right, offset.across, grow),
bottom: edge(bounds.bottom, offset.down, grow),
};
(frame.width() > Length::ZERO && frame.height() > Length::ZERO).then_some(frame)
}
fn blur_parts(blur: Length) -> i128 {
let span = i128::from(SHADOW_BLUR_PIXELS) * i128::from(Length::UNITS_PER_INCH);
let reach = i128::from(blur.units().max(0)) * i128::from(SHADOW_PIXELS_PER_INCH);
((reach + span - 1) / span).max(1)
}
fn segments(
commands: &[PathCommand],
place: &impl Fn(Point) -> Option<Place>,
) -> Option<Vec<Segment>> {
commands
.iter()
.map(|command| {
Some(match *command {
PathCommand::MoveTo(point) => Segment::MoveTo(place(point)?),
PathCommand::LineTo(point) => Segment::LineTo(place(point)?),
PathCommand::QuadTo(control, point) => {
Segment::QuadTo(place(control)?, place(point)?)
}
PathCommand::CubicTo(first, second, point) => {
Segment::CubicTo(place(first)?, place(second)?, place(point)?)
}
PathCommand::Close => Segment::Close,
})
})
.collect()
}
#[cfg(test)]
mod tests;