Skip to content

armgit / WacOS

Public Imported from GitHub
0

A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.

Rust
9.8 KB
Raw Blame
//! src\comum\vidro.h e squircle.h: a borda do Liquid Glass desenhada em D2D (borda escurecida + brilho especular), a
//! luz que segue o ponteiro, a "gosma" do Spotlight e o canto contínuo da Apple (squircle, corner smoothing de 60%).
#![allow(dead_code)]

use std::collections::HashMap;

use comum::windows::Win32::Graphics::Direct2D::Common::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::*;

/// a borda do Liquid Glass (agora na comum, que o menu de contexto também usa)
pub use comum::vidro::borda;
/// A luz do brilho seguindo o ponteiro, numa mola crítica de 0,3 s integrada por quadro
#[derive(Clone, Copy)]
pub struct LuzSegue {
    pub x: f32,
    pub y: f32,
    vx: f32,
    vy: f32,
}
impl Default for LuzSegue {
    fn default() -> Self {
        LuzSegue { x: -1.0, y: -1.0, vx: 0.0, vy: 0.0 }
    }
}
impl LuzSegue {
    /// avança até o alvo; true enquanto ainda anda
    pub fn passo(&mut self, tx: f32, ty: f32, dt_sec: f32) -> bool {
        if tx < 0.0 || ty < 0.0 {
            *self = LuzSegue::default();
            return false;
        }
        if self.x < 0.0 || self.y < 0.0 {
            *self = LuzSegue { x: tx, y: ty, vx: 0.0, vy: 0.0 }; // entrou agora: começa no ponteiro
            return false;
        }
        let w = 2.0 * std::f32::consts::PI / 0.3;
        let dt = dt_sec.clamp(0.0, 0.05);
        for _ in 0..4 {
            let h = dt / 4.0;
            let ax = w * w * (tx - self.x) - 2.0 * w * self.vx;
            let ay = w * w * (ty - self.y) - 2.0 * w * self.vy;
            self.vx += ax * h;
            self.vy += ay * h;
            self.x += self.vx * h;
            self.y += self.vy * h;
        }
        let moving = (tx - self.x).abs() > 0.3 || (ty - self.y).abs() > 0.3 || self.vx.abs() > 2.0 || self.vy.abs() > 2.0;
        if !moving {
            *self = LuzSegue { x: tx, y: ty, vx: 0.0, vy: 0.0 };
        }
        moving
    }
}
/// o pescoço rompe quando a folga entre os dois passa disto
pub fn gosma_rompe(raio: f32) -> f32 {
    0.28 * raio
}
/// "Gosma" do Liquid Glass: a cápsula e os círculos como uma peça só (pescoços côncavos entre vizinhos)
pub unsafe fn gosma(f: &ID2D1Factory, cap: RectF, cap_r: f32, cs: &[D2D1_ELLIPSE], broken: u32) -> Option<ID2D1Geometry> {
    let rrg = f.CreateRoundedRectangleGeometry(&comum::rr(cap, cap_r, cap_r)).ok()?;
    let mut acc: ID2D1Geometry = rrg.into();
    let unite = |acc: &mut ID2D1Geometry, g: ID2D1Geometry| {
        let Ok(p) = f.CreatePathGeometry() else { return };
        if let Ok(s) = p.Open() {
            if acc.CombineWithGeometry(&g, D2D1_COMBINE_MODE_UNION, None, 0.2, &s).is_ok() {
                let _ = s.Close();
                *acc = p.into();
            }
        }
    };
    let cy = (cap.top + cap.bottom) / 2.0;
    let mut prev = ell(pt(cap.right - cap_r, cy), cap_r, cap_r); // a ponta da cápsula
    for (i, c) in cs.iter().enumerate() {
        if c.radiusX < 0.5 || c.radiusY < 0.5 {
            continue;
        }
        if let Ok(eg) = f.CreateEllipseGeometry(c) {
            unite(&mut acc, eg.into());
        }
        let m = prev.radiusY.min(c.radiusY);
        let gap = (c.point.x - c.radiusX) - (prev.point.x + prev.radiusX);
        let g = gosma_rompe(m);
        if gap < g && c.point.x > prev.point.x && broken & (1 << i) == 0 {
            let k = (1.0 - gap / g).clamp(0.0, 4.0);
            let h = m * (0.05 + 0.28 * k).clamp(0.0, 0.92); // meia altura do pescoço no meio
            let (ax, bx) = (prev.point.x + prev.radiusX * 0.35, c.point.x - c.radiusX * 0.35);
            let mx = (ax + bx) / 2.0;
            let (ay, by) = (prev.radiusY * 0.937, c.radiusY * 0.937);
            if bx > ax {
                if let Ok(bp) = f.CreatePathGeometry() {
                    if let Ok(s) = bp.Open() {
                        s.BeginFigure(pt(ax, cy - ay), D2D1_FIGURE_BEGIN_FILLED);
                        s.AddQuadraticBezier(&D2D1_QUADRATIC_BEZIER_SEGMENT { point1: pt(mx, cy - h), point2: pt(bx, cy - by) });
                        s.AddLine(pt(bx, cy + by));
                        s.AddQuadraticBezier(&D2D1_QUADRATIC_BEZIER_SEGMENT { point1: pt(mx, cy + h), point2: pt(ax, cy + ay) });
                        s.EndFigure(D2D1_FIGURE_END_CLOSED);
                        let _ = s.Close();
                        unite(&mut acc, bp.into());
                    }
                }
            }
        }
        prev = *c;
    }
    Some(acc)
}
// ---- canto contínuo (squircle.h)
#[derive(Clone, Default)]
pub struct SqPerfil {
    pub r: f32,
    /// até onde a curva vai a partir da quina (1,6 × R)
    pub p: f32,
    /// a curva do canto de cima à esquerda, quina em (0,0): de (p, 0) até (0, p)
    pub xs: Vec<f32>,
    pub ys: Vec<f32>,
}
impl SqPerfil {
    /// altura da curva na distância dx da borda esquerda
    pub fn y_at(&self, dx: f32) -> f32 {
        if dx >= self.p {
            return 0.0;
        }
        for i in 0..self.xs.len().saturating_sub(1) {
            if dx <= self.xs[i] && dx >= self.xs[i + 1] {
                let t = if self.xs[i] == self.xs[i + 1] { 0.0 } else { (self.xs[i] - dx) / (self.xs[i] - self.xs[i + 1]) };
                return self.ys[i] + t * (self.ys[i + 1] - self.ys[i]);
            }
        }
        self.p
    }
    /// distância até a curva
    pub fn dist(&self, x: f32, y: f32) -> f32 {
        let mut best = 1e9f32;
        for i in 0..self.xs.len().saturating_sub(1) {
            let (ax, ay) = (self.xs[i], self.ys[i]);
            let (bx, by) = (self.xs[i + 1] - ax, self.ys[i + 1] - ay);
            let l2 = bx * bx + by * by;
            let t = if l2 > 0.0 { (((x - ax) * bx + (y - ay) * by) / l2).clamp(0.0, 1.0) } else { 0.0 };
            let (ex, ey) = (x - (ax + t * bx), y - (ay + t * by));
            best = best.min(ex * ex + ey * ey);
        }
        best.sqrt()
    }
}
thread_local! {
    static CACHE: std::cell::RefCell<HashMap<i32, SqPerfil>> = std::cell::RefCell::new(HashMap::new());
}
pub fn perfil_sq(r: f32) -> SqPerfil {
    let key = (r.max(0.0) * 8.0).round() as i32; // por raio (1/8 de px)
    if let Some(p) = CACHE.with(|c| c.borrow().get(&key).cloned()) {
        return p;
    }
    let r = key as f32 / 8.0;
    let mut pf = SqPerfil { r, ..Default::default() };
    let (sm, deg) = (0.6f32, std::f32::consts::PI / 180.0);
    let p = (1.0 + sm) * r;
    let arc_measure = 90.0 * (1.0 - sm);
    let arc_len = (arc_measure / 2.0 * deg).sin() * r * std::f32::consts::SQRT_2;
    let alpha = (90.0 - arc_measure) / 2.0;
    let p34 = r * (alpha / 2.0 * deg).tan();
    let beta = 45.0 * sm;
    let c = p34 * (beta * deg).cos();
    let d = c * (beta * deg).tan();
    let b = (p - arc_len - c - d) / 3.0;
    let a = 2.0 * b;
    pf.p = p;
    if r <= 0.0 {
        pf.xs = vec![0.0, 0.0];
        pf.ys = vec![0.0, 0.0];
    } else {
        // o traçado do canto de cima à DIREITA, a partir de (0,0) na borda de cima; vira o de cima à esquerda espelhando x
        let mut add = |x: f32, y: f32, pf: &mut SqPerfil| {
            pf.xs.push(p - x);
            pf.ys.push(y);
        };
        let bez = |pts: [f32; 8], first: bool, pf: &mut SqPerfil, add: &mut dyn FnMut(f32, f32, &mut SqPerfil)| {
            let [x0, y0, x1, y1, x2, y2, x3, y3] = pts;
            for k in (if first { 0 } else { 1 })..=16 {
                let t = k as f32 / 16.0;
                let u = 1.0 - t;
                add(u * u * u * x0 + 3.0 * u * u * t * x1 + 3.0 * u * t * t * x2 + t * t * t * x3, u * u * u * y0 + 3.0 * u * u * t * y1 + 3.0 * u * t * t * y2 + t * t * t * y3, pf);
            }
        };
        let (p3x, p3y) = (a + b + c, d);
        let (p4x, p4y) = (p3x + arc_len, p3y + arc_len);
        bez([0.0, 0.0, a, 0.0, a + b, 0.0, p3x, p3y], true, &mut pf, &mut add);
        let (cx, cy) = (p - r, r);
        let (a0, a1) = ((p3y - cy).atan2(p3x - cx), (p4y - cy).atan2(p4x - cx));
        for k in 1..=10 {
            let an = a0 + (a1 - a0) * k as f32 / 10.0;
            add(cx + r * an.cos(), cy + r * an.sin(), &mut pf);
        }
        bez([p4x, p4y, p4x + d, p4y + c, p4x + d, p4y + b + c, p4x + d, p4y + a + b + c], false, &mut pf, &mut add);
    }
    CACHE.with(|cc| cc.borrow_mut().insert(key, pf.clone()));
    pf
}
/// o raio que cabe num retângulo de meias medidas hw × hh (a curva vai até 1,6 × raio)
pub fn sq_raio(r: f32, hw: f32, hh: f32) -> f32 {
    r.min(hw.min(hh) / 1.6).max(0.0)
}
/// o retângulo inteiro com os quatro cantos contínuos, como figura fechada
pub unsafe fn sq_retangulo(sk: &ID2D1GeometrySink, r: RectF, radius: f32) {
    let rr_ = sq_raio(radius, (r.right - r.left) / 2.0, (r.bottom - r.top) / 2.0);
    let pf = perfil_sq(rr_);
    let p = if rr_ > 0.0 { pf.p } else { 0.0 };
    let n = if rr_ > 0.0 { pf.xs.len() } else { 0 };
    sk.BeginFigure(pt(r.left + p, r.top), D2D1_FIGURE_BEGIN_FILLED);
    sk.AddLine(pt(r.right - p, r.top));
    for i in 0..n {
        sk.AddLine(pt(r.right - pf.xs[i], r.top + pf.ys[i])); // cima à direita
    }
    sk.AddLine(pt(r.right, r.bottom - p));
    for i in 0..n {
        sk.AddLine(pt(r.right - pf.ys[i], r.bottom - pf.xs[i])); // baixo à direita
    }
    sk.AddLine(pt(r.left + p, r.bottom));
    for i in 0..n {
        sk.AddLine(pt(r.left + pf.xs[i], r.bottom - pf.ys[i])); // baixo à esquerda
    }
    sk.AddLine(pt(r.left, r.top + p));
    for i in 0..n {
        sk.AddLine(pt(r.left + pf.ys[i], r.top + pf.xs[i])); // cima à esquerda
    }
    sk.EndFigure(D2D1_FIGURE_END_CLOSED);
}
/// geometria do squircle (para preencher ou recortar)
pub unsafe fn squircle(f: &ID2D1Factory, r: RectF, radius: f32) -> Option<ID2D1PathGeometry> {
    let g = f.CreatePathGeometry().ok()?;
    let s = g.Open().ok()?;
    sq_retangulo(&s, r, radius);
    s.Close().ok()?;
    Some(g)
}