1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
use super::UiTransform;
use amethyst_core::specs::prelude::{BitSet, Entities, InsertedFlag, Join, ModifiedFlag,
                                    ReadExpect, ReadStorage, ReaderId, Resources, System,
                                    WriteStorage};
use amethyst_core::{HierarchyEvent, Parent, ParentHierarchy};
use amethyst_renderer::ScreenDimensions;

/// Indicates if the position and margins should be calculated in pixel or
/// relative to their parent size.
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
pub enum ScaleMode {
    /// Use directly the pixel value.
    Pixel,
    /// Use a proportion (%) of the parent's dimensions (or screen, if there is no parent).
    Percent,
}

/// Indicated where the anchor is, relative to the parent (or to the screen, if there is no parent).
/// Follow a normal english Y,X naming.
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)]
pub enum Anchor {
    /// Anchors the entity at the top left of the parent.
    TopLeft,
    /// Anchors the entity at the top middle of the parent.
    TopMiddle,
    /// Anchors the entity at the top right of the parent.
    TopRight,
    /// Anchors the entity at the middle left of the parent.
    MiddleLeft,
    /// Anchors the entity at the center of the parent.
    Middle,
    /// Anchors the entity at the middle right of the parent.
    MiddleRight,
    /// Anchors the entity at the bottom left of the parent.
    BottomLeft,
    /// Anchors the entity at the bottom middle of the parent.
    BottomMiddle,
    /// Anchors the entity at the bottom right of the parent.
    BottomRight,
}

impl Anchor {
    /// Returns the normalized offset using the `Anchor` setting.
    /// The normalized offset is a [-0.5,0.5] value
    /// indicating the relative offset from the parent's position (centered).
    pub fn norm_offset(&self) -> (f32, f32) {
        match self {
            Anchor::TopLeft => (-0.5, -0.5),
            Anchor::TopMiddle => (0.0, -0.5),
            Anchor::TopRight => (0.5, -0.5),
            Anchor::MiddleLeft => (-0.5, 0.0),
            Anchor::Middle => (0.0, 0.0),
            Anchor::MiddleRight => (0.5, 0.0),
            Anchor::BottomLeft => (-0.5, 0.5),
            Anchor::BottomMiddle => (0.0, 0.5),
            Anchor::BottomRight => (0.5, 0.5),
        }
    }
}

/// Indicates if a component should be stretched.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum Stretch {
    /// No stretching occurs
    NoStretch,
    /// Stretches on the X axis.
    X {
        /// The margin length for the width
        x_margin: f32,
    },
    /// Stretches on the Y axis.
    Y {
        /// The margin length for the height
        y_margin: f32,
    },
    /// Stretches on both axes.
    XY {
        /// The margin length for the width
        x_margin: f32,
        /// The margin length for the height
        y_margin: f32,
    },
}

/// Manages the `Parent` component on entities having `UiTransform`
/// It does almost the same as the `TransformSystem`, but with some differences,
/// like `UiTransform` alignment and stretching.
#[derive(Default)]
pub struct UiTransformSystem {
    transform_modified: BitSet,

    inserted_transform_id: Option<ReaderId<InsertedFlag>>,
    modified_transform_id: Option<ReaderId<ModifiedFlag>>,

    parent_events_id: Option<ReaderId<HierarchyEvent>>,

    screen_size: (f32, f32),
}

impl<'a> System<'a> for UiTransformSystem {
    type SystemData = (
        Entities<'a>,
        WriteStorage<'a, UiTransform>,
        ReadStorage<'a, Parent>,
        ReadExpect<'a, ScreenDimensions>,
        ReadExpect<'a, ParentHierarchy>,
    );
    fn run(&mut self, data: Self::SystemData) {
        let (entities, mut transforms, parents, screen_dim, hierarchy) = data;
        #[cfg(feature = "profiler")]
        profile_scope!("ui_parent_system");

        self.transform_modified.clear();

        transforms.populate_inserted(
            &mut self.inserted_transform_id.as_mut().unwrap(),
            &mut self.transform_modified,
        );
        transforms.populate_modified(
            &mut self.modified_transform_id.as_mut().unwrap(),
            &mut self.transform_modified,
        );

        for event in hierarchy
            .changed()
            .read(&mut self.parent_events_id.as_mut().unwrap())
        {
            if let HierarchyEvent::Modified(entity) = *event {
                self.transform_modified.add(entity.id());
            }
        }

        let current_screen_size = (screen_dim.width(), screen_dim.height());
        let screen_resized = current_screen_size != self.screen_size;
        self.screen_size = current_screen_size;
        for (entity, _) in (&*entities, !&parents).join() {
            let self_dirty = self.transform_modified.contains(entity.id());
            if self_dirty || screen_resized {
                // By doing things this way we prevent grabbing mutable
                // borrows unnecessarily which allows us to avoid re-computing
                // for no changes.
                let transform = transforms.get_mut(entity);
                if transform.is_none() {
                    continue;
                }
                let transform = transform.unwrap();
                let norm = transform.anchor.norm_offset();
                transform.pixel_x = screen_dim.width() * norm.0;
                transform.pixel_y = screen_dim.height() * norm.1;
                transform.global_z = transform.local_z;

                let new_size = match transform.stretch {
                    Stretch::NoStretch => (transform.width, transform.height),
                    Stretch::X { x_margin } => {
                        (screen_dim.width() - x_margin * 2.0, transform.height)
                    }
                    Stretch::Y { y_margin } => {
                        (transform.width, screen_dim.height() - y_margin * 2.0)
                    }
                    Stretch::XY { x_margin, y_margin } => (
                        screen_dim.width() - x_margin * 2.0,
                        screen_dim.height() - y_margin * 2.0,
                    ),
                };
                transform.width = new_size.0;
                transform.height = new_size.1;
                match transform.scale_mode {
                    ScaleMode::Pixel => {
                        transform.pixel_x += transform.local_x;
                        transform.pixel_y += transform.local_y;
                        transform.pixel_width = transform.width;
                        transform.pixel_height = transform.height;
                    }
                    ScaleMode::Percent => {
                        transform.pixel_x += transform.local_x * screen_dim.width();
                        transform.pixel_y += transform.local_y * screen_dim.height();
                        transform.pixel_width = transform.width * screen_dim.width();
                        transform.pixel_height = transform.height * screen_dim.height();
                    }
                }
            }
        }

        // Populate the modifications we just did.
        transforms.populate_modified(
            &mut self.modified_transform_id.as_mut().unwrap(),
            &mut self.transform_modified,
        );

        // Compute transforms with parents.
        for entity in hierarchy.all() {
            {
                let self_dirty = self.transform_modified.contains(entity.id());
                let parent_entity = parents.get(*entity).unwrap().entity;
                let parent_dirty = self.transform_modified.contains(parent_entity.id());
                if parent_dirty || self_dirty || screen_resized {
                    let parent_transform_copy = transforms.get(parent_entity).cloned();
                    let transform = transforms.get_mut(*entity);
                    if parent_transform_copy.is_none() || transform.is_none() {
                        continue;
                    }
                    let parent_transform_copy = parent_transform_copy.unwrap();
                    let mut transform = transform.unwrap();
                    let norm = transform.anchor.norm_offset();
                    transform.pixel_x =
                        parent_transform_copy.pixel_x + parent_transform_copy.pixel_width * norm.0;
                    transform.pixel_y =
                        parent_transform_copy.pixel_y + parent_transform_copy.pixel_height * norm.1;
                    transform.global_z = parent_transform_copy.global_z + transform.local_z;

                    let new_size = match transform.stretch {
                        Stretch::NoStretch => (transform.width, transform.height),
                        Stretch::X { x_margin } => (
                            parent_transform_copy.pixel_width - x_margin * 2.0,
                            transform.height,
                        ),
                        Stretch::Y { y_margin } => (
                            transform.width,
                            parent_transform_copy.pixel_height - y_margin * 2.0,
                        ),
                        Stretch::XY { x_margin, y_margin } => (
                            parent_transform_copy.pixel_width - x_margin * 2.0,
                            parent_transform_copy.pixel_height - y_margin * 2.0,
                        ),
                    };
                    transform.width = new_size.0;
                    transform.height = new_size.1;
                    match transform.scale_mode {
                        ScaleMode::Pixel => {
                            transform.pixel_x += transform.local_x;
                            transform.pixel_y += transform.local_y;
                            transform.pixel_width = transform.width;
                            transform.pixel_height = transform.height;
                        }
                        ScaleMode::Percent => {
                            transform.pixel_x +=
                                transform.local_x * parent_transform_copy.pixel_width;
                            transform.pixel_y +=
                                transform.local_y * parent_transform_copy.pixel_height;
                            transform.pixel_width =
                                transform.width * parent_transform_copy.pixel_width;
                            transform.pixel_height =
                                transform.height * parent_transform_copy.pixel_height;
                        }
                    }
                }
            }
            // Populate the modifications we just did.
            transforms.populate_modified(
                &mut self.modified_transform_id.as_mut().unwrap(),
                &mut self.transform_modified,
            );
        }
        // We need to treat any changes done inside the system as non-modifications, so we read out
        // any events that were generated during the system run
        transforms.populate_inserted(
            &mut self.inserted_transform_id.as_mut().unwrap(),
            &mut self.transform_modified,
        );
        transforms.populate_modified(
            &mut self.modified_transform_id.as_mut().unwrap(),
            &mut self.transform_modified,
        );
    }

    fn setup(&mut self, res: &mut Resources) {
        use amethyst_core::specs::prelude::SystemData;
        Self::SystemData::setup(res);
        self.parent_events_id = Some(res.fetch_mut::<ParentHierarchy>().track());
        let mut transforms = WriteStorage::<UiTransform>::fetch(res);
        self.inserted_transform_id = Some(transforms.track_inserted());
        self.modified_transform_id = Some(transforms.track_modified());
    }
}