use super::*;
impl WorkerLayoutScratch {
pub(crate) fn begin_pass(&mut self) {
let Self {
flow_scratch,
abs_scratch,
flex_items_scratch,
flex_lines_scratch,
translate_arena_scratch,
translate_bfs_scratch,
nodes_computed,
nodes_changed,
simd_translations,
simd_text_measures,
..
} = self;
flow_scratch.clear();
abs_scratch.clear();
flex_items_scratch.clear();
flex_lines_scratch.clear();
translate_arena_scratch.clear();
translate_bfs_scratch.clear();
*nodes_computed = 0;
*nodes_changed = 0;
*simd_translations = 0;
*simd_text_measures = 0;
}
pub(crate) fn measure_text_cached(
&mut self,
text: &str,
is_ascii: bool,
text_style: TextStyle,
max_width: Option<f32>,
) -> TextSizeMeasurement {
let (hash_a, hash_b): (u64, u64) = TextSizeCache::hash_text_128(text.as_bytes());
let Self {
text_size_cache,
simd_text_measures,
..
} = self;
let mut used_simd: bool = false;
let measured: TextSizeMeasurement = text_size_cache.get_or_measure_hashed(
text,
(hash_a, hash_b, text.len() as u32),
text_style,
max_width,
|sample_text: &str, sample_style: TextStyle, width_limit: Option<f32>| -> Size {
let (measured_size, hit_simd): (Size, bool) =
measure_text_simd_or_fallback(sample_text, is_ascii, sample_style, width_limit);
if hit_simd {
used_simd = true;
}
measured_size
},
);
if used_simd {
*simd_text_measures = simd_text_measures.saturating_add(1);
}
measured
}
}
unsafe impl Sync for WorkerScratchBank {}
impl Default for WorkerScratchBank {
fn default() -> Self {
let mut lanes: Vec<UnsafeCell<WorkerLayoutScratch>> =
Vec::with_capacity(PARALLEL_SCRATCH_LANES);
for _ in 0..PARALLEL_SCRATCH_LANES {
lanes.push(UnsafeCell::new(WorkerLayoutScratch::default()));
}
Self { lanes }
}
}
impl Clone for WorkerScratchBank {
fn clone(&self) -> Self {
Self::default()
}
}
impl WorkerScratchBank {
pub(crate) fn begin_pass(&mut self) {
let Self { lanes } = self;
for lane_cell in lanes.iter_mut() {
lane_cell.get_mut().begin_pass();
}
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
pub(crate) fn lane_ptr(&self, lane_index: usize) -> *mut WorkerLayoutScratch {
let Self { lanes } = self;
let clamped: usize = lane_index.min(lanes.len().saturating_sub(1));
lanes[clamped].get()
}
pub(crate) fn aggregate_metrics(&mut self) -> (usize, usize, usize, usize) {
let Self { lanes } = self;
let mut computed_total: usize = 0;
let mut changed_total: usize = 0;
let mut simd_trans_total: usize = 0;
let mut simd_text_total: usize = 0;
for lane_cell in lanes.iter_mut() {
let lane: &WorkerLayoutScratch = lane_cell.get_mut();
computed_total = computed_total.saturating_add(lane.nodes_computed);
changed_total = changed_total.saturating_add(lane.nodes_changed);
simd_trans_total = simd_trans_total.saturating_add(lane.simd_translations);
simd_text_total = simd_text_total.saturating_add(lane.simd_text_measures);
}
(
computed_total,
changed_total,
simd_trans_total,
simd_text_total,
)
}
}
impl ParallelOutputArena {
pub(crate) fn prepare_from_soa(&mut self, soa: &SceneLayoutSoa) {
let src_boxes: &[LayoutBox] = soa.get_layout_boxes().as_slice();
let arena_len: usize = src_boxes.len();
let Self {
boxes,
constraints,
subtree_bounds,
results,
} = self;
boxes.clear();
boxes.extend_from_slice(src_boxes);
constraints.clear();
constraints.resize(arena_len, None);
subtree_bounds.clear();
subtree_bounds.resize(arena_len, Rect::default());
results.clear();
results.resize(arena_len, ParallelNodeResult::default());
}
pub(crate) fn as_disjoint_view(&mut self) -> DisjointOutputView {
let Self {
boxes,
constraints,
subtree_bounds,
results,
} = self;
DisjointOutputView {
boxes_ptr: boxes.as_mut_ptr(),
constraints_ptr: constraints.as_mut_ptr(),
subtree_bounds_ptr: subtree_bounds.as_mut_ptr(),
results_ptr: results.as_mut_ptr(),
arena_len: boxes.len(),
}
}
}
unsafe impl Send for DisjointOutputView {}
unsafe impl Sync for DisjointOutputView {}
impl DisjointOutputView {
#[cfg_attr(not(target_arch = "wasm32"), inline)]
pub(crate) unsafe fn read_box(&self, arena_index: usize) -> LayoutBox {
let Self {
boxes_ptr,
arena_len,
..
} = self;
if arena_index >= *arena_len {
return LayoutBox::default();
}
unsafe { *boxes_ptr.add(arena_index) }
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
pub(crate) unsafe fn write_box(&self, arena_index: usize, next_box: LayoutBox) {
let Self {
boxes_ptr,
arena_len,
..
} = self;
if arena_index < *arena_len {
unsafe {
*boxes_ptr.add(arena_index) = next_box;
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
pub(crate) unsafe fn write_constraint(&self, arena_index: usize, space: AvailableSpace) {
let Self {
constraints_ptr,
arena_len,
..
} = self;
if arena_index < *arena_len {
unsafe {
*constraints_ptr.add(arena_index) = Some(space);
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
pub(crate) unsafe fn read_constraint(&self, arena_index: usize) -> Option<AvailableSpace> {
let Self {
constraints_ptr,
arena_len,
..
} = self;
if arena_index >= *arena_len {
return None;
}
unsafe { *constraints_ptr.add(arena_index) }
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
pub(crate) unsafe fn read_subtree_bounds(&self, arena_index: usize) -> Rect {
let Self {
subtree_bounds_ptr,
arena_len,
..
} = self;
if arena_index >= *arena_len {
return Rect::default();
}
unsafe { *subtree_bounds_ptr.add(arena_index) }
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
pub(crate) unsafe fn write_subtree_bounds(&self, arena_index: usize, bounds: Rect) {
let Self {
subtree_bounds_ptr,
arena_len,
..
} = self;
if arena_index < *arena_len {
unsafe {
*subtree_bounds_ptr.add(arena_index) = bounds;
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
pub(crate) unsafe fn read_result(&self, arena_index: usize) -> ParallelNodeResult {
let Self {
results_ptr,
arena_len,
..
} = self;
if arena_index >= *arena_len {
return ParallelNodeResult::default();
}
unsafe { *results_ptr.add(arena_index) }
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
pub(crate) unsafe fn write_result(&self, arena_index: usize, result: ParallelNodeResult) {
let Self {
results_ptr,
arena_len,
..
} = self;
if arena_index < *arena_len {
unsafe {
*results_ptr.add(arena_index) = result;
}
}
}
}
#[cfg(not(target_arch = "wasm32"))]
unsafe impl Send for DisjointOutcomeView {}
#[cfg(not(target_arch = "wasm32"))]
unsafe impl Sync for DisjointOutcomeView {}
#[cfg(not(target_arch = "wasm32"))]
impl DisjointOutcomeView {
#[cfg_attr(not(target_arch = "wasm32"), inline)]
pub(crate) unsafe fn write_outcome(&self, task_index: usize, outcome: ParallelChildOutcome) {
let Self {
outcomes_ptr,
outcomes_len,
} = self;
if task_index < *outcomes_len {
unsafe {
*outcomes_ptr.add(task_index) = outcome;
}
}
}
}
impl Default for ParallelLayoutSolver {
fn default() -> Self {
Self {
scratch_bank: WorkerScratchBank::default(),
output_arena: ParallelOutputArena::default(),
#[cfg(not(target_arch = "wasm32"))]
child_tasks: Vec::new(),
#[cfg(not(target_arch = "wasm32"))]
child_outcomes: Vec::new(),
last_stats: ParallelLayoutStats::default(),
}
}
}
impl Clone for ParallelLayoutSolver {
fn clone(&self) -> Self {
let Self {
output_arena,
last_stats,
..
} = self;
Self {
scratch_bank: WorkerScratchBank::default(),
output_arena: output_arena.clone(),
#[cfg(not(target_arch = "wasm32"))]
child_tasks: Vec::new(),
#[cfg(not(target_arch = "wasm32"))]
child_outcomes: Vec::new(),
last_stats: *last_stats,
}
}
}
impl ParallelLayoutSolver {
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
pub fn last_stats(&self) -> ParallelLayoutStats {
let Self { last_stats, .. } = self;
*last_stats
}
pub(crate) fn compute_synced(
&mut self,
tree: &mut SceneTree,
soa: &mut SceneLayoutSoa,
split_cache: &mut SplitLayoutCache,
viewport: Size,
) -> LayoutStats {
let _: SoaSyncMode = soa.sync_from_tree(tree);
if soa.get_topology().node_count() == 0 {
return LayoutStats::default();
}
let Self {
scratch_bank,
output_arena,
#[cfg(not(target_arch = "wasm32"))]
child_tasks,
#[cfg(not(target_arch = "wasm32"))]
child_outcomes,
last_stats,
} = self;
scratch_bank.begin_pass();
output_arena.prepare_from_soa(soa);
#[cfg(not(target_arch = "wasm32"))]
{
child_tasks.clear();
child_outcomes.clear();
}
let output_view: DisjointOutputView = output_arena.as_disjoint_view();
#[cfg(not(target_arch = "wasm32"))]
let pool: &EngineWorkerPool = global_engine_worker_pool();
#[cfg(not(target_arch = "wasm32"))]
let available_threads: usize = pool.total_threads();
#[cfg(target_arch = "wasm32")]
let available_threads: usize = 1;
#[cfg(not(target_arch = "wasm32"))]
let mut dispatched_tasks: usize = 0;
#[cfg(target_arch = "wasm32")]
let dispatched_tasks: usize = 0;
let root_space: AvailableSpace = AvailableSpace::root(viewport);
#[cfg(not(target_arch = "wasm32"))]
let _: (Size, u8, f32) = {
let mut fork_ctx: ParallelForkContext<'_> = ParallelForkContext {
soa,
output_view,
scratch_bank,
pool,
child_tasks,
child_outcomes,
dispatched_tasks: &mut dispatched_tasks,
};
Self::solve_node_dispatch(&mut fork_ctx, 0, root_space, LayoutRunMode::PerformLayout)
};
#[cfg(target_arch = "wasm32")]
let _: (Size, u8, f32) = {
let lane_zero: &mut WorkerLayoutScratch = unsafe { &mut *scratch_bank.lane_ptr(0) };
Self::solve_node_serial(
soa,
output_view,
lane_zero,
0,
root_space,
LayoutRunMode::PerformLayout,
)
};
let (nodes_computed, nodes_changed, simd_translations, simd_text_measures): (
usize,
usize,
usize,
usize,
) = scratch_bank.aggregate_metrics();
Self::commit_arena_to_tree(tree, soa, output_arena, split_cache);
soa.sync_gpu_outputs_from_boxes();
*last_stats = ParallelLayoutStats::new(
dispatched_tasks > 0,
dispatched_tasks,
available_threads,
simd_translations,
simd_text_measures,
nodes_computed,
nodes_changed,
);
let mut layout_stats: LayoutStats = LayoutStats::new(nodes_computed, 0);
let _: &mut LayoutStats = layout_stats.set_nodes_changed(nodes_changed);
layout_stats
}
fn commit_arena_to_tree(
tree: &mut SceneTree,
soa: &mut SceneLayoutSoa,
arena: &ParallelOutputArena,
split_cache: &mut SplitLayoutCache,
) {
let SceneLayoutSoa {
topology,
node_ids,
layout_boxes,
dirty_masks,
..
} = soa;
let bfs_to_arena: &[u32] = topology.get_bfs_to_arena().as_slice();
let arena_len: usize = arena.boxes.len();
let soa_boxes: &mut [LayoutBox] = layout_boxes.as_mut_slice();
let soa_dirty: &mut [u16] = dirty_masks.as_mut_slice();
for &arena_u32 in bfs_to_arena.iter() {
let slot_idx: usize = arena_u32 as usize;
if slot_idx >= arena_len {
continue;
}
let node_res: ParallelNodeResult = arena.results[slot_idx];
if !node_res.written {
continue;
}
let out_box: LayoutBox = arena.boxes[slot_idx];
let out_space_opt: Option<AvailableSpace> = arena.constraints[slot_idx];
let out_sub_bounds: Rect = arena.subtree_bounds[slot_idx];
soa_boxes[slot_idx] = out_box;
soa_dirty[slot_idx] &= !DIRTY_LAYOUT_PASS_MASK;
let node_id: NodeId = node_ids[slot_idx];
let (_, content_gen): (usize, u32) = split_cache.prepare_node(node_id, true);
if let Some(node) = tree.get_mut_nodes().get_mut(slot_idx) {
let mut had_hidden_sub: bool = false;
if node_res.hidden {
had_hidden_sub = node.get_dirty().intersects(DIRTY_SUBTREE_LAYOUT);
}
let _: &mut LayoutBox = node
.get_mut_layout_box()
.set_bounds(out_box.get_bounds())
.set_content_bounds(out_box.get_content_bounds())
.set_content_size(out_box.get_content_size());
let _: &mut SceneNode = node.set_last_constraint(out_space_opt);
node.get_mut_dirty().remove(DIRTY_LAYOUT_PASS_MASK);
if had_hidden_sub {
tree.set_has_stale_hidden_dirty(true);
}
}
if let Some(meta) = tree.get_mut_meta().get_mut(slot_idx) {
let next_dirty: u16 = meta.get_dirty() & !DIRTY_LAYOUT_PASS_MASK;
let _: &mut NodeMeta = meta.set_dirty(next_dirty);
}
if let Some(space) = out_space_opt {
split_cache.store_final(
slot_idx,
FinalLayoutSlot {
space,
subtree_gen: content_gen,
size: node_res.size,
bounds: node_res.natural_bounds,
content_bounds: node_res.natural_content_bounds,
content_size: out_box.get_content_size(),
dep_flags: node_res.dep_flags,
min_avail_w: node_res.min_avail_w,
post_stretched: node_res.post_stretched,
hidden: node_res.hidden,
},
);
if !node_res.hidden {
split_cache.store_measure(
slot_idx,
space,
LayoutRunMode::PerformLayout,
content_gen,
(node_res.size, node_res.dep_flags, node_res.min_avail_w),
);
}
}
split_cache.store_subtree_meta(slot_idx, out_sub_bounds, node_res.has_nonzero_z);
}
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
fn rect_approx_eq(first: Rect, second: Rect) -> bool {
(first.get_x() - second.get_x()).abs() <= 0.001
&& (first.get_y() - second.get_y()).abs() <= 0.001
&& (first.get_width() - second.get_width()).abs() <= 0.001
&& (first.get_height() - second.get_height()).abs() <= 0.001
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
fn size_approx_eq(first: Size, second: Size) -> bool {
(first.get_width() - second.get_width()).abs() <= 0.001
&& (first.get_height() - second.get_height()).abs() <= 0.001
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
fn is_viewport_length(length: Length) -> bool {
matches!(length, Length::ViewportWidth(_) | Length::ViewportHeight(_))
}
fn translate_subtree_bfs(
soa: &SceneLayoutSoa,
output_view: DisjointOutputView,
scratch: &mut WorkerLayoutScratch,
root_bfs: u32,
delta_x: f32,
delta_y: f32,
) {
if delta_x == 0.0 && delta_y == 0.0 {
return;
}
let topology: &FlatBfsTopology = soa.get_topology();
let bfs_to_arena: &[u32] = topology.get_bfs_to_arena().as_slice();
let layout_styles: &[LayoutStyle] = soa.get_layout_styles().as_slice();
let WorkerLayoutScratch {
translate_arena_scratch,
translate_bfs_scratch,
simd_translations,
..
} = scratch;
translate_arena_scratch.clear();
translate_bfs_scratch.clear();
translate_bfs_scratch.push(root_bfs);
let mut is_root: bool = true;
while let Some(cur_bfs) = translate_bfs_scratch.pop() {
let arena_u32: u32 = bfs_to_arena[cur_bfs as usize];
let arena_idx: usize = arena_u32 as usize;
let style: LayoutStyle = layout_styles[arena_idx];
if !is_root && style.get_position() == Position::Fixed {
continue;
}
is_root = false;
unsafe {
if let Some(mut saved_space) = output_view.read_constraint(arena_idx) {
let next_ox: f32 = saved_space.get_origin_x() + delta_x;
let next_oy: f32 = saved_space.get_origin_y() + delta_y;
let _: &mut AvailableSpace =
saved_space.set_origin_x(next_ox).set_origin_y(next_oy);
output_view.write_constraint(arena_idx, saved_space);
}
}
if style.get_display() == Display::None {
continue;
}
translate_arena_scratch.push(arena_u32);
unsafe {
let prev_sub: Rect = output_view.read_subtree_bounds(arena_idx);
if prev_sub.get_width() > 0.0 || prev_sub.get_height() > 0.0 {
output_view.write_subtree_bounds(
arena_idx,
simd_translate_rect(prev_sub, delta_x, delta_y),
);
}
let mut prev_res: ParallelNodeResult = output_view.read_result(arena_idx);
if prev_res.written && !prev_res.hidden {
prev_res.natural_bounds =
simd_translate_rect(prev_res.natural_bounds, delta_x, delta_y);
prev_res.natural_content_bounds =
simd_translate_rect(prev_res.natural_content_bounds, delta_x, delta_y);
output_view.write_result(arena_idx, prev_res);
}
}
let (child_start, child_end): (usize, usize) =
topology.children_bfs_range(cur_bfs as usize);
for child_bfs in child_start..child_end {
translate_bfs_scratch.push(child_bfs as u32);
}
}
let shifted_count: usize = unsafe {
simd_translate_subtree_ptr_4x(
output_view.boxes_ptr,
output_view.arena_len,
translate_arena_scratch.as_slice(),
delta_x,
delta_y,
)
};
*simd_translations = simd_translations.saturating_add(shifted_count);
}
#[cfg(not(target_arch = "wasm32"))]
fn solve_node_dispatch(
fork_ctx: &mut ParallelForkContext<'_>,
bfs_index: u32,
space: AvailableSpace,
mode: LayoutRunMode,
) -> (Size, u8, f32) {
let soa: &SceneLayoutSoa = fork_ctx.soa;
let output_view: DisjointOutputView = fork_ctx.output_view;
let scratch_bank: &WorkerScratchBank = fork_ctx.scratch_bank;
let pool: &EngineWorkerPool = fork_ctx.pool;
let topology: &FlatBfsTopology = soa.get_topology();
let subtree_weight: usize = topology
.get_subtree_sizes()
.get(bfs_index as usize)
.copied()
.unwrap_or(1) as usize;
if pool.worker_count() == 0 || subtree_weight < PARALLEL_LAYOUT_MIN_SUBTREE_NODES {
let lane_zero: &mut WorkerLayoutScratch = unsafe { &mut *scratch_bank.lane_ptr(0) };
return Self::solve_node_serial(soa, output_view, lane_zero, bfs_index, space, mode);
}
let arena_idx: usize = topology.get_bfs_to_arena()[bfs_index as usize] as usize;
let layout_style: LayoutStyle = soa.get_layout_styles()[arena_idx];
if layout_style.get_display() == Display::None {
let lane_zero: &mut WorkerLayoutScratch = unsafe { &mut *scratch_bank.lane_ptr(0) };
return Self::solve_node_serial(soa, output_view, lane_zero, bfs_index, space, mode);
}
let kind_tag: SoaNodeKindTag = soa.get_node_kinds()[arena_idx];
let (child_start, child_end): (usize, usize) =
topology.children_bfs_range(bfs_index as usize);
let child_count: usize = child_end.saturating_sub(child_start);
if child_count == 0
|| matches!(
kind_tag,
SoaNodeKindTag::Text | SoaNodeKindTag::Image | SoaNodeKindTag::Input
)
{
let lane_zero: &mut WorkerLayoutScratch = unsafe { &mut *scratch_bank.lane_ptr(0) };
return Self::solve_node_serial(soa, output_view, lane_zero, bfs_index, space, mode);
}
let constraints: ResolvedNodeConstraints =
Self::resolve_container_constraints(soa, arena_idx, layout_style, space);
let node_overflow: Overflow = layout_style.get_overflow();
let node_flex_grow: f32 = layout_style.get_flex_grow();
let width_independent: bool = constraints.explicit_w.is_some()
|| (constraints.stretched_w
&& constraints.resolved_w.is_some()
&& (node_overflow != Overflow::Visible || node_flex_grow > 0.0));
if mode == LayoutRunMode::ComputeSize
&& width_independent
&& constraints.resolved_h.is_some()
{
let lane_zero: &mut WorkerLayoutScratch = unsafe { &mut *scratch_bank.lane_ptr(0) };
lane_zero.nodes_computed = lane_zero.nodes_computed.saturating_add(1);
let final_w: f32 = constraints
.resolved_w
.unwrap_or(0.0)
.clamp(constraints.min_w, constraints.max_w)
.max(0.0);
let final_h: f32 = constraints
.resolved_h
.unwrap_or(0.0)
.clamp(constraints.min_h, constraints.max_h)
.max(0.0);
return (Size::new(final_w, final_h), constraints.own_deps, 0.0);
}
let min_inner_size: Size = Size::new(
(constraints.min_w - constraints.chrome_h).max(0.0),
(constraints.min_h - constraints.chrome_v).max(0.0),
);
let frame: ContainerFrame = ContainerFrame::new(
layout_style,
Size::new(constraints.inner_avail_w, constraints.inner_avail_h),
space.get_viewport(),
Point::new(constraints.content_origin_x, constraints.content_origin_y),
constraints.resolved_w.is_some(),
constraints.resolved_h.is_some(),
min_inner_size,
);
let (content_size, child_deps, child_min_aw): (Size, u8, f32) =
Self::solve_children_dispatch(fork_ctx, (child_start, child_end), frame, mode);
let lane_zero: &mut WorkerLayoutScratch = unsafe { &mut *scratch_bank.lane_ptr(0) };
lane_zero.nodes_computed = lane_zero.nodes_computed.saturating_add(1);
Self::finalize_node_box(
soa,
output_view,
lane_zero,
(layout_style, space, mode, arena_idx),
constraints,
(content_size, child_deps, child_min_aw),
Some((child_start, child_end)),
)
}
#[cfg(not(target_arch = "wasm32"))]
fn solve_children_dispatch(
fork_ctx: &mut ParallelForkContext<'_>,
child_range: (usize, usize),
frame: ContainerFrame,
mode: LayoutRunMode,
) -> (Size, u8, f32) {
let (child_start, child_end): (usize, usize) = child_range;
let child_count: usize = child_end.saturating_sub(child_start);
if child_count == 0 {
return (Size::default(), LAYOUT_DEP_NONE, 0.0);
}
let soa: &SceneLayoutSoa = fork_ctx.soa;
let output_view: DisjointOutputView = fork_ctx.output_view;
let scratch_bank: &WorkerScratchBank = fork_ctx.scratch_bank;
let topology: &FlatBfsTopology = soa.get_topology();
let bfs_to_arena: &[u32] = topology.get_bfs_to_arena().as_slice();
let layout_styles: &[LayoutStyle] = soa.get_layout_styles().as_slice();
let node_kinds: &[SoaNodeKindTag] = soa.get_node_kinds().as_slice();
let text_styles: &[TextStyle] = soa.get_text_styles().as_slice();
let parent_layout: LayoutStyle = frame.get_parent_layout();
let inner_avail: Size = frame.get_inner_avail();
let viewport: Size = frame.get_viewport();
let content_origin: Point = frame.get_content_origin();
let flex_dir_opt: Option<FlexDirection> = match parent_layout.get_display() {
Display::Grid => None,
Display::Block => Some(FlexDirection::Column),
Display::Flex | Display::None => Some(parent_layout.get_flex_direction()),
};
let is_row_dir: bool = matches!(
flex_dir_opt,
Some(FlexDirection::Row | FlexDirection::RowReverse)
);
let is_reverse_dir: bool = matches!(
flex_dir_opt,
Some(FlexDirection::RowReverse | FlexDirection::ColumnReverse)
);
let parent_align: AlignItems = parent_layout.get_align_items();
let parent_height_auto: bool = parent_layout.get_height() == Length::Auto;
let parent_bounded_main: bool = if is_row_dir {
frame.get_definite_width() || parent_layout.get_max_width() != Length::Auto
} else {
frame.get_definite_height() || parent_layout.get_max_height() != Length::Auto
};
let mut single_pass_ok: bool = flex_dir_opt.is_some()
&& parent_layout.get_flex_wrap() != FlexWrap::Wrap
&& !is_reverse_dir
&& parent_layout.get_justify_content() == JustifyContent::Start;
let mut shrinkable_flow_children: usize = 0;
let mut flow_children: Vec<u32> = Vec::with_capacity(child_count);
let mut abs_children: Vec<u32> = Vec::new();
let mut flow_subtree_nodes: usize = 0;
for (cur_bfs, &arena_u32) in bfs_to_arena
.iter()
.enumerate()
.take(child_end)
.skip(child_start)
{
let arena_idx: usize = arena_u32 as usize;
let child_layout: LayoutStyle = layout_styles[arena_idx];
if child_layout.get_display() == Display::None {
if mode == LayoutRunMode::PerformLayout {
let lane_zero: &mut WorkerLayoutScratch =
unsafe { &mut *scratch_bank.lane_ptr(0) };
let _: (Size, u8, f32) = Self::solve_node_serial(
soa,
output_view,
lane_zero,
cur_bfs as u32,
AvailableSpace::new(0.0, 0.0, viewport, 0.0, 0.0),
LayoutRunMode::PerformLayout,
);
}
continue;
}
match child_layout.get_position() {
Position::Relative => {
if single_pass_ok {
if parent_bounded_main && child_layout.get_flex_shrink() > 0.0 {
let can_shrink_child: bool = if is_row_dir {
child_layout.get_min_width() != Length::Auto
|| child_layout.get_overflow() != Overflow::Visible
|| node_kinds[arena_idx] != SoaNodeKindTag::Text
|| text_styles[arena_idx].get_overflow() != TextOverflow::Clip
} else {
child_layout.get_min_height() != Length::Auto
|| child_layout.get_overflow() != Overflow::Visible
};
if can_shrink_child {
shrinkable_flow_children =
shrinkable_flow_children.saturating_add(1);
}
}
if child_layout.get_flex_grow() > 0.0
|| child_layout.get_flex_basis() != Length::Auto
{
single_pass_ok = false;
} else {
let align: AlignItems = match child_layout.get_align_self() {
AlignSelf::Auto => parent_align,
AlignSelf::Stretch => AlignItems::Stretch,
AlignSelf::Start => AlignItems::Start,
AlignSelf::Center => AlignItems::Center,
AlignSelf::End => AlignItems::End,
};
let non_start_align: bool =
matches!(align, AlignItems::Center | AlignItems::End);
let auto_row_stretch: bool = align == AlignItems::Stretch
&& is_row_dir
&& child_layout.get_height() == Length::Auto
&& (parent_height_auto
|| frame.get_min_inner_size().get_height() > 0.0);
if non_start_align || auto_row_stretch {
single_pass_ok = false;
}
}
}
flow_children.push(cur_bfs as u32);
let child_weight: usize = topology
.get_subtree_sizes()
.get(cur_bfs)
.copied()
.unwrap_or(1) as usize;
flow_subtree_nodes = flow_subtree_nodes.saturating_add(child_weight);
}
Position::Absolute | Position::Fixed => {
if mode == LayoutRunMode::PerformLayout {
abs_children.push(cur_bfs as u32);
}
}
}
}
let flow_count: usize = flow_children.len();
if single_pass_ok && shrinkable_flow_children > 0 && (!is_row_dir || flow_count >= 2) {
single_pass_ok = false;
}
let can_fork_here: bool = flow_count >= PARALLEL_LAYOUT_MIN_CHILDREN
&& flow_subtree_nodes >= PARALLEL_LAYOUT_MIN_SUBTREE_NODES;
let flow_result: (Size, u8, f32) = if let Some(flex_dir) = flex_dir_opt {
if single_pass_ok && can_fork_here {
Self::solve_flex_single_pass_parallel(
fork_ctx,
flow_children.as_slice(),
frame,
flex_dir,
mode,
)
} else if single_pass_ok {
Self::solve_flex_single_pass_recurse(
fork_ctx,
flow_children.as_slice(),
frame,
flex_dir,
mode,
)
} else {
Self::solve_flex_two_pass_dispatch(
fork_ctx,
flow_children.as_slice(),
frame,
flex_dir,
mode,
can_fork_here,
)
}
} else if can_fork_here {
Self::solve_grid_parallel(fork_ctx, flow_children.as_slice(), frame, mode)
} else {
Self::solve_grid_recurse(fork_ctx, flow_children.as_slice(), frame, mode)
};
if mode == LayoutRunMode::PerformLayout && !abs_children.is_empty() {
let lane_zero: &mut WorkerLayoutScratch = unsafe { &mut *scratch_bank.lane_ptr(0) };
Self::solve_absolute_children_serial(
soa,
output_view,
lane_zero,
abs_children.as_slice(),
inner_avail,
viewport,
content_origin,
);
}
flow_result
}
#[cfg(not(target_arch = "wasm32"))]
fn run_parallel_child_wave(fork_ctx: &mut ParallelForkContext<'_>) {
let soa: &SceneLayoutSoa = fork_ctx.soa;
let output_view: DisjointOutputView = fork_ctx.output_view;
let scratch_bank: &WorkerScratchBank = fork_ctx.scratch_bank;
let pool: &EngineWorkerPool = fork_ctx.pool;
let tasks: &[ParallelChildTask] = fork_ctx.child_tasks.as_slice();
fork_ctx.child_outcomes.clear();
fork_ctx
.child_outcomes
.resize(tasks.len(), ParallelChildOutcome::default());
let outcome_view: DisjointOutcomeView = DisjointOutcomeView {
outcomes_ptr: fork_ctx.child_outcomes.as_mut_ptr(),
outcomes_len: fork_ctx.child_outcomes.len(),
};
*fork_ctx.dispatched_tasks = fork_ctx.dispatched_tasks.saturating_add(tasks.len());
pool.parallel_work_steal(
tasks,
|task_idx: usize, task: &ParallelChildTask, worker_lane: usize| {
let scratch: &mut WorkerLayoutScratch =
unsafe { &mut *scratch_bank.lane_ptr(worker_lane) };
let (size, dep_flags, min_avail_w): (Size, u8, f32) = Self::solve_node_serial(
soa,
output_view,
scratch,
task.bfs_index,
task.space,
task.mode,
);
unsafe {
outcome_view.write_outcome(
task_idx,
ParallelChildOutcome {
size,
dep_flags,
min_avail_w,
},
);
}
},
);
}
#[cfg(not(target_arch = "wasm32"))]
fn solve_grid_parallel(
fork_ctx: &mut ParallelForkContext<'_>,
flow_children: &[u32],
frame: ContainerFrame,
mode: LayoutRunMode,
) -> (Size, u8, f32) {
if flow_children.is_empty() {
return (Size::default(), LAYOUT_DEP_NONE, 0.0);
}
let soa: &SceneLayoutSoa = fork_ctx.soa;
let output_view: DisjointOutputView = fork_ctx.output_view;
let scratch_bank: &WorkerScratchBank = fork_ctx.scratch_bank;
let parent_layout: LayoutStyle = frame.get_parent_layout();
let inner_avail: Size = frame.get_inner_avail();
let viewport: Size = frame.get_viewport();
let content_origin: Point = frame.get_content_origin();
let cols: usize = (parent_layout.get_grid_columns() as usize).max(1);
let col_gap: f32 = parent_layout.get_column_gap();
let row_gap: f32 = parent_layout.get_row_gap();
let total_col_gaps: f32 = col_gap * ((cols.saturating_sub(1)) as f32);
let col_w: f32 = ((inner_avail.get_width() - total_col_gaps) / (cols as f32)).max(0.0);
let col_step: f32 = col_w + col_gap;
let origin_x: f32 = content_origin.get_x();
let origin_y: f32 = content_origin.get_y();
let inner_h: f32 = inner_avail.get_height();
let bfs_to_arena: &[u32] = soa.get_topology().get_bfs_to_arena().as_slice();
let layout_styles: &[LayoutStyle] = soa.get_layout_styles().as_slice();
fork_ctx.child_tasks.clear();
for (item_pos, &child_bfs) in flow_children.iter().enumerate() {
let arena_idx: usize = bfs_to_arena[child_bfs as usize] as usize;
let auto_w: bool = layout_styles[arena_idx].get_width() == Length::Auto;
let col_idx: usize = item_pos % cols;
let pos_x: f32 = origin_x + (col_idx as f32) * col_step;
let cell_space: AvailableSpace =
AvailableSpace::new(col_w, inner_h, viewport, pos_x, 0.0)
.with_stretch(auto_w, false);
fork_ctx.child_tasks.push(ParallelChildTask {
bfs_index: child_bfs,
space: cell_space,
mode,
});
}
Self::run_parallel_child_wave(fork_ctx);
let lane_zero: &mut WorkerLayoutScratch = unsafe { &mut *scratch_bank.lane_ptr(0) };
let mut y_cursor: f32 = 0.0;
let mut grid_deps: u8 = LAYOUT_DEP_AVAIL_W;
let mut idx: usize = 0;
let flow_len: usize = flow_children.len();
while idx < flow_len {
let row_end: usize = (idx + cols).min(flow_len);
let mut row_h: f32 = 0.0;
let mut min_row_h: f32 = f32::INFINITY;
let pos_y: f32 = origin_y + y_cursor;
for &outcome in &fork_ctx.child_outcomes[idx..row_end] {
grid_deps |= outcome.dep_flags;
let child_h: f32 = outcome.size.get_height();
row_h = row_h.max(child_h);
min_row_h = min_row_h.min(child_h);
}
if mode == LayoutRunMode::PerformLayout {
for pos in idx..row_end {
let child_bfs: u32 = flow_children[pos];
let outcome: ParallelChildOutcome = fork_ctx.child_outcomes[pos];
if pos_y.abs() > 0.0001 {
Self::translate_subtree_bfs(
soa,
output_view,
lane_zero,
child_bfs,
0.0,
pos_y,
);
}
let arena_idx: usize = bfs_to_arena[child_bfs as usize] as usize;
let width_needs_adjust: bool = (outcome.size.get_width() - col_w).abs() > 0.001;
let height_needs_adjust: bool =
row_end - idx > 1 && min_row_h < row_h && outcome.size.get_height() < row_h;
if width_needs_adjust || height_needs_adjust {
Self::apply_post_stretch(
soa,
output_view,
arena_idx,
if width_needs_adjust {
Some(col_w)
} else {
None
},
if height_needs_adjust {
Some(row_h)
} else {
None
},
);
}
}
}
y_cursor += row_h;
if row_end < flow_len {
y_cursor += row_gap;
}
idx = row_end;
}
(Size::new(inner_avail.get_width(), y_cursor), grid_deps, 0.0)
}
#[cfg(not(target_arch = "wasm32"))]
fn solve_grid_recurse(
fork_ctx: &mut ParallelForkContext<'_>,
flow_children: &[u32],
frame: ContainerFrame,
mode: LayoutRunMode,
) -> (Size, u8, f32) {
let soa: &SceneLayoutSoa = fork_ctx.soa;
let output_view: DisjointOutputView = fork_ctx.output_view;
let parent_layout: LayoutStyle = frame.get_parent_layout();
let inner_avail: Size = frame.get_inner_avail();
let viewport: Size = frame.get_viewport();
let content_origin: Point = frame.get_content_origin();
let cols: usize = (parent_layout.get_grid_columns() as usize).max(1);
let col_gap: f32 = parent_layout.get_column_gap();
let row_gap: f32 = parent_layout.get_row_gap();
let total_col_gaps: f32 = col_gap * ((cols.saturating_sub(1)) as f32);
let col_w: f32 = ((inner_avail.get_width() - total_col_gaps) / (cols as f32)).max(0.0);
let col_step: f32 = col_w + col_gap;
let origin_x: f32 = content_origin.get_x();
let origin_y: f32 = content_origin.get_y();
let inner_h: f32 = inner_avail.get_height();
let bfs_to_arena: &[u32] = soa.get_topology().get_bfs_to_arena().as_slice();
let layout_styles: &[LayoutStyle] = soa.get_layout_styles().as_slice();
let mut y_cursor: f32 = 0.0;
let mut grid_deps: u8 = LAYOUT_DEP_AVAIL_W;
let mut idx: usize = 0;
let flow_len: usize = flow_children.len();
while idx < flow_len {
let row_end: usize = (idx + cols).min(flow_len);
let mut row_h: f32 = 0.0;
let mut min_row_h: f32 = f32::INFINITY;
let pos_y: f32 = origin_y + y_cursor;
let mut pos_x: f32 = origin_x;
for &child_bfs in &flow_children[idx..row_end] {
let arena_idx: usize = bfs_to_arena[child_bfs as usize] as usize;
let auto_w: bool = layout_styles[arena_idx].get_width() == Length::Auto;
let cell_space: AvailableSpace =
AvailableSpace::new(col_w, inner_h, viewport, pos_x, pos_y)
.with_stretch(auto_w, false);
let (child_size, c_deps, _): (Size, u8, f32) =
Self::solve_node_dispatch(fork_ctx, child_bfs, cell_space, mode);
grid_deps |= c_deps;
if mode == LayoutRunMode::PerformLayout
&& (child_size.get_width() - col_w).abs() > 0.001
{
Self::apply_post_stretch(soa, output_view, arena_idx, Some(col_w), None);
}
let child_h: f32 = child_size.get_height();
row_h = row_h.max(child_h);
min_row_h = min_row_h.min(child_h);
pos_x += col_step;
}
if mode == LayoutRunMode::PerformLayout && row_end - idx > 1 && min_row_h < row_h {
for &child_bfs in &flow_children[idx..row_end] {
let arena_idx: usize = bfs_to_arena[child_bfs as usize] as usize;
let cur_h: f32 = unsafe { output_view.read_box(arena_idx) }
.get_bounds()
.get_height();
if cur_h < row_h {
Self::apply_post_stretch(soa, output_view, arena_idx, None, Some(row_h));
}
}
}
y_cursor += row_h;
if row_end < flow_len {
y_cursor += row_gap;
}
idx = row_end;
}
(Size::new(inner_avail.get_width(), y_cursor), grid_deps, 0.0)
}
#[cfg(not(target_arch = "wasm32"))]
fn solve_flex_single_pass_parallel(
fork_ctx: &mut ParallelForkContext<'_>,
flow_children: &[u32],
frame: ContainerFrame,
direction: FlexDirection,
mode: LayoutRunMode,
) -> (Size, u8, f32) {
if flow_children.is_empty() {
return (Size::default(), LAYOUT_DEP_NONE, 0.0);
}
let soa: &SceneLayoutSoa = fork_ctx.soa;
let output_view: DisjointOutputView = fork_ctx.output_view;
let scratch_bank: &WorkerScratchBank = fork_ctx.scratch_bank;
let parent_layout: LayoutStyle = frame.get_parent_layout();
let inner_avail: Size = frame.get_inner_avail();
let viewport: Size = frame.get_viewport();
let content_origin: Point = frame.get_content_origin();
let is_row: bool = matches!(direction, FlexDirection::Row | FlexDirection::RowReverse);
let main_gap: f32 = if is_row {
parent_layout.get_column_gap()
} else {
parent_layout.get_row_gap()
};
let cross_avail: f32 = if is_row {
inner_avail.get_height()
} else {
inner_avail.get_width()
};
let parent_align: AlignItems = parent_layout.get_align_items();
let bfs_to_arena: &[u32] = soa.get_topology().get_bfs_to_arena().as_slice();
let layout_styles: &[LayoutStyle] = soa.get_layout_styles().as_slice();
fork_ctx.child_tasks.clear();
let mut agg_deps: u8 = LAYOUT_DEP_NONE;
for &child_bfs in flow_children.iter() {
let arena_idx: usize = bfs_to_arena[child_bfs as usize] as usize;
let child_layout: LayoutStyle = layout_styles[arena_idx];
let margin: Edges = child_layout.get_margin();
let align: AlignItems = match child_layout.get_align_self() {
AlignSelf::Auto => parent_align,
AlignSelf::Stretch => AlignItems::Stretch,
AlignSelf::Start => AlignItems::Start,
AlignSelf::Center => AlignItems::Center,
AlignSelf::End => AlignItems::End,
};
let stretch_w: bool =
!is_row && align == AlignItems::Stretch && child_layout.get_width() == Length::Auto;
let stretch_h: bool =
is_row && align == AlignItems::Stretch && child_layout.get_height() == Length::Auto;
if stretch_w {
agg_deps |= LAYOUT_DEP_AVAIL_W;
}
if stretch_h {
agg_deps |= LAYOUT_DEP_AVAIL_H;
}
let space_w: f32 = if stretch_w {
(inner_avail.get_width() - margin.horizontal()).max(0.0)
} else {
inner_avail.get_width()
};
let space_h: f32 = if stretch_h {
(inner_avail.get_height() - margin.vertical()).max(0.0)
} else {
inner_avail.get_height()
};
let local_origin_x: f32 = if is_row {
0.0
} else {
content_origin.get_x() + margin.get_left()
};
let local_origin_y: f32 = if is_row {
content_origin.get_y() + margin.get_top()
} else {
0.0
};
let child_space: AvailableSpace =
AvailableSpace::new(space_w, space_h, viewport, local_origin_x, local_origin_y)
.with_stretch(stretch_w, stretch_h);
fork_ctx.child_tasks.push(ParallelChildTask {
bfs_index: child_bfs,
space: child_space,
mode,
});
}
Self::run_parallel_child_wave(fork_ctx);
let lane_zero: &mut WorkerLayoutScratch = unsafe { &mut *scratch_bank.lane_ptr(0) };
let mut main_cursor: f32 = 0.0;
let mut max_cross: f32 = 0.0;
let mut agg_min_aw: f32 = 0.0;
let mut stretched_records: Vec<(usize, Size, Edges)> = Vec::new();
let count_all: usize = flow_children.len();
for (offset, &child_bfs) in flow_children.iter().enumerate() {
let arena_idx: usize = bfs_to_arena[child_bfs as usize] as usize;
let child_layout: LayoutStyle = layout_styles[arena_idx];
let margin: Edges = child_layout.get_margin();
let task: ParallelChildTask = fork_ctx.child_tasks[offset];
let outcome: ParallelChildOutcome = fork_ctx.child_outcomes[offset];
agg_deps |= outcome.dep_flags;
if outcome.min_avail_w > 0.0 {
agg_min_aw = agg_min_aw.max(outcome.min_avail_w + margin.horizontal());
}
let stretch_w: bool = task.space.get_stretch_width();
let stretch_h: bool = task.space.get_stretch_height();
let target_w: f32 = if stretch_w {
task.space.get_width().max(outcome.size.get_width())
} else {
outcome.size.get_width()
};
let target_h: f32 = if stretch_h {
task.space.get_height().max(outcome.size.get_height())
} else {
outcome.size.get_height()
};
if mode == LayoutRunMode::PerformLayout {
let (shift_x, shift_y): (f32, f32) = if is_row {
(
content_origin.get_x() + main_cursor + margin.get_left(),
0.0,
)
} else {
(0.0, content_origin.get_y() + main_cursor + margin.get_top())
};
if shift_x.abs() > 0.0001 || shift_y.abs() > 0.0001 {
Self::translate_subtree_bfs(
soa,
output_view,
lane_zero,
child_bfs,
shift_x,
shift_y,
);
}
if (stretch_w && target_w > outcome.size.get_width() + 0.01)
|| (stretch_h && target_h > outcome.size.get_height() + 0.01)
{
Self::apply_post_stretch(
soa,
output_view,
arena_idx,
Some(target_w),
Some(target_h),
);
}
if stretch_w {
stretched_records.push((arena_idx, Size::new(target_w, target_h), margin));
}
}
if is_row {
main_cursor += target_w + margin.horizontal();
max_cross = max_cross.max(target_h + margin.vertical());
} else {
main_cursor += target_h + margin.vertical();
max_cross = max_cross.max(target_w + margin.horizontal());
}
if offset + 1 < count_all {
main_cursor += main_gap;
}
}
if mode == LayoutRunMode::PerformLayout
&& !stretched_records.is_empty()
&& max_cross > cross_avail + 0.5
{
for (arena_idx, rec_size, rec_margin) in stretched_records.iter().copied() {
let widened: f32 = (max_cross - rec_margin.horizontal()).max(rec_size.get_width());
Self::apply_post_stretch(soa, output_view, arena_idx, Some(widened), None);
}
}
let out_size: Size = if is_row {
Size::new(main_cursor, max_cross)
} else {
Size::new(max_cross, main_cursor)
};
(out_size, agg_deps, agg_min_aw)
}
#[cfg(not(target_arch = "wasm32"))]
fn solve_flex_single_pass_recurse(
fork_ctx: &mut ParallelForkContext<'_>,
flow_children: &[u32],
frame: ContainerFrame,
direction: FlexDirection,
mode: LayoutRunMode,
) -> (Size, u8, f32) {
let soa: &SceneLayoutSoa = fork_ctx.soa;
let output_view: DisjointOutputView = fork_ctx.output_view;
let parent_layout: LayoutStyle = frame.get_parent_layout();
let inner_avail: Size = frame.get_inner_avail();
let viewport: Size = frame.get_viewport();
let content_origin: Point = frame.get_content_origin();
let is_row: bool = matches!(direction, FlexDirection::Row | FlexDirection::RowReverse);
let main_gap: f32 = if is_row {
parent_layout.get_column_gap()
} else {
parent_layout.get_row_gap()
};
let cross_avail: f32 = if is_row {
inner_avail.get_height()
} else {
inner_avail.get_width()
};
let parent_align: AlignItems = parent_layout.get_align_items();
let bfs_to_arena: &[u32] = soa.get_topology().get_bfs_to_arena().as_slice();
let layout_styles: &[LayoutStyle] = soa.get_layout_styles().as_slice();
let mut main_cursor: f32 = 0.0;
let mut max_cross: f32 = 0.0;
let mut agg_deps: u8 = LAYOUT_DEP_NONE;
let mut agg_min_aw: f32 = 0.0;
let mut stretched_records: Vec<(usize, Size, Edges)> = Vec::new();
let count_all: usize = flow_children.len();
for (offset, &child_bfs) in flow_children.iter().enumerate() {
let arena_idx: usize = bfs_to_arena[child_bfs as usize] as usize;
let child_layout: LayoutStyle = layout_styles[arena_idx];
let margin: Edges = child_layout.get_margin();
let align: AlignItems = match child_layout.get_align_self() {
AlignSelf::Auto => parent_align,
AlignSelf::Stretch => AlignItems::Stretch,
AlignSelf::Start => AlignItems::Start,
AlignSelf::Center => AlignItems::Center,
AlignSelf::End => AlignItems::End,
};
let (pos_x, pos_y): (f32, f32) = if is_row {
(
content_origin.get_x() + main_cursor + margin.get_left(),
content_origin.get_y() + margin.get_top(),
)
} else {
(
content_origin.get_x() + margin.get_left(),
content_origin.get_y() + main_cursor + margin.get_top(),
)
};
let stretch_w: bool =
!is_row && align == AlignItems::Stretch && child_layout.get_width() == Length::Auto;
let stretch_h: bool =
is_row && align == AlignItems::Stretch && child_layout.get_height() == Length::Auto;
if stretch_w {
agg_deps |= LAYOUT_DEP_AVAIL_W;
}
if stretch_h {
agg_deps |= LAYOUT_DEP_AVAIL_H;
}
let space_w: f32 = if stretch_w {
(inner_avail.get_width() - margin.horizontal()).max(0.0)
} else {
inner_avail.get_width()
};
let space_h: f32 = if stretch_h {
(inner_avail.get_height() - margin.vertical()).max(0.0)
} else {
inner_avail.get_height()
};
let final_space: AvailableSpace =
AvailableSpace::new(space_w, space_h, viewport, pos_x, pos_y)
.with_stretch(stretch_w, stretch_h);
let (placed, c_deps, c_min_aw): (Size, u8, f32) =
Self::solve_node_dispatch(fork_ctx, child_bfs, final_space, mode);
agg_deps |= c_deps;
if c_min_aw > 0.0 {
agg_min_aw = agg_min_aw.max(c_min_aw + margin.horizontal());
}
let target_w: f32 = if stretch_w {
space_w.max(placed.get_width())
} else {
placed.get_width()
};
let target_h: f32 = if stretch_h {
space_h.max(placed.get_height())
} else {
placed.get_height()
};
if mode == LayoutRunMode::PerformLayout {
if (stretch_w && target_w > placed.get_width() + 0.01)
|| (stretch_h && target_h > placed.get_height() + 0.01)
{
Self::apply_post_stretch(
soa,
output_view,
arena_idx,
Some(target_w),
Some(target_h),
);
}
if stretch_w {
stretched_records.push((arena_idx, Size::new(target_w, target_h), margin));
}
}
if is_row {
main_cursor += target_w + margin.horizontal();
max_cross = max_cross.max(target_h + margin.vertical());
} else {
main_cursor += target_h + margin.vertical();
max_cross = max_cross.max(target_w + margin.horizontal());
}
if offset + 1 < count_all {
main_cursor += main_gap;
}
}
if mode == LayoutRunMode::PerformLayout
&& !stretched_records.is_empty()
&& max_cross > cross_avail + 0.5
{
for (arena_idx, rec_size, rec_margin) in stretched_records.iter().copied() {
let widened: f32 = (max_cross - rec_margin.horizontal()).max(rec_size.get_width());
Self::apply_post_stretch(soa, output_view, arena_idx, Some(widened), None);
}
}
let out_size: Size = if is_row {
Size::new(main_cursor, max_cross)
} else {
Size::new(max_cross, main_cursor)
};
(out_size, agg_deps, agg_min_aw)
}
#[cfg(not(target_arch = "wasm32"))]
fn solve_flex_two_pass_dispatch(
fork_ctx: &mut ParallelForkContext<'_>,
flow_children: &[u32],
frame: ContainerFrame,
direction: FlexDirection,
mode: LayoutRunMode,
can_fork_here: bool,
) -> (Size, u8, f32) {
if flow_children.is_empty() {
return (Size::default(), LAYOUT_DEP_NONE, 0.0);
}
let soa: &SceneLayoutSoa = fork_ctx.soa;
let output_view: DisjointOutputView = fork_ctx.output_view;
let scratch_bank: &WorkerScratchBank = fork_ctx.scratch_bank;
let is_reverse: bool = matches!(
direction,
FlexDirection::RowReverse | FlexDirection::ColumnReverse
);
let ordered: Vec<u32> = if is_reverse {
flow_children.iter().copied().rev().collect()
} else {
flow_children.to_vec()
};
if !can_fork_here {
let lane_zero: &mut WorkerLayoutScratch = unsafe { &mut *scratch_bank.lane_ptr(0) };
let flow_start: usize = lane_zero.flow_scratch.len();
lane_zero.flow_scratch.extend_from_slice(ordered.as_slice());
let flow_end: usize = lane_zero.flow_scratch.len();
let result: (Size, u8, f32) = Self::solve_flex_serial(
soa,
output_view,
lane_zero,
(flow_start, flow_end),
frame,
direction,
(false, false, mode),
);
lane_zero.flow_scratch.truncate(flow_start);
return result;
}
let parent_layout: LayoutStyle = frame.get_parent_layout();
let inner_avail: Size = frame.get_inner_avail();
let viewport: Size = frame.get_viewport();
let content_origin: Point = frame.get_content_origin();
let is_row: bool = matches!(direction, FlexDirection::Row | FlexDirection::RowReverse);
let main_gap: f32 = if is_row {
parent_layout.get_column_gap()
} else {
parent_layout.get_row_gap()
};
let cross_gap: f32 = if is_row {
parent_layout.get_row_gap()
} else {
parent_layout.get_column_gap()
};
let main_avail: f32 = if is_row {
inner_avail.get_width()
} else {
inner_avail.get_height()
};
let cross_avail: f32 = if is_row {
inner_avail.get_height()
} else {
inner_avail.get_width()
};
let wrap_enabled: bool = parent_layout.get_flex_wrap() == FlexWrap::Wrap;
let probe_template: AvailableSpace = AvailableSpace::new(
inner_avail.get_width(),
inner_avail.get_height(),
viewport,
content_origin.get_x(),
content_origin.get_y(),
);
let bfs_to_arena: &[u32] = soa.get_topology().get_bfs_to_arena().as_slice();
let layout_styles: &[LayoutStyle] = soa.get_layout_styles().as_slice();
let node_kinds: &[SoaNodeKindTag] = soa.get_node_kinds().as_slice();
let text_styles: &[TextStyle] = soa.get_text_styles().as_slice();
let mut records: Vec<ParallelFlexItem> = Vec::with_capacity(ordered.len());
let mut item_meta: Vec<PreparedFlexItemMeta> = Vec::with_capacity(ordered.len());
let mut pass1_deps: u8 = LAYOUT_DEP_NONE;
fork_ctx.child_tasks.clear();
for &child_bfs in ordered.iter() {
let (rec, meta, dep_bits): (ParallelFlexItem, PreparedFlexItemMeta, u8) =
Self::prepare_flex_item(
child_bfs,
layout_styles[bfs_to_arena[child_bfs as usize] as usize],
node_kinds[bfs_to_arena[child_bfs as usize] as usize],
text_styles[bfs_to_arena[child_bfs as usize] as usize],
(is_row, wrap_enabled, main_avail, cross_avail, viewport),
);
pass1_deps |= dep_bits;
if meta.zero_basis_size.is_none() {
fork_ctx.child_tasks.push(ParallelChildTask {
bfs_index: child_bfs,
space: probe_template,
mode: LayoutRunMode::ComputeSize,
});
}
records.push(rec);
item_meta.push(meta);
}
if !fork_ctx.child_tasks.is_empty() {
Self::run_parallel_child_wave(fork_ctx);
}
let mut probe_cursor: usize = 0;
let mut total_grow: f32 = 0.0;
let mut single_line_main: f32 = 0.0;
let mut single_line_cross: f32 = 0.0;
let mut pass1_min_aw: f32 = 0.0;
for (item_idx, rec) in records.iter_mut().enumerate() {
let meta: PreparedFlexItemMeta = item_meta[item_idx];
total_grow += rec.get_flex_grow();
let mut child_size: Size = if let Some(zero_size) = meta.zero_basis_size {
zero_size
} else {
let outcome: ParallelChildOutcome = fork_ctx.child_outcomes[probe_cursor];
probe_cursor = probe_cursor.saturating_add(1);
pass1_deps |= outcome.dep_flags;
if outcome.min_avail_w > 0.0 {
pass1_min_aw =
pass1_min_aw.max(outcome.min_avail_w + rec.get_margin().horizontal());
}
outcome.size
};
if let Some(basis_raw) = meta.explicit_basis_main
&& meta.zero_basis_size.is_none()
{
let mut clamped_basis: f32 = basis_raw.max(meta.explicit_min_main.unwrap_or(0.0));
if let Some(max_bound) = meta.explicit_max_main {
clamped_basis = clamped_basis.min(max_bound);
}
if is_row {
child_size.set_width(clamped_basis);
} else {
child_size.set_height(clamped_basis);
}
}
let resolved_min_main: f32 = if let Some(explicit_min) = meta.explicit_min_main {
explicit_min.max(0.0)
} else if rec.get_overflow() == Overflow::Scroll
|| (rec.get_overflow() == Overflow::Hidden && !meta.has_px_main)
{
0.0
} else if is_row {
if meta.is_unwrapped_clip_text {
child_size.get_width()
} else {
0.0
}
} else {
child_size.get_height()
};
let _: &mut ParallelFlexItem = rec.set_min_main(resolved_min_main).set_size(child_size);
if !wrap_enabled {
if is_row {
single_line_main += child_size.get_width() + rec.get_margin().horizontal();
single_line_cross = single_line_cross
.max(child_size.get_height() + rec.get_margin().vertical());
} else {
single_line_main += child_size.get_height() + rec.get_margin().vertical();
single_line_cross = single_line_cross
.max(child_size.get_width() + rec.get_margin().horizontal());
}
}
}
let mut lines: Vec<(usize, usize)> = Vec::new();
let mut wrap_deps: u8 = pass1_deps;
let mut wrap_min_aw: f32 = pass1_min_aw;
if !wrap_enabled {
lines.push((0, records.len()));
} else {
let mut cur_line_start: usize = 0;
let mut line_main: f32 = 0.0;
for (item_idx, item) in records.iter().enumerate() {
let item_main: f32 = if is_row {
item.get_size().get_width() + item.get_margin().horizontal()
} else {
item.get_size().get_height() + item.get_margin().vertical()
};
let line_empty: bool = item_idx == cur_line_start;
let needed: f32 = if line_empty {
item_main
} else {
line_main + main_gap + item_main
};
if !line_empty && needed > main_avail && main_avail > 0.0 {
lines.push((cur_line_start, item_idx));
cur_line_start = item_idx;
line_main = item_main;
} else {
line_main = needed;
}
}
if cur_line_start < records.len() {
lines.push((cur_line_start, records.len()));
}
if is_row {
if lines.len() > 1 {
wrap_deps |= LAYOUT_DEP_AVAIL_W;
} else {
wrap_min_aw = wrap_min_aw.max(line_main + 0.5);
}
} else {
wrap_deps |= LAYOUT_DEP_AVAIL_H;
}
}
let line_count: usize = lines.len();
let mut cross_cursor: f32 = 0.0;
let mut max_main_extent: f32 = 0.0;
for (line_offset, &(line_start, line_end)) in lines.iter().enumerate() {
let line_grow: f32 = if !wrap_enabled {
total_grow
} else {
records[line_start..line_end]
.iter()
.map(ParallelFlexItem::get_flex_grow)
.sum()
};
let mut line_ctx: FlexLineContext = FlexLineContext::new(
frame,
is_row,
main_gap,
main_avail,
cross_avail,
line_grow,
mode,
);
let _: &mut FlexLineContext = line_ctx
.set_wrap_enabled(wrap_enabled)
.set_line_count(line_count);
let precomputed: Option<(f32, f32)> = if !wrap_enabled {
Some((single_line_main, single_line_cross))
} else {
None
};
let (line_size, l_deps, l_min_aw): (Size, u8, f32) = Self::solve_flex_line_parallel(
fork_ctx,
&mut records[line_start..line_end],
cross_cursor,
precomputed,
line_ctx,
);
wrap_deps |= l_deps;
wrap_min_aw = wrap_min_aw.max(l_min_aw);
if !wrap_enabled {
return (line_size, wrap_deps, wrap_min_aw);
}
if is_row {
max_main_extent = max_main_extent.max(line_size.get_width());
cross_cursor += line_size.get_height();
} else {
max_main_extent = max_main_extent.max(line_size.get_height());
cross_cursor += line_size.get_width();
}
if line_offset + 1 < line_count {
cross_cursor += cross_gap;
}
}
let out_size: Size = if is_row {
Size::new(max_main_extent, cross_cursor)
} else {
Size::new(cross_cursor, max_main_extent)
};
(out_size, wrap_deps, wrap_min_aw)
}
#[cfg(not(target_arch = "wasm32"))]
fn solve_flex_line_parallel(
fork_ctx: &mut ParallelForkContext<'_>,
line_items: &mut [ParallelFlexItem],
cross_cursor: f32,
precomputed: Option<(f32, f32)>,
ctx: FlexLineContext,
) -> (Size, u8, f32) {
let soa: &SceneLayoutSoa = fork_ctx.soa;
let output_view: DisjointOutputView = fork_ctx.output_view;
let scratch_bank: &WorkerScratchBank = fork_ctx.scratch_bank;
let lane_zero: &mut WorkerLayoutScratch = unsafe { &mut *scratch_bank.lane_ptr(0) };
let (
final_used_main,
line_cross,
line_deps,
line_min_aw,
line_shrunk,
effective_main_avail,
): (f32, f32, u8, f32, bool, f32) = Self::resolve_flex_line_sizes(
soa,
output_view,
lane_zero,
line_items,
precomputed,
ctx,
);
let is_row: bool = ctx.get_is_row();
let mode: LayoutRunMode = ctx.get_mode();
if mode == LayoutRunMode::ComputeSize {
let sz: Size = if is_row {
Size::new(final_used_main, line_cross)
} else {
Size::new(line_cross, final_used_main)
};
return (sz, line_deps, line_min_aw);
}
let frame: ContainerFrame = ctx.get_frame();
let parent_layout: LayoutStyle = frame.get_parent_layout();
let inner_avail: Size = frame.get_inner_avail();
let viewport: Size = frame.get_viewport();
let content_origin: Point = frame.get_content_origin();
let main_gap: f32 = ctx.get_main_gap();
let cross_avail: f32 = ctx.get_cross_avail();
let wrap_enabled: bool = ctx.get_wrap_enabled();
let line_count: usize = ctx.get_line_count();
let count: usize = line_items.len();
let rem: f32 = (effective_main_avail - final_used_main).max(0.0);
let (mut main_cursor, extra_step): (f32, f32) = match parent_layout.get_justify_content() {
JustifyContent::Start => (0.0, 0.0),
JustifyContent::Center => (rem * 0.5, 0.0),
JustifyContent::End => (rem, 0.0),
JustifyContent::SpaceBetween => {
if count > 1 {
(0.0, rem / ((count - 1) as f32))
} else {
(0.0, 0.0)
}
}
JustifyContent::SpaceAround => {
let slot: f32 = rem / (count.max(1) as f32);
(slot * 0.5, slot)
}
JustifyContent::SpaceEvenly => {
let slot: f32 = rem / ((count + 1) as f32);
(slot, slot)
}
};
let min_cross: f32 = if is_row {
frame.get_min_inner_size().get_height()
} else {
frame.get_min_inner_size().get_width()
};
let definite_cross: bool = !is_row || frame.get_definite_height();
let effective_line_cross: f32 = if line_count == 1 {
let floor_cross: f32 = if definite_cross && (!wrap_enabled || is_row) {
cross_avail.max(min_cross)
} else {
min_cross
};
line_cross.max(floor_cross)
} else {
line_cross
};
let parent_align: AlignItems = parent_layout.get_align_items();
fork_ctx.child_tasks.clear();
let mut placement_meta: Vec<FlexPlacementMeta> = Vec::with_capacity(count);
for (idx, rec) in line_items.iter().copied().enumerate() {
let child_size: Size = rec.get_size();
let margin: Edges = rec.get_margin();
let width_auto: bool = (rec.get_flags() & FLEX_ITEM_WIDTH_AUTO) != 0;
let height_auto: bool = (rec.get_flags() & FLEX_ITEM_HEIGHT_AUTO) != 0;
let item_cross: f32 = if is_row {
child_size.get_height()
} else {
child_size.get_width()
};
let align: AlignItems = match rec.get_align_self() {
AlignSelf::Auto => parent_align,
AlignSelf::Stretch => AlignItems::Stretch,
AlignSelf::Start => AlignItems::Start,
AlignSelf::Center => AlignItems::Center,
AlignSelf::End => AlignItems::End,
};
let avail_item_cross: f32 = (effective_line_cross
- if is_row {
margin.vertical()
} else {
margin.horizontal()
})
.max(0.0);
let cross_offset: f32 = match align {
AlignItems::Start | AlignItems::Stretch => 0.0,
AlignItems::Center => ((avail_item_cross - item_cross) * 0.5).max(0.0),
AlignItems::End => (avail_item_cross - item_cross).max(0.0),
};
let main_resized_item: bool = rec.get_flex_grow() > 0.0 || line_shrunk;
let auto_cross_grow: bool =
main_resized_item && if is_row { height_auto } else { width_auto };
let target_w: f32 = if !is_row && align == AlignItems::Stretch && width_auto {
avail_item_cross.max(child_size.get_width())
} else {
child_size.get_width()
};
let target_h: f32 = if is_row && align == AlignItems::Stretch && height_auto {
avail_item_cross.max(child_size.get_height())
} else {
child_size.get_height()
};
let (pos_x, pos_y): (f32, f32) = if is_row {
(
content_origin.get_x() + main_cursor + margin.get_left(),
content_origin.get_y() + cross_cursor + cross_offset + margin.get_top(),
)
} else {
(
content_origin.get_x() + cross_cursor + cross_offset + margin.get_left(),
content_origin.get_y() + main_cursor + margin.get_top(),
)
};
let stretch_child_w: bool = !(auto_cross_grow && !is_row)
&& ((!is_row && align == AlignItems::Stretch && width_auto)
|| (is_row && main_resized_item && width_auto));
let stretch_child_h: bool = !(auto_cross_grow && is_row)
&& ((is_row && align == AlignItems::Stretch && height_auto)
|| (!is_row && main_resized_item && height_auto));
let space_w: f32 =
if !stretch_child_w && (rec.get_flags() & FLEX_ITEM_WIDTH_PERCENT) != 0 {
inner_avail.get_width()
} else if auto_cross_grow && !is_row {
cross_avail
} else {
target_w
};
let space_h: f32 =
if !stretch_child_h && (rec.get_flags() & FLEX_ITEM_HEIGHT_PERCENT) != 0 {
inner_avail.get_height()
} else if auto_cross_grow && is_row {
cross_avail
} else {
target_h
};
let final_space: AvailableSpace =
AvailableSpace::new(space_w, space_h, viewport, pos_x, pos_y)
.with_stretch(stretch_child_w, stretch_child_h);
fork_ctx.child_tasks.push(ParallelChildTask {
bfs_index: rec.get_bfs_index(),
space: final_space,
mode: LayoutRunMode::PerformLayout,
});
placement_meta.push(FlexPlacementMeta {
target_w,
target_h,
avail_item_cross,
cross_offset,
align,
auto_cross_grow,
main_resized_item,
});
let advance: f32 = if is_row {
target_w + margin.horizontal()
} else {
target_h + margin.vertical()
};
main_cursor += advance;
if idx + 1 < count {
main_cursor += main_gap + extra_step;
}
}
Self::run_parallel_child_wave(fork_ctx);
let lane_zero_after: &mut WorkerLayoutScratch = unsafe { &mut *scratch_bank.lane_ptr(0) };
let bfs_to_arena: &[u32] = soa.get_topology().get_bfs_to_arena().as_slice();
let mut actual_line_cross: f32 = line_cross;
for (idx, rec) in line_items.iter().copied().enumerate() {
let FlexPlacementMeta {
target_w,
target_h,
avail_item_cross,
cross_offset,
align,
auto_cross_grow,
main_resized_item,
} = placement_meta[idx];
let placed_final: Size = fork_ctx.child_outcomes[idx].size;
if auto_cross_grow && matches!(align, AlignItems::Center | AlignItems::End) {
let actual_item_cross: f32 = if is_row {
placed_final.get_height()
} else {
placed_final.get_width()
};
let refined_offset: f32 = match align {
AlignItems::Center => ((avail_item_cross - actual_item_cross) * 0.5).max(0.0),
AlignItems::End => (avail_item_cross - actual_item_cross).max(0.0),
AlignItems::Start | AlignItems::Stretch => cross_offset,
};
let delta_cross: f32 = refined_offset - cross_offset;
if delta_cross.abs() > 0.001 {
let (dx, dy): (f32, f32) = if is_row {
(0.0, delta_cross)
} else {
(delta_cross, 0.0)
};
Self::translate_subtree_bfs(
soa,
output_view,
lane_zero_after,
rec.get_bfs_index(),
dx,
dy,
);
}
}
let margin: Edges = rec.get_margin();
let is_clipped: bool =
matches!(rec.get_overflow(), Overflow::Hidden | Overflow::Scroll);
let (desired_w, desired_h): (f32, f32) = if auto_cross_grow {
if is_row {
actual_line_cross =
actual_line_cross.max(placed_final.get_height() + margin.vertical());
(target_w, placed_final.get_height())
} else {
actual_line_cross =
actual_line_cross.max(placed_final.get_width() + margin.horizontal());
(placed_final.get_width(), target_h)
}
} else if is_clipped || main_resized_item {
(target_w, target_h)
} else {
(
target_w.max(placed_final.get_width()),
target_h.max(placed_final.get_height()),
)
};
let arena_idx: usize = bfs_to_arena[rec.get_bfs_index() as usize] as usize;
let cur_bounds: Rect = unsafe { output_view.read_box(arena_idx) }.get_bounds();
if (cur_bounds.get_width() - desired_w).abs() > 0.001
|| (cur_bounds.get_height() - desired_h).abs() > 0.001
{
Self::apply_post_stretch(
soa,
output_view,
arena_idx,
Some(desired_w),
Some(desired_h),
);
}
}
let sz: Size = if is_row {
Size::new(final_used_main, actual_line_cross)
} else {
Size::new(actual_line_cross, final_used_main)
};
(sz, line_deps, line_min_aw)
}
#[cfg_attr(not(target_arch = "wasm32"), inline)]
fn resolve_container_constraints(
soa: &SceneLayoutSoa,
arena_idx: usize,
layout_style: LayoutStyle,
space: AvailableSpace,
) -> ResolvedNodeConstraints {
let w_len: Length = layout_style.get_width();
let h_len: Length = layout_style.get_height();
let min_w_len: Length = layout_style.get_min_width();
let max_w_len: Length = layout_style.get_max_width();
let min_h_len: Length = layout_style.get_min_height();
let max_h_len: Length = layout_style.get_max_height();
let mut own_deps: u8 = LAYOUT_DEP_NONE;
if matches!(w_len, Length::Percent(_))
|| matches!(min_w_len, Length::Percent(_))
|| matches!(max_w_len, Length::Percent(_))
{
own_deps |= LAYOUT_DEP_AVAIL_W;
}
if matches!(h_len, Length::Percent(_))
|| matches!(min_h_len, Length::Percent(_))
|| matches!(max_h_len, Length::Percent(_))
{
own_deps |= LAYOUT_DEP_AVAIL_H;
}
if Self::is_viewport_length(w_len)
|| Self::is_viewport_length(h_len)
|| Self::is_viewport_length(min_w_len)
|| Self::is_viewport_length(max_w_len)
|| Self::is_viewport_length(min_h_len)
|| Self::is_viewport_length(max_h_len)
{
own_deps |= LAYOUT_DEP_VIEWPORT;
}
let padding: Edges = layout_style.get_padding();
let border_w: f32 = soa.get_border_widths()[arena_idx];
let chrome_h: f32 = padding.horizontal() + border_w * 2.0;
let chrome_v: f32 = padding.vertical() + border_w * 2.0;
let explicit_w: Option<f32> = w_len.resolve(space.get_width(), space.get_viewport());
let explicit_h: Option<f32> = h_len.resolve(space.get_height(), space.get_viewport());
let mut resolved_w: Option<f32> = explicit_w;
let mut resolved_h: Option<f32> = explicit_h;
let stretched_w: bool = resolved_w.is_none() && space.get_stretch_width();
let stretched_h: bool = resolved_h.is_none() && space.get_stretch_height();
if stretched_w {
resolved_w = Some(space.get_width());
own_deps |= LAYOUT_DEP_AVAIL_W;
}
if stretched_h {
resolved_h = Some(space.get_height());
own_deps |= LAYOUT_DEP_AVAIL_H;
}
let min_w: f32 = min_w_len
.resolve(space.get_width(), space.get_viewport())
.unwrap_or(0.0);
let min_h: f32 = min_h_len
.resolve(space.get_height(), space.get_viewport())
.unwrap_or(0.0);
let max_w: f32 = max_w_len
.resolve(space.get_width(), space.get_viewport())
.unwrap_or(f32::INFINITY)
.max(min_w);
let max_h: f32 = max_h_len
.resolve(space.get_height(), space.get_viewport())
.unwrap_or(f32::INFINITY)
.max(min_h);
if let Some(ratio) = layout_style.aspect_ratio_value()
&& ratio > 0.0
{
if let Some(width_val) = resolved_w
&& resolved_h.is_none()
{
resolved_h = Some(width_val.clamp(min_w, max_w) / ratio);
} else if let Some(height_val) = resolved_h
&& resolved_w.is_none()
{
resolved_w = Some(height_val.clamp(min_h, max_h) * ratio);
}
}
let avail_w_outer: f32 = resolved_w
.unwrap_or(space.get_width())
.max(min_w)
.min(max_w);
let avail_h_outer: f32 = resolved_h
.unwrap_or(space.get_height())
.max(min_h)
.min(max_h);
let inner_avail_w: f32 = (avail_w_outer - chrome_h).max(0.0);
let inner_avail_h: f32 = (avail_h_outer - chrome_v).max(0.0);
let content_origin_x: f32 = space.get_origin_x() + padding.get_left() + border_w;
let content_origin_y: f32 = space.get_origin_y() + padding.get_top() + border_w;
ResolvedNodeConstraints {
own_deps,
resolved_w,
resolved_h,
explicit_w,
stretched_w,
min_w,
max_w,
min_h,
max_h,
chrome_h,
chrome_v,
inner_avail_w,
inner_avail_h,
content_origin_x,
content_origin_y,
}
}
fn finalize_node_box(
soa: &SceneLayoutSoa,
output_view: DisjointOutputView,
scratch: &mut WorkerLayoutScratch,
node_ctx: (LayoutStyle, AvailableSpace, LayoutRunMode, usize),
constraints: ResolvedNodeConstraints,
content_tuple: (Size, u8, f32),
child_range: Option<(usize, usize)>,
) -> (Size, u8, f32) {
let (layout_style, space, mode, arena_idx): (
LayoutStyle,
AvailableSpace,
LayoutRunMode,
usize,
) = node_ctx;
let ResolvedNodeConstraints {
own_deps,
resolved_w,
resolved_h,
explicit_w,
stretched_w,
min_w,
max_w,
min_h,
max_h,
chrome_h,
chrome_v,
content_origin_x,
content_origin_y,
..
} = constraints;
let (content_size, child_deps, child_min_aw): (Size, u8, f32) = content_tuple;
let node_overflow: Overflow = layout_style.get_overflow();
let node_flex_grow: f32 = layout_style.get_flex_grow();
let content_outer_w: f32 = content_size.get_width() + chrome_h;
let content_outer_h: f32 = content_size.get_height() + chrome_v;
let mut final_w: f32 = match (explicit_w, stretched_w) {
(Some(span_width), _) => span_width,
(None, true) => {
let base_w: f32 = resolved_w.unwrap_or(content_outer_w);
if node_overflow == Overflow::Visible
&& node_flex_grow <= 0.0
&& content_outer_w > base_w + 0.5
{
content_outer_w
} else {
base_w
}
}
(None, false) => content_outer_w,
};
let mut final_h: f32 = resolved_h.unwrap_or(content_outer_h);
if let Some(ratio) = layout_style.aspect_ratio_value()
&& ratio > 0.0
{
if resolved_w.is_some() && resolved_h.is_none() {
final_h = final_w / ratio;
} else if resolved_h.is_some() && resolved_w.is_none() {
final_w = final_h * ratio;
}
}
final_w = final_w.clamp(min_w, max_w).max(0.0);
final_h = final_h.clamp(min_h, max_h).max(0.0);
let final_size: Size = Size::new(final_w, final_h);
let shields_avail_w: bool = resolved_w.is_some() && (own_deps & LAYOUT_DEP_AVAIL_W) == 0;
let shields_avail_h: bool = resolved_h.is_some() && (own_deps & LAYOUT_DEP_AVAIL_H) == 0;
let mut final_deps: u8 = own_deps | (child_deps & LAYOUT_DEP_VIEWPORT);
let mut final_min_aw: f32 = 0.0;
if !shields_avail_w {
if (child_deps & LAYOUT_DEP_AVAIL_W) != 0 {
final_deps |= LAYOUT_DEP_AVAIL_W;
} else if child_min_aw > 0.0 {
final_min_aw = child_min_aw + chrome_h;
}
}
if !shields_avail_h {
final_deps |= child_deps & LAYOUT_DEP_AVAIL_H;
}
if mode == LayoutRunMode::ComputeSize {
return (final_size, final_deps, final_min_aw);
}
let bounds: Rect = Rect::new(space.get_origin_x(), space.get_origin_y(), final_w, final_h);
let content_bounds: Rect = Rect::new(
content_origin_x,
content_origin_y,
(final_w - chrome_h).max(0.0),
(final_h - chrome_v).max(0.0),
);
let prev_box: LayoutBox = soa.get_layout_boxes()[arena_idx];
let changed: bool = !Self::rect_approx_eq(prev_box.get_bounds(), bounds)
|| !Self::rect_approx_eq(prev_box.get_content_bounds(), content_bounds)
|| !Self::size_approx_eq(prev_box.get_content_size(), content_size);
if changed {
scratch.nodes_changed = scratch.nodes_changed.saturating_add(1);
}
let mut next_box: LayoutBox = prev_box;
let _: &mut LayoutBox = next_box
.set_bounds(bounds)
.set_content_bounds(content_bounds)
.set_content_size(content_size);
unsafe {
output_view.write_box(arena_idx, next_box);
output_view.write_constraint(arena_idx, space);
}
let node_transform: Transform2D = soa.get_transforms()[arena_idx];
let node_scroll: Point = prev_box.get_scroll_offset();
let self_is_portal: bool = soa.get_node_kinds()[arena_idx] == SoaNodeKindTag::Portal
|| layout_style.get_position() == Position::Fixed;
let own_vis: Rect = shifted_node_bounds(bounds, Point::default(), node_transform);
let is_clipped: bool = matches!(node_overflow, Overflow::Hidden | Overflow::Scroll);
let mut sub_bounds: Rect = own_vis;
let mut has_nonzero_z: bool = false;
if let Some((c_start, c_end)) = child_range {
let bfs_to_arena: &[u32] = soa.get_topology().get_bfs_to_arena().as_slice();
let layout_styles: &[LayoutStyle] = soa.get_layout_styles().as_slice();
let node_kinds: &[SoaNodeKindTag] = soa.get_node_kinds().as_slice();
let transforms: &[Transform2D] = soa.get_transforms().as_slice();
let tx: f32 = node_transform.get_translate_x() - node_scroll.get_x();
let ty: f32 = node_transform.get_translate_y() - node_scroll.get_y();
for &c_arena_u32 in &bfs_to_arena[c_start..c_end] {
let c_arena: usize = c_arena_u32 as usize;
let c_layout: LayoutStyle = layout_styles[c_arena];
if c_layout.get_z_index() != 0 {
has_nonzero_z = true;
}
let c_is_portal: bool = node_kinds[c_arena] == SoaNodeKindTag::Portal
|| c_layout.get_position() == Position::Fixed;
if !is_clipped
&& c_layout.get_display() != Display::None
&& (self_is_portal || !c_is_portal)
{
let child_sb: Rect = unsafe {
let stored: Rect = output_view.read_subtree_bounds(c_arena);
if stored.get_width() > 0.0 || stored.get_height() > 0.0 {
stored
} else {
shifted_node_bounds(
output_view.read_box(c_arena).get_bounds(),
Point::default(),
transforms[c_arena],
)
}
};
if child_sb.get_width() > 0.0 && child_sb.get_height() > 0.0 {
let shifted_child: Rect = simd_translate_rect(child_sb, tx, ty);
sub_bounds = sub_bounds.union(shifted_child);
}
}
}
}
unsafe {
output_view.write_subtree_bounds(arena_idx, sub_bounds);
output_view.write_result(
arena_idx,
ParallelNodeResult {
size: final_size,
natural_bounds: bounds,
natural_content_bounds: content_bounds,
dep_flags: final_deps,
min_avail_w: final_min_aw,
post_stretched: false,
hidden: false,
written: true,
has_nonzero_z,
},
);
}
(final_size, final_deps, final_min_aw)
}
fn apply_post_stretch(
soa: &SceneLayoutSoa,
output_view: DisjointOutputView,
arena_idx: usize,
new_width: Option<f32>,
new_height: Option<f32>,
) {
let layout_style: LayoutStyle = soa.get_layout_styles()[arena_idx];
let padding: Edges = layout_style.get_padding();
let border_w: f32 = soa.get_border_widths()[arena_idx];
let transform_val: Transform2D = soa.get_transforms()[arena_idx];
let is_clipped: bool = matches!(
layout_style.get_overflow(),
Overflow::Hidden | Overflow::Scroll
);
unsafe {
let mut cur_box: LayoutBox = output_view.read_box(arena_idx);
let mut bounds: Rect = cur_box.get_bounds();
let mut content_bounds: Rect = cur_box.get_content_bounds();
if let Some(target_w) = new_width {
let _: &mut Rect = bounds.set_width(target_w);
let _: &mut Rect = content_bounds
.set_width((target_w - padding.horizontal() - border_w * 2.0).max(0.0));
}
if let Some(target_h) = new_height {
let _: &mut Rect = bounds.set_height(target_h);
let _: &mut Rect = content_bounds
.set_height((target_h - padding.vertical() - border_w * 2.0).max(0.0));
}
let _: &mut LayoutBox = cur_box
.set_bounds(bounds)
.set_content_bounds(content_bounds);
output_view.write_box(arena_idx, cur_box);
let own_vis: Rect = shifted_node_bounds(bounds, Point::default(), transform_val);
let next_sub: Rect = if is_clipped {
own_vis
} else {
output_view.read_subtree_bounds(arena_idx).union(own_vis)
};
output_view.write_subtree_bounds(arena_idx, next_sub);
let mut res: ParallelNodeResult = output_view.read_result(arena_idx);
res.post_stretched = true;
output_view.write_result(arena_idx, res);
}
}
fn solve_node_serial(
soa: &SceneLayoutSoa,
output_view: DisjointOutputView,
scratch: &mut WorkerLayoutScratch,
bfs_index: u32,
space: AvailableSpace,
mode: LayoutRunMode,
) -> (Size, u8, f32) {
scratch.nodes_computed = scratch.nodes_computed.saturating_add(1);
let topology: &FlatBfsTopology = soa.get_topology();
let arena_idx: usize = topology.get_bfs_to_arena()[bfs_index as usize] as usize;
let layout_style: LayoutStyle = soa.get_layout_styles()[arena_idx];
if layout_style.get_display() == Display::None {
if mode == LayoutRunMode::PerformLayout {
let prev_box: LayoutBox = soa.get_layout_boxes()[arena_idx];
if !Self::rect_approx_eq(prev_box.get_bounds(), Rect::default()) {
scratch.nodes_changed = scratch.nodes_changed.saturating_add(1);
}
let mut hidden_box: LayoutBox = prev_box;
let _: &mut LayoutBox = hidden_box
.set_bounds(Rect::default())
.set_content_bounds(Rect::default());
unsafe {
output_view.write_box(arena_idx, hidden_box);
output_view.write_constraint(arena_idx, space);
output_view.write_subtree_bounds(arena_idx, Rect::default());
output_view.write_result(
arena_idx,
ParallelNodeResult {
size: Size::default(),
natural_bounds: Rect::default(),
natural_content_bounds: Rect::default(),
dep_flags: LAYOUT_DEP_NONE,
min_avail_w: 0.0,
post_stretched: false,
hidden: true,
written: true,
has_nonzero_z: false,
},
);
}
}
return (Size::default(), LAYOUT_DEP_NONE, 0.0);
}
let constraints: ResolvedNodeConstraints =
Self::resolve_container_constraints(soa, arena_idx, layout_style, space);
let node_overflow: Overflow = layout_style.get_overflow();
let node_flex_grow: f32 = layout_style.get_flex_grow();
let width_independent: bool = constraints.explicit_w.is_some()
|| (constraints.stretched_w
&& constraints.resolved_w.is_some()
&& (node_overflow != Overflow::Visible || node_flex_grow > 0.0));
let height_independent: bool =
constraints.resolved_h.is_some() && layout_style.get_height() != Length::Auto;
if mode == LayoutRunMode::ComputeSize
&& width_independent
&& constraints.resolved_h.is_some()
{
let final_w: f32 = constraints
.resolved_w
.unwrap_or(0.0)
.clamp(constraints.min_w, constraints.max_w)
.max(0.0);
let final_h: f32 = constraints
.resolved_h
.unwrap_or(0.0)
.clamp(constraints.min_h, constraints.max_h)
.max(0.0);
return (Size::new(final_w, final_h), constraints.own_deps, 0.0);
}
let skip_leaf_measure: bool =
node_overflow != Overflow::Scroll && width_independent && height_independent;
let kind_tag: SoaNodeKindTag = soa.get_node_kinds()[arena_idx];
let text_style: TextStyle = soa.get_text_styles()[arena_idx];
let text_slice: SoaTextSlice = soa.get_text_slices()[arena_idx];
let mut child_deps: u8 = LAYOUT_DEP_NONE;
let mut child_min_aw: f32 = 0.0;
let mut child_range: Option<(usize, usize)> = None;
let content_size: Size = match kind_tag {
SoaNodeKindTag::Text => {
if skip_leaf_measure {
Size::new(constraints.inner_avail_w, constraints.inner_avail_h)
} else {
let sample_str: &str = soa.text_for_arena(arena_idx);
let measured: TextSizeMeasurement = scratch.measure_text_cached(
sample_str,
text_slice.get_is_ascii(),
text_style,
Some(constraints.inner_avail_w.max(1.0)),
);
if text_style.get_overflow() != TextOverflow::Clip {
if measured.unwrapped && measured.max_content_w.is_finite() {
child_min_aw = measured.max_content_w + 0.5;
} else {
child_deps |= LAYOUT_DEP_AVAIL_W;
}
}
measured.size
}
}
SoaNodeKindTag::Image => soa.get_image_sizes()[arena_idx],
SoaNodeKindTag::Input => {
if skip_leaf_measure {
Size::new(constraints.inner_avail_w, constraints.inner_avail_h)
} else {
let sample_str: &str = soa.text_for_arena(arena_idx);
let measured: TextSizeMeasurement = scratch.measure_text_cached(
sample_str,
text_slice.get_is_ascii(),
text_style,
Some(constraints.inner_avail_w.max(1.0)),
);
if text_style.get_overflow() != TextOverflow::Clip {
if measured.unwrapped && measured.max_content_w.is_finite() {
child_min_aw = measured.max_content_w + 0.5;
} else {
child_deps |= LAYOUT_DEP_AVAIL_W;
}
}
Size::new(
measured.size.get_width().max(120.0),
measured.size.get_height().max(20.0),
)
}
}
SoaNodeKindTag::Container
| SoaNodeKindTag::ScrollView
| SoaNodeKindTag::Portal
| SoaNodeKindTag::Fragment
| SoaNodeKindTag::Canvas => {
let (c_start, c_end): (usize, usize) =
topology.children_bfs_range(bfs_index as usize);
if c_start >= c_end {
Size::default()
} else {
child_range = Some((c_start, c_end));
let min_inner_size: Size = Size::new(
(constraints.min_w - constraints.chrome_h).max(0.0),
(constraints.min_h - constraints.chrome_v).max(0.0),
);
let frame: ContainerFrame = ContainerFrame::new(
layout_style,
Size::new(constraints.inner_avail_w, constraints.inner_avail_h),
space.get_viewport(),
Point::new(constraints.content_origin_x, constraints.content_origin_y),
constraints.resolved_w.is_some(),
constraints.resolved_h.is_some(),
min_inner_size,
);
let (size, c_deps, c_min_aw): (Size, u8, f32) = Self::solve_children_serial(
soa,
output_view,
scratch,
(c_start, c_end),
frame,
mode,
);
child_deps = c_deps;
child_min_aw = c_min_aw;
size
}
}
};
Self::finalize_node_box(
soa,
output_view,
scratch,
(layout_style, space, mode, arena_idx),
constraints,
(content_size, child_deps, child_min_aw),
child_range,
)
}
fn solve_children_serial(
soa: &SceneLayoutSoa,
output_view: DisjointOutputView,
scratch: &mut WorkerLayoutScratch,
child_range: (usize, usize),
frame: ContainerFrame,
mode: LayoutRunMode,
) -> (Size, u8, f32) {
let (child_start, child_end): (usize, usize) = child_range;
if child_start >= child_end {
return (Size::default(), LAYOUT_DEP_NONE, 0.0);
}
let bfs_to_arena: &[u32] = soa.get_topology().get_bfs_to_arena().as_slice();
let layout_styles: &[LayoutStyle] = soa.get_layout_styles().as_slice();
let node_kinds: &[SoaNodeKindTag] = soa.get_node_kinds().as_slice();
let text_styles: &[TextStyle] = soa.get_text_styles().as_slice();
let parent_layout: LayoutStyle = frame.get_parent_layout();
let inner_avail: Size = frame.get_inner_avail();
let viewport: Size = frame.get_viewport();
let content_origin: Point = frame.get_content_origin();
let flex_dir_opt: Option<FlexDirection> = match parent_layout.get_display() {
Display::Grid => None,
Display::Block => Some(FlexDirection::Column),
Display::Flex | Display::None => Some(parent_layout.get_flex_direction()),
};
let is_row_dir: bool = matches!(
flex_dir_opt,
Some(FlexDirection::Row | FlexDirection::RowReverse)
);
let is_reverse_dir: bool = matches!(
flex_dir_opt,
Some(FlexDirection::RowReverse | FlexDirection::ColumnReverse)
);
let parent_align: AlignItems = parent_layout.get_align_items();
let parent_height_auto: bool = parent_layout.get_height() == Length::Auto;
let parent_bounded_main: bool = if is_row_dir {
frame.get_definite_width() || parent_layout.get_max_width() != Length::Auto
} else {
frame.get_definite_height() || parent_layout.get_max_height() != Length::Auto
};
let mut single_pass_ok: bool = flex_dir_opt.is_some()
&& parent_layout.get_flex_wrap() != FlexWrap::Wrap
&& !is_reverse_dir
&& parent_layout.get_justify_content() == JustifyContent::Start;
let mut shrinkable_flow_children: usize = 0;
let flow_start: usize = scratch.flow_scratch.len();
let abs_start: usize = scratch.abs_scratch.len();
for (cur_bfs, &arena_u32) in bfs_to_arena
.iter()
.enumerate()
.take(child_end)
.skip(child_start)
{
let arena_idx: usize = arena_u32 as usize;
let child_layout: LayoutStyle = layout_styles[arena_idx];
if child_layout.get_display() == Display::None {
if mode == LayoutRunMode::PerformLayout {
let _: (Size, u8, f32) = Self::solve_node_serial(
soa,
output_view,
scratch,
cur_bfs as u32,
AvailableSpace::new(0.0, 0.0, viewport, 0.0, 0.0),
LayoutRunMode::PerformLayout,
);
}
continue;
}
match child_layout.get_position() {
Position::Relative => {
if single_pass_ok {
if parent_bounded_main && child_layout.get_flex_shrink() > 0.0 {
let can_shrink_child: bool = if is_row_dir {
child_layout.get_min_width() != Length::Auto
|| child_layout.get_overflow() != Overflow::Visible
|| node_kinds[arena_idx] != SoaNodeKindTag::Text
|| text_styles[arena_idx].get_overflow() != TextOverflow::Clip
} else {
child_layout.get_min_height() != Length::Auto
|| child_layout.get_overflow() != Overflow::Visible
};
if can_shrink_child {
shrinkable_flow_children =
shrinkable_flow_children.saturating_add(1);
}
}
if child_layout.get_flex_grow() > 0.0
|| child_layout.get_flex_basis() != Length::Auto
{
single_pass_ok = false;
} else {
let align: AlignItems = match child_layout.get_align_self() {
AlignSelf::Auto => parent_align,
AlignSelf::Stretch => AlignItems::Stretch,
AlignSelf::Start => AlignItems::Start,
AlignSelf::Center => AlignItems::Center,
AlignSelf::End => AlignItems::End,
};
let non_start_align: bool =
matches!(align, AlignItems::Center | AlignItems::End);
let auto_row_stretch: bool = align == AlignItems::Stretch
&& is_row_dir
&& child_layout.get_height() == Length::Auto
&& (parent_height_auto
|| frame.get_min_inner_size().get_height() > 0.0);
if non_start_align || auto_row_stretch {
single_pass_ok = false;
}
}
}
scratch.flow_scratch.push(cur_bfs as u32);
}
Position::Absolute | Position::Fixed => {
if mode == LayoutRunMode::PerformLayout {
scratch.abs_scratch.push(cur_bfs as u32);
}
}
}
}
let flow_end: usize = scratch.flow_scratch.len();
let flow_count: usize = flow_end.saturating_sub(flow_start);
if single_pass_ok && shrinkable_flow_children > 0 && (!is_row_dir || flow_count >= 2) {
single_pass_ok = false;
}
let abs_end: usize = scratch.abs_scratch.len();
let flow_result: (Size, u8, f32) = if let Some(flex_dir) = flex_dir_opt {
Self::solve_flex_serial(
soa,
output_view,
scratch,
(flow_start, flow_end),
frame,
flex_dir,
(single_pass_ok, true, mode),
)
} else {
Self::solve_grid_serial(
soa,
output_view,
scratch,
(flow_start, flow_end),
frame,
mode,
)
};
scratch.flow_scratch.truncate(flow_start);
if mode == LayoutRunMode::PerformLayout && abs_end > abs_start {
let abs_copy: Vec<u32> = scratch.abs_scratch[abs_start..abs_end].to_vec();
scratch.abs_scratch.truncate(abs_start);
Self::solve_absolute_children_serial(
soa,
output_view,
scratch,
abs_copy.as_slice(),
inner_avail,
viewport,
content_origin,
);
} else {
scratch.abs_scratch.truncate(abs_start);
}
flow_result
}
fn solve_absolute_children_serial(
soa: &SceneLayoutSoa,
output_view: DisjointOutputView,
scratch: &mut WorkerLayoutScratch,
abs_children: &[u32],
inner_avail: Size,
viewport: Size,
content_origin: Point,
) {
let bfs_to_arena: &[u32] = soa.get_topology().get_bfs_to_arena().as_slice();
let layout_styles: &[LayoutStyle] = soa.get_layout_styles().as_slice();
for &abs_bfs in abs_children.iter() {
let arena_idx: usize = bfs_to_arena[abs_bfs as usize] as usize;
let child_layout: LayoutStyle = layout_styles[arena_idx];
let is_fixed: bool = child_layout.get_position() == Position::Fixed;
let ref_origin: Point = if is_fixed {
Point::new(0.0, 0.0)
} else {
content_origin
};
let ref_size: Size = if is_fixed { viewport } else { inner_avail };
let resolved_w: Option<f32> = child_layout
.get_width()
.resolve(ref_size.get_width(), viewport);
let resolved_h: Option<f32> = child_layout
.get_height()
.resolve(ref_size.get_height(), viewport);
let needs_intrinsic: bool = (resolved_w.is_none()
&& child_layout.left_offset().is_none()
&& child_layout.right_offset().is_some())
|| (resolved_h.is_none()
&& child_layout.top_offset().is_none()
&& child_layout.bottom_offset().is_some());
let probed: Size = if needs_intrinsic {
let probe_space: AvailableSpace = AvailableSpace::new(
ref_size.get_width(),
ref_size.get_height(),
viewport,
ref_origin.get_x(),
ref_origin.get_y(),
);
Self::solve_node_serial(
soa,
output_view,
scratch,
abs_bfs,
probe_space,
LayoutRunMode::ComputeSize,
)
.0
} else {
Size::new(ref_size.get_width(), ref_size.get_height())
};
let child_w: f32 = resolved_w.unwrap_or(probed.get_width());
let child_h: f32 = resolved_h.unwrap_or(probed.get_height());
let pos_x: f32 = if let Some(left) = child_layout.left_offset() {
ref_origin.get_x() + left
} else if let Some(right) = child_layout.right_offset() {
ref_origin.get_x() + (ref_size.get_width() - child_w - right)
} else {
ref_origin.get_x()
};
let pos_y: f32 = if let Some(top) = child_layout.top_offset() {
ref_origin.get_y() + top
} else if let Some(bottom) = child_layout.bottom_offset() {
ref_origin.get_y() + (ref_size.get_height() - child_h - bottom)
} else {
ref_origin.get_y()
};
let abs_space: AvailableSpace = AvailableSpace::new(
ref_size.get_width(),
ref_size.get_height(),
viewport,
pos_x,
pos_y,
);
let _: (Size, u8, f32) = Self::solve_node_serial(
soa,
output_view,
scratch,
abs_bfs,
abs_space,
LayoutRunMode::PerformLayout,
);
}
}
fn prepare_flex_item(
child_bfs: u32,
child_layout: LayoutStyle,
kind_tag: SoaNodeKindTag,
child_text: TextStyle,
axis_ctx: (bool, bool, f32, f32, Size),
) -> (ParallelFlexItem, PreparedFlexItemMeta, u8) {
let (is_row, wrap_enabled, main_avail, cross_avail, viewport): (
bool,
bool,
f32,
f32,
Size,
) = axis_ctx;
let width_len: Length = child_layout.get_width();
let height_len: Length = child_layout.get_height();
let basis_len: Length = child_layout.get_flex_basis();
let has_px_main: bool =
matches!(if is_row { width_len } else { height_len }, Length::Px(_));
let min_main_len: Length = if is_row {
child_layout.get_min_width()
} else {
child_layout.get_min_height()
};
let max_main_len: Length = if is_row {
child_layout.get_max_width()
} else {
child_layout.get_max_height()
};
let mut deps: u8 = LAYOUT_DEP_NONE;
if matches!(min_main_len, Length::Percent(_))
|| matches!(max_main_len, Length::Percent(_))
|| matches!(basis_len, Length::Percent(_))
{
deps |= if is_row {
LAYOUT_DEP_AVAIL_W
} else {
LAYOUT_DEP_AVAIL_H
};
}
if Self::is_viewport_length(min_main_len)
|| Self::is_viewport_length(max_main_len)
|| Self::is_viewport_length(basis_len)
{
deps |= LAYOUT_DEP_VIEWPORT;
}
let explicit_min_main: Option<f32> = min_main_len.resolve(main_avail, viewport);
let explicit_max_main: Option<f32> = max_main_len.resolve(main_avail, viewport);
let explicit_basis_main: Option<f32> = basis_len.resolve(main_avail, viewport);
let is_unwrapped_clip_text: bool =
kind_tag == SoaNodeKindTag::Text && child_text.get_overflow() == TextOverflow::Clip;
let grow: f32 = child_layout.get_flex_grow();
let shrink: f32 = child_layout.get_flex_shrink().max(0.0);
let width_auto: bool = width_len == Length::Auto;
let height_auto: bool = height_len == Length::Auto;
let mut factor_val: u16 = 0;
if width_auto {
factor_val |= FLEX_ITEM_WIDTH_AUTO;
}
if height_auto {
factor_val |= FLEX_ITEM_HEIGHT_AUTO;
}
if matches!(width_len, Length::Percent(_))
|| matches!(child_layout.get_min_width(), Length::Percent(_))
|| matches!(child_layout.get_max_width(), Length::Percent(_))
{
factor_val |= FLEX_ITEM_WIDTH_PERCENT;
}
if matches!(height_len, Length::Percent(_))
|| matches!(child_layout.get_min_height(), Length::Percent(_))
|| matches!(child_layout.get_max_height(), Length::Percent(_))
{
factor_val |= FLEX_ITEM_HEIGHT_PERCENT;
}
let mut zero_basis_size: Option<Size> = None;
if let Some(basis_raw) = explicit_basis_main {
let mut clamped_basis: f32 = basis_raw.max(explicit_min_main.unwrap_or(0.0));
if let Some(max_bound) = explicit_max_main {
clamped_basis = clamped_basis.min(max_bound);
}
if is_row {
if matches!(height_len, Length::Percent(_)) {
deps |= LAYOUT_DEP_AVAIL_H;
}
if Self::is_viewport_length(height_len) {
deps |= LAYOUT_DEP_VIEWPORT;
}
if let Some(resolved_h) = height_len.resolve(cross_avail, viewport) {
zero_basis_size = Some(Size::new(clamped_basis, resolved_h));
} else if grow > 0.0 {
zero_basis_size = Some(Size::new(clamped_basis, 0.0));
}
} else {
if matches!(width_len, Length::Percent(_)) {
deps |= LAYOUT_DEP_AVAIL_W;
}
if Self::is_viewport_length(width_len) {
deps |= LAYOUT_DEP_VIEWPORT;
}
if let Some(resolved_w) = width_len.resolve(cross_avail, viewport) {
zero_basis_size = Some(Size::new(resolved_w, clamped_basis));
} else if grow > 0.0 {
zero_basis_size = Some(Size::new(0.0, clamped_basis));
}
}
} else {
let zero_basis: bool =
!wrap_enabled && grow > 0.0 && if is_row { width_auto } else { height_auto };
if zero_basis {
if is_row {
if matches!(height_len, Length::Percent(_)) {
deps |= LAYOUT_DEP_AVAIL_H;
}
if Self::is_viewport_length(height_len) {
deps |= LAYOUT_DEP_VIEWPORT;
}
let height_val: f32 = height_len.resolve(cross_avail, viewport).unwrap_or(0.0);
zero_basis_size = Some(Size::new(0.0, height_val));
} else {
if matches!(width_len, Length::Percent(_)) {
deps |= LAYOUT_DEP_AVAIL_W;
}
if Self::is_viewport_length(width_len) {
deps |= LAYOUT_DEP_VIEWPORT;
}
let width_val: f32 = width_len.resolve(cross_avail, viewport).unwrap_or(0.0);
zero_basis_size = Some(Size::new(width_val, 0.0));
}
}
}
let mut rec: ParallelFlexItem = ParallelFlexItem::new(
child_bfs,
Size::default(),
child_layout.get_margin(),
child_layout.get_align_self(),
child_layout.get_overflow(),
factor_val,
);
let _: &mut ParallelFlexItem = rec.set_flex_grow(grow).set_flex_shrink(shrink);
(
rec,
PreparedFlexItemMeta {
zero_basis_size,
explicit_basis_main,
explicit_min_main,
explicit_max_main,
is_unwrapped_clip_text,
has_px_main,
},
deps,
)
}
fn resolve_flex_line_sizes(
soa: &SceneLayoutSoa,
output_view: DisjointOutputView,
scratch: &mut WorkerLayoutScratch,
line_items: &mut [ParallelFlexItem],
precomputed: Option<(f32, f32)>,
ctx: FlexLineContext,
) -> (f32, f32, u8, f32, bool, f32) {
let frame: ContainerFrame = ctx.get_frame();
let is_row: bool = ctx.get_is_row();
let wrap_enabled: bool = ctx.get_wrap_enabled();
let main_gap: f32 = ctx.get_main_gap();
let main_avail: f32 = ctx.get_main_avail();
let cross_avail: f32 = ctx.get_cross_avail();
let total_grow: f32 = ctx.get_total_grow();
let parent_layout: LayoutStyle = frame.get_parent_layout();
let viewport: Size = frame.get_viewport();
let content_origin: Point = frame.get_content_origin();
let count: usize = line_items.len();
let gaps_total: f32 = if count > 1 {
main_gap * ((count - 1) as f32)
} else {
0.0
};
let mut line_deps: u8 = LAYOUT_DEP_NONE;
let mut line_min_aw: f32 = 0.0;
let has_definite_or_grow: bool = frame.get_definite_width() || total_grow > 0.0;
let effective_main_avail: f32 = if is_row {
if has_definite_or_grow || wrap_enabled {
if total_grow > 0.0 {
line_deps |= LAYOUT_DEP_AVAIL_W;
}
main_avail
} else {
let min_w_len: Length = parent_layout.get_min_width();
if matches!(min_w_len, Length::Percent(_)) || Self::is_viewport_length(min_w_len) {
line_deps |= LAYOUT_DEP_VIEWPORT;
}
frame.get_min_inner_size().get_width()
}
} else if frame.get_definite_height() {
if total_grow > 0.0 {
line_deps |= LAYOUT_DEP_AVAIL_H;
}
main_avail
} else {
let min_h_len: Length = parent_layout.get_min_height();
if matches!(min_h_len, Length::Percent(_)) || Self::is_viewport_length(min_h_len) {
line_deps |= LAYOUT_DEP_VIEWPORT;
}
frame.get_min_inner_size().get_height()
};
let has_main_cap: bool = parent_layout.get_overflow() != Overflow::Scroll
&& if is_row {
frame.get_definite_width() || parent_layout.get_max_width() != Length::Auto
} else {
frame.get_definite_height() || parent_layout.get_max_height() != Length::Auto
};
let pre_overflows: bool = !wrap_enabled
&& has_main_cap
&& precomputed
.map(|(items_main, _): (f32, f32)| items_main + gaps_total > main_avail + 0.5)
.unwrap_or(false);
let mut line_shrunk: bool = false;
let (final_used_main, line_cross): (f32, f32) = if let Some((items_main, pre_cross)) =
precomputed
&& total_grow == 0.0
&& !pre_overflows
{
(items_main + gaps_total, pre_cross)
} else {
let used_main: f32 = if let Some((items_main, _)) = precomputed {
items_main + gaps_total
} else {
let mut acc: f32 = gaps_total;
for item in line_items.iter() {
let sz: f32 = if is_row {
item.get_size().get_width() + item.get_margin().horizontal()
} else {
item.get_size().get_height() + item.get_margin().vertical()
};
acc += sz;
}
acc
};
let free_main: f32 = (effective_main_avail - used_main).max(0.0);
let mut any_main_resized: bool = false;
if total_grow > 0.0 && free_main > 0.0 {
for item in line_items.iter_mut() {
let grow: f32 = item.get_flex_grow();
if grow > 0.0 {
let extra: f32 = free_main * (grow / total_grow);
if is_row {
let next_w: f32 = item.get_size().get_width() + extra;
item.get_mut_size().set_width(next_w);
} else {
let next_h: f32 = item.get_size().get_height() + extra;
item.get_mut_size().set_height(next_h);
}
any_main_resized = true;
}
}
} else if !wrap_enabled && has_main_cap && used_main > main_avail + 0.5 {
line_deps |= if is_row {
LAYOUT_DEP_AVAIL_W
} else {
LAYOUT_DEP_AVAIL_H
};
let mut rem_overflow: f32 = used_main - main_avail;
for _ in 0..4usize {
if rem_overflow <= 0.05 {
break;
}
let mut weighted_sum: f32 = 0.0;
for item in line_items.iter() {
let cur_main: f32 = if is_row {
item.get_size().get_width()
} else {
item.get_size().get_height()
};
if item.get_flex_shrink() > 0.0 && cur_main > item.get_min_main() + 0.05 {
weighted_sum += item.get_flex_shrink() * cur_main.max(1.0);
}
}
if weighted_sum <= 0.0 {
break;
}
let pass_overflow: f32 = rem_overflow;
let mut absorbed: f32 = 0.0;
for item in line_items.iter_mut() {
let cur_main: f32 = if is_row {
item.get_size().get_width()
} else {
item.get_size().get_height()
};
let min_m: f32 = item.get_min_main();
let shrink_f: f32 = item.get_flex_shrink();
if shrink_f > 0.0 && cur_main > min_m + 0.05 {
let weight_val: f32 = shrink_f * cur_main.max(1.0);
let raw_cut: f32 = pass_overflow * (weight_val / weighted_sum);
let next_main: f32 = (cur_main - raw_cut).max(min_m);
let cut: f32 = cur_main - next_main;
if cut > 0.01 {
if is_row {
item.get_mut_size().set_width(next_main);
} else {
item.get_mut_size().set_height(next_main);
}
absorbed += cut;
any_main_resized = true;
line_shrunk = true;
}
}
}
if absorbed <= 0.01 {
break;
}
rem_overflow = (rem_overflow - absorbed).max(0.0);
}
}
if total_grow > 0.0 || any_main_resized {
for item in line_items.iter_mut() {
let resized_item: bool = item.get_flex_grow() > 0.0 || any_main_resized;
let auto_cross: bool = resized_item
&& if is_row {
(item.get_flags() & FLEX_ITEM_HEIGHT_AUTO) != 0
} else {
(item.get_flags() & FLEX_ITEM_WIDTH_AUTO) != 0
};
if auto_cross {
let probe_w: f32 = if is_row {
item.get_size().get_width()
} else {
cross_avail
};
let probe_h: f32 = if is_row {
cross_avail
} else {
item.get_size().get_height()
};
let stretch_pw: bool =
is_row && (item.get_flags() & FLEX_ITEM_WIDTH_AUTO) != 0;
let stretch_ph: bool =
!is_row && (item.get_flags() & FLEX_ITEM_HEIGHT_AUTO) != 0;
let probe_sp: AvailableSpace = AvailableSpace::new(
probe_w,
probe_h,
viewport,
content_origin.get_x(),
content_origin.get_y(),
)
.with_stretch(stretch_pw, stretch_ph);
let (measured, c_deps, c_min_aw): (Size, u8, f32) = Self::solve_node_serial(
soa,
output_view,
scratch,
item.get_bfs_index(),
probe_sp,
LayoutRunMode::ComputeSize,
);
line_deps |= c_deps;
if c_min_aw > 0.0 {
line_min_aw =
line_min_aw.max(c_min_aw + item.get_margin().horizontal());
}
if is_row {
item.get_mut_size().set_height(measured.get_height());
} else {
item.get_mut_size().set_width(measured.get_width());
}
}
}
}
let mut sum_main: f32 = gaps_total;
let mut max_cross: f32 = 0.0;
for item in line_items.iter() {
if is_row {
sum_main += item.get_size().get_width() + item.get_margin().horizontal();
max_cross =
max_cross.max(item.get_size().get_height() + item.get_margin().vertical());
} else {
sum_main += item.get_size().get_height() + item.get_margin().vertical();
max_cross =
max_cross.max(item.get_size().get_width() + item.get_margin().horizontal());
}
}
(sum_main, max_cross)
};
(
final_used_main,
line_cross,
line_deps,
line_min_aw,
line_shrunk,
effective_main_avail,
)
}
fn solve_flex_serial(
soa: &SceneLayoutSoa,
output_view: DisjointOutputView,
scratch: &mut WorkerLayoutScratch,
flow_range: (usize, usize),
frame: ContainerFrame,
direction: FlexDirection,
mode_flags: (bool, bool, LayoutRunMode),
) -> (Size, u8, f32) {
let (flow_start, flow_end): (usize, usize) = flow_range;
let (single_pass_ok, apply_reverse, mode): (bool, bool, LayoutRunMode) = mode_flags;
let count_all: usize = flow_end.saturating_sub(flow_start);
if count_all == 0 {
return (Size::default(), LAYOUT_DEP_NONE, 0.0);
}
let parent_layout: LayoutStyle = frame.get_parent_layout();
let inner_avail: Size = frame.get_inner_avail();
let viewport: Size = frame.get_viewport();
let content_origin: Point = frame.get_content_origin();
let is_row: bool = matches!(direction, FlexDirection::Row | FlexDirection::RowReverse);
let is_reverse: bool = matches!(
direction,
FlexDirection::RowReverse | FlexDirection::ColumnReverse
);
let main_gap: f32 = if is_row {
parent_layout.get_column_gap()
} else {
parent_layout.get_row_gap()
};
let cross_gap: f32 = if is_row {
parent_layout.get_row_gap()
} else {
parent_layout.get_column_gap()
};
let main_avail: f32 = if is_row {
inner_avail.get_width()
} else {
inner_avail.get_height()
};
let cross_avail: f32 = if is_row {
inner_avail.get_height()
} else {
inner_avail.get_width()
};
if apply_reverse && is_reverse {
scratch.flow_scratch[flow_start..flow_end].reverse();
}
let wrap_enabled: bool = parent_layout.get_flex_wrap() == FlexWrap::Wrap;
let bfs_to_arena: &[u32] = soa.get_topology().get_bfs_to_arena().as_slice();
let layout_styles: &[LayoutStyle] = soa.get_layout_styles().as_slice();
let node_kinds: &[SoaNodeKindTag] = soa.get_node_kinds().as_slice();
let text_styles: &[TextStyle] = soa.get_text_styles().as_slice();
if single_pass_ok {
let parent_align: AlignItems = parent_layout.get_align_items();
let mut main_cursor: f32 = 0.0;
let mut max_cross: f32 = 0.0;
let mut agg_deps: u8 = LAYOUT_DEP_NONE;
let mut agg_min_aw: f32 = 0.0;
let records_start: usize = scratch.flex_items_scratch.len();
for offset in 0..count_all {
let child_bfs: u32 = scratch.flow_scratch[flow_start + offset];
let arena_idx: usize = bfs_to_arena[child_bfs as usize] as usize;
let child_layout: LayoutStyle = layout_styles[arena_idx];
let margin: Edges = child_layout.get_margin();
let align: AlignItems = match child_layout.get_align_self() {
AlignSelf::Auto => parent_align,
AlignSelf::Stretch => AlignItems::Stretch,
AlignSelf::Start => AlignItems::Start,
AlignSelf::Center => AlignItems::Center,
AlignSelf::End => AlignItems::End,
};
let (pos_x, pos_y): (f32, f32) = if is_row {
(
content_origin.get_x() + main_cursor + margin.get_left(),
content_origin.get_y() + margin.get_top(),
)
} else {
(
content_origin.get_x() + margin.get_left(),
content_origin.get_y() + main_cursor + margin.get_top(),
)
};
let stretch_w: bool = !is_row
&& align == AlignItems::Stretch
&& child_layout.get_width() == Length::Auto;
let stretch_h: bool = is_row
&& align == AlignItems::Stretch
&& child_layout.get_height() == Length::Auto;
if stretch_w {
agg_deps |= LAYOUT_DEP_AVAIL_W;
}
if stretch_h {
agg_deps |= LAYOUT_DEP_AVAIL_H;
}
let space_w: f32 = if stretch_w {
(inner_avail.get_width() - margin.horizontal()).max(0.0)
} else {
inner_avail.get_width()
};
let space_h: f32 = if stretch_h {
(inner_avail.get_height() - margin.vertical()).max(0.0)
} else {
inner_avail.get_height()
};
let final_space: AvailableSpace =
AvailableSpace::new(space_w, space_h, viewport, pos_x, pos_y)
.with_stretch(stretch_w, stretch_h);
let (placed, c_deps, c_min_aw): (Size, u8, f32) = Self::solve_node_serial(
soa,
output_view,
scratch,
child_bfs,
final_space,
mode,
);
agg_deps |= c_deps;
if c_min_aw > 0.0 {
agg_min_aw = agg_min_aw.max(c_min_aw + margin.horizontal());
}
let target_w: f32 = if stretch_w {
space_w.max(placed.get_width())
} else {
placed.get_width()
};
let target_h: f32 = if stretch_h {
space_h.max(placed.get_height())
} else {
placed.get_height()
};
if mode == LayoutRunMode::PerformLayout {
if (stretch_w && target_w > placed.get_width() + 0.01)
|| (stretch_h && target_h > placed.get_height() + 0.01)
{
Self::apply_post_stretch(
soa,
output_view,
arena_idx,
Some(target_w),
Some(target_h),
);
}
if stretch_w {
scratch.flex_items_scratch.push(ParallelFlexItem::new(
child_bfs,
Size::new(target_w, target_h),
margin,
AlignSelf::Stretch,
child_layout.get_overflow(),
0,
));
}
}
if is_row {
main_cursor += target_w + margin.horizontal();
max_cross = max_cross.max(target_h + margin.vertical());
} else {
main_cursor += target_h + margin.vertical();
max_cross = max_cross.max(target_w + margin.horizontal());
}
if offset + 1 < count_all {
main_cursor += main_gap;
}
}
let records_end: usize = scratch.flex_items_scratch.len();
if mode == LayoutRunMode::PerformLayout
&& records_end > records_start
&& max_cross > cross_avail + 0.5
{
for &rec in &scratch.flex_items_scratch[records_start..records_end] {
let arena_idx: usize = bfs_to_arena[rec.get_bfs_index() as usize] as usize;
let widened: f32 =
(max_cross - rec.get_margin().horizontal()).max(rec.get_size().get_width());
Self::apply_post_stretch(soa, output_view, arena_idx, Some(widened), None);
}
}
scratch.flex_items_scratch.truncate(records_start);
let out_size: Size = if is_row {
Size::new(main_cursor, max_cross)
} else {
Size::new(max_cross, main_cursor)
};
return (out_size, agg_deps, agg_min_aw);
}
let items_start: usize = scratch.flex_items_scratch.len();
let probe_template: AvailableSpace = AvailableSpace::new(
inner_avail.get_width(),
inner_avail.get_height(),
viewport,
content_origin.get_x(),
content_origin.get_y(),
);
let mut total_grow: f32 = 0.0;
let mut single_line_main: f32 = 0.0;
let mut single_line_cross: f32 = 0.0;
let mut pass1_deps: u8 = LAYOUT_DEP_NONE;
let mut pass1_min_aw: f32 = 0.0;
for flow_idx in flow_start..flow_end {
let child_bfs: u32 = scratch.flow_scratch[flow_idx];
let arena_idx: usize = bfs_to_arena[child_bfs as usize] as usize;
let (mut rec, meta, dep_bits): (ParallelFlexItem, PreparedFlexItemMeta, u8) =
Self::prepare_flex_item(
child_bfs,
layout_styles[arena_idx],
node_kinds[arena_idx],
text_styles[arena_idx],
(is_row, wrap_enabled, main_avail, cross_avail, viewport),
);
let PreparedFlexItemMeta {
zero_basis_size,
explicit_basis_main,
explicit_min_main,
explicit_max_main,
is_unwrapped_clip_text,
has_px_main,
} = meta;
pass1_deps |= dep_bits;
total_grow += rec.get_flex_grow();
let mut child_size: Size = if let Some(zb) = zero_basis_size {
zb
} else {
let (measured, c_deps, c_min_aw): (Size, u8, f32) = Self::solve_node_serial(
soa,
output_view,
scratch,
child_bfs,
probe_template,
LayoutRunMode::ComputeSize,
);
pass1_deps |= c_deps;
if c_min_aw > 0.0 {
pass1_min_aw = pass1_min_aw.max(c_min_aw + rec.get_margin().horizontal());
}
measured
};
if let Some(basis_raw) = explicit_basis_main
&& zero_basis_size.is_none()
{
let mut clamped_basis: f32 = basis_raw.max(explicit_min_main.unwrap_or(0.0));
if let Some(max_bound) = explicit_max_main {
clamped_basis = clamped_basis.min(max_bound);
}
if is_row {
child_size.set_width(clamped_basis);
} else {
child_size.set_height(clamped_basis);
}
}
let resolved_min_main: f32 = if let Some(explicit_min) = explicit_min_main {
explicit_min.max(0.0)
} else if rec.get_overflow() == Overflow::Scroll
|| (rec.get_overflow() == Overflow::Hidden && !has_px_main)
{
0.0
} else if is_row {
if is_unwrapped_clip_text {
child_size.get_width()
} else {
0.0
}
} else {
child_size.get_height()
};
let _: &mut ParallelFlexItem = rec.set_min_main(resolved_min_main).set_size(child_size);
if !wrap_enabled {
if is_row {
single_line_main += child_size.get_width() + rec.get_margin().horizontal();
single_line_cross = single_line_cross
.max(child_size.get_height() + rec.get_margin().vertical());
} else {
single_line_main += child_size.get_height() + rec.get_margin().vertical();
single_line_cross = single_line_cross
.max(child_size.get_width() + rec.get_margin().horizontal());
}
}
scratch.flex_items_scratch.push(rec);
}
let items_end: usize = scratch.flex_items_scratch.len();
if !wrap_enabled {
let mut line_ctx: FlexLineContext = FlexLineContext::new(
frame,
is_row,
main_gap,
main_avail,
cross_avail,
total_grow,
mode,
);
let _: &mut FlexLineContext = line_ctx.set_line_count(1);
let (line_size, line_deps, line_min_aw): (Size, u8, f32) = Self::solve_flex_line_serial(
soa,
output_view,
scratch,
(items_start, items_end),
0.0,
Some((single_line_main, single_line_cross)),
line_ctx,
);
scratch.flex_items_scratch.truncate(items_start);
return (
line_size,
pass1_deps | line_deps,
pass1_min_aw.max(line_min_aw),
);
}
let lines_start: usize = scratch.flex_lines_scratch.len();
let mut cur_line_start: usize = items_start;
let mut line_main: f32 = 0.0;
for item_idx in items_start..items_end {
let item: ParallelFlexItem = scratch.flex_items_scratch[item_idx];
let item_main: f32 = if is_row {
item.get_size().get_width() + item.get_margin().horizontal()
} else {
item.get_size().get_height() + item.get_margin().vertical()
};
let line_empty: bool = item_idx == cur_line_start;
let needed: f32 = if line_empty {
item_main
} else {
line_main + main_gap + item_main
};
if !line_empty && needed > main_avail && main_avail > 0.0 {
scratch.flex_lines_scratch.push((cur_line_start, item_idx));
cur_line_start = item_idx;
line_main = item_main;
} else {
line_main = needed;
}
}
if cur_line_start < items_end {
scratch.flex_lines_scratch.push((cur_line_start, items_end));
}
let lines_end: usize = scratch.flex_lines_scratch.len();
let line_count: usize = lines_end.saturating_sub(lines_start);
let mut cross_cursor: f32 = 0.0;
let mut max_main_extent: f32 = 0.0;
let mut wrap_deps: u8 = pass1_deps;
let mut wrap_min_aw: f32 = pass1_min_aw;
if is_row {
if line_count > 1 {
wrap_deps |= LAYOUT_DEP_AVAIL_W;
} else {
wrap_min_aw = wrap_min_aw.max(line_main + 0.5);
}
} else {
wrap_deps |= LAYOUT_DEP_AVAIL_H;
}
for line_offset in 0..line_count {
let line_range: (usize, usize) = scratch.flex_lines_scratch[lines_start + line_offset];
let mut line_grow: f32 = 0.0;
for item in &scratch.flex_items_scratch[line_range.0..line_range.1] {
line_grow += item.get_flex_grow();
}
let mut line_ctx: FlexLineContext = FlexLineContext::new(
frame,
is_row,
main_gap,
main_avail,
cross_avail,
line_grow,
mode,
);
let _: &mut FlexLineContext =
line_ctx.set_wrap_enabled(true).set_line_count(line_count);
let (line_size, l_deps, l_min_aw): (Size, u8, f32) = Self::solve_flex_line_serial(
soa,
output_view,
scratch,
line_range,
cross_cursor,
None,
line_ctx,
);
wrap_deps |= l_deps;
wrap_min_aw = wrap_min_aw.max(l_min_aw);
if is_row {
max_main_extent = max_main_extent.max(line_size.get_width());
cross_cursor += line_size.get_height();
} else {
max_main_extent = max_main_extent.max(line_size.get_height());
cross_cursor += line_size.get_width();
}
if line_offset + 1 < line_count {
cross_cursor += cross_gap;
}
}
scratch.flex_lines_scratch.truncate(lines_start);
scratch.flex_items_scratch.truncate(items_start);
let out_size: Size = if is_row {
Size::new(max_main_extent, cross_cursor)
} else {
Size::new(cross_cursor, max_main_extent)
};
(out_size, wrap_deps, wrap_min_aw)
}
fn solve_flex_line_serial(
soa: &SceneLayoutSoa,
output_view: DisjointOutputView,
scratch: &mut WorkerLayoutScratch,
line_range: (usize, usize),
cross_cursor: f32,
precomputed: Option<(f32, f32)>,
ctx: FlexLineContext,
) -> (Size, u8, f32) {
let (line_start, line_end): (usize, usize) = line_range;
let mut local_items: Vec<ParallelFlexItem> =
scratch.flex_items_scratch[line_start..line_end].to_vec();
let (
final_used_main,
line_cross,
line_deps,
line_min_aw,
line_shrunk,
effective_main_avail,
): (f32, f32, u8, f32, bool, f32) = Self::resolve_flex_line_sizes(
soa,
output_view,
scratch,
local_items.as_mut_slice(),
precomputed,
ctx,
);
let is_row: bool = ctx.get_is_row();
let mode: LayoutRunMode = ctx.get_mode();
if mode == LayoutRunMode::ComputeSize {
let sz: Size = if is_row {
Size::new(final_used_main, line_cross)
} else {
Size::new(line_cross, final_used_main)
};
return (sz, line_deps, line_min_aw);
}
let frame: ContainerFrame = ctx.get_frame();
let parent_layout: LayoutStyle = frame.get_parent_layout();
let inner_avail: Size = frame.get_inner_avail();
let viewport: Size = frame.get_viewport();
let content_origin: Point = frame.get_content_origin();
let main_gap: f32 = ctx.get_main_gap();
let cross_avail: f32 = ctx.get_cross_avail();
let wrap_enabled: bool = ctx.get_wrap_enabled();
let line_count: usize = ctx.get_line_count();
let count: usize = local_items.len();
let rem: f32 = (effective_main_avail - final_used_main).max(0.0);
let (mut main_cursor, extra_step): (f32, f32) = match parent_layout.get_justify_content() {
JustifyContent::Start => (0.0, 0.0),
JustifyContent::Center => (rem * 0.5, 0.0),
JustifyContent::End => (rem, 0.0),
JustifyContent::SpaceBetween => {
if count > 1 {
(0.0, rem / ((count - 1) as f32))
} else {
(0.0, 0.0)
}
}
JustifyContent::SpaceAround => {
let slot: f32 = rem / (count.max(1) as f32);
(slot * 0.5, slot)
}
JustifyContent::SpaceEvenly => {
let slot: f32 = rem / ((count + 1) as f32);
(slot, slot)
}
};
let min_cross: f32 = if is_row {
frame.get_min_inner_size().get_height()
} else {
frame.get_min_inner_size().get_width()
};
let definite_cross: bool = !is_row || frame.get_definite_height();
let effective_line_cross: f32 = if line_count == 1 {
let floor_cross: f32 = if definite_cross && (!wrap_enabled || is_row) {
cross_avail.max(min_cross)
} else {
min_cross
};
line_cross.max(floor_cross)
} else {
line_cross
};
let mut actual_line_cross: f32 = line_cross;
let parent_align: AlignItems = parent_layout.get_align_items();
let bfs_to_arena: &[u32] = soa.get_topology().get_bfs_to_arena().as_slice();
for (idx, rec) in local_items.iter().copied().enumerate() {
let child_bfs: u32 = rec.get_bfs_index();
let child_size: Size = rec.get_size();
let margin: Edges = rec.get_margin();
let width_auto: bool = (rec.get_flags() & FLEX_ITEM_WIDTH_AUTO) != 0;
let height_auto: bool = (rec.get_flags() & FLEX_ITEM_HEIGHT_AUTO) != 0;
let item_cross: f32 = if is_row {
child_size.get_height()
} else {
child_size.get_width()
};
let align: AlignItems = match rec.get_align_self() {
AlignSelf::Auto => parent_align,
AlignSelf::Stretch => AlignItems::Stretch,
AlignSelf::Start => AlignItems::Start,
AlignSelf::Center => AlignItems::Center,
AlignSelf::End => AlignItems::End,
};
let avail_item_cross: f32 = (effective_line_cross
- if is_row {
margin.vertical()
} else {
margin.horizontal()
})
.max(0.0);
let cross_offset: f32 = match align {
AlignItems::Start | AlignItems::Stretch => 0.0,
AlignItems::Center => ((avail_item_cross - item_cross) * 0.5).max(0.0),
AlignItems::End => (avail_item_cross - item_cross).max(0.0),
};
let main_resized_item: bool = rec.get_flex_grow() > 0.0 || line_shrunk;
let auto_cross_grow: bool =
main_resized_item && if is_row { height_auto } else { width_auto };
let target_w: f32 = if !is_row && align == AlignItems::Stretch && width_auto {
avail_item_cross.max(child_size.get_width())
} else {
child_size.get_width()
};
let target_h: f32 = if is_row && align == AlignItems::Stretch && height_auto {
avail_item_cross.max(child_size.get_height())
} else {
child_size.get_height()
};
let (pos_x, pos_y): (f32, f32) = if is_row {
(
content_origin.get_x() + main_cursor + margin.get_left(),
content_origin.get_y() + cross_cursor + cross_offset + margin.get_top(),
)
} else {
(
content_origin.get_x() + cross_cursor + cross_offset + margin.get_left(),
content_origin.get_y() + main_cursor + margin.get_top(),
)
};
let stretch_child_w: bool = !(auto_cross_grow && !is_row)
&& ((!is_row && align == AlignItems::Stretch && width_auto)
|| (is_row && main_resized_item && width_auto));
let stretch_child_h: bool = !(auto_cross_grow && is_row)
&& ((is_row && align == AlignItems::Stretch && height_auto)
|| (!is_row && main_resized_item && height_auto));
let space_w: f32 =
if !stretch_child_w && (rec.get_flags() & FLEX_ITEM_WIDTH_PERCENT) != 0 {
inner_avail.get_width()
} else if auto_cross_grow && !is_row {
cross_avail
} else {
target_w
};
let space_h: f32 =
if !stretch_child_h && (rec.get_flags() & FLEX_ITEM_HEIGHT_PERCENT) != 0 {
inner_avail.get_height()
} else if auto_cross_grow && is_row {
cross_avail
} else {
target_h
};
let final_space: AvailableSpace =
AvailableSpace::new(space_w, space_h, viewport, pos_x, pos_y)
.with_stretch(stretch_child_w, stretch_child_h);
let (placed_final, _, _): (Size, u8, f32) = Self::solve_node_serial(
soa,
output_view,
scratch,
child_bfs,
final_space,
LayoutRunMode::PerformLayout,
);
if auto_cross_grow && matches!(align, AlignItems::Center | AlignItems::End) {
let actual_item_cross: f32 = if is_row {
placed_final.get_height()
} else {
placed_final.get_width()
};
let refined_offset: f32 = match align {
AlignItems::Center => ((avail_item_cross - actual_item_cross) * 0.5).max(0.0),
AlignItems::End => (avail_item_cross - actual_item_cross).max(0.0),
AlignItems::Start | AlignItems::Stretch => cross_offset,
};
let delta_cross: f32 = refined_offset - cross_offset;
if delta_cross.abs() > 0.001 {
let (dx, dy): (f32, f32) = if is_row {
(0.0, delta_cross)
} else {
(delta_cross, 0.0)
};
Self::translate_subtree_bfs(soa, output_view, scratch, child_bfs, dx, dy);
}
}
let is_clipped: bool =
matches!(rec.get_overflow(), Overflow::Hidden | Overflow::Scroll);
let (desired_w, desired_h): (f32, f32) = if auto_cross_grow {
if is_row {
actual_line_cross =
actual_line_cross.max(placed_final.get_height() + margin.vertical());
(target_w, placed_final.get_height())
} else {
actual_line_cross =
actual_line_cross.max(placed_final.get_width() + margin.horizontal());
(placed_final.get_width(), target_h)
}
} else if is_clipped || main_resized_item {
(target_w, target_h)
} else {
(
target_w.max(placed_final.get_width()),
target_h.max(placed_final.get_height()),
)
};
let arena_idx: usize = bfs_to_arena[child_bfs as usize] as usize;
let cur_bounds: Rect = unsafe { output_view.read_box(arena_idx) }.get_bounds();
if (cur_bounds.get_width() - desired_w).abs() > 0.001
|| (cur_bounds.get_height() - desired_h).abs() > 0.001
{
Self::apply_post_stretch(
soa,
output_view,
arena_idx,
Some(desired_w),
Some(desired_h),
);
}
let advance: f32 = if is_row {
target_w + margin.horizontal()
} else {
target_h + margin.vertical()
};
main_cursor += advance;
if idx + 1 < count {
main_cursor += main_gap + extra_step;
}
}
let sz: Size = if is_row {
Size::new(final_used_main, actual_line_cross)
} else {
Size::new(actual_line_cross, final_used_main)
};
(sz, line_deps, line_min_aw)
}
fn solve_grid_serial(
soa: &SceneLayoutSoa,
output_view: DisjointOutputView,
scratch: &mut WorkerLayoutScratch,
flow_range: (usize, usize),
frame: ContainerFrame,
mode: LayoutRunMode,
) -> (Size, u8, f32) {
let (flow_start, flow_end): (usize, usize) = flow_range;
if flow_start >= flow_end {
return (Size::default(), LAYOUT_DEP_NONE, 0.0);
}
let parent_layout: LayoutStyle = frame.get_parent_layout();
let inner_avail: Size = frame.get_inner_avail();
let viewport: Size = frame.get_viewport();
let content_origin: Point = frame.get_content_origin();
let cols: usize = (parent_layout.get_grid_columns() as usize).max(1);
let col_gap: f32 = parent_layout.get_column_gap();
let row_gap: f32 = parent_layout.get_row_gap();
let total_col_gaps: f32 = col_gap * ((cols.saturating_sub(1)) as f32);
let col_w: f32 = ((inner_avail.get_width() - total_col_gaps) / (cols as f32)).max(0.0);
let col_step: f32 = col_w + col_gap;
let origin_x: f32 = content_origin.get_x();
let origin_y: f32 = content_origin.get_y();
let inner_h: f32 = inner_avail.get_height();
let bfs_to_arena: &[u32] = soa.get_topology().get_bfs_to_arena().as_slice();
let layout_styles: &[LayoutStyle] = soa.get_layout_styles().as_slice();
let mut y_cursor: f32 = 0.0;
let mut idx: usize = flow_start;
let mut grid_deps: u8 = LAYOUT_DEP_AVAIL_W;
while idx < flow_end {
let row_end: usize = (idx + cols).min(flow_end);
let mut row_h: f32 = 0.0;
let mut min_row_h: f32 = f32::INFINITY;
let pos_y: f32 = origin_y + y_cursor;
let mut pos_x: f32 = origin_x;
for pos in idx..row_end {
let child_bfs: u32 = scratch.flow_scratch[pos];
let arena_idx: usize = bfs_to_arena[child_bfs as usize] as usize;
let auto_w: bool = layout_styles[arena_idx].get_width() == Length::Auto;
let cell_space: AvailableSpace =
AvailableSpace::new(col_w, inner_h, viewport, pos_x, pos_y)
.with_stretch(auto_w, false);
let (child_size, c_deps, _): (Size, u8, f32) =
Self::solve_node_serial(soa, output_view, scratch, child_bfs, cell_space, mode);
grid_deps |= c_deps;
if mode == LayoutRunMode::PerformLayout
&& (child_size.get_width() - col_w).abs() > 0.001
{
Self::apply_post_stretch(soa, output_view, arena_idx, Some(col_w), None);
}
let child_h: f32 = child_size.get_height();
row_h = row_h.max(child_h);
min_row_h = min_row_h.min(child_h);
pos_x += col_step;
}
if mode == LayoutRunMode::PerformLayout && row_end - idx > 1 && min_row_h < row_h {
for &child_bfs in &scratch.flow_scratch[idx..row_end] {
let arena_idx: usize = bfs_to_arena[child_bfs as usize] as usize;
let cur_h: f32 = unsafe { output_view.read_box(arena_idx) }
.get_bounds()
.get_height();
if cur_h < row_h {
Self::apply_post_stretch(soa, output_view, arena_idx, None, Some(row_h));
}
}
}
y_cursor += row_h;
if row_end < flow_end {
y_cursor += row_gap;
}
idx = row_end;
}
(Size::new(inner_avail.get_width(), y_cursor), grid_deps, 0.0)
}
}