hayro_interpret/
soft_mask.rs

1use crate::cache::Cache;
2use crate::color::{Color, ColorComponents, ColorSpace};
3use crate::context::Context;
4use crate::device::Device;
5use crate::function::Function;
6use crate::interpret::state::State;
7use crate::util::hash128;
8use crate::x_object::{FormXObject, draw_form_xobject};
9use crate::{CacheKey, InterpreterSettings};
10use hayro_syntax::object::Name;
11use hayro_syntax::object::ObjectIdentifier;
12use hayro_syntax::object::Stream;
13use hayro_syntax::object::dict::keys::*;
14use hayro_syntax::object::{Dict, Object};
15use hayro_syntax::page::Resources;
16use hayro_syntax::xref::XRef;
17use kurbo::Affine;
18use smallvec::smallvec;
19use std::fmt::Debug;
20use std::hash::{Hash, Hasher};
21use std::ops::Deref;
22use std::sync::Arc;
23
24/// Type type of mask.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum MaskType {
27    /// A luminosity mask.
28    Luminosity,
29    /// An alpha mask.
30    Alpha,
31}
32
33/// A transfer function to apply to the opacity values of a mask.
34pub struct TransferFunction(Function);
35
36impl TransferFunction {
37    /// Apply the transfer function to the given value.
38    ///
39    /// The input value needs to be between 0 and 1 and the return value is
40    /// guaranteed to be between 0 and 1.
41    #[inline]
42    pub fn apply(&self, val: f32) -> f32 {
43        self.0
44            .eval(smallvec![val])
45            .and_then(|v| v.first().copied())
46            .unwrap_or(0.0)
47            .clamp(0.0, 1.0)
48    }
49}
50
51struct Repr<'a> {
52    obj_id: ObjectIdentifier,
53    group: FormXObject<'a>,
54    mask_type: MaskType,
55    parent_resources: Resources<'a>,
56    root_transform: Affine,
57    bbox: kurbo::Rect,
58    object_cache: Cache,
59    transfer_function: Option<TransferFunction>,
60    settings: InterpreterSettings,
61    background: Color,
62    xref: &'a XRef,
63}
64
65impl Hash for Repr<'_> {
66    fn hash<H: Hasher>(&self, state: &mut H) {
67        self.obj_id.hash(state);
68        self.root_transform.cache_key().hash(state);
69    }
70}
71
72/// A soft mask.
73#[derive(Clone, Hash)]
74pub struct SoftMask<'a>(Arc<Repr<'a>>);
75
76impl Debug for SoftMask<'_> {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        write!(f, "SoftMask({:?})", self.0.obj_id)
79    }
80}
81
82impl PartialEq for SoftMask<'_> {
83    fn eq(&self, other: &Self) -> bool {
84        self.0.obj_id == other.0.obj_id
85    }
86}
87
88impl Eq for SoftMask<'_> {}
89
90impl CacheKey for SoftMask<'_> {
91    fn cache_key(&self) -> u128 {
92        hash128(self)
93    }
94}
95
96impl<'a> SoftMask<'a> {
97    pub(crate) fn new(
98        dict: &Dict<'a>,
99        context: &Context<'a>,
100        parent_resources: Resources<'a>,
101    ) -> Option<Self> {
102        // TODO: With this setup, if there is a luminosity mask and alpha mask pointing to the
103        // same xobject, the ID will be the same.
104        let obj_id = dict.get_ref(G)?.into();
105        let group_stream = dict.get::<Stream<'_>>(G)?;
106        let group = FormXObject::new(&group_stream)?;
107        let cs = ColorSpace::new(
108            group.dict.get::<Dict<'_>>(GROUP)?.get::<Object<'_>>(CS)?,
109            &context.object_cache,
110        )?;
111        let transfer_function = dict
112            .get::<Object<'_>>(TR)
113            .and_then(|o| Function::new(&o))
114            .map(TransferFunction);
115        let (mask_type, background) = match dict.get::<Name<'_>>(S)?.deref() {
116            LUMINOSITY => {
117                let color = dict
118                    .get::<ColorComponents>(BC)
119                    .map(|c| Color::new(cs, c, 1.0))
120                    .unwrap_or(Color::new(ColorSpace::device_gray(), smallvec![0.0], 1.0));
121
122                (MaskType::Luminosity, color)
123            }
124            ALPHA => (
125                MaskType::Alpha,
126                // Background color attribute should only be used with luminosity masks.
127                Color::new(ColorSpace::device_gray(), smallvec![0.0], 1.0),
128            ),
129            _ => return None,
130        };
131
132        Some(Self(Arc::new(Repr {
133            obj_id,
134            group,
135            mask_type,
136            root_transform: context.get().ctm,
137            transfer_function,
138            bbox: context.bbox(),
139            object_cache: context.object_cache.clone(),
140            settings: context.settings.clone(),
141            xref: context.xref,
142            background,
143            parent_resources,
144        })))
145    }
146
147    /// Interpret the contents of the mask into the given device.
148    pub fn interpret(&self, device: &mut impl Device<'a>) {
149        let state = State::new(self.0.root_transform);
150        let mut ctx = Context::new_with(
151            self.0.root_transform,
152            self.0.bbox,
153            self.0.object_cache.clone(),
154            self.0.xref,
155            self.0.settings.clone(),
156            state,
157        );
158        draw_form_xobject(&self.0.parent_resources, &self.0.group, &mut ctx, device);
159    }
160
161    /// Return the object identifier of the mask.
162    ///
163    /// This can be used as a unique identifier for caching purposes.
164    pub fn id(&self) -> ObjectIdentifier {
165        self.0.obj_id
166    }
167
168    /// Return the underlying mask type.
169    pub fn mask_type(&self) -> MaskType {
170        self.0.mask_type
171    }
172
173    /// The background color against which the mask should be composited.
174    pub fn background_color(&self) -> Color {
175        self.0.background.clone()
176    }
177
178    /// Return the transfer function that should be used for the mask.
179    pub fn transfer_function(&self) -> Option<&TransferFunction> {
180        self.0.transfer_function.as_ref()
181    }
182}