<commit_before>// Virvo - Virtual Reality Volume Rendering
// Contact: Stefan Zellmann, zellmans@uni-koeln.de
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.

// Glew:

// No circular dependencies between gl.h and glew.h
#ifndef GLEW_INCLUDED
#include <GL/glew.h>
#define GLEW_INCLUDED
#endif

#include "vvgltools.h"
#include "vvoffscreenbuffer.h"

vvOffscreenBuffer::vvOffscreenBuffer(const float scale = 1.0f, const BufferPrecision precision = VV_BYTE)
  : vvRenderTarget()
{
  glewInit();
  _type = VV_OFFSCREEN_BUFFER;
  const vvGLTools::Viewport v = vvGLTools::getViewport();
  _viewportWidth = v.values[2];
  _viewportHeight = v.values[3];
  _scale = scale;
  _preserveDepthBuffer = false;
  _useNVDepthStencil = false;
  _precision = precision;
  glGenTextures(1, &_textureId);
  glGenTextures(1, &_depthTextureId);
  _updatePosted = true;
  _pixels = NULL;
  _scaledDepthBuffer = NULL;
  _depthPixelsF = NULL;
  _depthPixelsNV = NULL;
  resize(_viewportWidth, _viewportHeight);
}

vvOffscreenBuffer::~vvOffscreenBuffer()
{
  delete[] _pixels;
  delete _scaledDepthBuffer;
  delete[] _depthPixelsF;
  delete[] _depthPixelsNV;
}

void vvOffscreenBuffer::initForRender()
{
  if (_preserveDepthBuffer)
  {
    storeDepthBuffer();
  }

  const vvGLTools::Viewport v = vvGLTools::getViewport();
  resize(v.values[2], v.values[3]);

  glPushAttrib(GL_VIEWPORT_BIT);

  // If width and height haven't changed, resize will return immediatly.
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _frameBufferObject);
  glViewport(0, 0, _bufferWidth, _bufferHeight);
  glBindTexture(GL_TEXTURE_2D, 0);
}

void vvOffscreenBuffer::writeBack(const int w, const int h)
{
  if (_preserveDepthBuffer)
  {
    storeColorBuffer();
  }

  vvGLTools::Viewport viewport;
  if ((w == -1) || (h == -1))
  {
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

    glPopAttrib();

    glGetIntegerv(GL_VIEWPORT, viewport.values);
  }
  else
  {
    viewport.values[2] = w;
    viewport.values[3] = h;
  }

  if (_preserveDepthBuffer)
  {
    renderToViewAlignedQuad();
  }
  else
  {
    glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, _frameBufferObject);
    glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0);
    glBlitFramebufferEXT(0, 0, _bufferWidth, _bufferHeight,
                         0, 0, viewport[2], viewport[3],
                         GL_COLOR_BUFFER_BIT, GL_LINEAR);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  }
}

void vvOffscreenBuffer::resize(const int w, const int h)
{
  if ((_viewportWidth == w) && (_viewportHeight == h) && (!_updatePosted))
  {
    return;
  }

  _viewportWidth = w;
  _viewportHeight = h;

  doScale();

  GLuint tex;
  glGenFramebuffersEXT(1, &_frameBufferObject);
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _frameBufferObject);
  glGenRenderbuffersEXT(1, &_depthBuffer);
  glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _depthBuffer);
  glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT32, _bufferWidth, _bufferHeight);
  glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
                               GL_RENDERBUFFER_EXT, _depthBuffer);
  glGenTextures(1, &tex);
  glBindTexture(GL_TEXTURE_2D, tex);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  switch (_precision)
  {
  case VV_BYTE:
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _bufferWidth, _bufferHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    break;
  case VV_SHORT:
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, _bufferWidth, _bufferHeight, 0, GL_RGBA, GL_SHORT, NULL);
    break;
  case VV_FLOAT:
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, _bufferWidth, _bufferHeight, 0, GL_RGBA, GL_FLOAT, NULL);
    break;
  }

  glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D,
                            tex, 0);

  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

  _updatePosted = false;
}

void vvOffscreenBuffer::clearBuffer()
{
  glClearColor(0.0, 0.0, 0.0, 0.0);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  if (_preserveDepthBuffer)
  {
    writeBackDepthBuffer();
  }
}

void vvOffscreenBuffer::bindFramebuffer() const
{
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _frameBufferObject);
}

void vvOffscreenBuffer::unbindFramebuffer() const
{
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

void vvOffscreenBuffer::bindTexture() const
{
  glBindTexture(GL_TEXTURE_2D, _textureId);
}

void vvOffscreenBuffer::setScale(const float scale)
{
  _scale = scale;
  update();
}

void vvOffscreenBuffer::setPreserveDepthBuffer(const bool preserveDepthBuffer)
{
  _preserveDepthBuffer = preserveDepthBuffer;
}

void vvOffscreenBuffer::setUseNVDepthStencil(const bool useNVDepthStencil)
{
  _useNVDepthStencil = useNVDepthStencil;
}

void vvOffscreenBuffer::setPrecision(const BufferPrecision& precision)
{
  _precision = precision;
  update();
}

int vvOffscreenBuffer::getBufferWidth() const
{
  return _bufferWidth;
}

int vvOffscreenBuffer::getBufferHeight() const
{
  return _bufferHeight;
}

float vvOffscreenBuffer::getScale() const
{
  return _scale;
}

bool vvOffscreenBuffer::getPreserveFramebuffer() const
{
  return _preserveDepthBuffer;
}

bool vvOffscreenBuffer::getUseNVDepthStencil() const
{
  return _useNVDepthStencil;
}

BufferPrecision vvOffscreenBuffer::getPrecision() const
{
  return _precision;
}

void vvOffscreenBuffer::doScale()
{
  _bufferWidth = (int)((float)_viewportWidth * _scale);
  _bufferHeight = (int)((float)_viewportHeight * _scale);
}

void vvOffscreenBuffer::update()
{
  // After the next render step, the resize() method won't return although size didn't change.
  _updatePosted = true;
}

void vvOffscreenBuffer::storeColorBuffer()
{
  delete[] _pixels;
  _pixels = new unsigned char[_bufferWidth * _bufferHeight * 4];
  glReadPixels(0, 0, _bufferWidth, _bufferHeight, GL_RGBA, GL_UNSIGNED_BYTE, _pixels);
}

void vvOffscreenBuffer::storeDepthBuffer()
{
  glFinish();

  delete _scaledDepthBuffer;
  _scaledDepthBuffer = new vvOffscreenBuffer(_scale);

  glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0);
  glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, _scaledDepthBuffer->_frameBufferObject);
  glBlitFramebufferEXT(0, 0, _viewportWidth, _viewportHeight,
                       0, 0, _scaledDepthBuffer->_bufferWidth, _scaledDepthBuffer->_bufferHeight,
                       GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  _scaledDepthBuffer->bindFramebuffer();

  delete[] _depthPixelsNV;
  delete[] _depthPixelsF;

  if (_useNVDepthStencil)
  {
    _depthPixelsNV = new GLuint[_bufferWidth * _bufferHeight];
    glReadPixels(0, 0, _bufferWidth, _bufferHeight, GL_DEPTH_STENCIL_NV, GL_UNSIGNED_INT_24_8_NV, _depthPixelsNV);
  }
  else
  {
    _depthPixelsF = new float[_bufferWidth * _bufferHeight];
    glReadPixels(0, 0, _bufferWidth, _bufferHeight, GL_DEPTH_COMPONENT, GL_FLOAT, _depthPixelsF);
  }
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

void vvOffscreenBuffer::renderToViewAlignedQuad() const
{
  glMatrixMode(GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();

  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();

  glPushAttrib(GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT
               | GL_ENABLE_BIT | GL_TEXTURE_BIT | GL_TRANSFORM_BIT);

  glDisable(GL_CULL_FACE);
  glDisable(GL_LIGHTING);
  glDisable(GL_DEPTH_TEST);
  glEnable(GL_COLOR_MATERIAL);
  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

  glEnable(GL_TEXTURE_2D);
  bindTexture();
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _bufferWidth, _bufferHeight,
               0, GL_RGBA, GL_UNSIGNED_BYTE, _pixels);
  vvGLTools::drawViewAlignedQuad();
  glDeleteTextures(1, &_textureId);

  glPopAttrib();

  glPopMatrix();
  glMatrixMode(GL_PROJECTION);
  glPopMatrix();
}

void vvOffscreenBuffer::writeBackDepthBuffer() const
{
  glPushAttrib(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);

  glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  glDepthMask(GL_TRUE);
  glDepthFunc(GL_ALWAYS);
  glEnable(GL_DEPTH_TEST);
  glWindowPos2i(0, 0);

  if (_useNVDepthStencil)
  {
    glDrawPixels(_bufferWidth, _bufferHeight, GL_DEPTH_STENCIL_NV, GL_UNSIGNED_INT_24_8_NV, _depthPixelsNV);
  }
  else
  {
    glDrawPixels(_bufferWidth, _bufferHeight, GL_DEPTH_COMPONENT, GL_FLOAT, _depthPixelsF);
  }

  glPopClientAttrib();
  glPopAttrib();
}
<commit_msg>Freeing offscreen buffer resources is a good idea when generating and destroying one each frame...<commit_after>// Virvo - Virtual Reality Volume Rendering
// Contact: Stefan Zellmann, zellmans@uni-koeln.de
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.

// Glew:

// No circular dependencies between gl.h and glew.h
#ifndef GLEW_INCLUDED
#include <GL/glew.h>
#define GLEW_INCLUDED
#endif

#include "vvgltools.h"
#include "vvoffscreenbuffer.h"

vvOffscreenBuffer::vvOffscreenBuffer(const float scale = 1.0f, const BufferPrecision precision = VV_BYTE)
  : vvRenderTarget()
{
  glewInit();
  _type = VV_OFFSCREEN_BUFFER;
  const vvGLTools::Viewport v = vvGLTools::getViewport();
  _viewportWidth = v.values[2];
  _viewportHeight = v.values[3];
  _scale = scale;
  _preserveDepthBuffer = false;
  _useNVDepthStencil = false;
  _precision = precision;
  glGenTextures(1, &_textureId);
  glGenTextures(1, &_depthTextureId);
  _updatePosted = true;
  _pixels = NULL;
  _scaledDepthBuffer = NULL;
  _depthPixelsF = NULL;
  _depthPixelsNV = NULL;
  resize(_viewportWidth, _viewportHeight);
}

vvOffscreenBuffer::~vvOffscreenBuffer()
{
  delete[] _pixels;
  delete _scaledDepthBuffer;
  delete[] _depthPixelsF;
  delete[] _depthPixelsNV;

  glDeleteTextures(1, &_colorBuffer);
  glDeleteRenderbuffersEXT(1, &_depthBuffer);
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  glDeleteFramebuffersEXT(1, &_frameBufferObject);
}

void vvOffscreenBuffer::initForRender()
{
  if (_preserveDepthBuffer)
  {
    storeDepthBuffer();
  }

  const vvGLTools::Viewport v = vvGLTools::getViewport();
  resize(v.values[2], v.values[3]);

  glPushAttrib(GL_VIEWPORT_BIT);

  // If width and height haven't changed, resize will return immediatly.
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _frameBufferObject);
  glViewport(0, 0, _bufferWidth, _bufferHeight);
  glBindTexture(GL_TEXTURE_2D, 0);
}

void vvOffscreenBuffer::writeBack(const int w, const int h)
{
  if (_preserveDepthBuffer)
  {
    storeColorBuffer();
  }

  vvGLTools::Viewport viewport;
  if ((w == -1) || (h == -1))
  {
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

    glPopAttrib();

    glGetIntegerv(GL_VIEWPORT, viewport.values);
  }
  else
  {
    viewport.values[2] = w;
    viewport.values[3] = h;
  }

  if (_preserveDepthBuffer)
  {
    renderToViewAlignedQuad();
  }
  else
  {
    glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, _frameBufferObject);
    glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0);
    glBlitFramebufferEXT(0, 0, _bufferWidth, _bufferHeight,
                         0, 0, viewport[2], viewport[3],
                         GL_COLOR_BUFFER_BIT, GL_LINEAR);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  }
}

void vvOffscreenBuffer::resize(const int w, const int h)
{
  if ((_viewportWidth == w) && (_viewportHeight == h) && (!_updatePosted))
  {
    return;
  }

  _viewportWidth = w;
  _viewportHeight = h;

  doScale();

  glGenFramebuffersEXT(1, &_frameBufferObject);
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _frameBufferObject);
  glGenRenderbuffersEXT(1, &_depthBuffer);
  glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _depthBuffer);
  glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT32, _bufferWidth, _bufferHeight);
  glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
                               GL_RENDERBUFFER_EXT, _depthBuffer);
  glGenTextures(1, &_colorBuffer);
  glBindTexture(GL_TEXTURE_2D, _colorBuffer);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  switch (_precision)
  {
  case VV_BYTE:
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _bufferWidth, _bufferHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    break;
  case VV_SHORT:
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, _bufferWidth, _bufferHeight, 0, GL_RGBA, GL_SHORT, NULL);
    break;
  case VV_FLOAT:
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, _bufferWidth, _bufferHeight, 0, GL_RGBA, GL_FLOAT, NULL);
    break;
  }

  glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D,
                            _colorBuffer, 0);

  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

  _updatePosted = false;
}

void vvOffscreenBuffer::clearBuffer()
{
  glClearColor(0.0, 0.0, 0.0, 0.0);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  if (_preserveDepthBuffer)
  {
    writeBackDepthBuffer();
  }
}

void vvOffscreenBuffer::bindFramebuffer() const
{
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _frameBufferObject);
}

void vvOffscreenBuffer::unbindFramebuffer() const
{
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

void vvOffscreenBuffer::bindTexture() const
{
  glBindTexture(GL_TEXTURE_2D, _textureId);
}

void vvOffscreenBuffer::setScale(const float scale)
{
  _scale = scale;
  update();
}

void vvOffscreenBuffer::setPreserveDepthBuffer(const bool preserveDepthBuffer)
{
  _preserveDepthBuffer = preserveDepthBuffer;
}

void vvOffscreenBuffer::setUseNVDepthStencil(const bool useNVDepthStencil)
{
  _useNVDepthStencil = useNVDepthStencil;
}

void vvOffscreenBuffer::setPrecision(const BufferPrecision& precision)
{
  _precision = precision;
  update();
}

int vvOffscreenBuffer::getBufferWidth() const
{
  return _bufferWidth;
}

int vvOffscreenBuffer::getBufferHeight() const
{
  return _bufferHeight;
}

float vvOffscreenBuffer::getScale() const
{
  return _scale;
}

bool vvOffscreenBuffer::getPreserveFramebuffer() const
{
  return _preserveDepthBuffer;
}

bool vvOffscreenBuffer::getUseNVDepthStencil() const
{
  return _useNVDepthStencil;
}

BufferPrecision vvOffscreenBuffer::getPrecision() const
{
  return _precision;
}

void vvOffscreenBuffer::doScale()
{
  _bufferWidth = (int)((float)_viewportWidth * _scale);
  _bufferHeight = (int)((float)_viewportHeight * _scale);
}

void vvOffscreenBuffer::update()
{
  // After the next render step, the resize() method won't return although size didn't change.
  _updatePosted = true;
}

void vvOffscreenBuffer::storeColorBuffer()
{
  delete[] _pixels;
  _pixels = new unsigned char[_bufferWidth * _bufferHeight * 4];
  glReadPixels(0, 0, _bufferWidth, _bufferHeight, GL_RGBA, GL_UNSIGNED_BYTE, _pixels);
}

void vvOffscreenBuffer::storeDepthBuffer()
{
  glFinish();

  delete _scaledDepthBuffer;
  _scaledDepthBuffer = new vvOffscreenBuffer(_scale);

  glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0);
  glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, _scaledDepthBuffer->_frameBufferObject);
  glBlitFramebufferEXT(0, 0, _viewportWidth, _viewportHeight,
                       0, 0, _scaledDepthBuffer->_bufferWidth, _scaledDepthBuffer->_bufferHeight,
                       GL_DEPTH_BUFFER_BIT, GL_NEAREST);
  _scaledDepthBuffer->bindFramebuffer();

  delete[] _depthPixelsNV;
  delete[] _depthPixelsF;

  if (_useNVDepthStencil)
  {
    _depthPixelsNV = new GLuint[_bufferWidth * _bufferHeight];
    glReadPixels(0, 0, _bufferWidth, _bufferHeight, GL_DEPTH_STENCIL_NV, GL_UNSIGNED_INT_24_8_NV, _depthPixelsNV);
  }
  else
  {
    _depthPixelsF = new float[_bufferWidth * _bufferHeight];
    glReadPixels(0, 0, _bufferWidth, _bufferHeight, GL_DEPTH_COMPONENT, GL_FLOAT, _depthPixelsF);
  }
  glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}

void vvOffscreenBuffer::renderToViewAlignedQuad() const
{
  glMatrixMode(GL_PROJECTION);
  glPushMatrix();
  glLoadIdentity();

  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();

  glPushAttrib(GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT
               | GL_ENABLE_BIT | GL_TEXTURE_BIT | GL_TRANSFORM_BIT);

  glDisable(GL_CULL_FACE);
  glDisable(GL_LIGHTING);
  glDisable(GL_DEPTH_TEST);
  glEnable(GL_COLOR_MATERIAL);
  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

  glEnable(GL_TEXTURE_2D);
  bindTexture();
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _bufferWidth, _bufferHeight,
               0, GL_RGBA, GL_UNSIGNED_BYTE, _pixels);
  vvGLTools::drawViewAlignedQuad();
  glDeleteTextures(1, &_textureId);vvGLTools::printGLError("ERROR");

  glPopAttrib();

  glPopMatrix();
  glMatrixMode(GL_PROJECTION);
  glPopMatrix();
}

void vvOffscreenBuffer::writeBackDepthBuffer() const
{
  glPushAttrib(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);

  glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  glDepthMask(GL_TRUE);
  glDepthFunc(GL_ALWAYS);
  glEnable(GL_DEPTH_TEST);
  glWindowPos2i(0, 0);

  if (_useNVDepthStencil)
  {
    glDrawPixels(_bufferWidth, _bufferHeight, GL_DEPTH_STENCIL_NV, GL_UNSIGNED_INT_24_8_NV, _depthPixelsNV);
  }
  else
  {
    glDrawPixels(_bufferWidth, _bufferHeight, GL_DEPTH_COMPONENT, GL_FLOAT, _depthPixelsF);
  }

  glPopClientAttrib();
  glPopAttrib();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: unocontrolbase.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: mt $ $Date: 2001-10-11 14:56:21 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _TOOLKIT_AWT_UNOCONTROLBASE_HXX_
#define _TOOLKIT_AWT_UNOCONTROLBASE_HXX_

#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif

#include <toolkit/controls/unocontrol.hxx>

//  ----------------------------------------------------
//  class UnoControlBase
//  ----------------------------------------------------

class UnoControlBase : public UnoControl
{
protected:
    sal_Bool                    ImplHasProperty( sal_uInt16 nProp );
    sal_Bool                    ImplHasProperty( const ::rtl::OUString& aPropertyName );
    void                        ImplSetPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue, sal_Bool bUpdateThis );
    ::com::sun::star::uno::Any  ImplGetPropertyValue( const ::rtl::OUString& aPropertyName );

    sal_Bool        ImplGetPropertyValue_BOOL( sal_uInt16 nProp );
    sal_Int16       ImplGetPropertyValue_INT16( sal_uInt16 nProp );
    sal_uInt16      ImplGetPropertyValue_UINT16( sal_uInt16 nProp );
    sal_Int32       ImplGetPropertyValue_INT32( sal_uInt16 nProp );
    sal_uInt32      ImplGetPropertyValue_UINT32( sal_uInt16 nProp );
    double          ImplGetPropertyValue_DOUBLE( sal_uInt16 nProp );
    ::rtl::OUString ImplGetPropertyValue_UString( sal_uInt16 nProp );

    // XLayoutConstrains (nur wenn das Control es unterstuetzt!)
    ::com::sun::star::awt::Size Impl_getMinimumSize();
    ::com::sun::star::awt::Size Impl_getPreferredSize();
    ::com::sun::star::awt::Size Impl_calcAdjustedSize( const ::com::sun::star::awt::Size& rNewSize );

    // XTextLayoutConstrains (nur wenn das Control es unterstuetzt!)
    ::com::sun::star::awt::Size Impl_getMinimumSize( sal_Int16 nCols, sal_Int16 nLines );
    void                        Impl_getColumnsAndLines( sal_Int16& nCols, sal_Int16& nLines );
};

#endif // _TOOLKIT_AWT_UNOCONTROLBASE_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.420); FILE MERGED 2005/09/05 16:57:45 rt 1.2.420.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unocontrolbase.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:51:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _TOOLKIT_AWT_UNOCONTROLBASE_HXX_
#define _TOOLKIT_AWT_UNOCONTROLBASE_HXX_

#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif

#include <toolkit/controls/unocontrol.hxx>

//  ----------------------------------------------------
//  class UnoControlBase
//  ----------------------------------------------------

class UnoControlBase : public UnoControl
{
protected:
    sal_Bool                    ImplHasProperty( sal_uInt16 nProp );
    sal_Bool                    ImplHasProperty( const ::rtl::OUString& aPropertyName );
    void                        ImplSetPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue, sal_Bool bUpdateThis );
    ::com::sun::star::uno::Any  ImplGetPropertyValue( const ::rtl::OUString& aPropertyName );

    sal_Bool        ImplGetPropertyValue_BOOL( sal_uInt16 nProp );
    sal_Int16       ImplGetPropertyValue_INT16( sal_uInt16 nProp );
    sal_uInt16      ImplGetPropertyValue_UINT16( sal_uInt16 nProp );
    sal_Int32       ImplGetPropertyValue_INT32( sal_uInt16 nProp );
    sal_uInt32      ImplGetPropertyValue_UINT32( sal_uInt16 nProp );
    double          ImplGetPropertyValue_DOUBLE( sal_uInt16 nProp );
    ::rtl::OUString ImplGetPropertyValue_UString( sal_uInt16 nProp );

    // XLayoutConstrains (nur wenn das Control es unterstuetzt!)
    ::com::sun::star::awt::Size Impl_getMinimumSize();
    ::com::sun::star::awt::Size Impl_getPreferredSize();
    ::com::sun::star::awt::Size Impl_calcAdjustedSize( const ::com::sun::star::awt::Size& rNewSize );

    // XTextLayoutConstrains (nur wenn das Control es unterstuetzt!)
    ::com::sun::star::awt::Size Impl_getMinimumSize( sal_Int16 nCols, sal_Int16 nLines );
    void                        Impl_getColumnsAndLines( sal_Int16& nCols, sal_Int16& nLines );
};

#endif // _TOOLKIT_AWT_UNOCONTROLBASE_HXX_

<|endoftext|>


<commit_before>#include <iostream>
#include <math.h>
#include <string.h>
#include <vector>
#include <map>
#include "mex.h"

#include <nix.hpp>

#include "handle.h"
#include "arguments.h"
#include "struct.h"
#include "datatypes.h"

// helpers

void check_arg_type(const mxArray *arr, nix::DataType dtype) {
    if (dtype_mex2nix(arr) != dtype) {
        throw std::invalid_argument("wrong type");
    }
}

// extractors

nix::NDSize mx_to_ndsize(const mxArray *arr) {

    size_t m = mxGetM(arr);
    size_t n = mxGetN(arr);

    //if (m != 1 && n != 1)

    size_t k = std::max(n, m);
    nix::NDSize size(k);

    double *data = mxGetPr(arr);
    for (size_t i = 0; i < size.size(); i++) {
        size[i] = static_cast<nix::NDSize::value_type>(data[i]);
    }

    return size;
}

std::vector<std::string> mx_to_strings(const mxArray *arr) {
    /*
    To convert to a string vector we actually expect a cell
    array of strings. It's a logical representation since matlab
    arrays require that elements have equal length.
    */
    std::vector<std::string> res;
    const mxArray *el_ptr;

    mwSize length = mxGetNumberOfElements(arr);
    mwIndex index;

    for (index = 0; index < length; index++)  {
        el_ptr = mxGetCell(arr, index);

        if (!mxIsChar(el_ptr)) {
            throw std::invalid_argument("All elements of a cell array should be of a string type");
        }

        char *tmp = mxArrayToString(el_ptr);
        std::string the_string(tmp);
        res.push_back(the_string);
        mxFree(tmp);
    }

    return res;
}

nix::LinkType mx_to_linktype(const mxArray *arr) {
    const uint8_t link_type = mx_to_num<uint8_t>(arr);
    nix::LinkType retLinkType;

    switch (link_type) {
    case 0: retLinkType = nix::LinkType::Tagged; break;
    case 1: retLinkType = nix::LinkType::Untagged; break;
    case 2: retLinkType = nix::LinkType::Indexed; break;
    default: throw std::invalid_argument("unkown link type");
    }

    return retLinkType;
}

std::string mx_to_str(const mxArray *arr) {
    check_arg_type(arr, nix::DataType::String);

    std::string the_string = mxArrayToString(arr);
    return the_string;
}

bool mx_to_bool(const mxArray *arr) {
    check_arg_type(arr, nix::DataType::Bool);

    const mxLogical *l = mxGetLogicals(arr);
    return l[0];
}

nix::Value mx_to_value_from_scalar(const mxArray *arr) {
    /*
    Assuming arr is a scalar mxArray.
    */
    nix::Value val;

    switch (mxGetClassID(arr)) {
    case mxLOGICAL_CLASS: val.set(mx_to_bool(arr)); break;
    case mxCHAR_CLASS: val.set(mx_to_str(arr)); break;
    case mxDOUBLE_CLASS: val.set(mx_to_num<double>(arr)); break;
    case mxUINT32_CLASS: val.set(mx_to_num<uint32_t>(arr)); break;
    case mxINT32_CLASS:  val.set(mx_to_num<int32_t>(arr)); break;
    case mxUINT64_CLASS: val.set(mx_to_num<uint64_t>(arr)); break;
    case mxINT64_CLASS:  val.set(mx_to_num<int64_t>(arr)); break;

    case mxSINGLE_CLASS: throw std::invalid_argument("Element type is not supported");
    case mxUINT8_CLASS:  throw std::invalid_argument("Element type is not supported");
    case mxINT8_CLASS:   throw std::invalid_argument("Element type is not supported");
    case mxUINT16_CLASS: throw std::invalid_argument("Element type is not supported");
    case mxINT16_CLASS:  throw std::invalid_argument("Element type is not supported");

    default: throw std::invalid_argument("Element type is not recognized");
    }

    return val;
}

nix::Value mx_to_value_from_struct(const mxArray *arr) {
    /*
    Assuming arr is a struct mxArray.
    */
    static std::map<std::string, int> arg_map = {
        { "value", 0 },
        { "uncertainty", 1 },
        { "checksum", 2 },
        { "encoder", 3 },
        { "filename", 4 },
        { "reference", 5 }
    };

    nix::Value val;
    bool has_value = false;

    int number_of_fields = mxGetNumberOfFields(arr);
    for (int idx = 0; idx < number_of_fields; idx++)  {
        const char  *field_name = mxGetFieldNameByNumber(arr, idx);
        const mxArray *field_array_ptr = mxGetFieldByNumber(arr, 0, idx);

        std::string arg_name = field_name;
        switch (arg_map[arg_name]) {
        case 0: val = mx_to_value_from_scalar(field_array_ptr); break;
        case 1: val.uncertainty = mx_to_num<double>(field_array_ptr); break;
        case 2: val.checksum = mx_to_str(field_array_ptr); break;
        case 3: val.encoder = mx_to_str(field_array_ptr); break;
        case 4: val.filename = mx_to_str(field_array_ptr); break;
        case 5: val.reference = mx_to_str(field_array_ptr); break;
        default: throw std::invalid_argument(strcat("Field is not supported: ", field_name));
        }
    }

    return val;
}

std::vector<nix::Value> mx_to_values(const mxArray *arr) {
    /*
    To convert to a vector of Values we actually expect either
    - a cell array with scalar values, or
    - a cell array with structs each having Value attrs
    (uncertainty, checksum etc.) as fields
    */
    std::vector<nix::Value> vals;
    const mxArray *cell_element_ptr;

    if (mxGetClassID(arr) == mxCELL_CLASS) {

        mwSize size = mxGetNumberOfElements(arr);
        for (mwIndex index = 0; index < size; index++)  {
            cell_element_ptr = mxGetCell(arr, index);

            if (mxGetClassID(cell_element_ptr) == mxSTRUCT_CLASS) {
                // assume values are given as matlab structs
                vals.push_back(mx_to_value_from_struct(cell_element_ptr));
            } else {
                // assume just a scalar value given
                vals.push_back(mx_to_value_from_scalar(cell_element_ptr));
            }
        }
    } else {
        throw std::invalid_argument("Values must be given as cell array");
    }

    return vals;
}<commit_msg>to_value_from_struct: replace strcat with string+<commit_after>#include <iostream>
#include <math.h>
#include <string.h>
#include <vector>
#include <map>
#include "mex.h"

#include <nix.hpp>

#include "handle.h"
#include "arguments.h"
#include "struct.h"
#include "datatypes.h"

// helpers

void check_arg_type(const mxArray *arr, nix::DataType dtype) {
    if (dtype_mex2nix(arr) != dtype) {
        throw std::invalid_argument("wrong type");
    }
}

// extractors

nix::NDSize mx_to_ndsize(const mxArray *arr) {

    size_t m = mxGetM(arr);
    size_t n = mxGetN(arr);

    //if (m != 1 && n != 1)

    size_t k = std::max(n, m);
    nix::NDSize size(k);

    double *data = mxGetPr(arr);
    for (size_t i = 0; i < size.size(); i++) {
        size[i] = static_cast<nix::NDSize::value_type>(data[i]);
    }

    return size;
}

std::vector<std::string> mx_to_strings(const mxArray *arr) {
    /*
    To convert to a string vector we actually expect a cell
    array of strings. It's a logical representation since matlab
    arrays require that elements have equal length.
    */
    std::vector<std::string> res;
    const mxArray *el_ptr;

    mwSize length = mxGetNumberOfElements(arr);
    mwIndex index;

    for (index = 0; index < length; index++)  {
        el_ptr = mxGetCell(arr, index);

        if (!mxIsChar(el_ptr)) {
            throw std::invalid_argument("All elements of a cell array should be of a string type");
        }

        char *tmp = mxArrayToString(el_ptr);
        std::string the_string(tmp);
        res.push_back(the_string);
        mxFree(tmp);
    }

    return res;
}

nix::LinkType mx_to_linktype(const mxArray *arr) {
    const uint8_t link_type = mx_to_num<uint8_t>(arr);
    nix::LinkType retLinkType;

    switch (link_type) {
    case 0: retLinkType = nix::LinkType::Tagged; break;
    case 1: retLinkType = nix::LinkType::Untagged; break;
    case 2: retLinkType = nix::LinkType::Indexed; break;
    default: throw std::invalid_argument("unkown link type");
    }

    return retLinkType;
}

std::string mx_to_str(const mxArray *arr) {
    check_arg_type(arr, nix::DataType::String);

    std::string the_string = mxArrayToString(arr);
    return the_string;
}

bool mx_to_bool(const mxArray *arr) {
    check_arg_type(arr, nix::DataType::Bool);

    const mxLogical *l = mxGetLogicals(arr);
    return l[0];
}

nix::Value mx_to_value_from_scalar(const mxArray *arr) {
    /*
    Assuming arr is a scalar mxArray.
    */
    nix::Value val;

    switch (mxGetClassID(arr)) {
    case mxLOGICAL_CLASS: val.set(mx_to_bool(arr)); break;
    case mxCHAR_CLASS: val.set(mx_to_str(arr)); break;
    case mxDOUBLE_CLASS: val.set(mx_to_num<double>(arr)); break;
    case mxUINT32_CLASS: val.set(mx_to_num<uint32_t>(arr)); break;
    case mxINT32_CLASS:  val.set(mx_to_num<int32_t>(arr)); break;
    case mxUINT64_CLASS: val.set(mx_to_num<uint64_t>(arr)); break;
    case mxINT64_CLASS:  val.set(mx_to_num<int64_t>(arr)); break;

    case mxSINGLE_CLASS: throw std::invalid_argument("Element type is not supported");
    case mxUINT8_CLASS:  throw std::invalid_argument("Element type is not supported");
    case mxINT8_CLASS:   throw std::invalid_argument("Element type is not supported");
    case mxUINT16_CLASS: throw std::invalid_argument("Element type is not supported");
    case mxINT16_CLASS:  throw std::invalid_argument("Element type is not supported");

    default: throw std::invalid_argument("Element type is not recognized");
    }

    return val;
}

nix::Value mx_to_value_from_struct(const mxArray *arr) {
    /*
    Assuming arr is a struct mxArray.
    */
    static std::map<std::string, int> arg_map = {
        { "value", 0 },
        { "uncertainty", 1 },
        { "checksum", 2 },
        { "encoder", 3 },
        { "filename", 4 },
        { "reference", 5 }
    };

    nix::Value val;
    bool has_value = false;

    int number_of_fields = mxGetNumberOfFields(arr);
    for (int idx = 0; idx < number_of_fields; idx++)  {
        const char  *field_name = mxGetFieldNameByNumber(arr, idx);
        const mxArray *field_array_ptr = mxGetFieldByNumber(arr, 0, idx);

        std::string arg_name = field_name;
        switch (arg_map[arg_name]) {
        case 0: val = mx_to_value_from_scalar(field_array_ptr); break;
        case 1: val.uncertainty = mx_to_num<double>(field_array_ptr); break;
        case 2: val.checksum = mx_to_str(field_array_ptr); break;
        case 3: val.encoder = mx_to_str(field_array_ptr); break;
        case 4: val.filename = mx_to_str(field_array_ptr); break;
        case 5: val.reference = mx_to_str(field_array_ptr); break;
        default: throw std::invalid_argument(std::string("Field is not supported: ") + std::string(field_name));
        }
    }

    return val;
}

std::vector<nix::Value> mx_to_values(const mxArray *arr) {
    /*
    To convert to a vector of Values we actually expect either
    - a cell array with scalar values, or
    - a cell array with structs each having Value attrs
    (uncertainty, checksum etc.) as fields
    */
    std::vector<nix::Value> vals;
    const mxArray *cell_element_ptr;

    if (mxGetClassID(arr) == mxCELL_CLASS) {

        mwSize size = mxGetNumberOfElements(arr);
        for (mwIndex index = 0; index < size; index++)  {
            cell_element_ptr = mxGetCell(arr, index);

            if (mxGetClassID(cell_element_ptr) == mxSTRUCT_CLASS) {
                // assume values are given as matlab structs
                vals.push_back(mx_to_value_from_struct(cell_element_ptr));
            } else {
                // assume just a scalar value given
                vals.push_back(mx_to_value_from_scalar(cell_element_ptr));
            }
        }
    } else {
        throw std::invalid_argument("Values must be given as cell array");
    }

    return vals;
}
<|endoftext|>


<commit_before>#include <catch.hpp>

#ifndef WX_PRECOMP
    #include "wx/app.h"
    #include "wx/sizer.h"
    #include "wx/uiaction.h"
#endif // WX_PRECOMP
#include <iostream>
#include <string>
#include "testableframe.h"
#include "OptionsGroup/Field.hpp"
#include "ConfigBase.hpp"

using namespace Slic3r::GUI;
using namespace std::string_literals;

SCENARIO( "TextCtrl initializes with default value if available.") {
    wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());

    old->Destroy();
    wxTheApp->SetTopWindow(new wxTestableFrame());
    wxMilliSleep(250);

    Slic3r::ConfigOptionDef simple_option;
    simple_option.type = coInt;
    auto* intopt { new Slic3r::ConfigOptionInt(7) };
    simple_option.default_value = intopt; // no delete, it's taken care of by ConfigOptionDef
    GIVEN ( "A UI Textctrl") {
        auto test_field {Slic3r::GUI::UI_TextCtrl(wxTheApp->GetTopWindow(), simple_option)};

        wxTheApp->GetTopWindow()->Show();
        wxTheApp->GetTopWindow()->Fit();

        REQUIRE(test_field.get_string() == "7"s);
    }
}

SCENARIO( "Receiving a Textctrl event") {
    wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
    old->Destroy();
    wxTheApp->SetTopWindow(new wxTestableFrame());
    wxMilliSleep(250);
    GIVEN ( "A UI Textctrl") {
        auto exec_counter {0};
        auto changefunc {[&exec_counter] (const std::string& opt_id, std::string value) { exec_counter++; }};
        auto test_field {Slic3r::GUI::UI_TextCtrl(wxTheApp->GetTopWindow(), Slic3r::ConfigOptionDef())};

        test_field.on_change = changefunc;

        wxTheApp->GetTopWindow()->Show();
        wxTheApp->GetTopWindow()->Fit();
        WHEN( "A text event occurs") {
            exec_counter = 0;
            auto ev {wxCommandEvent(wxEVT_TEXT_ENTER, test_field.textctrl()->GetId())};
            ev.SetEventObject(test_field.textctrl());
            test_field.textctrl()->ProcessWindowEvent(ev);
            wxYield();
            wxMilliSleep(250);
            THEN( "on_change is executed.") {
                REQUIRE(exec_counter == 1);
            }
        }
        WHEN( "A text event occurs and change event is disabled") {
            exec_counter = 0;
            test_field.disable_change_event = false;
            auto ev {wxCommandEvent(wxEVT_TEXT_ENTER, test_field.textctrl()->GetId())};
            ev.SetEventObject(test_field.textctrl());
            test_field.textctrl()->ProcessWindowEvent(ev);
            wxYield();
            wxMilliSleep(250);
            THEN( "on_change is not executed.") {
                REQUIRE(exec_counter == 1);
            }
        }
    }
}

SCENARIO( "TextCtrl: Changing the text via entry works on pressing enter") {
    wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
    old->Destroy();
    wxTheApp->SetTopWindow(new wxTestableFrame());
    wxUIActionSimulator sim;
    wxMilliSleep(500);
    GIVEN ( "A UI Textctrl") {
        auto exec_counter {0};
        auto changefunc {[&exec_counter] (const std::string& opt_id, std::string value) { exec_counter++; }};
        auto test_field {Slic3r::GUI::UI_TextCtrl(wxTheApp->GetTopWindow(), Slic3r::ConfigOptionDef())};

        test_field.on_change = changefunc;

        wxTheApp->GetTopWindow()->Show();
        wxTheApp->GetTopWindow()->Fit();
        WHEN( "A number is entered followed by enter key") {
            exec_counter = 0;
            test_field.textctrl()->SetFocus();
            wxYield();
            wxMilliSleep(250);
            sim.Char('3');
            wxMilliSleep(250);
            sim.Char(WXK_RETURN);
            wxMilliSleep(250);
            wxYield();
            THEN( "on_change is executed.") {
                REQUIRE(exec_counter == 1);
            }
            THEN( "get_string returns entered value.") {
                REQUIRE(test_field.get_string() == "3"s);
            }
        }
        WHEN( "A number is entered followed by enter key and change event is disabled") {
            exec_counter = 0;
            test_field.disable_change_event = true;
            test_field.textctrl()->SetFocus();
            wxYield();
            wxMilliSleep(250);
            sim.Char('3');
            wxMilliSleep(250);
            sim.Char(WXK_RETURN);
            wxMilliSleep(250);
            wxYield();
            THEN( "on_change is not executed.") {
                REQUIRE(exec_counter == 0);
            }
            THEN( "get_string returns entered value.") {
                REQUIRE(test_field.get_string() == "3"s);
            }
        }
        WHEN( "A number is entered and focus is lost") {
            auto killfunc {[&exec_counter](const std::string& opt_id) { exec_counter += 1; }};
            test_field.on_kill_focus = killfunc;

            auto ev {wxFocusEvent(wxEVT_KILL_FOCUS, test_field.textctrl()->GetId())};
            ev.SetEventObject(test_field.textctrl());

            exec_counter = 0;
            test_field.textctrl()->SetValue("3");
            test_field.textctrl()->SetFocus();
            wxYield();
            wxMilliSleep(250);
            sim.Char('7');
            wxYield();
            wxMilliSleep(250);
            test_field.textctrl()->ProcessWindowEvent(ev);
            wxMilliSleep(250);
            wxYield();
            THEN( "on_kill_focus is executed and on_change are both executed.") {
                REQUIRE(exec_counter == 2);
            }
            THEN( "get_string returns updated value.") {
                REQUIRE(test_field.get_string() == "7"s);
            }
            THEN( "get_bool returns 0.") {
                REQUIRE(test_field.get_bool() == 0);
            }
            THEN( "get_int returns 0.") {
                REQUIRE(test_field.get_int() == 0);
            }
        }

    }
}

SCENARIO( "Multiline doesn't update other than on focus change.") {
    wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
    old->Destroy();
    wxTheApp->SetTopWindow(new wxTestableFrame());
    wxUIActionSimulator sim;
    wxMilliSleep(500);

    Slic3r::ConfigOptionDef simple_option;
    simple_option.type = coInt;
    simple_option.multiline = true;
    auto* stropt { new Slic3r::ConfigOptionString("7") };
    GIVEN ( "A UI Textctrl") {
        auto exec_counter {0};
        auto changefunc {[&exec_counter] (const std::string& opt_id, std::string value) { exec_counter++; }};
        auto test_field {Slic3r::GUI::UI_TextCtrl(wxTheApp->GetTopWindow(), Slic3r::ConfigOptionDef())};

        test_field.on_change = changefunc;

        wxTheApp->GetTopWindow()->Show();
        wxTheApp->GetTopWindow()->Fit();
        WHEN( "pressing enter") {
            auto killfunc {[&exec_counter](const std::string& opt_id) { exec_counter += 1; }};
            test_field.on_kill_focus = killfunc;

            auto ev {wxFocusEvent(wxEVT_KILL_FOCUS, test_field.textctrl()->GetId())};
            ev.SetEventObject(test_field.textctrl());

            exec_counter = 0;
            test_field.textctrl()->SetValue("3");
            test_field.textctrl()->SetFocus();
            wxYield();
            wxMilliSleep(250);
            sim.Char('7');
            wxYield();
            wxMilliSleep(250);
            test_field.textctrl()->ProcessWindowEvent(ev);
            wxMilliSleep(250);
            wxYield();
            THEN( "on_kill_focus is executed and on_change are both executed.") {
                REQUIRE(exec_counter == 2);
            }
            THEN( "get_string returns updated value.") {
                REQUIRE(test_field.get_string() == "77"s);
            }
            THEN( "get_bool returns 0.") {
                REQUIRE(test_field.get_bool() == 0);
            }
            THEN( "get_int returns 0.") {
                REQUIRE(test_field.get_int() == 0);
            }
        }
    }
}
<commit_msg>all tests pass<commit_after>#include <catch.hpp>

#ifndef WX_PRECOMP
    #include "wx/app.h"
    #include "wx/sizer.h"
    #include "wx/uiaction.h"
#endif // WX_PRECOMP
#include <iostream>
#include <string>
#include "testableframe.h"
#include "OptionsGroup/Field.hpp"
#include "ConfigBase.hpp"

using namespace Slic3r::GUI;
using namespace std::string_literals;

SCENARIO( "TextCtrl initializes with default value if available.") {
    wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());

    old->Destroy();
    wxTheApp->SetTopWindow(new wxTestableFrame());
    wxMilliSleep(250);

    Slic3r::ConfigOptionDef simple_option;
    simple_option.type = coString;
    auto* stropt { new Slic3r::ConfigOptionString("7") };
    simple_option.default_value = stropt; // no delete, it's taken care of by ConfigOptionDef
    GIVEN ( "A UI Textctrl") {
        auto test_field {Slic3r::GUI::UI_TextCtrl(wxTheApp->GetTopWindow(), simple_option)};

        wxTheApp->GetTopWindow()->Show();
        wxTheApp->GetTopWindow()->Fit();

        REQUIRE(test_field.get_string() == "7"s);
    }
}

SCENARIO( "Receiving a Textctrl event") {
    wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
    old->Destroy();
    wxTheApp->SetTopWindow(new wxTestableFrame());
    wxMilliSleep(250);
    GIVEN ( "A UI Textctrl") {
        auto exec_counter {0};
        auto changefunc {[&exec_counter] (const std::string& opt_id, std::string value) { exec_counter++; }};
        auto test_field {Slic3r::GUI::UI_TextCtrl(wxTheApp->GetTopWindow(), Slic3r::ConfigOptionDef())};

        test_field.on_change = changefunc;

        wxTheApp->GetTopWindow()->Show();
        wxTheApp->GetTopWindow()->Fit();
        WHEN( "A text event occurs") {
            exec_counter = 0;
            auto ev {wxCommandEvent(wxEVT_TEXT_ENTER, test_field.textctrl()->GetId())};
            ev.SetEventObject(test_field.textctrl());
            test_field.textctrl()->ProcessWindowEvent(ev);
            wxYield();
            wxMilliSleep(250);
            THEN( "on_change is executed.") {
                REQUIRE(exec_counter == 1);
            }
        }
        WHEN( "A text event occurs and change event is disabled") {
            exec_counter = 0;
            test_field.disable_change_event = false;
            auto ev {wxCommandEvent(wxEVT_TEXT_ENTER, test_field.textctrl()->GetId())};
            ev.SetEventObject(test_field.textctrl());
            test_field.textctrl()->ProcessWindowEvent(ev);
            wxYield();
            wxMilliSleep(250);
            THEN( "on_change is not executed.") {
                REQUIRE(exec_counter == 1);
            }
        }
    }
}

SCENARIO( "TextCtrl: Changing the text via entry works on pressing enter") {
    wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
    old->Destroy();
    wxTheApp->SetTopWindow(new wxTestableFrame());
    wxUIActionSimulator sim;
    wxMilliSleep(500);
    GIVEN ( "A UI Textctrl") {
        auto exec_counter {0};
        auto changefunc {[&exec_counter] (const std::string& opt_id, std::string value) { exec_counter++; }};
        auto test_field {Slic3r::GUI::UI_TextCtrl(wxTheApp->GetTopWindow(), Slic3r::ConfigOptionDef())};

        test_field.on_change = changefunc;

        wxTheApp->GetTopWindow()->Show();
        wxTheApp->GetTopWindow()->Fit();
        WHEN( "A number is entered followed by enter key") {
            exec_counter = 0;
            test_field.textctrl()->SetFocus();
            wxYield();
            wxMilliSleep(250);
            sim.Char('3');
            wxMilliSleep(250);
            sim.Char(WXK_RETURN);
            wxMilliSleep(250);
            wxYield();
            THEN( "on_change is executed.") {
                REQUIRE(exec_counter == 1);
            }
            THEN( "get_string returns entered value.") {
                REQUIRE(test_field.get_string() == "3"s);
            }
        }
        WHEN( "A number is entered followed by enter key and change event is disabled") {
            exec_counter = 0;
            test_field.disable_change_event = true;
            test_field.textctrl()->SetFocus();
            wxYield();
            wxMilliSleep(250);
            sim.Char('3');
            wxMilliSleep(250);
            sim.Char(WXK_RETURN);
            wxMilliSleep(250);
            wxYield();
            THEN( "on_change is not executed.") {
                REQUIRE(exec_counter == 0);
            }
            THEN( "get_string returns entered value.") {
                REQUIRE(test_field.get_string() == "3"s);
            }
        }
        WHEN( "A number is entered and focus is lost") {
            auto killfunc {[&exec_counter](const std::string& opt_id) { exec_counter += 1; }};
            test_field.on_kill_focus = killfunc;

            auto ev {wxFocusEvent(wxEVT_KILL_FOCUS, test_field.textctrl()->GetId())};
            ev.SetEventObject(test_field.textctrl());

            exec_counter = 0;
            test_field.textctrl()->SetValue("3");
            test_field.textctrl()->SetFocus();
            wxYield();
            wxMilliSleep(250);
            sim.Char('7');
            wxYield();
            wxMilliSleep(250);
            test_field.textctrl()->ProcessWindowEvent(ev);
            wxMilliSleep(250);
            wxYield();
            THEN( "on_kill_focus is executed and on_change are both executed.") {
                REQUIRE(exec_counter == 2);
            }
            THEN( "get_string returns updated value.") {
                REQUIRE(test_field.get_string() == "7"s);
            }
            THEN( "get_bool returns 0.") {
                REQUIRE(test_field.get_bool() == 0);
            }
            THEN( "get_int returns 0.") {
                REQUIRE(test_field.get_int() == 0);
            }
        }

    }
}

SCENARIO( "Multiline doesn't update other than on focus change.") {
    wxTestableFrame* old = dynamic_cast<wxTestableFrame*>(wxTheApp->GetTopWindow());
    old->Destroy();
    wxTheApp->SetTopWindow(new wxTestableFrame());
    wxUIActionSimulator sim;
    wxMilliSleep(500);

    Slic3r::ConfigOptionDef simple_option;
    simple_option.type = coString;
    simple_option.multiline = true;
    auto* stropt { new Slic3r::ConfigOptionString("7") };
    GIVEN ( "A multiline UI Textctrl") {
        auto exec_counter {0};
        auto changefunc {[&exec_counter] (const std::string& opt_id, std::string value) { exec_counter++; }};
        auto test_field {Slic3r::GUI::UI_TextCtrl(wxTheApp->GetTopWindow(), Slic3r::ConfigOptionDef())};

        test_field.on_change = changefunc;

        wxTheApp->GetTopWindow()->Show();
        wxTheApp->GetTopWindow()->Fit();
        WHEN( "text is entered and focus is lost") {
            auto killfunc {[&exec_counter](const std::string& opt_id) { exec_counter += 1; }};
            test_field.on_kill_focus = killfunc;

            auto ev {wxFocusEvent(wxEVT_KILL_FOCUS, test_field.textctrl()->GetId())};
            ev.SetEventObject(test_field.textctrl());

            exec_counter = 0;
            test_field.textctrl()->SetFocus();
            wxYield();
            wxMilliSleep(250);
            sim.Char(WXK_LEFT);
            sim.Char('7');
            wxYield();
            sim.Char('7');
            wxYield();
            wxMilliSleep(250);
            test_field.textctrl()->ProcessWindowEvent(ev);
            wxYield();
            wxMilliSleep(250);
            wxYield();
            THEN( "on_kill_focus is executed and on_change are both executed.") {
                REQUIRE(exec_counter == 2);
            }
            THEN( "get_string returns updated value.") {
                REQUIRE(test_field.get_string() == "77"s);
            }
            THEN( "get_bool returns 0.") {
                REQUIRE(test_field.get_bool() == 0);
            }
            THEN( "get_int returns 0.") {
                REQUIRE(test_field.get_int() == 0);
            }
        }
    }
}
<|endoftext|>


<commit_before>#include <cassert>
#include "SDShared.hpp"
#include "exception/exception.hpp"

SDShared::SDShared(const std::vector< std::pair<int, int> >& coords,
        const CoordConverter& coordConverter,
        unsigned int index):
    std::vector< std::pair<int ,int> >(coords),
    _coordConverter(coordConverter),
    _id(index) {
}

void SDShared::execEquation(eqType& eqFunc,
        const std::map< std::string, Quantity<real>* >& quantityMap) {

    eqFunc(*this, quantityMap);
}

void SDShared::addDirichletCell(std::pair < std::pair<int, int>, std::map<std::string, real> > d) {
    for (auto p : d.second)
        _dirichletCellMap[p.first][convert(d.first.first, d.first.second)] = p.second;
}

void SDShared::addNeumannCell(std::pair< std::pair<int, int>, std::pair< std::pair<int, int>, std::map<std::string, real> > > n) {
    for (auto p : n.second.second)
        _neumannCellMap[p.first][convert(n.first.first, n.first.second)] = std::make_pair(convert(n.second.first.first, n.second.first.second), p.second);
}

size_t SDShared::getOverlapCellNumber(unsigned int sddId) const {
    if (_sendIndexMap.find(sddId) == _sendIndexMap.end())
        return 0;

    return _sendIndexMap.at(sddId).size();
}

void SDShared::addOverlapCell(unsigned int sddId, size_t sendIndex, size_t recvIndex) {
    _sendIndexMap[sddId].push_back(sendIndex);
    _recvIndexMap[sddId].push_back(recvIndex);
}

void SDShared::updateBoundaryCells(Quantity<real>* quantity) const {
    updateDirichletCells(quantity);
    updateNeumannCells(quantity);
}

void SDShared::updateDirichletCells(Quantity<real>* quantity) const {
    auto& qty(*quantity);

    // No dirichlet values stored for this quantity.
    std::map<std::string, std::unordered_map< size_t, real >>::const_iterator it = _dirichletCellMap.find(qty.getName());
    if (it == _dirichletCellMap.end())
        return;

    const std::unordered_map< size_t, real>& dirichletValue = it->second;

    // This cannot be.
    assert(!dirichletValue.size());

    for (auto it = dirichletValue.begin(); it != dirichletValue.end(); ++it)
        qty.set0(it->second, it->first);
}

void SDShared::updateNeumannCells(Quantity<real>* quantity) const {

    auto& qty(*quantity);

    // No dirichlet values stored for this quantity.
    std::map<std::string, std::unordered_map< size_t, std::pair<size_t, real>>>::const_iterator cit = _neumannCellMap.find(qty.getName());
    if (cit == _neumannCellMap.end())
        return;

    const std::unordered_map< size_t, std::pair<size_t, real>>& neumannCoeff = cit->second;

    // This cannot be.
    assert(neumannCoeff.size() != 0);

    for (auto it = neumannCoeff.begin(); it != neumannCoeff.end(); ++it) {
        qty.set0(it->second.second * qty.get0(it->second.first), it->first);
    }
}

void SDShared::copyOverlapCellIn(const std::map< std::string, Quantity<real>* >& quantityMap, const std::unordered_map<unsigned int, real* >& buffer) const {

    const size_t plus(quantityMap.size());
    for (auto const& it: _sendIndexMap) {
        size_t startPos(_bufferStartPos.at(it.first) * quantityMap.size());
        real* sddBuffer(buffer.at(it.first));
        for (const auto p: quantityMap) {
            auto& qty(*p.second);
            size_t index(startPos++);
            for (const unsigned int i : it.second) {
                sddBuffer[index] = qty.get0(i);
                index += plus;
            }
        }
    }
}

void SDShared::copyOverlapCellFrom(const std::map< std::string, Quantity<real>* >& quantityMap, const std::unordered_map<unsigned int, real* >& buffer) const {
    const size_t plus(quantityMap.size());
    for (auto const& it: _recvIndexMap) {
        real* sddBuffer(buffer.at(it.first));
        size_t startPos(_bufferStartPos.at(it.first) * plus);
        for (const auto p: quantityMap) {
            auto& qty(*p.second);
            size_t index(startPos++);
            for (const unsigned int i : it.second) {
                qty.set0(sddBuffer[index], i);
                index += plus;
            }
        }
    }
}

<commit_msg>Wrong assertion negation ... who knows since when ...<commit_after>#include <cassert>
#include "SDShared.hpp"
#include "exception/exception.hpp"

SDShared::SDShared(const std::vector< std::pair<int, int> >& coords,
        const CoordConverter& coordConverter,
        unsigned int index):
    std::vector< std::pair<int ,int> >(coords),
    _coordConverter(coordConverter),
    _id(index) {
}

void SDShared::execEquation(eqType& eqFunc,
        const std::map< std::string, Quantity<real>* >& quantityMap) {

    eqFunc(*this, quantityMap);
}

void SDShared::addDirichletCell(std::pair < std::pair<int, int>, std::map<std::string, real> > d) {
    for (auto p : d.second)
        _dirichletCellMap[p.first][convert(d.first.first, d.first.second)] = p.second;
}

void SDShared::addNeumannCell(std::pair< std::pair<int, int>, std::pair< std::pair<int, int>, std::map<std::string, real> > > n) {
    for (auto p : n.second.second)
        _neumannCellMap[p.first][convert(n.first.first, n.first.second)] = std::make_pair(convert(n.second.first.first, n.second.first.second), p.second);
}

size_t SDShared::getOverlapCellNumber(unsigned int sddId) const {
    if (_sendIndexMap.find(sddId) == _sendIndexMap.end())
        return 0;

    return _sendIndexMap.at(sddId).size();
}

void SDShared::addOverlapCell(unsigned int sddId, size_t sendIndex, size_t recvIndex) {
    _sendIndexMap[sddId].push_back(sendIndex);
    _recvIndexMap[sddId].push_back(recvIndex);
}

void SDShared::updateBoundaryCells(Quantity<real>* quantity) const {
    updateDirichletCells(quantity);
    updateNeumannCells(quantity);
}

void SDShared::updateDirichletCells(Quantity<real>* quantity) const {
    auto& qty(*quantity);

    // No dirichlet values stored for this quantity.
    std::map<std::string, std::unordered_map< size_t, real >>::const_iterator it = _dirichletCellMap.find(qty.getName());
    if (it == _dirichletCellMap.end())
        return;

    const std::unordered_map< size_t, real>& dirichletValue = it->second;

    // This cannot be.
    assert(dirichletValue.size() != 0);

    for (auto it = dirichletValue.begin(); it != dirichletValue.end(); ++it)
        qty.set0(it->second, it->first);
}

void SDShared::updateNeumannCells(Quantity<real>* quantity) const {

    auto& qty(*quantity);

    // No dirichlet values stored for this quantity.
    std::map<std::string, std::unordered_map< size_t, std::pair<size_t, real>>>::const_iterator cit = _neumannCellMap.find(qty.getName());
    if (cit == _neumannCellMap.end())
        return;

    const std::unordered_map< size_t, std::pair<size_t, real>>& neumannCoeff = cit->second;

    // This cannot be.
    assert(neumannCoeff.size() != 0);

    for (auto it = neumannCoeff.begin(); it != neumannCoeff.end(); ++it) {
        qty.set0(it->second.second * qty.get0(it->second.first), it->first);
    }
}

void SDShared::copyOverlapCellIn(const std::map< std::string, Quantity<real>* >& quantityMap, const std::unordered_map<unsigned int, real* >& buffer) const {

    const size_t plus(quantityMap.size());
    for (auto const& it: _sendIndexMap) {
        size_t startPos(_bufferStartPos.at(it.first) * quantityMap.size());
        real* sddBuffer(buffer.at(it.first));
        for (const auto p: quantityMap) {
            auto& qty(*p.second);
            size_t index(startPos++);
            for (const unsigned int i : it.second) {
                sddBuffer[index] = qty.get0(i);
                index += plus;
            }
        }
    }
}

void SDShared::copyOverlapCellFrom(const std::map< std::string, Quantity<real>* >& quantityMap, const std::unordered_map<unsigned int, real* >& buffer) const {
    const size_t plus(quantityMap.size());
    for (auto const& it: _recvIndexMap) {
        real* sddBuffer(buffer.at(it.first));
        size_t startPos(_bufferStartPos.at(it.first) * plus);
        for (const auto p: quantityMap) {
            auto& qty(*p.second);
            size_t index(startPos++);
            for (const unsigned int i : it.second) {
                qty.set0(sddBuffer[index], i);
                index += plus;
            }
        }
    }
}

<|endoftext|>


<commit_before>#include "testing/testing.hpp"

#include "routing/routing_quality/waypoints.hpp"

using namespace routing_quality;

// In most cases a passby road should be preferred in case of going pass a city.
// Test on such cases should be grouped in this file.
namespace
{
UNIT_TEST(RoutingQuality_RussiaZelegonrad2Domodedovo)
{
  // From Zelenograd to Domodedovo. MKAD should be preferred.
  TEST(CheckCarRoute({55.98301, 37.21141} /* start */, {55.42081, 37.89361} /* finish */,
                     {{{55.99751, 37.23804}, // Through M-11 and MKAD.
                       {56.00719, 37.28533},
                       {55.88759, 37.48068},
                       {55.83513, 37.39569},
                       {55.57103, 37.69203}},
                      {{55.99775, 37.24941}, // Through M-10 and MKAD.
                       {55.88627, 37.43915},
                       {55.86882, 37.40784},
                       {55.58645, 37.71672},
                       {55.57855, 37.75468}}} /* reference tracks */),
       ());
}

UNIT_TEST(RoutingQuality_BelarusKobrin)
{
  // Test on using a passby road around Kobirn.
  TEST(CheckCarRoute({52.18429, 24.20225} /* start */, {52.24404, 24.45842} /* finish */,
                     {{{52.18694, 24.39903}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_BelarusBobruisk)
{
  TEST(CheckCarRoute({53.24596, 28.93816} /* start */, {53.04386, 29.58098} /* finish */,
                     {{{53.24592, 29.29409}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_RussiaStPetersburg)
{
  TEST(CheckCarRoute({60.08634, 30.10277} /* start */, {59.94584, 30.57703} /* finish */,
                     {{{60.03478, 30.44084}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_BelarusMinsk)
{
  TEST(CheckCarRoute({53.75958, 28.005} /* start */, {54.03957, 26.83097} /* finish */,
                     {{{53.70668, 27.4487}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_BelarusMinskMKAD)
{
  TEST(CheckCarRoute({53.81784, 27.76789} /* start */, {53.94655, 27.36398} /* finish */,
                     {{{53.95037, 27.65361}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_EnglandLondon)
{
  TEST(CheckCarRoute({51.90356, -0.20133} /* start */, {51.23253, -0.33076} /* finish */,
                     {{{51.57098, -0.53503}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_UkraineChernigov)
{
  TEST(CheckCarRoute({51.29419, 31.25718} /* start */, {51.62678, 31.21787} /* finish */,
                     {{{51.48362, 31.18757}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_PolandSiedlce)
{
  TEST(CheckCarRoute({52.17525, 22.19702} /* start */, {52.119802, 22.35855} /* finish */,
                     {{{52.14355, 22.231}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_HungarySzolnok)
{
  TEST(CheckCarRoute({47.18462, 20.04432} /* start */, {47.17919, 20.33486} /* finish */,
                     {{{47.14467, 20.17032}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_USATexasAbilene)
{
  TEST(CheckCarRoute({32.46041, -99.93058} /* start */, {32.43085, -99.59475} /* finish */,
                     {{{32.49038, -99.7269}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_ItalyParma)
{
  TEST(CheckCarRoute({44.81937, 10.2403} /* start */, {44.78228, 10.38824} /* finish */,
                     {{{44.81625, 10.34545}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_SlovenijaLjubljana)
{
  TEST(CheckCarRoute({45.99272, 14.59186} /* start */, {46.10318, 14.46829} /* finish */,
                     {{{46.04449, 14.44669}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_FrancePoitiers)
{
  TEST(CheckCarRoute({46.63612, 0.35762} /* start */, {46.49, 0.36787} /* finish */,
                     {{{46.58706, 0.39232}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_FranceLoudun)
{
  TEST(CheckCarRoute({47.03437, 0.04437} /* start */, {46.97887, 0.09692} /* finish */,
                     {{{47.00307, 0.06713}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_FranceDoueIaFontaine)
{
  TEST(CheckCarRoute({47.22972, -0.30962} /* start */, {47.17023, -0.2185} /* finish */,
                     {{{47.19117, -0.31334}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_BelgiumBrussel)
{
  TEST(CheckCarRoute({50.88374, 4.2195} /* start */, {50.91494, 4.38122} /* finish */,
                     {{{50.91727, 4.36858}}} /* reference point */),
       ());
}
}  // namespace
<commit_msg>[routing] Comment test and add another.<commit_after>#include "testing/testing.hpp"

#include "routing/routing_quality/waypoints.hpp"

using namespace routing_quality;

// In most cases a passby road should be preferred in case of going pass a city.
// Test on such cases should be grouped in this file.
namespace
{
UNIT_TEST(RoutingQuality_RussiaZelegonrad2Domodedovo)
{
  // From Zelenograd to Domodedovo. MKAD should be preferred.
  TEST(CheckCarRoute({55.98301, 37.21141} /* start */, {55.42081, 37.89361} /* finish */,
                     {{{55.99751, 37.23804}, // Through M-11 and MKAD.
                       {56.00719, 37.28533},
                       {55.88759, 37.48068},
                       {55.83513, 37.39569},
                       {55.57103, 37.69203}},
                      {{55.99775, 37.24941}, // Through M-10 and MKAD.
                       {55.88627, 37.43915},
                       {55.86882, 37.40784},
                       {55.58645, 37.71672},
                       {55.57855, 37.75468}}} /* reference tracks */),
       ());
}

UNIT_TEST(RoutingQuality_BelarusKobrin)
{
  // Test on using a passby road around Kobirn.
  TEST(CheckCarRoute({52.18429, 24.20225} /* start */, {52.24404, 24.45842} /* finish */,
                     {{{52.18694, 24.39903}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_BelarusBobruisk)
{
  TEST(CheckCarRoute({53.24596, 28.93816} /* start */, {53.04386, 29.58098} /* finish */,
                     {{{53.24592, 29.29409}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_RussiaStPetersburg)
{
  TEST(CheckCarRoute({60.08634, 30.10277} /* start */, {59.94584, 30.57703} /* finish */,
                     {{{60.03478, 30.44084}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_BelarusMinsk)
{
  TEST(CheckCarRoute({53.75958, 28.005} /* start */, {54.03957, 26.83097} /* finish */,
                     {{{53.70668, 27.4487}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_BelarusMinskMKAD)
{
  TEST(CheckCarRoute({53.81784, 27.76789} /* start */, {53.94655, 27.36398} /* finish */,
                     {{{53.95037, 27.65361}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_EnglandLondon)
{
  TEST(CheckCarRoute({51.90356, -0.20133} /* start */, {51.23253, -0.33076} /* finish */,
                     {{{51.57098, -0.53503}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_UkraineChernigov)
{
  TEST(CheckCarRoute({51.29419, 31.25718} /* start */, {51.62678, 31.21787} /* finish */,
                     {{{51.48362, 31.18757}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_PolandSiedlce)
{
  TEST(CheckCarRoute({52.17525, 22.19702} /* start */, {52.119802, 22.35855} /* finish */,
                     {{{52.14355, 22.231}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_HungarySzolnok)
{
  TEST(CheckCarRoute({47.18462, 20.04432} /* start */, {47.17919, 20.33486} /* finish */,
                     {{{47.14467, 20.17032}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_USATexasAbilene)
{
  TEST(CheckCarRoute({32.46041, -99.93058} /* start */, {32.43085, -99.59475} /* finish */,
                     {{{32.49038, -99.7269}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_ItalyParma)
{
  TEST(CheckCarRoute({44.81937, 10.2403} /* start */, {44.78228, 10.38824} /* finish */,
                     {{{44.81625, 10.34545}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_SlovenijaLjubljana)
{
  TEST(CheckCarRoute({45.99272, 14.59186} /* start */, {46.10318, 14.46829} /* finish */,
                     {{{46.04449, 14.44669}}} /* reference point */),
       ());
}

// TODO: Uncomment this test when correct city boundaries or crossroads will be ready.
//UNIT_TEST(RoutingQuality_FrancePoitiers)
//{
//  TEST(CheckCarRoute({46.63612, 0.35762} /* start */, {46.49, 0.36787} /* finish */,
//                     {{{46.58706, 0.39232}}} /* reference point */),
//       ());
//}

UNIT_TEST(RoutingQuality_FranceLoudun)
{
  TEST(CheckCarRoute({47.03437, 0.04437} /* start */, {46.97887, 0.09692} /* finish */,
                     {{{47.00307, 0.06713}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_FranceDoueIaFontaine)
{
  TEST(CheckCarRoute({47.22972, -0.30962} /* start */, {47.17023, -0.2185} /* finish */,
                     {{{47.19117, -0.31334}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_BelgiumBrussel)
{
  TEST(CheckCarRoute({50.88374, 4.2195} /* start */, {50.91494, 4.38122} /* finish */,
                     {{{50.91727, 4.36858}}} /* reference point */),
       ());
}

UNIT_TEST(RoutingQuality_SouthernDenmarkPastUnclassified)
{
  TEST(CheckCarRoute({55.44681, 10.29} /* start */, {55.45877, 10.26456} /* finish */,
                     {{{55.45505, 10.26972}}} /* reference point */),
       ());

}
}  // namespace
<|endoftext|>


<commit_before>#include <caffe/caffe.hpp>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

using namespace caffe;
using namespace cv;

void WrapInputLayer(std::vector<Mat>* input_channels, const Net<float>& net) {
  Blob<float>* input_layer = net.input_blobs()[0];

  int width = input_layer->width();
  int height = input_layer->height();
  float* input_data = input_layer->mutable_cpu_data();
  std::cout << input_layer->channels() << std::endl;
  for (int i = 0; i < input_layer->channels(); ++i) {
    Mat channel(height, width, CV_32FC1, input_data);
    input_channels->push_back(channel);
    input_data += width * height;
  }
}

void Preprocess(const Mat& img, std::vector<Mat>* input_channels,
                int num_channels, const Size& input_geometry) {

  Mat sample;
  cvtColor(img, sample, COLOR_BGR2BGRA);
<<<<<<< HEAD

  std::cout << "Num channels: " << num_channels << std::endl;
  std::cout << "Num channelsimg: " << img.channels() << std::endl;
=======
>>>>>>> 3e39e24667d133f9bf6ae333d53f97010eac185a

  Mat sample_resized;
  if (sample.size() != input_geometry)
    resize(sample, sample_resized, input_geometry);
  else
    sample_resized = sample;

  for (int i = 0; i < sample_resized.size().width; ++i) {
    for (int j = 0; j < sample_resized.size().height; ++j) {
      sample_resized.at<Vec4f>(i, j)[0] = sample_resized.at<Vec4f>(i, j)[0] / 255;
      sample_resized.at<Vec4f>(i, j)[1] = sample_resized.at<Vec4f>(i, j)[1] / 255;
      sample_resized.at<Vec4f>(i, j)[2] = sample_resized.at<Vec4f>(i, j)[2] / 255;
      sample_resized.at<Vec4f>(i, j)[3] = 1;
    }
  }

  for (int i = 0; i < sample_resized.size().width; ++i) {
    for (int j = 0; j < sample_resized.size().height; ++j) {
      sample_resized.at<float>(i, j) = sample_resized.at<float>(i, j) * 255;
    }
  }

  split(sample_resized, *input_channels);
}

int main(int argc, char** argv) {
  if (argc != 4) {
    printf("Usage %s <model_file> <trained_file> <test_image>", argv[0]);
    return -1;
  }

  std::string model_file = argv[1];
  std::string trained_file = argv[2];
  std::string test_image_file = argv[3];
  Mat test_image = imread(test_image_file, IMREAD_UNCHANGED);

  // Initialize Caffe.
  Caffe::set_mode(Caffe::CPU);
  Net<float> net(model_file, TEST);
  net.CopyTrainedLayersFrom(trained_file);
  Blob<float>* input_layer = net.input_blobs()[0];
  int num_channels = input_layer->channels();
  Size input_geometry = Size(input_layer->width(), input_layer->height());
  input_layer->Reshape(1, num_channels, input_geometry.height,
                       input_geometry.width);
  net.Reshape();

  std::vector<cv::Mat> input_channels;
  WrapInputLayer(&input_channels, net);

  Preprocess(test_image, &input_channels, num_channels, input_geometry);

  net.Forward();

  Blob<float>* output_layer = net.output_blobs()[0];
  std::cout << output_layer->shape_string() << std::endl;

  float* channel = output_layer->mutable_cpu_data();
  for (int i = 0; i < output_layer->channels(); ++i) {
    Mat class_heatmap(output_layer->height(), output_layer->width(), CV_32FC1,
                      channel);
    channel += output_layer->width() * output_layer->height();

    for (int i = 0; i < class_heatmap.size().width; ++i) {
      for (int j = 0; j < class_heatmap.size().height; ++j) {
        class_heatmap.at<float>(i, j) = class_heatmap.at<float>(i, j) * 255;
      }
    }

    // double min, max;
    // cv::Point min_loc, max_loc;
    // cv::minMaxLoc(class_heatmap, &min, &max, &min_loc, &max_loc);
    // std::cout << class_heatmap << std::endl;

    // circle(class_heatmap, max_loc, 1, Scalar(255, 255, 255), 3);
    // circle(class_heatmap, min_loc, 1, Scalar(255, 255, 255), 3);

    namedWindow("Display View", CV_WINDOW_AUTOSIZE);
    imshow("Display View", class_heatmap);

    waitKey(0);
  }

  // for (int i = 0; i < output_layer->width(); ++i) {
  //   for (int j = 0; j < output_layer->height(); ++j) {
  //     class_heatmap.at<float>(i, j) = 0;
  //   }
  // }

}
<commit_msg>Fix merge artifacts<commit_after>#include <caffe/caffe.hpp>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

using namespace caffe;
using namespace cv;

void WrapInputLayer(std::vector<Mat>* input_channels, const Net<float>& net) {
  Blob<float>* input_layer = net.input_blobs()[0];

  int width = input_layer->width();
  int height = input_layer->height();
  float* input_data = input_layer->mutable_cpu_data();
  std::cout << input_layer->channels() << std::endl;
  for (int i = 0; i < input_layer->channels(); ++i) {
    Mat channel(height, width, CV_32FC1, input_data);
    input_channels->push_back(channel);
    input_data += width * height;
  }
}

void Preprocess(const Mat& img, std::vector<Mat>* input_channels,
                int num_channels, const Size& input_geometry) {

  Mat sample;
  cvtColor(img, sample, COLOR_BGR2BGRA);

  std::cout << "Num channels: " << num_channels << std::endl;
  std::cout << "Num channelsimg: " << img.channels() << std::endl;

  Mat sample_resized;
  if (sample.size() != input_geometry)
    resize(sample, sample_resized, input_geometry);
  else
    sample_resized = sample;

  for (int i = 0; i < sample_resized.size().width; ++i) {
    for (int j = 0; j < sample_resized.size().height; ++j) {
      sample_resized.at<Vec4f>(i, j)[0] = sample_resized.at<Vec4f>(i, j)[0] / 255;
      sample_resized.at<Vec4f>(i, j)[1] = sample_resized.at<Vec4f>(i, j)[1] / 255;
      sample_resized.at<Vec4f>(i, j)[2] = sample_resized.at<Vec4f>(i, j)[2] / 255;
      sample_resized.at<Vec4f>(i, j)[3] = 1;
    }
  }

  for (int i = 0; i < sample_resized.size().width; ++i) {
    for (int j = 0; j < sample_resized.size().height; ++j) {
      sample_resized.at<float>(i, j) = sample_resized.at<float>(i, j) * 255;
    }
  }

  split(sample_resized, *input_channels);
}

int main(int argc, char** argv) {
  if (argc != 4) {
    printf("Usage %s <model_file> <trained_file> <test_image>", argv[0]);
    return -1;
  }

  std::string model_file = argv[1];
  std::string trained_file = argv[2];
  std::string test_image_file = argv[3];
  Mat test_image = imread(test_image_file, IMREAD_UNCHANGED);

  // Initialize Caffe.
  Caffe::set_mode(Caffe::CPU);
  Net<float> net(model_file, TEST);
  net.CopyTrainedLayersFrom(trained_file);
  Blob<float>* input_layer = net.input_blobs()[0];
  int num_channels = input_layer->channels();
  Size input_geometry = Size(input_layer->width(), input_layer->height());
  input_layer->Reshape(1, num_channels, input_geometry.height,
                       input_geometry.width);
  net.Reshape();

  std::vector<cv::Mat> input_channels;
  WrapInputLayer(&input_channels, net);

  Preprocess(test_image, &input_channels, num_channels, input_geometry);

  net.Forward();

  Blob<float>* output_layer = net.output_blobs()[0];
  std::cout << output_layer->shape_string() << std::endl;

  float* channel = output_layer->mutable_cpu_data();
  for (int i = 0; i < output_layer->channels(); ++i) {
    Mat class_heatmap(output_layer->height(), output_layer->width(), CV_32FC1,
                      channel);
    channel += output_layer->width() * output_layer->height();

    for (int i = 0; i < class_heatmap.size().width; ++i) {
      for (int j = 0; j < class_heatmap.size().height; ++j) {
        class_heatmap.at<float>(i, j) = class_heatmap.at<float>(i, j) * 255;
      }
    }

    // double min, max;
    // cv::Point min_loc, max_loc;
    // cv::minMaxLoc(class_heatmap, &min, &max, &min_loc, &max_loc);
    // std::cout << class_heatmap << std::endl;

    // circle(class_heatmap, max_loc, 1, Scalar(255, 255, 255), 3);
    // circle(class_heatmap, min_loc, 1, Scalar(255, 255, 255), 3);

    namedWindow("Display View", CV_WINDOW_AUTOSIZE);
    imshow("Display View", class_heatmap);

    waitKey(0);
  }

  // for (int i = 0; i < output_layer->width(); ++i) {
  //   for (int j = 0; j < output_layer->height(); ++j) {
  //     class_heatmap.at<float>(i, j) = 0;
  //   }
  // }

}
<|endoftext|>


<commit_before>#include <QVariant>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include "oildatabase.h"

OilDatabase::OilDatabase(const QString &file)
 : db(QSqlDatabase::addDatabase("QSQLITE"))
{
    db.setDatabaseName(file);
    db.open();

    QSqlQuery query(db);
    if(!query.exec("SELECT name, hardness, cleansing, condition, bubbly, creamy, iodine, ins, lauric, myristic, palmitic, stearic, ricinoleic, oleic, linoleic, linolenic FROM \"oils\" ORDER BY name;")) {
        qDebug() << query.lastError().text();
    }

    while(query.next()) {
        qDebug() << query.value(0).toString();
        oils.insert(query.value(0).toString(),
                    Oil(query.value(0).toString(),
                        query.value(1).toDouble(),
                        query.value(2).toDouble(),
                        query.value(3).toDouble(),
                        query.value(4).toDouble(),
                        query.value(5).toDouble(),
                        query.value(6).toDouble(),
                        query.value(7).toDouble(),
                        query.value(8).toDouble(),
                        query.value(9).toDouble(),
                        query.value(10).toDouble(),
                        query.value(11).toDouble(),
                        query.value(12).toDouble(),
                        query.value(13).toDouble(),
                        query.value(14).toDouble(),
                        query.value(15).toDouble()
                        ));
    }

}

Oil OilDatabase::get_oil(const QString &name) {
    return oils[name];
}

QList<Oil> OilDatabase::get_oils() {
    return oils.values();
}
<commit_msg>Remove debugging prints<commit_after>#include <QVariant>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include "oildatabase.h"

OilDatabase::OilDatabase(const QString &file)
 : db(QSqlDatabase::addDatabase("QSQLITE"))
{
    db.setDatabaseName(file);
    db.open();

    QSqlQuery query(db);
    if(!query.exec("SELECT name, hardness, cleansing, condition, bubbly, creamy, iodine, ins, lauric, myristic, palmitic, stearic, ricinoleic, oleic, linoleic, linolenic FROM \"oils\" ORDER BY name;")) {
        qDebug() << query.lastError().text();
    }

    while(query.next()) {
        oils.insert(query.value(0).toString(),
                    Oil(query.value(0).toString(),
                        query.value(1).toDouble(),
                        query.value(2).toDouble(),
                        query.value(3).toDouble(),
                        query.value(4).toDouble(),
                        query.value(5).toDouble(),
                        query.value(6).toDouble(),
                        query.value(7).toDouble(),
                        query.value(8).toDouble(),
                        query.value(9).toDouble(),
                        query.value(10).toDouble(),
                        query.value(11).toDouble(),
                        query.value(12).toDouble(),
                        query.value(13).toDouble(),
                        query.value(14).toDouble(),
                        query.value(15).toDouble()
                        ));
    }

}

Oil OilDatabase::get_oil(const QString &name) {
    return oils[name];
}

QList<Oil> OilDatabase::get_oils() {
    return oils.values();
}
<|endoftext|>