<commit_before>/*
 * Copyright 2011 Scott MacDonald
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "stdafx.h"
#include "hailstorm_sandbox.h"
#include "gameclient.h"
#include "gui/mainwindow.h"
#include "graphics/dxrenderer.h"
#include "runtime/logging.h"
#include "camera/RotationalCamera.h"

#include "demos/WaterLandscapeDemoScene.h"

// For console
#include <fcntl.h>
#include <io.h>

// Let VC++ know we are compiling for Windows Vista and newer
#ifndef _WIN32_WINNT
#define _WIN32_WINNT   0x0600 // Vista
#endif

void CreateConsoleWindow(bool redirectStdout);

/////////////////////////////////////////////////////////////////////////////
// Application entry point
/////////////////////////////////////////////////////////////////////////////
int APIENTRY _tWinMain( HINSTANCE hInstance,
                        HINSTANCE hPrevInstance,
                        LPTSTR    lpCmdLine,
                        int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);
    UNREFERENCED_PARAMETER(nCmdShow);

    // Enable Visual Studio's debug heap and various memory checking features
    int flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);

    flags |= _CRTDBG_LEAK_CHECK_DF;         // Turn on leak-checking bit.
    flags &= ~_CRTDBG_CHECK_CRT_DF;         // Turn off CRT block checking bit.
    _CrtSetDbgFlag(flags);                  // Now set debug flags

    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);

    // We need a console window
    CreateConsoleWindow(true);

    // A camra is important! We can't see without one, and what kind of graphics demo would this be if we couldn't
    // see anything??
    std::shared_ptr<RotationalCamera> camera(new RotationalCamera());

    // Make sure the logging system is initialized first before any of the
    // other critical system services
    GlobalLog::start();

    // Create a new window
    LOG_NOTICE("WinMain") << "Application has started";
    LOG_NOTICE("WinMain") << "Creating main application window";

    std::shared_ptr<MainWindow> mainWindow( new MainWindow(hInstance, "Hailstorm Tech Demo", 800u, 600u));
    mainWindow->create();

    // Create the renderer (but do not initialize it yet).
    DXRenderer renderer(camera, mainWindow, mainWindow->windowHandle());

    // Create the game client
    LOG_NOTICE("WinMain") << "Creating the game client";
    GameClient game(camera, mainWindow, &renderer);

    // Run the game
    LOG_NOTICE("WinMain") << "Starting the game";
    game.Run(new WaterLandscapeDemoScene(camera));

    return EXIT_SUCCESS;
}

/**
* Creates the a console window using the Windows API, and optionally
* redirects standard output/input to this console window
*/
void CreateConsoleWindow(bool redirectStdout)
{
    // --- I think we should break all this out into a separate class ---
    const int MAX_CONSOLE_LINES = 4096;
    //        const int CONSOLE_COLS      = 100;

    intptr_t stdHandle = 0;
    int consoleHandle = 0;
    FILE * pFile = NULL;

    // Create the console window
    AllocConsole();

    SetConsoleTitleW(L"Application Console");

    // Set up the screen buffer to be big enough that we can scroll the text
    // area
    CONSOLE_SCREEN_BUFFER_INFOEX consoleInfo;
    GetConsoleScreenBufferInfoEx(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo);

    //        consoleInfo.dwSize.X = CONSOLE_COLS;
    consoleInfo.dwSize.Y = MAX_CONSOLE_LINES;

    SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), consoleInfo.dwSize);

    // Redirect unbuffered STDOUT to the console window
    stdHandle = reinterpret_cast<intptr_t>(GetStdHandle(STD_OUTPUT_HANDLE));
    consoleHandle = _open_osfhandle(stdHandle, _O_TEXT);
    pFile = _fdopen(consoleHandle, "w");

    *stdout = *pFile;
    setvbuf(stdout, NULL, _IOLBF, 4096);  // is this large enough?

    // Redirect unbuffered STDIN to the console
    stdHandle = reinterpret_cast<intptr_t>(GetStdHandle(STD_INPUT_HANDLE));
    consoleHandle = _open_osfhandle(stdHandle, _O_TEXT);
    pFile = _fdopen(consoleHandle, "r");

    *stdin = *pFile;
    setvbuf(stdin, NULL, _IONBF, 0);

    // Redirect unbuffered STDERR to the console
    stdHandle = reinterpret_cast<intptr_t>(GetStdHandle(STD_ERROR_HANDLE));
    consoleHandle = _open_osfhandle(stdHandle, _O_TEXT);
    pFile = _fdopen(consoleHandle, "w");

    *stderr = *pFile;
    setvbuf(stderr, NULL, _IONBF, 0);

    // Sync C++ cout/cin/cerr/clog with the new handles
    std::ios::sync_with_stdio();
}<commit_msg>Fixed a bug with pointer ownership. Game client was taking ownership of DXRenderer, but main() had it in local scope and was deleting it as well.<commit_after>/*
 * Copyright 2011 Scott MacDonald
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "stdafx.h"
#include "hailstorm_sandbox.h"
#include "gameclient.h"
#include "gui/mainwindow.h"
#include "graphics/dxrenderer.h"
#include "runtime/logging.h"
#include "camera/RotationalCamera.h"

#include "demos/WaterLandscapeDemoScene.h"

// For console
#include <fcntl.h>
#include <io.h>

// Let VC++ know we are compiling for Windows Vista and newer
#ifndef _WIN32_WINNT
#define _WIN32_WINNT   0x0600 // Vista
#endif

void CreateConsoleWindow(bool redirectStdout);

/////////////////////////////////////////////////////////////////////////////
// Application entry point
/////////////////////////////////////////////////////////////////////////////
int APIENTRY _tWinMain( HINSTANCE hInstance,
                        HINSTANCE hPrevInstance,
                        LPTSTR    lpCmdLine,
                        int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);
    UNREFERENCED_PARAMETER(nCmdShow);

    // Enable Visual Studio's debug heap and various memory checking features
    int flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);

    flags |= _CRTDBG_LEAK_CHECK_DF;         // Turn on leak-checking bit.
    flags &= ~_CRTDBG_CHECK_CRT_DF;         // Turn off CRT block checking bit.
    _CrtSetDbgFlag(flags);                  // Now set debug flags

    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);

    // We need a console window
    CreateConsoleWindow(true);

    // A camra is important! We can't see without one, and what kind of graphics demo would this be if we couldn't
    // see anything??
    std::shared_ptr<RotationalCamera> camera(new RotationalCamera());

    // Make sure the logging system is initialized first before any of the
    // other critical system services
    GlobalLog::start();

    // Create a new window
    LOG_NOTICE("WinMain") << "Application has started";
    LOG_NOTICE("WinMain") << "Creating main application window";

    std::shared_ptr<MainWindow> mainWindow( new MainWindow(hInstance, "Hailstorm Tech Demo", 800u, 600u));
    mainWindow->create();

    // Create the game client
    LOG_NOTICE("WinMain") << "Creating the game client";
    std::unique_ptr<GameClient> game(
        new GameClient(
            camera,
            mainWindow,
            new DXRenderer(
                camera,
                mainWindow,
                mainWindow->windowHandle())));

    // Run the game
    LOG_NOTICE("WinMain") << "Starting the game";
    game->Run(new WaterLandscapeDemoScene(camera));

    return EXIT_SUCCESS;
}

/**
* Creates the a console window using the Windows API, and optionally
* redirects standard output/input to this console window
*/
void CreateConsoleWindow(bool redirectStdout)
{
    // --- I think we should break all this out into a separate class ---
    const int MAX_CONSOLE_LINES = 4096;
    //        const int CONSOLE_COLS      = 100;

    intptr_t stdHandle = 0;
    int consoleHandle = 0;
    FILE * pFile = NULL;

    // Create the console window
    AllocConsole();

    SetConsoleTitleW(L"Application Console");

    // Set up the screen buffer to be big enough that we can scroll the text
    // area
    CONSOLE_SCREEN_BUFFER_INFOEX consoleInfo;
    GetConsoleScreenBufferInfoEx(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo);

    //        consoleInfo.dwSize.X = CONSOLE_COLS;
    consoleInfo.dwSize.Y = MAX_CONSOLE_LINES;

    SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), consoleInfo.dwSize);

    // Redirect unbuffered STDOUT to the console window
    stdHandle = reinterpret_cast<intptr_t>(GetStdHandle(STD_OUTPUT_HANDLE));
    consoleHandle = _open_osfhandle(stdHandle, _O_TEXT);
    pFile = _fdopen(consoleHandle, "w");

    *stdout = *pFile;
    setvbuf(stdout, NULL, _IOLBF, 4096);  // is this large enough?

    // Redirect unbuffered STDIN to the console
    stdHandle = reinterpret_cast<intptr_t>(GetStdHandle(STD_INPUT_HANDLE));
    consoleHandle = _open_osfhandle(stdHandle, _O_TEXT);
    pFile = _fdopen(consoleHandle, "r");

    *stdin = *pFile;
    setvbuf(stdin, NULL, _IONBF, 0);

    // Redirect unbuffered STDERR to the console
    stdHandle = reinterpret_cast<intptr_t>(GetStdHandle(STD_ERROR_HANDLE));
    consoleHandle = _open_osfhandle(stdHandle, _O_TEXT);
    pFile = _fdopen(consoleHandle, "w");

    *stderr = *pFile;
    setvbuf(stderr, NULL, _IONBF, 0);

    // Sync C++ cout/cin/cerr/clog with the new handles
    std::ios::sync_with_stdio();
}<|endoftext|>


<commit_before>// Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//

// GEOM GEOMGUI : GUI for Geometry component
// File   : MeasureGUI_BndBoxDlg.cxx
// Author : Nicolas REJNERI, Open CASCADE S.A.S.

#include "MeasureGUI_BndBoxDlg.h"
#include "MeasureGUI_Widgets.h"

#include "GeometryGUI.h"

#include <GEOMBase.h>
#include <DlgRef.h>

#include <BRepPrimAPI_MakeBox.hxx>

#include <SUIT_Session.h>
#include <SUIT_ResourceMgr.h>
#include <SUIT_OverrideCursor.h>
#include <SalomeApp_Application.h>
#include <SalomeApp_Tools.h>
#include <LightApp_SelectionMgr.h>

//=================================================================================
// class    : MeasureGUI_BndBoxDlg()
// purpose  : Constructs a MeasureGUI_BndBoxDlg which is a child of 'parent', with the
//            name 'name' and widget flags set to 'f'.
//            The dialog will by default be modeless, unless you set 'modal' to
//            true to construct a modal dialog.
//=================================================================================
MeasureGUI_BndBoxDlg::MeasureGUI_BndBoxDlg (GeometryGUI* GUI, QWidget* parent)
  : GEOMBase_Skeleton(GUI, parent)
{
  QPixmap image0 (SUIT_Session::session()->resourceMgr()->loadPixmap("GEOM", tr("ICON_DLG_BOUNDING_BOX")));
  QPixmap image1 (SUIT_Session::session()->resourceMgr()->loadPixmap("GEOM", tr("ICON_SELECT")));

  setWindowTitle(tr("GEOM_BNDBOX_TITLE"));

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

  mainFrame()->GroupConstructors->setTitle(tr("GEOM_BNDBOX"));
  mainFrame()->RadioButton1->setIcon(image0);
  mainFrame()->RadioButton2->setAttribute( Qt::WA_DeleteOnClose );
  mainFrame()->RadioButton2->close();
  mainFrame()->RadioButton3->setAttribute( Qt::WA_DeleteOnClose );
  mainFrame()->RadioButton3->close();

  myGrp = new MeasureGUI_1Sel6LineEdit (centralWidget());
  myGrp->GroupBox1->setTitle( tr( "GEOM_BNDBOX_OBJDIM" ) );
  myGrp->TextLabel1->setText( tr( "GEOM_OBJECT" ) );
  myGrp->TextLabel2->setText( tr( "GEOM_MIN" ) );
  myGrp->TextLabel3->setText( tr( "GEOM_MAX" ) );
  myGrp->TextLabel4->setText( tr( "GEOM_X" ) );
  myGrp->TextLabel5->setText( tr( "GEOM_Y" ) );
  myGrp->TextLabel6->setText( tr( "GEOM_Z" ) );
  myGrp->LineEdit11->setReadOnly( true );
  myGrp->LineEdit12->setReadOnly( true );
  myGrp->LineEdit21->setReadOnly( true );
  myGrp->LineEdit22->setReadOnly( true );
  myGrp->LineEdit31->setReadOnly( true );
  myGrp->LineEdit32->setReadOnly( true );
  myGrp->LineEdit11->setMinimumWidth(120);
  myGrp->LineEdit12->setMinimumWidth(120);
  myGrp->LineEdit21->setMinimumWidth(120);
  myGrp->LineEdit22->setMinimumWidth(120);
  myGrp->LineEdit31->setMinimumWidth(120);
  myGrp->LineEdit32->setMinimumWidth(120);
  myGrp->PushButton1->setIcon( image1 );
  myGrp->LineEdit1->setReadOnly( true );

  QVBoxLayout* layout = new QVBoxLayout( centralWidget() );
  layout->setMargin( 0 ); layout->setSpacing( 6 );
  layout->addWidget( myGrp );

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

  myHelpFileName = "bounding_box_page.html";

  /* Initialisation */
  Init();
}

//=================================================================================
// function : ~MeasureGUI_BndBoxDlg()
// purpose  : Destroys the object and frees any allocated resources
//=================================================================================
MeasureGUI_BndBoxDlg::~MeasureGUI_BndBoxDlg()
{
}

//=================================================================================
// function : Init()
// purpose  :
//=================================================================================
void MeasureGUI_BndBoxDlg::Init()
{
  myEditCurrentArgument = myGrp->LineEdit1;

  connect(buttonOk(),         SIGNAL(clicked()), this, SLOT(ClickOnOk()));
  connect(buttonApply(),      SIGNAL(clicked()), this, SLOT(ClickOnApply()));
  connect(myGrp->PushButton1, SIGNAL(clicked()), this, SLOT(SelectionIntoArgument()));

  connect(myGeomGUI->getApp()->selectionMgr(), SIGNAL(currentSelectionChanged()),
          this, SLOT(SelectionIntoArgument()));

  initName(tr("GEOM_BNDBOX"));
  globalSelection();
  SelectionIntoArgument();
}

//=================================================================================
// function : ClickOnOk()
// purpose  :
//=================================================================================
void MeasureGUI_BndBoxDlg::ClickOnOk()
{
  if (ClickOnApply())
    ClickOnCancel();
}

//=================================================================================
// function : ClickOnApply()
// purpose  :
//=================================================================================
bool MeasureGUI_BndBoxDlg::ClickOnApply()
{
  if (!onAccept())
    return false;

  initName();
  return true;
}

//=================================================================================
// function : ActivateThisDialog()
// purpose  :
//=================================================================================
void MeasureGUI_BndBoxDlg::ActivateThisDialog()
{
  GEOMBase_Skeleton::ActivateThisDialog();

  connect(myGeomGUI->getApp()->selectionMgr(), SIGNAL(currentSelectionChanged()),
          this, SLOT(SelectionIntoArgument()));

  globalSelection();
  redisplayPreview();
}

//=================================================================================
// function : enterEvent()
// purpose  :
//=================================================================================
void MeasureGUI_BndBoxDlg::enterEvent(QEvent*)
{
  if (!mainFrame()->GroupConstructors->isEnabled())
    ActivateThisDialog();
}

//=================================================================================
// function : processObject
// purpose  :
//=================================================================================
void MeasureGUI_BndBoxDlg::processObject()
{
  double aXMin, aXMax, aYMin, aYMax, aZMin, aZMax;

  if (!getParameters(aXMin, aXMax, aYMin, aYMax, aZMin, aZMax)) {
    myEditCurrentArgument->setText("");
    myGrp->LineEdit11->setText("");
    myGrp->LineEdit12->setText("");
    myGrp->LineEdit21->setText("");
    myGrp->LineEdit22->setText("");
    myGrp->LineEdit31->setText("");
    myGrp->LineEdit32->setText("");
  }
  else {
    SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
    int aPrecision = resMgr->integerValue( "Geometry", "length_precision", 6 );

    myGrp->LineEdit11->setText( DlgRef::PrintDoubleValue( aXMin, aPrecision ) );
    myGrp->LineEdit12->setText( DlgRef::PrintDoubleValue( aXMax, aPrecision ) );

    myGrp->LineEdit21->setText( DlgRef::PrintDoubleValue( aYMin, aPrecision ) );
    myGrp->LineEdit22->setText( DlgRef::PrintDoubleValue( aYMax, aPrecision ) );

    myGrp->LineEdit31->setText( DlgRef::PrintDoubleValue( aZMin, aPrecision ) );
    myGrp->LineEdit32->setText( DlgRef::PrintDoubleValue( aZMax, aPrecision ) );
  }
}

//=================================================================================
// function : getParameters
// purpose  :
//=================================================================================
bool MeasureGUI_BndBoxDlg::getParameters (double& theXmin, double& theXmax,
                                          double& theYmin, double& theYmax,
                                          double& theZmin, double& theZmax)
{
  if (myObj->_is_nil())
    return false;

  GEOM::GEOM_IMeasureOperations_var anOper = GEOM::GEOM_IMeasureOperations::_narrow(getOperation());
  anOper->GetBoundingBox(myObj, true, theXmin, theXmax, theYmin, theYmax, theZmin, theZmax);

  return anOper->IsDone();
}

//=================================================================================
// function : buildPrs
// purpose  :
//=================================================================================
SALOME_Prs* MeasureGUI_BndBoxDlg::buildPrs()
{
  double aXMin, aYMin, aZMin, aXMax, aYMax, aZMax;

  if (!getParameters(aXMin, aXMax, aYMin, aYMax, aZMin, aZMax))
    return 0;

  TopoDS_Shape aShape = BRepPrimAPI_MakeBox(gp_Pnt(aXMin, aYMin, aZMin),
                                            gp_Pnt(aXMax, aYMax, aZMax)).Shape();

  return !aShape.IsNull() ? getDisplayer()->BuildPrs(aShape) : 0;
}

//=================================================================================
// function : SelectionIntoArgument()
// purpose  : Called when selection as changed or other case
//=================================================================================
void MeasureGUI_BndBoxDlg::SelectionIntoArgument()
{
  myEditCurrentArgument->setText("");
  myObj = GEOM::GEOM_Object::_nil();

  LightApp_SelectionMgr* aSelMgr = myGeomGUI->getApp()->selectionMgr();
  SALOME_ListIO aSelList;
  aSelMgr->selectedObjects(aSelList);

  if (aSelList.Extent() != 1) {
    processObject();
    erasePreview();
    return;
  }

  GEOM::GEOM_Object_var aSelectedObject = GEOMBase::ConvertIOinGEOMObject(aSelList.First());

  if (aSelectedObject->_is_nil()) {
    processObject();
    erasePreview();
    return;
  }

  myObj = aSelectedObject;
  myEditCurrentArgument->setText(GEOMBase::GetName(myObj));
  processObject();
  redisplayPreview();
}

//=================================================================================
// function : createOperation
// purpose  :
//=================================================================================
GEOM::GEOM_IOperations_ptr MeasureGUI_BndBoxDlg::createOperation()
{
  return getGeomEngine()->GetIMeasureOperations(getStudyId());
}

//=================================================================================
// function : isValid
// purpose  :
//=================================================================================
bool MeasureGUI_BndBoxDlg::isValid (QString&)
{
  return !myObj->_is_nil();
}

//=================================================================================
// function : execute
// purpose  :
//=================================================================================
bool MeasureGUI_BndBoxDlg::execute (ObjectList& objects)
{
  GEOM::GEOM_IMeasureOperations_var anOper = GEOM::GEOM_IMeasureOperations::_narrow(getOperation());
  GEOM::GEOM_Object_var anObj = anOper->MakeBoundingBox(myObj, true);

  if (!anObj->_is_nil())
    objects.push_back(anObj._retn());

  return true;
}

//=================================================================================
// function : redisplayPreview()
// purpose  :
//=================================================================================
void MeasureGUI_BndBoxDlg::redisplayPreview()
{
  QString aMess;
  if (!isValid(aMess)) {
    erasePreview(true);
    return;
  }

  erasePreview(false);

  try {
    SUIT_OverrideCursor();

    getDisplayer()->SetColor(Quantity_NOC_VIOLET);
    getDisplayer()->SetToActivate(false);

    if (SALOME_Prs* aPrs = buildPrs())
      displayPreview(aPrs);
  }
  catch (const SALOME::SALOME_Exception& e) {
    SalomeApp_Tools::QtCatchCorbaException(e);
  }
}
<commit_msg>Fix exception when zero bounding box is obtained<commit_after>// Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//

// GEOM GEOMGUI : GUI for Geometry component
// File   : MeasureGUI_BndBoxDlg.cxx
// Author : Nicolas REJNERI, Open CASCADE S.A.S.

#include "MeasureGUI_BndBoxDlg.h"
#include "MeasureGUI_Widgets.h"

#include "GeometryGUI.h"

#include <GEOMBase.h>
#include <DlgRef.h>

#include <BRepPrimAPI_MakeBox.hxx>

#include <SUIT_Session.h>
#include <SUIT_ResourceMgr.h>
#include <SUIT_OverrideCursor.h>
#include <SalomeApp_Application.h>
#include <SalomeApp_Tools.h>
#include <LightApp_SelectionMgr.h>

//=================================================================================
// class    : MeasureGUI_BndBoxDlg()
// purpose  : Constructs a MeasureGUI_BndBoxDlg which is a child of 'parent', with the
//            name 'name' and widget flags set to 'f'.
//            The dialog will by default be modeless, unless you set 'modal' to
//            true to construct a modal dialog.
//=================================================================================
MeasureGUI_BndBoxDlg::MeasureGUI_BndBoxDlg (GeometryGUI* GUI, QWidget* parent)
  : GEOMBase_Skeleton(GUI, parent)
{
  QPixmap image0 (SUIT_Session::session()->resourceMgr()->loadPixmap("GEOM", tr("ICON_DLG_BOUNDING_BOX")));
  QPixmap image1 (SUIT_Session::session()->resourceMgr()->loadPixmap("GEOM", tr("ICON_SELECT")));

  setWindowTitle(tr("GEOM_BNDBOX_TITLE"));

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

  mainFrame()->GroupConstructors->setTitle(tr("GEOM_BNDBOX"));
  mainFrame()->RadioButton1->setIcon(image0);
  mainFrame()->RadioButton2->setAttribute( Qt::WA_DeleteOnClose );
  mainFrame()->RadioButton2->close();
  mainFrame()->RadioButton3->setAttribute( Qt::WA_DeleteOnClose );
  mainFrame()->RadioButton3->close();

  myGrp = new MeasureGUI_1Sel6LineEdit (centralWidget());
  myGrp->GroupBox1->setTitle( tr( "GEOM_BNDBOX_OBJDIM" ) );
  myGrp->TextLabel1->setText( tr( "GEOM_OBJECT" ) );
  myGrp->TextLabel2->setText( tr( "GEOM_MIN" ) );
  myGrp->TextLabel3->setText( tr( "GEOM_MAX" ) );
  myGrp->TextLabel4->setText( tr( "GEOM_X" ) );
  myGrp->TextLabel5->setText( tr( "GEOM_Y" ) );
  myGrp->TextLabel6->setText( tr( "GEOM_Z" ) );
  myGrp->LineEdit11->setReadOnly( true );
  myGrp->LineEdit12->setReadOnly( true );
  myGrp->LineEdit21->setReadOnly( true );
  myGrp->LineEdit22->setReadOnly( true );
  myGrp->LineEdit31->setReadOnly( true );
  myGrp->LineEdit32->setReadOnly( true );
  myGrp->LineEdit11->setMinimumWidth(120);
  myGrp->LineEdit12->setMinimumWidth(120);
  myGrp->LineEdit21->setMinimumWidth(120);
  myGrp->LineEdit22->setMinimumWidth(120);
  myGrp->LineEdit31->setMinimumWidth(120);
  myGrp->LineEdit32->setMinimumWidth(120);
  myGrp->PushButton1->setIcon( image1 );
  myGrp->LineEdit1->setReadOnly( true );

  QVBoxLayout* layout = new QVBoxLayout( centralWidget() );
  layout->setMargin( 0 ); layout->setSpacing( 6 );
  layout->addWidget( myGrp );

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

  myHelpFileName = "bounding_box_page.html";

  /* Initialisation */
  Init();
}

//=================================================================================
// function : ~MeasureGUI_BndBoxDlg()
// purpose  : Destroys the object and frees any allocated resources
//=================================================================================
MeasureGUI_BndBoxDlg::~MeasureGUI_BndBoxDlg()
{
}

//=================================================================================
// function : Init()
// purpose  :
//=================================================================================
void MeasureGUI_BndBoxDlg::Init()
{
  myEditCurrentArgument = myGrp->LineEdit1;

  connect(buttonOk(),         SIGNAL(clicked()), this, SLOT(ClickOnOk()));
  connect(buttonApply(),      SIGNAL(clicked()), this, SLOT(ClickOnApply()));
  connect(myGrp->PushButton1, SIGNAL(clicked()), this, SLOT(SelectionIntoArgument()));

  connect(myGeomGUI->getApp()->selectionMgr(), SIGNAL(currentSelectionChanged()),
          this, SLOT(SelectionIntoArgument()));

  initName(tr("GEOM_BNDBOX"));
  globalSelection();
  SelectionIntoArgument();
}

//=================================================================================
// function : ClickOnOk()
// purpose  :
//=================================================================================
void MeasureGUI_BndBoxDlg::ClickOnOk()
{
  if (ClickOnApply())
    ClickOnCancel();
}

//=================================================================================
// function : ClickOnApply()
// purpose  :
//=================================================================================
bool MeasureGUI_BndBoxDlg::ClickOnApply()
{
  if (!onAccept())
    return false;

  initName();
  return true;
}

//=================================================================================
// function : ActivateThisDialog()
// purpose  :
//=================================================================================
void MeasureGUI_BndBoxDlg::ActivateThisDialog()
{
  GEOMBase_Skeleton::ActivateThisDialog();

  connect(myGeomGUI->getApp()->selectionMgr(), SIGNAL(currentSelectionChanged()),
          this, SLOT(SelectionIntoArgument()));

  globalSelection();
  redisplayPreview();
}

//=================================================================================
// function : enterEvent()
// purpose  :
//=================================================================================
void MeasureGUI_BndBoxDlg::enterEvent(QEvent*)
{
  if (!mainFrame()->GroupConstructors->isEnabled())
    ActivateThisDialog();
}

//=================================================================================
// function : processObject
// purpose  :
//=================================================================================
void MeasureGUI_BndBoxDlg::processObject()
{
  double aXMin, aXMax, aYMin, aYMax, aZMin, aZMax;

  if (!getParameters(aXMin, aXMax, aYMin, aYMax, aZMin, aZMax)) {
    myEditCurrentArgument->setText("");
    myGrp->LineEdit11->setText("");
    myGrp->LineEdit12->setText("");
    myGrp->LineEdit21->setText("");
    myGrp->LineEdit22->setText("");
    myGrp->LineEdit31->setText("");
    myGrp->LineEdit32->setText("");
  }
  else {
    SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
    int aPrecision = resMgr->integerValue( "Geometry", "length_precision", 6 );

    myGrp->LineEdit11->setText( DlgRef::PrintDoubleValue( aXMin, aPrecision ) );
    myGrp->LineEdit12->setText( DlgRef::PrintDoubleValue( aXMax, aPrecision ) );

    myGrp->LineEdit21->setText( DlgRef::PrintDoubleValue( aYMin, aPrecision ) );
    myGrp->LineEdit22->setText( DlgRef::PrintDoubleValue( aYMax, aPrecision ) );

    myGrp->LineEdit31->setText( DlgRef::PrintDoubleValue( aZMin, aPrecision ) );
    myGrp->LineEdit32->setText( DlgRef::PrintDoubleValue( aZMax, aPrecision ) );
  }
}

//=================================================================================
// function : getParameters
// purpose  :
//=================================================================================
bool MeasureGUI_BndBoxDlg::getParameters (double& theXmin, double& theXmax,
                                          double& theYmin, double& theYmax,
                                          double& theZmin, double& theZmax)
{
  if (myObj->_is_nil())
    return false;

  GEOM::GEOM_IMeasureOperations_var anOper = GEOM::GEOM_IMeasureOperations::_narrow(getOperation());
  anOper->GetBoundingBox(myObj, true, theXmin, theXmax, theYmin, theYmax, theZmin, theZmax);

  return anOper->IsDone();
}

//=================================================================================
// function : buildPrs
// purpose  :
//=================================================================================
SALOME_Prs* MeasureGUI_BndBoxDlg::buildPrs()
{
  double aXMin, aYMin, aZMin, aXMax, aYMax, aZMax;

  if (!getParameters(aXMin, aXMax, aYMin, aYMax, aZMin, aZMax))
    return 0;

  TopoDS_Shape aShape = BRepPrimAPI_MakeBox(gp_Pnt(aXMin, aYMin, aZMin),
                                            gp_Pnt(aXMax, aYMax, aZMax)).Shape();

  return !aShape.IsNull() ? getDisplayer()->BuildPrs(aShape) : 0;
}

//=================================================================================
// function : SelectionIntoArgument()
// purpose  : Called when selection as changed or other case
//=================================================================================
void MeasureGUI_BndBoxDlg::SelectionIntoArgument()
{
  myEditCurrentArgument->setText("");
  myObj = GEOM::GEOM_Object::_nil();

  LightApp_SelectionMgr* aSelMgr = myGeomGUI->getApp()->selectionMgr();
  SALOME_ListIO aSelList;
  aSelMgr->selectedObjects(aSelList);

  if (aSelList.Extent() != 1) {
    processObject();
    erasePreview();
    return;
  }

  GEOM::GEOM_Object_var aSelectedObject = GEOMBase::ConvertIOinGEOMObject(aSelList.First());

  if (aSelectedObject->_is_nil()) {
    processObject();
    erasePreview();
    return;
  }

  myObj = aSelectedObject;
  myEditCurrentArgument->setText(GEOMBase::GetName(myObj));
  processObject();
  redisplayPreview();
}

//=================================================================================
// function : createOperation
// purpose  :
//=================================================================================
GEOM::GEOM_IOperations_ptr MeasureGUI_BndBoxDlg::createOperation()
{
  return getGeomEngine()->GetIMeasureOperations(getStudyId());
}

//=================================================================================
// function : isValid
// purpose  :
//=================================================================================
bool MeasureGUI_BndBoxDlg::isValid (QString&)
{
  return !myObj->_is_nil();
}

//=================================================================================
// function : execute
// purpose  :
//=================================================================================
bool MeasureGUI_BndBoxDlg::execute (ObjectList& objects)
{
  GEOM::GEOM_IMeasureOperations_var anOper = GEOM::GEOM_IMeasureOperations::_narrow(getOperation());
  GEOM::GEOM_Object_var anObj = anOper->MakeBoundingBox(myObj, true);

  if (!anObj->_is_nil())
    objects.push_back(anObj._retn());

  return true;
}

//=================================================================================
// function : redisplayPreview()
// purpose  :
//=================================================================================
void MeasureGUI_BndBoxDlg::redisplayPreview()
{
  QString aMess;
  if (!isValid(aMess)) {
    erasePreview(true);
    return;
  }

  erasePreview(false);

  try {
    SUIT_OverrideCursor();

    getDisplayer()->SetColor(Quantity_NOC_VIOLET);
    getDisplayer()->SetToActivate(false);

    if (SALOME_Prs* aPrs = buildPrs())
      displayPreview(aPrs);
  }
  catch (const SALOME::SALOME_Exception& e) {
    SalomeApp_Tools::QtCatchCorbaException(e);
  }
  catch (...) {
  }
}
<|endoftext|>


<commit_before>#include <atomic>
#include <chrono>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>

#include <derecho/core/derecho.hpp>

#include "aggregate_bandwidth.hpp"
#include "bytes_object.hpp"
#include "log_results.hpp"
#include "partial_senders_allocator.hpp"

using std::cout;
using std::endl;
using namespace persistent;

class ByteArrayObject : public mutils::ByteRepresentable, public derecho::PersistsFields {
public:
    Persistent<test::Bytes> pers_bytes;

    void change_pers_bytes(const test::Bytes& bytes) {
        *pers_bytes = bytes;
    }

    // deserialization constructor
    ByteArrayObject(Persistent<test::Bytes>& _p_bytes) : pers_bytes(std::move(_p_bytes)) {}
    // default constructor
    ByteArrayObject(PersistentRegistry* pr)
            : pers_bytes(std::make_unique<test::Bytes>, nullptr, pr) {}

    REGISTER_RPC_FUNCTIONS(ByteArrayObject, change_pers_bytes);
    DEFAULT_SERIALIZATION_SUPPORT(ByteArrayObject, pers_bytes);
};

struct persistent_bw_result {
    int num_nodes;
    int num_senders_selector;
    int message_payload_size;
    int num_msgs;
    double persist_bw;

    void print(std::ofstream& fout) {
        fout << num_nodes << " " << num_senders_selector << " "
             << message_payload_size << " " << num_msgs << " "
             << persist_bw << std::endl;
    }
};

int main(int argc, char* argv[]) {
    //std::chrono is too verbose
    using namespace std::chrono;

    if(argc < 4) {
        std::cout << "usage:" << argv[0] << " <all|half|one> <num_of_nodes> <num_msgs>" << std::endl;
        return -1;
    }
    pthread_setname_np(pthread_self(), "persistent_bw_test");

    derecho::Conf::initialize(argc, argv);

    //The maximum number of bytes that can be sent to change_pers_bytes() is not quite MAX_PAYLOAD_SIZE.
    //The serialized Bytes object will include its size field as well as the actual buffer, and
    //the RPC function header contains an InvocationID (which is a size_t) as well as the header
    //fields defined by remote_invocation_utilites::header_space().
    const std::size_t rpc_header_size = sizeof(std::size_t) + sizeof(std::size_t)
                                        + derecho::remote_invocation_utilities::header_space();

    PartialSendMode sender_selector = PartialSendMode::ALL_SENDERS;
    if(strcmp(argv[1], "half") == 0) sender_selector = PartialSendMode::HALF_SENDERS;
    if(strcmp(argv[1], "one") == 0) sender_selector = PartialSendMode::ONE_SENDER;
    const int num_of_nodes = atoi(argv[2]);
    const int msg_size = derecho::getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE) - rpc_header_size;
    const int num_msgs = atoi(argv[3]);
    steady_clock::time_point begin_time, send_complete_time, persist_complete_time;

    bool is_sending = true;

    long total_num_messages;
    switch(sender_selector) {
        case PartialSendMode::ALL_SENDERS:
            total_num_messages = num_of_nodes * num_msgs;
            break;
        case PartialSendMode::HALF_SENDERS:
            total_num_messages = (num_of_nodes / 2) * num_msgs;
            break;
        case PartialSendMode::ONE_SENDER:
            total_num_messages = num_msgs;
            break;
    }
    // variable 'done' tracks the end of the test
    volatile bool done = false;

    // last_version and its flag is shared between the stability callback and persistence callback.
    // This is a clumsy hack to figure out what version number is assigned to the last delivered message.
    persistent::version_t last_version;
    std::atomic<bool> last_version_set = false;

    auto stability_callback = [&last_version,
                               &last_version_set,
                               &send_complete_time,
                               total_num_messages,
                               num_delivered = 0u](uint32_t subgroup,
                                                   uint32_t sender_id,
                                                   long long int index,
                                                   std::optional<std::pair<char*, long long int>> data,
                                                   persistent::version_t ver) mutable {
        //Count the total number of messages delivered
        ++num_delivered;
        if(num_delivered == total_num_messages) {
            send_complete_time = std::chrono::steady_clock::now();
            last_version = ver;
            last_version_set = true;
        }
    };

    auto persistence_callback = [&](derecho::subgroup_id_t subgroup, persistent::version_t ver) {
        if(last_version_set && ver == last_version) {
            persist_complete_time = std::chrono::steady_clock::now();
            done = true;
        }
    };
    derecho::CallbackSet callback_set{
            stability_callback,
            persistence_callback};

    derecho::SubgroupInfo subgroup_info(PartialSendersAllocator(num_of_nodes, sender_selector));

    auto ba_factory = [](PersistentRegistry* pr, derecho::subgroup_id_t) { return std::make_unique<ByteArrayObject>(pr); };

    derecho::Group<ByteArrayObject> group{callback_set, subgroup_info, {},
                                          std::vector<derecho::view_upcall_t>{}, ba_factory};

    std::cout << "Finished constructing/joining Group" << std::endl;

    auto node_rank = group.get_my_rank();
    if((sender_selector == PartialSendMode::HALF_SENDERS) && (node_rank <= (num_of_nodes - 1) / 2)) {
        is_sending = false;
    }
    if((sender_selector == PartialSendMode::ONE_SENDER) && (node_rank != num_of_nodes - 1)) {
        is_sending = false;
    }
    std::cout << "my rank is: " << node_rank << ", and I'm sending: " << std::boolalpha << is_sending << std::endl;

    //Allocate this memory before starting the timer, even if we end up not needing it
    char* bbuf = new char[msg_size];
    memset(bbuf, 0, msg_size);
    test::Bytes bs(bbuf, msg_size);

    // Start the experiment timer
    begin_time = std::chrono::steady_clock::now();
    if(is_sending) {
        derecho::Replicated<ByteArrayObject>& handle = group.get_subgroup<ByteArrayObject>();
        for(int i = 0; i < num_msgs; i++) {
            handle.ordered_send<RPC_NAME(change_pers_bytes)>(bs);
        }
#if defined(_PERFORMANCE_DEBUG)
        (*handle.user_object_ptr)->pers_bytes.print_performance_stat();
#endif  //_PERFORMANCE_DEBUG
    }

    while(!done) {
    }
    int64_t send_nanosec = duration_cast<nanoseconds>(send_complete_time - begin_time).count();
    double send_millisec = static_cast<double>(send_nanosec) / 1000000;
    int64_t persist_nanosec = duration_cast<nanoseconds>(persist_complete_time - begin_time).count();
    double persist_millisec = static_cast<double>(persist_nanosec) / 1000000;

    //Calculate bandwidth
    //Bytes / nanosecond just happens to be equivalent to GigaBytes / second (in "decimal" GB)
    //Note that total_num_messages already incorporates multiplying by the number of senders
    double send_thp_gbps = (static_cast<double>(total_num_messages) * msg_size) / send_nanosec;
    double send_thp_ops = (static_cast<double>(total_num_messages) * 1000000000) / send_nanosec;
    std::cout << "(send)timespan: " << send_millisec << " milliseconds." << std::endl;
    std::cout << "(send)throughput: " << send_thp_gbps << "GB/s." << std::endl;
    std::cout << "(send)throughput: " << send_thp_ops << "ops." << std::endl;

    double thp_gbps = (static_cast<double>(total_num_messages) * msg_size) / persist_nanosec;
    double thp_ops = (static_cast<double>(total_num_messages) * 1000000000) / persist_nanosec;
    std::cout << "(pers)timespan: " << persist_millisec << " millisecond." << std::endl;
    std::cout << "(pers)throughput: " << thp_gbps << "GB/s." << std::endl;
    std::cout << "(pers)throughput: " << thp_ops << "ops." << std::endl;
    std::cout << std::flush;

    //aggregate_bandwidth only supports one value, so aggregate the more important persistence value
    auto members = group.get_members();
    double avg_persist_bw = aggregate_bandwidth(members, members[node_rank], thp_gbps);

    if(node_rank == 0) {
        log_results(persistent_bw_result{num_of_nodes, static_cast<std::underlying_type_t<PartialSendMode>>(sender_selector),
                                         msg_size, num_msgs, avg_persist_bw},
                    "data_persistent_bw");
    }

    group.barrier_sync();
    group.leave();
}
<commit_msg>minor bug fix.<commit_after>#include <atomic>
#include <chrono>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>

#include <derecho/core/derecho.hpp>

#include "aggregate_bandwidth.hpp"
#include "bytes_object.hpp"
#include "log_results.hpp"
#include "partial_senders_allocator.hpp"

using std::cout;
using std::endl;
using namespace persistent;

class ByteArrayObject : public mutils::ByteRepresentable, public derecho::PersistsFields {
public:
    Persistent<test::Bytes> pers_bytes;

    void change_pers_bytes(const test::Bytes& bytes) {
        *pers_bytes = bytes;
    }

    // deserialization constructor
    ByteArrayObject(Persistent<test::Bytes>& _p_bytes) : pers_bytes(std::move(_p_bytes)) {}
    // default constructor
    ByteArrayObject(PersistentRegistry* pr)
            : pers_bytes(std::make_unique<test::Bytes>, nullptr, pr) {}

    REGISTER_RPC_FUNCTIONS(ByteArrayObject, change_pers_bytes);
    DEFAULT_SERIALIZATION_SUPPORT(ByteArrayObject, pers_bytes);
};

struct persistent_bw_result {
    int num_nodes;
    int num_senders_selector;
    int message_payload_size;
    int num_msgs;
    double persist_bw;

    void print(std::ofstream& fout) {
        fout << num_nodes << " " << num_senders_selector << " "
             << message_payload_size << " " << num_msgs << " "
             << persist_bw << std::endl;
    }
};

int main(int argc, char* argv[]) {
    //std::chrono is too verbose
    using namespace std::chrono;

    if(argc < 4) {
        std::cout << "usage:" << argv[0] << " <all|half|one> <num_of_nodes> <num_msgs>" << std::endl;
        return -1;
    }
    pthread_setname_np(pthread_self(), "persistent_bw_test");

    derecho::Conf::initialize(argc, argv);

    //The maximum number of bytes that can be sent to change_pers_bytes() is not quite MAX_PAYLOAD_SIZE.
    //The serialized Bytes object will include its size field as well as the actual buffer, and
    //the RPC function header contains an InvocationID (which is a size_t) as well as the header
    //fields defined by remote_invocation_utilites::header_space().
    const std::size_t rpc_header_size = sizeof(std::size_t) + sizeof(std::size_t)
                                        + derecho::remote_invocation_utilities::header_space();

    PartialSendMode sender_selector = PartialSendMode::ALL_SENDERS;
    if(strcmp(argv[1], "half") == 0) sender_selector = PartialSendMode::HALF_SENDERS;
    if(strcmp(argv[1], "one") == 0) sender_selector = PartialSendMode::ONE_SENDER;
    const int num_of_nodes = atoi(argv[2]);
    const int msg_size = derecho::getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE) - rpc_header_size;
    const int num_msgs = atoi(argv[3]);
    steady_clock::time_point begin_time, send_complete_time, persist_complete_time;

    bool is_sending = true;

    long total_num_messages;
    switch(sender_selector) {
        case PartialSendMode::ALL_SENDERS:
            total_num_messages = num_of_nodes * num_msgs;
            break;
        case PartialSendMode::HALF_SENDERS:
            total_num_messages = (num_of_nodes / 2) * num_msgs;
            break;
        case PartialSendMode::ONE_SENDER:
            total_num_messages = num_msgs;
            break;
    }
    // variable 'done' tracks the end of the test
    volatile bool done = false;

    // last_version and its flag is shared between the stability callback and persistence callback.
    // This is a clumsy hack to figure out what version number is assigned to the last delivered message.
    persistent::version_t last_version;
    std::atomic<bool> last_version_set = false;

    auto stability_callback = [&last_version,
                               &last_version_set,
                               &send_complete_time,
                               total_num_messages,
                               num_delivered = 0u](uint32_t subgroup,
                                                   uint32_t sender_id,
                                                   long long int index,
                                                   std::optional<std::pair<char*, long long int>> data,
                                                   persistent::version_t ver) mutable {
        //Count the total number of messages delivered
        ++num_delivered;
        if(num_delivered == total_num_messages) {
            send_complete_time = std::chrono::steady_clock::now();
            last_version = ver;
            last_version_set = true;
        }
    };

    auto persistence_callback = [&](derecho::subgroup_id_t subgroup, persistent::version_t ver) {
        if(last_version_set && ver == last_version) {
            persist_complete_time = std::chrono::steady_clock::now();
            done = true;
        }
    };
    derecho::CallbackSet callback_set{
            stability_callback,
            nullptr,
            persistence_callback};

    derecho::SubgroupInfo subgroup_info(PartialSendersAllocator(num_of_nodes, sender_selector));

    auto ba_factory = [](PersistentRegistry* pr, derecho::subgroup_id_t) { return std::make_unique<ByteArrayObject>(pr); };

    derecho::Group<ByteArrayObject> group{callback_set, subgroup_info, {},
                                          std::vector<derecho::view_upcall_t>{}, ba_factory};

    std::cout << "Finished constructing/joining Group" << std::endl;

    auto node_rank = group.get_my_rank();
    if((sender_selector == PartialSendMode::HALF_SENDERS) && (node_rank <= (num_of_nodes - 1) / 2)) {
        is_sending = false;
    }
    if((sender_selector == PartialSendMode::ONE_SENDER) && (node_rank != num_of_nodes - 1)) {
        is_sending = false;
    }
    std::cout << "my rank is: " << node_rank << ", and I'm sending: " << std::boolalpha << is_sending << std::endl;

    //Allocate this memory before starting the timer, even if we end up not needing it
    char* bbuf = new char[msg_size];
    memset(bbuf, 0, msg_size);
    test::Bytes bs(bbuf, msg_size);

    // Start the experiment timer
    begin_time = std::chrono::steady_clock::now();
    if(is_sending) {
        derecho::Replicated<ByteArrayObject>& handle = group.get_subgroup<ByteArrayObject>();
        for(int i = 0; i < num_msgs; i++) {
            handle.ordered_send<RPC_NAME(change_pers_bytes)>(bs);
        }
#if defined(_PERFORMANCE_DEBUG)
        (*handle.user_object_ptr)->pers_bytes.print_performance_stat();
#endif  //_PERFORMANCE_DEBUG
    }

    while(!done) {
    }
    int64_t send_nanosec = duration_cast<nanoseconds>(send_complete_time - begin_time).count();
    double send_millisec = static_cast<double>(send_nanosec) / 1000000;
    int64_t persist_nanosec = duration_cast<nanoseconds>(persist_complete_time - begin_time).count();
    double persist_millisec = static_cast<double>(persist_nanosec) / 1000000;

    //Calculate bandwidth
    //Bytes / nanosecond just happens to be equivalent to GigaBytes / second (in "decimal" GB)
    //Note that total_num_messages already incorporates multiplying by the number of senders
    double send_thp_gbps = (static_cast<double>(total_num_messages) * msg_size) / send_nanosec;
    double send_thp_ops = (static_cast<double>(total_num_messages) * 1000000000) / send_nanosec;
    std::cout << "(send)timespan: " << send_millisec << " milliseconds." << std::endl;
    std::cout << "(send)throughput: " << send_thp_gbps << "GB/s." << std::endl;
    std::cout << "(send)throughput: " << send_thp_ops << "ops." << std::endl;

    double thp_gbps = (static_cast<double>(total_num_messages) * msg_size) / persist_nanosec;
    double thp_ops = (static_cast<double>(total_num_messages) * 1000000000) / persist_nanosec;
    std::cout << "(pers)timespan: " << persist_millisec << " millisecond." << std::endl;
    std::cout << "(pers)throughput: " << thp_gbps << "GB/s." << std::endl;
    std::cout << "(pers)throughput: " << thp_ops << "ops." << std::endl;
    std::cout << std::flush;

    //aggregate_bandwidth only supports one value, so aggregate the more important persistence value
    auto members = group.get_members();
    double avg_persist_bw = aggregate_bandwidth(members, members[node_rank], thp_gbps);

    if(node_rank == 0) {
        log_results(persistent_bw_result{num_of_nodes, static_cast<std::underlying_type_t<PartialSendMode>>(sender_selector),
                                         msg_size, num_msgs, avg_persist_bw},
                    "data_persistent_bw");
    }

    group.barrier_sync();
    group.leave();
}
<|endoftext|>


<commit_before>//===- InheritViz.cpp - Graphviz visualization for inheritance --*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements CXXRecordDecl::viewInheritance, which
//  generates a GraphViz DOT file that depicts the class inheritance
//  diagram and then calls Graphviz/dot+gv on it.
//
//===----------------------------------------------------------------------===//

#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/TypeOrdering.h"
#include "llvm/Support/GraphWriter.h"
#include <fstream>
#include <map>

using namespace llvm;

namespace clang {

/// InheritanceHierarchyWriter - Helper class that writes out a
/// GraphViz file that diagrams the inheritance hierarchy starting at
/// a given C++ class type. Note that we do not use LLVM's
/// GraphWriter, because the interface does not permit us to properly
/// differentiate between uses of types as virtual bases
/// vs. non-virtual bases.
class InheritanceHierarchyWriter {
  ASTContext& Context;
  std::ostream &Out;
  std::map<QualType, int, QualTypeOrdering> DirectBaseCount;
  std::set<QualType, QualTypeOrdering> KnownVirtualBases;

public:
  InheritanceHierarchyWriter(ASTContext& Context, std::ostream& Out)
    : Context(Context), Out(Out) { }

  void WriteGraph(QualType Type) {
    Out << "digraph \"" << DOT::EscapeString(Type.getAsString()) << "\" {\n";
    WriteNode(Type, false);
    Out << "}\n";
  }

protected:
  /// WriteNode - Write out the description of node in the inheritance
  /// diagram, which may be a base class or it may be the root node.
  void WriteNode(QualType Type, bool FromVirtual);

  /// WriteNodeReference - Write out a reference to the given node,
  /// using a unique identifier for each direct base and for the
  /// (only) virtual base.
  std::ostream& WriteNodeReference(QualType Type, bool FromVirtual);
};

void InheritanceHierarchyWriter::WriteNode(QualType Type, bool FromVirtual) {
  QualType CanonType = Context.getCanonicalType(Type);

  if (FromVirtual) {
    if (KnownVirtualBases.find(CanonType) != KnownVirtualBases.end())
      return;

    // We haven't seen this virtual base before, so display it and
    // its bases.
    KnownVirtualBases.insert(CanonType);
  }

  // Declare the node itself.
  Out << "  ";
  WriteNodeReference(Type, FromVirtual);

  // Give the node a label based on the name of the class.
  std::string TypeName = Type.getAsString();
  Out << " [ shape=\"box\", label=\"" << DOT::EscapeString(TypeName);

  // If the name of the class was a typedef or something different
  // from the "real" class name, show the real class name in
  // parentheses so we don't confuse ourselves.
  if (TypeName != CanonType.getAsString()) {
    Out << "\\n(" << CanonType.getAsString() << ")";
  }

  // Finished describing the node.
  Out << " \"];\n";

  // Display the base classes.
  const CXXRecordDecl *Decl
    = static_cast<const CXXRecordDecl *>(Type->getAsRecordType()->getDecl());
  for (unsigned idx = 0; idx < Decl->getNumBases(); ++idx) {
    const CXXBaseSpecifier *Base = Decl->getBase(idx);
    QualType CanonBaseType = Context.getCanonicalType(Base->getType());

    // If this is not virtual inheritance, bump the direct base
    // count for the type.
    if (!Base->isVirtual())
      ++DirectBaseCount[CanonBaseType];

    // Write out the node (if we need to).
    WriteNode(Base->getType(), Base->isVirtual());

    // Write out the edge.
    Out << "  ";
    WriteNodeReference(Type, FromVirtual);
    Out << " -> ";
    WriteNodeReference(Base->getType(), Base->isVirtual());

    // Write out edge attributes to show the kind of inheritance.
    if (Base->isVirtual()) {
      Out << " [ style=\"dashed\" ]";
    }
    Out << ";";
  }
}

/// WriteNodeReference - Write out a reference to the given node,
/// using a unique identifier for each direct base and for the
/// (only) virtual base.
std::ostream&
InheritanceHierarchyWriter::WriteNodeReference(QualType Type,
                                               bool FromVirtual) {
  QualType CanonType = Context.getCanonicalType(Type);

  Out << "Class_" << CanonType.getAsOpaquePtr();
  if (!FromVirtual)
    Out << "_" << DirectBaseCount[CanonType];
  return Out;
}

/// viewInheritance - Display the inheritance hierarchy of this C++
/// class using GraphViz.
void QualType::viewInheritance(ASTContext& Context) {
  if (!(*this)->getAsRecordType()) {
    cerr << "Type " << getAsString() << " is not a C++ class type.\n";
    return;
  }
#ifndef NDEBUG
  std::string ErrMsg;
  sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg);
  if (Filename.isEmpty()) {
    cerr << "Error: " << ErrMsg << "\n";
    return;
  }
  Filename.appendComponent(getAsString() + ".dot");
  if (Filename.makeUnique(true,&ErrMsg)) {
    cerr << "Error: " << ErrMsg << "\n";
    return;
  }

  cerr << "Writing '" << Filename << "'... ";

  std::ofstream O(Filename.c_str());

  if (O.good()) {
    InheritanceHierarchyWriter Writer(Context, O);
    Writer.WriteGraph(*this);
    cerr << " done. \n";

    O.close();

    // Display the graph
    DisplayGraph(Filename);
  } else {
    cerr << "error opening file for writing!\n";
    Filename.clear();
  }
#else
  cerr << "QualType::viewInheritance is only available in debug "
       << "builds on systems with Graphviz or gv!\n";
#endif
}

}
<commit_msg>If NDEBUG is set, don't include any of the code for visualizing inheritance hierarchies<commit_after>//===- InheritViz.cpp - Graphviz visualization for inheritance --*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements CXXRecordDecl::viewInheritance, which
//  generates a GraphViz DOT file that depicts the class inheritance
//  diagram and then calls Graphviz/dot+gv on it.
//
//===----------------------------------------------------------------------===//

#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/TypeOrdering.h"
#include "llvm/Support/GraphWriter.h"
#include <fstream>
#include <map>

using namespace llvm;

namespace clang {

#ifndef NDEBUG
/// InheritanceHierarchyWriter - Helper class that writes out a
/// GraphViz file that diagrams the inheritance hierarchy starting at
/// a given C++ class type. Note that we do not use LLVM's
/// GraphWriter, because the interface does not permit us to properly
/// differentiate between uses of types as virtual bases
/// vs. non-virtual bases.
class InheritanceHierarchyWriter {
  ASTContext& Context;
  std::ostream &Out;
  std::map<QualType, int, QualTypeOrdering> DirectBaseCount;
  std::set<QualType, QualTypeOrdering> KnownVirtualBases;

public:
  InheritanceHierarchyWriter(ASTContext& Context, std::ostream& Out)
    : Context(Context), Out(Out) { }

  void WriteGraph(QualType Type) {
    Out << "digraph \"" << DOT::EscapeString(Type.getAsString()) << "\" {\n";
    WriteNode(Type, false);
    Out << "}\n";
  }

protected:
  /// WriteNode - Write out the description of node in the inheritance
  /// diagram, which may be a base class or it may be the root node.
  void WriteNode(QualType Type, bool FromVirtual);

  /// WriteNodeReference - Write out a reference to the given node,
  /// using a unique identifier for each direct base and for the
  /// (only) virtual base.
  std::ostream& WriteNodeReference(QualType Type, bool FromVirtual);
};

void InheritanceHierarchyWriter::WriteNode(QualType Type, bool FromVirtual) {
  QualType CanonType = Context.getCanonicalType(Type);

  if (FromVirtual) {
    if (KnownVirtualBases.find(CanonType) != KnownVirtualBases.end())
      return;

    // We haven't seen this virtual base before, so display it and
    // its bases.
    KnownVirtualBases.insert(CanonType);
  }

  // Declare the node itself.
  Out << "  ";
  WriteNodeReference(Type, FromVirtual);

  // Give the node a label based on the name of the class.
  std::string TypeName = Type.getAsString();
  Out << " [ shape=\"box\", label=\"" << DOT::EscapeString(TypeName);

  // If the name of the class was a typedef or something different
  // from the "real" class name, show the real class name in
  // parentheses so we don't confuse ourselves.
  if (TypeName != CanonType.getAsString()) {
    Out << "\\n(" << CanonType.getAsString() << ")";
  }

  // Finished describing the node.
  Out << " \"];\n";

  // Display the base classes.
  const CXXRecordDecl *Decl
    = static_cast<const CXXRecordDecl *>(Type->getAsRecordType()->getDecl());
  for (unsigned idx = 0; idx < Decl->getNumBases(); ++idx) {
    const CXXBaseSpecifier *Base = Decl->getBase(idx);
    QualType CanonBaseType = Context.getCanonicalType(Base->getType());

    // If this is not virtual inheritance, bump the direct base
    // count for the type.
    if (!Base->isVirtual())
      ++DirectBaseCount[CanonBaseType];

    // Write out the node (if we need to).
    WriteNode(Base->getType(), Base->isVirtual());

    // Write out the edge.
    Out << "  ";
    WriteNodeReference(Type, FromVirtual);
    Out << " -> ";
    WriteNodeReference(Base->getType(), Base->isVirtual());

    // Write out edge attributes to show the kind of inheritance.
    if (Base->isVirtual()) {
      Out << " [ style=\"dashed\" ]";
    }
    Out << ";";
  }
}

/// WriteNodeReference - Write out a reference to the given node,
/// using a unique identifier for each direct base and for the
/// (only) virtual base.
std::ostream&
InheritanceHierarchyWriter::WriteNodeReference(QualType Type,
                                               bool FromVirtual) {
  QualType CanonType = Context.getCanonicalType(Type);

  Out << "Class_" << CanonType.getAsOpaquePtr();
  if (!FromVirtual)
    Out << "_" << DirectBaseCount[CanonType];
  return Out;
}
#endif

/// viewInheritance - Display the inheritance hierarchy of this C++
/// class using GraphViz.
void QualType::viewInheritance(ASTContext& Context) {
  if (!(*this)->getAsRecordType()) {
    cerr << "Type " << getAsString() << " is not a C++ class type.\n";
    return;
  }
#ifndef NDEBUG
  std::string ErrMsg;
  sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg);
  if (Filename.isEmpty()) {
    cerr << "Error: " << ErrMsg << "\n";
    return;
  }
  Filename.appendComponent(getAsString() + ".dot");
  if (Filename.makeUnique(true,&ErrMsg)) {
    cerr << "Error: " << ErrMsg << "\n";
    return;
  }

  cerr << "Writing '" << Filename << "'... ";

  std::ofstream O(Filename.c_str());

  if (O.good()) {
    InheritanceHierarchyWriter Writer(Context, O);
    Writer.WriteGraph(*this);
    cerr << " done. \n";

    O.close();

    // Display the graph
    DisplayGraph(Filename);
  } else {
    cerr << "error opening file for writing!\n";
    Filename.clear();
  }
#else
  cerr << "QualType::viewInheritance is only available in debug "
       << "builds on systems with Graphviz or gv!\n";
#endif
}

}
<|endoftext|>


<commit_before>//===-- Passes.cpp - Target independent code generation passes ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines interfaces to access the target independent code
// generation passes provided by the LLVM backend.
//
//===---------------------------------------------------------------------===//

#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/Passes.h"

using namespace llvm;

//===---------------------------------------------------------------------===//
///
/// RegisterRegAlloc class - Track the registration of register allocators.
///
//===---------------------------------------------------------------------===//
MachinePassRegistry RegisterRegAlloc::Registry;

static FunctionPass *createDefaultRegisterAllocator() { return 0; }
static RegisterRegAlloc
defaultRegAlloc("default",
                "pick register allocator based on -O option",
                createDefaultRegisterAllocator);

//===---------------------------------------------------------------------===//
///
/// RegAlloc command line options.
///
//===---------------------------------------------------------------------===//
static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
               RegisterPassParser<RegisterRegAlloc> >
RegAlloc("regalloc",
         cl::init(&createDefaultRegisterAllocator),
         cl::desc("Register allocator to use"));

//===---------------------------------------------------------------------===//
///
/// createRegisterAllocator - choose the appropriate register allocator.
///
//===---------------------------------------------------------------------===//
FunctionPass *llvm::createRegisterAllocator(CodeGenOpt::Level OptLevel) {
  RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();

  if (!Ctor) {
    Ctor = RegAlloc;
    RegisterRegAlloc::setDefault(RegAlloc);
  }

  // This forces linking of the greedy register allocator, so -regalloc=greedy
  // works in clang.
  if (Ctor == createGreedyRegisterAllocator)
    return createGreedyRegisterAllocator();

  if (Ctor != createDefaultRegisterAllocator)
    return Ctor();

  // When the 'default' allocator is requested, pick one based on OptLevel.
  switch (OptLevel) {
  case CodeGenOpt::None:
    return createFastRegisterAllocator();
  default:
    return createLinearScanRegisterAllocator();
  }
}
<commit_msg>Use a greedy algorithm for allocating registers.<commit_after>//===-- Passes.cpp - Target independent code generation passes ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines interfaces to access the target independent code
// generation passes provided by the LLVM backend.
//
//===---------------------------------------------------------------------===//

#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/Passes.h"

using namespace llvm;

//===---------------------------------------------------------------------===//
///
/// RegisterRegAlloc class - Track the registration of register allocators.
///
//===---------------------------------------------------------------------===//
MachinePassRegistry RegisterRegAlloc::Registry;

static FunctionPass *createDefaultRegisterAllocator() { return 0; }
static RegisterRegAlloc
defaultRegAlloc("default",
                "pick register allocator based on -O option",
                createDefaultRegisterAllocator);

//===---------------------------------------------------------------------===//
///
/// RegAlloc command line options.
///
//===---------------------------------------------------------------------===//
static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
               RegisterPassParser<RegisterRegAlloc> >
RegAlloc("regalloc",
         cl::init(&createDefaultRegisterAllocator),
         cl::desc("Register allocator to use"));

//===---------------------------------------------------------------------===//
///
/// createRegisterAllocator - choose the appropriate register allocator.
///
//===---------------------------------------------------------------------===//
FunctionPass *llvm::createRegisterAllocator(CodeGenOpt::Level OptLevel) {
  RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();

  if (!Ctor) {
    Ctor = RegAlloc;
    RegisterRegAlloc::setDefault(RegAlloc);
  }

  // This forces linking of the greedy register allocator, so -regalloc=greedy
  // works in clang.
  if (Ctor == createLinearScanRegisterAllocator)
    return createLinearScanRegisterAllocator();

  if (Ctor != createDefaultRegisterAllocator)
    return Ctor();

  // When the 'default' allocator is requested, pick one based on OptLevel.
  switch (OptLevel) {
  case CodeGenOpt::None:
    return createFastRegisterAllocator();
  default:
    return createGreedyRegisterAllocator();
  }
}
<|endoftext|>