From fb35fa4658ea074e9c4a343919724edcc2b6a98a Mon Sep 17 00:00:00 2001 From: Alexandre Quessy Date: Fri, 4 Dec 2026 00:26:43 -0500 Subject: [PATCH 1/6] Add a scan with structured light, tested on computed scenes The first part of the automatic mapping with a camera: the projector shows white, black, then black and white stripes of a Gray code, each followed by its inverse; a camera films them, and MapMap finds, for each point of the camera, the point of the output that lights it. From it comes the scene seen from the projector, with the points the camera did not see left transparent. The scan runs with the event loop. After each change of the projection, the first images of the camera are thrown away, as a webcam often sends images filmed before, then the scan waits for two images in a row that hardly differ. It fails when the camera sends nothing steady, or does not see the projection. SyntheticScene computes what a camera would film of flat faces on a table, with noise and the light of a room, so that the tests need no camera and no projector: more than 99 % of the lit points are read, less than half a pixel away. --- mapmap.pro | 1 + src/automap/AutoMapFrameSource.cpp | 130 +++++++++++ src/automap/AutoMapFrameSource.h | 134 +++++++++++ src/automap/AutoMapScan.cpp | 274 ++++++++++++++++++++++ src/automap/AutoMapScan.h | 171 ++++++++++++++ src/automap/Correspondence.cpp | 209 +++++++++++++++++ src/automap/Correspondence.h | 104 +++++++++ src/automap/GrayCodeDecoder.cpp | 148 ++++++++++++ src/automap/GrayCodeDecoder.h | 124 ++++++++++ src/automap/GrayCodePattern.cpp | 147 ++++++++++++ src/automap/GrayCodePattern.h | 124 ++++++++++ src/automap/SyntheticScene.cpp | 259 +++++++++++++++++++++ src/automap/SyntheticScene.h | 134 +++++++++++ src/automap/automap.pri | 18 ++ src/src.pri | 1 + tests/TestAutoMap.cpp | 350 +++++++++++++++++++++++++++++ tests/TestAutoMap.h | 44 ++++ tests/main.cpp | 5 + tests/tests.pro | 15 +- 19 files changed, 2389 insertions(+), 3 deletions(-) create mode 100644 src/automap/AutoMapFrameSource.cpp create mode 100644 src/automap/AutoMapFrameSource.h create mode 100644 src/automap/AutoMapScan.cpp create mode 100644 src/automap/AutoMapScan.h create mode 100644 src/automap/Correspondence.cpp create mode 100644 src/automap/Correspondence.h create mode 100644 src/automap/GrayCodeDecoder.cpp create mode 100644 src/automap/GrayCodeDecoder.h create mode 100644 src/automap/GrayCodePattern.cpp create mode 100644 src/automap/GrayCodePattern.h create mode 100644 src/automap/SyntheticScene.cpp create mode 100644 src/automap/SyntheticScene.h create mode 100644 src/automap/automap.pri create mode 100644 tests/TestAutoMap.cpp create mode 100644 tests/TestAutoMap.h diff --git a/mapmap.pro b/mapmap.pro index 13ee9423..28047514 100644 --- a/mapmap.pro +++ b/mapmap.pro @@ -21,6 +21,7 @@ DEFINES += MAPMAP_VERSION_STRING=\\\"$$MAPMAP_VERSION\\\" include(src/core/core.pri) include(src/shape/shape.pri) +include(src/automap/automap.pri) include(src/gui/gui.pri) include(src/control/control.pri) include(src/app/app.pri) diff --git a/src/automap/AutoMapFrameSource.cpp b/src/automap/AutoMapFrameSource.cpp new file mode 100644 index 00000000..dd6b5f87 --- /dev/null +++ b/src/automap/AutoMapFrameSource.cpp @@ -0,0 +1,130 @@ +/* + * AutoMapFrameSource.cpp + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "AutoMapFrameSource.h" + +#include +#include +#include +#include +#include + +namespace mmp { + +CameraFrameSource::CameraFrameSource(const QCameraDevice& device, QObject* parent) + : AutoMapFrameSource(parent), + _device(device) +{ +} + +CameraFrameSource::~CameraFrameSource() +{ + stop(); +} + +bool CameraFrameSource::start(QString* error) +{ + if (_camera) + return true; + if (_device.isNull()) + { + if (error) + *error = tr("No camera is connected."); + return false; + } + + _camera = new QCamera(_device, this); + _session = new QMediaCaptureSession(this); + _sink = new QVideoSink(this); + _session->setCamera(_camera); + _session->setVideoSink(_sink); + connect(_sink, &QVideoSink::videoFrameChanged, this, &CameraFrameSource::_onFrame); + connect(_camera, &QCamera::errorOccurred, this, [](QCamera::Error, const QString& message) { + qWarning() << "Auto-mapping camera:" << message; + }); + _camera->start(); + return true; +} + +void CameraFrameSource::stop() +{ + if (_camera) + _camera->stop(); + delete _session; + delete _sink; + delete _camera; + _session = nullptr; + _sink = nullptr; + _camera = nullptr; +} + +void CameraFrameSource::_onFrame(const QVideoFrame& frame) +{ + if (!frame.isValid()) + return; + const QImage image = frame.toImage(); + if (!image.isNull()) + emit frameReady(image.convertToFormat(QImage::Format_RGB32)); +} + +SimulatedFrameSource::SimulatedFrameSource(const SyntheticScene& scene, int frameInterval, + int latencyFrames, QObject* parent) + : AutoMapFrameSource(parent), + _scene(scene), + _latencyFrames(qMax(0, latencyFrames)) +{ + _timer.setInterval(frameInterval); + connect(&_timer, &QTimer::timeout, this, &SimulatedFrameSource::_sendFrame); + _projected = QImage(scene.outputSize(), QImage::Format_Grayscale8); + _projected.fill(Qt::black); +} + +bool SimulatedFrameSource::start(QString* error) +{ + Q_UNUSED(error); + _pending.clear(); + _timer.start(); + return true; +} + +void SimulatedFrameSource::stop() +{ + _timer.stop(); + _pending.clear(); +} + +void SimulatedFrameSource::setProjectedImage(const QImage& image) +{ + if (image.isNull()) + { + _projected = QImage(_scene.outputSize(), QImage::Format_Grayscale8); + _projected.fill(Qt::black); + } + else + _projected = image; +} + +void SimulatedFrameSource::_sendFrame() +{ + _pending.enqueue(_scene.film(_projected, _frameNumber++)); + if (_pending.size() > _latencyFrames) + emit frameReady(_pending.dequeue()); +} + +} diff --git a/src/automap/AutoMapFrameSource.h b/src/automap/AutoMapFrameSource.h new file mode 100644 index 00000000..b360a53a --- /dev/null +++ b/src/automap/AutoMapFrameSource.h @@ -0,0 +1,134 @@ +/* + * AutoMapFrameSource.h + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef AUTO_MAP_FRAME_SOURCE_H_ +#define AUTO_MAP_FRAME_SOURCE_H_ + +#include "SyntheticScene.h" + +#include +#include +#include +#include +#include + +class QCamera; +class QMediaCaptureSession; +class QVideoFrame; +class QVideoSink; + +namespace mmp { + +/** + * What films the scene during a scan: a real camera, or a simulated one. + * + * It sends each image as it comes, in colour. Nothing is written to the disk. + */ +class AutoMapFrameSource : public QObject +{ + Q_OBJECT + +public: + explicit AutoMapFrameSource(QObject* parent = nullptr) : QObject(parent) {} + + /// Starts sending images. Returns false, with a message in @a error, when it cannot. + virtual bool start(QString* error) = 0; + + /// Stops sending images. + virtual void stop() = 0; + + /** + * Tells what the projector shows now. A real camera does not need it: it + * films the scene. A simulated camera computes what it would see. + */ + virtual void setProjectedImage(const QImage& image) { Q_UNUSED(image); } + +signals: + /// A new image of the camera. + void frameReady(const QImage& frame); +}; + +/// A real camera, opened with Qt Multimedia. +class CameraFrameSource : public AutoMapFrameSource +{ + Q_OBJECT + +public: + explicit CameraFrameSource(const QCameraDevice& device, QObject* parent = nullptr); + ~CameraFrameSource() override; + + bool start(QString* error) override; + void stop() override; + +private: + void _onFrame(const QVideoFrame& frame); + + QCameraDevice _device; + QCamera* _camera = nullptr; + QMediaCaptureSession* _session = nullptr; + QVideoSink* _sink = nullptr; +}; + +/** + * A simulated camera that films a SyntheticScene, to try the scan without a + * camera or a projector. + * + * Like many webcams, it sends its images late: what the projector shows + * appears only after a few images. + */ +class SimulatedFrameSource : public AutoMapFrameSource +{ + Q_OBJECT + +public: + /// How many images late a simulated camera is, by default. + static const int DEFAULT_LATENCY_FRAMES = 3; + + /// The time between two images of a simulated camera, by default: 30 images per second. + static const int DEFAULT_FRAME_INTERVAL_MS = 33; + + /** + * @param scene what the camera films. + * @param frameInterval the time between two images, in milliseconds. + * @param latencyFrames how many images late it is. + */ + SimulatedFrameSource(const SyntheticScene& scene, + int frameInterval = DEFAULT_FRAME_INTERVAL_MS, + int latencyFrames = DEFAULT_LATENCY_FRAMES, + QObject* parent = nullptr); + + bool start(QString* error) override; + void stop() override; + void setProjectedImage(const QImage& image) override; + +private: + void _sendFrame(); + + SyntheticScene _scene; + int _latencyFrames; + QTimer _timer; + QImage _projected; + // The images computed but not sent yet: the latency of the camera. + QQueue _pending; + int _frameNumber = 0; +}; + +} + +#endif /* AUTO_MAP_FRAME_SOURCE_H_ */ diff --git a/src/automap/AutoMapScan.cpp b/src/automap/AutoMapScan.cpp new file mode 100644 index 00000000..6ffa0e90 --- /dev/null +++ b/src/automap/AutoMapScan.cpp @@ -0,0 +1,274 @@ +/* + * AutoMapScan.cpp + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "AutoMapScan.h" + +#include +#include +#include +#include + +namespace mmp { + +namespace { + +// The width of the thumbnails compared to tell a steady image. +const int THUMBNAIL_WIDTH = 80; + +// The size of the number of the countdown, and of the text under it, as shares of the height of the output. +const qreal COUNTDOWN_NUMBER_HEIGHT = 0.45; +const qreal COUNTDOWN_TEXT_HEIGHT = 0.07; +// Where the text is, below the number, as a share of the height of the output. +const qreal COUNTDOWN_TEXT_TOP = 0.72; + +const int MILLISECONDS_PER_SECOND = 1000; + +} + +AutoMapScan::AutoMapScan(AutoMapFrameSource* source, Display display, const Options& options, QObject* parent) + : QObject(parent), + _source(source), + _display(std::move(display)), + _options(options), + _pattern(options.outputSize, options.skippedFineBits), + _decoder(_pattern) +{ + _countdownTimer.setInterval(_options.countdownStepMs); + connect(&_countdownTimer, &QTimer::timeout, this, &AutoMapScan::_countdownTick); + _patternTimer.setSingleShot(true); + connect(&_patternTimer, &QTimer::timeout, this, &AutoMapScan::_onPatternTimeout); +} + +AutoMapScan::~AutoMapScan() +{ + if (isRunning()) + _stop(); +} + +int AutoMapScan::holeFillPasses(int skippedFineBits) +{ + // A camera with fewer points than the output leaves holes of a pixel or + // two; with skipped bits, the points land on a grid of 2^skipped pixels. + return (1 << qMax(0, skippedFineBits)) + 1; +} + +QImage AutoMapScan::countdownImage(const QSize& size, int number) +{ + QImage image(size, QImage::Format_RGB32); + image.fill(Qt::black); + QPainter painter(&image); + painter.setRenderHint(QPainter::Antialiasing); + painter.setRenderHint(QPainter::TextAntialiasing); + painter.setPen(Qt::white); + + QFont font = painter.font(); + font.setBold(true); + font.setPixelSize(qMax(1, qRound(size.height() * COUNTDOWN_NUMBER_HEIGHT))); + painter.setFont(font); + painter.drawText(QRect(0, 0, size.width(), qRound(size.height() * COUNTDOWN_TEXT_TOP)), + Qt::AlignCenter, QString::number(number)); + + font.setBold(false); + font.setPixelSize(qMax(1, qRound(size.height() * COUNTDOWN_TEXT_HEIGHT))); + painter.setFont(font); + painter.drawText(QRect(0, qRound(size.height() * COUNTDOWN_TEXT_TOP), size.width(), + size.height() - qRound(size.height() * COUNTDOWN_TEXT_TOP)), + Qt::AlignHCenter | Qt::AlignTop, tr("Step out of the picture and do not move")); + return image; +} + +void AutoMapScan::start() +{ + if (isRunning()) + return; + + _decoder = GrayCodeDecoder(_pattern); + _correspondence = Correspondence(); + _projectorView = QImage(); + + if (!_options.imagesFolder.isEmpty() && !QDir().mkpath(_options.imagesFolder)) + qWarning() << "Auto-mapping: cannot create the folder" << _options.imagesFolder; + + QString error; + connect(_source, &AutoMapFrameSource::frameReady, this, &AutoMapScan::_onFrame, Qt::UniqueConnection); + if (!_source->start(&error)) + { + disconnect(_source, &AutoMapFrameSource::frameReady, this, &AutoMapScan::_onFrame); + emit failed(error); + return; + } + + _state = State::Countdown; + _countdownLeft = _options.countdownSeconds; + emit progressChanged(0, _totalSteps()); + if (_countdownLeft > 0) + { + const QImage image = countdownImage(_options.outputSize, _countdownLeft); + _display(image); + _source->setProjectedImage(image); + _countdownTimer.start(); + } + else + { + _state = State::Patterns; + _showPattern(0); + } +} + +void AutoMapScan::cancel() +{ + if (isRunning()) + _stop(); +} + +void AutoMapScan::_countdownTick() +{ + _countdownLeft--; + emit progressChanged(_options.countdownSeconds - _countdownLeft, _totalSteps()); + if (_countdownLeft > 0) + { + const QImage image = countdownImage(_options.outputSize, _countdownLeft); + _display(image); + _source->setProjectedImage(image); + return; + } + _countdownTimer.stop(); + _state = State::Patterns; + _showPattern(0); +} + +void AutoMapScan::_showPattern(int index) +{ + _patternIndex = index; + _framesSinceShown = 0; + _previousThumbnail = QImage(); + const QImage image = _pattern.image(index); + _display(image); + _source->setProjectedImage(image); + _patternTimer.start(_options.patternTimeoutMs); +} + +void AutoMapScan::_onFrame(const QImage& frame) +{ + if (_state != State::Patterns || frame.isNull()) + return; + + // The first images may have been filmed before the projection changed. + _framesSinceShown++; + if (_framesSinceShown <= _options.discardedFrames) + return; + + const QImage thumbnail = _thumbnail(frame); + if (!_previousThumbnail.isNull() && _meanDifference(thumbnail, _previousThumbnail) <= _options.steadyDifference) + { + _acceptFrame(frame); + return; + } + _previousThumbnail = thumbnail; +} + +void AutoMapScan::_acceptFrame(const QImage& frame) +{ + _patternTimer.stop(); + if (!_options.imagesFolder.isEmpty()) + { + const QString name = QStringLiteral("%1-%2.png").arg(_patternIndex, 2, 10, QLatin1Char('0')) + .arg(_pattern.step(_patternIndex).name()); + if (!frame.save(QDir(_options.imagesFolder).filePath(name))) + qWarning() << "Auto-mapping: cannot write" << name << "in" << _options.imagesFolder; + } + + if (!_decoder.addImage(_patternIndex, frame)) + { + _fail(tr("The camera changed the size of its images during the scan.")); + return; + } + + // Once white and black are read: does the camera see the projection at all? + if (_pattern.step(_patternIndex).kind == PatternStep::Black && _decoder.litShare() < MINIMUM_LIT_SHARE) + { + _fail(tr("The camera does not see the projection. Point it at what the projector lights, and darken the room.")); + return; + } + + emit progressChanged(_options.countdownSeconds + _patternIndex + 1, _totalSteps()); + if (_patternIndex + 1 < _pattern.stepCount()) + _showPattern(_patternIndex + 1); + else + _finish(); +} + +void AutoMapScan::_onPatternTimeout() +{ + if (_state != State::Patterns) + return; + if (_framesSinceShown == 0) + _fail(tr("The camera sends no images.")); + else + _fail(tr("The image of the camera did not settle within %1 seconds: something moves in the picture.") + .arg(_options.patternTimeoutMs / MILLISECONDS_PER_SECOND)); +} + +void AutoMapScan::_finish() +{ + _stop(); + _correspondence = _decoder.result(); + _projectorView = _correspondence.projectorView(_decoder.whiteImage(), holeFillPasses(_pattern.skippedFineBits())); + if (!_options.imagesFolder.isEmpty()) + _projectorView.save(QDir(_options.imagesFolder).filePath(QStringLiteral("projector-view.png"))); + emit finished(); +} + +void AutoMapScan::_fail(const QString& message) +{ + _stop(); + emit failed(message); +} + +void AutoMapScan::_stop() +{ + _state = State::Idle; + _countdownTimer.stop(); + _patternTimer.stop(); + disconnect(_source, &AutoMapFrameSource::frameReady, this, &AutoMapScan::_onFrame); + _source->setProjectedImage(QImage()); + _display(QImage()); +} + +QImage AutoMapScan::_thumbnail(const QImage& frame) +{ + return frame.scaledToWidth(THUMBNAIL_WIDTH, Qt::SmoothTransformation).convertToFormat(QImage::Format_Grayscale8); +} + +qreal AutoMapScan::_meanDifference(const QImage& a, const QImage& b) +{ + if (a.size() != b.size() || a.isNull()) + return std::numeric_limits::max(); + qint64 sum = 0; + for (int y = 0; y < a.height(); y++) + { + const uchar* lineA = a.constScanLine(y); + const uchar* lineB = b.constScanLine(y); + for (int x = 0; x < a.width(); x++) + sum += qAbs(int(lineA[x]) - int(lineB[x])); + } + return qreal(sum) / (qreal(a.width()) * a.height()); +} + +} diff --git a/src/automap/AutoMapScan.h b/src/automap/AutoMapScan.h new file mode 100644 index 00000000..b5ddfa65 --- /dev/null +++ b/src/automap/AutoMapScan.h @@ -0,0 +1,171 @@ +/* + * AutoMapScan.h + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef AUTO_MAP_SCAN_H_ +#define AUTO_MAP_SCAN_H_ + +#include "AutoMapFrameSource.h" +#include "Correspondence.h" +#include "GrayCodeDecoder.h" +#include "GrayCodePattern.h" + +#include +#include +#include +#include + +namespace mmp { + +/** + * The scan of the scene with structured light, from the countdown to the + * image of the scene seen from the projector. + * + * It runs with the event loop, without ever blocking the interface: + * + * 1. A countdown is projected, one number per second, so that everyone steps + * out of the field of the camera. + * 2. Each image of the GrayCodePattern is projected in turn. The first + * images that the camera sends afterwards are thrown away: a webcam often + * sends images that it filmed before. Then the scan waits for two images + * in a row that hardly differ, and keeps the second. + * 3. Once every image was read, it computes the Correspondence and the + * image of the scene seen from the projector. + * + * It fails when the camera sends no steady image in time, or when it does not + * see the projection at all. + */ +class AutoMapScan : public QObject +{ + Q_OBJECT + +public: + /// Shows an image over the whole output; a null image stops showing it. + using Display = std::function; + + /// How the scan is made. + struct Options { + /// The size of the output, in pixels. + QSize outputSize; + /// How many of the finest series of stripes to skip (see GrayCodePattern). + int skippedFineBits = 0; + /// How many numbers the countdown shows, one per second. + int countdownSeconds = DEFAULT_COUNTDOWN_SECONDS; + /// How long each number of the countdown stays, in milliseconds. + int countdownStepMs = COUNTDOWN_STEP_MS; + /// How many images of the camera are thrown away after each change of the projection. + int discardedFrames = DEFAULT_DISCARDED_FRAMES; + /// How long to wait for a steady image of each projection, in milliseconds. + int patternTimeoutMs = DEFAULT_PATTERN_TIMEOUT_MS; + /// The largest mean difference between two images in a row that are steady, in levels from 0 to 255. + qreal steadyDifference = DEFAULT_STEADY_DIFFERENCE; + /// When not empty, the images kept are written there: only when asked for. + QString imagesFolder; + }; + + static const int DEFAULT_COUNTDOWN_SECONDS = 3; + static const int COUNTDOWN_STEP_MS = 1000; + static const int DEFAULT_DISCARDED_FRAMES = 4; + static const int DEFAULT_PATTERN_TIMEOUT_MS = 3000; + static constexpr qreal DEFAULT_STEADY_DIFFERENCE = 3.0; + + /// Below this share of points of the camera lit by the projector, the camera does not see the projection. + static constexpr qreal MINIMUM_LIT_SHARE = 0.01; + + /** + * @param source what films the scene; the scan starts and stops it. + * @param display what shows an image over the whole output. + */ + AutoMapScan(AutoMapFrameSource* source, Display display, const Options& options, QObject* parent = nullptr); + ~AutoMapScan() override; + + /// Returns the number of images projected after the countdown. + int patternCount() const { return _pattern.stepCount(); } + + /// Returns true while the scan runs. + bool isRunning() const { return _state != State::Idle; } + + /// Starts the scan. Does nothing while it runs. + void start(); + + /// Stops the scan, without result. + void cancel(); + + /// Returns what was read, once finished() was sent. + const Correspondence& correspondence() const { return _correspondence; } + + /** + * Returns the scene seen from the projector, once finished() was sent: an + * image of the size of the output, transparent where nothing was read. + */ + QImage projectorView() const { return _projectorView; } + + /// Returns how many times holes are filled in the image of the scene, for a number of skipped bits. + static int holeFillPasses(int skippedFineBits); + + /// Returns the image of a number of the countdown, of the size @a size. + static QImage countdownImage(const QSize& size, int number); + +signals: + /// The scan moved on: @a done images projected out of @a total, countdown included. + void progressChanged(int done, int total); + + /// The scan ended, with a result. + void finished(); + + /// The scan stopped, for the reason given, already translated. + void failed(const QString& message); + +private: + enum class State { Idle, Countdown, Patterns }; + + void _countdownTick(); + void _showPattern(int index); + void _onFrame(const QImage& frame); + void _acceptFrame(const QImage& frame); + void _onPatternTimeout(); + void _finish(); + void _fail(const QString& message); + void _stop(); + int _totalSteps() const { return _options.countdownSeconds + _pattern.stepCount(); } + + // A small image in shades of gray, to compare two images of the camera quickly. + static QImage _thumbnail(const QImage& frame); + static qreal _meanDifference(const QImage& a, const QImage& b); + + AutoMapFrameSource* _source; + Display _display; + Options _options; + GrayCodePattern _pattern; + GrayCodeDecoder _decoder; + + State _state = State::Idle; + int _countdownLeft = 0; + int _patternIndex = 0; + int _framesSinceShown = 0; + QImage _previousThumbnail; + QTimer _countdownTimer; + QTimer _patternTimer; + + Correspondence _correspondence; + QImage _projectorView; +}; + +} + +#endif /* AUTO_MAP_SCAN_H_ */ diff --git a/src/automap/Correspondence.cpp b/src/automap/Correspondence.cpp new file mode 100644 index 00000000..aa498f96 --- /dev/null +++ b/src/automap/Correspondence.cpp @@ -0,0 +1,209 @@ +/* + * Correspondence.cpp + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "Correspondence.h" + +#include + +namespace mmp { + +namespace { + +// The x of a point of the camera that is not read. +const qreal NOT_READ = -1; + +// A hole is filled when at least this many of its eight neighbours are read: +// one or two would make the edges of what was read grow outwards. +const int MINIMUM_NEIGHBOURS_TO_FILL = 3; + +// The alpha of a pixel that was read, and of one that was not. +const int OPAQUE = 255; +const int TRANSPARENT = 0; + +} + +Correspondence::Correspondence(const QSize& cameraSize, const QSize& outputSize) + : _cameraSize(cameraSize), + _outputSize(outputSize), + _points(cameraSize.width() * cameraSize.height(), QPointF(NOT_READ, NOT_READ)) +{ +} + +void Correspondence::set(int x, int y, const QPointF& outputPoint) +{ + if (x < 0 || y < 0 || x >= _cameraSize.width() || y >= _cameraSize.height()) + return; + _points[_index(x, y)] = outputPoint; +} + +bool Correspondence::isRead(int x, int y) const +{ + if (x < 0 || y < 0 || x >= _cameraSize.width() || y >= _cameraSize.height()) + return false; + return _points.at(_index(x, y)).x() >= 0; +} + +QPointF Correspondence::outputPoint(int x, int y) const +{ + return isRead(x, y) ? _points.at(_index(x, y)) : QPointF(NOT_READ, NOT_READ); +} + +int Correspondence::readCount() const +{ + int count = 0; + for (const QPointF& point : _points) + if (point.x() >= 0) + count++; + return count; +} + +QImage Correspondence::projectorView(const QImage& cameraImage, int holeFillPasses) const +{ + QImage result(_outputSize, QImage::Format_ARGB32); + result.fill(Qt::transparent); + if (isEmpty() || cameraImage.size() != _cameraSize || _outputSize.isEmpty()) + return result; + + const QImage camera = cameraImage.convertToFormat(QImage::Format_RGB32); + const int width = _outputSize.width(); + const int height = _outputSize.height(); + const int pixelCount = width * height; + + // Add up the colours that land on each pixel of the output. + QVector red(pixelCount, 0), green(pixelCount, 0), blue(pixelCount, 0), count(pixelCount, 0); + for (int y = 0; y < _cameraSize.height(); y++) + { + const QRgb* line = reinterpret_cast(camera.constScanLine(y)); + for (int x = 0; x < _cameraSize.width(); x++) + { + const QPointF& point = _points.at(_index(x, y)); + if (point.x() < 0) + continue; + const int u = qFloor(point.x()); + const int v = qFloor(point.y()); + if (u < 0 || v < 0 || u >= width || v >= height) + continue; + const int i = v * width + u; + red[i] += qRed(line[x]); + green[i] += qGreen(line[x]); + blue[i] += qBlue(line[x]); + count[i]++; + } + } + + // Each pixel takes the mean of what landed on it. + QVector colors(pixelCount, 0); + QVector read(pixelCount, false); + for (int i = 0; i < pixelCount; i++) + { + if (count.at(i) == 0) + continue; + colors[i] = qRgb(red.at(i) / count.at(i), green.at(i) / count.at(i), blue.at(i) / count.at(i)); + read[i] = true; + } + + // Fill the small holes from their neighbours, from what was read before each pass only. + for (int pass = 0; pass < holeFillPasses; pass++) + { + QVector nextRead = read; + QVector nextColors = colors; + bool changed = false; + for (int v = 0; v < height; v++) + { + for (int u = 0; u < width; u++) + { + const int i = v * width + u; + if (read.at(i)) + continue; + int r = 0, g = 0, b = 0, n = 0; + for (int dv = -1; dv <= 1; dv++) + { + for (int du = -1; du <= 1; du++) + { + const int nu = u + du; + const int nv = v + dv; + if ((du == 0 && dv == 0) || nu < 0 || nv < 0 || nu >= width || nv >= height) + continue; + const int j = nv * width + nu; + if (!read.at(j)) + continue; + r += qRed(colors.at(j)); + g += qGreen(colors.at(j)); + b += qBlue(colors.at(j)); + n++; + } + } + if (n < MINIMUM_NEIGHBOURS_TO_FILL) + continue; + nextColors[i] = qRgb(r / n, g / n, b / n); + nextRead[i] = true; + changed = true; + } + } + read = nextRead; + colors = nextColors; + if (!changed) + break; + } + + for (int v = 0; v < height; v++) + { + QRgb* line = reinterpret_cast(result.scanLine(v)); + for (int u = 0; u < width; u++) + { + const int i = v * width + u; + if (read.at(i)) + line[u] = (colors.at(i) & RGB_MASK) | (uint(OPAQUE) << 24); + } + } + return result; +} + +qreal Correspondence::readShare(const QImage& projectorView) +{ + if (projectorView.isNull()) + return 0; + const QImage image = projectorView.convertToFormat(QImage::Format_ARGB32); + qint64 read = 0; + for (int y = 0; y < image.height(); y++) + { + const QRgb* line = reinterpret_cast(image.constScanLine(y)); + for (int x = 0; x < image.width(); x++) + if (qAlpha(line[x]) != TRANSPARENT) + read++; + } + return qreal(read) / (qreal(image.width()) * image.height()); +} + +QImage Correspondence::withCoverage(const QImage& projectorView, const QColor& unreadColor) +{ + QImage result = projectorView.convertToFormat(QImage::Format_ARGB32); + // Unpremultiplied ARGB: the colour and its alpha are written as they are. + const QRgb unread = unreadColor.rgba(); + for (int y = 0; y < result.height(); y++) + { + QRgb* line = reinterpret_cast(result.scanLine(y)); + for (int x = 0; x < result.width(); x++) + if (qAlpha(line[x]) == TRANSPARENT) + line[x] = unread; + } + return result; +} + +} diff --git a/src/automap/Correspondence.h b/src/automap/Correspondence.h new file mode 100644 index 00000000..5e497939 --- /dev/null +++ b/src/automap/Correspondence.h @@ -0,0 +1,104 @@ +/* + * Correspondence.h + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef CORRESPONDENCE_H_ +#define CORRESPONDENCE_H_ + +#include +#include +#include +#include +#include + +namespace mmp { + +/** + * What a scan with structured light found: for each point of the camera, the + * point of the output that lights it, or nothing. + * + * Points of the output are in pixels of the output, as the shapes of the + * output editor: (0, 0) is the top left corner of the output, and the middle + * of its first pixel is (0.5, 0.5). + */ +class Correspondence +{ +public: + /// An empty correspondence: nothing was read. + Correspondence() = default; + + /// A correspondence of the given sizes, where nothing is read yet. + Correspondence(const QSize& cameraSize, const QSize& outputSize); + + /// Returns the size of the images of the camera. + QSize cameraSize() const { return _cameraSize; } + + /// Returns the size of the output. + QSize outputSize() const { return _outputSize; } + + /// Returns true when nothing can be read in it. + bool isEmpty() const { return _points.isEmpty(); } + + /// Records that point (x, y) of the camera is lit by @a outputPoint. + void set(int x, int y, const QPointF& outputPoint); + + /// Returns true when the output point that lights point (x, y) of the camera is known. + bool isRead(int x, int y) const; + + /// Returns the output point that lights point (x, y) of the camera, if isRead(). + QPointF outputPoint(int x, int y) const; + + /// Returns how many points of the camera are read. + int readCount() const; + + /** + * Returns the scene seen from the projector: for each pixel of the output, + * the colour the camera saw there. + * + * Each point of the camera that was read gives its colour to the pixel of + * the output that lights it. A camera usually has fewer points than the part + * of the output it sees: small holes are left, which are filled from their + * neighbours, @a holeFillPasses times. + * + * @param cameraImage an image of the camera, of cameraSize(): usually the scene under white light. + * @param holeFillPasses how many times to fill the holes from their neighbours. + * @return an image of outputSize(), transparent where nothing was read. + */ + QImage projectorView(const QImage& cameraImage, int holeFillPasses) const; + + /// Returns the share of the pixels of @a projectorView that were read (not transparent), from 0 to 1. + static qreal readShare(const QImage& projectorView); + + /** + * Returns @a projectorView with the pixels that were not read painted with + * @a unreadColor: where the camera did not see the projection. + */ + static QImage withCoverage(const QImage& projectorView, const QColor& unreadColor); + +private: + int _index(int x, int y) const { return y * _cameraSize.width() + x; } + + QSize _cameraSize; + QSize _outputSize; + // One point per point of the camera; x is negative when it is not read. + QVector _points; +}; + +} + +#endif /* CORRESPONDENCE_H_ */ diff --git a/src/automap/GrayCodeDecoder.cpp b/src/automap/GrayCodeDecoder.cpp new file mode 100644 index 00000000..d81bd062 --- /dev/null +++ b/src/automap/GrayCodeDecoder.cpp @@ -0,0 +1,148 @@ +/* + * GrayCodeDecoder.cpp + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "GrayCodeDecoder.h" + +#include + +namespace mmp { + +namespace { + +// The middle of a pixel, or of a group of pixels, from its first edge. +const qreal HALF = 0.5; + +} + +GrayCodeDecoder::GrayCodeDecoder(const GrayCodePattern& pattern) + : _pattern(pattern) +{ +} + +QVector GrayCodeDecoder::_grayLevels(const QImage& image) +{ + const QImage gray = image.convertToFormat(QImage::Format_Grayscale8); + QVector levels(gray.width() * gray.height()); + for (int y = 0; y < gray.height(); y++) + { + const uchar* line = gray.constScanLine(y); + std::copy(line, line + gray.width(), levels.begin() + y * gray.width()); + } + return levels; +} + +bool GrayCodeDecoder::addImage(int stepIndex, const QImage& image) +{ + if (stepIndex != _nextStep || isComplete() || image.isNull()) + return false; + if (stepIndex == 0) + _cameraSize = image.size(); + else if (image.size() != _cameraSize) + return false; + + const PatternStep step = _pattern.step(stepIndex); + const int pointCount = _cameraSize.width() * _cameraSize.height(); + switch (step.kind) + { + case PatternStep::White: + _whiteImage = image.convertToFormat(QImage::Format_RGB32); + _white = _grayLevels(image); + break; + + case PatternStep::Black: + { + const QVector black = _grayLevels(image); + _lit = QVector(pointCount, false); + for (int i = 0; i < pointCount; i++) + _lit[i] = int(_white.at(i)) - int(black.at(i)) >= _minimumLightContrast; + _columnCodes = QVector(pointCount, 0); + _rowCodes = QVector(pointCount, 0); + _undecided = QVector(pointCount, false); + break; + } + + case PatternStep::Stripes: + if (!step.inverted) + { + _stripes = _grayLevels(image); + break; + } + { + const QVector inverse = _grayLevels(image); + QVector& codes = (step.direction == StripeDirection::Columns) ? _columnCodes : _rowCodes; + const int shift = step.bit - _pattern.skippedFineBits(); + for (int i = 0; i < pointCount; i++) + { + if (!_lit.at(i)) + continue; + const int difference = int(_stripes.at(i)) - int(inverse.at(i)); + if (qAbs(difference) < _minimumBitContrast) + _undecided[i] = true; + else if (difference > 0) + codes[i] |= (1u << shift); + } + _stripes.clear(); + } + break; + } + + _nextStep++; + return true; +} + +qreal GrayCodeDecoder::litShare() const +{ + if (_lit.isEmpty()) + return 0; + int lit = 0; + for (bool isLit : _lit) + if (isLit) + lit++; + return qreal(lit) / _lit.size(); +} + +Correspondence GrayCodeDecoder::result() const +{ + if (!isComplete()) + return Correspondence(); + + const QSize outputSize = _pattern.outputSize(); + Correspondence result(_cameraSize, outputSize); + // With skipped bits, a code names a group of 2^skipped pixels: take its middle. + const qreal groupSize = qreal(1 << _pattern.skippedFineBits()); + for (int y = 0; y < _cameraSize.height(); y++) + { + for (int x = 0; x < _cameraSize.width(); x++) + { + const int i = y * _cameraSize.width() + x; + if (!_lit.at(i) || _undecided.at(i)) + continue; + const qreal u = (GrayCodePattern::fromGray(_columnCodes.at(i)) + HALF) * groupSize; + const qreal v = (GrayCodePattern::fromGray(_rowCodes.at(i)) + HALF) * groupSize; + // Codes past the edge of the output are never projected: noise. + if (u >= outputSize.width() + groupSize / 2 || v >= outputSize.height() + groupSize / 2) + continue; + result.set(x, y, QPointF(qMin(u, qreal(outputSize.width()) - HALF), + qMin(v, qreal(outputSize.height()) - HALF))); + } + } + return result; +} + +} diff --git a/src/automap/GrayCodeDecoder.h b/src/automap/GrayCodeDecoder.h new file mode 100644 index 00000000..44d92de3 --- /dev/null +++ b/src/automap/GrayCodeDecoder.h @@ -0,0 +1,124 @@ +/* + * GrayCodeDecoder.h + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef GRAY_CODE_DECODER_H_ +#define GRAY_CODE_DECODER_H_ + +#include "Correspondence.h" +#include "GrayCodePattern.h" + +#include +#include + +namespace mmp { + +/** + * Reads the images that a camera filmed during a scan, one by one, and finds + * for each point of the camera the point of the output that lights it. + * + * The images are given in the order of GrayCodePattern: white, black, then + * each series of stripes followed by its inverse. Only two images of the + * camera are kept at a time, besides the white one: the decoding is done as + * they come. + * + * A point of the camera is read when the white image is brighter than the + * black one by at least minimumLightContrast(): it is lit by the projector. + * Each bit is then read by comparing the stripes with their inverse, which + * makes the light of the room cancel out. A point on the edge of a stripe + * sees them nearly equal: it is still decided by the sign of the difference, + * since the Gray code then puts it on the neighbouring column, one pixel + * away. A point is only dropped when the difference is below + * minimumBitContrast(), which is 0 by default: never. + */ +class GrayCodeDecoder +{ +public: + /// The difference between white and black, in levels of gray from 0 to 255, below which a point is not lit. + static const int DEFAULT_MINIMUM_LIGHT_CONTRAST = 20; + + /// The difference between stripes and inverse, in levels of gray, below which a bit is undecided: never, by default. + static const int DEFAULT_MINIMUM_BIT_CONTRAST = 0; + + /// Prepares the decoding of a scan made with @a pattern. + explicit GrayCodeDecoder(const GrayCodePattern& pattern); + + /// Sets the difference between white and black below which a point is not lit. + void setMinimumLightContrast(int levels) { _minimumLightContrast = levels; } + + /// Returns the difference between white and black below which a point is not lit. + int minimumLightContrast() const { return _minimumLightContrast; } + + /// Sets the difference between stripes and inverse below which a bit is undecided, and the point not read. + void setMinimumBitContrast(int levels) { _minimumBitContrast = levels; } + + /// Returns the difference between stripes and inverse below which a bit is undecided. + int minimumBitContrast() const { return _minimumBitContrast; } + + /** + * Reads the image filmed while image number @a stepIndex of the pattern was projected. + * + * @return false when the image cannot be read: out of order, or not of the + * size of the first image. + */ + bool addImage(int stepIndex, const QImage& image); + + /// Returns the number of the next image expected. + int nextStep() const { return _nextStep; } + + /// Returns true when every image of the pattern was read. + bool isComplete() const { return _nextStep >= _pattern.stepCount(); } + + /// Returns the size of the images of the camera, once the first one was given. + QSize cameraSize() const { return _cameraSize; } + + /// Returns the image filmed under white light, in colour: the scene as the projector lights it. + QImage whiteImage() const { return _whiteImage; } + + /// Returns the share of the points of the camera lit by the projector, from 0 to 1, once the black image was read. + qreal litShare() const; + + /// Returns what was read, once isComplete(); an empty correspondence before. + Correspondence result() const; + +private: + // The level of gray of each point of an image. + static QVector _grayLevels(const QImage& image); + + GrayCodePattern _pattern; + int _minimumLightContrast = DEFAULT_MINIMUM_LIGHT_CONTRAST; + int _minimumBitContrast = DEFAULT_MINIMUM_BIT_CONTRAST; + + int _nextStep = 0; + QSize _cameraSize; + QImage _whiteImage; + QVector _white; + // Whether each point is lit by the projector, once the black image was read. + QVector _lit; + // The image of stripes waiting for its inverse. + QVector _stripes; + // The bits read so far, as a Gray code, for the columns and the rows. + QVector _columnCodes; + QVector _rowCodes; + // Whether a bit of each point was undecided. + QVector _undecided; +}; + +} + +#endif /* GRAY_CODE_DECODER_H_ */ diff --git a/src/automap/GrayCodePattern.cpp b/src/automap/GrayCodePattern.cpp new file mode 100644 index 00000000..ef540c50 --- /dev/null +++ b/src/automap/GrayCodePattern.cpp @@ -0,0 +1,147 @@ +/* + * GrayCodePattern.cpp + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "GrayCodePattern.h" + +#include +#include + +namespace mmp { + +namespace { + +// The first two images: white, then black. +const int REFERENCE_IMAGES = 2; + +// Each bit gives two images: the stripes and their inverse. +const int IMAGES_PER_BIT = 2; + +const uchar WHITE_LEVEL = 255; +const uchar BLACK_LEVEL = 0; + +} + +QString PatternStep::name() const +{ + switch (kind) + { + case White: return QStringLiteral("white"); + case Black: return QStringLiteral("black"); + case Stripes: break; + } + return QStringLiteral("%1-%2%3") + .arg(direction == StripeDirection::Columns ? QStringLiteral("columns") : QStringLiteral("rows")) + .arg(bit, 2, 10, QLatin1Char('0')) + .arg(inverted ? QStringLiteral("-inverse") : QString()); +} + +GrayCodePattern::GrayCodePattern(const QSize& outputSize, int skippedFineBits) + : _outputSize(outputSize.expandedTo(QSize(1, 1))), + _columnBits(bitsFor(_outputSize.width())), + _rowBits(bitsFor(_outputSize.height())) +{ + // At least one series of stripes in each direction. + _skippedFineBits = qBound(0, skippedFineBits, qMin(_columnBits, _rowBits) - 1); +} + +int GrayCodePattern::stepCount() const +{ + return REFERENCE_IMAGES + IMAGES_PER_BIT * (_usedColumnBits() + _usedRowBits()); +} + +PatternStep GrayCodePattern::step(int index) const +{ + PatternStep result; + if (index <= 0) + return result; + if (index == 1) + { + result.kind = PatternStep::Black; + return result; + } + + int stripeIndex = qMin(index, stepCount() - 1) - REFERENCE_IMAGES; + result.kind = PatternStep::Stripes; + result.inverted = (stripeIndex % IMAGES_PER_BIT) != 0; + int bitIndex = stripeIndex / IMAGES_PER_BIT; + if (bitIndex < _usedColumnBits()) + { + result.direction = StripeDirection::Columns; + result.bit = _columnBits - 1 - bitIndex; + } + else + { + bitIndex -= _usedColumnBits(); + result.direction = StripeDirection::Rows; + result.bit = _rowBits - 1 - bitIndex; + } + return result; +} + +QImage GrayCodePattern::image(int index) const +{ + QImage result(_outputSize, QImage::Format_Grayscale8); + const PatternStep what = step(index); + if (what.kind != PatternStep::Stripes) + { + result.fill(what.kind == PatternStep::White ? Qt::white : Qt::black); + return result; + } + + const uchar on = what.inverted ? BLACK_LEVEL : WHITE_LEVEL; + const uchar off = what.inverted ? WHITE_LEVEL : BLACK_LEVEL; + if (what.direction == StripeDirection::Columns) + { + // Every line is the same: compute the first one, then copy it. + uchar* first = result.scanLine(0); + for (int x = 0; x < _outputSize.width(); x++) + first[x] = isWhite(x, what.bit) ? on : off; + for (int y = 1; y < _outputSize.height(); y++) + std::memcpy(result.scanLine(y), first, size_t(_outputSize.width())); + } + else + { + for (int y = 0; y < _outputSize.height(); y++) + std::memset(result.scanLine(y), isWhite(y, what.bit) ? on : off, size_t(_outputSize.width())); + } + return result; +} + +int GrayCodePattern::bitsFor(int length) +{ + int bits = 1; + while ((1 << bits) < length) + bits++; + return bits; +} + +quint32 GrayCodePattern::toGray(quint32 value) +{ + return value ^ (value >> 1); +} + +quint32 GrayCodePattern::fromGray(quint32 gray) +{ + quint32 value = gray; + for (quint32 shift = gray >> 1; shift != 0; shift >>= 1) + value ^= shift; + return value; +} + +} diff --git a/src/automap/GrayCodePattern.h b/src/automap/GrayCodePattern.h new file mode 100644 index 00000000..74100693 --- /dev/null +++ b/src/automap/GrayCodePattern.h @@ -0,0 +1,124 @@ +/* + * GrayCodePattern.h + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef GRAY_CODE_PATTERN_H_ +#define GRAY_CODE_PATTERN_H_ + +#include +#include +#include + +namespace mmp { + +/// Whether a series of stripes tells the columns or the rows of the output apart. +enum class StripeDirection { + Columns, ///< Vertical stripes: they give the column of each point. + Rows ///< Horizontal stripes: they give the row of each point. +}; + +/// One image of the scan: what the projector shows. +struct PatternStep { + /// What the image is. + enum Kind { + White, ///< The whole output lit: the brightest each point gets. + Black, ///< The whole output dark: the light of the room alone. + Stripes ///< Black and white stripes, for one bit of the Gray code. + }; + + Kind kind = White; + StripeDirection direction = StripeDirection::Columns; ///< For Stripes only. + int bit = 0; ///< For Stripes only: the bit of the Gray code, 0 for the finest stripes. + bool inverted = false; ///< For Stripes only: black and white swapped. + + /// Returns a short name, in English, for file names and the log: "white", "columns-10-inverse"… + QString name() const; +}; + +/** + * The images projected during a scan with structured light. + * + * First a white image and a black one, then, for the columns and then for the + * rows, one image of stripes per bit of the Gray code of the coordinate, from + * the widest stripes to the finest, each one followed by its inverse. A point + * of the scene lit by column c is white in the stripes of bit b when bit b of + * the Gray code of c is 1. + * + * The Gray code is used rather than plain binary because two neighbouring + * columns differ by one bit only: a point on the edge of a stripe, read + * wrongly, lands on the neighbouring column, not far away. + * + * The finest stripes can be skipped: a webcam often sees them blurred. The + * position of a point is then only known to 2^skipped pixels. + */ +class GrayCodePattern +{ +public: + /** + * @param outputSize the size of the output, in pixels: the size of the images. + * @param skippedFineBits how many of the finest series of stripes to skip, in each direction. + */ + explicit GrayCodePattern(const QSize& outputSize, int skippedFineBits = 0); + + /// Returns the size of the output, which is also the size of the images. + QSize outputSize() const { return _outputSize; } + + /// Returns the number of bits of the Gray code of a column (all of them, skipped or not). + int columnBits() const { return _columnBits; } + + /// Returns the number of bits of the Gray code of a row (all of them, skipped or not). + int rowBits() const { return _rowBits; } + + /// Returns how many of the finest bits are skipped, in each direction. + int skippedFineBits() const { return _skippedFineBits; } + + /// Returns the number of images of the scan. + int stepCount() const; + + /// Returns what image number @a index shows (from 0). + PatternStep step(int index) const; + + /// Returns image number @a index, in shades of gray, of the size of the output. + QImage image(int index) const; + + /// Returns the number of bits needed to number @a length positions (at least 1). + static int bitsFor(int length); + + /// Returns the Gray code of @a value. + static quint32 toGray(quint32 value); + + /// Returns the value whose Gray code is @a gray. + static quint32 fromGray(quint32 gray); + + /// Returns true when the stripes of bit @a bit are white at @a coordinate. + static bool isWhite(int coordinate, int bit) { return (toGray(quint32(coordinate)) >> bit) & 1u; } + +private: + // The number of bits used in each direction: those not skipped. + int _usedColumnBits() const { return _columnBits - _skippedFineBits; } + int _usedRowBits() const { return _rowBits - _skippedFineBits; } + + QSize _outputSize; + int _columnBits; + int _rowBits; + int _skippedFineBits; +}; + +} + +#endif /* GRAY_CODE_PATTERN_H_ */ diff --git a/src/automap/SyntheticScene.cpp b/src/automap/SyntheticScene.cpp new file mode 100644 index 00000000..9fa65ceb --- /dev/null +++ b/src/automap/SyntheticScene.cpp @@ -0,0 +1,259 @@ +/* + * SyntheticScene.cpp + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "SyntheticScene.h" + +#include + +namespace mmp { + +namespace { + +// Each point of the camera is the mean of SAMPLES_PER_SIDE × SAMPLES_PER_SIDE samples. +const int SAMPLES_PER_SIDE = 2; + +// What a camera sees in a dark room, in levels from 0 to 255 for a white face. +const qreal DEFAULT_AMBIENT_LIGHT = 25; +const qreal DEFAULT_PROJECTOR_LIGHT = 200; +const qreal DEFAULT_NOISE = 2; +const quint32 DEFAULT_SEED = 1; + +// What surrounds the faces: a dark wall, out of the projection. +const qreal SURROUNDING_REFLECTANCE = 0.3; + +const qreal MAXIMUM_LEVEL = 255; + +// A sum of this many uniform draws, centred, is close to a normal draw. +const int UNIFORM_DRAWS_PER_NORMAL = 4; +// The standard deviation of that sum, for draws between -0.5 and 0.5. +const qreal SUM_STANDARD_DEVIATION = 0.57735; // sqrt(4 / 12) + +/// A small generator of pseudo-random numbers, the same on every system. +class Random +{ +public: + explicit Random(quint64 seed) : _state(seed ? seed : 1) {} + + /// Returns a number between -0.5 and 0.5. + qreal uniform() + { + // xorshift64* + _state ^= _state >> 12; + _state ^= _state << 25; + _state ^= _state >> 27; + const quint64 value = _state * 2685821657736338717ULL; + return qreal(value >> 11) / qreal(1ULL << 53) - 0.5; + } + + /// Returns a number drawn from a normal law of standard deviation 1, roughly. + qreal normal() + { + qreal sum = 0; + for (int i = 0; i < UNIFORM_DRAWS_PER_NORMAL; i++) + sum += uniform(); + return sum / SUM_STANDARD_DEVIATION; + } + +private: + quint64 _state; +}; + +// Points given as fractions of a size. +QPolygonF quad(const QSizeF& size, const QPointF& a, const QPointF& b, const QPointF& c, const QPointF& d) +{ + const auto scaled = [&size](const QPointF& p) { return QPointF(p.x() * size.width(), p.y() * size.height()); }; + return QPolygonF() << scaled(a) << scaled(b) << scaled(c) << scaled(d); +} + +} + +SyntheticScene::SyntheticScene(const QSize& cameraSize, const QSize& outputSize) + : _cameraSize(cameraSize), + _outputSize(outputSize), + _ambientLight(DEFAULT_AMBIENT_LIGHT), + _projectorLight(DEFAULT_PROJECTOR_LIGHT), + _noise(DEFAULT_NOISE), + _seed(DEFAULT_SEED) +{ +} + +void SyntheticScene::addFace(const Face& face) +{ + QTransform cameraToOutput; + if (!QTransform::quadToQuad(face.cameraQuad, face.outputQuad, cameraToOutput)) + return; + _faces.append(face); + _cameraToOutput.append(cameraToOutput); + _samples.clear(); +} + +SyntheticScene SyntheticScene::blocksOnTable(const QSize& cameraSize, const QSize& outputSize) +{ + SyntheticScene scene(cameraSize, outputSize); + const QSizeF camera(cameraSize); + const QSizeF output(outputSize); + + // The table receives the whole output; the camera, beside the projector, sees it as a trapezoid. + Face table; + table.outputQuad = quad(output, {0, 0}, {1, 0}, {1, 1}, {0, 1}); + table.cameraQuad = quad(camera, {0.18, 0.12}, {0.82, 0.12}, {0.95, 0.90}, {0.05, 0.90}); + table.color = QColor(210, 180, 140); + table.reflectance = 0.9; + scene.addFace(table); + + QTransform outputToTable; + QTransform::quadToQuad(table.outputQuad, table.cameraQuad, outputToTable); + + // A face raised above the table: the camera sees it higher than the part of the table it hides. + const auto raised = [&](const QPolygonF& outputQuad, qreal height, const QColor& color, qreal reflectance) { + Face face; + face.outputQuad = outputQuad; + face.cameraQuad = outputToTable.map(outputQuad).translated(0, -height * camera.height()); + face.color = color; + face.reflectance = reflectance; + return face; + }; + + // Block A: its top, then its front, between the bottom edge of its top and the table. + const QPolygonF topA = quad(output, {0.15, 0.25}, {0.35, 0.25}, {0.35, 0.45}, {0.15, 0.45}); + const Face faceTopA = raised(topA, 0.06, QColor(200, 120, 80), 0.8); + Face frontA; + frontA.outputQuad = quad(output, {0.15, 0.45}, {0.35, 0.45}, {0.35, 0.50}, {0.15, 0.50}); + frontA.cameraQuad = QPolygonF() << faceTopA.cameraQuad.at(3) << faceTopA.cameraQuad.at(2) + << outputToTable.map(frontA.outputQuad.at(2)) + << outputToTable.map(frontA.outputQuad.at(3)); + frontA.color = QColor(180, 100, 70); + frontA.reflectance = 0.7; + scene.addFace(frontA); + scene.addFace(faceTopA); + + // Block B, turned a little, and block C, lower. + scene.addFace(raised(quad(output, {0.55, 0.20}, {0.80, 0.22}, {0.78, 0.40}, {0.53, 0.38}), + 0.08, QColor(120, 170, 90), 0.8)); + scene.addFace(raised(quad(output, {0.40, 0.60}, {0.62, 0.60}, {0.62, 0.80}, {0.40, 0.80}), + 0.04, QColor(230, 210, 120), 0.85)); + + // A black object: the camera cannot read the stripes on it. + scene.addFace(raised(quad(output, {0.75, 0.62}, {0.88, 0.62}, {0.88, 0.82}, {0.75, 0.82}), + 0.03, QColor(20, 20, 20), 0.03)); + return scene; +} + +int SyntheticScene::faceAt(const QPointF& cameraPoint) const +{ + for (int i = _faces.size() - 1; i >= 0; i--) + if (_faces.at(i).cameraQuad.containsPoint(cameraPoint, Qt::OddEvenFill)) + return i; + return -1; +} + +bool SyntheticScene::outputPointAt(const QPointF& cameraPoint, QPointF* outputPoint) const +{ + const int face = faceAt(cameraPoint); + if (face < 0) + return false; + const QPointF point = _cameraToOutput.at(face).map(cameraPoint); + if (point.x() < 0 || point.y() < 0 || point.x() >= _outputSize.width() || point.y() >= _outputSize.height()) + return false; + if (outputPoint) + *outputPoint = point; + return true; +} + +void SyntheticScene::_prepareSamples() const +{ + if (!_samples.isEmpty()) + return; + const int samplesPerPoint = SAMPLES_PER_SIDE * SAMPLES_PER_SIDE; + _samples.resize(_cameraSize.width() * _cameraSize.height() * samplesPerPoint); + int s = 0; + for (int y = 0; y < _cameraSize.height(); y++) + { + for (int x = 0; x < _cameraSize.width(); x++) + { + for (int sy = 0; sy < SAMPLES_PER_SIDE; sy++) + { + for (int sx = 0; sx < SAMPLES_PER_SIDE; sx++, s++) + { + const QPointF point(x + (sx + 0.5) / SAMPLES_PER_SIDE, y + (sy + 0.5) / SAMPLES_PER_SIDE); + Sample& sample = _samples[s]; + sample.face = faceAt(point); + QPointF outputPoint; + if (sample.face >= 0 && outputPointAt(point, &outputPoint)) + sample.outputIndex = qFloor(outputPoint.y()) * _outputSize.width() + qFloor(outputPoint.x()); + } + } + } + } +} + +QImage SyntheticScene::film(const QImage& projected, int frameNumber) const +{ + _prepareSamples(); + const QImage light = projected.convertToFormat(QImage::Format_Grayscale8) + .scaled(_outputSize, Qt::IgnoreAspectRatio, Qt::FastTransformation); + QImage result(_cameraSize, QImage::Format_RGB32); + Random random((quint64(_seed) << 32) ^ quint64(frameNumber + 1)); + const int samplesPerPoint = SAMPLES_PER_SIDE * SAMPLES_PER_SIDE; + const int outputWidth = _outputSize.width(); + + int s = 0; + for (int y = 0; y < _cameraSize.height(); y++) + { + QRgb* line = reinterpret_cast(result.scanLine(y)); + for (int x = 0; x < _cameraSize.width(); x++) + { + qreal red = 0, green = 0, blue = 0; + for (int k = 0; k < samplesPerPoint; k++, s++) + { + const Sample& sample = _samples.at(s); + qreal level; + QColor color; + if (sample.face < 0) + { + level = _ambientLight * SURROUNDING_REFLECTANCE; + color = Qt::white; + } + else + { + const Face& face = _faces.at(sample.face); + qreal projector = 0; + if (sample.outputIndex >= 0) + { + const int u = sample.outputIndex % outputWidth; + const int v = sample.outputIndex / outputWidth; + projector = light.constScanLine(v)[u] / MAXIMUM_LEVEL; + } + level = (_ambientLight + _projectorLight * projector) * face.reflectance; + color = face.color; + } + red += level * color.redF(); + green += level * color.greenF(); + blue += level * color.blueF(); + } + const auto channel = [&](qreal sum) { + return qBound(0, qRound(sum / samplesPerPoint + _noise * random.normal()), int(MAXIMUM_LEVEL)); + }; + line[x] = qRgb(channel(red), channel(green), channel(blue)); + } + } + return result; +} + +} diff --git a/src/automap/SyntheticScene.h b/src/automap/SyntheticScene.h new file mode 100644 index 00000000..05a1087a --- /dev/null +++ b/src/automap/SyntheticScene.h @@ -0,0 +1,134 @@ +/* + * SyntheticScene.h + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef SYNTHETIC_SCENE_H_ +#define SYNTHETIC_SCENE_H_ + +#include +#include +#include +#include +#include +#include + +namespace mmp { + +/** + * A scene computed rather than filmed: flat faces lit by a projector and seen + * by a camera, to try the scan without either. + * + * Each face is a quadrilateral seen by the camera, and the quadrilateral of + * the output that lands on it: the passage from one to the other is a + * perspective, as for a real flat face. The faces added last hide those added + * before, as objects on a table hide the table. + * + * film() computes what the camera sees while the projector shows an image: + * the light of the room, plus the light of the projector reflected by each + * face, with a little noise. Each point of the camera is the mean of several + * samples, so that the edges of the stripes are blurred as by a real lens. + */ +class SyntheticScene +{ +public: + /// A flat face of the scene. + struct Face { + QPolygonF cameraQuad; ///< Where the camera sees it, in pixels of the camera. + QPolygonF outputQuad; ///< The part of the output that lands on it, in pixels of the output. + QColor color; ///< Its colour under white light. + qreal reflectance = 1; ///< How much of the light it sends back, from 0 (black) to 1. + }; + + /// A scene seen by a camera of @a cameraSize and lit by an output of @a outputSize, without faces. + SyntheticScene(const QSize& cameraSize, const QSize& outputSize); + + /** + * Returns a scene like the one of the demonstration: a table that receives + * the whole output, three blocks of wood standing on it, seen from a little + * aside, and a black object that the camera cannot read. + */ + static SyntheticScene blocksOnTable(const QSize& cameraSize, const QSize& outputSize); + + /// Adds a face, in front of those already there. + void addFace(const Face& face); + + /// Returns the faces, from the back to the front. + const QVector& faces() const { return _faces; } + + /// Returns the size of the images of the camera. + QSize cameraSize() const { return _cameraSize; } + + /// Returns the size of the output. + QSize outputSize() const { return _outputSize; } + + /// Sets the light of the room, from 0 to 255 for a white face. + void setAmbientLight(qreal level) { _ambientLight = level; } + + /// Sets the light of the projector at full white, from 0 to 255 for a white face. + void setProjectorLight(qreal level) { _projectorLight = level; } + + /// Sets the noise of the camera: the standard deviation, in levels from 0 to 255. + void setNoise(qreal level) { _noise = level; } + + /// Sets the seed of the noise: the same seed gives the same images. + void setSeed(quint32 seed) { _seed = seed; } + + /** + * Returns what the camera sees while the projector shows @a projected, + * an image of the size of the output. + * + * @param frameNumber changes the noise from one image to the next. + */ + QImage film(const QImage& projected, int frameNumber = 0) const; + + /** + * Gives the point of the output that lights point @a cameraPoint of the + * camera, in pixels of the output. + * + * @return false when no face is there, or when it is outside the output. + */ + bool outputPointAt(const QPointF& cameraPoint, QPointF* outputPoint) const; + + /// Returns the index of the face in front at @a cameraPoint, or -1. + int faceAt(const QPointF& cameraPoint) const; + +private: + // Where each sample of the camera falls, computed once. + struct Sample { + int outputIndex = -1; // The pixel of the output that lights it, or -1. + int face = -1; // The face it is on, or -1. + }; + void _prepareSamples() const; + + QSize _cameraSize; + QSize _outputSize; + QVector _faces; + // For each face, the passage from the camera to the output. + QVector _cameraToOutput; + + qreal _ambientLight; + qreal _projectorLight; + qreal _noise; + quint32 _seed; + + mutable QVector _samples; +}; + +} + +#endif /* SYNTHETIC_SCENE_H_ */ diff --git a/src/automap/automap.pri b/src/automap/automap.pri new file mode 100644 index 00000000..ea6a4272 --- /dev/null +++ b/src/automap/automap.pri @@ -0,0 +1,18 @@ +include(../src.pri) + +# The automatic mapping with a camera: the scan with structured light, and +# what is computed from it. The calculations have no interface, to be tested +# on scenes computed by the tests. +HEADERS += $$PWD/AutoMapFrameSource.h \ + $$PWD/AutoMapScan.h \ + $$PWD/Correspondence.h \ + $$PWD/GrayCodeDecoder.h \ + $$PWD/GrayCodePattern.h \ + $$PWD/SyntheticScene.h + +SOURCES += $$PWD/AutoMapFrameSource.cpp \ + $$PWD/AutoMapScan.cpp \ + $$PWD/Correspondence.cpp \ + $$PWD/GrayCodeDecoder.cpp \ + $$PWD/GrayCodePattern.cpp \ + $$PWD/SyntheticScene.cpp diff --git a/src/src.pri b/src/src.pri index 43bf5163..a6cbef67 100644 --- a/src/src.pri +++ b/src/src.pri @@ -17,6 +17,7 @@ qtHaveModule(httpserver) { #Includes common configuration for all subdirectory .pro files. INCLUDEPATH += $$PWD/core \ $$PWD/shape \ + $$PWD/automap \ $$PWD/gui \ $$PWD/gui/inspector \ $$PWD/control \ diff --git a/tests/TestAutoMap.cpp b/tests/TestAutoMap.cpp new file mode 100644 index 00000000..0fd29425 --- /dev/null +++ b/tests/TestAutoMap.cpp @@ -0,0 +1,350 @@ +/* + * TestAutoMap.cpp + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + */ + +#include "TestAutoMap.h" + +#include "AutoMapFrameSource.h" +#include "AutoMapScan.h" +#include "Correspondence.h" +#include "GrayCodeDecoder.h" +#include "GrayCodePattern.h" +#include "SyntheticScene.h" + +#include + +using namespace mmp; + +namespace { + +// A camera with more points than the output, as a 1080p webcam close to a small scene. +const QSize CAMERA_SIZE(1280, 960); +const QSize OUTPUT_SIZE(640, 360); + +// A small camera and output, for the scans that run with the event loop. +const QSize SMALL_CAMERA_SIZE(320, 240); +const QSize SMALL_OUTPUT_SIZE(320, 180); + +// What the criteria of the slice ask: more than 99 % of the lit points read, half a pixel of error. +const qreal MINIMUM_READ_SHARE = 0.99; +const qreal MAXIMUM_MEAN_ERROR = 0.5; + +// With the two finest series skipped, a point is only known to a square of four pixels by four: a point +// of a square of side 4 is on average 1.53 pixels from its middle (0.3826 times the side). +const int SKIPPED_BITS = 2; +const qreal MAXIMUM_MEAN_ERROR_SKIPPED = 1.6; + +// A face lighter than this sends back enough light to be read. +const qreal READABLE_REFLECTANCE = 0.5; + +// How far from the middle of a point of the camera its corners are checked. +const qreal POINT_HALF_SIZE = 0.45; + +// How long a scan with the event loop may take. +const int SCAN_TIMEOUT_MS = 60000; + +/// Films every image of @a pattern in @a scene and decodes them. +GrayCodeDecoder decodeScene(const SyntheticScene& scene, const GrayCodePattern& pattern) +{ + GrayCodeDecoder decoder(pattern); + for (int i = 0; i < pattern.stepCount(); i++) + decoder.addImage(i, scene.film(pattern.image(i), i)); + return decoder; +} + +/// The scene of the demonstration, filmed by the large camera. +const SyntheticScene& largeScene() +{ + static const SyntheticScene scene = SyntheticScene::blocksOnTable(CAMERA_SIZE, OUTPUT_SIZE); + return scene; +} + +/// The decoding of the large scene with every bit, made once for all the tests that read it. +const GrayCodeDecoder& largeSceneDecoder() +{ + static const GrayCodeDecoder decoder = decodeScene(largeScene(), GrayCodePattern(OUTPUT_SIZE)); + return decoder; +} + +/// What a decoding gives on the points of the camera that can be read. +struct Measure { + int readable = 0; // Points of the camera wholly on a light face, inside the output. + int read = 0; // Those of them that were read. + qreal meanError = 0; // The mean distance to the true point of the output, in pixels of the output. +}; + +/// Compares @a correspondence with the truth of @a scene. +Measure measure(const SyntheticScene& scene, const Correspondence& correspondence) +{ + Measure result; + qreal errorSum = 0; + for (int y = 0; y < scene.cameraSize().height(); y++) + { + for (int x = 0; x < scene.cameraSize().width(); x++) + { + const QPointF middle(x + 0.5, y + 0.5); + const int face = scene.faceAt(middle); + if (face < 0 || scene.faces().at(face).reflectance < READABLE_REFLECTANCE) + continue; + // Points across the edge of a face, or of the output, mix two places. + bool whole = true; + for (qreal dy : {-POINT_HALF_SIZE, POINT_HALF_SIZE}) + for (qreal dx : {-POINT_HALF_SIZE, POINT_HALF_SIZE}) + if (scene.faceAt(middle + QPointF(dx, dy)) != face || !scene.outputPointAt(middle + QPointF(dx, dy), nullptr)) + whole = false; + if (!whole) + continue; + + result.readable++; + if (!correspondence.isRead(x, y)) + continue; + result.read++; + QPointF truth; + scene.outputPointAt(middle, &truth); + errorSum += QLineF(truth, correspondence.outputPoint(x, y)).length(); + } + } + if (result.read > 0) + result.meanError = errorSum / result.read; + return result; +} + +/// A camera that never sends an image. +class SilentFrameSource : public AutoMapFrameSource +{ +public: + bool start(QString*) override { return true; } + void stop() override {} +}; + +/// The options of a quick scan with the event loop. +AutoMapScan::Options quickOptions(const QSize& outputSize) +{ + AutoMapScan::Options options; + options.outputSize = outputSize; + options.countdownSeconds = 1; + options.countdownStepMs = 10; + return options; +} + +} + +void TestAutoMap::grayCodeRoundTrip() +{ + for (quint32 value = 0; value < 4096; value++) + QCOMPARE(GrayCodePattern::fromGray(GrayCodePattern::toGray(value)), value); +} + +void TestAutoMap::neighboursDifferByOneBit() +{ + for (quint32 value = 0; value < 4095; value++) + { + const quint32 changed = GrayCodePattern::toGray(value) ^ GrayCodePattern::toGray(value + 1); + QCOMPARE(qPopulationCount(changed), 1); + } +} + +void TestAutoMap::countsImages() +{ + // As the slice says: 11 bits for 1920 columns and for 1080 rows, two images each, plus white and black. + const GrayCodePattern full(QSize(1920, 1080)); + QCOMPARE(full.columnBits(), 11); + QCOMPARE(full.rowBits(), 11); + QCOMPARE(full.stepCount(), 46); + + const GrayCodePattern skipped(QSize(1920, 1080), SKIPPED_BITS); + QCOMPARE(skipped.stepCount(), 38); + QCOMPARE(skipped.step(skipped.stepCount() - 1).bit, SKIPPED_BITS); + + QCOMPARE(full.step(0).kind, PatternStep::White); + QCOMPARE(full.step(1).kind, PatternStep::Black); + QCOMPARE(full.step(2).direction, StripeDirection::Columns); + QCOMPARE(full.step(2).bit, 10); + QVERIFY(!full.step(2).inverted); + QVERIFY(full.step(3).inverted); + QCOMPARE(full.step(24).direction, StripeDirection::Rows); + QCOMPARE(full.step(24).bit, 10); + QCOMPARE(full.step(3).name(), QStringLiteral("columns-10-inverse")); + + // Never fewer than one series of stripes in each direction. + QCOMPARE(GrayCodePattern(QSize(4, 4), 10).stepCount(), 6); +} + +void TestAutoMap::drawsStripes() +{ + const GrayCodePattern pattern(QSize(16, 8)); + const QImage white = pattern.image(0); + QCOMPARE(white.size(), QSize(16, 8)); + QCOMPARE(white.pixelColor(5, 5), QColor(Qt::white)); + QCOMPARE(pattern.image(1).pixelColor(5, 5), QColor(Qt::black)); + + // Image 2: the widest vertical stripes, bit 3 of the Gray code: the right half is white. + const QImage stripes = pattern.image(2); + QCOMPARE(stripes.pixelColor(7, 3), QColor(Qt::black)); + QCOMPARE(stripes.pixelColor(8, 3), QColor(Qt::white)); + const QImage inverse = pattern.image(3); + QCOMPARE(inverse.pixelColor(7, 3), QColor(Qt::white)); + QCOMPARE(inverse.pixelColor(8, 3), QColor(Qt::black)); + + // Each column is white where its Gray code says so, on every row. + const QImage finest = pattern.image(2 + 2 * 3); + for (int x = 0; x < 16; x++) + for (int y = 0; y < 8; y++) + QCOMPARE(finest.pixelColor(x, y) == QColor(Qt::white), GrayCodePattern::isWhite(x, 0)); +} + +void TestAutoMap::decodesScene() +{ + const SyntheticScene& scene = largeScene(); + const GrayCodeDecoder& decoder = largeSceneDecoder(); + QVERIFY(decoder.isComplete()); + + const Measure m = measure(scene, decoder.result()); + QVERIFY(m.readable > 100000); + const qreal readShare = qreal(m.read) / m.readable; + QVERIFY2(readShare > MINIMUM_READ_SHARE, qPrintable(QString::number(readShare))); + QVERIFY2(m.meanError < MAXIMUM_MEAN_ERROR, qPrintable(QString::number(m.meanError))); +} + +void TestAutoMap::decodesSceneWithSkippedBits() +{ + const SyntheticScene& scene = largeScene(); + const GrayCodePattern pattern(OUTPUT_SIZE, SKIPPED_BITS); + const Measure m = measure(scene, decodeScene(scene, pattern).result()); + const qreal readShare = qreal(m.read) / m.readable; + QVERIFY2(readShare > MINIMUM_READ_SHARE, qPrintable(QString::number(readShare))); + QVERIFY2(m.meanError < MAXIMUM_MEAN_ERROR_SKIPPED, qPrintable(QString::number(m.meanError))); +} + +void TestAutoMap::doesNotReadBlackObject() +{ + const SyntheticScene& scene = largeScene(); + const Correspondence correspondence = largeSceneDecoder().result(); + + // The black object is the last face; its middle, and the dark wall around the table. + const QPolygonF black = scene.faces().last().cameraQuad; + const QPointF middle = black.boundingRect().center(); + QVERIFY(!correspondence.isRead(int(middle.x()), int(middle.y()))); + QVERIFY(!correspondence.isRead(2, 2)); +} + +void TestAutoMap::decodesTheSameTwice() +{ + const SyntheticScene scene = SyntheticScene::blocksOnTable(SMALL_CAMERA_SIZE, SMALL_OUTPUT_SIZE); + const GrayCodePattern pattern(SMALL_OUTPUT_SIZE); + const Correspondence first = decodeScene(scene, pattern).result(); + const Correspondence second = decodeScene(scene, pattern).result(); + QCOMPARE(first.readCount(), second.readCount()); + for (int y = 0; y < SMALL_CAMERA_SIZE.height(); y++) + for (int x = 0; x < SMALL_CAMERA_SIZE.width(); x++) + QCOMPARE(first.outputPoint(x, y), second.outputPoint(x, y)); +} + +void TestAutoMap::refusesImagesOutOfOrder() +{ + const GrayCodePattern pattern(SMALL_OUTPUT_SIZE); + GrayCodeDecoder decoder(pattern); + QImage image(SMALL_CAMERA_SIZE, QImage::Format_RGB32); + image.fill(Qt::gray); + QVERIFY(!decoder.addImage(1, image)); + QVERIFY(decoder.addImage(0, image)); + QVERIFY(!decoder.addImage(1, image.scaled(10, 10))); + QCOMPARE(decoder.nextStep(), 1); + QVERIFY(decoder.result().isEmpty()); +} + +void TestAutoMap::buildsProjectorView() +{ + const SyntheticScene& scene = largeScene(); + const GrayCodeDecoder& decoder = largeSceneDecoder(); + const QImage view = decoder.result().projectorView(decoder.whiteImage(), AutoMapScan::holeFillPasses(0)); + QCOMPARE(view.size(), OUTPUT_SIZE); + + // Most of the output is seen; the black object and what the blocks hide from the camera are not. + const qreal share = Correspondence::readShare(view); + QVERIFY2(share > 0.8 && share < 0.99, qPrintable(QString::number(share))); + + // The middle of the top of block C has its colour under the white light of the projector. + const QColor blockC = view.pixelColor(qRound(0.51 * OUTPUT_SIZE.width()), qRound(0.70 * OUTPUT_SIZE.height())); + QCOMPARE(blockC.alpha(), 255); + const SyntheticScene::Face& faceC = scene.faces().at(4); + const qreal light = (25 + 200) * faceC.reflectance; + QVERIFY(qAbs(blockC.red() - light * faceC.color.redF()) < 15); + QVERIFY(qAbs(blockC.green() - light * faceC.color.greenF()) < 15); + QVERIFY(qAbs(blockC.blue() - light * faceC.color.blueF()) < 15); + + // The middle of the black object is not read. + QCOMPARE(view.pixelColor(qRound(0.81 * OUTPUT_SIZE.width()), qRound(0.72 * OUTPUT_SIZE.height())).alpha(), 0); +} + +void TestAutoMap::paintsCoverage() +{ + QImage view(4, 2, QImage::Format_ARGB32); + view.fill(Qt::transparent); + view.setPixelColor(1, 1, QColor(10, 20, 30)); + QCOMPARE(Correspondence::readShare(view), 1.0 / 8); + + const QColor unread(255, 0, 0, 128); + const QImage covered = Correspondence::withCoverage(view, unread); + QCOMPARE(covered.pixelColor(0, 0), unread); + QCOMPARE(covered.pixelColor(1, 1), QColor(10, 20, 30)); +} + +void TestAutoMap::scansWithLateCamera() +{ + const SyntheticScene scene = SyntheticScene::blocksOnTable(SMALL_CAMERA_SIZE, SMALL_OUTPUT_SIZE); + // Three images late, as a webcam: without throwing the first images away, each one would be read as the one before. + SimulatedFrameSource source(scene, 1, SimulatedFrameSource::DEFAULT_LATENCY_FRAMES); + int shown = 0; + AutoMapScan scan(&source, [&shown](const QImage& image) { if (!image.isNull()) shown++; }, + quickOptions(SMALL_OUTPUT_SIZE)); + QSignalSpy finished(&scan, &AutoMapScan::finished); + QSignalSpy failed(&scan, &AutoMapScan::failed); + scan.start(); + QVERIFY(scan.isRunning()); + QTRY_VERIFY_WITH_TIMEOUT(finished.count() + failed.count() > 0, SCAN_TIMEOUT_MS); + QCOMPARE(failed.count(), 0); + QVERIFY(!scan.isRunning()); + QCOMPARE(shown, 1 + scan.patternCount()); + + const Measure m = measure(scene, scan.correspondence()); + const qreal readShare = qreal(m.read) / m.readable; + QVERIFY2(readShare > 0.95, qPrintable(QString::number(readShare))); + QVERIFY2(m.meanError < 1.0, qPrintable(QString::number(m.meanError))); + QCOMPARE(scan.projectorView().size(), SMALL_OUTPUT_SIZE); +} + +void TestAutoMap::failsWithoutSteadyImage() +{ + SilentFrameSource source; + bool cleared = false; + AutoMapScan::Options options = quickOptions(SMALL_OUTPUT_SIZE); + options.patternTimeoutMs = 50; + AutoMapScan scan(&source, [&cleared](const QImage& image) { cleared = image.isNull(); }, options); + QSignalSpy failed(&scan, &AutoMapScan::failed); + scan.start(); + QTRY_COMPARE_WITH_TIMEOUT(failed.count(), 1, SCAN_TIMEOUT_MS); + QVERIFY(!scan.isRunning()); + // The projection stops with the scan. + QVERIFY(cleared); +} + +void TestAutoMap::failsWhenCameraDoesNotSeeProjection() +{ + SyntheticScene scene = SyntheticScene::blocksOnTable(SMALL_CAMERA_SIZE, SMALL_OUTPUT_SIZE); + scene.setProjectorLight(0); + SimulatedFrameSource source(scene, 1, 0); + AutoMapScan scan(&source, [](const QImage&) {}, quickOptions(SMALL_OUTPUT_SIZE)); + QSignalSpy finished(&scan, &AutoMapScan::finished); + QSignalSpy failed(&scan, &AutoMapScan::failed); + scan.start(); + QTRY_COMPARE_WITH_TIMEOUT(failed.count(), 1, SCAN_TIMEOUT_MS); + QCOMPARE(finished.count(), 0); +} diff --git a/tests/TestAutoMap.h b/tests/TestAutoMap.h new file mode 100644 index 00000000..57792236 --- /dev/null +++ b/tests/TestAutoMap.h @@ -0,0 +1,44 @@ +/* + * TestAutoMap.h + * + * Unit tests for the scan with structured light (src/automap): the stripes + * projected, their decoding on scenes computed by SyntheticScene, with noise + * and the light of a room, the image of the scene seen from the projector, and + * the whole scan with a simulated camera that sends its images late. No + * camera and no projector are needed. + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + */ + +#ifndef TEST_AUTO_MAP_H_ +#define TEST_AUTO_MAP_H_ + +#include + +class TestAutoMap : public QObject +{ + Q_OBJECT + +private slots: + void grayCodeRoundTrip(); + void neighboursDifferByOneBit(); + void countsImages(); + void drawsStripes(); + void decodesScene(); + void decodesSceneWithSkippedBits(); + void doesNotReadBlackObject(); + void decodesTheSameTwice(); + void refusesImagesOutOfOrder(); + void buildsProjectorView(); + void paintsCoverage(); + void scansWithLateCamera(); + void failsWithoutSteadyImage(); + void failsWhenCameraDoesNotSeeProjection(); +}; + +#endif /* TEST_AUTO_MAP_H_ */ diff --git a/tests/main.cpp b/tests/main.cpp index 9d1d05da..8bd21c5c 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -50,6 +50,7 @@ #include "TestEffects.h" #include "TestOutputScreen.h" #include "TestTranslations.h" +#include "TestAutoMap.h" namespace { @@ -213,6 +214,10 @@ int main(int argc, char** argv) TestTranslations test; status |= runTests(&test, argc, argv); } + { + TestAutoMap test; + status |= runTests(&test, argc, argv); + } { TestProjectRoundTrip test; status |= runTests(&test, argc, argv); diff --git a/tests/tests.pro b/tests/tests.pro index 45ef0a97..424082cc 100644 --- a/tests/tests.pro +++ b/tests/tests.pro @@ -23,8 +23,9 @@ CORE = $$PWD/../src/core SHAPE = $$PWD/../src/shape CONTROL = $$PWD/../src/control GUI = $$PWD/../src/gui +AUTOMAP = $$PWD/../src/automap -INCLUDEPATH += $$CORE $$SHAPE $$CONTROL $$GUI $$GUI/inspector +INCLUDEPATH += $$CORE $$SHAPE $$CONTROL $$GUI $$GUI/inspector $$AUTOMAP # Production sources under test plus the minimal set of dependencies they # need to link. We deliberately avoid pulling in the whole core/shape .pri @@ -125,7 +126,8 @@ HEADERS += \ TestLayerTree.h \ TestEffects.h \ TestOutputScreen.h \ - TestTranslations.h + TestTranslations.h \ + TestAutoMap.h SOURCES += \ $$CORE/MM.cpp \ @@ -220,7 +222,14 @@ SOURCES += \ TestLayerTree.cpp \ TestEffects.cpp \ TestOutputScreen.cpp \ - TestTranslations.cpp + TestTranslations.cpp \ + TestAutoMap.cpp + +# The scan with structured light: everything but the dialog. +HEADERS += $$AUTOMAP/AutoMapFrameSource.h $$AUTOMAP/AutoMapScan.h $$AUTOMAP/Correspondence.h \ + $$AUTOMAP/GrayCodeDecoder.h $$AUTOMAP/GrayCodePattern.h $$AUTOMAP/SyntheticScene.h +SOURCES += $$AUTOMAP/AutoMapFrameSource.cpp $$AUTOMAP/AutoMapScan.cpp $$AUTOMAP/Correspondence.cpp \ + $$AUTOMAP/GrayCodeDecoder.cpp $$AUTOMAP/GrayCodePattern.cpp $$AUTOMAP/SyntheticScene.cpp # The inspector. HEADERS += $$GUI/inspector/SettingFormat.h $$GUI/inspector/SettingControl.h $$GUI/inspector/ChoiceChips.h \ From 85a30a881fa39f5f3742dbae81501381a4a34594 Mon Sep 17 00:00:00 2001 From: Alexandre Quessy Date: Fri, 4 Dec 2026 00:26:49 -0500 Subject: [PATCH 2/6] Show the images of a scan over the output, and an image under the shapes of the output editor The output canvas shows an image over the whole output frame, in place of the shapes and of the test signal, pixel for pixel and without smoothing, so that the finest stripes stay sharp. The canvases of the editors draw an image under the shapes, over their content rectangle. --- src/gui/MapperGLCanvas.cpp | 13 +++++++++++++ src/gui/MapperGLCanvas.h | 13 +++++++++++++ src/gui/OutputGLCanvas.cpp | 24 +++++++++++++++++++++++- src/gui/OutputGLCanvas.h | 12 ++++++++++++ 4 files changed, 61 insertions(+), 1 deletion(-) diff --git a/src/gui/MapperGLCanvas.cpp b/src/gui/MapperGLCanvas.cpp index 6362a67e..9ed45025 100644 --- a/src/gui/MapperGLCanvas.cpp +++ b/src/gui/MapperGLCanvas.cpp @@ -324,10 +324,23 @@ void MapperGLCanvas::resizeEvent(QResizeEvent* event) void MapperGLCanvas::drawBackground(QPainter* painter, const QRectF& rect) { QGraphicsView::drawBackground(painter, rect); + if (!_backgroundImage.isNull() && !_contentRect.isEmpty()) + { + painter->save(); + painter->setRenderHint(QPainter::SmoothPixmapTransform); + painter->drawImage(_contentRect, _backgroundImage); + painter->restore(); + } // Under the shapes and their controls, so that it never hides them. _drawContentOutline(painter); } +void MapperGLCanvas::setBackgroundImage(const QImage& image) +{ + _backgroundImage = image; + viewport()->update(); +} + void MapperGLCanvas::setContentLabel(const QString& label) { _contentLabel = label; diff --git a/src/gui/MapperGLCanvas.h b/src/gui/MapperGLCanvas.h index 916e5ff6..31becea9 100644 --- a/src/gui/MapperGLCanvas.h +++ b/src/gui/MapperGLCanvas.h @@ -117,6 +117,16 @@ class MapperGLCanvas: public QGraphicsView /// Sets the name shown above the outline of the content rectangle. void setContentLabel(const QString& label); + /** + * Sets an image drawn under the shapes, stretched over the content + * rectangle: in the output editor, the scene seen from the projector after + * an automatic mapping. A null image removes it. + */ + void setBackgroundImage(const QImage& image); + + /// Returns the image drawn under the shapes, or a null image. + QImage backgroundImage() const { return _backgroundImage; } + // Apply zoom to view void applyZoomToView(); @@ -207,6 +217,9 @@ class MapperGLCanvas: public QGraphicsView // Name shown above the outline of the content rectangle. QString _contentLabel; + // Drawn under the shapes, over the content rectangle (see setBackgroundImage()). + QImage _backgroundImage; + // Drag in progress on a scale or rotation handle of the current shape. std::optional _handleDrag; // The mode when the handle drag started, which names the undo step. diff --git a/src/gui/OutputGLCanvas.cpp b/src/gui/OutputGLCanvas.cpp index a6f48563..c343d4fb 100644 --- a/src/gui/OutputGLCanvas.cpp +++ b/src/gui/OutputGLCanvas.cpp @@ -126,6 +126,24 @@ void OutputGLCanvas::setSyphonServerName(const QString& name) #endif } +void OutputGLCanvas::setPatternImage(const QImage& image) +{ + _patternImage = image; + viewport()->update(); +} + +void OutputGLCanvas::_drawPatternImage(QPainter* painter) +{ + // In window pixels, over black, without smoothing: the edges of the finest + // stripes must stay sharp. + painter->save(); + painter->resetTransform(); + painter->fillRect(viewport()->rect(), Qt::black); + painter->setRenderHint(QPainter::SmoothPixmapTransform, false); + painter->drawImage(viewportTransform().mapRect(_outputFrame), _patternImage); + painter->restore(); +} + void OutputGLCanvas::drawForeground(QPainter *painter , const QRectF &rect) { #if defined(HAVE_SYPHON) && defined(SYPHON_OUTPUT_EXPERIMENTAL) @@ -147,7 +165,11 @@ void OutputGLCanvas::drawForeground(QPainter *painter , const QRectF &rect) // Shapes reaching outside the output frame must not show around it. _maskOutsideOutputFrame(painter, rect); - if (_displayTestSignal) + if (!_patternImage.isNull()) + { + _drawPatternImage(painter); + } + else if (_displayTestSignal) { // Draw the preferred signal test card, in window pixels. int testCard = settings.value("signalTestCard", MM::DEFAULT_TEST_CARD).toInt(); diff --git a/src/gui/OutputGLCanvas.h b/src/gui/OutputGLCanvas.h index fbec6137..0d75c464 100644 --- a/src/gui/OutputGLCanvas.h +++ b/src/gui/OutputGLCanvas.h @@ -65,6 +65,13 @@ class OutputGLCanvas: public MapperGLCanvas _displayTestSignal = displayTestSignal; } + /** + * Shows @a image over the whole output frame, in place of the shapes and of + * the test signal, pixel for pixel: the images of the automatic mapping. + * A null image shows the output again. + */ + void setPatternImage(const QImage& image); + // Syphon output (macOS): publish the rendered output as a Syphon server. // No-ops on platforms without Syphon support. void setSyphonOutputEnabled(bool on); @@ -101,8 +108,13 @@ class OutputGLCanvas: public MapperGLCanvas // How long the mouse must be idle before editing is hidden (in milliseconds). static const int EDITING_HIDE_DELAY = 3000; + // Draws the image of the automatic mapping over the output frame. + void _drawPatternImage(QPainter* painter); + bool _displayCrosshair; bool _displayTestSignal; + // Shown in place of everything else while not null (see setPatternImage()). + QImage _patternImage; QImage _classicTestCard; QBrush _brush_test_signal; QImage _palTestCard; From 022297fdf428bfdb9f332b75a1e347152712a4ee Mon Sep 17 00:00:00 2001 From: Alexandre Quessy Date: Fri, 4 Dec 2026 00:26:49 -0500 Subject: [PATCH 3/6] Add Tools > Auto-Mapping, to see the scene from the projector The window chooses the camera and the screen of the projector, shows what the camera films, and starts the scan. During the scan, the output covers the screen of the projector, for this session only, and shows a countdown, then the stripes; it is shown as before afterwards. The scene seen from the projector then shows under the shapes of the output editor, with in red what the camera did not see. Tools > Show Auto-Mapping Image hides it, Tools > Clear Auto-Mapping Image forgets it; it is never saved, and goes with the project. --auto-mapping-simulation films a computed scene instead of a camera; --auto-mapping-save-images writes the images of the camera, which are otherwise never written to the disk. --- CHANGELOG.md | 1 + src/app/main.cpp | 15 ++ src/gui/AutoMappingDialog.cpp | 343 ++++++++++++++++++++++++++++++++++ src/gui/AutoMappingDialog.h | 106 +++++++++++ src/gui/MainWindow.cpp | 139 +++++++++++++- src/gui/MainWindow.h | 44 +++++ src/gui/gui.pri | 2 + 7 files changed, 648 insertions(+), 2 deletions(-) create mode 100644 src/gui/AutoMappingDialog.cpp create mode 100644 src/gui/AutoMappingDialog.h diff --git a/CHANGELOG.md b/CHANGELOG.md index e7768074..3964121f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ New: - Choose the output screen at launch with `--output-screen `, by its name or its number in the list that `--list-screens` writes, then quits. - Control the output window by OSC: `/mapmap/output/mode` (`hidden`, `window` or `screen`), `/mapmap/output/screen` (a name, or a number from 1) and `/mapmap/output/window` (`x y width height`). - Translate MapMap into Arabic, laid out from right to left with numbers written with the digits 0 to 9, into Hindi and into Russian: choose them in Preferences > Interface > Language, or with `--lang ar`, `hi` or `ru`. No speaker of these languages has read them yet. +- See the scene from the projector, with a camera placed next to it: Tools > Auto-Mapping covers the screen of the projector with the output, projects a countdown, then black and white stripes that the camera films, about 15 seconds in all. The scene seen from the projector then shows under the shapes of the output editor, with in red what the camera did not see, to place the shapes on it by hand. Tools > Show Auto-Mapping Image hides it, Tools > Clear Auto-Mapping Image forgets it; it is never saved, and goes with the project. No image of the camera is written to the disk, unless asked with `--auto-mapping-save-images `. `--auto-mapping-simulation` films a computed scene instead, to try it without a camera or a projector. Placing shapes on the flat faces found comes in a later version. Improvements: diff --git a/src/app/main.cpp b/src/app/main.cpp index e51cc828..1f7f65c2 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -12,6 +12,7 @@ #include "FrameStats.h" #include "VideoImpl.h" #include "MainWindow.h" +#include "AutoMappingDialog.h" #include "OutputScreen.h" #include "MainApplication.h" @@ -230,6 +231,17 @@ int main(int argc, char *argv[]) "Write the game controllers connected, then each button pressed and each axis pushed beyond half way, until Ctrl+C. Opens no window."); parser.addOption(listGamepadsOption); + // --auto-mapping-simulation option + QCommandLineOption autoMappingSimulationOption("auto-mapping-simulation", + "In Tools > Auto-Mapping, film a computed scene instead of a camera: to try the scan without a camera or a projector."); + parser.addOption(autoMappingSimulationOption); + + // --auto-mapping-save-images option + QCommandLineOption autoMappingSaveImagesOption("auto-mapping-save-images", + "Write the images of the camera kept by Tools > Auto-Mapping, and the scene seen from the projector, to . " + "Without this option, no image of the camera is ever written.", "folder"); + parser.addOption(autoMappingSaveImagesOption); + // Positional argument: file parser.addPositionalArgument("file", "Load project from that file."); @@ -365,6 +377,9 @@ int main(int argc, char *argv[]) if (parser.isSet(verboseOption)) win->setVerbose(true); + AutoMappingDialog::setSimulation(parser.isSet(autoMappingSimulationOption)); + AutoMappingDialog::setImagesFolder(parser.value(autoMappingSaveImagesOption)); + #ifdef HAVE_MCP QString mcpPortValue = parser.value("mcp-port"); if (mcpPortValue != "") diff --git a/src/gui/AutoMappingDialog.cpp b/src/gui/AutoMappingDialog.cpp new file mode 100644 index 00000000..5d393983 --- /dev/null +++ b/src/gui/AutoMappingDialog.cpp @@ -0,0 +1,343 @@ +/* + * AutoMappingDialog.cpp + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "AutoMappingDialog.h" + +#include "AutoMapFrameSource.h" +#include "AutoMapScan.h" +#include "Correspondence.h" +#include "MainWindow.h" +#include "SyntheticScene.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace mmp { + +namespace { + +bool simulation = false; +QString imagesFolderPath; + +// The size of the image of the camera in the window. +const QSize PREVIEW_SIZE(480, 270); +// The time between two images of the preview, in milliseconds: enough to aim the camera. +const int PREVIEW_INTERVAL_MS = 100; + +// The size of the images of the simulated camera: a 720p webcam. +const QSize SIMULATED_CAMERA_SIZE(1280, 720); + +// What a webcam sends, to estimate how long a scan takes. +const int CAMERA_FRAMES_PER_SECOND = 30; +// Besides those thrown away, two images are needed to tell that the image is steady. +const int FRAMES_TO_SETTLE = 2; + +// Where nothing was read, in the scene seen from the projector: red, half seen through. +const QColor UNREAD_COLOR(220, 0, 0, 140); + +const int PERCENT = 100; + +} + +AutoMappingDialog::AutoMappingDialog(MainWindow* mainWindow) + : QDialog(mainWindow), + _mainWindow(mainWindow) +{ + setWindowTitle(tr("Auto-Mapping")); + + _cameraBox = new QComboBox(this); + if (simulation) + _cameraBox->addItem(tr("Simulated scene (--auto-mapping-simulation)")); + else + { + const QList cameras = QMediaDevices::videoInputs(); + for (const QCameraDevice& camera : cameras) + { + _cameraBox->addItem(camera.description(), QVariant::fromValue(camera)); + if (camera == QMediaDevices::defaultVideoInput()) + _cameraBox->setCurrentIndex(_cameraBox->count() - 1); + } + } + + _screenBox = new QComboBox(this); + const QList screens = QGuiApplication::screens(); + for (QScreen* screen : screens) + { + _screenBox->addItem(tr("%1 - %2 × %3").arg(screen->name()) + .arg(screen->size().width()).arg(screen->size().height())); + if (screen == _mainWindow->outputScreen()) + _screenBox->setCurrentIndex(_screenBox->count() - 1); + } + if (!_mainWindow->outputScreen() && !screens.isEmpty()) + _screenBox->setCurrentIndex(screens.size() - 1); + + _preview = new QLabel(this); + _preview->setFixedSize(PREVIEW_SIZE); + _preview->setAlignment(Qt::AlignCenter); + _preview->setStyleSheet(QStringLiteral("background-color: black; color: gray;")); + + _reminder = new QLabel(tr("Place the camera next to the projector, so that it sees everything the projector lights. " + "Nobody in the picture, and darken the room.\n" + "After the scan, do not touch the zoom, the focus or the framing of the projector: " + "the image would no longer match."), this); + _reminder->setWordWrap(true); + + _skipFineStripes = new QCheckBox(tr("Skip the finest stripes (faster, for a blurry camera, but less precise)"), this); + _estimate = new QLabel(this); + + _progress = new QProgressBar(this); + _progress->setTextVisible(false); + _status = new QLabel(this); + _status->setWordWrap(true); + + QDialogButtonBox* buttons = new QDialogButtonBox(this); + _startButton = buttons->addButton(tr("Start"), QDialogButtonBox::AcceptRole); + _closeButton = buttons->addButton(QDialogButtonBox::Close); + _startButton->setDefault(true); + + QFormLayout* form = new QFormLayout; + form->addRow(tr("Camera:"), _cameraBox); + form->addRow(tr("Projector screen:"), _screenBox); + + QVBoxLayout* layout = new QVBoxLayout(this); + layout->addLayout(form); + layout->addWidget(_preview, 0, Qt::AlignHCenter); + layout->addWidget(_reminder); + layout->addWidget(_skipFineStripes); + layout->addWidget(_estimate); + layout->addWidget(_progress); + layout->addWidget(_status); + layout->addWidget(buttons); + + connect(_cameraBox, &QComboBox::currentIndexChanged, this, &AutoMappingDialog::_openCamera); + connect(_skipFineStripes, &QCheckBox::toggled, this, &AutoMappingDialog::_updateEstimate); + connect(_startButton, &QPushButton::clicked, this, &AutoMappingDialog::_start); + connect(_closeButton, &QPushButton::clicked, this, &AutoMappingDialog::reject); + + _updateEstimate(); + _setRunning(false); + _openCamera(); +} + +AutoMappingDialog::~AutoMappingDialog() +{ + _cancel(); + _closeCamera(); +} + +void AutoMappingDialog::setSimulation(bool on) +{ + simulation = on; +} + +bool AutoMappingDialog::isSimulation() +{ + return simulation; +} + +void AutoMappingDialog::setImagesFolder(const QString& folder) +{ + imagesFolderPath = folder; +} + +QString AutoMappingDialog::imagesFolder() +{ + return imagesFolderPath; +} + +QSize AutoMappingDialog::_outputSize() const +{ + return _mainWindow->getOutputFrame().size().toSize(); +} + +void AutoMappingDialog::_openCamera() +{ + _closeCamera(); + _preview->clear(); + + if (simulation) + _source = new SimulatedFrameSource(SyntheticScene::blocksOnTable(SIMULATED_CAMERA_SIZE, _outputSize()), + SimulatedFrameSource::DEFAULT_FRAME_INTERVAL_MS, + SimulatedFrameSource::DEFAULT_LATENCY_FRAMES, this); + else if (_cameraBox->currentIndex() >= 0) + _source = new CameraFrameSource(_cameraBox->currentData().value(), this); + else + { + _preview->setText(tr("No camera is connected.")); + _startButton->setEnabled(false); + return; + } + + connect(_source, &AutoMapFrameSource::frameReady, this, &AutoMappingDialog::_onPreviewFrame); + QString error; + if (!_source->start(&error)) + { + _preview->setText(error); + _startButton->setEnabled(false); + return; + } + _startButton->setEnabled(true); +} + +void AutoMappingDialog::_closeCamera() +{ + if (!_source) + return; + _source->stop(); + delete _source; +} + +void AutoMappingDialog::_onPreviewFrame(const QImage& frame) +{ + static QElapsedTimer sincePreview; + if (sincePreview.isValid() && sincePreview.elapsed() < PREVIEW_INTERVAL_MS) + return; + sincePreview.start(); + _preview->setPixmap(QPixmap::fromImage(frame.scaled(PREVIEW_SIZE, Qt::KeepAspectRatio, Qt::FastTransformation))); +} + +void AutoMappingDialog::_updateEstimate() +{ + const GrayCodePattern pattern(_outputSize(), _skipFineStripes->isChecked() ? SKIPPED_FINE_BITS : 0); + const int frames = pattern.stepCount() * (AutoMapScan::DEFAULT_DISCARDED_FRAMES + FRAMES_TO_SETTLE); + const int seconds = AutoMapScan::DEFAULT_COUNTDOWN_SECONDS + qCeil(qreal(frames) / CAMERA_FRAMES_PER_SECOND); + _estimate->setText(tr("%1 images, about %2 seconds.").arg(pattern.stepCount()).arg(seconds)); +} + +void AutoMappingDialog::_start() +{ + if (_scan || !_source) + return; + + // The simulated scene follows the size of the output, which may have changed. + if (simulation) + _openCamera(); + + const QList screens = QGuiApplication::screens(); + const int screenIndex = _screenBox->currentIndex(); + QScreen* screen = (screenIndex >= 0 && screenIndex < screens.size()) ? screens.at(screenIndex) : nullptr; + if (!_mainWindow->beginAutoMappingOutput(screen)) + { + _status->setText(tr("The scan needs the output over the whole screen of the projector.")); + return; + } + + AutoMapScan::Options options; + options.outputSize = _outputSize(); + options.skippedFineBits = _skipFineStripes->isChecked() ? SKIPPED_FINE_BITS : 0; + options.imagesFolder = imagesFolderPath; + + MainWindow* mainWindow = _mainWindow; + _scan = new AutoMapScan(_source, [mainWindow](const QImage& image) { mainWindow->showAutoMappingPattern(image); }, + options, this); + connect(_scan, &AutoMapScan::progressChanged, this, &AutoMappingDialog::_onProgress); + connect(_scan, &AutoMapScan::finished, this, &AutoMappingDialog::_onFinished); + connect(_scan, &AutoMapScan::failed, this, &AutoMappingDialog::_onFailed); + + _status->setText(tr("Scanning: do not move.")); + _setRunning(true); + _scan->start(); +} + +void AutoMappingDialog::_cancel() +{ + if (!_scan) + return; + _scan->cancel(); + _scan->deleteLater(); + _scan = nullptr; + _mainWindow->endAutoMappingOutput(); + _setRunning(false); + _progress->reset(); + _status->setText(tr("Scan cancelled.")); + // The scan stopped the camera: start it again for the preview. + if (_source) + { + QString error; + _source->start(&error); + } +} + +void AutoMappingDialog::reject() +{ + if (_scan) + { + _cancel(); + return; + } + QDialog::reject(); +} + +void AutoMappingDialog::_onProgress(int done, int total) +{ + _progress->setMaximum(total); + _progress->setValue(done); +} + +void AutoMappingDialog::_onFinished() +{ + const QImage view = _scan->projectorView(); + _scan->deleteLater(); + _scan = nullptr; + _mainWindow->endAutoMappingOutput(); + _setRunning(false); + + _mainWindow->setAutoMappingImage(Correspondence::withCoverage(view, UNREAD_COLOR)); + const int readPercent = qRound(Correspondence::readShare(view) * PERCENT); + _status->setText(tr("Done: the camera saw %1 % of the output. The scene seen from the projector is under the shapes " + "of the output editor; in red, what the camera did not see. Tools > Show Auto-Mapping Image " + "hides it, Tools > Clear Auto-Mapping Image forgets it.").arg(readPercent)); +} + +void AutoMappingDialog::_onFailed(const QString& message) +{ + _scan->deleteLater(); + _scan = nullptr; + _mainWindow->endAutoMappingOutput(); + _setRunning(false); + _progress->reset(); + _status->setText(message); + if (_source) + { + QString error; + _source->start(&error); + } +} + +void AutoMappingDialog::_setRunning(bool running) +{ + _cameraBox->setEnabled(!running && !simulation); + _screenBox->setEnabled(!running); + _skipFineStripes->setEnabled(!running); + _startButton->setEnabled(!running && _source); + _closeButton->setText(running ? tr("Cancel") : tr("Close")); +} + +} diff --git a/src/gui/AutoMappingDialog.h b/src/gui/AutoMappingDialog.h new file mode 100644 index 00000000..5feeed3c --- /dev/null +++ b/src/gui/AutoMappingDialog.h @@ -0,0 +1,106 @@ +/* + * AutoMappingDialog.h + * + * (c) 2026 MapMap contributors + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef AUTO_MAPPING_DIALOG_H_ +#define AUTO_MAPPING_DIALOG_H_ + +#include +#include +#include + +class QCheckBox; +class QComboBox; +class QLabel; +class QProgressBar; +class QPushButton; + +namespace mmp { + +class AutoMapFrameSource; +class AutoMapScan; +class MainWindow; + +/** + * The window of the automatic mapping (Tools > Auto-Mapping…). + * + * One chooses the camera and the screen of the projector, sees what the + * camera films, and starts the scan. During the scan, the output covers the + * screen of the projector and shows a countdown, then the stripes; afterwards + * it is shown as before. The scene seen from the projector then appears under + * the shapes of the output editor. + */ +class AutoMappingDialog : public QDialog +{ + Q_OBJECT + +public: + explicit AutoMappingDialog(MainWindow* mainWindow); + ~AutoMappingDialog() override; + + /// Uses a computed scene instead of a camera (--auto-mapping-simulation). + static void setSimulation(bool simulation); + + /// Returns true when a computed scene is used instead of a camera. + static bool isSimulation(); + + /// Writes the images of the camera kept during a scan to @a folder (--auto-mapping-save-images); empty: nowhere. + static void setImagesFolder(const QString& folder); + + /// Returns the folder where the images of the camera are written, or an empty text. + static QString imagesFolder(); + + /// How many of the finest series of stripes are skipped when asked to. + static const int SKIPPED_FINE_BITS = 2; + +public slots: + /// Stops a scan that runs, then closes. + void reject() override; + +private: + void _openCamera(); + void _closeCamera(); + void _onPreviewFrame(const QImage& frame); + void _start(); + void _cancel(); + void _onProgress(int done, int total); + void _onFinished(); + void _onFailed(const QString& message); + void _setRunning(bool running); + void _updateEstimate(); + QSize _outputSize() const; + + MainWindow* _mainWindow; + QComboBox* _cameraBox; + QComboBox* _screenBox; + QLabel* _preview; + QLabel* _reminder; + QCheckBox* _skipFineStripes; + QLabel* _estimate; + QProgressBar* _progress; + QLabel* _status; + QPushButton* _startButton; + QPushButton* _closeButton; + + QPointer _source; + QPointer _scan; +}; + +} + +#endif /* AUTO_MAPPING_DIALOG_H_ */ diff --git a/src/gui/MainWindow.cpp b/src/gui/MainWindow.cpp index 9574734b..e2a82f1f 100644 --- a/src/gui/MainWindow.cpp +++ b/src/gui/MainWindow.cpp @@ -20,6 +20,7 @@ */ #include "MainWindow.h" +#include "AutoMappingDialog.h" #include "EffectTypes.h" #include "MediaCues.h" #include "SettingFormat.h" @@ -2009,6 +2010,9 @@ bool MainWindow::clearProject() mappingManager->clearAll(); setOutputResolution(defaultOutputResolution()); + // The scene seen from the projector belongs to the room of this project. + clearAutoMappingImage(); + // Refresh GL canvases to clear them out. sourceCanvas->repaint(); destinationCanvas->repaint(); @@ -3136,6 +3140,26 @@ void MainWindow::createActions() _linksWindow->activateWindow(); }); + // The automatic mapping with a camera. + autoMappingAction = new QAction(tr("&Auto-Mapping…"), this); + autoMappingAction->setToolTip(tr("Film stripes projected on the scene, to see it from the projector")); + addAction(autoMappingAction); + connect(autoMappingAction, &QAction::triggered, this, &MainWindow::openAutoMapping); + + showAutoMappingImageAction = new QAction(tr("&Show Auto-Mapping Image"), this); + showAutoMappingImageAction->setToolTip(tr("Show the scene seen from the projector under the shapes of the output")); + showAutoMappingImageAction->setCheckable(true); + showAutoMappingImageAction->setChecked(true); + showAutoMappingImageAction->setEnabled(false); + addAction(showAutoMappingImageAction); + connect(showAutoMappingImageAction, &QAction::toggled, this, &MainWindow::setAutoMappingImageShown); + + clearAutoMappingImageAction = new QAction(tr("&Clear Auto-Mapping Image"), this); + clearAutoMappingImageAction->setToolTip(tr("Forget the scene seen from the projector")); + clearAutoMappingImageAction->setEnabled(false); + addAction(clearAutoMappingImageAction); + connect(clearAutoMappingImageAction, &QAction::triggered, this, &MainWindow::clearAutoMappingImage); + // Toggle display of zoom tool buttons displayZoomToolAction = new QAction(tr("Display &Zoom Toolbar"), this); displayZoomToolAction->setShortcut(Qt::ALT | Qt::Key_Z); @@ -3373,6 +3397,12 @@ void MainWindow::createMenus() viewMenu->addAction(pauseAction); viewMenu->addAction(rewindAction); + // Tools + toolsMenu = menuBar->addMenu(tr("&Tools")); + toolsMenu->addAction(autoMappingAction); + toolsMenu->addAction(showAutoMappingImageAction); + toolsMenu->addAction(clearAutoMappingImageAction); + // Window windowMenu = menuBar->addMenu(tr("&Window")); @@ -3688,9 +3718,18 @@ void MainWindow::writeSettings() if (outputWindow->windowGeometry().isValid()) settings.setValue("outputWindowGeometry", outputWindow->windowGeometry()); // Opened by the test signal, the output was hidden. - settings.setValue("outputMode", outputModeName(_testSignalOpenedOutput ? _outputModeBeforeScreen : _outputMode)); + // Taken by an automatic mapping, or opened by the test signal, the output was shown otherwise. + OutputMode savedOutputMode = _testSignalOpenedOutput ? _outputModeBeforeScreen : _outputMode; + if (_autoMappingOutputActive) + savedOutputMode = _outputModeBeforeAutoMapping; + settings.setValue("outputMode", outputModeName(savedOutputMode)); // A screen chosen for this session only leaves the retained one. - if (_outputScreenIsSaved && !_outputScreenIdentity.isEmpty()) + if (_autoMappingOutputActive) + { + if (_outputScreenSavedBeforeAutoMapping && !_outputScreenBeforeAutoMapping.isEmpty()) + settings.setValue("outputScreen", _outputScreenBeforeAutoMapping.toVariant()); + } + else if (_outputScreenIsSaved && !_outputScreenIdentity.isEmpty()) settings.setValue("outputScreen", _outputScreenIdentity.toVariant()); settings.setValue("displayTestSignal", displayTestSignalAction->isChecked()); settings.setValue("displayControls", displayControlsAction->isChecked()); @@ -4503,6 +4542,102 @@ void MainWindow::setOutputMode(OutputMode mode, bool askBeforeCovering) _applyOutputMode(); } +bool MainWindow::beginAutoMappingOutput(QScreen* screen) +{ + if (_autoMappingOutputActive) + return true; + + _outputModeBeforeAutoMapping = _outputMode; + _outputModeBeforeScreenBeforeAutoMapping = _outputModeBeforeScreen; + _outputScreenBeforeAutoMapping = _outputScreenIdentity; + _outputScreenSavedBeforeAutoMapping = _outputScreenIsSaved; + // Not the test signal: it would be hidden, and it would hide the output when turned off. + _testSignalOpenedOutput = false; + if (displayTestSignalAction->isChecked()) + { + QSignalBlocker blocker(displayTestSignalAction); + displayTestSignalAction->setChecked(false); + outputWindow->setDisplayTestSignal(false); + } + + // For this session only: the screen retained in the settings stays. + if (screen) + { + _outputScreenIdentity = ScreenIdentity::fromScreen(screen); + _outputScreenIsSaved = false; + } + if (_outputMode == OutputMode::Screen) + updateOutputScreens(); + else + { + updateOutputScreens(); + setOutputMode(OutputMode::Screen, true); + } + + if (_outputMode != OutputMode::Screen || !outputScreen()) + { + _outputScreenIdentity = _outputScreenBeforeAutoMapping; + _outputScreenIsSaved = _outputScreenSavedBeforeAutoMapping; + _outputMode = _outputModeBeforeAutoMapping; + _outputModeBeforeScreen = _outputModeBeforeScreenBeforeAutoMapping; + updateOutputScreens(); + return false; + } + _autoMappingOutputActive = true; + return true; +} + +void MainWindow::endAutoMappingOutput() +{ + showAutoMappingPattern(QImage()); + if (!_autoMappingOutputActive) + return; + _autoMappingOutputActive = false; + _outputScreenIdentity = _outputScreenBeforeAutoMapping; + _outputScreenIsSaved = _outputScreenSavedBeforeAutoMapping; + _outputMode = _outputModeBeforeAutoMapping; + _outputModeBeforeScreen = _outputModeBeforeScreenBeforeAutoMapping; + // Rebuilds the list of the screens, then shows the output as it was. + updateOutputScreens(); +} + +void MainWindow::showAutoMappingPattern(const QImage& image) +{ + outputWindow->getCanvas()->setPatternImage(image); +} + +void MainWindow::setAutoMappingImage(const QImage& image) +{ + _autoMappingImage = image; + // A project may be cleared before the actions are made. + if (showAutoMappingImageAction) + { + const bool hasImage = !image.isNull(); + showAutoMappingImageAction->setEnabled(hasImage); + clearAutoMappingImageAction->setEnabled(hasImage); + QSignalBlocker blocker(showAutoMappingImageAction); + showAutoMappingImageAction->setChecked(true); + } + if (destinationCanvas) + destinationCanvas->setBackgroundImage(image); +} + +void MainWindow::setAutoMappingImageShown(bool shown) +{ + destinationCanvas->setBackgroundImage(shown ? _autoMappingImage : QImage()); +} + +void MainWindow::clearAutoMappingImage() +{ + setAutoMappingImage(QImage()); +} + +void MainWindow::openAutoMapping() +{ + AutoMappingDialog dialog(this); + dialog.exec(); +} + void MainWindow::toggleOutputFillsScreen() { if (_outputMode == OutputMode::Screen) diff --git a/src/gui/MainWindow.h b/src/gui/MainWindow.h index e017d0cf..c64dc3dd 100644 --- a/src/gui/MainWindow.h +++ b/src/gui/MainWindow.h @@ -558,6 +558,19 @@ public slots: // Opens the list of the links. QAction* openLinksAction = nullptr; + // The automatic mapping with a camera: its window, and the scene seen from the projector. + QAction* autoMappingAction = nullptr; + QAction* showAutoMappingImageAction = nullptr; + QAction* clearAutoMappingImageAction = nullptr; + // The scene seen from the projector, from the last automatic mapping; never saved. + QImage _autoMappingImage; + // How the output was shown before an automatic mapping took it (see beginAutoMappingOutput()). + bool _autoMappingOutputActive = false; + OutputMode _outputModeBeforeAutoMapping = OutputMode::Hidden; + OutputMode _outputModeBeforeScreenBeforeAutoMapping = OutputMode::Hidden; + ScreenIdentity _outputScreenBeforeAutoMapping; + bool _outputScreenSavedBeforeAutoMapping = true; + /// Shows the links again when the window listing them is open. void refreshLinksWindow(); @@ -996,6 +1009,37 @@ public slots: */ void setOutputMode(OutputMode mode, bool askBeforeCovering = false); + /** + * Shows the output over the whole of @a screen for an automatic mapping, + * for this session only, until endAutoMappingOutput(). Asks first when it + * would cover this window. + * + * @return false when the output could not be shown there. + */ + bool beginAutoMappingOutput(QScreen* screen); + + /// Shows the output as it was before beginAutoMappingOutput(). + void endAutoMappingOutput(); + + /// Shows @a image over the whole output, in place of the shapes; a null image shows them again. + void showAutoMappingPattern(const QImage& image); + + /** + * Shows the scene seen from the projector, from an automatic mapping, under + * the shapes of the output editor. It is kept until the project is closed, + * and never saved. + */ + void setAutoMappingImage(const QImage& image); + + /// Shows or hides the scene seen from the projector, under the shapes of the output editor. + void setAutoMappingImageShown(bool shown); + + /// Forgets the scene seen from the projector. + void clearAutoMappingImage(); + + /// Opens the window of the automatic mapping. + void openAutoMapping(); + /// Returns how the output is shown, or would be when its screen is disconnected. OutputMode outputMode() const { return _outputMode; } diff --git a/src/gui/gui.pri b/src/gui/gui.pri index f1286f43..9c518b04 100644 --- a/src/gui/gui.pri +++ b/src/gui/gui.pri @@ -2,6 +2,7 @@ include(../src.pri) HEADERS += $$PWD/AboutDialog.h \ + $$PWD/AutoMappingDialog.h \ $$PWD/AddSourceActions.h \ $$PWD/ConsoleWindow.h \ $$PWD/GuiForward.h \ @@ -36,6 +37,7 @@ HEADERS += $$PWD/AboutDialog.h \ $$PWD/inspector/SettingFormat.h SOURCES += $$PWD/AboutDialog.cpp \ + $$PWD/AutoMappingDialog.cpp \ $$PWD/AddSourceActions.cpp \ $$PWD/ConsoleWindow.cpp \ $$PWD/HandleModeKeys.cpp \ From e3099f7aa3ee8ec343c68daecc7e33947be442a9 Mon Sep 17 00:00:00 2001 From: Alexandre Quessy Date: Fri, 4 Dec 2026 00:26:49 -0500 Subject: [PATCH 4/6] Translate the automatic mapping into French --- translations/mapmap_fr.ts | 692 +++++++++++++++++++++++--------------- 1 file changed, 424 insertions(+), 268 deletions(-) diff --git a/translations/mapmap_fr.ts b/translations/mapmap_fr.ts index 642f3693..6150d245 100644 --- a/translations/mapmap_fr.ts +++ b/translations/mapmap_fr.ts @@ -306,7 +306,7 @@ QGuiApplication - + QT_LAYOUT_DIRECTION Translate this string to the string 'LTR' in left-to-right languages or to 'RTL' in right-to-left languages (such as Hebrew and Arabic) to get proper widget layout. LTR @@ -315,12 +315,12 @@ QObject - + Initiating program... Lancement du logiciel... - + Done. Terminé. @@ -1039,7 +1039,7 @@ Source - + Syphon Syphon @@ -1127,6 +1127,127 @@ MapMap utilise SDL, qui reçoit les manettes de jeu, sous cette licence : + + mmp::AutoMapScan + + + Step out of the picture and do not move + Sortez du champ et ne bougez plus + + + + The camera changed the size of its images during the scan. + La caméra a changé la taille de ses images pendant le relevé. + + + + The camera does not see the projection. Point it at what the projector lights, and darken the room. + La caméra ne voit pas la projection. Tournez-la vers ce que le projecteur éclaire, et assombrissez la salle. + + + + The camera sends no images. + La caméra n'envoie aucune image. + + + + The image of the camera did not settle within %1 seconds: something moves in the picture. + L'image de la caméra ne s'est pas stabilisée en %1 secondes : quelque chose bouge dans le champ. + + + + mmp::AutoMappingDialog + + + Auto-Mapping + Calage automatique + + + + Simulated scene (--auto-mapping-simulation) + Scène simulée (--auto-mapping-simulation) + + + + %1 - %2 × %3 + %1 - %2 × %3 + + + + Place the camera next to the projector, so that it sees everything the projector lights. Nobody in the picture, and darken the room. +After the scan, do not touch the zoom, the focus or the framing of the projector: the image would no longer match. + Placez la caméra à côté du projecteur, pour qu'elle voie tout ce qu'il éclaire. Personne dans le champ, et la salle assombrie. +Après le relevé, ne touchez plus au zoom, à la mise au point ni au cadrage du projecteur : l'image ne correspondrait plus. + + + + Skip the finest stripes (faster, for a blurry camera, but less precise) + Sauter les rayures les plus fines (plus rapide, pour une caméra floue, mais moins précis) + + + + Start + Lancer + + + + Camera: + Caméra : + + + + Projector screen: + Écran du projecteur : + + + + No camera is connected. + Aucune caméra n'est branchée. + + + + %1 images, about %2 seconds. + %1 images, environ %2 secondes. + + + + The scan needs the output over the whole screen of the projector. + Le relevé a besoin de la sortie sur tout l'écran du projecteur. + + + + Scanning: do not move. + Relevé en cours : ne bougez pas. + + + + Scan cancelled. + Relevé annulé. + + + + Done: the camera saw %1 % of the output. The scene seen from the projector is under the shapes of the output editor; in red, what the camera did not see. Tools > Show Auto-Mapping Image hides it, Tools > Clear Auto-Mapping Image forgets it. + Terminé : la caméra a vu %1 % de la sortie. La scène vue depuis le projecteur est sous les formes de l'éditeur de sortie ; en rouge, ce que la caméra n'a pas vu. Outils > Montrer l'image du calage la masque, Outils > Effacer l'image du calage l'oublie. + + + + Cancel + Annuler + + + + Close + Fermer + + + + mmp::CameraFrameSource + + + No camera is connected. + Aucune caméra n'est branchée. + + mmp::ChoiceControl @@ -1732,1123 +1853,1158 @@ mmp::MainWindow - - + + Open project Ouvrir un projet - - - - + + + + MapMap files (*.%1) Fichiers MapMap (*.%1) - - + + Save project Sauvegarder le projet - - + + Import media source file Importer un média - - + + Media files (%1 %2);;All files (*) Fichiers média (%1-%2);;Tous les fichiers (*) - + Select camera Selectionner une caméra - - + + No camera available Aucune caméra disponible - - + + You can not use this feature! No camera available in your system Vous ne pouvez pas utiliser cette fonctionnalité. Aucune caméra n'est disponible sur ce système. - - - + + + MapMap MapMap - + &New &Nouveau - + Create a new project Créer un nouveau projet - + &Open… &Ouvrir… - + Open an existing project Ouvrir un projet existant - + &Save &Sauvegarder - + Save the project Sauvegarder le projet - + Save &As… S&auvegarder sous… - + Save the project as… Sauvegarder le projet sous… - + No Recents Videos Pas de vidéos récentes - + &Import Media File… &Importer un fichier média … - + Import a video or image file… Importer un fichier vidéo ou image … - + Open &Camera Device… Ajouter une source &caméra… - + Choose your camera device… Choisir la caméra… - + E&xit &Quitter - + Exit the application Quitter l'application - + &Undo Ann&uler - + &Redo &Retablir - + &About MapMap &A propos de MapMap - + Show the application's About box Afficher le dialogue "À propos de l'application" - + &Preferences… &Préférences… - + Configure preferences… Configurer les préférences… - - + + Play Lecture - - + + Pause Pause - + &Display Controls &Afficher les points de contrôle - + Display canvas controls Afficher les points de contrôle du canevas - + &Sticky Vertices &Sommets collants - + Enable sticky vertices Activer les sommets collants - + Show &Test Signal Afficher le signal de &Test - + Show Test signal Afficher le signal de Test - + Display &Undo History &Afficher l'historique des opérations - + Open Conso&le Ouvrir la conso&le - + + &Auto-Mapping… + &Calage automatique… + + + + Film stripes projected on the scene, to see it from the projector + Filmer des rayures projetées sur la scène, pour la voir depuis le projecteur + + + + &Show Auto-Mapping Image + &Montrer l'image du calage + + + + Show the scene seen from the projector under the shapes of the output + Montrer la scène vue depuis le projecteur sous les formes de la sortie + + + + &Clear Auto-Mapping Image + &Effacer l'image du calage + + + + Forget the scene seen from the projector + Oublier la scène vue depuis le projecteur + + + Display &Zoom Toolbar Afficher la barre de contrôle du &Zoom - + &Menu Bar Barre de &Menu - + Main Layout Vue normale - + Switch to the Main layout. Passer à la vue normale. - + Documentation Documentation - + &File &Fichier - + Open Recents Projects Ouvrir les projets récents - + Open Recents Videos Ouvrir les vidéo récentes - + &Edit &Édition - + + &Tools + &Outils + + + &Window &Fenêtre - + &Help &Aide - + &Toolbar &Barre de menu - + The document has been modified. Do you want to save your changes? Ce document a été modifié. Voulez-vous sauvegarder vos changements? - - + + Error reading mapping project file Erreur de lecture du projet - - + + Cannot read file %1: %2. Impossible de lire le fichier %1: %2. - + File loaded Fichier chargé - - + + Error saving mapping project Erreur en sauvegardant le fichier du projet - + Cannot write file %1: %2. Impossible d'écrire le fichier %1 : %2. - + Cannot rename temporary file to %1. Impossible de renommer le fichier temporaire en %1. - + File saved Fichier sauvegardé - + Untitled Sans titre - + %1[*] - %2 %1[*] - %2 - - + + MapMap Project Projet MapMap - - - + + + &%1 %2 &%1 %2 - + Clear List Vider la liste - + No Recents Projects Aucun projet récent - + %1 - %2x%3 %1 - %2x%3 - + File imported Fichier importé - + Warning Avertissement - + The following file is not supported: %1 Le fichier suivant n'est pas supporté: %1 - + Cannot load movie Impossible de charger le film - - + + %1 files (%2) Fichiers %1 (%2) - + Undo history Historique - + Camera device Dispositif caméra - + Report an issue Rapporter un problème - + Submit feedback via email Soumettre une remarque par courriel - + &View &Apparence - + Unable to use file %1. The original file is not found. Please locate. Impossible d'utiliser le fichier %1. Le fichier original est introuvable. Prière de le localiser. - - + + Locate file %1 Localiser le fichier %1 - + - Primary - Principal - + Used by %1 layers: changing it changes them all. Utilisé par %1 calques : le modifier les modifie tous. - + Replace effect Remplacer l'effet - - + + Replace Effect Remplacer l'effet - - - + + + Add Effect Ajouter un effet - + Save over a project of a later version? Écraser un projet d'une version plus récente? - + %1 was saved by a later version of MapMap, in the format %2. This version keeps what it does not know, but the later version may not open the project as it was. Save over it anyway? %1 a été sauvegardé par une version plus récente de MapMap, au format %2. Cette version garde ce qu'elle ne connaît pas, mais la version plus récente pourrait ne pas ouvrir le projet tel qu'il était. L'écraser quand même? - + Learning MIDI for %1: press a pad for "%2", or turn a knob to move it both ways. Escape stops, Delete removes the MIDI controls of the point. Apprentissage MIDI pour %1 : appuyez sur un pad pour « %2 », ou tournez un bouton pour le déplacer dans les deux sens. Échap arrête, Suppr retire les contrôles MIDI du point. - + Learning keys for %1: press a key for "%2". Escape stops, Delete removes the keys of the point. Apprentissage des touches pour %1 : appuyez sur une touche pour « %2 ». Échap arrête, Suppr retire les touches du point. - + Learning MIDI: move a control or press a pad for %1. Delete removes its MIDI control. Apprentissage MIDI : bougez un contrôle ou appuyez sur un pad pour %1. Suppr retire son contrôle MIDI. - + Learning MIDI: click a control outlined in blue, then move a control of the MIDI device. The MIDI controls already learned act. Apprentissage MIDI : cliquez sur un contrôle entouré de bleu, puis bougez un contrôle de l'appareil MIDI. Les contrôles MIDI déjà appris agissent. - + Learning keys: press a key for %1. Delete removes its key. Apprentissage des touches : appuyez sur une touche pour %1. Suppr retire sa touche. - + Learning keys: click a control outlined in blue, then press a key. Learned keys do not act until learning stops (Escape). Apprentissage des touches : cliquez sur un contrôle entouré de bleu, puis appuyez sur une touche. Les touches apprises n'agissent qu'à la fin de l'apprentissage (Échap). - - + + %1: %2 %1 : %2 - + Move a MIDI control for %1. Delete removes its MIDI control, Escape stops learning. Bougez un contrôle MIDI pour %1. Suppr retire son contrôle MIDI, Échap arrête l'apprentissage. - + MIDI learn: click a control outlined in blue, then move a control of the MIDI device. Escape stops learning. Apprentissage MIDI : cliquez sur un contrôle entouré de bleu, puis bougez un contrôle de l'appareil MIDI. Échap arrête l'apprentissage. - + Press a key for %1. Delete removes its key, Escape stops learning. Appuyez sur une touche pour %1. Suppr retire sa touche, Échap arrête l'apprentissage. - + Keyboard learn: click a control outlined in blue, then press a key. Escape stops learning. Apprentissage clavier : cliquez sur un contrôle entouré de bleu, puis appuyez sur une touche. Échap arrête l'apprentissage. - + Learning MIDI: move a control of the MIDI device, not a key. Edit > Keyboard Learn learns keys. Apprentissage MIDI : bougez un contrôle de l'appareil MIDI, pas une touche. Édition > Apprentissage clavier apprend les touches. - + %1 drives %2. Press Escape to stop learning: %1 then acts. %1 commande %2. Appuyez sur Échap pour arrêter l'apprentissage : %1 agira alors. - + Click a control outlined in blue first, then press %1. Cliquez d'abord sur un contrôle entouré de bleu, puis appuyez sur %1. - + %1 is already the shortcut of %2: choose another key. %1 sert déjà (%2) : choisissez une autre touche. - - + + %1 → %2 %1 → %2 - + %1 → %2: %3 %1 → %2 : %3 - + MIDI control removed from %1 Contrôle MIDI retiré de %1 - + Key removed from %1 Touche retirée de %1 - + Click a control outlined in blue first, then move %1. Cliquez d'abord sur un contrôle entouré de bleu, puis bougez %1. - + Input Editor: %1% Éditeur d'entrée : %1 % - + Output Editor: %1% Éditeur de sortie : %1 % - + Stop Learning Arrêter l'apprentissage - + Stop learning (Escape) Arrêter l'apprentissage (Échap) - - + + Add &Generator Ajouter un &générateur - + Add a generator Ajouter un générateur - + Remove Effect Retirer l'effet - + Remove the selected effect Retirer l'effet sélectionné - + Solo layer item Calque en solo - + Rotate 90° CW Pivoter de 90° dans le sens horaire - + Rotate 90° clockwise. In the input view, rotates the image inside the layer. Pivoter de 90° dans le sens horaire. Dans la vue d’entrée, fait pivoter l’image à l’intérieur du calque. - + Rotate 90° CCW Pivoter de 90° dans le sens antihoraire - + Rotate 90° counterclockwise. In the input view, rotates the image inside the layer. Pivoter de 90° dans le sens antihoraire. Dans la vue d’entrée, fait pivoter l’image à l’intérieur du calque. - + Rotate 180° Pivoter de 180° - + Rotate 180°. In the input view, rotates the image inside the layer. Pivoter de 180°. Dans la vue d’entrée, fait pivoter l’image à l’intérieur du calque. - + Flip horizontally. In the input view, flips the image inside the layer. Retourner horizontalement. Dans la vue d’entrée, retourne l’image à l’intérieur du calque. - + Flip vertically. In the input view, flips the image inside the layer. Retourner verticalement. Dans la vue d’entrée, retourne l’image à l’intérieur du calque. - - + + Raise Monter - - + + Lower Descendre - + Raise to Top Monter tout en haut - + Raise to top Monter tout en haut - + Lower to Bottom Descendre tout en bas - + Lower to bottom Descendre tout en bas - + &Keyboard Learn Apprentissage &clavier - + Link keys of the keyboard to settings: click a control, then press a key Lier des touches du clavier à des réglages : cliquez sur un contrôle, puis appuyez sur une touche - + &MIDI Learn Apprentissage &MIDI - + Link controls and notes of a MIDI device to settings: click a control, then move a MIDI control Lier des contrôles et des notes d'un appareil MIDI à des réglages : cliquez sur un contrôle, puis bougez un contrôle MIDI - + Learned K&eys Active &Touches apprises actives - + Turn the learned keys off while typing for something else, and on again Désactiver les touches apprises le temps de taper autre chose, puis les réactiver - + &Publish Syphon Output &Publier la sortie Syphon - + Publish the output composition as a Syphon server other apps can receive Publier la composition de sortie comme un serveur Syphon que d'autres applications peuvent recevoir - + &Links Lie&ns - + List the keys linked to settings Lister les touches liées aux réglages - - + + Zoom In Agrandir - - + + Zoom Out Réduire - + Remove this source and all its associated layers? Supprimer cette source et tous les calques associés ? - + Syphon source added Source Syphon ajoutée - + Input Editor Éditeur d'entrée - + Output Editor Éditeur de sortie - + Library Bibliothèque - + Layers Calques - + Add &Syphon Source… Ajouter une source &Syphon… - + Receive live video from another application via Syphon… Recevoir de la vidéo en direct d'une autre application via Syphon… - + Duplicate Layer Dupliquer le calque - + Duplicate layer item Dupliquer un élément du calque - + Delete Layer Supprimer le calque - + Delete layer item Supprimer un élément du calque - + Rename Layer Renommer le calque - + Rename layer item Renommer un élément du calque - + Lock Layer Vérouiller le calque - + Lock layer item Vérouiller un élément du calque - + Hide Layer Cacher le calque - + Hide layer item Cacher un élément du calque - + Solo Layer Calque solo - + Delete Source Supprimer la source - + Delete source item Supprimer un élément de la source - + Rename Source Renommer la source - + Rename source item Renommer un élément de la source - + Add &Mesh Layer Ajouter un calque &maillage - + Add mesh layer Ajouter un calque de maillage - + Add &Triangle Layer Ajouter un calque &triangle - + Add triangle layer Ajouter un calque triangulaire - + Add &Ellipse Layer Ajouter un calque &ellipse - + Add ellipse layer Ajouter un calque elliptique - + &Display Controls of Layers of a Source Commandes d'&affichage des calques d'une source - + Display all canvas controls related to current source Afficher tous les contrôles de la toile liés à la source actuelle - + Input editor Layout Vue de l'éditeur d'entrée - + Switch to the Input editor Layout. Passer à la vue de l'éditeur d'entrée. - + Output Editor Layout Vue de l'éditeur de sortie - + Switch to the Output Editors Layout. Passer à la vue de l'éditeur de sortie. - + Import New Media Importer un nouveau média - + Import new media file if not exists on the list Importer un nouveau média si le fichier n'existe pas sur la liste - - + + Restart Redémarrer - + Actual Pixels (1:1) Taille réelle (1:1) - + Show one image pixel per screen pixel Afficher un pixel de l'image par pixel de l'écran - + Fit To View (100%) Ajuster à la vue (100 %) - + Show the whole image or output frame Afficher toute l'image ou tout le cadre de sortie - + Output &Resolution... &Résolution de sortie... - + Choose the size of the output frame Choisir la taille du cadre de sortie - + Professional services && custom development… Services professionnels && développement sur mesure… - + Hire Art Plus Code for video mapping installations, custom features, integration and training Engagez Art Plus Code pour des installations de mapping vidéo, des fonctionnalités sur mesure, de l'intégration et de la formation - + Support the project (donate)… Soutenir le projet (faire un don)… - + Help fund MapMap's ongoing development Aidez à financer le développement continu de MapMap - + &Keyboard shortcuts &Raccourcis clavier - + Welcome to %1… Bienvenue dans %1… - + Change Layer Source Changer la source du calque - + Flip Horizontally Retourner horizontalement - + Flip Vertically Retourner verticalement - + The output screen %1 is disconnected: the output is hidden until it comes back. L'écran de sortie %1 est débranché : la sortie est cachée jusqu'à son retour. - + The output screen %1 is back. L'écran de sortie %1 est revenu. - + &Hide Output &Cacher la sortie - + Output in a &Window Sortie dans une &fenêtre - + Output &Fills a Screen La sortie &couvre un écran - + Output Sortie - + Output Fills a Screen (%1). The arrow chooses how and where the output is shown. La sortie couvre un écran (%1). La flèche choisit comment et où montrer la sortie. - + The learned keys act again. Les touches apprises agissent de nouveau. - + The learned keys are off: they do nothing until turned on again. Les touches apprises sont désactivées : elles ne font rien jusqu'à ce qu'on les réactive. - + Learned keys: on Touches apprises : actives - + Learned keys: off Touches apprises : inactives - + Edit > Learned Keys Active (%1) turns them on and off. Édition > Touches apprises actives (%1) les active et les désactive. - + Cannot read %1: %2 Impossible de lire %1 : %2 - + Project of a later version Projet d'une version plus récente - + This project was saved by a later version of MapMap, in the format %1; this version writes %2. What this version does not know is kept, but may not work as the later version intended. Ce projet a été sauvegardé par une version plus récente de MapMap, au format %1; cette version écrit %2. Ce que cette version ne connaît pas est conservé, mais pourrait ne pas fonctionner comme la version plus récente le prévoyait. - + Project opened with missing entries Projet ouvert avec des entrées manquantes - + MapMap skipped these project entries: %1 MapMap a ignoré ces entrées du projet : %1 - + Sources this version cannot open Sources que cette version ne peut pas ouvrir - + This project has sources of types this version of MapMap cannot open: %1. They are kept with their layers, which show a "missing" image, and saved as they are. Ce projet a des sources de types que cette version de MapMap ne peut pas ouvrir : %1. Elles sont conservées avec leurs calques, qui affichent une image « manquante », et sauvegardées telles quelles. - - + + File loaded: %n link(s) active Fichier chargé : %n lien actif @@ -2856,7 +3012,7 @@ Elles sont conservées avec leurs calques, qui affichent une image « manqu - + , %n kept but not usable here , %n conservé mais inutilisable ici @@ -2864,82 +3020,82 @@ Elles sont conservées avec leurs calques, qui affichent une image « manqu - + %1 added Source ajoutée : %1 - + Output %1 × %2 Sortie %1 × %2 - + Output Editor (%1 × %2) Éditeur de sortie (%1 × %2) - + Output Resolution Résolution de sortie - + Size of the output frame, usually the resolution of the projector. The output window scales it to fill the output screen. Taille du cadre de sortie, en général la résolution du projecteur. La fenêtre de sortie le met à l'échelle pour remplir l'écran de sortie. - + Scale the shapes to keep them in place in the frame Mettre les formes à l'échelle pour les garder en place dans le cadre - + %1 %2 × %3 %1 %2 × %3 - + %1 - disconnected %1 - débranché - + Output Fills a Screen La sortie couvre un écran - + The output will cover this screen. Press Esc to bring MapMap back. La sortie va couvrir cet écran. Appuyez sur Échap pour faire revenir MapMap. - + Cover the Screen Couvrir l'écran - + Don't ask again Ne plus demander - + &Output &Sortie - + Cue %1 Repère %1 - + Cue %1 — %2 Repère %1 — %2 - + %1 set at %2 %1 posé à %2 From 4e464f934d9bf21ccb30b006eb2bd48b59c69732 Mon Sep 17 00:00:00 2001 From: Alexandre Quessy Date: Fri, 4 Dec 2026 00:44:05 -0500 Subject: [PATCH 5/6] Hide the pointer over the images of the automatic mapping On macOS, a blank cursor does not hide the pointer when the output window comes under a still mouse, as it does when a scan starts: the camera would film it. It is now hidden again at each image, as long as it is over the output. --- src/gui/OutputGLCanvas.cpp | 29 +++++++++++++++++++++++++++++ src/gui/OutputGLCanvas.h | 3 +++ 2 files changed, 32 insertions(+) diff --git a/src/gui/OutputGLCanvas.cpp b/src/gui/OutputGLCanvas.cpp index c343d4fb..1951dcf1 100644 --- a/src/gui/OutputGLCanvas.cpp +++ b/src/gui/OutputGLCanvas.cpp @@ -128,10 +128,39 @@ void OutputGLCanvas::setSyphonServerName(const QString& name) void OutputGLCanvas::setPatternImage(const QImage& image) { + const bool wasShown = !_patternImage.isNull(); _patternImage = image; + if (!image.isNull()) + _hidePointerOverPattern(); + else if (wasShown) + { + // As before the images: the cursor of the window, unless the mouse is idle. + if (_editingIsVisible) + { + viewport()->unsetCursor(); +#ifdef Q_OS_MACOS + setMacCursorHiddenUntilMouseMoves(false); +#endif + } + else + viewport()->setCursor(Qt::BlankCursor); + } viewport()->update(); } +void OutputGLCanvas::_hidePointerOverPattern() +{ + // The camera would film the pointer over the images. + viewport()->setCursor(Qt::BlankCursor); +#ifdef Q_OS_MACOS + // A blank cursor is not enough when the window came under a still mouse: + // hide it again at each image, as long as it is over the output. + const QPoint pointer = QCursor::pos(); + if (window()->frameGeometry().contains(pointer)) + setMacCursorHiddenUntilMouseMoves(true); +#endif +} + void OutputGLCanvas::_drawPatternImage(QPainter* painter) { // In window pixels, over black, without smoothing: the edges of the finest diff --git a/src/gui/OutputGLCanvas.h b/src/gui/OutputGLCanvas.h index 0d75c464..f164f262 100644 --- a/src/gui/OutputGLCanvas.h +++ b/src/gui/OutputGLCanvas.h @@ -111,6 +111,9 @@ class OutputGLCanvas: public MapperGLCanvas // Draws the image of the automatic mapping over the output frame. void _drawPatternImage(QPainter* painter); + // Hides the mouse pointer while it is over the images of the automatic mapping. + void _hidePointerOverPattern(); + bool _displayCrosshair; bool _displayTestSignal; // Shown in place of everything else while not null (see setPatternImage()). From ef52fe2bea5715085f07228827889b297e8d054c Mon Sep 17 00:00:00 2001 From: Alexandre Quessy Date: Fri, 4 Dec 2026 00:47:16 -0500 Subject: [PATCH 6/6] Remove the light outline around the output covering a screen on macOS The shadow of a window draws a thin light outline around it, even without a frame: around the whole screen when the output covers it. The output has no shadow while it covers a screen, and gets it back as an ordinary window. --- src/gui/MacWindowLevel.h | 4 +++- src/gui/MacWindowLevel.mm | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/gui/MacWindowLevel.h b/src/gui/MacWindowLevel.h index a755f756..a8af4d6e 100644 --- a/src/gui/MacWindowLevel.h +++ b/src/gui/MacWindowLevel.h @@ -27,7 +27,9 @@ namespace mmp { /** * Puts a window above the menu bar and the Dock of macOS, or back among the * other windows. Qt has no way to do it: a window without a frame that - * covers a screen would stay below the menu bar of that screen. + * covers a screen would stay below the menu bar of that screen. Above the + * menu bar, the window has no shadow, which would draw a light outline + * around the screen. * * @param window a window that is shown. * @param above true to put it above the menu bar and the Dock. diff --git a/src/gui/MacWindowLevel.mm b/src/gui/MacWindowLevel.mm index 8eebe51d..bec31844 100644 --- a/src/gui/MacWindowLevel.mm +++ b/src/gui/MacWindowLevel.mm @@ -43,6 +43,9 @@ void setMacWindowAboveMenuBar(QWidget* window, bool above) else behavior &= ~NSWindowCollectionBehaviorFullScreenAuxiliary; [nsWindow setCollectionBehavior:behavior]; + // The shadow of a window draws a thin light outline around it: around the + // whole screen, on a projector. + [nsWindow setHasShadow:(above ? NO : YES)]; } }