<commit_before>// "Walk Of Life" Data Structure Test
//Only ever include the data structure - insures only registered plugins work
#include "dataStructure.h"
#include "ThreadManager.h"
#include "Graphics.h"
#include <random>
#include <iostream>
using namespace std;

void init(Bin& bin, ostream& os = cout);
void graphics(const Bin* const bin, const ThreadManager* const manager);

int main()
{
    //Create Bin
    Bin bin(500, 500, 5);

    init(bin); //Initialize the content of the bin

    //This is the multithreading a thread for each for
     //updating the hexes
     //updating the entities
     //Timing the update cycle and adjusting resolution
    ThreadManager manager(bin);

    //Start drawing the screen, in a seperate thread
    manager.startGraphics(&graphics);

    //Will "endlessly" update the map (spawns and updates the described threads)
    manager.startUpdatingMap();

    manager.waitForThreadsEnd();
}

void init(Bin& bin, ostream& os)
{
    os << "INIT: Initializing Map...\n";

    //Random number stuff
    random_device seed;
    mt19937 gen(seed());

    //Make two generators for generating entities in random locations
    uniform_real_distribution<double> randRangeWidth (0.0, bin.getWidth() );
    uniform_real_distribution<double> randRangeHeight(0.0, bin.getHeight());

    const unsigned int numFlowers = 500;
    os << "INIT: Generating " << numFlowers << " flowers\n";
    vector<Flower>* flowerBucket = new vector<Flower>(numFlowers, Flower(randRangeWidth(gen), randRangeHeight(gen))); //Make space
    for(unsigned int numOfNodes = 0; numOfNodes < numFlowers; ++numOfNodes)
    {
        bin.insert(&(*flowerBucket)[numOfNodes]);
    }
    const unsigned int numDoggies = 500;
    os << "INIT: Generating " << numDoggies << " dogs\n";
    vector<Dog>* dogBucket = new vector<Dog>(numDoggies, Dog(randRangeWidth(gen), randRangeHeight(gen)));  //Make space
    for(unsigned int numOfNodes = 0; numOfNodes < numDoggies; ++numOfNodes)
    {
        bin.insert(&(*dogBucket)[numOfNodes]);
    }

    os << "INIT: Done!\n\n";
}

void graphics(const Bin* const bin, const ThreadManager* const manager)
{
    Graphics graphic(bin, manager);
    graphic.spin();
}
<commit_msg>Changed Entity Creation<commit_after>// "Walk Of Life" Data Structure Test
//Only ever include the data structure - insures only registered plugins work
#include "dataStructure.h"
#include "ThreadManager.h"
#include "Graphics.h"
#include <random>
#include <iostream>
using namespace std;

void init(Bin& bin, ostream& os = cout);
void graphics(const Bin* const bin, const ThreadManager* const manager);

int main()
{
    //Create Bin
    Bin bin(500, 500, 5);

    init(bin); //Initialize the content of the bin

    //This is the multithreading a thread for each for
     //updating the hexes
     //updating the entities
     //Timing the update cycle and adjusting resolution
    ThreadManager manager(bin);

    //Start drawing the screen, in a seperate thread
    manager.startGraphics(&graphics);

    //Will "endlessly" update the map (spawns and updates the described threads)
    manager.startUpdatingMap();

    manager.waitForThreadsEnd();
}

void init(Bin& bin, ostream& os)
{
    os << "INIT: Initializing Map...\n";

    //Random number stuff
    random_device seed;
    mt19937 gen(seed());

    //Make two generators for generating entities in random locations
    uniform_real_distribution<double> randRangeWidth (0.0, bin.getWidth() );
    uniform_real_distribution<double> randRangeHeight(0.0, bin.getHeight());

    const unsigned int numFlowers = 500;
    os << "INIT: Generating " << numFlowers << " flowers\n";
    for(unsigned int numOfNodes = 0; numOfNodes < numFlowers; ++numOfNodes)
    {
        bin.insert(new Flower(randRangeWidth(gen), randRangeHeight(gen)));
    }
    const unsigned int numDoggies = 500;
    os << "INIT: Generating " << numDoggies << " dogs\n";
    for(unsigned int numOfNodes = 0; numOfNodes < numDoggies; ++numOfNodes)
    {
        bin.insert(new Dog(randRangeWidth(gen), randRangeHeight(gen)));
    }

    os << "INIT: Done!\n\n";
}

void graphics(const Bin* const bin, const ThreadManager* const manager)
{
    Graphics graphic(bin, manager);
    graphic.spin();
}
<|endoftext|>


<commit_before>// @(#)root/gl:$Name:  $:$Id: TGLManip.cxx
// Author:  Richard Maunder  16/09/2005

/*************************************************************************
 * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TGLManip.h"
#include "TGLUtil.h"
#include "TGLCamera.h"
#include "TGLViewer.h"
#include "TGLPhysicalShape.h"
#include "TGLIncludes.h"

TGLQuadric TGLManip::fgQuad;

//TODO: Should really use LOD adjustment on top?
UInt_t TGLManip::fgQuality = 60;

Float_t TGLManip::fgRed[4]    = {1.0, 0.0, 0.0, 1.0 };
Float_t TGLManip::fgGreen[4]  = {0.0, 1.0, 0.0, 1.0 };
Float_t TGLManip::fgBlue[4]   = {0.0, 0.0, 1.0, 1.0 };
Float_t TGLManip::fgYellow[4] = {1.0, 1.0, 0.0, 1.0 };
Float_t TGLManip::fgWhite[4]  = {1.0, 1.0, 1.0, 1.0 };
Float_t TGLManip::fgGrey[4]   = {0.5, 0.5, 0.5, 0.4 };

ClassImp(TGLManip)

//______________________________________________________________________________
TGLManip::TGLManip(TGLViewer & viewer) :
   fViewer(viewer), fShape(0),
   fSelectedWidget(0), fActive(kFALSE),
   fFirstMouse(0, 0),
   fLastMouse(0, 0)
{
}

//______________________________________________________________________________
TGLManip::TGLManip(TGLViewer & viewer, TGLPhysicalShape * shape) :
   fViewer(viewer), fShape(shape),
   fSelectedWidget(0), fActive(kFALSE),
   fFirstMouse(0, 0),
   fLastMouse(0, 0)
{
}

//______________________________________________________________________________
TGLManip::~TGLManip()
{
}

//______________________________________________________________________________
void TGLManip::Select(const TGLCamera & camera)
{
   static UInt_t selectBuffer[4*4];
   glSelectBuffer(4*4, &selectBuffer[0]);
   glRenderMode(GL_SELECT);
   glInitNames();
   Draw(camera);
   Int_t hits = glRenderMode(GL_RENDER);
   TGLUtil::CheckError();
   if (hits < 0) {
      Error("TGLManip::Select", "selection buffer overflow");
      return;
   }

   if (hits > 0) {
      fSelectedWidget = 0;
      UInt_t minDepth = kMaxUInt;
      for (Int_t i = 0; i < hits; i++) {
         // Skip selection on unnamed hits
         if (selectBuffer[i * 4] == 0) {
            continue;
         }
         if (selectBuffer[i * 4 + 1] < minDepth) {
            fSelectedWidget = selectBuffer[i * 4 + 3];
         }
      }
   } else {
      fSelectedWidget = 0;
   }
}

//______________________________________________________________________________
Bool_t TGLManip::HandleButton(const Event_t * event, const TGLCamera & /*camera*/)
{
   // Only interested in Left mouse button actions
   if (event->fCode != kButton1) {
      return kFALSE;
   }

   // Mouse down on selected widget?
   if (event->fType == kButtonPress && fSelectedWidget != 0) {
      fFirstMouse.SetX(event->fX);
      fFirstMouse.SetY(event->fY);
      fLastMouse.SetX(event->fX);
      fLastMouse.SetY(event->fY);
      fActive = kTRUE;
      return kTRUE;
   } else if (event->fType == kButtonRelease && fActive) {
      fActive = kFALSE;
      return kTRUE;
   } else {
      return kFALSE;
   }
}

//______________________________________________________________________________
Bool_t TGLManip::HandleMotion(const Event_t * event, const TGLCamera & /*camera*/)
{
   TGLRect selectRect(event->fX, event->fY, 3, 3);
   // Need to do this cross thread under Windows for gVirtualGL context - very ugly...
   UInt_t oldSelection = fSelectedWidget;
   fViewer.RequestSelectManip(selectRect);
   return (fSelectedWidget != oldSelection);
}

//______________________________________________________________________________
Double_t TGLManip::DrawScale(const TGLBoundingBox & box, const TGLCamera & camera) const
{
   TGLVector3 pixelInWorld = camera.ViewportDeltaToWorld(box.Center(), 1, 1);
   Double_t pixelScale = pixelInWorld.Mag();
   Double_t scale = box.Extents().Mag() / 100.0;
   if (scale < pixelScale * 2.0) {
      scale = pixelScale * 2.0;
   } else if (scale > pixelScale * 5.0) {
      scale = pixelScale * 5.0;
   }
   return scale;
}

//______________________________________________________________________________
void TGLManip::DrawAxisWidget(EHeadShape head, Double_t scale, const TGLVertex3 & origin, const TGLVector3 & vector, Float_t rgba[4]) const
{
   // Draw an axis widget with head type of arrow or box
   SetDrawColors(rgba);
   glPushMatrix();
   TGLMatrix local(origin, vector);
   glMultMatrixd(local.CArr());
   gluCylinder(fgQuad.Get(), scale/4.0, scale/4.0, vector.Mag(), fgQuality, fgQuality); // Line
   gluQuadricOrientation(fgQuad.Get(), (GLenum)GLU_INSIDE);
   gluDisk(fgQuad.Get(), 0.0, scale/4.0, fgQuality, fgQuality);

   // TODO: axis is longer than vector by head object - this is attached at end
   // doesn't really matter...?
   glTranslated(0.0, 0.0, vector.Mag()); // Shift down local Z to end of vector

   if (head == kArrow) {
      gluDisk(fgQuad.Get(), 0.0, scale, fgQuality, fgQuality);
      gluQuadricOrientation(fgQuad.Get(), (GLenum)GLU_OUTSIDE);
      gluCylinder(fgQuad.Get(), scale, 0.0, scale*2.0, fgQuality, fgQuality); // Arrow head
   } else if (head == kBox) {
      gluQuadricOrientation(fgQuad.Get(), (GLenum)GLU_OUTSIDE);
      // TODO: Drawing box should be simplier - maybe make a static helper which BB + others use.
      // This doesn't tesselate properly - ugly lighting
      TGLBoundingBox box(TGLVertex3(-scale*.7, -scale*.7, 0.0), TGLVertex3(scale*.7, scale*.7, scale*1.4));
      box.Draw(kTRUE);
   }
   glPopMatrix();
}

//______________________________________________________________________________
void TGLManip::DrawOrigin(const TGLVertex3 & origin, Double_t scale, Float_t rgba[4]) const
{
   SetDrawColors(rgba);
   glPushMatrix();
   glTranslated(origin.X(), origin.Y(), origin.Z());
   gluSphere(fgQuad.Get(), scale*2.0, fgQuality, fgQuality);
   glPopMatrix();
}

//______________________________________________________________________________
void TGLManip::SetDrawColors(Float_t rgba[4]) const
{
   static Float_t ambient[4] = {0.0, 0.0, 0.0, 1.0};
   static Float_t specular[4] = {0.8, 0.8, 0.8, 1.0};
   static Float_t emission[4] = {0.1, 0.1, 0.1, 1.0};

   glMaterialfv(GL_FRONT, GL_DIFFUSE, rgba);
   glMaterialfv(GL_FRONT, GL_AMBIENT, ambient);
   glMaterialfv(GL_FRONT, GL_SPECULAR, specular);
   glMaterialfv(GL_FRONT, GL_EMISSION, emission);
   glMaterialf(GL_FRONT, GL_SHININESS, 60.0);
}
<commit_msg>From Richard: Fix minor bug with manipulator component selection.<commit_after>// @(#)root/gl:$Name:  $:$Id: TGLManip.cxx
// Author:  Richard Maunder  16/09/2005

/*************************************************************************
 * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TGLManip.h"
#include "TGLUtil.h"
#include "TGLCamera.h"
#include "TGLViewer.h"
#include "TGLPhysicalShape.h"
#include "TGLIncludes.h"

TGLQuadric TGLManip::fgQuad;

//TODO: Should really use LOD adjustment on top?
UInt_t TGLManip::fgQuality = 60;

Float_t TGLManip::fgRed[4]    = {1.0, 0.0, 0.0, 1.0 };
Float_t TGLManip::fgGreen[4]  = {0.0, 1.0, 0.0, 1.0 };
Float_t TGLManip::fgBlue[4]   = {0.0, 0.0, 1.0, 1.0 };
Float_t TGLManip::fgYellow[4] = {1.0, 1.0, 0.0, 1.0 };
Float_t TGLManip::fgWhite[4]  = {1.0, 1.0, 1.0, 1.0 };
Float_t TGLManip::fgGrey[4]   = {0.5, 0.5, 0.5, 0.4 };

ClassImp(TGLManip)

//______________________________________________________________________________
TGLManip::TGLManip(TGLViewer & viewer) :
   fViewer(viewer), fShape(0),
   fSelectedWidget(0), fActive(kFALSE),
   fFirstMouse(0, 0),
   fLastMouse(0, 0)
{
}

//______________________________________________________________________________
TGLManip::TGLManip(TGLViewer & viewer, TGLPhysicalShape * shape) :
   fViewer(viewer), fShape(shape),
   fSelectedWidget(0), fActive(kFALSE),
   fFirstMouse(0, 0),
   fLastMouse(0, 0)
{
}

//______________________________________________________________________________
TGLManip::~TGLManip()
{
}

//______________________________________________________________________________
void TGLManip::Select(const TGLCamera & camera)
{
   static UInt_t selectBuffer[4*4];
   glSelectBuffer(4*4, &selectBuffer[0]);
   glRenderMode(GL_SELECT);
   glInitNames();
   Draw(camera);
   Int_t hits = glRenderMode(GL_RENDER);
   TGLUtil::CheckError();
   if (hits < 0) {
      Error("TGLManip::Select", "selection buffer overflow");
      return;
   }

   if (hits > 0) {
      fSelectedWidget = 0;
      UInt_t minDepth = kMaxUInt;
      for (Int_t i = 0; i < hits; i++) {
         // Skip selection on unnamed hits
         if (selectBuffer[i * 4] == 0) {
            continue;
         }
         if (selectBuffer[i * 4 + 1] < minDepth) {
            fSelectedWidget = selectBuffer[i * 4 + 3];
            minDepth = selectBuffer[i * 4 + 1];
         }
      }
   } else {
      fSelectedWidget = 0;
   }
}

//______________________________________________________________________________
Bool_t TGLManip::HandleButton(const Event_t * event, const TGLCamera & /*camera*/)
{
   // Only interested in Left mouse button actions
   if (event->fCode != kButton1) {
      return kFALSE;
   }

   // Mouse down on selected widget?
   if (event->fType == kButtonPress && fSelectedWidget != 0) {
      fFirstMouse.SetX(event->fX);
      fFirstMouse.SetY(event->fY);
      fLastMouse.SetX(event->fX);
      fLastMouse.SetY(event->fY);
      fActive = kTRUE;
      return kTRUE;
   } else if (event->fType == kButtonRelease && fActive) {
      fActive = kFALSE;
      return kTRUE;
   } else {
      return kFALSE;
   }
}

//______________________________________________________________________________
Bool_t TGLManip::HandleMotion(const Event_t * event, const TGLCamera & /*camera*/)
{
   TGLRect selectRect(event->fX, event->fY, 3, 3);
   // Need to do this cross thread under Windows for gVirtualGL context - very ugly...
   UInt_t oldSelection = fSelectedWidget;
   fViewer.RequestSelectManip(selectRect);
   return (fSelectedWidget != oldSelection);
}

//______________________________________________________________________________
Double_t TGLManip::DrawScale(const TGLBoundingBox & box, const TGLCamera & camera) const
{
   TGLVector3 pixelInWorld = camera.ViewportDeltaToWorld(box.Center(), 1, 1);
   Double_t pixelScale = pixelInWorld.Mag();
   Double_t scale = box.Extents().Mag() / 100.0;
   if (scale < pixelScale * 2.0) {
      scale = pixelScale * 2.0;
   } else if (scale > pixelScale * 5.0) {
      scale = pixelScale * 5.0;
   }
   return scale;
}

//______________________________________________________________________________
void TGLManip::DrawAxisWidget(EHeadShape head, Double_t scale, const TGLVertex3 & origin, const TGLVector3 & vector, Float_t rgba[4]) const
{
   // Draw an axis widget with head type of arrow or box
   SetDrawColors(rgba);
   glPushMatrix();
   TGLMatrix local(origin, vector);
   glMultMatrixd(local.CArr());
   gluCylinder(fgQuad.Get(), scale/4.0, scale/4.0, vector.Mag(), fgQuality, fgQuality); // Line
   gluQuadricOrientation(fgQuad.Get(), (GLenum)GLU_INSIDE);
   gluDisk(fgQuad.Get(), 0.0, scale/4.0, fgQuality, fgQuality);

   // TODO: axis is longer than vector by head object - this is attached at end
   // doesn't really matter...?
   glTranslated(0.0, 0.0, vector.Mag()); // Shift down local Z to end of vector

   if (head == kArrow) {
      gluDisk(fgQuad.Get(), 0.0, scale, fgQuality, fgQuality);
      gluQuadricOrientation(fgQuad.Get(), (GLenum)GLU_OUTSIDE);
      gluCylinder(fgQuad.Get(), scale, 0.0, scale*2.0, fgQuality, fgQuality); // Arrow head
   } else if (head == kBox) {
      gluQuadricOrientation(fgQuad.Get(), (GLenum)GLU_OUTSIDE);
      // TODO: Drawing box should be simplier - maybe make a static helper which BB + others use.
      // This doesn't tesselate properly - ugly lighting
      TGLBoundingBox box(TGLVertex3(-scale*.7, -scale*.7, 0.0), TGLVertex3(scale*.7, scale*.7, scale*1.4));
      box.Draw(kTRUE);
   }
   glPopMatrix();
}

//______________________________________________________________________________
void TGLManip::DrawOrigin(const TGLVertex3 & origin, Double_t scale, Float_t rgba[4]) const
{
   SetDrawColors(rgba);
   glPushMatrix();
   glTranslated(origin.X(), origin.Y(), origin.Z());
   gluSphere(fgQuad.Get(), scale*2.0, fgQuality, fgQuality);
   glPopMatrix();
}

//______________________________________________________________________________
void TGLManip::SetDrawColors(Float_t rgba[4]) const
{
   static Float_t ambient[4] = {0.0, 0.0, 0.0, 1.0};
   static Float_t specular[4] = {0.8, 0.8, 0.8, 1.0};
   static Float_t emission[4] = {0.1, 0.1, 0.1, 1.0};

   glMaterialfv(GL_FRONT, GL_DIFFUSE, rgba);
   glMaterialfv(GL_FRONT, GL_AMBIENT, ambient);
   glMaterialfv(GL_FRONT, GL_SPECULAR, specular);
   glMaterialfv(GL_FRONT, GL_EMISSION, emission);
   glMaterialf(GL_FRONT, GL_SHININESS, 60.0);
}
<|endoftext|>


<commit_before>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2006 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 0.9.5, packaged on February, 2006.

 http://glc-lib.sourceforge.net

 GLC-lib is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 GLC-lib is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*****************************************************************************/

//! \file glc_boundingbox.cpp implementation of the GLC_BoundingBox class.

#include "glc_boundingbox.h"

//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////

// Default constructor
GLC_BoundingBox::GLC_BoundingBox()
: m_Lower(0, 0, 0)
, m_Upper(0, 0, 0)
{

}

// Copy constructor
GLC_BoundingBox::GLC_BoundingBox(const GLC_BoundingBox& boundingBox)
: m_Lower(boundingBox.m_Lower)
, m_Upper(boundingBox.m_Upper)
{
}

// Constructor with 2 points.
GLC_BoundingBox::GLC_BoundingBox(const GLC_Vector4d& lower, const GLC_Vector4d& upper)
: m_Lower(lower)
, m_Upper(upper)
{

}

//////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////

// Test if a point is in the bounding Box
bool GLC_BoundingBox::intersect(const GLC_Vector4d& point) const
{
	bool result= (point.GetX() < m_Upper.GetX()) && (point.GetY() < m_Upper.GetY())
	&& (point.GetZ() < m_Upper.GetZ()) && (point.GetX() > m_Lower.GetX())
	&& (point.GetY() > m_Lower.GetY()) && (point.GetZ() > m_Lower.GetZ());

	return result;
}

// Get the lower corner of the bounding box
GLC_Vector4d GLC_BoundingBox::getLower(void) const
{
	return m_Lower;
}

// Get the upper corner of the bounding box
GLC_Vector4d GLC_BoundingBox::getUpper(void) const
{
	return m_Upper;
}

// Get the center of the bounding box
GLC_Vector4d GLC_BoundingBox::getCenter(void) const
{
	const double x= (m_Lower.GetX() + m_Upper.GetX()) / 2.0;
	const double y= (m_Lower.GetY() + m_Upper.GetY()) / 2.0;
	const double z= (m_Lower.GetZ() + m_Upper.GetZ()) / 2.0;

	GLC_Vector4d vectResult(x, y, z);
	return vectResult;

}

//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////

// Combine the bounding Box with new geometry point
void GLC_BoundingBox::combine(const GLC_Vector4d& point)
{
	double lowerX= fmin(point.GetX(), m_Lower.GetX());
	double lowerY= fmin(point.GetY(), m_Lower.GetY());
	double lowerZ= fmin(point.GetZ(), m_Lower.GetZ());
	m_Lower.SetVect(lowerX, lowerY, lowerZ);

	double upperX= fmax(point.GetX(), m_Upper.GetX());
	double upperY= fmax(point.GetY(), m_Upper.GetY());
	double upperZ= fmax(point.GetZ(), m_Upper.GetZ());
	m_Upper.SetVect(upperX, upperY, upperZ);

}

// Combine the bounding Box with new geometry point
void GLC_BoundingBox::combine(const GLC_Vector3d& point)
{
	double lowerX= fmin(point.GetX(), m_Lower.GetX());
	double lowerY= fmin(point.GetY(), m_Lower.GetY());
	double lowerZ= fmin(point.GetZ(), m_Lower.GetZ());
	m_Lower.SetVect(lowerX, lowerY, lowerZ);

	double upperX= fmax(point.GetX(), m_Upper.GetX());
	double upperY= fmax(point.GetY(), m_Upper.GetY());
	double upperZ= fmax(point.GetZ(), m_Upper.GetZ());
	m_Upper.SetVect(upperX, upperY, upperZ);

}

// Combine the bounding Box with another bounding box
void GLC_BoundingBox::combine(const GLC_BoundingBox& box)
{
	if (m_Lower.IsNull() && m_Upper.IsNull())
	{
		m_Lower= box.m_Lower;
		m_Upper= box.m_Upper;
	}
	else if (!box.m_Lower.IsNull() && !box.m_Upper.IsNull())
	{
		double lowerX= fmin(box.m_Lower.GetX(), m_Lower.GetX());
		double lowerY= fmin(box.m_Lower.GetY(), m_Lower.GetY());
		double lowerZ= fmin(box.m_Lower.GetZ(), m_Lower.GetZ());
		m_Lower.SetVect(lowerX, lowerY, lowerZ);

		double upperX= fmax(box.m_Upper.GetX(), m_Upper.GetX());
		double upperY= fmax(box.m_Upper.GetY(), m_Upper.GetY());
		double upperZ= fmax(box.m_Upper.GetZ(), m_Upper.GetZ());
		m_Upper.SetVect(upperX, upperY, upperZ);
	}

}

<commit_msg>Add member to determine if the bounding box is empty. Update Combine methods<commit_after>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2006 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 0.9.5, packaged on February, 2006.

 http://glc-lib.sourceforge.net

 GLC-lib is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 GLC-lib is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*****************************************************************************/

//! \file glc_boundingbox.cpp implementation of the GLC_BoundingBox class.

#include "glc_boundingbox.h"

//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////

// Default constructor
GLC_BoundingBox::GLC_BoundingBox()
: m_Lower(0, 0, 0)
, m_Upper(0, 0, 0)
, m_IsEmpty(true)
{

}

// Copy constructor
GLC_BoundingBox::GLC_BoundingBox(const GLC_BoundingBox& boundingBox)
: m_Lower(boundingBox.m_Lower)
, m_Upper(boundingBox.m_Upper)
, m_IsEmpty(boundingBox.m_IsEmpty)
{
}

// Constructor with 2 points.
GLC_BoundingBox::GLC_BoundingBox(const GLC_Vector4d& lower, const GLC_Vector4d& upper)
: m_Lower(lower)
, m_Upper(upper)
, m_IsEmpty(false)
{

}

//////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////

// Test if a point is in the bounding Box
bool GLC_BoundingBox::intersect(const GLC_Vector4d& point) const
{
	if (!m_IsEmpty)
	{
		bool result= (point.GetX() < m_Upper.GetX()) && (point.GetY() < m_Upper.GetY())
		&& (point.GetZ() < m_Upper.GetZ()) && (point.GetX() > m_Lower.GetX())
		&& (point.GetY() > m_Lower.GetY()) && (point.GetZ() > m_Lower.GetZ());

		return result;
	}
	else
	{
		return false;
	}
}

// Get the lower corner of the bounding box
GLC_Vector4d GLC_BoundingBox::getLower(void) const
{
	return m_Lower;
}

// Get the upper corner of the bounding box
GLC_Vector4d GLC_BoundingBox::getUpper(void) const
{
	return m_Upper;
}

// Get the center of the bounding box
GLC_Vector4d GLC_BoundingBox::getCenter(void) const
{
	const double x= (m_Lower.GetX() + m_Upper.GetX()) / 2.0;
	const double y= (m_Lower.GetY() + m_Upper.GetY()) / 2.0;
	const double z= (m_Lower.GetZ() + m_Upper.GetZ()) / 2.0;

	GLC_Vector4d vectResult(x, y, z);
	return vectResult;

}

//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////

// Combine the bounding Box with new geometry point
void GLC_BoundingBox::combine(const GLC_Vector4d& point)
{
	if (m_IsEmpty)
	{
		m_Lower= point;
		m_Upper= point;
		m_IsEmpty= false;
	}
	else
	{
		double lowerX= fmin(point.GetX(), m_Lower.GetX());
		double lowerY= fmin(point.GetY(), m_Lower.GetY());
		double lowerZ= fmin(point.GetZ(), m_Lower.GetZ());
		m_Lower.SetVect(lowerX, lowerY, lowerZ);

		double upperX= fmax(point.GetX(), m_Upper.GetX());
		double upperY= fmax(point.GetY(), m_Upper.GetY());
		double upperZ= fmax(point.GetZ(), m_Upper.GetZ());
		m_Upper.SetVect(upperX, upperY, upperZ);
	}

}

// Combine the bounding Box with new geometry point
void GLC_BoundingBox::combine(const GLC_Vector3d& point)
{
	if (m_IsEmpty)
	{
		m_Lower= point;
		m_Upper= point;
		m_IsEmpty= false;
	}
	else
	{
		double lowerX= fmin(point.GetX(), m_Lower.GetX());
		double lowerY= fmin(point.GetY(), m_Lower.GetY());
		double lowerZ= fmin(point.GetZ(), m_Lower.GetZ());
		m_Lower.SetVect(lowerX, lowerY, lowerZ);

		double upperX= fmax(point.GetX(), m_Upper.GetX());
		double upperY= fmax(point.GetY(), m_Upper.GetY());
		double upperZ= fmax(point.GetZ(), m_Upper.GetZ());
		m_Upper.SetVect(upperX, upperY, upperZ);
	}

}

// Combine the bounding Box with another bounding box
void GLC_BoundingBox::combine(const GLC_BoundingBox& box)
{
	if (m_IsEmpty)
	{
		m_Lower= box.m_Lower;
		m_Upper= box.m_Upper;
		m_IsEmpty= false;
	}
	else
	{
		double lowerX= fmin(box.m_Lower.GetX(), m_Lower.GetX());
		double lowerY= fmin(box.m_Lower.GetY(), m_Lower.GetY());
		double lowerZ= fmin(box.m_Lower.GetZ(), m_Lower.GetZ());
		m_Lower.SetVect(lowerX, lowerY, lowerZ);

		double upperX= fmax(box.m_Upper.GetX(), m_Upper.GetX());
		double upperY= fmax(box.m_Upper.GetY(), m_Upper.GetY());
		double upperZ= fmax(box.m_Upper.GetZ(), m_Upper.GetZ());
		m_Upper.SetVect(upperX, upperY, upperZ);
	}

}

<|endoftext|>


<commit_before>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "gm.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkColor.h"
#include "SkMatrix.h"
#include "SkPath.h"
#include "SkRect.h"
#include "SkSize.h"
#include "SkString.h"

namespace skiagm {

class DrawBitmapMatrixGM : public GM {
public:
    DrawBitmapMatrixGM() {}

protected:
    virtual SkString onShortName() SK_OVERRIDE {
        return SkString("drawbitmapmatrix");
    }

    virtual SkISize onISize() SK_OVERRIDE { return make_isize(1024, 256); }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        SkBitmap bm;
        this->setupBitmap(&bm);

        // Draw normally.
        SkMatrix matrix;
        matrix.reset();
        SkPaint paint;
        paint.setAntiAlias(true);
        paint.setDither(true);
        canvas->drawBitmapMatrix(bm, matrix, &paint);

        // Draw stretched horizontally and squished vertically.
        canvas->translate(SkIntToScalar(bm.width() + 5), 0);
        matrix.setScale(SkIntToScalar(2), SK_ScalarHalf);
        canvas->drawBitmapMatrix(bm, matrix, &paint);

        // Draw rotated
        canvas->translate(SkIntToScalar(bm.width()*2 + 5), 0);
        matrix.reset();
        matrix.setRotate(SkIntToScalar(45), SkIntToScalar(bm.width() / 2),
                         SkIntToScalar(bm.height() / 2));
        canvas->save();
        canvas->translate(0, SkIntToScalar(10));
        canvas->drawBitmapMatrix(bm, matrix, &paint);
        canvas->restore();

        // Draw with perspective
        canvas->translate(SkIntToScalar(bm.width() + 15), 0);
        matrix.reset();
        matrix.setPerspX(SkScalarDiv(SK_Scalar1, SkIntToScalar(1000)));
        matrix.setPerspY(SkScalarDiv(SK_Scalar1, SkIntToScalar(1000)));
        canvas->drawBitmapMatrix(bm, matrix, &paint);

        // Draw with skew
        canvas->translate(SkIntToScalar(bm.width() + 5), 0);
        matrix.reset();
        matrix.setSkew(SkIntToScalar(2), SkIntToScalar(2));
        canvas->drawBitmapMatrix(bm, matrix, &paint);

        // Draw with sin/cos
        canvas->translate(SkIntToScalar(bm.width() * 4), 0);
        matrix.reset();
        matrix.setSinCos(SK_ScalarHalf, SkIntToScalar(2));
        canvas->drawBitmapMatrix(bm, matrix, &paint);
    }
private:
    void setupBitmap(SkBitmap* bm) {
        SkASSERT(bm);
        static const int SIZE = 64;
        bm->setConfig(SkBitmap::kARGB_8888_Config, SIZE, SIZE);
        bm->allocPixels();
        SkCanvas canvas(*bm);

        SkPaint paint;
        paint.setColor(SK_ColorGREEN);
        canvas.drawPaint(paint);

        paint.setColor(SK_ColorBLUE);
        paint.setAntiAlias(true);
        SkRect rect = SkRect::MakeWH(SkIntToScalar(SIZE), SkIntToScalar(SIZE));
        SkPath path;
        path.addOval(rect);
        canvas.drawPath(path, paint);
    }
};

////////////////////////////////////////////////////////////////////////////////

static GM* MyFactory(void*) { return new DrawBitmapMatrixGM; }
static GMRegistry reg(MyFactory);

}
<commit_msg>Added additional case to GM:drawbitmapmatrix<commit_after>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "gm.h"
#include "SkBitmap.h"
#include "SkBlurMaskFilter.h"
#include "SkCanvas.h"
#include "SkColor.h"
#include "SkMatrix.h"
#include "SkPath.h"
#include "SkRect.h"
#include "SkSize.h"
#include "SkString.h"

namespace skiagm {

class DrawBitmapMatrixGM : public GM {
public:
    DrawBitmapMatrixGM() {}

protected:
    virtual SkString onShortName() SK_OVERRIDE {
        return SkString("drawbitmapmatrix");
    }

    virtual SkISize onISize() SK_OVERRIDE { return make_isize(1024, 256); }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        SkBitmap bm;
        this->setupBitmap(&bm);

        // Draw normally.
        SkMatrix matrix;
        matrix.reset();
        SkPaint paint;
        paint.setAntiAlias(true);
        paint.setDither(true);
        canvas->drawBitmapMatrix(bm, matrix, &paint);

        // Draw stretched horizontally and squished vertically.
        canvas->translate(SkIntToScalar(bm.width() + 5), 0);
        matrix.setScale(SkIntToScalar(2), SK_ScalarHalf);
        canvas->drawBitmapMatrix(bm, matrix, &paint);

        // Draw rotated
        canvas->translate(SkIntToScalar(bm.width()*2 + 5), 0);
        matrix.reset();
        matrix.setRotate(SkIntToScalar(45), SkIntToScalar(bm.width() / 2),
                         SkIntToScalar(bm.height() / 2));
        canvas->save();
        canvas->translate(0, SkIntToScalar(10));
        canvas->drawBitmapMatrix(bm, matrix, &paint);
        canvas->restore();

        // Draw with perspective
        canvas->translate(SkIntToScalar(bm.width() + 15), 0);
        matrix.reset();
        matrix.setPerspX(SkScalarDiv(SK_Scalar1, SkIntToScalar(1000)));
        matrix.setPerspY(SkScalarDiv(SK_Scalar1, SkIntToScalar(1000)));
        canvas->drawBitmapMatrix(bm, matrix, &paint);

        // Draw with skew
        canvas->translate(SkIntToScalar(bm.width() + 5), 0);
        matrix.reset();
        matrix.setSkew(SkIntToScalar(2), SkIntToScalar(2));
        canvas->drawBitmapMatrix(bm, matrix, &paint);

        // Draw with sin/cos
        canvas->translate(SkIntToScalar(bm.width() * 4), 0);
        matrix.reset();
        matrix.setSinCos(SK_ScalarHalf, SkIntToScalar(2));
        canvas->drawBitmapMatrix(bm, matrix, &paint);

        {
            // test the following code path:
            // SkGpuDevice::drawPath() -> SkGpuDevice::drawWithMaskFilter()
            SkPaint paint;

            paint.setFilterBitmap(true);

            SkMaskFilter* mf = SkBlurMaskFilter::Create(
                5,
                SkBlurMaskFilter::kNormal_BlurStyle,
                SkBlurMaskFilter::kHighQuality_BlurFlag |
                SkBlurMaskFilter::kIgnoreTransform_BlurFlag);
            paint.setMaskFilter(mf)->unref();

            canvas->translate(SkIntToScalar(bm.width()*2 + 20), 0);

            matrix.reset();
            matrix.setRotate(SkIntToScalar(45), SkIntToScalar(bm.width() / 2),
                             SkIntToScalar(bm.height() / 2));

            canvas->save();
            canvas->translate(0, SkIntToScalar(20));
            canvas->drawBitmapMatrix(bm, matrix, &paint);
            canvas->restore();
        }

    }
private:
    void setupBitmap(SkBitmap* bm) {
        SkASSERT(bm);
        static const int SIZE = 64;
        bm->setConfig(SkBitmap::kARGB_8888_Config, SIZE, SIZE);
        bm->allocPixels();
        SkCanvas canvas(*bm);

        SkPaint paint;
        paint.setColor(SK_ColorGREEN);
        canvas.drawPaint(paint);

        paint.setColor(SK_ColorBLUE);
        paint.setAntiAlias(true);
        SkRect rect = SkRect::MakeWH(SkIntToScalar(SIZE), SkIntToScalar(SIZE));
        SkPath path;
        path.addOval(rect);
        canvas.drawPath(path, paint);
    }
};

////////////////////////////////////////////////////////////////////////////////

static GM* MyFactory(void*) { return new DrawBitmapMatrixGM; }
static GMRegistry reg(MyFactory);

}
<|endoftext|>


<commit_before>#include "analysis.h"

/**
 * @brief POI::POI
 */
POI::POI(){}

/**
 * @brief POI::add_detections
 * Adds OOIs for a specific frame in a POI.
 * @param frame_num
 * @param detections
 */
void POI::add_detections(int frame_num, std::vector<OOI> detections) {
    if (start_frame == -1)
        start_frame = frame_num;
    OOIs[frame_num] = detections;
}

/**
 * @brief POI::set_end_frame
 * Sets the end frame of the POI.
 * @param frame_num
 */
void POI::set_end_frame(int frame_num) {
    end_frame = frame_num;
}

/**
 * @brief POI::read
 * Reads POI from json format.
 * @param json
 */
void POI::read(const QJsonObject& json) {
    this->start_frame = json["start"].toInt();
    this->end_frame = json["end"].toInt();
    for(int i = start_frame; i != end_frame; i++){
        std::cout << QString::number(i).toStdString() << std::endl;
        QJsonArray json_frame_OOIs = json[QString::number(i)].toArray();
        std::vector<OOI> oois;
        for(int j = 0; j != json_frame_OOIs.size(); j++){
            OOI ooi;
            ooi.read(json_frame_OOIs[j].toObject());
            oois.push_back(ooi);
        }
        this->OOIs.insert(std::make_pair(i, oois));
    }
}

/**
 * @brief POI::write
 * Writes POI to json format.
 * @param json
 */
void POI::write(QJsonObject& json) {
    json["start"] = start_frame;
    json["end"] = end_frame;
    for(const auto& ooi_pair : OOIs){
        QJsonArray json_frame_OOIs;
        int frame = ooi_pair.first;
        std::vector<OOI> oois = ooi_pair.second;
        for (OOI o : oois) {
            QJsonObject json_ooi;
            o.write(json_ooi);
            json_frame_OOIs.append(json_ooi);
        }
        json[QString::number(frame)] = json_frame_OOIs;
    }
}

/**
 * @brief OOI::OOI
 */
OOI::OOI(){}

/**
 * @brief OOI::OOI
 * @param upper_left
 * @param down_right
 */
OOI::OOI(std::pair<int, int> upper_left, std::pair<int, int> down_right){
    this->upper_left = upper_left;
    this->lower_right = down_right;
}

/**
 * @brief OOI::OOI
 * @param upper_left
 * @param height
 * @param width
 */
OOI::OOI(std::pair<int, int> upper_left, int height, int width){
    this->upper_left = upper_left;
    this ->lower_right = std::make_pair(upper_left.second + width, upper_left.second + height);
}

/**
 * @brief OOI::OOI
 * Creates an OOI from a cv::Rect.
 * @param rect
 */
OOI::OOI(cv::Rect rect) {
    upper_left = std::make_pair(rect.x, rect.y);
    lower_right = std::make_pair(rect.x + rect.width, rect.y + rect.height);
}

/**
 * @brief OOI::read
 * Reads OOI from json format.
 * @param json
 */
void OOI::read(const QJsonObject &json){
    this->upper_left.first = json["UL_X"].toInt();
    this->upper_left.second = json["UL_Y"].toInt();

    this->lower_right.first = json["LR_X"].toInt();
    this->lower_right.second = json["LR_Y"].toInt();
}

/**
 * @brief OOI::write
 * Writes OOI to json format.
 * @param json
 */
void OOI::write(QJsonObject &json){
    json["UL_X"] = this->upper_left.first;
    json["UL_Y"] = this->upper_left.second;

    json["LR_X"] = this->lower_right.first;
    json["LR_Y"] = this->lower_right.second;
}

/**
 * @brief OOI::get_rect
 * Returns the rectangle specified by the OOI.
 * @return
 */
cv::Rect OOI::get_rect() {
    return cv::Rect(upper_left.first, upper_left.second, lower_right.first - upper_left.first,
                      lower_right.second - upper_left.second);
}

/**
 * @brief OOI::scale_coordinates
 * Scales the coordinates in the OOI according to the scale ratio parameter.
 * @param scale_ratio
 */
void OOI::scale_coordinates(float scale_ratio) {
    this->upper_left.first *= scale_ratio;
    this->upper_left.second *= scale_ratio;
    this->lower_right.first *= scale_ratio;
    this->lower_right.second *= scale_ratio;
}

/**
 * @brief Analysis::Analysis
 */
Analysis::Analysis() {
}

/**
 * @brief Analysis::Analysis
 * Copy constructor. Needed for signals and slots.
 * @param obj
 */
Analysis::Analysis(const Analysis &obj) {
    POIs = obj.POIs;
    type = obj.type;
}

/**
 * @brief Analysis::~Analysis
 */
Analysis::~Analysis() {
}

/**
 * @brief Analysis::add_POI
 * Adds a POI to the analysis.
 * @param poi
 */
void Analysis::add_POI(POI poi){
    this->POIs.push_back(poi);
}

/**
 * @brief Analysis::read
 * Reads analysis from json format.
 * @param json
 */
void Analysis::read(const QJsonObject &json){
    this->type = (ANALYSIS_TYPE)json["analysis"].toInt();
    QJsonArray json_pois = json["POI:s"].toArray();
    for (int i = 0; i < json_pois.size(); ++i) {
        QJsonObject json_poi = json_pois[i].toObject();
        POI poi;
        poi.read(json_poi);
        this->add_POI(poi);
    }
}

/**
 * @brief Analysis::write
 * Writes analysis to json format.
 * @param json
 */
void Analysis::write(QJsonObject &json){
    json["type"] = this->type;
    QJsonArray json_POIs;
    for(auto it = this->POIs.begin(); it != this->POIs.end(); it++){
        QJsonObject json_POI;
        POI p = *it;
        p.write(json_POI);
        json_POIs.append(json_POI);
    }
    json["POI:s"] = json_POIs;
}

/**
 * @brief Analysis::get_detections_on_frame
 * Returns all detections on a specified frame in the analysed video.
 * @param frame_num
 * @return
 */
std::vector<cv::Rect> Analysis::get_detections_on_frame(int frame_num) {
    std::vector<cv::Rect> rects;
    for (POI p : POIs) {
        if (frame_num >= p.start_frame && frame_num <= p.end_frame) {
            std::vector<OOI> oois = p.OOIs[frame_num];
            for (OOI o : oois) {
                rects.push_back(o.get_rect());
            }
            break;
        }
    }
    return rects;
}
<commit_msg>removed print<commit_after>#include "analysis.h"

/**
 * @brief POI::POI
 */
POI::POI(){}

/**
 * @brief POI::add_detections
 * Adds OOIs for a specific frame in a POI.
 * @param frame_num
 * @param detections
 */
void POI::add_detections(int frame_num, std::vector<OOI> detections) {
    if (start_frame == -1)
        start_frame = frame_num;
    OOIs[frame_num] = detections;
}

/**
 * @brief POI::set_end_frame
 * Sets the end frame of the POI.
 * @param frame_num
 */
void POI::set_end_frame(int frame_num) {
    end_frame = frame_num;
}

/**
 * @brief POI::read
 * Reads POI from json format.
 * @param json
 */
void POI::read(const QJsonObject& json) {
    this->start_frame = json["start"].toInt();
    this->end_frame = json["end"].toInt();
    for(int i = start_frame; i != end_frame; i++){
        QJsonArray json_frame_OOIs = json[QString::number(i)].toArray();
        std::vector<OOI> oois;
        for(int j = 0; j != json_frame_OOIs.size(); j++){
            OOI ooi;
            ooi.read(json_frame_OOIs[j].toObject());
            oois.push_back(ooi);
        }
        this->OOIs.insert(std::make_pair(i, oois));
    }
}

/**
 * @brief POI::write
 * Writes POI to json format.
 * @param json
 */
void POI::write(QJsonObject& json) {
    json["start"] = start_frame;
    json["end"] = end_frame;
    for(const auto& ooi_pair : OOIs){
        QJsonArray json_frame_OOIs;
        int frame = ooi_pair.first;
        std::vector<OOI> oois = ooi_pair.second;
        for (OOI o : oois) {
            QJsonObject json_ooi;
            o.write(json_ooi);
            json_frame_OOIs.append(json_ooi);
        }
        json[QString::number(frame)] = json_frame_OOIs;
    }
}

/**
 * @brief OOI::OOI
 */
OOI::OOI(){}

/**
 * @brief OOI::OOI
 * @param upper_left
 * @param down_right
 */
OOI::OOI(std::pair<int, int> upper_left, std::pair<int, int> down_right){
    this->upper_left = upper_left;
    this->lower_right = down_right;
}

/**
 * @brief OOI::OOI
 * @param upper_left
 * @param height
 * @param width
 */
OOI::OOI(std::pair<int, int> upper_left, int height, int width){
    this->upper_left = upper_left;
    this ->lower_right = std::make_pair(upper_left.second + width, upper_left.second + height);
}

/**
 * @brief OOI::OOI
 * Creates an OOI from a cv::Rect.
 * @param rect
 */
OOI::OOI(cv::Rect rect) {
    upper_left = std::make_pair(rect.x, rect.y);
    lower_right = std::make_pair(rect.x + rect.width, rect.y + rect.height);
}

/**
 * @brief OOI::read
 * Reads OOI from json format.
 * @param json
 */
void OOI::read(const QJsonObject &json){
    this->upper_left.first = json["UL_X"].toInt();
    this->upper_left.second = json["UL_Y"].toInt();

    this->lower_right.first = json["LR_X"].toInt();
    this->lower_right.second = json["LR_Y"].toInt();
}

/**
 * @brief OOI::write
 * Writes OOI to json format.
 * @param json
 */
void OOI::write(QJsonObject &json){
    json["UL_X"] = this->upper_left.first;
    json["UL_Y"] = this->upper_left.second;

    json["LR_X"] = this->lower_right.first;
    json["LR_Y"] = this->lower_right.second;
}

/**
 * @brief OOI::get_rect
 * Returns the rectangle specified by the OOI.
 * @return
 */
cv::Rect OOI::get_rect() {
    return cv::Rect(upper_left.first, upper_left.second, lower_right.first - upper_left.first,
                      lower_right.second - upper_left.second);
}

/**
 * @brief OOI::scale_coordinates
 * Scales the coordinates in the OOI according to the scale ratio parameter.
 * @param scale_ratio
 */
void OOI::scale_coordinates(float scale_ratio) {
    this->upper_left.first *= scale_ratio;
    this->upper_left.second *= scale_ratio;
    this->lower_right.first *= scale_ratio;
    this->lower_right.second *= scale_ratio;
}

/**
 * @brief Analysis::Analysis
 */
Analysis::Analysis() {
}

/**
 * @brief Analysis::Analysis
 * Copy constructor. Needed for signals and slots.
 * @param obj
 */
Analysis::Analysis(const Analysis &obj) {
    POIs = obj.POIs;
    type = obj.type;
}

/**
 * @brief Analysis::~Analysis
 */
Analysis::~Analysis() {
}

/**
 * @brief Analysis::add_POI
 * Adds a POI to the analysis.
 * @param poi
 */
void Analysis::add_POI(POI poi){
    this->POIs.push_back(poi);
}

/**
 * @brief Analysis::read
 * Reads analysis from json format.
 * @param json
 */
void Analysis::read(const QJsonObject &json){
    this->type = (ANALYSIS_TYPE)json["analysis"].toInt();
    QJsonArray json_pois = json["POI:s"].toArray();
    for (int i = 0; i < json_pois.size(); ++i) {
        QJsonObject json_poi = json_pois[i].toObject();
        POI poi;
        poi.read(json_poi);
        this->add_POI(poi);
    }
}

/**
 * @brief Analysis::write
 * Writes analysis to json format.
 * @param json
 */
void Analysis::write(QJsonObject &json){
    json["type"] = this->type;
    QJsonArray json_POIs;
    for(auto it = this->POIs.begin(); it != this->POIs.end(); it++){
        QJsonObject json_POI;
        POI p = *it;
        p.write(json_POI);
        json_POIs.append(json_POI);
    }
    json["POI:s"] = json_POIs;
}

/**
 * @brief Analysis::get_detections_on_frame
 * Returns all detections on a specified frame in the analysed video.
 * @param frame_num
 * @return
 */
std::vector<cv::Rect> Analysis::get_detections_on_frame(int frame_num) {
    std::vector<cv::Rect> rects;
    for (POI p : POIs) {
        if (frame_num >= p.start_frame && frame_num <= p.end_frame) {
            std::vector<OOI> oois = p.OOIs[frame_num];
            for (OOI o : oois) {
                rects.push_back(o.get_rect());
            }
            break;
        }
    }
    return rects;
}
<|endoftext|>


<commit_before>// vim: set sts=2 sw=2 et:
// encoding: utf-8
//
// Copyleft 2011 RIME Developers
// License: GPLv3
//
// 2011-07-03 GONG Chen <chen.sst@gmail.com>
//
#include <gtest/gtest.h>
#include <rime/impl/table.h>

TEST(RimeTableTest, IntegrityTest) {
  const char file_name[] = "table_test.bin";
  rime::scoped_ptr<rime::Table> table;
  table.reset(new rime::Table(file_name));
  ASSERT_TRUE(table);
  table->Remove();

  rime::Syllabary syll;
  rime::Vocabulary voc;
  rime::DictEntry d;
  syll.insert("0");
  // no entries for '0', however
  syll.insert("1");
  d.code.push_back(1);
  d.text = "yi";
  d.weight = 1.0;
  voc[1].entries.push_back(d);
  syll.insert("2");
  d.code.back() = 2;
  d.text = "er";
  voc[2].entries.push_back(d);
  d.text = "liang";
  voc[2].entries.push_back(d);
  d.text = "lia";
  voc[2].entries.push_back(d);
  syll.insert("3");
  d.code.back() = 3;
  d.text = "san";
  voc[3].entries.push_back(d);
  d.text = "sa";
  voc[3].entries.push_back(d);
  syll.insert("4");
  rime::Vocabulary *lv2 = new rime::Vocabulary;
  voc[1].next_level.reset(lv2);
  rime::Vocabulary *lv3 = new rime::Vocabulary;
  (*lv2)[2].next_level.reset(lv3);
  rime::Vocabulary *lv4 = new rime::Vocabulary;
  (*lv3)[3].next_level.reset(lv4);
  d.code.back() = 1;
  d.code.push_back(2);
  d.code.push_back(3);
  d.code.push_back(4);
  d.text = "yi-er-san-si";
  (*lv4)[-1].entries.push_back(d);

  ASSERT_TRUE(table->Build(syll, voc, 7));
  ASSERT_TRUE(table->Save());
  table.reset();

  table.reset(new rime::Table(file_name));
  ASSERT_TRUE(table);
  ASSERT_TRUE(table->Load());

  EXPECT_STREQ("0", table->GetSyllableById(0));
  EXPECT_STREQ("3", table->GetSyllableById(3));
  EXPECT_STREQ("4", table->GetSyllableById(4));

  rime::TableVisitor v = table->QueryWords(1);
  ASSERT_FALSE(v.exhausted());
  ASSERT_EQ(1, v.remaining());
  ASSERT_TRUE(v.entry());
  EXPECT_STREQ("yi", v.entry()->text.c_str());
  EXPECT_EQ(1.0, v.entry()->weight);
  EXPECT_FALSE(v.Next());

  v = table->QueryWords(2);
  ASSERT_EQ(3, v.remaining());
  EXPECT_STREQ("er", v.entry()->text.c_str());
  v.Next();
  EXPECT_STREQ("liang", v.entry()->text.c_str());
  v.Next();
  EXPECT_STREQ("lia", v.entry()->text.c_str());

  v = table->QueryWords(3);
  ASSERT_EQ(2, v.remaining());
  EXPECT_STREQ("san", v.entry()->text.c_str());
  v.Next();
  EXPECT_STREQ("sa", v.entry()->text.c_str());

  rime::Code code;
  code.push_back(1);
  code.push_back(2);
  code.push_back(3);
  code.push_back(4);
  v = table->QueryPhrases(code);
  ASSERT_FALSE(v.exhausted());
  ASSERT_EQ(1, v.remaining());
  ASSERT_TRUE(v.entry());
  EXPECT_STREQ("yi-er-san-si", v.entry()->text.c_str());
  ASSERT_TRUE(v.extra_code());
  ASSERT_EQ(1, v.extra_code()->size);
  EXPECT_EQ(4, *v.extra_code()->at);
  EXPECT_FALSE(v.Next());
}
<commit_msg>Warnings.<commit_after>// vim: set sts=2 sw=2 et:
// encoding: utf-8
//
// Copyleft 2011 RIME Developers
// License: GPLv3
//
// 2011-07-03 GONG Chen <chen.sst@gmail.com>
//
#include <gtest/gtest.h>
#include <rime/impl/table.h>

TEST(RimeTableTest, IntegrityTest) {
  const char file_name[] = "table_test.bin";
  rime::scoped_ptr<rime::Table> table;
  table.reset(new rime::Table(file_name));
  ASSERT_TRUE(table);
  table->Remove();

  rime::Syllabary syll;
  rime::Vocabulary voc;
  rime::DictEntry d;
  syll.insert("0");
  // no entries for '0', however
  syll.insert("1");
  d.code.push_back(1);
  d.text = "yi";
  d.weight = 1.0;
  voc[1].entries.push_back(d);
  syll.insert("2");
  d.code.back() = 2;
  d.text = "er";
  voc[2].entries.push_back(d);
  d.text = "liang";
  voc[2].entries.push_back(d);
  d.text = "lia";
  voc[2].entries.push_back(d);
  syll.insert("3");
  d.code.back() = 3;
  d.text = "san";
  voc[3].entries.push_back(d);
  d.text = "sa";
  voc[3].entries.push_back(d);
  syll.insert("4");
  rime::Vocabulary *lv2 = new rime::Vocabulary;
  voc[1].next_level.reset(lv2);
  rime::Vocabulary *lv3 = new rime::Vocabulary;
  (*lv2)[2].next_level.reset(lv3);
  rime::Vocabulary *lv4 = new rime::Vocabulary;
  (*lv3)[3].next_level.reset(lv4);
  d.code.back() = 1;
  d.code.push_back(2);
  d.code.push_back(3);
  d.code.push_back(4);
  d.text = "yi-er-san-si";
  (*lv4)[-1].entries.push_back(d);

  ASSERT_TRUE(table->Build(syll, voc, 7));
  ASSERT_TRUE(table->Save());
  table.reset();

  table.reset(new rime::Table(file_name));
  ASSERT_TRUE(table);
  ASSERT_TRUE(table->Load());

  EXPECT_STREQ("0", table->GetSyllableById(0));
  EXPECT_STREQ("3", table->GetSyllableById(3));
  EXPECT_STREQ("4", table->GetSyllableById(4));

  rime::TableVisitor v = table->QueryWords(1);
  ASSERT_FALSE(v.exhausted());
  ASSERT_EQ(1, v.remaining());
  ASSERT_TRUE(v.entry() != NULL);
  EXPECT_STREQ("yi", v.entry()->text.c_str());
  EXPECT_EQ(1.0, v.entry()->weight);
  EXPECT_FALSE(v.Next());

  v = table->QueryWords(2);
  ASSERT_EQ(3, v.remaining());
  EXPECT_STREQ("er", v.entry()->text.c_str());
  v.Next();
  EXPECT_STREQ("liang", v.entry()->text.c_str());
  v.Next();
  EXPECT_STREQ("lia", v.entry()->text.c_str());

  v = table->QueryWords(3);
  ASSERT_EQ(2, v.remaining());
  EXPECT_STREQ("san", v.entry()->text.c_str());
  v.Next();
  EXPECT_STREQ("sa", v.entry()->text.c_str());

  rime::Code code;
  code.push_back(1);
  code.push_back(2);
  code.push_back(3);
  code.push_back(4);
  v = table->QueryPhrases(code);
  ASSERT_FALSE(v.exhausted());
  ASSERT_EQ(1, v.remaining());
  ASSERT_TRUE(v.entry() != NULL);
  EXPECT_STREQ("yi-er-san-si", v.entry()->text.c_str());
  ASSERT_TRUE(v.extra_code() != NULL);
  ASSERT_EQ(1, v.extra_code()->size);
  EXPECT_EQ(4, *v.extra_code()->at);
  EXPECT_FALSE(v.Next());
}
<|endoftext|>


<commit_before>#include "test_core.h"
#include "swoole_file.h"
#include <regex>

using namespace swoole;

const char *file = "/tmp/swoole_log_test.log";

TEST(log, level) {
    sw_logger()->reset();
    sw_logger()->set_level(SW_LOG_NOTICE);
    sw_logger()->open(file);

    sw_logger()->put(SW_LOG_INFO, SW_STRL("hello info"));
    sw_logger()->put(SW_LOG_NOTICE, SW_STRL("hello notice"));
    sw_logger()->put(SW_LOG_WARNING, SW_STRL("hello warning"));

    auto content = file_get_contents(file);

    sw_logger()->close();
    unlink(file);

    ASSERT_FALSE(content->contains(SW_STRL("hello info")));
    ASSERT_TRUE(content->contains(SW_STRL("hello notice")));
    ASSERT_TRUE(content->contains(SW_STRL("hello warning")));
}

TEST(log, date_format) {
    sw_logger()->reset();
    sw_logger()->set_date_format("day %d of %B in the year %Y. Time: %I:%S %p");
    sw_logger()->open(file);

    sw_logger()->put(SW_LOG_WARNING, SW_STRL("hello world"));
    auto content = file_get_contents(file);

    sw_logger()->close();
    unlink(file);

    int data[16];
    char *month = nullptr;
    char *am = nullptr;

    int n = std::sscanf(content->value(),
                        "[day %d of %s in the year %d. Time: %d:%d %s @%d.%d]\tWARNING\thello world",
                        data,
                        month,
                        data + 1,
                        data + 2,
                        data + 3,
                        am,
                        data + 4,
                        data + 5);

    ASSERT_TRUE(n);
}

TEST(log, date_format_long_string) {
    sw_logger()->reset();
    sw_logger()->set_level(SW_LOG_ERROR);
    std::unique_ptr<String> content(new String(256));
    auto str = content.get();

    str->repeat("x", 1, 120);
    str->append(SW_STRL("day %d of %B in the year %Y. Time: %I:%S %p"));

    bool retval = sw_logger()->set_date_format(str->str);

    ASSERT_FALSE(retval);
    ASSERT_EQ(swoole_get_last_error(), SW_ERROR_INVALID_PARAMS);
}

TEST(log, date_with_microseconds) {
    sw_logger()->reset();
    sw_logger()->set_date_with_microseconds(true);
    sw_logger()->open(file);

    sw_logger()->put(SW_LOG_WARNING, SW_STRL("hello world"));
    auto content = file_get_contents(file);

    sw_logger()->close();
    unlink(file);

    std::regex e("\\[\\S+\\s\\d{2}:\\d{2}:\\d{2}\\<\\.(\\d+)\\>\\s@\\d+\\.\\d+\\]\tWARNING\thello world");
    ASSERT_TRUE(std::regex_search(content->value(), e));
}

TEST(log, rotation) {
    sw_logger()->reset();
    sw_logger()->set_rotation(SW_LOG_ROTATION_DAILY);
    sw_logger()->open(file);

    sw_logger()->put(SW_LOG_WARNING, SW_STRL("hello world"));

    ASSERT_EQ(access(sw_logger()->get_file(), R_OK), -1);
    ASSERT_EQ(errno, ENOENT);
    ASSERT_EQ(access(sw_logger()->get_real_file(), R_OK), 0);

    sw_logger()->close();
    unlink(sw_logger()->get_real_file());
}

TEST(log, redirect) {
    char *p = getenv("GITHUB_ACTIONS");
    if (p) {
        return;
    }

    sw_logger()->reset();
    ASSERT_TRUE(sw_logger()->open(file));
    ASSERT_TRUE(sw_logger()->redirect_stdout_and_stderr(1));

    printf("hello world\n");
    auto content = file_get_contents(file);
    ASSERT_NE(content.get(), nullptr);

    sw_logger()->close();
    ASSERT_TRUE(sw_logger()->redirect_stdout_and_stderr(0));
    unlink(sw_logger()->get_real_file());

    ASSERT_TRUE(content->contains(SW_STRL("hello world\n")));
}

namespace TestA {
class TestPrettyName {
  public:
    static void fun(bool strip, const char *expect_str);
};

void TestPrettyName::fun(bool strip, const char *expect_str) {
    ASSERT_STREQ(Logger::get_pretty_name(__PRETTY_FUNCTION__, strip).c_str(), expect_str);
}

void test_pretty_name(bool strip, const char *expect_str) {
    ASSERT_STREQ(Logger::get_pretty_name(__PRETTY_FUNCTION__, strip).c_str(), expect_str);
}
}  // namespace TestA

void test_pretty_name(bool strip, const char *expect_str) {
    ASSERT_STREQ(Logger::get_pretty_name(__PRETTY_FUNCTION__, strip).c_str(), expect_str);
}

TEST(log, pretty_name) {
    TestA::TestPrettyName::fun(false, "TestA::TestPrettyName::fun");
    TestA::test_pretty_name(false, "TestA::test_pretty_name");
    test_pretty_name(false, "test_pretty_name");

    TestA::TestPrettyName::fun(true, "TestPrettyName::fun");
    TestA::test_pretty_name(true, "test_pretty_name");
    test_pretty_name(true, "test_pretty_name");
}
<commit_msg>Added pretty_name_lambda core test<commit_after>#include "test_core.h"
#include "swoole_file.h"
#include <regex>

using namespace swoole;

const char *file = "/tmp/swoole_log_test.log";

TEST(log, level) {
    sw_logger()->reset();
    sw_logger()->set_level(SW_LOG_NOTICE);
    sw_logger()->open(file);

    sw_logger()->put(SW_LOG_INFO, SW_STRL("hello info"));
    sw_logger()->put(SW_LOG_NOTICE, SW_STRL("hello notice"));
    sw_logger()->put(SW_LOG_WARNING, SW_STRL("hello warning"));

    auto content = file_get_contents(file);

    sw_logger()->close();
    unlink(file);

    ASSERT_FALSE(content->contains(SW_STRL("hello info")));
    ASSERT_TRUE(content->contains(SW_STRL("hello notice")));
    ASSERT_TRUE(content->contains(SW_STRL("hello warning")));
}

TEST(log, date_format) {
    sw_logger()->reset();
    sw_logger()->set_date_format("day %d of %B in the year %Y. Time: %I:%S %p");
    sw_logger()->open(file);

    sw_logger()->put(SW_LOG_WARNING, SW_STRL("hello world"));
    auto content = file_get_contents(file);

    sw_logger()->close();
    unlink(file);

    int data[16];
    char *month = nullptr;
    char *am = nullptr;

    int n = std::sscanf(content->value(),
                        "[day %d of %s in the year %d. Time: %d:%d %s @%d.%d]\tWARNING\thello world",
                        data,
                        month,
                        data + 1,
                        data + 2,
                        data + 3,
                        am,
                        data + 4,
                        data + 5);

    ASSERT_TRUE(n);
}

TEST(log, date_format_long_string) {
    sw_logger()->reset();
    sw_logger()->set_level(SW_LOG_ERROR);
    std::unique_ptr<String> content(new String(256));
    auto str = content.get();

    str->repeat("x", 1, 120);
    str->append(SW_STRL("day %d of %B in the year %Y. Time: %I:%S %p"));

    bool retval = sw_logger()->set_date_format(str->str);

    ASSERT_FALSE(retval);
    ASSERT_EQ(swoole_get_last_error(), SW_ERROR_INVALID_PARAMS);
}

TEST(log, date_with_microseconds) {
    sw_logger()->reset();
    sw_logger()->set_date_with_microseconds(true);
    sw_logger()->open(file);

    sw_logger()->put(SW_LOG_WARNING, SW_STRL("hello world"));
    auto content = file_get_contents(file);

    sw_logger()->close();
    unlink(file);

    std::regex e("\\[\\S+\\s\\d{2}:\\d{2}:\\d{2}\\<\\.(\\d+)\\>\\s@\\d+\\.\\d+\\]\tWARNING\thello world");
    ASSERT_TRUE(std::regex_search(content->value(), e));
}

TEST(log, rotation) {
    sw_logger()->reset();
    sw_logger()->set_rotation(SW_LOG_ROTATION_DAILY);
    sw_logger()->open(file);

    sw_logger()->put(SW_LOG_WARNING, SW_STRL("hello world"));

    ASSERT_EQ(access(sw_logger()->get_file(), R_OK), -1);
    ASSERT_EQ(errno, ENOENT);
    ASSERT_EQ(access(sw_logger()->get_real_file(), R_OK), 0);

    sw_logger()->close();
    unlink(sw_logger()->get_real_file());
}

TEST(log, redirect) {
    char *p = getenv("GITHUB_ACTIONS");
    if (p) {
        return;
    }

    sw_logger()->reset();
    ASSERT_TRUE(sw_logger()->open(file));
    ASSERT_TRUE(sw_logger()->redirect_stdout_and_stderr(1));

    printf("hello world\n");
    auto content = file_get_contents(file);
    ASSERT_NE(content.get(), nullptr);

    sw_logger()->close();
    ASSERT_TRUE(sw_logger()->redirect_stdout_and_stderr(0));
    unlink(sw_logger()->get_real_file());

    ASSERT_TRUE(content->contains(SW_STRL("hello world\n")));
}

namespace TestA {
class TestPrettyName {
  public:
    static void fun(bool strip, const char *expect_str);
};

void TestPrettyName::fun(bool strip, const char *expect_str) {
    ASSERT_STREQ(Logger::get_pretty_name(__PRETTY_FUNCTION__, strip).c_str(), expect_str);
}

static void test_pretty_name(bool strip, const char *expect_str) {
    ASSERT_STREQ(Logger::get_pretty_name(__PRETTY_FUNCTION__, strip).c_str(), expect_str);
}

static void test_pretty_name_lambda(bool strip, const char *expect_str) {
    auto fn = [](bool strip, const char *expect_str) {
        ASSERT_STREQ(Logger::get_pretty_name(__PRETTY_FUNCTION__, strip).c_str(), expect_str);
    };
    fn(strip, expect_str);
}

}  // namespace TestA

static void test_pretty_name(bool strip, const char *expect_str) {
    ASSERT_STREQ(Logger::get_pretty_name(__PRETTY_FUNCTION__, strip).c_str(), expect_str);
}

static void test_pretty_name_lambda(bool strip, const char *expect_str) {
    auto fn = [](bool strip, const char *expect_str) {
        ASSERT_STREQ(Logger::get_pretty_name(__PRETTY_FUNCTION__, strip).c_str(), expect_str);
    };
    fn(strip, expect_str);
}

TEST(log, pretty_name) {
    TestA::TestPrettyName::fun(false, "TestA::TestPrettyName::fun");
    TestA::test_pretty_name(false, "TestA::test_pretty_name");
    test_pretty_name(false, "test_pretty_name");

    TestA::TestPrettyName::fun(true, "TestPrettyName::fun");
    TestA::test_pretty_name(true, "test_pretty_name");
    test_pretty_name(true, "test_pretty_name");
}

TEST(log, pretty_name_lambda) {
    TestA::test_pretty_name_lambda(true, "test_pretty_name_lambda");
    test_pretty_name_lambda(true, "test_pretty_name_lambda");

    TestA::test_pretty_name_lambda(false, "TestA::test_pretty_name_lambda");
    test_pretty_name_lambda(false, "test_pretty_name_lambda");
}
<|endoftext|>


<commit_before>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2009 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library 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.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "gluonobjectfactory.h"

#include "directoryprovider.h"
#include "gluonobject.h"
#include "debughelper.h"

#include <QtGui/QApplication>
#include <QtCore/QDir>
#include <QtCore/QPluginLoader>
#include <QtCore/QVariant>

using namespace GluonCore;

GLUON_DEFINE_SINGLETON( GluonObjectFactory )

QStringList
GluonObjectFactory::objectTypeNames() const
{
    QStringList theNames;

    QHash<QString, const QMetaObject*>::const_iterator i;
    for( i = m_objectTypes.constBegin(); i != m_objectTypes.constEnd(); ++i )
        theNames << i.key();

    return theNames;
}

QHash<QString, const QMetaObject*>
GluonObjectFactory::objectTypes() const
{
    return m_objectTypes;
}

const QHash<QString, int>
GluonObjectFactory::objectTypeIDs() const
{
    return m_objectTypeIDs;
}

QStringList
GluonObjectFactory::objectMimeTypes() const
{
    return m_mimeTypes.keys();
}

GluonObject*
GluonObjectFactory::instantiateObjectByName( const QString& objectTypeName )
{
    DEBUG_BLOCK
    QString fullObjectTypeName( objectTypeName );
    if( !objectTypeName.contains( "::" ) )
        fullObjectTypeName = QString( "Gluon::" ) + fullObjectTypeName;

    const QMetaObject* meta;
    if( ( meta = m_objectTypes.value( objectTypeName, 0 ) ) )
    {
        GluonObject* obj = qobject_cast<GluonObject*>( meta->newInstance() );
        if( obj )
        {
            return obj;
        }
        else
        {
            DEBUG_TEXT2( "If you are seeing this message, you have most likely failed to mark the constructor of %1 as Q_INVOKABLE", objectTypeName );
            return 0;
        }
    }

    DEBUG_TEXT( QString( "Object type named %1 not found in factory!" ).arg( objectTypeName ) );

    return 0;
}

GluonObject*
GluonObjectFactory::instantiateObjectByMimetype( const QString& objectMimeType )
{
    return instantiateObjectByName( m_mimeTypes[objectMimeType] );
}

QVariant
GluonObjectFactory::wrapObject( const QVariant& original, GluonObject* newValue )
{
    DEBUG_BLOCK
    QString type = original.typeName();

    if( type.endsWith( '*' ) ) //Remove the * from the type
    {
        type = type.left( type.length() - 1 );
    }

    if( m_objectTypes.contains( type ) )
    {
        QScopedPointer<GluonObject> obj( instantiateObjectByName( type ) );
        return obj->toVariant( newValue );
    }

    DEBUG_TEXT( QString( "Warning: Type %1 not found." ).arg( type ) );

    return QVariant();
}

QVariant
GluonObjectFactory::wrapObject( const QString& type, GluonObject* newValue )
{
    DEBUG_BLOCK
    QString typeName = type;
    if( type.endsWith( '*' ) )
        typeName = type.left( type.length() - 1 );

    if( m_objectTypes.contains( typeName ) )
    {
        QScopedPointer<GluonObject> obj( instantiateObjectByName( typeName ) );
        return obj->toVariant( newValue );
    }

    DEBUG_TEXT( QString( "Warning: Type %1 not found." ).arg( typeName ) );

    return QVariant();
}

GluonObject*
GluonObjectFactory::wrappedObject( const QVariant& wrappedObject )
{
    QString type( wrappedObject.typeName() );
    QString typeName = type;
    if( type.endsWith( '*' ) )
        typeName = type.left( type.length() - 1 );

    if( m_objectTypes.contains( typeName ) )
    {
        QScopedPointer<GluonObject> obj( instantiateObjectByName( typeName ) );
        return obj->fromVariant( wrappedObject );
    }

    DEBUG_BLOCK
    DEBUG_TEXT( QString( "Warning: Type %1 not found." ).arg( typeName ) );

    return 0;
}

void
GluonObjectFactory::loadPlugins()
{
    DEBUG_FUNC_NAME
    QList<QDir> pluginDirs;

    QDir pluginDir( QApplication::applicationDirPath() );

#if defined(Q_OS_WIN)
    if( pluginDir.dirName().toLower() == "debug" || pluginDir.dirName().toLower() == "release" )
        pluginDir.cdUp();
#elif defined(Q_OS_MAC)
    if( pluginDir.dirName() == "MacOS" )
    {
        pluginDir.cdUp();
    }
#endif
    if( pluginDir.cd( "PlugIns" ) )
        pluginDirs.append( pluginDir );

    if( pluginDir.cd( GluonCore::DirectoryProvider::instance()->libDirectory() ) )
        pluginDirs.append( pluginDir );

    // this is the plugin dir on windows
    if( pluginDir.cd( GluonCore::DirectoryProvider::instance()->libDirectory() + "/kde4" ) )
        pluginDirs.append( pluginDir );

    if( pluginDir.cd( GluonCore::DirectoryProvider::instance()->libDirectory() + "/gluon" ) )
        pluginDirs.append( pluginDir );

    if( pluginDir.cd( QDir::homePath() + "/gluonplugins" ) )
        pluginDirs.append( pluginDir );

    DEBUG_TEXT( QString( "Number of plugin locations: %1" ).arg( pluginDirs.count() ) );
    for( QList<QDir>::iterator theDir = pluginDirs.begin(); theDir != pluginDirs.end(); ++theDir )
    {
        DEBUG_TEXT( QString( "Looking for pluggable components in %1" ).arg( (*theDir).absolutePath() ) );

#ifdef Q_WS_X11
        //Only attempt to load our current version. This makes it possible to have different versions
        //of the plugins in the plugin dir.
        (*theDir).setNameFilters( QStringList() << QString( "*.so.%1.%2.%3" ).arg( GLUON_VERSION_MAJOR ).arg( GLUON_VERSION_MINOR ).arg( GLUON_VERSION_PATCH ) );
#endif
        (*theDir).setFilter( QDir::NoDotAndDotDot );

        DEBUG_TEXT( QString( "Found %1 potential plugins. Attempting to load..." ).arg( (*theDir).count() ) );
        foreach( const QString & fileName, (*theDir).entryList( QDir::Files ) )
        {
            // Don't attempt to load non-gluon_plugin prefixed libraries
            if( !fileName.contains( "gluon" ) )
                continue;

            // Don't attempt to load non-libraries
            if( !QLibrary::isLibrary( (*theDir).absoluteFilePath( fileName ) ) )
                continue;

            QPluginLoader loader( (*theDir).absoluteFilePath( fileName ) );
            loader.load();

            if( !loader.isLoaded() )
            {
                DEBUG_TEXT( loader.errorString() );
            }
        }
    }

    DEBUG_TEXT2( "Total number of objects in factory after loading: %1", m_objectTypes.count() );
}

GluonObjectFactory::GluonObjectFactory ( QObject* parent )
    : GluonCore::Singleton< GluonCore::GluonObjectFactory >( parent )
{

}

#include "gluonobjectfactory.moc"
<commit_msg>Fix up the plugin loading issue on Windows/Mac by a one-liner change<commit_after>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2009 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library 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.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "gluonobjectfactory.h"

#include "directoryprovider.h"
#include "gluonobject.h"
#include "debughelper.h"

#include <QtGui/QApplication>
#include <QtCore/QDir>
#include <QtCore/QPluginLoader>
#include <QtCore/QVariant>

using namespace GluonCore;

GLUON_DEFINE_SINGLETON( GluonObjectFactory )

QStringList
GluonObjectFactory::objectTypeNames() const
{
    QStringList theNames;

    QHash<QString, const QMetaObject*>::const_iterator i;
    for( i = m_objectTypes.constBegin(); i != m_objectTypes.constEnd(); ++i )
        theNames << i.key();

    return theNames;
}

QHash<QString, const QMetaObject*>
GluonObjectFactory::objectTypes() const
{
    return m_objectTypes;
}

const QHash<QString, int>
GluonObjectFactory::objectTypeIDs() const
{
    return m_objectTypeIDs;
}

QStringList
GluonObjectFactory::objectMimeTypes() const
{
    return m_mimeTypes.keys();
}

GluonObject*
GluonObjectFactory::instantiateObjectByName( const QString& objectTypeName )
{
    DEBUG_BLOCK
    QString fullObjectTypeName( objectTypeName );
    if( !objectTypeName.contains( "::" ) )
        fullObjectTypeName = QString( "Gluon::" ) + fullObjectTypeName;

    const QMetaObject* meta;
    if( ( meta = m_objectTypes.value( objectTypeName, 0 ) ) )
    {
        GluonObject* obj = qobject_cast<GluonObject*>( meta->newInstance() );
        if( obj )
        {
            return obj;
        }
        else
        {
            DEBUG_TEXT2( "If you are seeing this message, you have most likely failed to mark the constructor of %1 as Q_INVOKABLE", objectTypeName );
            return 0;
        }
    }

    DEBUG_TEXT( QString( "Object type named %1 not found in factory!" ).arg( objectTypeName ) );

    return 0;
}

GluonObject*
GluonObjectFactory::instantiateObjectByMimetype( const QString& objectMimeType )
{
    return instantiateObjectByName( m_mimeTypes[objectMimeType] );
}

QVariant
GluonObjectFactory::wrapObject( const QVariant& original, GluonObject* newValue )
{
    DEBUG_BLOCK
    QString type = original.typeName();

    if( type.endsWith( '*' ) ) //Remove the * from the type
    {
        type = type.left( type.length() - 1 );
    }

    if( m_objectTypes.contains( type ) )
    {
        QScopedPointer<GluonObject> obj( instantiateObjectByName( type ) );
        return obj->toVariant( newValue );
    }

    DEBUG_TEXT( QString( "Warning: Type %1 not found." ).arg( type ) );

    return QVariant();
}

QVariant
GluonObjectFactory::wrapObject( const QString& type, GluonObject* newValue )
{
    DEBUG_BLOCK
    QString typeName = type;
    if( type.endsWith( '*' ) )
        typeName = type.left( type.length() - 1 );

    if( m_objectTypes.contains( typeName ) )
    {
        QScopedPointer<GluonObject> obj( instantiateObjectByName( typeName ) );
        return obj->toVariant( newValue );
    }

    DEBUG_TEXT( QString( "Warning: Type %1 not found." ).arg( typeName ) );

    return QVariant();
}

GluonObject*
GluonObjectFactory::wrappedObject( const QVariant& wrappedObject )
{
    QString type( wrappedObject.typeName() );
    QString typeName = type;
    if( type.endsWith( '*' ) )
        typeName = type.left( type.length() - 1 );

    if( m_objectTypes.contains( typeName ) )
    {
        QScopedPointer<GluonObject> obj( instantiateObjectByName( typeName ) );
        return obj->fromVariant( wrappedObject );
    }

    DEBUG_BLOCK
    DEBUG_TEXT( QString( "Warning: Type %1 not found." ).arg( typeName ) );

    return 0;
}

void
GluonObjectFactory::loadPlugins()
{
    DEBUG_FUNC_NAME
    QList<QDir> pluginDirs;

    QDir pluginDir( QApplication::applicationDirPath() );

#if defined(Q_OS_WIN)
    if( pluginDir.dirName().toLower() == "debug" || pluginDir.dirName().toLower() == "release" )
        pluginDir.cdUp();
#elif defined(Q_OS_MAC)
    if( pluginDir.dirName() == "MacOS" )
    {
        pluginDir.cdUp();
    }
#endif
    if( pluginDir.cd( "PlugIns" ) )
        pluginDirs.append( pluginDir );

    if( pluginDir.cd( GluonCore::DirectoryProvider::instance()->libDirectory() ) )
        pluginDirs.append( pluginDir );

    // this is the plugin dir on windows
    if( pluginDir.cd( GluonCore::DirectoryProvider::instance()->libDirectory() + "/kde4" ) )
        pluginDirs.append( pluginDir );

    if( pluginDir.cd( GluonCore::DirectoryProvider::instance()->libDirectory() + "/gluon" ) )
        pluginDirs.append( pluginDir );

    if( pluginDir.cd( QDir::homePath() + "/gluonplugins" ) )
        pluginDirs.append( pluginDir );

    DEBUG_TEXT( QString( "Number of plugin locations: %1" ).arg( pluginDirs.count() ) );
    for( QList<QDir>::iterator theDir = pluginDirs.begin(); theDir != pluginDirs.end(); ++theDir )
    {
        DEBUG_TEXT( QString( "Looking for pluggable components in %1" ).arg( (*theDir).absolutePath() ) );

#ifdef Q_WS_X11
        //Only attempt to load our current version. This makes it possible to have different versions
        //of the plugins in the plugin dir.
        (*theDir).setNameFilters( QStringList() << QString( "*.so.%1.%2.%3" ).arg( GLUON_VERSION_MAJOR ).arg( GLUON_VERSION_MINOR ).arg( GLUON_VERSION_PATCH ) );
#endif
        (*theDir).setFilter( QDir::AllEntries| QDir::NoDotAndDotDot );

        DEBUG_TEXT( QString( "Found %1 potential plugins. Attempting to load..." ).arg( (*theDir).count() ) );
        foreach( const QString & fileName, (*theDir).entryList( QDir::Files ) )
        {
            // Don't attempt to load non-gluon_plugin prefixed libraries
            if( !fileName.contains( "gluon" ) )
                continue;

            // Don't attempt to load non-libraries
            if( !QLibrary::isLibrary( (*theDir).absoluteFilePath( fileName ) ) )
                continue;

            QPluginLoader loader( (*theDir).absoluteFilePath( fileName ) );
            loader.load();

            if( !loader.isLoaded() )
            {
                DEBUG_TEXT( loader.errorString() );
            }
        }
    }

    DEBUG_TEXT2( "Total number of objects in factory after loading: %1", m_objectTypes.count() );
}

GluonObjectFactory::GluonObjectFactory ( QObject* parent )
    : GluonCore::Singleton< GluonCore::GluonObjectFactory >( parent )
{

}

#include "gluonobjectfactory.moc"
<|endoftext|>


<commit_before>/* main() definition for libpqxx test runners.
 */
#include <cassert>
#include <iostream>
#include <list>
#include <new>
#include <stdexcept>

#include "test_helpers.hxx"

using namespace pqxx;
using namespace pqxx::test;

namespace
{
std::string deref_field(const field &f)
{
  return f.c_str();
}
} // namespace

namespace pqxx::test
{
test_failure::test_failure(
  const std::string &ffile, int fline, const std::string &desc) :
        std::logic_error(desc),
        m_file(ffile),
        m_line(fline)
{}

test_failure::~test_failure() noexcept {}

/// Drop table, if it exists.
void drop_table(transaction_base &t, const std::string &table)
{
  t.exec("DROP TABLE IF EXISTS " + table);
}

[[noreturn]] void
check_notreached(const char file[], int line, std::string desc)
{
  throw test_failure(file, line, desc);
}

void check(
  const char file[], int line, bool condition, const char text[],
  std::string desc)
{
  if (not condition)
    throw test_failure(
      file, line, desc + " (failed expression: " + text + ")");
}

void expected_exception(const std::string &message)
{
  std::cout << "(Expected) " << message << std::endl;
}

std::string list_row(row Obj)
{
  return separated_list(", ", Obj.begin(), Obj.end(), deref_field);
}

std::string list_result(result Obj)
{
  if (Obj.empty())
    return "<empty>";
  return "{" +
         separated_list(
           "}\n{", Obj.begin(), Obj.end(), [](row r) { return list_row(r); }) +
         "}";
}

std::string list_result_iterator(result::const_iterator Obj)
{
  return "<iterator at " + to_string(Obj.rownumber()) + ">";
}

void create_pqxxevents(transaction_base &t)
{
  t.exec(
    "CREATE TEMP TABLE pqxxevents(year integer, event varchar) "
    "ON COMMIT PRESERVE ROWS");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (71, 'jtv')");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (38, 'time_t overflow')");
  t.exec(
    "INSERT INTO pqxxevents(year, event) VALUES (1, '''911'' WTC attack')");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (81, 'C:\\>')");
  t.exec(
    "INSERT INTO pqxxevents(year, event) VALUES (1978, 'bloody\t\tcold')");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (99, '')");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (2002, 'libpqxx')");
  t.exec(
    "INSERT INTO pqxxevents(year, event) "
    "VALUES (1989, 'Ode an die Freiheit')");
  t.exec(
    "INSERT INTO pqxxevents(year, event) VALUES (2001, 'New millennium')");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (1974, '')");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (97, 'Asian crisis')");
  t.exec(
    "INSERT INTO pqxxevents(year, event) VALUES (2001, 'A Space Odyssey')");
}
} // namespace pqxx::test

namespace
{
std::map<const char *, testfunc> *all_tests = nullptr;
} // namespace

namespace pqxx::test
{
void register_test(const char name[], testfunc func)
{
  if (all_tests == nullptr)
  {
    all_tests = new std::map<const char *, testfunc>();
  }
  else
  {
    assert(all_tests->find(name) == all_tests->end());
  }
  (*all_tests)[name] = func;
}
} // namespace pqxx::test

int main(int, const char *argv[])
{
  const char *const test_name = argv[1];

  int test_count = 0;
  std::list<std::string> failed;
  for (const auto &i : *all_tests)
    if (test_name == nullptr or std::string{test_name} == std::string{i.first})
    {
      std::cout << std::endl << "Running: " << i.first << std::endl;

      bool success = false;
      try
      {
        i.second();
        success = true;
      }
      catch (const test_failure &e)
      {
        std::cerr << "Test failure in " + e.file() + " line " +
                       to_string(e.line())
                  << ": " << e.what() << std::endl;
      }
      catch (const std::bad_alloc &)
      {
        std::cerr << "Out of memory!" << std::endl;
      }
      catch (const feature_not_supported &e)
      {
        std::cerr << "Not testing unsupported feature: " << e.what()
                  << std::endl;
        success = true;
        --test_count;
      }
      catch (const sql_error &e)
      {
        std::cerr << "SQL error: " << e.what() << std::endl
                  << "Query was: " << e.query() << std::endl;
      }
      catch (const std::exception &e)
      {
        std::cerr << "Exception: " << e.what() << std::endl;
      }
      catch (...)
      {
        std::cerr << "Unknown exception" << std::endl;
      }

      if (not success)
      {
        std::cerr << "FAILED: " << i.first << std::endl;
        failed.push_back(i.first);
      }
      ++test_count;
    }

  std::cout << "Ran " << test_count << " test(s).\n";

  if (not failed.empty())
  {
    std::cerr << "*** " << failed.size() << " test(s) failed: ***\n";
    for (const auto &i : failed) std::cerr << "\t" << i << '\n';
  }

  return int(failed.size());
}
<commit_msg>Use `emplace_back`.<commit_after>/* main() definition for libpqxx test runners.
 */
#include <cassert>
#include <iostream>
#include <list>
#include <new>
#include <stdexcept>

#include "test_helpers.hxx"

using namespace pqxx;
using namespace pqxx::test;

namespace
{
std::string deref_field(const field &f)
{
  return f.c_str();
}
} // namespace

namespace pqxx::test
{
test_failure::test_failure(
  const std::string &ffile, int fline, const std::string &desc) :
        std::logic_error(desc),
        m_file(ffile),
        m_line(fline)
{}

test_failure::~test_failure() noexcept {}

/// Drop table, if it exists.
void drop_table(transaction_base &t, const std::string &table)
{
  t.exec("DROP TABLE IF EXISTS " + table);
}

[[noreturn]] void
check_notreached(const char file[], int line, std::string desc)
{
  throw test_failure(file, line, desc);
}

void check(
  const char file[], int line, bool condition, const char text[],
  std::string desc)
{
  if (not condition)
    throw test_failure(
      file, line, desc + " (failed expression: " + text + ")");
}

void expected_exception(const std::string &message)
{
  std::cout << "(Expected) " << message << std::endl;
}

std::string list_row(row Obj)
{
  return separated_list(", ", Obj.begin(), Obj.end(), deref_field);
}

std::string list_result(result Obj)
{
  if (Obj.empty())
    return "<empty>";
  return "{" +
         separated_list(
           "}\n{", Obj.begin(), Obj.end(), [](row r) { return list_row(r); }) +
         "}";
}

std::string list_result_iterator(result::const_iterator Obj)
{
  return "<iterator at " + to_string(Obj.rownumber()) + ">";
}

void create_pqxxevents(transaction_base &t)
{
  t.exec(
    "CREATE TEMP TABLE pqxxevents(year integer, event varchar) "
    "ON COMMIT PRESERVE ROWS");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (71, 'jtv')");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (38, 'time_t overflow')");
  t.exec(
    "INSERT INTO pqxxevents(year, event) VALUES (1, '''911'' WTC attack')");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (81, 'C:\\>')");
  t.exec(
    "INSERT INTO pqxxevents(year, event) VALUES (1978, 'bloody\t\tcold')");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (99, '')");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (2002, 'libpqxx')");
  t.exec(
    "INSERT INTO pqxxevents(year, event) "
    "VALUES (1989, 'Ode an die Freiheit')");
  t.exec(
    "INSERT INTO pqxxevents(year, event) VALUES (2001, 'New millennium')");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (1974, '')");
  t.exec("INSERT INTO pqxxevents(year, event) VALUES (97, 'Asian crisis')");
  t.exec(
    "INSERT INTO pqxxevents(year, event) VALUES (2001, 'A Space Odyssey')");
}
} // namespace pqxx::test

namespace
{
std::map<const char *, testfunc> *all_tests = nullptr;
} // namespace

namespace pqxx::test
{
void register_test(const char name[], testfunc func)
{
  if (all_tests == nullptr)
  {
    all_tests = new std::map<const char *, testfunc>();
  }
  else
  {
    assert(all_tests->find(name) == all_tests->end());
  }
  (*all_tests)[name] = func;
}
} // namespace pqxx::test

int main(int, const char *argv[])
{
  const char *const test_name = argv[1];

  int test_count = 0;
  std::list<std::string> failed;
  for (const auto &i : *all_tests)
    if (test_name == nullptr or std::string{test_name} == std::string{i.first})
    {
      std::cout << std::endl << "Running: " << i.first << std::endl;

      bool success = false;
      try
      {
        i.second();
        success = true;
      }
      catch (const test_failure &e)
      {
        std::cerr << "Test failure in " + e.file() + " line " +
                       to_string(e.line())
                  << ": " << e.what() << std::endl;
      }
      catch (const std::bad_alloc &)
      {
        std::cerr << "Out of memory!" << std::endl;
      }
      catch (const feature_not_supported &e)
      {
        std::cerr << "Not testing unsupported feature: " << e.what()
                  << std::endl;
        success = true;
        --test_count;
      }
      catch (const sql_error &e)
      {
        std::cerr << "SQL error: " << e.what() << std::endl
                  << "Query was: " << e.query() << std::endl;
      }
      catch (const std::exception &e)
      {
        std::cerr << "Exception: " << e.what() << std::endl;
      }
      catch (...)
      {
        std::cerr << "Unknown exception" << std::endl;
      }

      if (not success)
      {
        std::cerr << "FAILED: " << i.first << std::endl;
        failed.emplace_back(i.first);
      }
      ++test_count;
    }

  std::cout << "Ran " << test_count << " test(s).\n";

  if (not failed.empty())
  {
    std::cerr << "*** " << failed.size() << " test(s) failed: ***\n";
    for (const auto &i : failed) std::cerr << "\t" << i << '\n';
  }

  return int(failed.size());
}
<|endoftext|>