global formatting

pull/3471/head
kallaballa 2 years ago
parent a6fb2c9124
commit d129f28d42
  1. 8
      src/common/detail/clvacontext.cpp
  2. 4
      src/common/detail/clvacontext.hpp
  3. 60
      src/common/detail/framebuffercontext.cpp
  4. 13
      src/common/detail/framebuffercontext.hpp
  5. 5
      src/common/detail/nanovgcontext.cpp
  6. 9
      src/common/detail/nanovgcontext.hpp
  7. 49
      src/common/dialog.cpp
  8. 5
      src/common/dialog.hpp
  9. 18
      src/common/formhelper.cpp
  10. 16
      src/common/formhelper.hpp
  11. 79
      src/common/nvg.cpp
  12. 199
      src/common/nvg.hpp
  13. 5
      src/common/sink.cpp
  14. 8
      src/common/source.cpp
  15. 61
      src/common/util.cpp
  16. 10
      src/common/util.hpp
  17. 183
      src/common/viz2d.cpp
  18. 15
      src/common/viz2d.hpp

@ -11,25 +11,25 @@ namespace cv {
namespace viz { namespace viz {
namespace detail { namespace detail {
CLVAContext::CLVAContext(FrameBufferContext &clglContext) : CLVAContext::CLVAContext(FrameBufferContext& clglContext) :
clglContext_(clglContext) { clglContext_(clglContext) {
} }
void CLVAContext::setVideoFrameSize(const cv::Size& sz) { void CLVAContext::setVideoFrameSize(const cv::Size& sz) {
if(videoFrameSize_ != cv::Size(0,0)) if (videoFrameSize_ != cv::Size(0, 0))
assert(videoFrameSize_ == sz || "Input and output video sizes don't match"); assert(videoFrameSize_ == sz || "Input and output video sizes don't match");
videoFrameSize_ = sz; videoFrameSize_ = sz;
} }
cv::Size CLVAContext::getVideoFrameSize() { cv::Size CLVAContext::getVideoFrameSize() {
assert(videoFrameSize_ == cv::Size(0,0) || "Video frame size not initialized"); assert(videoFrameSize_ == cv::Size(0, 0) || "Video frame size not initialized");
return videoFrameSize_; return videoFrameSize_;
} }
bool CLVAContext::capture(std::function<void(cv::UMat&)> fn) { bool CLVAContext::capture(std::function<void(cv::UMat&)> fn) {
{ {
if(!context_ .empty()) { if (!context_.empty()) {
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
CLExecScope_t scope(context_); CLExecScope_t scope(context_);
#endif #endif

@ -16,7 +16,7 @@ namespace detail {
class CLVAContext { class CLVAContext {
friend class cv::viz::Viz2D; friend class cv::viz::Viz2D;
CLExecContext_t context_; CLExecContext_t context_;
FrameBufferContext &clglContext_; FrameBufferContext& clglContext_;
cv::UMat frameBuffer_; cv::UMat frameBuffer_;
cv::UMat videoFrame_; cv::UMat videoFrame_;
cv::UMat rgbBuffer_; cv::UMat rgbBuffer_;
@ -24,7 +24,7 @@ class CLVAContext {
cv::Size videoFrameSize_; cv::Size videoFrameSize_;
CLExecContext_t getCLExecContext(); CLExecContext_t getCLExecContext();
public: public:
CLVAContext(FrameBufferContext &fbContext); CLVAContext(FrameBufferContext& fbContext);
cv::Size getVideoFrameSize(); cv::Size getVideoFrameSize();
void setVideoFrameSize(const cv::Size& sz); void setVideoFrameSize(const cv::Size& sz);
bool capture(std::function<void(cv::UMat&)> fn); bool capture(std::function<void(cv::UMat&)> fn);

@ -19,7 +19,7 @@ FrameBufferContext::FrameBufferContext(const cv::Size& frameBufferSize) :
glewExperimental = true; glewExperimental = true;
glewInit(); glewInit();
try { try {
if(is_cl_gl_sharing_supported()) if (is_cl_gl_sharing_supported())
cv::ogl::ocl::initializeContextFromGL(); cv::ogl::ocl::initializeContextFromGL();
else else
clglSharing_ = false; clglSharing_ = false;
@ -39,13 +39,17 @@ FrameBufferContext::FrameBufferContext(const cv::Size& frameBufferSize) :
GL_CHECK(glBindTexture(GL_TEXTURE_2D, textureID_)); GL_CHECK(glBindTexture(GL_TEXTURE_2D, textureID_));
texture_ = new cv::ogl::Texture2D(frameBufferSize_, cv::ogl::Texture2D::RGBA, textureID_); texture_ = new cv::ogl::Texture2D(frameBufferSize_, cv::ogl::Texture2D::RGBA, textureID_);
GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1));
GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, frameBufferSize_.width, frameBufferSize_.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); GL_CHECK(
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, frameBufferSize_.width, frameBufferSize_.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0));
GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, renderBufferID_)); GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, renderBufferID_));
GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, frameBufferSize_.width, frameBufferSize_.height)); GL_CHECK(
GL_CHECK(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderBufferID_)); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, frameBufferSize_.width, frameBufferSize_.height));
GL_CHECK(
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderBufferID_));
GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureID_, 0)); GL_CHECK(
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureID_, 0));
assert(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); assert(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
context_ = CLExecContext_t::getCurrent(); context_ = CLExecContext_t::getCurrent();
@ -55,8 +59,8 @@ FrameBufferContext::FrameBufferContext(const cv::Size& frameBufferSize) :
FrameBufferContext::~FrameBufferContext() { FrameBufferContext::~FrameBufferContext() {
end(); end();
glDeleteTextures(1, &textureID_); glDeleteTextures(1, &textureID_);
glDeleteRenderbuffers( 1, &renderBufferID_); glDeleteRenderbuffers(1, &renderBufferID_);
glDeleteFramebuffers( 1, &frameBufferID_); glDeleteFramebuffers(1, &frameBufferID_);
} }
cv::Size FrameBufferContext::getSize() { cv::Size FrameBufferContext::getSize() {
@ -82,25 +86,24 @@ CLExecContext_t& FrameBufferContext::getCLExecContext() {
} }
#endif #endif
void FrameBufferContext::blitFrameBufferToScreen(const cv::Rect& viewport, const cv::Size& windowSize, bool stretch) { void FrameBufferContext::blitFrameBufferToScreen(const cv::Rect& viewport,
const cv::Size& windowSize, bool stretch) {
GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferID_)); GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, frameBufferID_));
GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0)); GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0));
GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0)); GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0));
GL_CHECK(glBlitFramebuffer( GL_CHECK(
viewport.x, viewport.y, viewport.x + viewport.width, viewport.y + viewport.height, glBlitFramebuffer( viewport.x, viewport.y, viewport.x + viewport.width, viewport.y + viewport.height, stretch ? 0 : windowSize.width - frameBufferSize_.width, stretch ? 0 : windowSize.height - frameBufferSize_.height, stretch ? windowSize.width : frameBufferSize_.width, stretch ? windowSize.height : frameBufferSize_.height, GL_COLOR_BUFFER_BIT, GL_NEAREST));
stretch ? 0 : windowSize.width - frameBufferSize_.width,
stretch ? 0 : windowSize.height - frameBufferSize_.height,
stretch ? windowSize.width : frameBufferSize_.width,
stretch ? windowSize.height : frameBufferSize_.height, GL_COLOR_BUFFER_BIT, GL_NEAREST));
} }
void FrameBufferContext::begin() { void FrameBufferContext::begin() {
GL_CHECK(glGetIntegerv( GL_VIEWPORT, viewport_ )); GL_CHECK(glGetIntegerv( GL_VIEWPORT, viewport_ ));
GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, frameBufferID_)); GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, frameBufferID_));
GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, renderBufferID_)); GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, renderBufferID_));
GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderBufferID_)); GL_CHECK(
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderBufferID_));
GL_CHECK(glBindTexture(GL_TEXTURE_2D, textureID_)); GL_CHECK(glBindTexture(GL_TEXTURE_2D, textureID_));
GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureID_, 0)); GL_CHECK(
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureID_, 0));
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE); assert(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
} }
@ -123,25 +126,16 @@ void FrameBufferContext::download(cv::UMat& m) {
void FrameBufferContext::upload(const cv::UMat& m) { void FrameBufferContext::upload(const cv::UMat& m) {
cv::Mat tmp = m.getMat(cv::ACCESS_READ); cv::Mat tmp = m.getMat(cv::ACCESS_READ);
assert(tmp.data != nullptr); assert(tmp.data != nullptr);
GL_CHECK(glTexSubImage2D( GL_CHECK(
GL_TEXTURE_2D, glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, tmp.cols, tmp.rows, GL_RGBA, GL_UNSIGNED_BYTE, tmp.data));
0,
0,
0,
tmp.cols,
tmp.rows,
GL_RGBA,
GL_UNSIGNED_BYTE,
tmp.data)
);
tmp.release(); tmp.release();
} }
void FrameBufferContext::acquireFromGL(cv::UMat &m) { void FrameBufferContext::acquireFromGL(cv::UMat& m) {
if(clglSharing_) { if (clglSharing_) {
GL_CHECK(cv::ogl::convertFromGLTexture2D(getTexture2D(), m)); GL_CHECK(cv::ogl::convertFromGLTexture2D(getTexture2D(), m));
} else { } else {
if(m.empty()) if (m.empty())
m.create(getSize(), CV_8UC4); m.create(getSize(), CV_8UC4);
download(m); download(m);
GL_CHECK(glFlush()); GL_CHECK(glFlush());
@ -151,13 +145,13 @@ void FrameBufferContext::acquireFromGL(cv::UMat &m) {
cv::flip(m, m, 0); cv::flip(m, m, 0);
} }
void FrameBufferContext::releaseToGL(cv::UMat &m) { void FrameBufferContext::releaseToGL(cv::UMat& m) {
//FIXME //FIXME
cv::flip(m, m, 0); cv::flip(m, m, 0);
if(clglSharing_) { if (clglSharing_) {
GL_CHECK(cv::ogl::convertToGLTexture2D(m, getTexture2D())); GL_CHECK(cv::ogl::convertToGLTexture2D(m, getTexture2D()));
} else { } else {
if(m.empty()) if (m.empty())
m.create(getSize(), CV_8UC4); m.create(getSize(), CV_8UC4);
upload(m); upload(m);
GL_CHECK(glFlush()); GL_CHECK(glFlush());

@ -50,13 +50,15 @@ class FrameBufferContext {
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
CLExecContext_t& getCLExecContext(); CLExecContext_t& getCLExecContext();
#endif #endif
void blitFrameBufferToScreen(const cv::Rect& viewport, const cv::Size& windowSize, bool stretch = false); void blitFrameBufferToScreen(const cv::Rect& viewport, const cv::Size& windowSize,
bool stretch = false);
public: public:
class FrameBufferScope { class FrameBufferScope {
FrameBufferContext& ctx_; FrameBufferContext& ctx_;
cv::UMat& m_; cv::UMat& m_;
public: public:
FrameBufferScope(FrameBufferContext& ctx, cv::UMat& m) : ctx_(ctx), m_(m) { FrameBufferScope(FrameBufferContext& ctx, cv::UMat& m) :
ctx_(ctx), m_(m) {
ctx_.acquireFromGL(m_); ctx_.acquireFromGL(m_);
} }
@ -68,7 +70,8 @@ public:
class GLScope { class GLScope {
FrameBufferContext& ctx_; FrameBufferContext& ctx_;
public: public:
GLScope(FrameBufferContext& ctx) : ctx_(ctx) { GLScope(FrameBufferContext& ctx) :
ctx_(ctx) {
ctx_.begin(); ctx_.begin();
} }
@ -86,8 +89,8 @@ protected:
void end(); void end();
void download(cv::UMat& m); void download(cv::UMat& m);
void upload(const cv::UMat& m); void upload(const cv::UMat& m);
void acquireFromGL(cv::UMat &m); void acquireFromGL(cv::UMat& m);
void releaseToGL(cv::UMat &m); void releaseToGL(cv::UMat& m);
cv::UMat frameBuffer_; cv::UMat frameBuffer_;
cv::ogl::Texture2D* texture_ = nullptr; cv::ogl::Texture2D* texture_ = nullptr;
}; };

@ -10,7 +10,7 @@
namespace cv { namespace cv {
namespace viz { namespace viz {
namespace detail { namespace detail {
NanoVGContext::NanoVGContext(Viz2D &v2d, NVGcontext *context, FrameBufferContext &fbContext) : NanoVGContext::NanoVGContext(Viz2D& v2d, NVGcontext* context, FrameBufferContext& fbContext) :
v2d_(v2d), context_(context), clglContext_(fbContext) { v2d_(v2d), context_(context), clglContext_(fbContext) {
//FIXME workaround for first frame color glitch //FIXME workaround for first frame color glitch
cv::UMat tmp; cv::UMat tmp;
@ -23,8 +23,7 @@ void NanoVGContext::render(std::function<void(const cv::Size&)> fn) {
#endif #endif
FrameBufferContext::GLScope glScope(clglContext_); FrameBufferContext::GLScope glScope(clglContext_);
NanoVGContext::Scope nvgScope(*this); NanoVGContext::Scope nvgScope(*this);
cv::viz::nvg::detail::NVG::setCurrentContext(context_), cv::viz::nvg::detail::NVG::setCurrentContext(context_), fn(clglContext_.getSize());
fn(clglContext_.getSize());
} }
void push() { void push() {

@ -23,13 +23,14 @@ namespace viz {
namespace detail { namespace detail {
class NanoVGContext { class NanoVGContext {
Viz2D& v2d_; Viz2D& v2d_;
NVGcontext *context_; NVGcontext* context_;
FrameBufferContext &clglContext_; FrameBufferContext& clglContext_;
public: public:
class Scope { class Scope {
NanoVGContext& ctx_; NanoVGContext& ctx_;
public: public:
Scope(NanoVGContext& ctx) : ctx_(ctx) { Scope(NanoVGContext& ctx) :
ctx_(ctx) {
ctx_.begin(); ctx_.begin();
} }
@ -37,7 +38,7 @@ public:
ctx_.end(); ctx_.end();
} }
}; };
NanoVGContext(Viz2D& v2d, NVGcontext *context, FrameBufferContext &fbContext); NanoVGContext(Viz2D& v2d, NVGcontext* context, FrameBufferContext& fbContext);
void render(std::function<void(const cv::Size&)> fn); void render(std::function<void(const cv::Size&)> fn);
private: private:
void begin(); void begin();

@ -10,11 +10,13 @@
namespace cv { namespace cv {
namespace viz { namespace viz {
std::function<bool(Dialog*, Dialog*)> Dialog::viz2DWin_Xcomparator([](Dialog* lhs, Dialog* rhs) {
return lhs->position()[0] < rhs->position()[0];
});
std::set<Dialog*, decltype(Dialog::viz2DWin_Xcomparator)> Dialog::all_windows_xsorted_(
viz2DWin_Xcomparator);
std::function<bool(Dialog*, Dialog*)> Dialog::viz2DWin_Xcomparator([](Dialog* lhs, Dialog* rhs){ return lhs->position()[0] < rhs->position()[0]; }); Dialog::Dialog(nanogui::Screen* screen, int x, int y, const string& title) :
std::set<Dialog*, decltype(Dialog::viz2DWin_Xcomparator)> Dialog::all_windows_xsorted_(viz2DWin_Xcomparator);
Dialog::Dialog(nanogui::Screen *screen, int x, int y, const string &title) :
Window(screen, title), screen_(screen), lastDragPos_(x, y) { Window(screen, title), screen_(screen), lastDragPos_(x, y) {
all_windows_xsorted_.insert(this); all_windows_xsorted_.insert(this);
oldLayout_ = new nanogui::AdvancedGridLayout( { 10, 0, 10, 0 }, { }); oldLayout_ = new nanogui::AdvancedGridLayout( { 10, 0, 10, 0 }, { });
@ -34,7 +36,7 @@ Dialog::Dialog(nanogui::Screen *screen, int x, int y, const string &title) :
this->minBtn_->set_visible(true); this->minBtn_->set_visible(true);
this->maxBtn_->set_visible(false); this->maxBtn_->set_visible(false);
for (auto *child : this->children()) { for (auto* child : this->children()) {
child->set_visible(true); child->set_visible(true);
} }
@ -48,7 +50,7 @@ Dialog::Dialog(nanogui::Screen *screen, int x, int y, const string &title) :
this->minBtn_->set_visible(false); this->minBtn_->set_visible(false);
this->maxBtn_->set_visible(true); this->maxBtn_->set_visible(true);
for (auto *child : this->children()) { for (auto* child : this->children()) {
child->set_visible(false); child->set_visible(false);
} }
this->set_size( { 0, 0 }); this->set_size( { 0, 0 });
@ -61,18 +63,18 @@ Dialog::Dialog(nanogui::Screen *screen, int x, int y, const string &title) :
this->maximizedPos_ = this->position(); this->maximizedPos_ = this->position();
for (Dialog* win : all_windows_xsorted_) { for (Dialog* win : all_windows_xsorted_) {
if(win != this && win->isMinimized()) { if (win != this && win->isMinimized()) {
x = win->position()[0]; x = win->position()[0];
gap = lastX + x; gap = lastX + x;
if(gap >= w) { if (gap >= w) {
this->set_position({lastX, screen_->height() - this->height()}); this->set_position( { lastX, screen_->height() - this->height() });
break; break;
} }
lastX = x + win->width() + 1; lastX = x + win->width() + 1;
} }
} }
if(gap < w) { if (gap < w) {
this->set_position({lastX, screen_->height() - this->height()}); this->set_position( { lastX, screen_->height() - this->height() });
} }
this->minimized_ = true; this->minimized_ = true;
}); });
@ -86,19 +88,26 @@ bool Dialog::isMinimized() {
return minimized_; return minimized_;
} }
bool Dialog::mouse_drag_event(const nanogui::Vector2i &p, const nanogui::Vector2i &rel, int button, int mods) { bool Dialog::mouse_drag_event(const nanogui::Vector2i& p, const nanogui::Vector2i& rel, int button,
int mods) {
if (m_drag && (button & (1 << GLFW_MOUSE_BUTTON_1)) != 0) { if (m_drag && (button & (1 << GLFW_MOUSE_BUTTON_1)) != 0) {
if(maxBtn_->visible()) { if (maxBtn_->visible()) {
for (auto *win : all_windows_xsorted_) { for (auto* win : all_windows_xsorted_) {
if (win != this) { if (win != this) {
if (win->contains(this->position()) if (win->contains(this->position())
|| win->contains( { this->position()[0] + this->size()[0], this->position()[1] + this->size()[1] }) || win->contains(
|| win->contains( { this->position()[0], this->position()[1] + this->size()[1] }) { this->position()[0] + this->size()[0], this->position()[1]
|| win->contains( { this->position()[0] + this->size()[0], this->position()[1] }) + this->size()[1] }) || win->contains( {
this->position()[0], this->position()[1] + this->size()[1] })
|| win->contains(
{ this->position()[0] + this->size()[0], this->position()[1] })
|| this->contains(win->position()) || this->contains(win->position())
|| this->contains( { win->position()[0] + win->size()[0], win->position()[1] + win->size()[1] }) || this->contains(
|| this->contains( { win->position()[0], win->position()[1] + win->size()[1] }) { win->position()[0] + win->size()[0], win->position()[1]
|| this->contains( { win->position()[0] + win->size()[0], win->position()[1] })) { + win->size()[1] }) || this->contains( {
win->position()[0], win->position()[1] + win->size()[1] })
|| this->contains( { win->position()[0] + win->size()[0],
win->position()[1] })) {
this->set_position(lastDragPos_); this->set_position(lastDragPos_);
return true; return true;
} }

@ -16,7 +16,7 @@ namespace viz {
using std::string; using std::string;
class Dialog : public nanogui::Window { class Dialog: public nanogui::Window {
private: private:
static std::function<bool(Dialog*, Dialog*)> viz2DWin_Xcomparator; static std::function<bool(Dialog*, Dialog*)> viz2DWin_Xcomparator;
static std::set<Dialog*, decltype(viz2DWin_Xcomparator)> all_windows_xsorted_; static std::set<Dialog*, decltype(viz2DWin_Xcomparator)> all_windows_xsorted_;
@ -32,7 +32,8 @@ public:
Dialog(nanogui::Screen* screen, int x, int y, const string& title); Dialog(nanogui::Screen* screen, int x, int y, const string& title);
virtual ~Dialog(); virtual ~Dialog();
bool isMinimized(); bool isMinimized();
bool mouse_drag_event(const nanogui::Vector2i &p, const nanogui::Vector2i &rel, int button, int mods) override; bool mouse_drag_event(const nanogui::Vector2i& p, const nanogui::Vector2i& rel, int button,
int mods) override;
}; };
} /* namespace viz2d */ } /* namespace viz2d */

@ -8,23 +8,25 @@
namespace cv { namespace cv {
namespace viz { namespace viz {
FormHelper::FormHelper(nanogui::Screen* screen) : nanogui::FormHelper(screen) { FormHelper::FormHelper(nanogui::Screen* screen) :
nanogui::FormHelper(screen) {
} }
FormHelper::~FormHelper() { FormHelper::~FormHelper() {
} }
Dialog* FormHelper::makeWindow(int x, int y, const string &title) { Dialog* FormHelper::makeWindow(int x, int y, const string& title) {
auto* win = new cv::viz::Dialog(m_screen, x, y, title); auto* win = new cv::viz::Dialog(m_screen, x, y, title);
this->set_window(win); this->set_window(win);
return win; return win;
} }
nanogui::Label* FormHelper::makeGroup(const string &label) { nanogui::Label* FormHelper::makeGroup(const string& label) {
return add_group(label); return add_group(label);
} }
nanogui::detail::FormWidget<bool>* FormHelper::makeFormVariable(const string &name, bool &v, const string &tooltip, bool visible, bool enabled) { nanogui::detail::FormWidget<bool>* FormHelper::makeFormVariable(const string& name, bool& v,
const string& tooltip, bool visible, bool enabled) {
auto var = add_variable(name, v); auto var = add_variable(name, v);
var->set_enabled(enabled); var->set_enabled(enabled);
var->set_visible(visible); var->set_visible(visible);
@ -33,13 +35,15 @@ nanogui::detail::FormWidget<bool>* FormHelper::makeFormVariable(const string &na
return var; return var;
} }
nanogui::ColorPicker* FormHelper::makeColorPicker(const string& label, nanogui::Color& color, const string& tooltip, std::function<void(const nanogui::Color)> fn, bool visible, bool enabled) { nanogui::ColorPicker* FormHelper::makeColorPicker(const string& label, nanogui::Color& color,
const string& tooltip, std::function<void(const nanogui::Color)> fn, bool visible,
bool enabled) {
auto* colorPicker = add_variable(label, color); auto* colorPicker = add_variable(label, color);
colorPicker->set_enabled(enabled); colorPicker->set_enabled(enabled);
colorPicker->set_visible(visible); colorPicker->set_visible(visible);
if (!tooltip.empty()) if (!tooltip.empty())
colorPicker->set_tooltip(tooltip); colorPicker->set_tooltip(tooltip);
if(fn) if (fn)
colorPicker->set_final_callback(fn); colorPicker->set_final_callback(fn);
return colorPicker; return colorPicker;

@ -3,7 +3,6 @@
// of this distribution and at http://opencv.org/license.html. // of this distribution and at http://opencv.org/license.html.
// Copyright Amir Hassan (kallaballa) <amir@viel-zu.org> // Copyright Amir Hassan (kallaballa) <amir@viel-zu.org>
#ifndef SRC_COMMON_FORMHELPER_HPP_ #ifndef SRC_COMMON_FORMHELPER_HPP_
#define SRC_COMMON_FORMHELPER_HPP_ #define SRC_COMMON_FORMHELPER_HPP_
#include "dialog.hpp" #include "dialog.hpp"
@ -13,7 +12,6 @@
#include <string> #include <string>
namespace cv { namespace cv {
namespace viz { namespace viz {
using std::string; using std::string;
@ -24,8 +22,11 @@ public:
Dialog* makeWindow(int x, int y, const string& title); Dialog* makeWindow(int x, int y, const string& title);
nanogui::Label* makeGroup(const string& label); nanogui::Label* makeGroup(const string& label);
nanogui::detail::FormWidget<bool>* makeFormVariable(const string &name, bool &v, const string &tooltip = "", bool visible = true, bool enabled = true); nanogui::detail::FormWidget<bool>* makeFormVariable(const string& name, bool& v,
template<typename T> nanogui::detail::FormWidget<T>* makeFormVariable(const string &name, T &v, const T &min, const T &max, bool spinnable, const string &unit, const string tooltip, bool visible = true, bool enabled = true) { const string& tooltip = "", bool visible = true, bool enabled = true);
template<typename T> nanogui::detail::FormWidget<T>* makeFormVariable(const string& name, T& v,
const T& min, const T& max, bool spinnable, const string& unit, const string tooltip,
bool visible = true, bool enabled = true) {
auto var = this->add_variable(name, v); auto var = this->add_variable(name, v);
var->set_enabled(enabled); var->set_enabled(enabled);
var->set_visible(visible); var->set_visible(visible);
@ -39,8 +40,11 @@ public:
return var; return var;
} }
nanogui::ColorPicker* makeColorPicker(const string& label, nanogui::Color& color, const string& tooltip = "", std::function<void(const nanogui::Color)> fn = nullptr, bool visible = true, bool enabled = true); nanogui::ColorPicker* makeColorPicker(const string& label, nanogui::Color& color,
template<typename T> nanogui::ComboBox* makeComboBox(const string &label, T& e, const std::vector<string>& items) { const string& tooltip = "", std::function<void(const nanogui::Color)> fn = nullptr,
bool visible = true, bool enabled = true);
template<typename T> nanogui::ComboBox* makeComboBox(const string& label, T& e,
const std::vector<string>& items) {
auto* var = this->add_variable(label, e, true); auto* var = this->add_variable(label, e, true);
var->set_items(items); var->set_items(items);
return var; return var;

@ -14,7 +14,7 @@ class NVG;
NVG* NVG::nvg_instance_ = nullptr; NVG* NVG::nvg_instance_ = nullptr;
void NVG::setCurrentContext(NVGcontext* ctx) { void NVG::setCurrentContext(NVGcontext* ctx) {
if(nvg_instance_ != nullptr) if (nvg_instance_ != nullptr)
delete nvg_instance_; delete nvg_instance_;
nvg_instance_ = new NVG(ctx); nvg_instance_ = new NVG(ctx);
} }
@ -84,11 +84,13 @@ float NVG::textBounds(float x, float y, const char* string, const char* end, flo
return nvgTextBounds(getContext(), x, y, string, end, bounds); return nvgTextBounds(getContext(), x, y, string, end, bounds);
} }
void NVG::textBoxBounds(float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds) { void NVG::textBoxBounds(float x, float y, float breakRowWidth, const char* string, const char* end,
float* bounds) {
nvgTextBoxBounds(getContext(), x, y, breakRowWidth, string, end, bounds); nvgTextBoxBounds(getContext(), x, y, breakRowWidth, string, end, bounds);
} }
int NVG::textGlyphPositions(float x, float y, const char* string, const char* end, GlyphPosition* positions, int maxPositions) { int NVG::textGlyphPositions(float x, float y, const char* string, const char* end,
GlyphPosition* positions, int maxPositions) {
return nvgTextGlyphPositions(getContext(), x, y, string, end, positions, maxPositions); return nvgTextGlyphPositions(getContext(), x, y, string, end, positions, maxPositions);
} }
@ -96,8 +98,9 @@ void NVG::textMetrics(float* ascender, float* descender, float* lineh) {
nvgTextMetrics(getContext(), ascender, descender, lineh); nvgTextMetrics(getContext(), ascender, descender, lineh);
} }
int NVG::textBreakLines(const char* string, const char* end, float breakRowWidth, TextRow* rows, int maxRows) { int NVG::textBreakLines(const char* string, const char* end, float breakRowWidth, TextRow* rows,
return nvgTextBreakLines(getContext(),string, end, breakRowWidth, rows, maxRows); int maxRows) {
return nvgTextBreakLines(getContext(), string, end, breakRowWidth, rows, maxRows);
} }
void NVG::save() { void NVG::save() {
@ -117,7 +120,7 @@ void NVG::shapeAntiAlias(int enabled) {
} }
void NVG::strokeColor(const cv::Scalar& bgra) { void NVG::strokeColor(const cv::Scalar& bgra) {
nvgStrokeColor(getContext(), nvgRGBA(bgra[2],bgra[1],bgra[0],bgra[3])); nvgStrokeColor(getContext(), nvgRGBA(bgra[2], bgra[1], bgra[0], bgra[3]));
} }
void NVG::strokePaint(Paint paint) { void NVG::strokePaint(Paint paint) {
@ -126,7 +129,7 @@ void NVG::strokePaint(Paint paint) {
} }
void NVG::fillColor(const cv::Scalar& bgra) { void NVG::fillColor(const cv::Scalar& bgra) {
nvgFillColor(getContext(), nvgRGBA(bgra[2],bgra[1],bgra[0],bgra[3])); nvgFillColor(getContext(), nvgRGBA(bgra[2], bgra[1], bgra[0], bgra[3]));
} }
void NVG::fillPaint(Paint paint) { void NVG::fillPaint(Paint paint) {
@ -278,8 +281,10 @@ void NVG::roundedRect(float x, float y, float w, float h, float r) {
nvgRoundedRect(getContext(), x, y, w, h, r); nvgRoundedRect(getContext(), x, y, w, h, r);
} }
void NVG::roundedRectVarying(float x, float y, float w, float h, float radTopLeft, float radTopRight, float radBottomRight, float radBottomLeft) { void NVG::roundedRectVarying(float x, float y, float w, float h, float radTopLeft,
nvgRoundedRectVarying(getContext(), x, y, w, h, radTopLeft, radTopRight, radBottomRight, radBottomLeft); float radTopRight, float radBottomRight, float radBottomLeft) {
nvgRoundedRectVarying(getContext(), x, y, w, h, radTopLeft, radTopRight, radBottomRight,
radBottomLeft);
} }
void NVG::ellipse(float cx, float cy, float rx, float ry) { void NVG::ellipse(float cx, float cy, float rx, float ry) {
@ -298,22 +303,32 @@ void NVG::stroke() {
nvgStroke(getContext()); nvgStroke(getContext());
} }
Paint NVG::linearGradient(float sx, float sy, float ex, float ey, const cv::Scalar& icol, const cv::Scalar& ocol) { Paint NVG::linearGradient(float sx, float sy, float ex, float ey, const cv::Scalar& icol,
NVGpaint np = nvgLinearGradient(getContext(), sx, sy, ex, ey, nvgRGBA(icol[2],icol[1],icol[0],icol[3]), nvgRGBA(ocol[2],ocol[1],ocol[0],ocol[3])); const cv::Scalar& ocol) {
NVGpaint np = nvgLinearGradient(getContext(), sx, sy, ex, ey,
nvgRGBA(icol[2], icol[1], icol[0], icol[3]),
nvgRGBA(ocol[2], ocol[1], ocol[0], ocol[3]));
return Paint(np); return Paint(np);
} }
Paint NVG::boxGradient(float x, float y, float w, float h, float r, float f, const cv::Scalar& icol, const cv::Scalar& ocol) { Paint NVG::boxGradient(float x, float y, float w, float h, float r, float f, const cv::Scalar& icol,
NVGpaint np = nvgBoxGradient(getContext(), x, y, w, h, r, f, nvgRGBA(icol[2],icol[1],icol[0],icol[3]), nvgRGBA(ocol[2],ocol[1],ocol[0],ocol[3])); const cv::Scalar& ocol) {
NVGpaint np = nvgBoxGradient(getContext(), x, y, w, h, r, f,
nvgRGBA(icol[2], icol[1], icol[0], icol[3]),
nvgRGBA(ocol[2], ocol[1], ocol[0], ocol[3]));
return Paint(np); return Paint(np);
} }
Paint NVG::radialGradient(float cx, float cy, float inr, float outr, const cv::Scalar& icol, const cv::Scalar& ocol) { Paint NVG::radialGradient(float cx, float cy, float inr, float outr, const cv::Scalar& icol,
NVGpaint np = nvgRadialGradient(getContext(), cx, cy, inr, outr, nvgRGBA(icol[2],icol[1],icol[0],icol[3]), nvgRGBA(ocol[2],ocol[1],ocol[0],ocol[3])); const cv::Scalar& ocol) {
NVGpaint np = nvgRadialGradient(getContext(), cx, cy, inr, outr,
nvgRGBA(icol[2], icol[1], icol[0], icol[3]),
nvgRGBA(ocol[2], ocol[1], ocol[0], ocol[3]));
return Paint(np); return Paint(np);
} }
Paint NVG::imagePattern(float ox, float oy, float ex, float ey, float angle, int image, float alpha) { Paint NVG::imagePattern(float ox, float oy, float ex, float ey, float angle, int image,
float alpha) {
NVGpaint np = nvgImagePattern(getContext(), ox, oy, ex, ey, angle, image, alpha); NVGpaint np = nvgImagePattern(getContext(), ox, oy, ex, ey, angle, image, alpha);
return Paint(np); return Paint(np);
} }
@ -332,7 +347,7 @@ void NVG::resetScissor() {
} }
int createFont(const char* name, const char* filename) { int createFont(const char* name, const char* filename) {
return detail::NVG::getCurrentContext()->createFont(name,filename); return detail::NVG::getCurrentContext()->createFont(name, filename);
} }
int createFontMem(const char* name, unsigned char* data, int ndata, int freeData) { int createFontMem(const char* name, unsigned char* data, int ndata, int freeData) {
@ -390,20 +405,25 @@ float textBounds(float x, float y, const char* string, const char* end, float* b
return detail::NVG::getCurrentContext()->textBounds(x, y, string, end, bounds); return detail::NVG::getCurrentContext()->textBounds(x, y, string, end, bounds);
} }
void textBoxBounds(float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds) { void textBoxBounds(float x, float y, float breakRowWidth, const char* string, const char* end,
float* bounds) {
detail::NVG::getCurrentContext()->textBoxBounds(x, y, breakRowWidth, string, end, bounds); detail::NVG::getCurrentContext()->textBoxBounds(x, y, breakRowWidth, string, end, bounds);
} }
int textGlyphPositions(float x, float y, const char* string, const char* end, GlyphPosition* positions, int maxPositions) { int textGlyphPositions(float x, float y, const char* string, const char* end,
return detail::NVG::getCurrentContext()->textGlyphPositions(x, y, string, end, positions, maxPositions); GlyphPosition* positions, int maxPositions) {
return detail::NVG::getCurrentContext()->textGlyphPositions(x, y, string, end, positions,
maxPositions);
} }
void textMetrics(float* ascender, float* descender, float* lineh) { void textMetrics(float* ascender, float* descender, float* lineh) {
detail::NVG::getCurrentContext()->textMetrics(ascender, descender, lineh); detail::NVG::getCurrentContext()->textMetrics(ascender, descender, lineh);
} }
int textBreakLines(const char* string, const char* end, float breakRowWidth, TextRow* rows, int maxRows) { int textBreakLines(const char* string, const char* end, float breakRowWidth, TextRow* rows,
return detail::NVG::getCurrentContext()->textBreakLines(string, end, breakRowWidth, rows, maxRows); int maxRows) {
return detail::NVG::getCurrentContext()->textBreakLines(string, end, breakRowWidth, rows,
maxRows);
} }
void save() { void save() {
@ -581,8 +601,10 @@ void roundedRect(float x, float y, float w, float h, float r) {
detail::NVG::getCurrentContext()->roundedRect(x, y, w, h, r); detail::NVG::getCurrentContext()->roundedRect(x, y, w, h, r);
} }
void roundedRectVarying(float x, float y, float w, float h, float radTopLeft, float radTopRight, float radBottomRight, float radBottomLeft) { void roundedRectVarying(float x, float y, float w, float h, float radTopLeft, float radTopRight,
detail::NVG::getCurrentContext()->roundedRectVarying(x, y, w, h, radTopLeft, radTopRight, radBottomRight, radBottomLeft); float radBottomRight, float radBottomLeft) {
detail::NVG::getCurrentContext()->roundedRectVarying(x, y, w, h, radTopLeft, radTopRight,
radBottomRight, radBottomLeft);
} }
void ellipse(float cx, float cy, float rx, float ry) { void ellipse(float cx, float cy, float rx, float ry) {
@ -601,15 +623,18 @@ void stroke() {
detail::NVG::getCurrentContext()->stroke(); detail::NVG::getCurrentContext()->stroke();
} }
Paint linearGradient(float sx, float sy, float ex, float ey, const cv::Scalar& icol, const cv::Scalar& ocol) { Paint linearGradient(float sx, float sy, float ex, float ey, const cv::Scalar& icol,
const cv::Scalar& ocol) {
return detail::NVG::getCurrentContext()->linearGradient(sx, sy, ex, ey, icol, ocol); return detail::NVG::getCurrentContext()->linearGradient(sx, sy, ex, ey, icol, ocol);
} }
Paint boxGradient(float x, float y, float w, float h, float r, float f, const cv::Scalar& icol, const cv::Scalar& ocol) { Paint boxGradient(float x, float y, float w, float h, float r, float f, const cv::Scalar& icol,
const cv::Scalar& ocol) {
return detail::NVG::getCurrentContext()->boxGradient(x, y, w, h, r, f, icol, ocol); return detail::NVG::getCurrentContext()->boxGradient(x, y, w, h, r, f, icol, ocol);
} }
Paint radialGradient(float cx, float cy, float inr, float outr, const cv::Scalar& icol, const cv::Scalar& ocol) { Paint radialGradient(float cx, float cy, float inr, float outr, const cv::Scalar& icol,
const cv::Scalar& ocol) {
return detail::NVG::getCurrentContext()->radialGradient(cx, cy, inr, outr, icol, ocol); return detail::NVG::getCurrentContext()->radialGradient(cx, cy, inr, outr, icol, ocol);
} }

@ -19,10 +19,10 @@ namespace cv {
namespace viz { namespace viz {
namespace nvg { namespace nvg {
struct TextRow : public NVGtextRow { struct TextRow: public NVGtextRow {
}; };
struct GlyphPosition : public NVGglyphPosition { struct GlyphPosition: public NVGglyphPosition {
}; };
struct Paint { struct Paint {
@ -33,8 +33,10 @@ struct Paint {
memcpy(this->extent, np.extent, sizeof(this->extent)); memcpy(this->extent, np.extent, sizeof(this->extent));
this->radius = np.radius; this->radius = np.radius;
this->feather = np.feather; this->feather = np.feather;
this->innerColor = cv::Scalar(np.innerColor.rgba[2] * 255, np.innerColor.rgba[1] * 255, np.innerColor.rgba[0] * 255, np.innerColor.rgba[3] * 255); this->innerColor = cv::Scalar(np.innerColor.rgba[2] * 255, np.innerColor.rgba[1] * 255,
this->outerColor = cv::Scalar(np.outerColor.rgba[2] * 255, np.outerColor.rgba[1] * 255, np.outerColor.rgba[0] * 255, np.outerColor.rgba[3] * 255); np.innerColor.rgba[0] * 255, np.innerColor.rgba[3] * 255);
this->outerColor = cv::Scalar(np.outerColor.rgba[2] * 255, np.outerColor.rgba[1] * 255,
np.outerColor.rgba[0] * 255, np.outerColor.rgba[3] * 255);
this->image = np.image; this->image = np.image;
} }
@ -44,8 +46,10 @@ struct Paint {
memcpy(np.extent, this->extent, sizeof(this->extent)); memcpy(np.extent, this->extent, sizeof(this->extent));
np.radius = this->radius; np.radius = this->radius;
np.feather = this->feather; np.feather = this->feather;
np.innerColor = nvgRGBA(this->innerColor[2], this->innerColor[1], this->innerColor[0], this->innerColor[3]); np.innerColor = nvgRGBA(this->innerColor[2], this->innerColor[1], this->innerColor[0],
np.outerColor = nvgRGBA(this->outerColor[2], this->outerColor[1], this->outerColor[0], this->outerColor[3]); this->innerColor[3]);
np.outerColor = nvgRGBA(this->outerColor[2], this->outerColor[1], this->outerColor[0],
this->outerColor[3]);
np.image = this->image; np.image = this->image;
return np; return np;
} }
@ -67,7 +71,8 @@ class NVG {
NVGcontext* ctx_ = nullptr; NVGcontext* ctx_ = nullptr;
public: public:
NVG(NVGcontext* ctx) : ctx_(ctx) { NVG(NVGcontext* ctx) :
ctx_(ctx) {
} }
static void setCurrentContext(NVGcontext* ctx); static void setCurrentContext(NVGcontext* ctx);
@ -79,87 +84,94 @@ public:
} }
public: public:
int createFont(const char* name, const char* filename); int createFont(const char* name, const char* filename);
int createFontMem(const char* name, unsigned char* data, int ndata, int freeData); int createFontMem(const char* name, unsigned char* data, int ndata, int freeData);
int findFont(const char* name); int findFont(const char* name);
int addFallbackFontId(int baseFont, int fallbackFont); int addFallbackFontId(int baseFont, int fallbackFont);
int addFallbackFont(const char* baseFont, const char* fallbackFont); int addFallbackFont(const char* baseFont, const char* fallbackFont);
void fontSize(float size); void fontSize(float size);
void fontBlur(float blur); void fontBlur(float blur);
void textLetterSpacing(float spacing); void textLetterSpacing(float spacing);
void textLineHeight(float lineHeight); void textLineHeight(float lineHeight);
void textAlign(int align); void textAlign(int align);
void fontFaceId(int font); void fontFaceId(int font);
void fontFace(const char* font); void fontFace(const char* font);
float text(float x, float y, const char* string, const char* end); float text(float x, float y, const char* string, const char* end);
void textBox(float x, float y, float breakRowWidth, const char* string, const char* end); void textBox(float x, float y, float breakRowWidth, const char* string, const char* end);
float textBounds(float x, float y, const char* string, const char* end, float* bounds); float textBounds(float x, float y, const char* string, const char* end, float* bounds);
void textBoxBounds(float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds); void textBoxBounds(float x, float y, float breakRowWidth, const char* string, const char* end,
int textGlyphPositions(float x, float y, const char* string, const char* end, GlyphPosition* positions, int maxPositions); float* bounds);
void textMetrics(float* ascender, float* descender, float* lineh); int textGlyphPositions(float x, float y, const char* string, const char* end,
int textBreakLines(const char* string, const char* end, float breakRowWidth, TextRow* rows, int maxRows); GlyphPosition* positions, int maxPositions);
void textMetrics(float* ascender, float* descender, float* lineh);
int textBreakLines(const char* string, const char* end, float breakRowWidth, TextRow* rows,
int maxRows);
void save(); void save();
void restore(); void restore();
void reset(); void reset();
void shapeAntiAlias(int enabled); void shapeAntiAlias(int enabled);
void strokeColor(const cv::Scalar& bgra); void strokeColor(const cv::Scalar& bgra);
void strokePaint(Paint paint); void strokePaint(Paint paint);
void fillColor(const cv::Scalar& bgra); void fillColor(const cv::Scalar& bgra);
void fillPaint(Paint paint); void fillPaint(Paint paint);
void miterLimit(float limit); void miterLimit(float limit);
void strokeWidth(float size); void strokeWidth(float size);
void lineCap(int cap); void lineCap(int cap);
void lineJoin(int join); void lineJoin(int join);
void globalAlpha(float alpha); void globalAlpha(float alpha);
void resetTransform(); void resetTransform();
void transform(float a, float b, float c, float d, float e, float f); void transform(float a, float b, float c, float d, float e, float f);
void translate(float x, float y); void translate(float x, float y);
void rotate(float angle); void rotate(float angle);
void skewX(float angle); void skewX(float angle);
void skewY(float angle); void skewY(float angle);
void scale(float x, float y); void scale(float x, float y);
void currentTransform(float* xform); void currentTransform(float* xform);
void transformIdentity(float* dst); void transformIdentity(float* dst);
void transformTranslate(float* dst, float tx, float ty); void transformTranslate(float* dst, float tx, float ty);
void transformScale(float* dst, float sx, float sy); void transformScale(float* dst, float sx, float sy);
void transformRotate(float* dst, float a); void transformRotate(float* dst, float a);
void transformSkewX(float* dst, float a); void transformSkewX(float* dst, float a);
void transformSkewY(float* dst, float a); void transformSkewY(float* dst, float a);
void transformMultiply(float* dst, const float* src); void transformMultiply(float* dst, const float* src);
void transformPremultiply(float* dst, const float* src); void transformPremultiply(float* dst, const float* src);
int transformInverse(float* dst, const float* src); int transformInverse(float* dst, const float* src);
void transformPoint(float* dstx, float* dsty, const float* xform, float srcx, float srcy); void transformPoint(float* dstx, float* dsty, const float* xform, float srcx, float srcy);
float degToRad(float deg); float degToRad(float deg);
float radToDeg(float rad); float radToDeg(float rad);
void beginPath(); void beginPath();
void moveTo(float x, float y); void moveTo(float x, float y);
void lineTo(float x, float y); void lineTo(float x, float y);
void bezierTo(float c1x, float c1y, float c2x, float c2y, float x, float y); void bezierTo(float c1x, float c1y, float c2x, float c2y, float x, float y);
void quadTo(float cx, float cy, float x, float y); void quadTo(float cx, float cy, float x, float y);
void arcTo(float x1, float y1, float x2, float y2, float radius); void arcTo(float x1, float y1, float x2, float y2, float radius);
void closePath(); void closePath();
void pathWinding(int dir); void pathWinding(int dir);
void arc(float cx, float cy, float r, float a0, float a1, int dir); void arc(float cx, float cy, float r, float a0, float a1, int dir);
void rect(float x, float y, float w, float h); void rect(float x, float y, float w, float h);
void roundedRect(float x, float y, float w, float h, float r); void roundedRect(float x, float y, float w, float h, float r);
void roundedRectVarying(float x, float y, float w, float h, float radTopLeft, float radTopRight, float radBottomRight, float radBottomLeft); void roundedRectVarying(float x, float y, float w, float h, float radTopLeft, float radTopRight,
void ellipse(float cx, float cy, float rx, float ry); float radBottomRight, float radBottomLeft);
void circle(float cx, float cy, float r); void ellipse(float cx, float cy, float rx, float ry);
void fill(); void circle(float cx, float cy, float r);
void stroke(); void fill();
void stroke();
Paint linearGradient(float sx, float sy, float ex, float ey, const cv::Scalar& icol, const cv::Scalar& ocol); Paint linearGradient(float sx, float sy, float ex, float ey, const cv::Scalar& icol,
Paint boxGradient(float x, float y, float w, float h, float r, float f, const cv::Scalar& icol, const cv::Scalar& ocol); const cv::Scalar& ocol);
Paint radialGradient(float cx, float cy, float inr, float outr, const cv::Scalar& icol, const cv::Scalar& ocol); Paint boxGradient(float x, float y, float w, float h, float r, float f, const cv::Scalar& icol,
Paint imagePattern(float ox, float oy, float ex, float ey, float angle, int image, float alpha); const cv::Scalar& ocol);
void scissor(float x, float y, float w, float h); Paint radialGradient(float cx, float cy, float inr, float outr, const cv::Scalar& icol,
void intersectScissor(float x, float y, float w, float h); const cv::Scalar& ocol);
void resetScissor(); Paint imagePattern(float ox, float oy, float ex, float ey, float angle, int image, float alpha);
void scissor(float x, float y, float w, float h);
void intersectScissor(float x, float y, float w, float h);
void resetScissor();
}; };
} // namespace detail } // namespace detail
@ -178,10 +190,13 @@ void fontFace(const char* font);
float text(float x, float y, const char* string, const char* end); float text(float x, float y, const char* string, const char* end);
void textBox(float x, float y, float breakRowWidth, const char* string, const char* end); void textBox(float x, float y, float breakRowWidth, const char* string, const char* end);
float textBounds(float x, float y, const char* string, const char* end, float* bounds); float textBounds(float x, float y, const char* string, const char* end, float* bounds);
void textBoxBounds(float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds); void textBoxBounds(float x, float y, float breakRowWidth, const char* string, const char* end,
int textGlyphPositions(float x, float y, const char* string, const char* end, GlyphPosition* positions, int maxPositions); float* bounds);
int textGlyphPositions(float x, float y, const char* string, const char* end,
GlyphPosition* positions, int maxPositions);
void textMetrics(float* ascender, float* descender, float* lineh); void textMetrics(float* ascender, float* descender, float* lineh);
int textBreakLines(const char* string, const char* end, float breakRowWidth, TextRow* rows, int maxRows); int textBreakLines(const char* string, const char* end, float breakRowWidth, TextRow* rows,
int maxRows);
void save(); void save();
void restore(); void restore();
@ -231,15 +246,19 @@ void pathWinding(int dir);
void arc(float cx, float cy, float r, float a0, float a1, int dir); void arc(float cx, float cy, float r, float a0, float a1, int dir);
void rect(float x, float y, float w, float h); void rect(float x, float y, float w, float h);
void roundedRect(float x, float y, float w, float h, float r); void roundedRect(float x, float y, float w, float h, float r);
void roundedRectVarying(float x, float y, float w, float h, float radTopLeft, float radTopRight, float radBottomRight, float radBottomLeft); void roundedRectVarying(float x, float y, float w, float h, float radTopLeft, float radTopRight,
float radBottomRight, float radBottomLeft);
void ellipse(float cx, float cy, float rx, float ry); void ellipse(float cx, float cy, float rx, float ry);
void circle(float cx, float cy, float r); void circle(float cx, float cy, float r);
void fill(); void fill();
void stroke(); void stroke();
Paint linearGradient(float sx, float sy, float ex, float ey, const cv::Scalar& icol, const cv::Scalar& ocol); Paint linearGradient(float sx, float sy, float ex, float ey, const cv::Scalar& icol,
Paint boxGradient(float x, float y, float w, float h, float r, float f, const cv::Scalar& icol, const cv::Scalar& ocol); const cv::Scalar& ocol);
Paint radialGradient(float cx, float cy, float inr, float outr, const cv::Scalar& icol, const cv::Scalar& ocol); Paint boxGradient(float x, float y, float w, float h, float r, float f, const cv::Scalar& icol,
const cv::Scalar& ocol);
Paint radialGradient(float cx, float cy, float inr, float outr, const cv::Scalar& icol,
const cv::Scalar& ocol);
Paint imagePattern(float ox, float oy, float ex, float ey, float angle, int image, float alpha); Paint imagePattern(float ox, float oy, float ex, float ey, float angle, int image, float alpha);
void scissor(float x, float y, float w, float h); void scissor(float x, float y, float w, float h);
void intersectScissor(float x, float y, float w, float h); void intersectScissor(float x, float y, float w, float h);
@ -248,6 +267,4 @@ void resetScissor();
} }
} }
#endif /* SRC_COMMON_NVG_HPP_ */ #endif /* SRC_COMMON_NVG_HPP_ */

@ -8,7 +8,8 @@
namespace cv { namespace cv {
namespace viz { namespace viz {
Sink::Sink(std::function<bool(const cv::UMat&)> consumer) : consumer_(consumer) { Sink::Sink(std::function<bool(const cv::UMat&)> consumer) :
consumer_(consumer) {
} }
Sink::Sink() { Sink::Sink() {
@ -18,7 +19,7 @@ Sink::~Sink() {
} }
bool Sink::isReady() { bool Sink::isReady() {
if(consumer_) if (consumer_)
return true; return true;
else else
return false; return false;

@ -8,17 +8,19 @@
namespace cv { namespace cv {
namespace viz { namespace viz {
Source::Source(std::function<bool(cv::UMat&)> generator, float fps) : generator_(generator), fps_(fps) { Source::Source(std::function<bool(cv::UMat&)> generator, float fps) :
generator_(generator), fps_(fps) {
} }
Source::Source() : fps_(0) { Source::Source() :
fps_(0) {
} }
Source::~Source() { Source::~Source() {
} }
bool Source::isReady() { bool Source::isReady() {
if(generator_) if (generator_)
return true; return true;
else else
return false; return false;

@ -35,10 +35,10 @@ std::string get_cl_info() {
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
std::vector<cv::ocl::PlatformInfo> plt_info; std::vector<cv::ocl::PlatformInfo> plt_info;
cv::ocl::getPlatfomsInfo(plt_info); cv::ocl::getPlatfomsInfo(plt_info);
const cv::ocl::Device &defaultDevice = cv::ocl::Device::getDefault(); const cv::ocl::Device& defaultDevice = cv::ocl::Device::getDefault();
cv::ocl::Device current; cv::ocl::Device current;
ss << endl; ss << endl;
for (const auto &info : plt_info) { for (const auto& info : plt_info) {
for (int i = 0; i < info.deviceNumber(); ++i) { for (int i = 0; i < info.deviceNumber(); ++i) {
ss << "\t"; ss << "\t";
info.getDevice(current, i); info.getDevice(current, i);
@ -47,8 +47,12 @@ std::string get_cl_info() {
else else
ss << " "; ss << " ";
ss << info.version() << " = " << info.name() << endl; ss << info.version() << " = " << info.name() << endl;
ss << "\t\t GL sharing: " << (current.isExtensionSupported("cl_khr_gl_sharing") ? "true" : "false") << endl; ss << "\t\t GL sharing: "
ss << "\t\t VAAPI media sharing: " << (current.isExtensionSupported("cl_intel_va_api_media_sharing") ? "true" : "false") << endl; << (current.isExtensionSupported("cl_khr_gl_sharing") ? "true" : "false")
<< endl;
ss << "\t\t VAAPI media sharing: "
<< (current.isExtensionSupported("cl_intel_va_api_media_sharing") ?
"true" : "false") << endl;
} }
} }
#endif #endif
@ -65,14 +69,14 @@ bool is_intel_va_supported() {
std::vector<cv::ocl::PlatformInfo> plt_info; std::vector<cv::ocl::PlatformInfo> plt_info;
cv::ocl::getPlatfomsInfo(plt_info); cv::ocl::getPlatfomsInfo(plt_info);
cv::ocl::Device current; cv::ocl::Device current;
for (const auto &info : plt_info) { for (const auto& info : plt_info) {
for (int i = 0; i < info.deviceNumber(); ++i) { for (int i = 0; i < info.deviceNumber(); ++i) {
info.getDevice(current, i); info.getDevice(current, i);
return current.isExtensionSupported("cl_intel_va_api_media_sharing"); return current.isExtensionSupported("cl_intel_va_api_media_sharing");
} }
} }
} catch (std::exception& ex) { } catch (std::exception& ex) {
cerr << "Intel VAAPI query failed: " << ex. what() << endl; cerr << "Intel VAAPI query failed: " << ex.what() << endl;
} catch (...) { } catch (...) {
cerr << "Intel VAAPI query failed" << endl; cerr << "Intel VAAPI query failed" << endl;
} }
@ -90,14 +94,14 @@ bool is_cl_gl_sharing_supported() {
std::vector<cv::ocl::PlatformInfo> plt_info; std::vector<cv::ocl::PlatformInfo> plt_info;
cv::ocl::getPlatfomsInfo(plt_info); cv::ocl::getPlatfomsInfo(plt_info);
cv::ocl::Device current; cv::ocl::Device current;
for (const auto &info : plt_info) { for (const auto& info : plt_info) {
for (int i = 0; i < info.deviceNumber(); ++i) { for (int i = 0; i < info.deviceNumber(); ++i) {
info.getDevice(current, i); info.getDevice(current, i);
return current.isExtensionSupported("cl_khr_gl_sharing"); return current.isExtensionSupported("cl_khr_gl_sharing");
} }
} }
} catch (std::exception& ex) { } catch (std::exception& ex) {
cerr << "CL-GL sharing query failed: " << ex. what() << endl; cerr << "CL-GL sharing query failed: " << ex.what() << endl;
} catch (...) { } catch (...) {
cerr << "CL-GL sharing query failed" << endl; cerr << "CL-GL sharing query failed" << endl;
} }
@ -139,7 +143,7 @@ static void install_signal_handlers() {
* @return true if the program should keep on running * @return true if the program should keep on running
*/ */
bool keep_running() { bool keep_running() {
if(!signal_handlers_installed) { if (!signal_handlers_installed) {
install_signal_handlers(); install_signal_handlers();
} }
return !finish_requested; return !finish_requested;
@ -170,7 +174,7 @@ void update_fps(cv::Ptr<cv::viz::Viz2D> v2d, bool graphically) {
} }
if (graphically) { if (graphically) {
v2d->nvg([&](const cv::Size &size) { v2d->nvg([&](const cv::Size& size) {
using namespace cv; using namespace cv;
string text = "FPS: " + std::to_string(fps); string text = "FPS: " + std::to_string(fps);
nvg::beginPath(); nvg::beginPath();
@ -201,22 +205,29 @@ void update_fps(cv::Ptr<cv::viz::Viz2D> v2d, bool graphically) {
* @param vaDeviceIndex * @param vaDeviceIndex
* @return * @return
*/ */
Sink make_va_sink(const string &outputFilename, const int fourcc, const float fps, const cv::Size &frameSize, const int vaDeviceIndex) { Sink make_va_sink(const string& outputFilename, const int fourcc, const float fps,
cv::Ptr<cv::VideoWriter> writer = new cv::VideoWriter(outputFilename, cv::CAP_FFMPEG, cv::VideoWriter::fourcc('V', 'P', '9', '0'), fps, frameSize, { cv::VIDEOWRITER_PROP_HW_DEVICE, vaDeviceIndex, cv::VIDEOWRITER_PROP_HW_ACCELERATION, cv::VIDEO_ACCELERATION_VAAPI, cv::VIDEOWRITER_PROP_HW_ACCELERATION_USE_OPENCL, 1 }); const cv::Size& frameSize, const int vaDeviceIndex) {
cv::Ptr<cv::VideoWriter> writer = new cv::VideoWriter(outputFilename, cv::CAP_FFMPEG,
return Sink([=](const cv::UMat& frame){ cv::VideoWriter::fourcc('V', 'P', '9', '0'), fps, frameSize, {
cv::VIDEOWRITER_PROP_HW_DEVICE, vaDeviceIndex,
cv::VIDEOWRITER_PROP_HW_ACCELERATION, cv::VIDEO_ACCELERATION_VAAPI,
cv::VIDEOWRITER_PROP_HW_ACCELERATION_USE_OPENCL, 1 });
return Sink([=](const cv::UMat& frame) {
(*writer) << frame; (*writer) << frame;
return writer->isOpened(); return writer->isOpened();
}); });
} }
Source make_va_source(const string &inputFilename, const int vaDeviceIndex) { Source make_va_source(const string& inputFilename, const int vaDeviceIndex) {
cv::Ptr<cv::VideoCapture> capture = new cv::VideoCapture(inputFilename, cv::CAP_FFMPEG, { cv::CAP_PROP_HW_DEVICE, vaDeviceIndex, cv::CAP_PROP_HW_ACCELERATION, cv::VIDEO_ACCELERATION_VAAPI, cv::CAP_PROP_HW_ACCELERATION_USE_OPENCL, 1 }); cv::Ptr<cv::VideoCapture> capture = new cv::VideoCapture(inputFilename, cv::CAP_FFMPEG, {
cv::CAP_PROP_HW_DEVICE, vaDeviceIndex, cv::CAP_PROP_HW_ACCELERATION,
cv::VIDEO_ACCELERATION_VAAPI, cv::CAP_PROP_HW_ACCELERATION_USE_OPENCL, 1 });
float fps = capture->get(cv::CAP_PROP_FPS); float fps = capture->get(cv::CAP_PROP_FPS);
float w = capture->get(cv::CAP_PROP_FRAME_WIDTH); float w = capture->get(cv::CAP_PROP_FRAME_WIDTH);
float h = capture->get(cv::CAP_PROP_FRAME_HEIGHT); float h = capture->get(cv::CAP_PROP_FRAME_HEIGHT);
return Source([=](cv::UMat& frame){ return Source([=](cv::UMat& frame) {
(*capture) >> frame; (*capture) >> frame;
return !frame.empty(); return !frame.empty();
}, fps); }, fps);
@ -235,21 +246,23 @@ Source make_va_source(const string &inputFilename, const int vaDeviceIndex) {
#endif #endif
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
Sink make_writer_sink(const string &outputFilename, const int fourcc, const float fps, const cv::Size &frameSize) { Sink make_writer_sink(const string& outputFilename, const int fourcc, const float fps,
if(is_intel_va_supported()) { const cv::Size& frameSize) {
if (is_intel_va_supported()) {
return make_va_sink(outputFilename, fourcc, fps, frameSize, 0); return make_va_sink(outputFilename, fourcc, fps, frameSize, 0);
} }
cv::Ptr<cv::VideoWriter> writer = new cv::VideoWriter(outputFilename, cv::CAP_FFMPEG, cv::VideoWriter::fourcc('V', 'P', '9', '0'), fps, frameSize); cv::Ptr<cv::VideoWriter> writer = new cv::VideoWriter(outputFilename, cv::CAP_FFMPEG,
cv::VideoWriter::fourcc('V', 'P', '9', '0'), fps, frameSize);
return Sink([=](const cv::UMat& frame){ return Sink([=](const cv::UMat& frame) {
(*writer) << frame; (*writer) << frame;
return writer->isOpened(); return writer->isOpened();
}); });
} }
Source make_capture_source(const string &inputFilename) { Source make_capture_source(const string& inputFilename) {
if(is_intel_va_supported()) { if (is_intel_va_supported()) {
return make_va_source(inputFilename, 0); return make_va_source(inputFilename, 0);
} }
@ -258,7 +271,7 @@ Source make_capture_source(const string &inputFilename) {
float w = capture->get(cv::CAP_PROP_FRAME_WIDTH); float w = capture->get(cv::CAP_PROP_FRAME_WIDTH);
float h = capture->get(cv::CAP_PROP_FRAME_HEIGHT); float h = capture->get(cv::CAP_PROP_FRAME_HEIGHT);
return Source([=](cv::UMat& frame){ return Source([=](cv::UMat& frame) {
(*capture) >> frame; (*capture) >> frame;
return !frame.empty(); return !frame.empty();
}, fps); }, fps);

@ -32,10 +32,12 @@ void print_system_info();
void update_fps(cv::Ptr<Viz2D> viz2d, bool graphical); void update_fps(cv::Ptr<Viz2D> viz2d, bool graphical);
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
Sink make_va_sink(const string &outputFilename, const int fourcc, const float fps, const cv::Size &frameSize, const int vaDeviceIndex); Sink make_va_sink(const string& outputFilename, const int fourcc, const float fps,
Source make_va_source(const string &inputFilename, const int vaDeviceIndex); const cv::Size& frameSize, const int vaDeviceIndex);
Sink make_writer_sink(const string &outputFilename, const int fourcc, const float fps, const cv::Size &frameSize); Source make_va_source(const string& inputFilename, const int vaDeviceIndex);
Source make_capture_source(const string &inputFilename); Sink make_writer_sink(const string& outputFilename, const int fourcc, const float fps,
const cv::Size& frameSize);
Source make_capture_source(const string& inputFilename);
#else #else
Source make_capture_source(int width, int height); Source make_capture_source(int width, int height);
#endif #endif

@ -15,57 +15,64 @@
namespace cv { namespace cv {
namespace viz { namespace viz {
namespace detail { namespace detail {
void gl_check_error(const std::filesystem::path &file, unsigned int line, const char *expression) { void gl_check_error(const std::filesystem::path& file, unsigned int line, const char* expression) {
int errorCode = glGetError(); int errorCode = glGetError();
if (errorCode != 0) { if (errorCode != 0) {
std::cerr << "GL failed in " << file.filename() << " (" << line << ") : " << "\nExpression:\n " << expression << "\nError code:\n " << errorCode << "\n " << std::endl; std::cerr << "GL failed in " << file.filename() << " (" << line << ") : "
<< "\nExpression:\n " << expression << "\nError code:\n " << errorCode
<< "\n " << std::endl;
assert(false); assert(false);
} }
} }
void error_callback(int error, const char *description) { void error_callback(int error, const char* description) {
fprintf(stderr, "GLFW Error: %s\n", description); fprintf(stderr, "GLFW Error: %s\n", description);
} }
} }
template <typename T> void find_widgets(nanogui::Widget* parent, std::vector<T>& widgets) { template<typename T> void find_widgets(nanogui::Widget* parent, std::vector<T>& widgets) {
T w; T w;
for(auto* child: parent->children()) { for (auto* child : parent->children()) {
find_widgets(child, widgets); find_widgets(child, widgets);
if((w = dynamic_cast<T>(child)) != nullptr) { if ((w = dynamic_cast<T>(child)) != nullptr) {
widgets.push_back(w); widgets.push_back(w);
} }
} }
} }
bool contains_absolute(nanogui::Widget* w, const nanogui::Vector2i &p) { bool contains_absolute(nanogui::Widget* w, const nanogui::Vector2i& p) {
nanogui::Vector2i d = p - w->absolute_position(); nanogui::Vector2i d = p - w->absolute_position();
return d.x() >= 0 && d.y() >= 0 && return d.x() >= 0 && d.y() >= 0 && d.x() < w->size().x() && d.y() < w->size().y();
d.x() < w->size().x() && d.y() < w->size().y();
} }
cv::Scalar color_convert(const cv::Scalar& src, cv::ColorConversionCodes code) { cv::Scalar color_convert(const cv::Scalar& src, cv::ColorConversionCodes code) {
cv::Mat tmpIn(1,1,CV_8UC3); cv::Mat tmpIn(1, 1, CV_8UC3);
cv::Mat tmpOut(1,1,CV_8UC3); cv::Mat tmpOut(1, 1, CV_8UC3);
tmpIn.at<cv::Vec3b>(0,0) = cv::Vec3b(src[0], src[1], src[2]); tmpIn.at<cv::Vec3b>(0, 0) = cv::Vec3b(src[0], src[1], src[2]);
cvtColor(tmpIn, tmpOut, code); cvtColor(tmpIn, tmpOut, code);
const cv::Vec3b& vdst = tmpOut.at<cv::Vec3b>(0,0); const cv::Vec3b& vdst = tmpOut.at<cv::Vec3b>(0, 0);
cv::Scalar dst(vdst[0],vdst[1],vdst[2], src[3]); cv::Scalar dst(vdst[0], vdst[1], vdst[2], src[3]);
return dst; return dst;
} }
Viz2D::Viz2D(const cv::Size &size, const cv::Size& frameBufferSize, bool offscreen, const string &title, int major, int minor, int samples, bool debug) : Viz2D::Viz2D(const cv::Size& size, const cv::Size& frameBufferSize, bool offscreen,
initialSize_(size), frameBufferSize_(frameBufferSize), viewport_(0, 0, frameBufferSize.width, frameBufferSize.height), scale_(1), mousePos_(0,0), offscreen_(offscreen), stretch_(false), title_(title), major_(major), minor_(minor), samples_(samples), debug_(debug) { const string& title, int major, int minor, int samples, bool debug) :
assert(frameBufferSize_.width >= initialSize_.width && frameBufferSize_.height >= initialSize_.height); initialSize_(size), frameBufferSize_(frameBufferSize), viewport_(0, 0,
frameBufferSize.width, frameBufferSize.height), scale_(1), mousePos_(0, 0), offscreen_(
offscreen), stretch_(false), title_(title), major_(major), minor_(minor), samples_(
samples), debug_(debug) {
assert(
frameBufferSize_.width >= initialSize_.width
&& frameBufferSize_.height >= initialSize_.height);
initializeWindowing(); initializeWindowing();
} }
Viz2D::~Viz2D() { Viz2D::~Viz2D() {
//don't delete form_. it is autmatically cleaned up by the base class (nanogui::Screen) //don't delete form_. it is autmatically cleaned up by the base class (nanogui::Screen)
if(screen_) if (screen_)
delete screen_; delete screen_;
if (writer_) if (writer_)
delete writer_; delete writer_;
@ -80,7 +87,7 @@ Viz2D::~Viz2D() {
} }
bool Viz2D::initializeWindowing() { bool Viz2D::initializeWindowing() {
if(glfwInit() != GLFW_TRUE) if (glfwInit() != GLFW_TRUE)
return false; return false;
glfwSetErrorCallback(cv::viz::error_callback); glfwSetErrorCallback(cv::viz::error_callback);
@ -129,7 +136,8 @@ bool Viz2D::initializeWindowing() {
*/ */
glfwWindowHint(GLFW_DOUBLEBUFFER, GL_FALSE); glfwWindowHint(GLFW_DOUBLEBUFFER, GL_FALSE);
glfwWindow_ = glfwCreateWindow(initialSize_.width, initialSize_.height, title_.c_str(), nullptr, nullptr); glfwWindow_ = glfwCreateWindow(initialSize_.width, initialSize_.height, title_.c_str(), nullptr,
nullptr);
if (glfwWindow_ == NULL) { if (glfwWindow_ == NULL) {
return false; return false;
} }
@ -143,51 +151,54 @@ bool Viz2D::initializeWindowing() {
glfwSetWindowUserPointer(getGLFWWindow(), this); glfwSetWindowUserPointer(getGLFWWindow(), this);
glfwSetCursorPosCallback(getGLFWWindow(), [](GLFWwindow *glfwWin, double x, double y) { glfwSetCursorPosCallback(getGLFWWindow(), [](GLFWwindow* glfwWin, double x, double y) {
Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin)); Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin));
v2d->screen().cursor_pos_callback_event(x, y); v2d->screen().cursor_pos_callback_event(x, y);
auto cursor = v2d->getMousePosition(); auto cursor = v2d->getMousePosition();
auto diff = cursor - cv::Vec2f(x, y); auto diff = cursor - cv::Vec2f(x, y);
if(v2d->isMouseDrag()) { if (v2d->isMouseDrag()) {
v2d->pan(diff[0], -diff[1]); v2d->pan(diff[0], -diff[1]);
} }
v2d->setMousePosition(x, y); v2d->setMousePosition(x, y);
} }
); );
glfwSetMouseButtonCallback(getGLFWWindow(), [](GLFWwindow *glfwWin, int button, int action, int modifiers) { glfwSetMouseButtonCallback(getGLFWWindow(),
Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin)); [](GLFWwindow* glfwWin, int button, int action, int modifiers) {
v2d->screen().mouse_button_callback_event(button, action, modifiers); Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin));
if (button == GLFW_MOUSE_BUTTON_RIGHT) { v2d->screen().mouse_button_callback_event(button, action, modifiers);
v2d->setMouseDrag(action == GLFW_PRESS); if (button == GLFW_MOUSE_BUTTON_RIGHT) {
} v2d->setMouseDrag(action == GLFW_PRESS);
} }
}
); );
glfwSetKeyCallback(getGLFWWindow(), [](GLFWwindow *glfwWin, int key, int scancode, int action, int mods) { glfwSetKeyCallback(getGLFWWindow(),
Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin)); [](GLFWwindow* glfwWin, int key, int scancode, int action, int mods) {
v2d->screen().key_callback_event(key, scancode, action, mods); Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin));
} v2d->screen().key_callback_event(key, scancode, action, mods);
}
); );
glfwSetCharCallback(getGLFWWindow(), [](GLFWwindow *glfwWin, unsigned int codepoint) { glfwSetCharCallback(getGLFWWindow(), [](GLFWwindow* glfwWin, unsigned int codepoint) {
Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin)); Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin));
v2d->screen().char_callback_event(codepoint); v2d->screen().char_callback_event(codepoint);
} }
); );
glfwSetDropCallback(getGLFWWindow(), [](GLFWwindow *glfwWin, int count, const char **filenames) { glfwSetDropCallback(getGLFWWindow(),
Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin)); [](GLFWwindow* glfwWin, int count, const char** filenames) {
v2d->screen().drop_callback_event(count, filenames); Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin));
} v2d->screen().drop_callback_event(count, filenames);
}
); );
glfwSetScrollCallback(getGLFWWindow(), [](GLFWwindow *glfwWin, double x, double y) { glfwSetScrollCallback(getGLFWWindow(), [](GLFWwindow* glfwWin, double x, double y) {
Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin)); Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin));
std::vector<nanogui::Widget*> widgets; std::vector<nanogui::Widget*> widgets;
find_widgets(&v2d->screen(), widgets); find_widgets(&v2d->screen(), widgets);
for(auto* w : widgets) { for (auto* w : widgets) {
auto mousePos = nanogui::Vector2i(v2d->getMousePosition()[0] / v2d->getXPixelRatio(), v2d->getMousePosition()[1] / v2d->getYPixelRatio()); auto mousePos = nanogui::Vector2i(v2d->getMousePosition()[0] / v2d->getXPixelRatio(), v2d->getMousePosition()[1] / v2d->getYPixelRatio());
if(contains_absolute(w, mousePos)) { if(contains_absolute(w, mousePos)) {
v2d->screen().scroll_callback_event(x, y); v2d->screen().scroll_callback_event(x, y);
return; return;
} }
} }
v2d->zoom(y < 0 ? 1.1 : 0.9); v2d->zoom(y < 0 ? 1.1 : 0.9);
} }
@ -199,11 +210,10 @@ bool Viz2D::initializeWindowing() {
// } // }
// ); // );
glfwSetFramebufferSizeCallback(getGLFWWindow(), [](GLFWwindow *glfwWin, int width, int height) { glfwSetFramebufferSizeCallback(getGLFWWindow(), [](GLFWwindow* glfwWin, int width, int height) {
Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin)); Viz2D* v2d = reinterpret_cast<Viz2D*>(glfwGetWindowUserPointer(glfwWin));
v2d->screen().resize_callback_event(width, height); v2d->screen().resize_callback_event(width, height);
} });
);
clglContext_ = new detail::FrameBufferContext(this->getFrameBufferSize()); clglContext_ = new detail::FrameBufferContext(this->getFrameBufferSize());
clvaContext_ = new detail::CLVAContext(*clglContext_); clvaContext_ = new detail::CLVAContext(*clglContext_);
@ -219,12 +229,13 @@ FormHelper& Viz2D::form() {
return *form_; return *form_;
} }
void Viz2D::setKeyboardEventCallback(std::function<bool(int key, int scancode, int action, int modifiers)> fn) { void Viz2D::setKeyboardEventCallback(
std::function<bool(int key, int scancode, int action, int modifiers)> fn) {
keyEventCb_ = fn; keyEventCb_ = fn;
} }
bool Viz2D::keyboard_event(int key, int scancode, int action, int modifiers) { bool Viz2D::keyboard_event(int key, int scancode, int action, int modifiers) {
if(keyEventCb_) if (keyEventCb_)
return keyEventCb_(key, scancode, action, modifiers); return keyEventCb_(key, scancode, action, modifiers);
if (screen().keyboard_event(key, scancode, action, modifiers)) if (screen().keyboard_event(key, scancode, action, modifiers))
@ -285,36 +296,36 @@ void Viz2D::nanogui(std::function<void(FormHelper& form)> fn) {
fn(form()); fn(form());
} }
void Viz2D::setSource(const Source &src) { void Viz2D::setSource(const Source& src) {
if (!clva().hasContext()) if (!clva().hasContext())
clva().copyContext(); clva().copyContext();
source_ = src; source_ = src;
} }
bool Viz2D::capture() { bool Viz2D::capture() {
return this->capture([&](cv::UMat &videoFrame) { return this->capture([&](cv::UMat& videoFrame) {
if(source_.isReady()) if (source_.isReady())
source_().second.copyTo(videoFrame); source_().second.copyTo(videoFrame);
}); });
} }
bool Viz2D::capture(std::function<void(cv::UMat&)> fn) { bool Viz2D::capture(std::function<void(cv::UMat&)> fn) {
return clva().capture(fn); return clva().capture(fn);
} }
bool Viz2D::isSourceReady() { bool Viz2D::isSourceReady() {
return source_.isReady(); return source_.isReady();
} }
void Viz2D::setSink(const Sink &sink) { void Viz2D::setSink(const Sink& sink) {
if (!clva().hasContext()) if (!clva().hasContext())
clva().copyContext(); clva().copyContext();
sink_ = sink; sink_ = sink;
} }
void Viz2D::write() { void Viz2D::write() {
this->write([&](const cv::UMat &videoFrame) { this->write([&](const cv::UMat& videoFrame) {
if(sink_.isReady()) if (sink_.isReady())
sink_(videoFrame); sink_(videoFrame);
}); });
} }
@ -335,18 +346,18 @@ void Viz2D::makeNoneCurrent() {
glfwMakeContextCurrent(nullptr); glfwMakeContextCurrent(nullptr);
} }
void Viz2D::clear(const cv::Scalar &rgba) { void Viz2D::clear(const cv::Scalar& rgba) {
const float &r = rgba[0] / 255.0f; const float& r = rgba[0] / 255.0f;
const float &g = rgba[1] / 255.0f; const float& g = rgba[1] / 255.0f;
const float &b = rgba[2] / 255.0f; const float& b = rgba[2] / 255.0f;
const float &a = rgba[3] / 255.0f; const float& a = rgba[3] / 255.0f;
GL_CHECK(glClearColor(r, g, b, a)); GL_CHECK(glClearColor(r, g, b, a));
GL_CHECK(glClear(GL_COLOR_BUFFER_BIT)); GL_CHECK(glClear(GL_COLOR_BUFFER_BIT));
} }
void Viz2D::showGui(bool s) { void Viz2D::showGui(bool s) {
auto children = screen().children(); auto children = screen().children();
for(auto* child : children) { for (auto* child : children) {
child->set_visible(s); child->set_visible(s);
} }
} }
@ -365,7 +376,7 @@ void Viz2D::pan(int x, int y) {
} }
void Viz2D::zoom(float factor) { void Viz2D::zoom(float factor) {
if(scale_ == 1 && viewport_.x == 0 && viewport_.y == 0 && factor > 1) if (scale_ == 1 && viewport_.x == 0 && viewport_.y == 0 && factor > 1)
return; return;
double oldScale = scale_; double oldScale = scale_;
@ -373,19 +384,23 @@ void Viz2D::zoom(float factor) {
double origH = getFrameBufferSize().height; double origH = getFrameBufferSize().height;
scale_ *= factor; scale_ *= factor;
if(scale_ <= 0.025) { if (scale_ <= 0.025) {
scale_ = 0.025; scale_ = 0.025;
return; return;
} else if(scale_ > 1) { } else if (scale_ > 1) {
scale_ = 1; scale_ = 1;
viewport_.width = origW; viewport_.width = origW;
viewport_.height = origH; viewport_.height = origH;
if(factor > 1) { if (factor > 1) {
viewport_.x += log10(((viewport_.x * (1.0 - factor)) / viewport_.width) * 9 + 1.0) * viewport_.width; viewport_.x += log10(((viewport_.x * (1.0 - factor)) / viewport_.width) * 9 + 1.0)
viewport_.y += log10(((viewport_.y * (1.0 - factor)) / viewport_.height) * 9 + 1.0) * viewport_.height; * viewport_.width;
viewport_.y += log10(((viewport_.y * (1.0 - factor)) / viewport_.height) * 9 + 1.0)
* viewport_.height;
} else { } else {
viewport_.x += log10(((-viewport_.x * (1.0 - factor)) / viewport_.width) * 9 + 1.0) * viewport_.width; viewport_.x += log10(((-viewport_.x * (1.0 - factor)) / viewport_.width) * 9 + 1.0)
viewport_.y += log10(((-viewport_.y * (1.0 - factor)) / viewport_.height) * 9 + 1.0) * viewport_.height; * viewport_.width;
viewport_.y += log10(((-viewport_.y * (1.0 - factor)) / viewport_.height) * 9 + 1.0)
* viewport_.height;
} }
return; return;
} }
@ -399,20 +414,22 @@ void Viz2D::zoom(float factor) {
float delta_x; float delta_x;
float delta_y; float delta_y;
if(factor < 1.0) { if (factor < 1.0) {
offset = cv::Vec2f(viewport_.x, viewport_.y) - cv::Vec2f(mousePos_[0], origH - mousePos_[1]); offset = cv::Vec2f(viewport_.x, viewport_.y)
- cv::Vec2f(mousePos_[0], origH - mousePos_[1]);
delta_x = offset[0] / oldW; delta_x = offset[0] / oldW;
delta_y = offset[1] / oldH; delta_y = offset[1] / oldH;
} else { } else {
offset = cv::Vec2f(viewport_.x - (viewport_.width / 2.0), viewport_.y - (viewport_.height / 2.0)) - cv::Vec2f(viewport_.x, viewport_.y); offset = cv::Vec2f(viewport_.x - (viewport_.width / 2.0),
viewport_.y - (viewport_.height / 2.0)) - cv::Vec2f(viewport_.x, viewport_.y);
delta_x = offset[0] / oldW; delta_x = offset[0] / oldW;
delta_y = offset[1] / oldH; delta_y = offset[1] / oldH;
} }
float x_offset; float x_offset;
float y_offset; float y_offset;
x_offset = delta_x * (viewport_.width - oldW); x_offset = delta_x * (viewport_.width - oldW);
y_offset = delta_y * (viewport_.height - oldH); y_offset = delta_y * (viewport_.height - oldH);
if (factor < 1.0) { if (factor < 1.0) {
viewport_.x += x_offset; viewport_.x += x_offset;
@ -435,7 +452,7 @@ cv::Vec2f Viz2D::getMousePosition() {
} }
void Viz2D::setMousePosition(int x, int y) { void Viz2D::setMousePosition(int x, int y) {
mousePos_ = {float(x), float(y)}; mousePos_ = { float(x), float(y) };
} }
float Viz2D::getScale() { float Viz2D::getScale() {
@ -490,7 +507,7 @@ float Viz2D::getYPixelRatio() {
#endif #endif
} }
void Viz2D::setWindowSize(const cv::Size &sz) { void Viz2D::setWindowSize(const cv::Size& sz) {
makeCurrent(); makeCurrent();
screen().set_size(nanogui::Vector2i(sz.width / getXPixelRatio(), sz.height / getYPixelRatio())); screen().set_size(nanogui::Vector2i(sz.width / getXPixelRatio(), sz.height / getYPixelRatio()));
} }
@ -503,12 +520,14 @@ bool Viz2D::isFullscreen() {
void Viz2D::setFullscreen(bool f) { void Viz2D::setFullscreen(bool f) {
makeCurrent(); makeCurrent();
auto monitor = glfwGetPrimaryMonitor(); auto monitor = glfwGetPrimaryMonitor();
const GLFWvidmode *mode = glfwGetVideoMode(monitor); const GLFWvidmode* mode = glfwGetVideoMode(monitor);
if (f) { if (f) {
glfwSetWindowMonitor(getGLFWWindow(), monitor, 0, 0, mode->width, mode->height, mode->refreshRate); glfwSetWindowMonitor(getGLFWWindow(), monitor, 0, 0, mode->width, mode->height,
mode->refreshRate);
setWindowSize(getNativeFrameBufferSize()); setWindowSize(getNativeFrameBufferSize());
} else { } else {
glfwSetWindowMonitor(getGLFWWindow(), nullptr, 0, 0, getInitialSize().width, getInitialSize().height, 0); glfwSetWindowMonitor(getGLFWWindow(), nullptr, 0, 0, getInitialSize().width,
getInitialSize().height, 0);
setWindowSize(getInitialSize()); setWindowSize(getInitialSize());
} }
} }
@ -559,7 +578,7 @@ void Viz2D::setDefaultKeyboardEventCallback() {
return true; return true;
} else if (key == GLFW_KEY_TAB && action == GLFW_PRESS) { } else if (key == GLFW_KEY_TAB && action == GLFW_PRESS) {
auto children = screen().children(); auto children = screen().children();
for(auto* child : children) { for (auto* child : children) {
child->set_visible(!child->visible()); child->set_visible(!child->visible());
} }

@ -11,7 +11,6 @@
#include "dialog.hpp" #include "dialog.hpp"
#include "formhelper.hpp" #include "formhelper.hpp"
#include <filesystem> #include <filesystem>
#include <iostream> #include <iostream>
#include <set> #include <set>
@ -37,13 +36,13 @@ class FrameBufferContext;
class CLVAContext; class CLVAContext;
class NanoVGContext; class NanoVGContext;
void gl_check_error(const std::filesystem::path &file, unsigned int line, const char *expression); void gl_check_error(const std::filesystem::path& file, unsigned int line, const char* expression);
#define GL_CHECK(expr) \ #define GL_CHECK(expr) \
expr; \ expr; \
cv::viz::gl_check_error(__FILE__, __LINE__, #expr); cv::viz::gl_check_error(__FILE__, __LINE__, #expr);
void error_callback(int error, const char *description); void error_callback(int error, const char* description);
} }
cv::Scalar color_convert(const cv::Scalar& src, cv::ColorConversionCodes code); cv::Scalar color_convert(const cv::Scalar& src, cv::ColorConversionCodes code);
@ -78,7 +77,7 @@ class Viz2D {
cv::VideoWriter* writer_ = nullptr; cv::VideoWriter* writer_ = nullptr;
FormHelper* form_ = nullptr; FormHelper* form_ = nullptr;
bool closed_ = false; bool closed_ = false;
cv::Size videoFrameSize_ = cv::Size(0,0); cv::Size videoFrameSize_ = cv::Size(0, 0);
int vaCaptureDeviceIndex_ = 0; int vaCaptureDeviceIndex_ = 0;
int vaWriterDeviceIndex_ = 0; int vaWriterDeviceIndex_ = 0;
bool mouseDrag_ = false; bool mouseDrag_ = false;
@ -87,7 +86,8 @@ class Viz2D {
Sink sink_; Sink sink_;
std::function<bool(int key, int scancode, int action, int modifiers)> keyEventCb_; std::function<bool(int key, int scancode, int action, int modifiers)> keyEventCb_;
public: public:
Viz2D(const cv::Size &initialSize, const cv::Size& frameBufferSize, bool offscreen, const string &title, int major = 4, int minor = 6, int samples = 0, bool debug = false); Viz2D(const cv::Size& initialSize, const cv::Size& frameBufferSize, bool offscreen,
const string& title, int major = 4, int minor = 6, int samples = 0, bool debug = false);
virtual ~Viz2D(); virtual ~Viz2D();
bool initializeWindowing(); bool initializeWindowing();
void makeCurrent(); void makeCurrent();
@ -100,7 +100,7 @@ public:
void nvg(std::function<void(const cv::Size&)> fn); void nvg(std::function<void(const cv::Size&)> fn);
void nanogui(std::function<void(FormHelper& form)>); void nanogui(std::function<void(FormHelper& form)>);
void clear(const cv::Scalar& rgba = cv::Scalar(0,0,0,255)); void clear(const cv::Scalar& rgba = cv::Scalar(0, 0, 0, 255));
bool capture(); bool capture();
bool capture(std::function<void(cv::UMat&)> fn); bool capture(std::function<void(cv::UMat&)> fn);
@ -146,7 +146,8 @@ public:
bool display(); bool display();
void setDefaultKeyboardEventCallback(); void setDefaultKeyboardEventCallback();
void setKeyboardEventCallback(std::function<bool(int key, int scancode, int action, int modifiers)> fn); void setKeyboardEventCallback(
std::function<bool(int key, int scancode, int action, int modifiers)> fn);
private: private:
bool keyboard_event(int key, int scancode, int action, int modifiers); bool keyboard_event(int key, int scancode, int action, int modifiers);
void setMousePosition(int x, int y); void setMousePosition(int x, int y);

Loading…
Cancel
Save