Build Packages / Create release (push) Successful in 24s
Build Packages / build:viewer:macos-arm64:nocuda (push) Successful in 3m29s
Build Packages / build:rugnux:macos-arm64:nocuda (push) Successful in 2m43s
Build Packages / build:rugnux:linux-aarch64:cuda (push) Successful in 8m27s
Build Packages / build:rugnux:linux-x86_64:cuda (push) Successful in 9m53s
Build Packages / build:viewer:linux-x86_64:nocuda (push) Successful in 9m58s
Build Packages / build:viewer:linux-x86_64:cuda (push) Successful in 11m22s
Build Packages / build:jfjoch:rocky8:nocuda (push) Successful in 13m39s
Build Packages / build:viewer:windows-x86_64:nocuda (push) Successful in 18m37s
Build Packages / build:jfjoch:rocky9:nocuda (push) Successful in 16m32s
Build Packages / build:viewer:windows-x86_64:cuda (push) Successful in 24m11s
Build Packages / HDF5 consumer tests (DIALS, XDS) (push) Successful in 25m30s
Build Packages / build:jfjoch:ubuntu2404:nocuda (push) Successful in 19m3s
Build Packages / build:jfjoch:ubuntu2204:nocuda (push) Successful in 20m23s
Build Packages / build:jfjoch:rocky8:cuda-sls9 (push) Successful in 19m41s
Build Packages / Generate python client (push) Successful in 50s
Build Packages / Build documentation (push) Successful in 1m16s
Build Packages / build:jfjoch:rocky9:cuda-sls9 (push) Successful in 21m0s
Build Packages / build:jfjoch:rocky8:cuda (push) Successful in 18m38s
Build Packages / build:rugnux:windows-x86_64:cuda (push) Successful in 14m33s
Build Packages / build:jfjoch:rocky9:cuda (push) Successful in 17m55s
Build Packages / build:jfjoch:ubuntu2204:cuda (push) Successful in 20m50s
Build Packages / build:jfjoch:ubuntu2404:cuda (push) Successful in 18m38s
Build Packages / Unit tests (push) Successful in 1h46m14s
* jfjoch_broker: Optional per-dataset authentication - statistics, images and plots can require a bearer token, which jfjoch_viewer supports. * jfjoch_viewer: Dark mode and a theme-matched colour scheme, a magnifier panel, and simpler contrast and background controls. * Rugnux: Multiple performance improvements on GPU and CPU (CPU-only processing up to 40% faster, faster image decoding on ARM), with unchanged results. * Rugnux: `--model` rigid-body refinement runs on the GPU, and the model-validation check is faster and more reliable. * Rugnux: Improved scaling and merging - error model, outlier rejection, absorption correction and French-Wilson amplitudes now agree more closely with XDS and ctruncate. * Rugnux: Improved integration - radial background on powder and ice rings, crowded rotation data keep their reflections, and CPU-only builds integrate large unit cells as GPU builds do. * Rugnux: More robust detector geometry - measured beam centre, X-ray bandwidth and goniometer rate, and geometry refinement accepted only on significant evidence. * Rugnux: Merged files are written in the standard setting, or in the setting of a reference MTZ, structure-factor mmCIF or model, with its free-R flags. * Rugnux: Richer report - ice and powder rings, further lattices, superstructure candidates and mosaicity, with warnings worded as prompts to check. * Rugnux: Clear error messages when a data set needs more GPU or host memory than is available. Reviewed-on: #83 Co-authored-by: Filip Leonarski <filip.leonarski@psi.ch>
286 lines
12 KiB
C++
286 lines
12 KiB
C++
// SPDX-FileCopyrightText: 2025 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
|
|
// SPDX-License-Identifier: GPL-3.0-only
|
|
|
|
#pragma once
|
|
|
|
#include <cmath>
|
|
#include <memory>
|
|
|
|
#include <QElapsedTimer>
|
|
#include <QTimer>
|
|
#include <QGraphicsView>
|
|
#include <QGraphicsItem>
|
|
#include <QImage>
|
|
#include <QMouseEvent>
|
|
#include <QPainterPath>
|
|
#include <QTransform>
|
|
#include <QPointF>
|
|
#include "../../common/ColorScale.h"
|
|
#include "../../common/JFJochMessages.h"
|
|
|
|
// Q_DECLARE_METATYPE(ROIMessage)
|
|
|
|
// Maps one pixel value to a colour. Shared by the generic float path and by subclasses that
|
|
// colour straight out of their own buffer, so the two cannot drift apart. Apply() takes a
|
|
// real value; the callers handle their own gap/bad/saturated encoding.
|
|
struct PixelColorMap {
|
|
const rgb *lut = nullptr;
|
|
int lut_size = 0;
|
|
float minv = 0.0f;
|
|
float range = 0.0f;
|
|
float inv_range = 0.0f;
|
|
float inv_range_log = 0.0f;
|
|
bool hdr = false;
|
|
rgb gap{}, bad{}, saturated{}, beam_stop{};
|
|
|
|
[[nodiscard]] rgb Apply(float v) const {
|
|
float f;
|
|
const float v_minv = v - minv;
|
|
|
|
if (hdr) {
|
|
if (v_minv <= 0.0f)
|
|
f = 0.0f;
|
|
else if (v_minv >= range)
|
|
f = static_cast<float>(lut_size);
|
|
else
|
|
f = std::log1p(v_minv) * inv_range_log;
|
|
} else
|
|
f = v_minv * inv_range;
|
|
|
|
if (f < 0.0f) f = 0.0f;
|
|
|
|
auto idx = static_cast<int>(f + 0.5f);
|
|
if (idx <= 0) idx = 0;
|
|
else if (idx >= lut_size) idx = lut_size - 1;
|
|
return lut[idx];
|
|
}
|
|
};
|
|
|
|
// Draws a rendered frame. A QGraphicsPixmapItem would mean converting the whole image into a
|
|
// QPixmap on every recolour, which costs one extra allocation and a full pass over the pixels.
|
|
// The frame is held by shared_ptr so that several views can show the same pixels.
|
|
class JFJochImageItem : public QGraphicsItem {
|
|
std::shared_ptr<const QImage> img_;
|
|
public:
|
|
explicit JFJochImageItem(std::shared_ptr<const QImage> img) : img_(std::move(img)) {}
|
|
QRectF boundingRect() const override;
|
|
QPainterPath opaqueArea() const override;
|
|
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
|
|
void refresh(); // the buffer behind the item changed
|
|
};
|
|
|
|
class JFJochImage : public QGraphicsView {
|
|
Q_OBJECT
|
|
|
|
bool m_adjustForegroundWithWheel = false;
|
|
bool m_adjustBackgroundWithWheel = false;
|
|
|
|
// Viewport-lock support: guard prevents the emit<->apply ping-pong between
|
|
// two linked views, and the helper broadcasts the current transform+center.
|
|
bool m_applyingViewport = false;
|
|
void emitViewportChanged();
|
|
|
|
void DrawROI();
|
|
virtual void addCustomOverlay();
|
|
void updateROI();
|
|
void drawPixelLabels(QPainter *painter, const QRectF &rect);
|
|
void wheelEvent(QWheelEvent* event) override;
|
|
void resizeEvent(QResizeEvent *event) override;
|
|
void contextMenuEvent(QContextMenuEvent *event) override;
|
|
|
|
void mousePressEvent(QMouseEvent *event) override;
|
|
void mouseMoveEvent(QMouseEvent *event) override;
|
|
void mouseReleaseEvent(QMouseEvent *event) override;
|
|
|
|
protected:
|
|
// Only the view that owns detector counts offers a region of interest; for the others a
|
|
// shift-drag would draw a box that means nothing.
|
|
[[nodiscard]] virtual bool AllowROI() const { return false; }
|
|
|
|
bool show_saturation = false;
|
|
// Beam-stop shadow drawn in its own colour; off shows it as an ordinary masked pixel.
|
|
bool show_beam_stop = true;
|
|
|
|
bool auto_bg = false;
|
|
bool auto_fg = false;
|
|
bool hdr_mode = false;
|
|
|
|
double scale_factor = 1.0;
|
|
|
|
size_t W = 0, H = 0;
|
|
size_t prev_W = 0, prev_H = 0;
|
|
|
|
// Height of one pixel as it is drawn, in units of its width. 1.0 for a detector image, where
|
|
// pixels are square; a grid scan whose x and y steps differ sets it so that a cell is drawn
|
|
// in the proportion of the area it covers. Only the view transform is anisotropic - scene
|
|
// coordinates stay one unit per pixel everywhere.
|
|
qreal pixel_aspect_ = 1.0;
|
|
qreal prev_aspect_ = 1.0;
|
|
|
|
// Track initial fit state and last image size
|
|
bool initial_fit_done_ = false;
|
|
|
|
QColor feature_color = Qt::magenta;
|
|
|
|
// Decimal places for non-integer per-pixel value labels. Float images are
|
|
// unreadable with many decimals, so subclasses can lower this.
|
|
int label_decimals_ = 3;
|
|
|
|
float foreground = 10.0;
|
|
float background = 0.0;
|
|
ColorScale color_scale;
|
|
std::vector<float> image_fp;
|
|
// The rendered RGB frame. Reused across frames (no per-frame allocation) and held by
|
|
// shared_ptr so follower views can display the very same pixels - see JFJochFollowerImage.
|
|
// The pointer itself is stable for the lifetime of the widget; only its contents change.
|
|
std::shared_ptr<QImage> frame_ = std::make_shared<QImage>();
|
|
|
|
// Persistent image item — never destroyed/recreated on overlay update
|
|
JFJochImageItem *image_item_ = nullptr;
|
|
// Overlay items managed separately
|
|
QList<QGraphicsItem *> overlay_items_;
|
|
|
|
// Helper: add an overlay item to the scene and track it for selective removal
|
|
void addOverlayItem(QGraphicsItem *item);
|
|
|
|
enum class MouseEventType {None, Panning, DrawingROI, MovingROI, ResizingROI, EditingExternalROI};
|
|
MouseEventType mouse_event_type = MouseEventType::None;
|
|
|
|
// Hooks for editing a named, persistent ROI drawn by a subclass (the base only
|
|
// owns the mouse events; the subclass knows the loaded ROIs). roiEditPress returns
|
|
// true to claim the gesture for ROI editing.
|
|
virtual bool roiEditPress(const QPointF &scenePos) { return false; }
|
|
virtual void roiEditMove(const QPointF &scenePos) {}
|
|
virtual void roiEditRelease() {}
|
|
virtual void roiScratchDrawn() {} // a shift/ctrl-drag finished drawing a new box/circle
|
|
QPoint lastMousePos; // To track panning movement
|
|
|
|
// Resizing which edge/corner
|
|
enum class ResizeHandle { None, Left, Right, Top, Bottom, TopLeft, TopRight, BottomLeft, BottomRight, Inside };
|
|
ResizeHandle active_handle_ = ResizeHandle::None;
|
|
ResizeHandle hover_handle_ = ResizeHandle::None;
|
|
|
|
enum class RoiType {RoiBox, RoiCircle};
|
|
RoiType roi_type = RoiType::RoiBox;
|
|
QPointF roiStartPos;
|
|
QPointF roiEndPos;
|
|
QRectF roiBox;
|
|
|
|
// Text for the per-pixel value label at (x, y). The base reads image_fp, which is what the
|
|
// float-valued views hold; a view whose source is exact integers overrides this so the label
|
|
// is exact and no float copy of the image has to exist at all.
|
|
[[nodiscard]] virtual QString PixelLabel(int x, int y) const;
|
|
void drawForeground(QPainter *painter, const QRectF &rect) override;
|
|
|
|
static QPointF RoundPoint(const QPointF& p);
|
|
virtual void mouseHover(const QPointF &scenePos, Qt::KeyboardModifiers modifiers) = 0;
|
|
|
|
// Hover feedback (status bar, resolution readout, magnifier) used to be regenerated on every
|
|
// single mouse motion. Each regeneration dirties the window, and on a remote X session every
|
|
// repaint costs a full-window pixel upload, so the thing to minimise is the number of
|
|
// repaints. ~15 Hz is far below the motion event rate and well above what the eye follows.
|
|
//
|
|
// The rate limit is applied inline rather than from a timer on purpose: running the update
|
|
// inside the mouse event keeps its damage in the same repaint as anything else that event
|
|
// triggers (a pan), instead of costing a second one. The timer only covers the tail, so the
|
|
// final position is still reported once the pointer stops.
|
|
static constexpr int kHoverIntervalMs = 66;
|
|
void ScheduleHoverUpdate(const QPointF &scenePos, Qt::KeyboardModifiers modifiers);
|
|
void UpdateHover();
|
|
void leaveEvent(QEvent *event) override;
|
|
QPointF hover_scene_pos_;
|
|
Qt::KeyboardModifiers hover_modifiers_ = Qt::NoModifier;
|
|
QElapsedTimer hover_rate_;
|
|
QTimer *hover_tail_timer_ = nullptr;
|
|
|
|
// Panning and wheel zooming repaint once per input event, which is fine locally and hopeless
|
|
// on a remote display (see ScheduleHoverUpdate above - same reasoning, same cadence, same
|
|
// inline-plus-tail shape). On a remote session the skipped events only accumulate - a pan its
|
|
// pixel delta, a zoom its wheel steps - and the accumulated gesture is applied whole, so the
|
|
// view ends exactly where the same gesture would have put it unthrottled. Locally every event
|
|
// is still applied inline and nothing changes.
|
|
void ApplyPendingPan();
|
|
QPoint pending_pan_;
|
|
QElapsedTimer pan_rate_;
|
|
QTimer *pan_tail_timer_ = nullptr;
|
|
|
|
void ApplyPendingZoom();
|
|
int pending_zoom_steps_ = 0;
|
|
QPoint zoom_anchor_vp_;
|
|
QElapsedTimer zoom_rate_;
|
|
QTimer *zoom_tail_timer_ = nullptr;
|
|
|
|
ResizeHandle hitTestROIHandle(const QPointF& scenePos, qreal tol = 3.0) const;
|
|
|
|
void updateOverlay();
|
|
void RenderImage();
|
|
PixelColorMap MakeColorMap() const;
|
|
// Colour one row into `out`. Called from worker threads, so it must stay const. The base
|
|
// maps image_fp; a subclass whose source is already a compact buffer can map that directly
|
|
// and skip materialising the float image.
|
|
virtual void ColorRow(size_t y, const PixelColorMap &map, QRgb *out) const;
|
|
// Re-render once the event queue drains. The foreground slider and the wheel emit far
|
|
// faster than a large image can be recoloured, so intermediate values are dropped
|
|
// instead of queueing a full recolour per event. On a remote display the drain still
|
|
// repaints once per event, so there the recolour is additionally held to the hover cadence.
|
|
void ScheduleRenderImage();
|
|
bool render_pending_ = false;
|
|
QElapsedTimer render_rate_;
|
|
QTimer *render_tail_timer_ = nullptr;
|
|
bool image_dirty_ = false; // frame_ changed since the item was last refreshed
|
|
void ClearFrame(); // drop the pixels and tell followers
|
|
// Set while a pan/zoom moves the scrollbars, so onScroll() does not rebuild the overlay
|
|
// once per scrollbar; the gesture rebuilds it once itself.
|
|
bool suppress_overlay_update_ = false;
|
|
void Redraw();
|
|
|
|
// Invalidate image_item_ and overlay tracking after scene()->clear()
|
|
void resetScenePointers();
|
|
|
|
// Perform initial fit-to-view (shorter direction), once per image size
|
|
void fitToViewShorterSideOnce();
|
|
|
|
// Render the current frame to an image at native resolution, optionally including the overlay
|
|
// (spots, predictions, rings, ROIs). Used by both the clipboard and save-to-file actions.
|
|
QImage renderToImage(bool with_overlay);
|
|
void copyImageToClipboard();
|
|
void copyImageWithOverlayToClipboard();
|
|
void saveImageToFile(bool with_overlay);
|
|
void clearROIInternal();
|
|
signals:
|
|
void autoForegroundChanged(bool input);
|
|
void foregroundChanged(float v);
|
|
void backgroundChanged(float v);
|
|
void writeStatusBar(QString string, int timeout_ms = 0);
|
|
void roiBoxUpdated(QRect box);
|
|
void roiCircleUpdated(double x, double y, double radius);
|
|
void viewportChanged(QTransform transform, QPointF center);
|
|
// A new frame has been rendered into Frame(). Follower views repaint on this.
|
|
void frameRendered();
|
|
// Asks for a move through the dataset (e.g. Home/End/PageUp/PageDown in a subclass'
|
|
// keyPressEvent): the navigation toolbar applies the step, clamped to the dataset's range.
|
|
void stepImage(int steps);
|
|
private slots:
|
|
void onScroll(int value);
|
|
public slots:
|
|
void setFeatureColor(QColor input);
|
|
void setColorMap(int color_map);
|
|
virtual void changeForeground(float val);
|
|
void changeBackground(float val);
|
|
|
|
void SetROIBox(QRect box);
|
|
void SetROICircle(double x, double y, double radius);
|
|
|
|
void centerOnSpot(QPointF point);
|
|
void applyViewport(QTransform transform, QPointF center);
|
|
void fitToView();
|
|
|
|
void adjustForeground(bool input);
|
|
void adjustBackground(bool input);
|
|
void setZoom(double input);
|
|
public:
|
|
explicit JFJochImage(QWidget *parent = nullptr);
|
|
double GetScaleFactor() const;
|
|
// The rendered frame, for views that want to show the same pixels without redoing the work
|
|
[[nodiscard]] std::shared_ptr<const QImage> Frame() const { return frame_; }
|
|
}; |