Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix clipping when a box/block has a radius #2338

Merged
merged 3 commits into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions crates/typst-library/src/layout/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,15 +146,23 @@ impl Layout for BoxElem {
frame.set_baseline(frame.baseline() - shift);
}

// Clip the contents
if self.clip(styles) {
frame.clip();
}

// Prepare fill and stroke.
let fill = self.fill(styles);
let stroke = self.stroke(styles).map(|s| s.map(Stroke::unwrap_or_default));

// Clip the contents
if self.clip(styles) {
let outset = self.outset(styles).relative_to(frame.size());
let size = frame.size() + outset.sum_by_axis();

let radius = self.radius(styles);
frame.clip(if radius.is_uniform() && radius.top_right.is_zero() {
Path::rect(size)
} else {
path_rect(size, radius, stroke.clone())
});
Dherse marked this conversation as resolved.
Show resolved Hide resolved
}

// Add fill and/or stroke.
if fill.is_some() || stroke.iter().any(Option::is_some) {
let outset = self.outset(styles);
Expand Down Expand Up @@ -408,17 +416,25 @@ impl Layout for BlockElem {
frames
};

// Prepare fill and stroke.
let fill = self.fill(styles);
let stroke = self.stroke(styles).map(|s| s.map(Stroke::unwrap_or_default));

// Clip the contents
if self.clip(styles) {
for frame in frames.iter_mut() {
frame.clip();
let outset = self.outset(styles).relative_to(frame.size());
let size = frame.size() + outset.sum_by_axis();

let radius = self.radius(styles);
frame.clip(if radius.is_uniform() && radius.top_right.is_zero() {
Path::rect(size)
} else {
path_rect(size, radius, stroke.clone())
});
}
}

// Prepare fill and stroke.
let fill = self.fill(styles);
let stroke = self.stroke(styles).map(|s| s.map(Stroke::unwrap_or_default));

// Add fill and/or stroke.
if fill.is_some() || stroke.iter().any(Option::is_some) {
let mut skip = false;
Expand Down
4 changes: 2 additions & 2 deletions crates/typst-library/src/visualize/image.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::ffi::OsStr;
use std::path::Path;

use typst::geom::Smart;
use typst::geom::{self, Smart};
use typst::image::{Image, ImageFormat, RasterFormat, VectorFormat};
use typst::util::option_eq;

Expand Down Expand Up @@ -212,7 +212,7 @@ impl Layout for ImageElem {

// Create a clipping group if only part of the image should be visible.
if fit == ImageFit::Cover && !target.fits(fitted) {
frame.clip();
frame.clip(geom::Path::rect(frame.size()));
}

// Apply metadata.
Expand Down
10 changes: 5 additions & 5 deletions crates/typst/src/doc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::export::PdfPageLabel;
use crate::font::Font;
use crate::geom::{
self, styled_rect, Abs, Axes, Color, Corners, Dir, Em, FixedAlign, FixedStroke,
Geometry, Length, Numeric, Paint, Point, Rel, Shape, Sides, Size, Transform,
Geometry, Length, Numeric, Paint, Path, Point, Rel, Shape, Sides, Size, Transform,
};
use crate::image::Image;
use crate::model::{Content, Location, MetaElem, StyleChain};
Expand Down Expand Up @@ -352,9 +352,9 @@ impl Frame {
}

/// Clip the contents of a frame to its size.
Dherse marked this conversation as resolved.
Show resolved Hide resolved
pub fn clip(&mut self) {
pub fn clip(&mut self, clip_path: Path) {
if !self.is_empty() {
self.group(|g| g.clips = true);
self.group(|g| g.clip_path = Some(clip_path));
}
}

Expand Down Expand Up @@ -505,7 +505,7 @@ pub struct GroupItem {
/// A transformation to apply to the group.
pub transform: Transform,
/// Whether the frame should be a clipping boundary.
pub clips: bool,
pub clip_path: Option<Path>,
}

impl GroupItem {
Expand All @@ -514,7 +514,7 @@ impl GroupItem {
Self {
frame,
transform: Transform::identity(),
clips: false,
clip_path: None,
}
}
}
Expand Down
10 changes: 2 additions & 8 deletions crates/typst/src/export/pdf/page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -462,14 +462,8 @@ fn write_group(ctx: &mut PageContext, pos: Point, group: &GroupItem) {
ctx.size(group.frame.size());
}

if group.clips {
let size = group.frame.size();
let w = size.x.to_f32();
let h = size.y.to_f32();
ctx.content.move_to(0.0, 0.0);
ctx.content.line_to(w, 0.0);
ctx.content.line_to(w, h);
ctx.content.line_to(0.0, h);
if let Some(clip_path) = &group.clip_path {
write_path(ctx, 0.0, 0.0, clip_path);
ctx.content.clip_nonzero();
ctx.content.end_path();
}
Expand Down
10 changes: 3 additions & 7 deletions crates/typst/src/export/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,13 +183,9 @@ fn render_group(canvas: &mut sk::Pixmap, state: State, group: &GroupItem) {

let mut mask = state.mask;
let storage;
if group.clips {
let size: geom::Axes<Abs> = group.frame.size();
let w = size.x.to_f32();
let h = size.y.to_f32();
if let Some(path) = sk::Rect::from_xywh(0.0, 0.0, w, h)
.map(sk::PathBuilder::from_rect)
.and_then(|path| path.transform(state.transform))
if let Some(clip_path) = group.clip_path.as_ref() {
if let Some(path) =
convert_path(clip_path).and_then(|path| path.transform(state.transform))
{
if let Some(mask) = mask {
let mut mask = mask.clone();
Expand Down
60 changes: 29 additions & 31 deletions crates/typst/src/export/svg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ use crate::doc::{Frame, FrameItem, FrameKind, GroupItem, TextItem};
use crate::eval::Repr;
use crate::font::Font;
use crate::geom::{
Abs, Angle, Axes, Color, FixedStroke, Geometry, Gradient, LineCap, LineJoin, Paint,
PathItem, Point, Quadrant, Ratio, RatioOrAngle, Relative, Shape, Size, Transform,
self, Abs, Angle, Axes, Color, FixedStroke, Geometry, Gradient, LineCap, LineJoin,
Paint, PathItem, Point, Quadrant, Ratio, RatioOrAngle, Relative, Shape, Size,
Transform,
};
use crate::image::{Image, ImageFormat, RasterFormat, VectorFormat};
use crate::util::hash128;
Expand Down Expand Up @@ -242,16 +243,9 @@ impl SVGRenderer {
self.xml.start_element("g");
self.xml.write_attribute("class", "typst-group");

if group.clips {
if let Some(clip_path) = &group.clip_path {
let hash = hash128(&group);
let size = group.frame.size();
let x = size.x.to_pt();
let y = size.y.to_pt();
let id = self.clip_paths.insert_with(hash, || {
let mut builder = SvgPathBuilder(EcoString::new());
builder.rect(x as f32, y as f32);
builder.0
});
let id = self.clip_paths.insert_with(hash, || convert_path(clip_path));
self.xml.write_attribute_fmt("clip-path", format_args!("url(#{id})"));
}

Expand Down Expand Up @@ -861,28 +855,32 @@ fn convert_geometry_to_path(geometry: &Geometry) -> EcoString {
let y = rect.y.to_pt() as f32;
builder.rect(x, y);
}
Geometry::Path(p) => {
for item in &p.0 {
match item {
PathItem::MoveTo(m) => {
builder.move_to(m.x.to_pt() as f32, m.y.to_pt() as f32)
}
PathItem::LineTo(l) => {
builder.line_to(l.x.to_pt() as f32, l.y.to_pt() as f32)
}
PathItem::CubicTo(c1, c2, t) => builder.curve_to(
c1.x.to_pt() as f32,
c1.y.to_pt() as f32,
c2.x.to_pt() as f32,
c2.y.to_pt() as f32,
t.x.to_pt() as f32,
t.y.to_pt() as f32,
),
PathItem::ClosePath => builder.close(),
}
Geometry::Path(p) => return convert_path(p),
};
builder.0
}

fn convert_path(path: &geom::Path) -> EcoString {
let mut builder = SvgPathBuilder::default();
for item in &path.0 {
match item {
PathItem::MoveTo(m) => {
builder.move_to(m.x.to_pt() as f32, m.y.to_pt() as f32)
}
PathItem::LineTo(l) => {
builder.line_to(l.x.to_pt() as f32, l.y.to_pt() as f32)
}
PathItem::CubicTo(c1, c2, t) => builder.curve_to(
c1.x.to_pt() as f32,
c1.y.to_pt() as f32,
c2.x.to_pt() as f32,
c2.y.to_pt() as f32,
t.x.to_pt() as f32,
t.y.to_pt() as f32,
),
PathItem::ClosePath => builder.close(),
}
};
}
builder.0
}

Expand Down
2 changes: 1 addition & 1 deletion crates/typst/src/geom/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ pub use self::paint::Paint;
pub use self::path::{Path, PathItem};
pub use self::point::Point;
pub use self::ratio::Ratio;
pub use self::rect::styled_rect;
pub use self::rect::{path_rect, styled_rect};
pub use self::rel::Rel;
pub use self::scalar::Scalar;
pub use self::shape::{Geometry, Shape};
Expand Down
111 changes: 111 additions & 0 deletions crates/typst/src/geom/rect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ impl PathExtension for Path {
}
}

/// Creates a new rectangle as a path.
pub fn path_rect(
size: Size,
radius: Corners<Rel<Abs>>,
stroke: Sides<Option<FixedStroke>>,
) -> Path {
if stroke.is_uniform() && radius.iter().cloned().all(Rel::is_zero) {
Path::rect(size)
} else {
segmented_path_rect(size, radius, stroke)
}
}

/// Create a styled rectangle with shapes.
/// - use rect primitive for simple rectangles
/// - stroke sides if possible
Expand All @@ -68,6 +81,67 @@ fn simple_rect(
vec![Shape { geometry: Geometry::Rect(size), fill, stroke }]
}

fn segmented_path_rect(
Dherse marked this conversation as resolved.
Show resolved Hide resolved
size: Size,
radius: Corners<Rel<Abs>>,
strokes: Sides<Option<FixedStroke>>,
) -> Path {
let stroke_widths = strokes
.clone()
.map(|s| s.map(|s| s.thickness / 2.0).unwrap_or(Abs::zero()));

let max_radius = (size.x.min(size.y)) / 2.0
+ stroke_widths.iter().cloned().min().unwrap_or(Abs::zero());

let radius = radius.map(|side| side.relative_to(max_radius * 2.0).min(max_radius));

let corners = Corners {
top_left: Corner::TopLeft,
top_right: Corner::TopRight,
bottom_right: Corner::BottomRight,
bottom_left: Corner::BottomLeft,
}
.map(|corner| ControlPoints {
radius: radius.get(corner),
stroke_before: stroke_widths.get(corner.side_ccw()),
stroke_after: stroke_widths.get(corner.side_cw()),
corner,
size,
same: match (
strokes.get_ref(corner.side_ccw()),
strokes.get_ref(corner.side_cw()),
) {
(Some(a), Some(b)) => a.paint == b.paint && a.dash_pattern == b.dash_pattern,
(None, None) => true,
_ => false,
},
});

// insert stroked sides below filled sides
let mut path = Path::new();
let current = corners.iter().find(|c| !c.same).map(|c| c.corner);
if let Some(mut current) = current {
// multiple segments
// start at a corner with a change between sides and iterate clockwise all other corners
let mut last = current;
for _ in 0..4 {
current = current.next_cw();
if corners.get_ref(current).same {
continue;
}
// create segment
let start = last;
let end = current;
last = current;
path_segment(start, end, &corners, &mut path);
}
} else if strokes.top.is_some() {
// single segment
path_segment(Corner::TopLeft, Corner::TopLeft, &corners, &mut path);
}
path
}

/// Use stroke and fill for the rectangle
fn segmented_rect(
size: Size,
Expand Down Expand Up @@ -171,6 +245,43 @@ fn segmented_rect(
res
}

fn path_segment(
start: Corner,
end: Corner,
corners: &Corners<ControlPoints>,
path: &mut Path,
) {
// create start corner
let c = corners.get_ref(start);
if start == end || !c.arc() {
path.move_to(c.end());
} else {
path.arc_move(c.mid(), c.center(), c.end());
}

// create corners between start and end
let mut current = start.next_cw();
while current != end {
let c = corners.get_ref(current);
if c.arc() {
path.arc_line(c.start(), c.center(), c.end());
} else {
path.line_to(c.end());
}
current = current.next_cw();
}

// create end corner
let c = corners.get_ref(end);
if !c.arc() {
path.line_to(c.start());
} else if start == end {
path.arc_line(c.start(), c.center(), c.end());
} else {
path.arc_line(c.start(), c.center(), c.mid());
}
}

/// Returns the shape for the segment and whether the shape should be drawn on top.
fn segment(
start: Corner,
Expand Down
Binary file modified tests/ref/layout/clip.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading