Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

11.3 KB
Raw Blame
//! Native Wayland `wlr-layer-shell` (`Layer::Background` or `Layer::Top`) surface backed directly
//! by a `wgpu::Surface` and `wp_viewporter` for fractional HiDPI + dynamic render scaling.
use std::ptr::NonNull;

use raw_window_handle::{RawDisplayHandle, RawWindowHandle, WaylandDisplayHandle, WaylandWindowHandle};
use smithay_client_toolkit::{
    compositor::{CompositorHandler, CompositorState},
    delegate_compositor, delegate_layer, delegate_output, delegate_registry, delegate_simple,
    output::{OutputHandler, OutputState},
    registry::{ProvidesRegistryState, RegistryState, SimpleGlobal},
    registry_handlers,
    shell::{
        wlr_layer::{Anchor, KeyboardInteractivity, Layer, LayerShell, LayerShellHandler, LayerSurface, LayerSurfaceConfigure},
        WaylandSurface,
    },
};
use wayland_client::{
    globals::registry_queue_init,
    protocol::{wl_output, wl_surface},
    Connection, Dispatch, EventQueue, Proxy, QueueHandle,
};
use wayland_protocols::wp::viewporter::client::{
    wp_viewport::{self, WpViewport},
    wp_viewporter::WpViewporter,
};

pub struct LayerApp {
    registry_state: RegistryState,
    output_state: OutputState,
    wp_viewporter: Option<SimpleGlobal<WpViewporter, 1>>,
    viewport: Option<WpViewport>,
    pub layer: LayerSurface,
    pub logical_w: u32,
    pub logical_h: u32,
    pub configured: bool,
    pub resized: bool,
    pub closed: bool,
}

impl CompositorHandler for LayerApp {
    fn scale_factor_changed(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_surface::WlSurface, _: i32) {}
    fn transform_changed(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_surface::WlSurface, _: wl_output::Transform) {}
    fn frame(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_surface::WlSurface, _: u32) {}
    fn surface_enter(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_surface::WlSurface, _: &wl_output::WlOutput) {}
    fn surface_leave(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &wl_surface::WlSurface, _: &wl_output::WlOutput) {}
}

impl OutputHandler for LayerApp {
    fn output_state(&mut self) -> &mut OutputState {
        &mut self.output_state
    }
    fn new_output(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {}
    fn update_output(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {}
    fn output_destroyed(&mut self, _: &Connection, _: &QueueHandle<Self>, _: wl_output::WlOutput) {}
}

impl LayerShellHandler for LayerApp {
    fn closed(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &LayerSurface) {
        self.closed = true;
    }

    fn configure(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &LayerSurface, configure: LayerSurfaceConfigure, _: u32) {
        let w = configure.new_size.0.max(1);
        let h = configure.new_size.1.max(1);
        if !self.configured || w != self.logical_w || h != self.logical_h {
            self.logical_w = w;
            self.logical_h = h;
            self.resized = true;
        }
        self.configured = true;
        if let Some(vp) = &self.viewport {
            vp.set_destination(self.logical_w as i32, self.logical_h as i32);
        }
    }
}

delegate_compositor!(LayerApp);
delegate_output!(LayerApp);
delegate_layer!(LayerApp);
delegate_registry!(LayerApp);
delegate_simple!(LayerApp, WpViewporter, 1);

impl Dispatch<WpViewport, ()> for LayerApp {
    fn event(_: &mut Self, _: &WpViewport, _: wp_viewport::Event, _: &(), _: &Connection, _: &QueueHandle<Self>) {}
}

impl ProvidesRegistryState for LayerApp {
    fn registry(&mut self) -> &mut RegistryState {
        &mut self.registry_state
    }
    registry_handlers![OutputState];
}

pub struct WaylandWallpaper {
    // Field order matters: `wgpu::Surface` must drop before `LayerApp` (`wl_surface`) and `Connection` (`wl_display`).
    pub surface: wgpu::Surface<'static>,
    pub state: LayerApp,
    queue: EventQueue<LayerApp>,
    conn: Connection,
    pub config: wgpu::SurfaceConfiguration,
    pub phys_w: u32,
    pub phys_h: u32,
    pub scale: f64,
}

impl WaylandWallpaper {
    pub fn new(
        instance: &wgpu::Instance,
        adapter: &wgpu::Adapter,
        device: &wgpu::Device,
        layer_kind: Layer,
        target_output: Option<&str>,
        output_scale: f64,
        render_scale: f64,
    ) -> Result<Self, String> {
        let conn = Connection::connect_to_env().map_err(|e| format!("Wayland connect: {e}"))?;
        let (globals, mut queue) = registry_queue_init::<LayerApp>(&conn).map_err(|e| format!("Wayland registry: {e}"))?;
        let qh = queue.handle();

        let compositor = CompositorState::bind(&globals, &qh).map_err(|e| format!("wl_compositor: {e}"))?;
        let layer_shell = LayerShell::bind(&globals, &qh).map_err(|e| format!("zwlr_layer_shell_v1: {e}"))?;
        let wp_viewporter = SimpleGlobal::<WpViewporter, 1>::bind(&globals, &qh).ok();
        let output_state = OutputState::new(&globals, &qh);
        let registry_state = RegistryState::new(&globals);

        // Pick requested wl_output if named, else let compositor pick default/focused output.
        let wl_surface = compositor.create_surface(&qh);
        let viewport = wp_viewporter
            .as_ref()
            .and_then(|vp| vp.get().ok())
            .map(|vp| vp.get_viewport(&wl_surface, &qh, ()));

        let mut chosen_output: Option<wl_output::WlOutput> = None;
        if let Some(name) = target_output {
            // Do one roundtrip after constructing LayerApp? We can pick by name if already advertised.
            for out in output_state.outputs() {
                if output_state.info(&out).and_then(|i| i.name).as_deref() == Some(name) {
                    chosen_output = Some(out);
                    break;
                }
            }
        }

        let layer = layer_shell.create_layer_surface(&qh, wl_surface, layer_kind, Some("threert-wallpaper"), chosen_output.as_ref());
        layer.set_anchor(Anchor::TOP | Anchor::BOTTOM | Anchor::LEFT | Anchor::RIGHT);
        layer.set_exclusive_zone(-1);
        layer.set_keyboard_interactivity(KeyboardInteractivity::None);
        layer.set_size(0, 0);
        layer.commit();

        let mut state = LayerApp {
            registry_state,
            output_state,
            wp_viewporter,
            viewport,
            layer,
            logical_w: 1280,
            logical_h: 800,
            configured: false,
            resized: false,
            closed: false,
        };

        // Wait for compositor's initial configure so we know the exact logical display dimensions.
        for _ in 0..32 {
            queue.roundtrip(&mut state).map_err(|e| format!("Wayland roundtrip: {e}"))?;
            if state.configured {
                break;
            }
        }
        if !state.configured {
            return Err("timed out waiting for wlr-layer-shell configure".into());
        }
        let _ = &state.wp_viewporter;

        let raw_display_handle = RawDisplayHandle::Wayland(WaylandDisplayHandle::new(
            NonNull::new(conn.backend().display_ptr() as *mut _).ok_or("null wl_display")?,
        ));
        let raw_window_handle = RawWindowHandle::Wayland(WaylandWindowHandle::new(
            NonNull::new(state.layer.wl_surface().id().as_ptr() as *mut _).ok_or("null wl_surface")?,
        ));
        let surface = unsafe {
            instance
                .create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle {
                    raw_display_handle,
                    raw_window_handle,
                })
                .map_err(|e| format!("create_surface: {e}"))?
        };

        let caps = surface.get_capabilities(adapter);
        let format = if caps.formats.contains(&wgpu::TextureFormat::Bgra8Unorm) {
            wgpu::TextureFormat::Bgra8Unorm
        } else if caps.formats.contains(&wgpu::TextureFormat::Rgba8Unorm) {
            wgpu::TextureFormat::Rgba8Unorm
        } else {
            *caps.formats.first().ok_or("surface has no supported formats")?
        };
        let alpha_mode = if caps.alpha_modes.contains(&wgpu::CompositeAlphaMode::Opaque) {
            wgpu::CompositeAlphaMode::Opaque
        } else {
            caps.alpha_modes[0]
        };

        let effective_scale = (output_scale * render_scale).clamp(0.25, 4.0);
        // Match three.js `Math.floor(width * pixelRatio)` so direct swapchain rendering never triggers a blit.
        let phys_w = ((state.logical_w as f64 * effective_scale).floor() as u32).max(1);
        let phys_h = ((state.logical_h as f64 * effective_scale).floor() as u32).max(1);
        if let Some(vp) = &state.viewport {
            vp.set_destination(state.logical_w as i32, state.logical_h as i32);
        }

        let usage = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::TEXTURE_BINDING;
        let supported_usage = caps.usages;
        let cfg_usage = if supported_usage.contains(usage) {
            usage
        } else {
            (usage & supported_usage) | wgpu::TextureUsages::RENDER_ATTACHMENT
        };

        let config = wgpu::SurfaceConfiguration {
            usage: cfg_usage,
            format,
            width: phys_w,
            height: phys_h,
            present_mode: wgpu::PresentMode::Fifo,
            desired_maximum_frame_latency: 2,
            alpha_mode,
            view_formats: vec![],
        };
        surface.configure(device, &config);
        state.resized = false;

        Ok(Self {
            conn,
            queue,
            state,
            surface,
            config,
            phys_w,
            phys_h,
            scale: effective_scale,
        })
    }

    pub fn reconfigure(&mut self, device: &wgpu::Device, effective_scale: f64) {
        let s = effective_scale.clamp(0.25, 4.0);
        let pw = ((self.state.logical_w as f64 * s).floor() as u32).max(1);
        let ph = ((self.state.logical_h as f64 * s).floor() as u32).max(1);
        if pw == self.phys_w && ph == self.phys_h && !self.state.resized {
            return;
        }
        self.scale = s;
        self.phys_w = pw;
        self.phys_h = ph;
        self.config.width = pw;
        self.config.height = ph;
        if let Some(vp) = &self.state.viewport {
            vp.set_destination(self.state.logical_w as i32, self.state.logical_h as i32);
        }
        self.surface.configure(device, &self.config);
        self.state.resized = false;
    }

    /// Non-blocking Wayland event pump (drains compositor configure/close events without blocking).
    pub fn poll_events(&mut self) {
        use std::os::fd::AsRawFd;
        let _ = self.conn.flush();
        if let Some(guard) = self.conn.prepare_read() {
            let mut pfd = libc::pollfd {
                fd: guard.connection_fd().as_raw_fd(),
                events: libc::POLLIN,
                revents: 0,
            };
            let ready = unsafe { libc::poll(&mut pfd, 1, 0) };
            if ready > 0 && (pfd.revents & libc::POLLIN) != 0 {
                let _ = guard.read();
            } else {
                drop(guard);
            }
        }
        let _ = self.queue.dispatch_pending(&mut self.state);
    }

    pub fn logical_size(&self) -> (u32, u32) {
        (self.state.logical_w, self.state.logical_h)
    }
}

impl Drop for WaylandWallpaper {
    fn drop(&mut self) {
        if let Some(vp) = self.state.viewport.take() {
            vp.destroy();
        }
    }
}