Created
November 11, 2026 14:38
-
-
Save ndevenish/e41b8eb5b1d7352ac17d2a58dc447154 to your computer and use it in GitHub Desktop.
Basic prototype of lattice viewer with resolution scaling over X
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| """Spike: a reciprocal lattice viewer that behaves well over remote X. | |
| The 3D view is rendered offscreen on the machine the program runs on, read | |
| back as pixels and drawn into an ordinary wx window as an image. The X server | |
| never sees an OpenGL request. | |
| While the user is interacting (rotating, zooming, resizing, moving a slider) | |
| the scene is rendered at 1/N of the window size. That small image is what is | |
| handed to the toolkit, with a scale transform, so that the X server does the | |
| enlargement. One full-size frame follows when the interaction stops. | |
| On Linux, PyPI has no wxPython wheels, so pip and uv try to compile it and | |
| need the GTK3 development headers. Install from conda-forge instead: | |
| mamba create -n lattice -c conda-forge python=3.12 wxpython moderngl numpy | |
| python lattice_viewer.py # run the viewer | |
| python lattice_viewer.py --snapshot out.ppm # test offscreen GL, no display | |
| Mouse: left-drag rotates, wheel zooms. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import ctypes | |
| import ctypes.util | |
| import os | |
| import sys | |
| import time | |
| import moderngl | |
| import numpy as np | |
| SETTLE_MS = 200 # quiet time after wheel/resize/slider before the sharp frame | |
| BACKGROUND = (0.05, 0.05, 0.07) | |
| # Rotation per pixel of drag at zoom 1. It is divided by the zoom, so the | |
| # lattice moves about the same distance on screen per pixel at any zoom. | |
| ROTATE_RAD_PER_PX = 0.01 | |
| # A display on a local socket that still takes longer than this to answer is | |
| # treated as remote (a forwarded socket, a container, a very loaded server). | |
| LOCAL_RTT_LIMIT_MS = 5.0 | |
| # Linear reductions the view can be rendered at while interacting. | |
| DIVISORS = (1, 2, 3, 4, 6, 8) | |
| # Automatic reduction only moves to a finer size when the predicted lag is | |
| # this fraction of the budget or less, so it does not flip between two sizes. | |
| AUTO_COMFORT = 0.7 | |
| def choose_divisor(current: int, full_bytes: float, bytes_per_ms: float, | |
| budget_ms: float) -> int: | |
| """Pick the reduction whose frames should arrive within the budget. | |
| Image bytes fall with the square of the divisor. Go coarser as soon as | |
| the current size is predicted to miss the budget; go finer only when the | |
| finer size fits with room to spare. | |
| """ | |
| def smallest_fitting(limit_ms: float) -> int: | |
| for divisor in DIVISORS: | |
| if full_bytes / divisor**2 / bytes_per_ms <= limit_ms: | |
| return divisor | |
| return DIVISORS[-1] | |
| must = smallest_fitting(budget_ms) | |
| if must > current: | |
| return must | |
| comfortable = smallest_fitting(budget_ms * AUTO_COMFORT) | |
| return min(current, comfortable) | |
| VERTEX_SHADER = """ | |
| #version 330 | |
| uniform mat3 u_rot; | |
| uniform vec2 u_scale; // lattice units -> NDC, per axis | |
| uniform float u_inv_rmax; // 1 / radius of the whole lattice | |
| uniform float u_point_px; | |
| uniform vec3 u_slice; // start (deg), width (deg), enabled | |
| in vec3 in_pos; | |
| in vec2 in_phi; // the two Ewald sphere crossings, or < 0 for none | |
| out float v_r; | |
| bool in_slice(float phi) { | |
| return phi >= 0.0 && mod(phi - u_slice.x, 360.0) <= u_slice.y; | |
| } | |
| void main() { | |
| if (u_slice.z > 0.5 && !in_slice(in_phi.x) && !in_slice(in_phi.y)) { | |
| gl_Position = vec4(2.0, 2.0, 2.0, 1.0); // outside the clip volume | |
| return; | |
| } | |
| vec3 p = u_rot * in_pos; | |
| // y is negated so that row 0 of the read-back is the top of the image. | |
| gl_Position = vec4(p.x * u_scale.x, -p.y * u_scale.y, | |
| -p.z * u_inv_rmax * 0.9, 1.0); | |
| gl_PointSize = u_point_px; | |
| v_r = length(in_pos) * u_inv_rmax; | |
| } | |
| """ | |
| FRAGMENT_SHADER = """ | |
| #version 330 | |
| uniform int u_style; // 0 = dot, 1 = cross | |
| uniform float u_point_px; | |
| in float v_r; | |
| out vec4 f_color; | |
| void main() { | |
| vec2 c = gl_PointCoord - 0.5; | |
| if (u_style == 0) { | |
| // Below 2 px a point is a single pixel, and rounding the corners off | |
| // would discard that pixel whenever the point sits off-centre in it. | |
| if (u_point_px >= 2.0 && dot(c, c) > 0.25) discard; | |
| } else { | |
| float arm = max(0.5 / u_point_px, 0.1); // arms at least 1 px thick | |
| if (abs(c.x) > arm && abs(c.y) > arm) discard; | |
| } | |
| // Warm at low resolution (near the origin), blue at high resolution. | |
| f_color = vec4(mix(vec3(1.0, 0.85, 0.3), vec3(0.35, 0.7, 1.0), v_r), 1.0); | |
| } | |
| """ | |
| LINE_VERTEX_SHADER = """ | |
| #version 330 | |
| uniform mat3 u_rot; | |
| uniform vec2 u_scale; | |
| uniform float u_inv_rmax; | |
| uniform vec2 u_offset; // NDC nudge, used to thicken lines | |
| in vec3 in_pos; | |
| void main() { | |
| vec3 p = u_rot * in_pos; | |
| gl_Position = vec4(p.x * u_scale.x + u_offset.x, -p.y * u_scale.y + u_offset.y, | |
| -p.z * u_inv_rmax * 0.9, 1.0); | |
| } | |
| """ | |
| LINE_FRAGMENT_SHADER = """ | |
| #version 330 | |
| uniform vec3 u_color; | |
| out vec4 f_color; | |
| void main() { | |
| f_color = vec4(u_color, 1.0); | |
| } | |
| """ | |
| AXIS_COLOR = (1.0, 0.35, 0.35) | |
| BEAM_COLOR = (0.4, 1.0, 0.5) | |
| CELL_COLOR = (1.0, 1.0, 1.0) | |
| def unit_cell_vertices() -> np.ndarray: | |
| """The 12 edges of the reciprocal unit cell, with one corner at the origin. | |
| Positions are in units of the cell's own basis, so the cell is the unit | |
| cube whatever the cell dimensions. | |
| """ | |
| corners = [(i, j, k) for i in (0, 1) for j in (0, 1) for k in (0, 1)] | |
| segments = [] | |
| for corner in corners: | |
| for axis in range(3): | |
| if corner[axis] == 0: | |
| far = list(corner) | |
| far[axis] = 1 | |
| segments += [corner, far] | |
| return np.array(segments, dtype="f4") | |
| def arrow_vertices(direction: np.ndarray, length: float) -> np.ndarray: | |
| """Line segments for a line through the origin with a head at +direction.""" | |
| d = direction / np.linalg.norm(direction) | |
| u = np.cross(d, [0.0, 1.0, 0.0] if abs(d[1]) < 0.9 else [1.0, 0.0, 0.0]) | |
| u /= np.linalg.norm(u) | |
| v = np.cross(d, u) | |
| tip = d * length | |
| back = d * length * 0.9 | |
| barbs = [back + side * length * 0.04 for side in (u, -u, v, -v)] | |
| segments = [-tip, tip] | |
| for barb in barbs: | |
| segments += [tip, barb] | |
| return np.array(segments, dtype="f4") | |
| class Lattice: | |
| """Points h,k,l of a cubic cell out to a radius, sorted by distance. | |
| Positions are in units of 1/a, so a point at radius r has d-spacing a/r. | |
| Sorting by radius turns a resolution cut-off into "draw the first n". | |
| `phi` holds, per point, the two rotation angles in degrees at which the | |
| point crosses the Ewald sphere, or NO_CROSSING for points too close to | |
| the rotation axis ever to cross it. The geometry is the usual one: the | |
| crystal turns about +x and the beam travels along -z. | |
| """ | |
| NO_CROSSING = -1.0 | |
| AXIS = np.array([1.0, 0.0, 0.0]) | |
| BEAM = np.array([0.0, 0.0, -1.0]) | |
| def __init__(self, rmax: float, cell_a: float, wavelength: float): | |
| n = int(np.floor(rmax)) | |
| axis = np.arange(-n, n + 1) | |
| hkl = np.stack(np.meshgrid(axis, axis, axis, indexing="ij"), -1) | |
| hkl = hkl.reshape(-1, 3) | |
| radius = np.linalg.norm(hkl, axis=1) | |
| keep = (radius > 0) & (radius <= rmax) | |
| order = np.argsort(radius[keep], kind="stable") | |
| self.points = hkl[keep][order].astype("f4") | |
| self.radius = radius[keep][order] | |
| self.rmax = rmax | |
| self.cell_a = cell_a | |
| self.wavelength = wavelength | |
| self.phi = self._ewald_crossings().astype("f4") | |
| def _ewald_crossings(self) -> np.ndarray: | |
| # A point r, turned by phi about the axis e, is | |
| # r(phi) = (r.e) e + cos(phi) r_perp + sin(phi) (e x r) | |
| # and diffracts when |s0 + r(phi)| = |s0|, i.e. 2 s0.r(phi) = -|r|^2. | |
| # That is A cos(phi) + B sin(phi) = C, with two solutions or none. | |
| r = self.points.astype("f8") | |
| e = self.AXIS | |
| s0 = self.BEAM * self.cell_a / self.wavelength # in units of 1/a | |
| along = r @ e | |
| a = (r - np.outer(along, e)) @ s0 | |
| b = np.cross(e, r) @ s0 | |
| c = -0.5 * np.einsum("ij,ij->i", r, r) - along * (s0 @ e) | |
| reach = np.hypot(a, b) | |
| crosses = (reach > 0) & (np.abs(c) <= reach) | |
| centre = np.arctan2(b, a) | |
| half = np.arccos(np.clip(c / np.where(crosses, reach, 1.0), -1.0, 1.0)) | |
| phi = np.degrees(np.stack([centre - half, centre + half], axis=1)) % 360.0 | |
| phi[~crosses] = self.NO_CROSSING | |
| return phi | |
| def count_shown(self, n: int, slice_range: tuple[float, float] | None) -> int: | |
| """How many of the first n points fall in the slice (start, width).""" | |
| if slice_range is None: | |
| return n | |
| start, width = slice_range | |
| phi = self.phi[:n] | |
| inside = (phi >= 0) & ((phi - start) % 360.0 <= width) | |
| return int(inside.any(axis=1).sum()) | |
| def count_within(self, r: float) -> int: | |
| return int(np.searchsorted(self.radius, r, side="right")) | |
| def d_spacing(self, r: float) -> float: | |
| return self.cell_a / r | |
| class OffscreenRenderer: | |
| """Draws the lattice into a framebuffer object and returns RGB bytes.""" | |
| def __init__(self, lattice: Lattice, backend: str): | |
| kwargs = {"standalone": True, "require": 330} | |
| if backend != "default": | |
| kwargs["backend"] = backend | |
| if backend == "egl": | |
| # The loader's default names are the unversioned "libEGL.so" and | |
| # "libGL.so", which only exist where the -devel packages are | |
| # installed. Ask for the runtime libraries instead. | |
| kwargs["libegl"] = ctypes.util.find_library("EGL") or "libEGL.so.1" | |
| kwargs["libgl"] = ctypes.util.find_library("GL") or "libGL.so.1" | |
| self.ctx = moderngl.create_context(**kwargs) | |
| self.lattice = lattice | |
| self.prog = self.ctx.program( | |
| vertex_shader=VERTEX_SHADER, fragment_shader=FRAGMENT_SHADER | |
| ) | |
| self.vao = self.ctx.vertex_array( | |
| self.prog, | |
| [ | |
| (self.ctx.buffer(lattice.points.tobytes()), "3f", "in_pos"), | |
| (self.ctx.buffer(lattice.phi.tobytes()), "2f", "in_phi"), | |
| ], | |
| ) | |
| self.prog["u_inv_rmax"].value = 1.0 / lattice.rmax | |
| # Line overlays: rotation axis and beam direction as arrows through | |
| # the origin, and the outline of the reciprocal unit cell. | |
| self.line_prog = self.ctx.program( | |
| vertex_shader=LINE_VERTEX_SHADER, fragment_shader=LINE_FRAGMENT_SHADER | |
| ) | |
| self.line_prog["u_inv_rmax"].value = 1.0 / lattice.rmax | |
| self.overlays = {} | |
| reach = lattice.rmax * 1.04 | |
| for name, vertices, color in ( | |
| ("axis", arrow_vertices(lattice.AXIS, reach), AXIS_COLOR), | |
| ("beam", arrow_vertices(lattice.BEAM, reach), BEAM_COLOR), | |
| ("cell", unit_cell_vertices(), CELL_COLOR), | |
| ): | |
| vao = self.ctx.vertex_array( | |
| self.line_prog, [(self.ctx.buffer(vertices.tobytes()), "3f", "in_pos")] | |
| ) | |
| self.overlays[name] = (vao, color) | |
| self._fbos: dict[tuple[int, int], moderngl.Framebuffer] = {} | |
| def describe(self) -> str: | |
| info = self.ctx.info | |
| return f"{info['GL_RENDERER']} ({info['GL_VERSION']})" | |
| def _framebuffer(self, size: tuple[int, int]) -> moderngl.Framebuffer: | |
| fbo = self._fbos.get(size) | |
| if fbo is None: | |
| if len(self._fbos) >= 4: # sizes churn during a window resize | |
| for old in self._fbos.values(): | |
| old.release() | |
| self._fbos.clear() | |
| fbo = self.ctx.framebuffer( | |
| color_attachments=[self.ctx.renderbuffer(size, components=4)], | |
| depth_attachment=self.ctx.depth_renderbuffer(size), | |
| ) | |
| self._fbos[size] = fbo | |
| return fbo | |
| def render( | |
| self, | |
| width: int, | |
| height: int, | |
| rot: np.ndarray, | |
| zoom: float, | |
| style: int, | |
| point_px: float, | |
| n_points: int, | |
| slice_range: tuple[float, float] | None = None, | |
| overlays: tuple[str, ...] = (), | |
| line_px: float = 1.0, | |
| ) -> bytes: | |
| """Return width*height*3 bytes of RGB, top row first.""" | |
| fbo = self._framebuffer((width, height)) | |
| fbo.use() | |
| fbo.clear(*BACKGROUND, 1.0, depth=1.0) | |
| self.ctx.enable_only(moderngl.DEPTH_TEST | moderngl.PROGRAM_POINT_SIZE) | |
| # Orthographic: the whole sphere fits the shorter side at zoom 1. | |
| fit = zoom / (self.lattice.rmax * 1.1) | |
| shorter = min(width, height) | |
| scale = (fit * shorter / width, fit * shorter / height) | |
| rot_bytes = rot.T.astype("f4").tobytes() # column-major | |
| self.prog["u_scale"].value = scale | |
| self.prog["u_rot"].write(rot_bytes) | |
| self.prog["u_style"].value = style | |
| self.prog["u_point_px"].value = max(1.0, point_px) | |
| self.prog["u_slice"].value = (*slice_range, 1.0) if slice_range else (0.0, 0.0, 0.0) | |
| if n_points > 0: | |
| self.vao.render(moderngl.POINTS, vertices=n_points) | |
| if overlays: | |
| self.line_prog["u_scale"].value = scale | |
| self.line_prog["u_rot"].write(rot_bytes) | |
| # Wide lines are not available in core OpenGL, so thicken by | |
| # redrawing one pixel apart. | |
| thickness = max(1, round(line_px)) | |
| for name in overlays: | |
| vao, color = self.overlays[name] | |
| self.line_prog["u_color"].value = color | |
| for i in range(thickness): | |
| for j in range(thickness): | |
| self.line_prog["u_offset"].value = (2 * i / width, 2 * j / height) | |
| vao.render(moderngl.LINES) | |
| return fbo.read(components=3, alignment=1) | |
| class DisplayLink: | |
| """The path between this process and the screen. | |
| `sync(nbytes)` blocks until the display has dealt with everything sent so | |
| far, `nbytes` being the size of the frame just sent. It is None when | |
| there is nothing to wait for. | |
| """ | |
| def __init__(self, sync, where: str, remote: bool = False): | |
| self._sync = sync | |
| self.where = where | |
| self.remote = remote | |
| self.rtt_ms = None | |
| if sync is not None: | |
| self.rtt_ms = min(self.wait(0) for _ in range(5)) | |
| def wait(self, nbytes: int) -> float: | |
| """Block for one round trip; return how long it took in ms.""" | |
| start = time.perf_counter() | |
| self._sync(nbytes) | |
| return (time.perf_counter() - start) * 1e3 | |
| @property | |
| def can_wait(self) -> bool: | |
| return self._sync is not None | |
| def describe(self) -> str: | |
| kind = "remote" if self.remote else "local" | |
| rtt = "" if self.rtt_ms is None else f", round trip {self.rtt_ms:.2f} ms" | |
| return f"{kind} ({self.where}{rtt})" | |
| def gdk_x11_sync(): | |
| """XSync on the toolkit's own X connection, or None if GDK is not on X11. | |
| It has to be the toolkit's connection: the server answers one client's | |
| requests in order, so the reply cannot arrive before the frame has. | |
| """ | |
| gdk = ctypes.CDLL(ctypes.util.find_library("gdk-3") or "libgdk-3.so.0") | |
| gobject = ctypes.CDLL( | |
| ctypes.util.find_library("gobject-2.0") or "libgobject-2.0.so.0" | |
| ) | |
| xlib = ctypes.CDLL(ctypes.util.find_library("X11") or "libX11.so.6") | |
| gdk.gdk_display_get_default.restype = ctypes.c_void_p | |
| gdk.gdk_x11_display_get_xdisplay.restype = ctypes.c_void_p | |
| gdk.gdk_x11_display_get_xdisplay.argtypes = [ctypes.c_void_p] | |
| gobject.g_type_name_from_instance.restype = ctypes.c_char_p | |
| gobject.g_type_name_from_instance.argtypes = [ctypes.c_void_p] | |
| xlib.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int] | |
| display = gdk.gdk_display_get_default() | |
| if not display or gobject.g_type_name_from_instance(display) != b"GdkX11Display": | |
| return None # Wayland or similar | |
| xdisplay = gdk.gdk_x11_display_get_xdisplay(display) | |
| return lambda _nbytes: xlib.XSync(xdisplay, 0) | |
| def detect_link(args, platform_info: tuple) -> DisplayLink: | |
| """Work out whether the display is local, and how to wait for it. | |
| Call after the wx.App exists, so that the toolkit has opened its display. | |
| """ | |
| if args.sim_rtt_ms is not None: | |
| rtt = args.sim_rtt_ms / 1e3 | |
| rate = args.sim_mbytes_per_s * 1e6 | |
| link = DisplayLink( | |
| lambda nbytes: time.sleep(rtt + nbytes / rate), | |
| f"simulated, {args.sim_mbytes_per_s:g} MB/s", | |
| remote=True, | |
| ) | |
| elif "wxGTK" not in platform_info: | |
| link = DisplayLink(None, f"{platform_info[1]}, not X11") | |
| else: | |
| name = os.environ.get("DISPLAY", "") | |
| host = name.rsplit(":", 1)[0] | |
| # ":0", "unix:0" and XQuartz's "/path/to/socket:0" are local sockets; | |
| # "localhost:10.0" is what ssh -X sets up. | |
| local_socket = host in ("", "unix") or host.startswith("/") | |
| try: | |
| sync = gdk_x11_sync() | |
| except (OSError, AttributeError) as exc: | |
| print(f"cannot reach Xlib through GDK ({exc}); frames will not be paced") | |
| link = DisplayLink(None, f"DISPLAY={name}", remote=not local_socket) | |
| else: | |
| if sync is None: | |
| link = DisplayLink(None, "GDK is not using X11") | |
| else: | |
| link = DisplayLink(sync, f"DISPLAY={name}") | |
| link.remote = not local_socket or link.rtt_ms > LOCAL_RTT_LIMIT_MS | |
| if args.link != "auto": | |
| link.remote = args.link == "remote" | |
| return link | |
| def rotation_xy(angle_x: float, angle_y: float) -> np.ndarray: | |
| """Rotation about screen x then screen y (x right, y up, z to viewer).""" | |
| cx, sx = np.cos(angle_x), np.sin(angle_x) | |
| cy, sy = np.cos(angle_y), np.sin(angle_y) | |
| rx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]]) | |
| ry = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]]) | |
| return ry @ rx | |
| DEFAULT_ROTATION = rotation_xy(0.35, -0.5) | |
| def write_ppm(path: str, width: int, height: int, rgb: bytes) -> None: | |
| with open(path, "wb") as f: | |
| f.write(b"P6\n%d %d\n255\n" % (width, height)) | |
| f.write(rgb) | |
| def run_snapshot(renderer: OffscreenRenderer, lattice: Lattice, path: str) -> None: | |
| size = 800 | |
| start = time.perf_counter() | |
| rgb = renderer.render( | |
| size, size, DEFAULT_ROTATION, 1.0, 0, 3.0, len(lattice.points) | |
| ) | |
| elapsed = (time.perf_counter() - start) * 1e3 | |
| write_ppm(path, size, size, rgb) | |
| print(f"renderer: {renderer.describe()}") | |
| print(f"{len(lattice.points)} points, {size}x{size} in {elapsed:.1f} ms -> {path}") | |
| def run_gui(renderer: OffscreenRenderer, lattice: Lattice, args) -> None: | |
| # wx is imported here so that --snapshot works on a host with no display. | |
| import wx | |
| app = wx.App() | |
| link = detect_link(args, wx.PlatformInfo) | |
| print(f"display: {link.describe()}") | |
| class LatticeView(wx.Window): | |
| def __init__(self, parent, on_frame): | |
| super().__init__(parent, style=wx.FULL_REPAINT_ON_RESIZE) | |
| # We paint every pixel ourselves; no background erase, no flicker. | |
| self.SetBackgroundStyle(wx.BG_STYLE_PAINT) | |
| self.on_frame = on_frame | |
| self.rot = DEFAULT_ROTATION.copy() | |
| self.zoom = 1.0 | |
| self.style = 0 | |
| self.point_size = 3 | |
| self.r_limit = lattice.rmax | |
| self.slice_range = None # (start, width) in degrees, or None | |
| self.overlays = () # any of "axis", "beam", "cell" | |
| self.divisor = 4 # linear down-scaling while interacting | |
| self.auto = True # choose the divisor from the measured lag | |
| self.target_ms = args.target_ms | |
| self._bytes_per_ms = None # smoothed throughput of the link | |
| self._bitmap = None | |
| self._unreported = None # stats of a frame drawn but not yet acked | |
| self._dirty = True | |
| self._low_res = False | |
| self._drag_from = None | |
| self._settle = wx.Timer(self) | |
| self.Bind(wx.EVT_PAINT, self.on_paint) | |
| self.Bind(wx.EVT_SIZE, self.on_size) | |
| self.Bind(wx.EVT_LEFT_DOWN, self.on_left_down) | |
| self.Bind(wx.EVT_LEFT_UP, self.on_left_up) | |
| self.Bind(wx.EVT_MOTION, self.on_motion) | |
| self.Bind(wx.EVT_MOUSEWHEEL, self.on_wheel) | |
| self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, self.on_capture_lost) | |
| self.Bind(wx.EVT_TIMER, self.on_settle, self._settle) | |
| # -- scheduling --------------------------------------------------- | |
| def invalidate(self, low_res: bool, settle: bool = False) -> None: | |
| """Ask for a new frame. Repeated calls collapse into one paint.""" | |
| self._low_res = low_res | |
| self._dirty = True | |
| if settle: | |
| self._settle.StartOnce(SETTLE_MS) | |
| self.Refresh(eraseBackground=False) | |
| def changed(self) -> None: | |
| """A setting moved: cheap frame now, sharp frame once it stops.""" | |
| self.invalidate(low_res=True, settle=True) | |
| def on_settle(self, _evt) -> None: | |
| if self._drag_from is None: | |
| self.invalidate(low_res=False) | |
| # -- drawing ------------------------------------------------------ | |
| def on_paint(self, _evt) -> None: | |
| # Drawn straight to the window. A wx.BufferedPaintDC would build | |
| # a full-size client-side bitmap and defeat the point. | |
| dc = wx.PaintDC(self) | |
| width, height = self.GetClientSize() | |
| if width < 1 or height < 1: | |
| return | |
| if self._dirty or self._bitmap is None: | |
| self._render(width, height) | |
| gc = wx.GraphicsContext.Create(dc) | |
| # Nearest-neighbour: the one filter every X server applies itself. | |
| gc.SetInterpolationQuality(wx.INTERPOLATION_FAST) | |
| gc.DrawBitmap(self._bitmap, 0, 0, width, height) | |
| if self._unreported is not None: | |
| # After this handler returns the toolkit finishes the paint. | |
| wx.CallAfter(self._frame_sent, *self._unreported) | |
| self._unreported = None | |
| def _frame_sent(self, width, height, divisor, render_ms, n_points) -> None: | |
| """Wait for the display to catch up, then report the frame. | |
| Blocking here is the pile-up fix. Input that arrives meanwhile | |
| queues up and collapses into a single next frame, so we can never | |
| render faster than the link delivers. | |
| """ | |
| ack_ms = None | |
| if link.remote and link.can_wait: | |
| wire_bytes = width * height * 4 | |
| ack_ms = link.wait(wire_bytes) | |
| self._adapt(wire_bytes * divisor**2, wire_bytes, ack_ms, render_ms) | |
| self.on_frame(width, height, divisor, render_ms, n_points, ack_ms) | |
| def _adapt(self, full_bytes, wire_bytes, ack_ms, render_ms) -> None: | |
| """Update the link estimate from one frame and re-pick the divisor. | |
| Every acknowledged frame counts, including full-size ones, so | |
| there is an estimate before the first drag starts. | |
| """ | |
| rate = wire_bytes / max(ack_ms - link.rtt_ms, 0.01) | |
| if self._bytes_per_ms is None: | |
| self._bytes_per_ms = rate | |
| else: | |
| self._bytes_per_ms = 0.7 * self._bytes_per_ms + 0.3 * rate | |
| if self.auto: | |
| # What is left of the target once the fixed costs are paid. | |
| budget_ms = max(self.target_ms - link.rtt_ms - render_ms, 1.0) | |
| self.divisor = choose_divisor( | |
| self.divisor, full_bytes, self._bytes_per_ms, budget_ms | |
| ) | |
| def _render(self, width: int, height: int) -> None: | |
| hidpi = self.GetContentScaleFactor() # 1 on X11, 2 on a Retina Mac | |
| # A local display gains nothing from a smaller image. | |
| divisor = self.divisor if self._low_res and link.remote else 1 | |
| render_w = max(1, round(width * hidpi) // divisor) | |
| render_h = max(1, round(height * hidpi) // divisor) | |
| n_points = lattice.count_within(self.r_limit) | |
| start = time.perf_counter() | |
| rgb = renderer.render( | |
| render_w, | |
| render_h, | |
| self.rot, | |
| self.zoom, | |
| self.style, | |
| self.point_size * render_w / width, | |
| n_points, | |
| self.slice_range, | |
| self.overlays, | |
| line_px=2 * render_w / width, | |
| ) | |
| elapsed_ms = (time.perf_counter() - start) * 1e3 | |
| self._bitmap = wx.Bitmap.FromBuffer(render_w, render_h, rgb) | |
| self._dirty = False | |
| n_shown = lattice.count_shown(n_points, self.slice_range) | |
| self._unreported = (render_w, render_h, divisor, elapsed_ms, n_shown) | |
| # -- input -------------------------------------------------------- | |
| # Positions come from the events; nothing here queries the server. | |
| def on_size(self, evt) -> None: | |
| self.changed() | |
| evt.Skip() | |
| def on_left_down(self, evt) -> None: | |
| self._drag_from = evt.GetPosition() | |
| self.CaptureMouse() | |
| def on_motion(self, evt) -> None: | |
| if self._drag_from is None or not evt.Dragging(): | |
| return | |
| pos = evt.GetPosition() | |
| dx = pos.x - self._drag_from.x | |
| dy = pos.y - self._drag_from.y | |
| self._drag_from = pos | |
| step = ROTATE_RAD_PER_PX / self.zoom | |
| self.rot = rotation_xy(dy * step, dx * step) @ self.rot | |
| self.invalidate(low_res=True) | |
| def on_left_up(self, _evt) -> None: | |
| self._end_drag() | |
| def on_capture_lost(self, _evt) -> None: | |
| self._drag_from = None | |
| self.invalidate(low_res=False) | |
| def _end_drag(self) -> None: | |
| if self._drag_from is None: | |
| return | |
| self._drag_from = None | |
| if self.HasCapture(): | |
| self.ReleaseMouse() | |
| self.invalidate(low_res=False) | |
| def on_wheel(self, evt) -> None: | |
| steps = evt.GetWheelRotation() / max(1, evt.GetWheelDelta()) | |
| self.zoom = float(np.clip(self.zoom * 1.1**steps, 0.2, 20.0)) | |
| self.changed() | |
| class MainFrame(wx.Frame): | |
| def __init__(self): | |
| super().__init__(None, title="Reciprocal lattice (remote X spike)") | |
| self.CreateStatusBar() | |
| panel = wx.Panel(self) | |
| self.view = LatticeView(panel, self.on_frame) | |
| self.style = wx.RadioBox( | |
| panel, label="Point style", choices=["Dot", "Cross"], | |
| majorDimension=1, style=wx.RA_SPECIFY_COLS, | |
| ) | |
| self.size_label = wx.StaticText(panel) | |
| self.size = wx.Slider(panel, value=self.view.point_size, minValue=1, maxValue=20) | |
| self.res_label = wx.StaticText(panel) | |
| # Tenths of a lattice unit; further right means higher resolution. | |
| self.res = wx.Slider( | |
| panel, value=int(lattice.rmax * 10), minValue=10, | |
| maxValue=int(lattice.rmax * 10), | |
| ) | |
| self.slice_on = wx.CheckBox(panel, label="Ewald sphere slice") | |
| self.slice_width_label = wx.StaticText(panel, label="Rotation angle (\u00b0)") | |
| self.slice_width = wx.SpinCtrlDouble( | |
| panel, min=0.1, max=360.0, initial=10.0, inc=1.0 | |
| ) | |
| self.slice_width.SetDigits(1) | |
| self.slice_offset_label = wx.StaticText(panel) | |
| # Tenths of a degree. | |
| self.slice_offset = wx.Slider(panel, value=0, minValue=0, maxValue=3599) | |
| self.show_axis = wx.CheckBox(panel, label="Show rotation axis (red)") | |
| self.show_beam = wx.CheckBox(panel, label="Show beam vector (green)") | |
| self.show_cell = wx.CheckBox(panel, label="Show unit cell (white)") | |
| self.divisor = wx.Choice( | |
| panel, | |
| choices=[f"auto (target {args.target_ms:g} ms)"] | |
| + ["full size (off)" if d == 1 else f"1/{d} size" for d in DIVISORS], | |
| ) | |
| # Without a way to wait for the display there is no lag to measure. | |
| self.view.auto = link.remote and link.can_wait | |
| self.divisor.SetSelection( | |
| 0 if self.view.auto else 1 + DIVISORS.index(self.view.divisor) | |
| ) | |
| self.divisor.Enable(link.remote) | |
| divisor_label = ( | |
| "While interacting, render at" if link.remote | |
| else "Local display: always full size" | |
| ) | |
| controls = wx.BoxSizer(wx.VERTICAL) | |
| controls.Add(self.style, 0, wx.EXPAND | wx.ALL, 8) | |
| controls.Add(self.size_label, 0, wx.LEFT | wx.RIGHT | wx.TOP, 8) | |
| controls.Add(self.size, 0, wx.EXPAND | wx.ALL, 8) | |
| controls.Add(self.res_label, 0, wx.LEFT | wx.RIGHT | wx.TOP, 8) | |
| controls.Add(self.res, 0, wx.EXPAND | wx.ALL, 8) | |
| controls.Add(self.slice_on, 0, wx.LEFT | wx.RIGHT | wx.TOP, 8) | |
| controls.Add(self.slice_width_label, 0, wx.LEFT | wx.RIGHT | wx.TOP, 8) | |
| controls.Add(self.slice_width, 0, wx.EXPAND | wx.ALL, 8) | |
| controls.Add(self.slice_offset_label, 0, wx.LEFT | wx.RIGHT | wx.TOP, 8) | |
| controls.Add(self.slice_offset, 0, wx.EXPAND | wx.ALL, 8) | |
| controls.Add(self.show_axis, 0, wx.LEFT | wx.RIGHT | wx.TOP, 8) | |
| controls.Add(self.show_beam, 0, wx.LEFT | wx.RIGHT | wx.TOP, 8) | |
| controls.Add(self.show_cell, 0, wx.ALL, 8) | |
| controls.Add(wx.StaticText(panel, label=divisor_label), | |
| 0, wx.LEFT | wx.RIGHT | wx.TOP, 8) | |
| controls.Add(self.divisor, 0, wx.EXPAND | wx.ALL, 8) | |
| controls.SetMinSize((230, -1)) | |
| layout = wx.BoxSizer(wx.HORIZONTAL) | |
| layout.Add(controls, 0, wx.EXPAND) | |
| layout.Add(self.view, 1, wx.EXPAND) | |
| panel.SetSizer(layout) | |
| self.style.Bind(wx.EVT_RADIOBOX, self.on_controls) | |
| self.size.Bind(wx.EVT_SLIDER, self.on_controls) | |
| self.res.Bind(wx.EVT_SLIDER, self.on_controls) | |
| self.slice_on.Bind(wx.EVT_CHECKBOX, self.on_controls) | |
| self.show_axis.Bind(wx.EVT_CHECKBOX, self.on_controls) | |
| self.show_beam.Bind(wx.EVT_CHECKBOX, self.on_controls) | |
| self.show_cell.Bind(wx.EVT_CHECKBOX, self.on_controls) | |
| self.slice_width.Bind(wx.EVT_SPINCTRLDOUBLE, self.on_controls) | |
| self.slice_offset.Bind(wx.EVT_SLIDER, self.on_controls) | |
| self.divisor.Bind(wx.EVT_CHOICE, self.on_controls) | |
| self.update_labels() | |
| self.SetClientSize((1030, 800)) | |
| def update_labels(self) -> None: | |
| r = self.res.GetValue() / 10 | |
| self.size_label.SetLabel(f"Point size: {self.size.GetValue()} px") | |
| start = self.slice_offset.GetValue() / 10 | |
| end = (start + self.slice_width.GetValue()) % 360 | |
| self.slice_offset_label.SetLabel( | |
| f"Offset: {start:.1f}\u00b0 (to {end:.1f}\u00b0)" | |
| ) | |
| slicing = self.slice_on.GetValue() | |
| for control in (self.slice_width_label, self.slice_width, | |
| self.slice_offset_label, self.slice_offset): | |
| control.Enable(slicing) | |
| self.res_label.SetLabel( | |
| f"Max resolution: {lattice.d_spacing(r):.2f} Å (|hkl| ≤ {r:.1f})" | |
| ) | |
| def on_controls(self, _evt) -> None: | |
| view = self.view | |
| view.style = self.style.GetSelection() | |
| view.point_size = self.size.GetValue() | |
| view.r_limit = self.res.GetValue() / 10 | |
| view.slice_range = ( | |
| (self.slice_offset.GetValue() / 10, self.slice_width.GetValue()) | |
| if self.slice_on.GetValue() else None | |
| ) | |
| view.overlays = tuple( | |
| name | |
| for name, box in ( | |
| ("axis", self.show_axis), | |
| ("beam", self.show_beam), | |
| ("cell", self.show_cell), | |
| ) | |
| if box.GetValue() | |
| ) | |
| choice = self.divisor.GetSelection() | |
| if choice == 0 and not link.can_wait: | |
| choice = 1 + DIVISORS.index(view.divisor) # cannot measure lag | |
| self.divisor.SetSelection(choice) | |
| view.auto = choice == 0 | |
| if not view.auto: | |
| view.divisor = DIVISORS[choice - 1] | |
| self.update_labels() | |
| view.changed() | |
| def on_frame(self, width, height, divisor, render_ms, n_points, ack_ms) -> None: | |
| parts = [f"render + read-back {render_ms:.1f} ms"] | |
| if not link.remote: | |
| scale = "full size - Local" | |
| else: | |
| scale = "full size" if divisor == 1 else f"1/{divisor} size" | |
| if self.view.auto and self.view._low_res: | |
| scale += ", auto" | |
| # 24-bit images travel as 4 bytes per pixel in the X protocol. | |
| wire_bytes = width * height * 4 | |
| parts.insert(0, f"~{wire_bytes / 1e3:,.0f} kB image") | |
| if ack_ms is not None: | |
| # The wait covers the transfer plus one round trip. | |
| transfer_ms = max(ack_ms - link.rtt_ms, 0.01) | |
| parts.append( | |
| f"lag {ack_ms:.0f} ms (~{wire_bytes / transfer_ms / 1e3:,.1f} MB/s)" | |
| ) | |
| parts.append(f"round trip {link.rtt_ms:.1f} ms") | |
| parts.append(f"{n_points:,} points") | |
| self.SetStatusText(f"{width} \u00d7 {height} ({scale}) " + " ".join(parts)) | |
| frame = MainFrame() | |
| frame.Show() | |
| app.MainLoop() | |
| def main() -> None: | |
| parser = argparse.ArgumentParser( | |
| description="Spike: a reciprocal lattice viewer that behaves well over remote X." | |
| ) | |
| parser.add_argument("--rmax", type=float, default=15.0, | |
| help="radius of the lattice sphere in units of 1/a (default 15)") | |
| parser.add_argument("--cell-a", type=float, default=30.0, | |
| help="cubic cell edge in Ångström (default 30, so rmax 15 is 2 Å)") | |
| parser.add_argument("--wavelength", type=float, default=1.0, | |
| help="beam wavelength in \u00c5ngstr\u00f6m, for the Ewald sphere (default 1)") | |
| parser.add_argument( | |
| "--gl-backend", | |
| default="egl" if sys.platform.startswith("linux") else "default", | |
| help="moderngl context backend. On Linux the default is 'egl', which needs " | |
| "no X server. Do not use 'default' over remote X: it asks the remote " | |
| "display for a GLX context.", | |
| ) | |
| parser.add_argument( | |
| "--link", choices=("auto", "local", "remote"), default="auto", | |
| help="override the local/remote detection", | |
| ) | |
| parser.add_argument( | |
| "--target-ms", type=float, default=100.0, metavar="MS", | |
| help="frame time the automatic reduction aims for while interacting (default 100)", | |
| ) | |
| parser.add_argument( | |
| "--sim-rtt-ms", type=float, metavar="MS", | |
| help="pretend the display is remote with this round-trip time, to try " | |
| "the remote behaviour on a local machine", | |
| ) | |
| parser.add_argument( | |
| "--sim-mbytes-per-s", type=float, default=2.0, metavar="MB", | |
| help="link speed used with --sim-rtt-ms (default 2)", | |
| ) | |
| parser.add_argument("--snapshot", metavar="FILE.ppm", | |
| help="render one frame to a PPM file and exit, without opening a window") | |
| args = parser.parse_args() | |
| lattice = Lattice(args.rmax, args.cell_a, args.wavelength) | |
| renderer = OffscreenRenderer(lattice, args.gl_backend) | |
| if args.snapshot: | |
| run_snapshot(renderer, lattice, args.snapshot) | |
| else: | |
| print(f"renderer: {renderer.describe()}") | |
| run_gui(renderer, lattice, args) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment