<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ThreeDHelper.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef CHART2_THREEDHELPER_HXX
#define CHART2_THREEDHELPER_HXX

#include <com/sun/star/chart2/XDiagram.hpp>
#include <com/sun/star/drawing/CameraGeometry.hpp>
#include <com/sun/star/drawing/ShadeMode.hpp>

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/**
*/

enum ThreeDLookScheme
{
    ThreeDLookScheme_Simple,
    ThreeDLookScheme_Realistic,
    ThreeDLookScheme_Unknown
};

class ThreeDHelper
{
public:

    /** Returns the default camera geometry that is set in the Diagram CTOR.
        This is not the property default!

        @todo deprecate the hard set camera geometry and use the property
              default
     */
    static ::com::sun::star::drawing::CameraGeometry getDefaultCameraGeometry( bool bPie=false );

    static void getRotationAngleFromDiagram(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet >& xSceneProperties
            , double& rfXAngleRad, double& rfYAngleRad, double& rfZAngleRad );
    static void setRotationAngleToDiagram(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet >& xSceneProperties
            , double fXAngleRad, double fYAngleRad, double fZAngleRad );

    static void switchRightAngledAxes( const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet >& xSceneProperties
            , sal_Bool bRightAngledAxes, bool bRotateLights=true );

    static void adaptRadAnglesForRightAngledAxes( double& rfXAngleRad, double& rfYAngleRad );
    static double getXDegreeAngleLimitForRightAngledAxes();
    static double getYDegreeAngleLimitForRightAngledAxes();
    static double getValueClippedToRange( double fValue, const double& fPositivLimit );

    static double getCameraDistance(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet >& xSceneProperties );
    static void setCameraDistance(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet >& xSceneProperties
            , double fCameraDistance );
    static void ensureCameraDistanceRange( double& rfCameraDistance );
    static void getCameraDistanceRange( double& rfMinimumDistance, double& rfMaximumDistance );

    static ThreeDLookScheme detectScheme( const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram >& xDiagram );
    static void setScheme( const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram >& xDiagram
            , ThreeDLookScheme aScheme );

    //sal_Int32 nRoundedEdges:  <0 or >100 -> mixed state
    //sal_Int32 nObjectLines:  0->no lines; 1->all lines on; other->mixed state

    static void getRoundedEdgesAndObjectLines( const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram >& xDiagram
            , sal_Int32& rnRoundedEdges, sal_Int32& rnObjectLines );
    static void setRoundedEdgesAndObjectLines( const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram >& xDiagram
            , sal_Int32 nRoundedEdges, sal_Int32 nObjectLines );
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS xmlfilter04 (1.2.94); FILE MERGED 2008/03/14 15:40:02 iha 1.2.94.1: #i72994# simpler access to 3D settings<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ThreeDHelper.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef CHART2_THREEDHELPER_HXX
#define CHART2_THREEDHELPER_HXX

#include <com/sun/star/chart2/XDiagram.hpp>
#include <com/sun/star/drawing/CameraGeometry.hpp>
#include <com/sun/star/drawing/ShadeMode.hpp>

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/**
*/

enum ThreeDLookScheme
{
    ThreeDLookScheme_Simple,
    ThreeDLookScheme_Realistic,
    ThreeDLookScheme_Unknown
};

class ThreeDHelper
{
public:

    /** Returns the default camera geometry that is set in the Diagram CTOR.
        This is not the property default!

        @todo deprecate the hard set camera geometry and use the property
              default
     */
    static ::com::sun::star::drawing::CameraGeometry getDefaultCameraGeometry( bool bPie=false );

    static void getRotationAngleFromDiagram(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet >& xSceneProperties
            , double& rfXAngleRad, double& rfYAngleRad, double& rfZAngleRad );
    static void setRotationAngleToDiagram(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet >& xSceneProperties
            , double fXAngleRad, double fYAngleRad, double fZAngleRad );

    static void getRotationFromDiagram(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet >& xSceneProperties
            , sal_Int32& rnHorizontalAngleDegree, sal_Int32& rnVerticalAngleDegree );
    static void setRotationToDiagram(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet >& xSceneProperties
            , sal_Int32 nHorizontalAngleDegree, sal_Int32 nVerticalYAngleDegree );

    static void switchRightAngledAxes( const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet >& xSceneProperties
            , sal_Bool bRightAngledAxes, bool bRotateLights=true );

    static void adaptRadAnglesForRightAngledAxes( double& rfXAngleRad, double& rfYAngleRad );
    static double getXDegreeAngleLimitForRightAngledAxes();
    static double getYDegreeAngleLimitForRightAngledAxes();
    static double getValueClippedToRange( double fValue, const double& fPositivLimit );

    static double getCameraDistance(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet >& xSceneProperties );
    static void setCameraDistance(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::beans::XPropertySet >& xSceneProperties
            , double fCameraDistance );
    static void ensureCameraDistanceRange( double& rfCameraDistance );
    static void getCameraDistanceRange( double& rfMinimumDistance, double& rfMaximumDistance );

    static double CameraDistanceToPerspective( double fCameraDistance );
    static double PerspectiveToCameraDistance( double fPerspective );

    static ThreeDLookScheme detectScheme( const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram >& xDiagram );
    static void setScheme( const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram >& xDiagram
            , ThreeDLookScheme aScheme );

    //sal_Int32 nRoundedEdges:  <0 or >100 -> mixed state
    //sal_Int32 nObjectLines:  0->no lines; 1->all lines on; other->mixed state

    static void getRoundedEdgesAndObjectLines( const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram >& xDiagram
            , sal_Int32& rnRoundedEdges, sal_Int32& rnObjectLines );
    static void setRoundedEdgesAndObjectLines( const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram >& xDiagram
            , sal_Int32 nRoundedEdges, sal_Int32 nObjectLines );
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|>


<commit_before>#include <cstring>
#include "InputPacket.h"

using namespace ni;

bool InputPacket::isValid() const {
	return magic == MAGIC;
}

bool InputPacket::isSafe() const {
	return length <= DATA_LENGTH;
}<commit_msg>Add additional data length check to InputPacket.<commit_after>#include <cstring>
#include "InputPacket.h"

using namespace ni;

bool InputPacket::isValid() const {
	return magic == MAGIC;
}

bool InputPacket::isSafe() const {
	return length <= DATA_LENGTH && length >= 0;
}<|endoftext|>


<commit_before>/*
 *  Created on: Aug, 2015
 *      Author: Thomas Faeulhammer
 *
 */

#include <v4r/common/faat_3d_rec_framework_defines.h>
#include <v4r/common/miscellaneous.h>
#include <v4r/io/eigen.h>
#include <v4r/io/filesystem.h>
#include <v4r/recognition/model_only_source.h>
#include <pcl/console/parse.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/cloud_viewer.h>
#include <iostream>
#include <fstream>

int main (int argc, char ** argv)
{
    typedef pcl::PointXYZRGB PointT;
    typedef v4r::Model<PointT> ModelT;
    typedef boost::shared_ptr<ModelT> ModelTPtr;

    std::string path_s, path_p, path_m, model_name;
    pcl::console::parse_argument (argc, argv, "-scene_path", path_s);
    pcl::console::parse_argument (argc, argv, "-pose_file", path_p);
    pcl::console::parse_argument (argc, argv, "-model_path", path_m);
    pcl::console::parse_argument (argc, argv, "-model_name", model_name);

    std::cout << path_s << " " << path_p << " " << path_m << std::endl;

    boost::shared_ptr < v4r::ModelOnlySource<pcl::PointXYZRGBNormal, pcl::PointXYZRGB> > source;
    source.reset (new v4r::ModelOnlySource<pcl::PointXYZRGBNormal, pcl::PointXYZRGB>);
    source->setPath (path_m);
    source->setLoadViews (false);
    source->setLoadIntoMemory(false);
    source->generate ();
    source->createVoxelGridAndDistanceTransform (0.005f);

    pcl::visualization::PCLVisualizer vis;
    // Loading file and corresponding indices file (if it exists)
    pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>);
    pcl::io::loadPCDFile (path_s, *cloud);

    Eigen::Matrix4f transform = v4r::io::readMatrixFromFile(path_p);

//    std::vector < std::string > parts;
//    boost::split (parts, path_p, boost::is_any_of ("/"));
//    std::string filename = parts.back();
//    boost::replace_all(filename, ".txt", "");
//    boost::split (parts, filename, boost::is_any_of ("_"));
//    filename = filename.substr(0, filename.length() - parts.back().length());
//    const std::string model_name =  parts[1] +  parts[2];

    ModelTPtr model;
    bool found = source->getModelById (model_name, model);
    pcl::PointCloud<PointT>::ConstPtr model_cloud = model->getAssembled(0.003f);
    pcl::PointCloud<PointT>::Ptr model_cloud_transformed(new pcl::PointCloud<PointT>(*model_cloud));
    pcl::transformPointCloud(*model_cloud, *model_cloud_transformed, v4r::RotTrans2Mat4f(cloud->sensor_orientation_, cloud->sensor_origin_) * transform);

    vis.addPointCloud (cloud, "original_cloud");
    vis.addPointCloud (model_cloud_transformed, "model_cloud");
    vis.spin();
    return true;
}
<commit_msg>remove voxelgriddistancetransform method call<commit_after>/*
 *  Created on: Aug, 2015
 *      Author: Thomas Faeulhammer
 *
 */

#include <v4r/common/faat_3d_rec_framework_defines.h>
#include <v4r/common/miscellaneous.h>
#include <v4r/io/eigen.h>
#include <v4r/io/filesystem.h>
#include <v4r/recognition/model_only_source.h>
#include <pcl/console/parse.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/cloud_viewer.h>
#include <iostream>
#include <fstream>

int main (int argc, char ** argv)
{
    typedef pcl::PointXYZRGB PointT;
    typedef v4r::Model<PointT> ModelT;
    typedef boost::shared_ptr<ModelT> ModelTPtr;

    std::string path_s, path_p, path_m, model_name;
    pcl::console::parse_argument (argc, argv, "-scene_path", path_s);
    pcl::console::parse_argument (argc, argv, "-pose_file", path_p);
    pcl::console::parse_argument (argc, argv, "-model_path", path_m);
    pcl::console::parse_argument (argc, argv, "-model_name", model_name);

    std::cout << path_s << " " << path_p << " " << path_m << std::endl;

    boost::shared_ptr < v4r::ModelOnlySource<pcl::PointXYZRGBNormal, pcl::PointXYZRGB> > source;
    source.reset (new v4r::ModelOnlySource<pcl::PointXYZRGBNormal, pcl::PointXYZRGB>);
    source->setPath (path_m);
    source->setLoadViews (false);
    source->setLoadIntoMemory(false);
    source->generate ();
//    source->createVoxelGridAndDistanceTransform (0.005f);

    pcl::visualization::PCLVisualizer vis;
    // Loading file and corresponding indices file (if it exists)
    pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>);
    pcl::io::loadPCDFile (path_s, *cloud);

    Eigen::Matrix4f transform = v4r::io::readMatrixFromFile(path_p);

//    std::vector < std::string > parts;
//    boost::split (parts, path_p, boost::is_any_of ("/"));
//    std::string filename = parts.back();
//    boost::replace_all(filename, ".txt", "");
//    boost::split (parts, filename, boost::is_any_of ("_"));
//    filename = filename.substr(0, filename.length() - parts.back().length());
//    const std::string model_name =  parts[1] +  parts[2];

    ModelTPtr model;
    bool found = source->getModelById (model_name, model);
    pcl::PointCloud<PointT>::ConstPtr model_cloud = model->getAssembled(0.003f);
    pcl::PointCloud<PointT>::Ptr model_cloud_transformed(new pcl::PointCloud<PointT>(*model_cloud));
    pcl::transformPointCloud(*model_cloud, *model_cloud_transformed, v4r::RotTrans2Mat4f(cloud->sensor_orientation_, cloud->sensor_origin_) * transform);

    vis.addPointCloud (cloud, "original_cloud");
    vis.addPointCloud (model_cloud_transformed, "model_cloud");
    vis.spin();
    return true;
}
<|endoftext|>


<commit_before><commit_msg>Updated `yli::common::Datatype`.<commit_after><|endoftext|>


<commit_before>// mmlaunch.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "mmlaunch.h"
#include <process.h>

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	_execl("C:\\Progra~1\\Java\\jre6\\bin\\javaw","C:\\Progra~1\\Java\\jre6\\bin\\javaw", "-Xmx1000M -cp ij.jar ij.ImageJ", NULL);
 	//system("javaw -cp ij.jar ij.ImageJ");

	return 0;
}

<commit_msg>use -XX:SoftRefLRUPolicyMSPerMB=1000000000000000<commit_after>// mmlaunch.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "mmlaunch.h"
#include <process.h>

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

	_execl("C:\\Progra~1\\Java\\jre6\\bin\\javaw","C:\\Progra~1\\Java\\jre6\\bin\\javaw", "-Xmx1200M -XX:SoftRefLRUPolicyMSPerMB=1000000000000000 -cp ij.jar ij.ImageJ", NULL);
 	//system("javaw -cp -Xms1200M -Xmx1200M -XX:SoftRefLRUPolicyMSPerMB=1000000000000000 ij.jar ij.ImageJ");

	return 0;
}

<|endoftext|>


<commit_before>/*
 * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
 *
 * 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.
 *
 */

#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE nblist_3body_test
#include <boost/test/unit_test.hpp>

#include <string>
#include <vector>
#include <votca/csg/bead.h>
#include <votca/csg/beadlist.h>
#include <votca/csg/beadtype.h>
#include <votca/csg/nblist_3body.h>
#include <votca/csg/topology.h>

using namespace std;
using namespace votca::csg;

BOOST_AUTO_TEST_SUITE(nblist_3body_test)

BOOST_AUTO_TEST_CASE(test_nblist_3body_constructor) { NBList_3Body nb; }

BOOST_AUTO_TEST_CASE(test_nblist_3body_generate_list) {
  NBList_3Body *nb;
  nb = new NBList_3Body();

  nb->setCutoff(2.0);

  Topology top;

  Eigen::Matrix3d m = 5 * Eigen::Matrix3d::Identity();

  top.setBox(m);

  Eigen::Vector3d pos = Eigen::Vector3d::Zero();

  Molecule *mol;
  mol = top.CreateMolecule("UNKNOWN");

  string bead_type_name = "CG";
  top.RegisterBeadType(bead_type_name);

  string name = "dummy1";
  votca::Index resnr = 0;
  double mass = 1.0;
  double charge = -1.0;
  Bead *b;
  b = top.CreateBead(Bead::spherical, name, bead_type_name, resnr, mass,
                     charge);
  b->setPos(pos);
  mol->AddBead(b, bead_type_name);

  name = "dummy2";
  resnr = 0;
  mass = 2.0;
  charge = -2.0;
  b = top.CreateBead(Bead::spherical, name, bead_type_name, resnr, mass,
                     charge);
  mol->AddBead(b, bead_type_name);
  pos = Eigen::Vector3d::UnitX();
  b->setPos(pos);

  name = "dummy3";
  resnr = 0;
  mass = 3.0;
  charge = -3.0;
  b = top.CreateBead(Bead::spherical, name, bead_type_name, resnr, mass,
                     charge);
  mol->AddBead(b, bead_type_name);
  pos[0] = 1.0;
  pos[1] = 1.0;
  pos[2] = 0.0;
  b->setPos(pos);

  BeadList beads;
  beads.Generate(top, "CG");

  nb->Generate(beads, true);

  BOOST_CHECK_EQUAL(nb->size(), 3);

  NBList_3Body::iterator triple_iter;
  triple_iter = nb->begin();
  BOOST_CHECK_EQUAL((*triple_iter)->bead1()->getId(), 0);
  BOOST_CHECK_EQUAL((*triple_iter)->bead2()->getId(), 1);
  BOOST_CHECK_EQUAL((*triple_iter)->bead3()->getId(), 2);
  BOOST_CHECK_CLOSE((*triple_iter)->dist12(), 1.0, 1e-4);
  BOOST_CHECK_CLOSE((*triple_iter)->dist13(), 1.414214, 1e-4);
  BOOST_CHECK_CLOSE((*triple_iter)->dist23(), 1.0, 1e-4);

  ++triple_iter;

  BOOST_CHECK_EQUAL((*triple_iter)->bead1()->getId(), 1);
  BOOST_CHECK_EQUAL((*triple_iter)->bead2()->getId(), 0);
  BOOST_CHECK_EQUAL((*triple_iter)->bead3()->getId(), 2);
  BOOST_CHECK_CLOSE((*triple_iter)->dist12(), 1.0, 1e-4);
  BOOST_CHECK_CLOSE((*triple_iter)->dist13(), 1.0, 1e-4);
  BOOST_CHECK_CLOSE((*triple_iter)->dist23(), 1.414214, 1e-4);

  ++triple_iter;

  BOOST_CHECK_EQUAL((*triple_iter)->bead1()->getId(), 2);
  BOOST_CHECK_EQUAL((*triple_iter)->bead2()->getId(), 0);
  BOOST_CHECK_EQUAL((*triple_iter)->bead3()->getId(), 1);
  BOOST_CHECK_CLOSE((*triple_iter)->dist12(), 1.414214, 1e-4);
  BOOST_CHECK_CLOSE((*triple_iter)->dist13(), 1.0, 1e-4);
  BOOST_CHECK_CLOSE((*triple_iter)->dist23(), 1.0, 1e-4);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Removed beadtype from test_nblist_3body<commit_after>/*
 * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
 *
 * 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.
 *
 */

#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE nblist_3body_test
#include <boost/test/unit_test.hpp>

#include <string>
#include <vector>
#include <votca/csg/bead.h>
#include <votca/csg/beadlist.h>
#include <votca/csg/nblist_3body.h>
#include <votca/csg/topology.h>

using namespace std;
using namespace votca::csg;

BOOST_AUTO_TEST_SUITE(nblist_3body_test)

BOOST_AUTO_TEST_CASE(test_nblist_3body_constructor) { NBList_3Body nb; }

BOOST_AUTO_TEST_CASE(test_nblist_3body_generate_list) {
  NBList_3Body *nb;
  nb = new NBList_3Body();

  nb->setCutoff(2.0);

  Topology top;

  Eigen::Matrix3d m = 5 * Eigen::Matrix3d::Identity();

  top.setBox(m);

  Eigen::Vector3d pos = Eigen::Vector3d::Zero();

  Molecule *mol;
  mol = top.CreateMolecule("UNKNOWN");

  string bead_type_name = "CG";
  top.RegisterBeadType(bead_type_name);

  string name = "dummy1";
  votca::Index resnr = 0;
  double mass = 1.0;
  double charge = -1.0;
  Bead *b;
  b = top.CreateBead(Bead::spherical, name, bead_type_name, resnr, mass,
                     charge);
  b->setPos(pos);
  mol->AddBead(b, bead_type_name);

  name = "dummy2";
  resnr = 0;
  mass = 2.0;
  charge = -2.0;
  b = top.CreateBead(Bead::spherical, name, bead_type_name, resnr, mass,
                     charge);
  mol->AddBead(b, bead_type_name);
  pos = Eigen::Vector3d::UnitX();
  b->setPos(pos);

  name = "dummy3";
  resnr = 0;
  mass = 3.0;
  charge = -3.0;
  b = top.CreateBead(Bead::spherical, name, bead_type_name, resnr, mass,
                     charge);
  mol->AddBead(b, bead_type_name);
  pos[0] = 1.0;
  pos[1] = 1.0;
  pos[2] = 0.0;
  b->setPos(pos);

  BeadList beads;
  beads.Generate(top, "CG");

  nb->Generate(beads, true);

  BOOST_CHECK_EQUAL(nb->size(), 3);

  NBList_3Body::iterator triple_iter;
  triple_iter = nb->begin();
  BOOST_CHECK_EQUAL((*triple_iter)->bead1()->getId(), 0);
  BOOST_CHECK_EQUAL((*triple_iter)->bead2()->getId(), 1);
  BOOST_CHECK_EQUAL((*triple_iter)->bead3()->getId(), 2);
  BOOST_CHECK_CLOSE((*triple_iter)->dist12(), 1.0, 1e-4);
  BOOST_CHECK_CLOSE((*triple_iter)->dist13(), 1.414214, 1e-4);
  BOOST_CHECK_CLOSE((*triple_iter)->dist23(), 1.0, 1e-4);

  ++triple_iter;

  BOOST_CHECK_EQUAL((*triple_iter)->bead1()->getId(), 1);
  BOOST_CHECK_EQUAL((*triple_iter)->bead2()->getId(), 0);
  BOOST_CHECK_EQUAL((*triple_iter)->bead3()->getId(), 2);
  BOOST_CHECK_CLOSE((*triple_iter)->dist12(), 1.0, 1e-4);
  BOOST_CHECK_CLOSE((*triple_iter)->dist13(), 1.0, 1e-4);
  BOOST_CHECK_CLOSE((*triple_iter)->dist23(), 1.414214, 1e-4);

  ++triple_iter;

  BOOST_CHECK_EQUAL((*triple_iter)->bead1()->getId(), 2);
  BOOST_CHECK_EQUAL((*triple_iter)->bead2()->getId(), 0);
  BOOST_CHECK_EQUAL((*triple_iter)->bead3()->getId(), 1);
  BOOST_CHECK_CLOSE((*triple_iter)->dist12(), 1.414214, 1e-4);
  BOOST_CHECK_CLOSE((*triple_iter)->dist13(), 1.0, 1e-4);
  BOOST_CHECK_CLOSE((*triple_iter)->dist23(), 1.0, 1e-4);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before><commit_msg>gui: generates new addres instead of popping from receiving address list<commit_after><|endoftext|>


<commit_before>#include "dcpbutton2.h"
#include <DuiLabel>
#include <QGraphicsGridLayout>

#define DISABLE_BACKGROUND 1

// main constructor
DcpButton2::DcpButton2(DuiWidget* parent)
    : DuiButton(parent), m_TextLayout(0), m_Label1(0), m_Label2(0),
      m_Triangle(0)
{
    setObjectName("DcpButton");
    this->setLayout(createLayout());
}

// protected constructor which avoids creating the layout
DcpButton2::DcpButton2(DuiWidget* parent, bool)
    : DuiButton(parent), m_TextLayout(0), m_Label1(0), m_Label2(0),
      m_Triangle(0)
{
    setObjectName("DcpButton");
}

QGraphicsLayout* DcpButton2::createLayout()
{
    // triangle
    m_Triangle = new DuiButton(this);
    m_Triangle->setObjectName("DcpSeeMoreIndicator");
    m_Triangle->setAcceptedMouseButtons(0);

    // create the labels:
    m_Label1 = new DuiLabel (this);
    m_Label1->setAcceptedMouseButtons(0);
//    m_Label1->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    m_Label2 = new DuiLabel();
    m_Label2->setAcceptedMouseButtons(0);
    m_Label2->setObjectName("DcpButtonLine2");
//    m_Label2->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    // create the layout:
    m_TextLayout = new QGraphicsGridLayout();
    m_TextLayout->setContentsMargins(0,0,0,0);
    m_TextLayout->addItem(m_Triangle,0,0, Qt::AlignCenter);
    m_TextLayout->addItem(m_Label1,0,1);
    m_TextLayout->addItem(m_Label2,1,1);

    updateLabelSizes();
    return m_TextLayout;
}

void DcpButton2::setText1(const QString& text)
{
    m_Label1->setText(text);
}

void DcpButton2::setText2(const QString& text)
{
    if (text == m_Label2->text()) return;
    m_Label2->setText(text);
    updateLabelSizes();
}

void DcpButton2::updateLabelSizes()
{
    if (m_Label2->text().isEmpty()) {
        m_Label1->setObjectName("DcpButtonMain");
        if (textLayout()->count() > 2) {
            textLayout()->removeAt(2);
        }
        m_Label2->hide();
    } else {
        m_Label1->setObjectName("DcpButtonLine1");
        if (textLayout()->count() <= 2) {
            textLayout()->addItem(m_Label2, 1,1);
        }
        m_Label2->show();
    }
}

// convenience function
void DcpButton2::setText(const QString& text1, const QString& text2)
{
    setText1(text1);
    setText2(text2);
}

QGraphicsGridLayout* DcpButton2::textLayout()
{
    return m_TextLayout;
}

#if DISABLE_BACKGROUND
    void DcpButton2::paintWindowFrame (QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {}
    void DcpButton2::paint (QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {}
#else // DISABLE_BACKGROUND
    void DcpButton2::paintWindowFrame (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
        DuiButton::paintWindowFrame(painter, option, widget);
    }
    void DcpButton2::paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
        DuiButton::paint(painter, option, widget);
    }
#endif // DISABLE_BACKGROUND

<commit_msg>Adds objectname for dcpbutton2 line 1<commit_after>#include "dcpbutton2.h"
#include <DuiLabel>
#include <QGraphicsGridLayout>

#define DISABLE_BACKGROUND 1

// main constructor
DcpButton2::DcpButton2(DuiWidget* parent)
    : DuiButton(parent), m_TextLayout(0), m_Label1(0), m_Label2(0),
      m_Triangle(0)
{
    setObjectName("DcpButton");
    this->setLayout(createLayout());
}

// protected constructor which avoids creating the layout
DcpButton2::DcpButton2(DuiWidget* parent, bool)
    : DuiButton(parent), m_TextLayout(0), m_Label1(0), m_Label2(0),
      m_Triangle(0)
{
    setObjectName("DcpButton");
}

QGraphicsLayout* DcpButton2::createLayout()
{
    // triangle
    m_Triangle = new DuiButton(this);
    m_Triangle->setObjectName("DcpSeeMoreIndicator");
    m_Triangle->setAcceptedMouseButtons(0);

    // create the labels:
    m_Label1 = new DuiLabel (this);
    m_Label1->setAcceptedMouseButtons(0);
    m_Label2->setObjectName("DcpButtonLine1");
//    m_Label1->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    m_Label2 = new DuiLabel();
    m_Label2->setAcceptedMouseButtons(0);
    m_Label2->setObjectName("DcpButtonLine2");
//    m_Label2->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    // create the layout:
    m_TextLayout = new QGraphicsGridLayout();
    m_TextLayout->setContentsMargins(0,0,0,0);
    m_TextLayout->addItem(m_Triangle,0,0, Qt::AlignCenter);
    m_TextLayout->addItem(m_Label1,0,1);
    m_TextLayout->addItem(m_Label2,1,1);

    updateLabelSizes();
    return m_TextLayout;
}

void DcpButton2::setText1(const QString& text)
{
    m_Label1->setText(text);
}

void DcpButton2::setText2(const QString& text)
{
    if (text == m_Label2->text()) return;
    m_Label2->setText(text);
    updateLabelSizes();
}

void DcpButton2::updateLabelSizes()
{
    if (m_Label2->text().isEmpty()) {
        m_Label1->setObjectName("DcpButtonMain");
        if (textLayout()->count() > 2) {
            textLayout()->removeAt(2);
        }
        m_Label2->hide();
    } else {
        m_Label1->setObjectName("DcpButtonLine1");
        if (textLayout()->count() <= 2) {
            textLayout()->addItem(m_Label2, 1,1);
        }
        m_Label2->show();
    }
}

// convenience function
void DcpButton2::setText(const QString& text1, const QString& text2)
{
    setText1(text1);
    setText2(text2);
}

QGraphicsGridLayout* DcpButton2::textLayout()
{
    return m_TextLayout;
}

#if DISABLE_BACKGROUND
    void DcpButton2::paintWindowFrame (QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {}
    void DcpButton2::paint (QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {}
#else // DISABLE_BACKGROUND
    void DcpButton2::paintWindowFrame (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
        DuiButton::paintWindowFrame(painter, option, widget);
    }
    void DcpButton2::paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
        DuiButton::paint(painter, option, widget);
    }
#endif // DISABLE_BACKGROUND

<|endoftext|>


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

#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SFX_INTERNO_HXX //autogen
#include <sfx2/interno.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef SW_SWDLL_HXX
#include <swdll.hxx>
#endif
#ifndef _SHELLID_HXX
#include <shellid.hxx>
#endif

class   SwDoc;
class   Sw3Io;
class   SfxDocumentInfoDialog;
class   SfxStyleSheetBasePool;
class   FontList;
class   SwView;
class   SwWrtShell;
class   SwFEShell;
class   Reader;
class   SwReader;
class   SwCrsrShell;
class   SwSrcView;
class   PushButton;
class   FixedText;
class   SwPaM;
class   SwgReaderOption;

class SwDocShell: public SfxObjectShell, public SfxInPlaceObject,
                  public SfxListener
{
    SwDoc*                  pDoc;           // Document
    Sw3Io*                  pIo;            // Reader / Writer
    SfxStyleSheetBasePool*  pBasePool;      // Durchreiche fuer Formate
    FontList*               pFontList;      // aktuelle FontListe

    // Nix geht ohne die WrtShell (historische Gruende)
    // RuekwaertsPointer auf die View (historische Gruende)
    // Dieser gilt solange bis im Activate ein neuer gesetzt wird
    // oder dieser im Dtor der View geloescht wird
    //
    SwView*                 pView;
    SwWrtShell*             pWrtShell;

    Timer                   aFinishedTimer; // Timer fuers ueberpriefen der
                                            // Grafik-Links. Sind alle da,
                                            // dann ist Doc voll. geladen

    SvPersistRef            xOLEChildList;  // fuers RemoveOLEObjects
    sal_Int16               nUpdateDocMode; // contains the com::sun::star::document::UpdateDocMode
    bool                    bInUpdateFontList; //prevent nested calls of UpdateFontList
    // Methoden fuer den Zugriff aufs Doc
    void                    AddLink();
    void                    RemoveLink();

    // Hint abfangen fuer DocInfo
    virtual void            Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    // FileIO
    virtual BOOL            InitNew(SvStorage* pNewStor);
    virtual BOOL            Load(SvStorage* pStor);
    virtual BOOL            LoadFrom(SvStorage* pStor);
    virtual BOOL            ConvertFrom( SfxMedium &rMedium );
    virtual void            HandsOff();
    virtual BOOL            SaveAs(SvStorage * pNewStor );
    virtual BOOL            ConvertTo(SfxMedium &rMedium );
    virtual BOOL            SaveCompleted(SvStorage * pNewStor );
    virtual USHORT          PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE );

    // DocInfo dem Doc melden
    //
    virtual SfxDocumentInfoDialog* CreateDocumentInfoDialog(
                                    Window *pParent, const SfxItemSet &);
    // OLE-Geraffel
    virtual void            Draw( OutputDevice*, const JobSetup&, USHORT);

    // Methoden fuer StyleSheets
    USHORT                  Edit( const String &rName, const String& rParent, USHORT nFamily,
                                    USHORT nMask, BOOL bNew,
                                    BOOL bColumn = FALSE,
                                    SwWrtShell* pActShell = 0,
                                    BOOL bBasic = FALSE );
    USHORT                  Delete(const String &rName, USHORT nFamily);
    USHORT                  ApplyStyles(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0,
                                        USHORT nMode = 0 );
    USHORT                  DoWaterCan( const String &rName, USHORT nFamily);
    USHORT                  UpdateStyle(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0);
    USHORT                  MakeByExample(const String &rName,
                                            USHORT nFamily, USHORT nMask, SwWrtShell* pShell = 0);

    void                    InitDraw();
    void                    SubInitNew();   // fuer InitNew und HtmlSourceModus
    inline void             SetWrtShell(SwWrtShell* pShell)
                                { pWrtShell = pShell; }

    void                    RemoveOLEObjects();
    void                    CalcLayoutForOLEObjects();

    void                    Init_Impl();
    DECL_STATIC_LINK( SwDocShell, IsLoadFinished, void* );

public:

    // aber selbst implementieren
    SFX_DECL_INTERFACE(SW_DOCSHELL);
    SFX_DECL_OBJECTFACTORY(SwDocShell);
    TYPEINFO();

    static SfxInterface *_GetInterface() { return _GetInterfaceImpl(); }

    //Das Doc wird fuer SO-Datenaustausch benoetigt!
    SwDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    SwDocShell( SwDoc *pDoc, SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD );
    ~SwDocShell();

    // OLE 2.0-Benachrichtigung
    DECL_LINK( Ole2ModifiedHdl, void * );

    // OLE-Geraffel
    virtual void      SetVisArea( const Rectangle &rRect );
    virtual Rectangle GetVisArea( USHORT nAspect ) const;
    virtual Printer  *GetDocumentPrinter();
    virtual OutputDevice* GetDocumentRefDev();
    virtual void      OnDocumentPrinterChanged( Printer * pNewPrinter );
    virtual ULONG     GetMiscStatus() const;

    virtual void            PrepareReload();
    virtual void            SetModified( BOOL = TRUE );

    // Dispatcher
    void                    Execute(SfxRequest &);
    void                    ExecStyleSheet(SfxRequest&);
    void                    ExecDB(SfxRequest&);

    void                    GetState(SfxItemSet &);
    void                    StateAlways(SfxItemSet &);
    void                    StateStyleSheet(SfxItemSet&, SwWrtShell* pSh = 0 );

    // Doc rausreichen aber VORSICHT
    inline SwDoc*           GetDoc() { return pDoc; }
    void                    UpdateFontList();
    void                    UpdateChildWindows();

    // DocumentInfo neu setzen
    BOOL                    SetDocumentInfo(const SfxDocumentInfo& rInfo);

    // globaler IO
    virtual BOOL            Save();
    inline BOOL                 SaveAsChilds( SvStorage *pStor );
    inline BOOL                 SaveCompletedChilds( SvStorage *pStor );

    // fuer VorlagenPI
    virtual SfxStyleSheetBasePool*  GetStyleSheetPool();

    // Fuer Organizer
    virtual BOOL Insert(SfxObjectShell &rSource,
                        USHORT  nSourceIdx1,
                        USHORT  nSourceIdx2,
                        USHORT  nSourceIdx3,
                        USHORT& nIdx1,
                        USHORT& nIdx2,
                        USHORT& nIdx3,
                        USHORT& nRemovedIdx);

    virtual BOOL Remove(USHORT nIdx1,
                        USHORT nIdx2 = INDEX_IGNORE,
                        USHORT nIdx3 = INDEX_IGNORE);

    virtual Bitmap      GetStyleFamilyBitmap( SfxStyleFamily eFamily, BmpColorMode eColorMode );

    // View setzen fuer Aktionen ueber Shell
    void          SetView(SwView* pVw);
    const SwView *GetView() const { return pView; }
    SwView       *GetView()       { return pView; }

    // Zugriff auf die zur SwView gehoerige SwWrtShell
          SwWrtShell *GetWrtShell()       { return pWrtShell; }
    const SwWrtShell *GetWrtShell() const { return pWrtShell; }

    // fuer die Core - die kennt die DocShell aber keine WrtShell!
          SwFEShell *GetFEShell();
    const SwFEShell *GetFEShell() const
                { return ((SwDocShell*)this)->GetFEShell(); }

    // Fuer Einfuegen Dokument
    Reader* StartConvertFrom(SfxMedium& rMedium, SwReader** ppRdr,
                            SwCrsrShell* pCrsrSh = 0, SwPaM* pPaM = 0);

    // Anforderung der pIo-Struktur fuer den Zugriff auf Substorages
    // und Streams
    Sw3Io* GetIoSystem() { return pIo; }

    virtual long DdeGetData( const String& rItem, const String& rMimeType,
                             ::com::sun::star::uno::Any & rValue );
    virtual long DdeSetData( const String& rItem, const String& rMimeType,
                                const ::com::sun::star::uno::Any & rValue );
    virtual ::so3::SvLinkSource* DdeCreateLinkSource( const String& rItem );
    virtual void FillClass( SvGlobalName * pClassName,
                                   ULONG * pClipFormat,
                                   String * pAppName,
                                   String * pLongUserName,
                                   String * pUserName,
                                   long nVersion = SOFFICE_FILEFORMAT_CURRENT ) const;

    virtual void LoadStyles( SfxObjectShell& rSource );

    void _LoadStyles( SfxObjectShell& rSource, BOOL bPreserveCurrentDocument );

    // Seitenvorlagedialog anzeigen, ggf. auf Spaltenpage
    void FormatPage( const String& rPage,
                        BOOL bColumn = FALSE,
                        SwWrtShell*     pActShell = 0 );

    // Timer starten fuers ueberpruefen der Grafik-Links. Sind alle
    // vollstaendig geladen, dann ist das Doc fertig
    void StartLoadFinishedTimer();

    // eine Uebertragung wird abgebrochen (wird aus dem SFX gerufen)
    virtual void CancelTransfers();

    // Doc aus Html-Source neu laden
    void    ReloadFromHtml( const String& rStreamName, SwSrcView* pSrcView );

    // embedded alle lokalen Links (Bereiche/Grafiken)
    BOOL EmbedAllLinks();
    sal_Int16   GetUpdateDocMode() const {return nUpdateDocMode;}

    //Activate wait cursor for all windows of this document
    //Optionally all dispatcher could be Locked
    //Usually locking should be done using the class: SwWaitObject!
    void EnterWait( BOOL bLockDispatcher );
    void LeaveWait( BOOL bLockDispatcher );

    void ToggleBrowserMode(BOOL bOn, SwView* pView = 0);

    ULONG LoadStylesFromFile( const String& rURL, SwgReaderOption& rOpt,
                                BOOL bUnoCall );
    void InvalidateModel();
    void ReactivateModel();

#if SUPD>620
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >  GetEventNames();
#endif
};

inline BOOL SwDocShell::SaveAsChilds( SvStorage *pStor )
{
    return SfxInPlaceObject::SaveAsChilds( pStor );
}

inline BOOL SwDocShell::SaveCompletedChilds( SvStorage *pStor )
{
    return SfxInPlaceObject::SaveCompletedChilds( pStor );
}
#endif
<commit_msg>INTEGRATION: CWS tune05 (1.24.140); FILE MERGED 2004/07/22 09:39:05 cmc 1.24.140.1: #i30554# unused SwDocShell::EmbedAllLinks<commit_after>/*************************************************************************
 *
 *  $RCSfile: docsh.hxx,v $
 *
 *  $Revision: 1.25 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 12:01:18 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SWDOCSH_HXX
#define _SWDOCSH_HXX

#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SFX_INTERNO_HXX //autogen
#include <sfx2/interno.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef SW_SWDLL_HXX
#include <swdll.hxx>
#endif
#ifndef _SHELLID_HXX
#include <shellid.hxx>
#endif

class   SwDoc;
class   Sw3Io;
class   SfxDocumentInfoDialog;
class   SfxStyleSheetBasePool;
class   FontList;
class   SwView;
class   SwWrtShell;
class   SwFEShell;
class   Reader;
class   SwReader;
class   SwCrsrShell;
class   SwSrcView;
class   PushButton;
class   FixedText;
class   SwPaM;
class   SwgReaderOption;

class SwDocShell: public SfxObjectShell, public SfxInPlaceObject,
                  public SfxListener
{
    SwDoc*                  pDoc;           // Document
    Sw3Io*                  pIo;            // Reader / Writer
    SfxStyleSheetBasePool*  pBasePool;      // Durchreiche fuer Formate
    FontList*               pFontList;      // aktuelle FontListe

    // Nix geht ohne die WrtShell (historische Gruende)
    // RuekwaertsPointer auf die View (historische Gruende)
    // Dieser gilt solange bis im Activate ein neuer gesetzt wird
    // oder dieser im Dtor der View geloescht wird
    //
    SwView*                 pView;
    SwWrtShell*             pWrtShell;

    Timer                   aFinishedTimer; // Timer fuers ueberpriefen der
                                            // Grafik-Links. Sind alle da,
                                            // dann ist Doc voll. geladen

    SvPersistRef            xOLEChildList;  // fuers RemoveOLEObjects
    sal_Int16               nUpdateDocMode; // contains the com::sun::star::document::UpdateDocMode
    bool                    bInUpdateFontList; //prevent nested calls of UpdateFontList
    // Methoden fuer den Zugriff aufs Doc
    void                    AddLink();
    void                    RemoveLink();

    // Hint abfangen fuer DocInfo
    virtual void            Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    // FileIO
    virtual BOOL            InitNew(SvStorage* pNewStor);
    virtual BOOL            Load(SvStorage* pStor);
    virtual BOOL            LoadFrom(SvStorage* pStor);
    virtual BOOL            ConvertFrom( SfxMedium &rMedium );
    virtual void            HandsOff();
    virtual BOOL            SaveAs(SvStorage * pNewStor );
    virtual BOOL            ConvertTo(SfxMedium &rMedium );
    virtual BOOL            SaveCompleted(SvStorage * pNewStor );
    virtual USHORT          PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE );

    // DocInfo dem Doc melden
    //
    virtual SfxDocumentInfoDialog* CreateDocumentInfoDialog(
                                    Window *pParent, const SfxItemSet &);
    // OLE-Geraffel
    virtual void            Draw( OutputDevice*, const JobSetup&, USHORT);

    // Methoden fuer StyleSheets
    USHORT                  Edit( const String &rName, const String& rParent, USHORT nFamily,
                                    USHORT nMask, BOOL bNew,
                                    BOOL bColumn = FALSE,
                                    SwWrtShell* pActShell = 0,
                                    BOOL bBasic = FALSE );
    USHORT                  Delete(const String &rName, USHORT nFamily);
    USHORT                  ApplyStyles(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0,
                                        USHORT nMode = 0 );
    USHORT                  DoWaterCan( const String &rName, USHORT nFamily);
    USHORT                  UpdateStyle(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0);
    USHORT                  MakeByExample(const String &rName,
                                            USHORT nFamily, USHORT nMask, SwWrtShell* pShell = 0);

    void                    InitDraw();
    void                    SubInitNew();   // fuer InitNew und HtmlSourceModus
    inline void             SetWrtShell(SwWrtShell* pShell)
                                { pWrtShell = pShell; }

    void                    RemoveOLEObjects();
    void                    CalcLayoutForOLEObjects();

    void                    Init_Impl();
    DECL_STATIC_LINK( SwDocShell, IsLoadFinished, void* );

public:

    // aber selbst implementieren
    SFX_DECL_INTERFACE(SW_DOCSHELL);
    SFX_DECL_OBJECTFACTORY(SwDocShell);
    TYPEINFO();

    static SfxInterface *_GetInterface() { return _GetInterfaceImpl(); }

    //Das Doc wird fuer SO-Datenaustausch benoetigt!
    SwDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    SwDocShell( SwDoc *pDoc, SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD );
    ~SwDocShell();

    // OLE 2.0-Benachrichtigung
    DECL_LINK( Ole2ModifiedHdl, void * );

    // OLE-Geraffel
    virtual void      SetVisArea( const Rectangle &rRect );
    virtual Rectangle GetVisArea( USHORT nAspect ) const;
    virtual Printer  *GetDocumentPrinter();
    virtual OutputDevice* GetDocumentRefDev();
    virtual void      OnDocumentPrinterChanged( Printer * pNewPrinter );
    virtual ULONG     GetMiscStatus() const;

    virtual void            PrepareReload();
    virtual void            SetModified( BOOL = TRUE );

    // Dispatcher
    void                    Execute(SfxRequest &);
    void                    ExecStyleSheet(SfxRequest&);
    void                    ExecDB(SfxRequest&);

    void                    GetState(SfxItemSet &);
    void                    StateAlways(SfxItemSet &);
    void                    StateStyleSheet(SfxItemSet&, SwWrtShell* pSh = 0 );

    // Doc rausreichen aber VORSICHT
    inline SwDoc*           GetDoc() { return pDoc; }
    void                    UpdateFontList();
    void                    UpdateChildWindows();

    // DocumentInfo neu setzen
    BOOL                    SetDocumentInfo(const SfxDocumentInfo& rInfo);

    // globaler IO
    virtual BOOL            Save();
    inline BOOL                 SaveAsChilds( SvStorage *pStor );
    inline BOOL                 SaveCompletedChilds( SvStorage *pStor );

    // fuer VorlagenPI
    virtual SfxStyleSheetBasePool*  GetStyleSheetPool();

    // Fuer Organizer
    virtual BOOL Insert(SfxObjectShell &rSource,
                        USHORT  nSourceIdx1,
                        USHORT  nSourceIdx2,
                        USHORT  nSourceIdx3,
                        USHORT& nIdx1,
                        USHORT& nIdx2,
                        USHORT& nIdx3,
                        USHORT& nRemovedIdx);

    virtual BOOL Remove(USHORT nIdx1,
                        USHORT nIdx2 = INDEX_IGNORE,
                        USHORT nIdx3 = INDEX_IGNORE);

    virtual Bitmap      GetStyleFamilyBitmap( SfxStyleFamily eFamily, BmpColorMode eColorMode );

    // View setzen fuer Aktionen ueber Shell
    void          SetView(SwView* pVw);
    const SwView *GetView() const { return pView; }
    SwView       *GetView()       { return pView; }

    // Zugriff auf die zur SwView gehoerige SwWrtShell
          SwWrtShell *GetWrtShell()       { return pWrtShell; }
    const SwWrtShell *GetWrtShell() const { return pWrtShell; }

    // fuer die Core - die kennt die DocShell aber keine WrtShell!
          SwFEShell *GetFEShell();
    const SwFEShell *GetFEShell() const
                { return ((SwDocShell*)this)->GetFEShell(); }

    // Fuer Einfuegen Dokument
    Reader* StartConvertFrom(SfxMedium& rMedium, SwReader** ppRdr,
                            SwCrsrShell* pCrsrSh = 0, SwPaM* pPaM = 0);

    // Anforderung der pIo-Struktur fuer den Zugriff auf Substorages
    // und Streams
    Sw3Io* GetIoSystem() { return pIo; }

    virtual long DdeGetData( const String& rItem, const String& rMimeType,
                             ::com::sun::star::uno::Any & rValue );
    virtual long DdeSetData( const String& rItem, const String& rMimeType,
                                const ::com::sun::star::uno::Any & rValue );
    virtual ::so3::SvLinkSource* DdeCreateLinkSource( const String& rItem );
    virtual void FillClass( SvGlobalName * pClassName,
                                   ULONG * pClipFormat,
                                   String * pAppName,
                                   String * pLongUserName,
                                   String * pUserName,
                                   long nVersion = SOFFICE_FILEFORMAT_CURRENT ) const;

    virtual void LoadStyles( SfxObjectShell& rSource );

    void _LoadStyles( SfxObjectShell& rSource, BOOL bPreserveCurrentDocument );

    // Seitenvorlagedialog anzeigen, ggf. auf Spaltenpage
    void FormatPage( const String& rPage,
                        BOOL bColumn = FALSE,
                        SwWrtShell*     pActShell = 0 );

    // Timer starten fuers ueberpruefen der Grafik-Links. Sind alle
    // vollstaendig geladen, dann ist das Doc fertig
    void StartLoadFinishedTimer();

    // eine Uebertragung wird abgebrochen (wird aus dem SFX gerufen)
    virtual void CancelTransfers();

    // Doc aus Html-Source neu laden
    void    ReloadFromHtml( const String& rStreamName, SwSrcView* pSrcView );

    sal_Int16   GetUpdateDocMode() const {return nUpdateDocMode;}

    //Activate wait cursor for all windows of this document
    //Optionally all dispatcher could be Locked
    //Usually locking should be done using the class: SwWaitObject!
    void EnterWait( BOOL bLockDispatcher );
    void LeaveWait( BOOL bLockDispatcher );

    void ToggleBrowserMode(BOOL bOn, SwView* pView = 0);

    ULONG LoadStylesFromFile( const String& rURL, SwgReaderOption& rOpt,
                                BOOL bUnoCall );
    void InvalidateModel();
    void ReactivateModel();

#if SUPD>620
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >  GetEventNames();
#endif
};

inline BOOL SwDocShell::SaveAsChilds( SvStorage *pStor )
{
    return SfxInPlaceObject::SaveAsChilds( pStor );
}

inline BOOL SwDocShell::SaveCompletedChilds( SvStorage *pStor )
{
    return SfxInPlaceObject::SaveCompletedChilds( pStor );
}
#endif
<|endoftext|>


<commit_before>#ifndef _sbl_order_statistic_tree_intrusive
#define _sbl_order_statistic_tree_intrusive
#include<cstddef>
#include<cstdlib>
#include<cassert>

/** \brief This is a intrusive data structure version of order statistic
 * tree.
 *
 * User must provide the node type, manage the memory, and guarantee:
 *
 * Member variant OrderStatisticTreeNode<NodePtr> node record the
 * information.
 *
 * Member function bool less_than(NodePtr other) to use for all comparisons
 * of keys
 */

namespace sbl {
namespace intrusive {

template < class NodePtr >
class OrderStatisticTree;

size_t random() {
    size_t c = rand() * rand();
    return c ? c : 1;
}

template<class NodePtr>
class OrderStatisticTreeNode {
        friend class OrderStatisticTree<NodePtr>;
        NodePtr child[2];
        size_t size;
        size_t priority;
};

/** @brief order statistic tree is a data structure described in Introduction
 * to Algorithm.
*
* This is an augmenting data structure, which add size attribute to every tree
* nodes.  Size attribute represent how many nodes in current subtree (treat the
* node we focus as root). For more information, read CLRS Chapter 14.
*
*
* @tparam NodePtr a pointer to the node which defined by user.
*/

template < class NodePtr >
class OrderStatisticTree {
    /// This data structure implement by using Treap.
    /// Treap is a binary search tree.
    private:

        /// get the node information from NodePtr
        OrderStatisticTreeNode<NodePtr> &get_node(NodePtr a) {
            return a->node;
        }

        /// get the left child from a NodePtr
        NodePtr &l(NodePtr a) {
            return get_node(a).child[0];
        }

        /// get the right child from a NodePtr
        NodePtr &r(NodePtr a) {
            return get_node(a).child[1];
        }

        /// get the child according index.
        ///
        /// @param index 0 represent left child, 1 represent right child.
        ///
        NodePtr &child(NodePtr a, size_t idx) {
            if (idx == 0) return l(a);
            if (idx == 1) return r(a);
            assert(false && "OrderStatisticTree:: subscript range error");
        }

        /// get priority from a NodePtr for treap
        size_t &priority(NodePtr a) {
            return get_node(a).priority;
        }

        /// update the size of current NodePtr
        void update_size(NodePtr a) {
            size(a) = size(l(a)) + size(r(a)) + 1;
        }

        /// Swap a NodePtr with her father.
        NodePtr rotate(NodePtr t, size_t idx) {
            assert(idx == 0 or idx == 1);
            NodePtr s = child(t, idx);
            child(t, idx) = child(s, 1 - idx);
            child(s, 1 - idx) = t;
            update_size(t);
            update_size(s);
            return s;
        }

        /// Add NodePtr a to subtree x.
        void add(NodePtr x, NodePtr &a) {
            if (a == nullPtr) {
                a = x;
                l(a) = r(a) = nullPtr;
                size(a) = 1;
                priority(a) = random();
            } else {
                int c = x->compare(a) ? 0 : 1;
                add(x, child(a, c));
                if (priority(child(a, c)) <= priority(a))
                    size(a)++;
                else
                    a = rotate(a, c);
            }

        }

        /// Delete NodePtr a from subtree x.
        NodePtr del(NodePtr x, NodePtr &a) {
            if (a == nullPtr) return 0;
            int c = x->compare(a) ? 0 : a->compare(x) ? 1 : 2;
            if (c == 2) {
                if (l(a) == r(a) and  r(a) == nullPtr) {
                    NodePtr ret = a;
                    a = nullPtr;
                    return ret;
                }
                c = priority(l(a)) > priority(r(a)) ? 1 : 0;
                a = rotate(a, 1 - c);
            }
            NodePtr ret = del(x, child(a, c));
            if (ret != 0)
                size(a)--;
            return ret;
        }

        /// @return number of nodes in subtree a.
        size_t &size(NodePtr a) {
            return get_node(a).size;
        }

        NodePtr root;
        NodePtr nullPtr; ///< a sentinel denote the empty pointer
    public:
        /** Since OrderStatisticTree could not be allocated memory for a NodePtr,
         * the user must given a useless NodePtr as a sentinel.
         */
        OrderStatisticTree(NodePtr a): root(a), nullPtr(a) {
            l(a) = r(a) = a;
            size(a) = 0;
            priority(a) = 0;
        }

        /// @return number of all nodes.
        size_t size() const{
            return root->node.size;
        }

        /// add NodePtr x to root.
        void insert(NodePtr x) {
            add(x, root);
        }

        /// remove NodePtr from root.
        NodePtr erase(NodePtr x) {
            return del(x, root);
        }

        /// @param x the NodePtr for comparing.
        /// @param a which subtree we are focused.
        ///
        /// @return number of nodes that (key) smaller than NodePtr x.
        size_t smaller_count(NodePtr x, NodePtr a = 0) {
            if (a == 0) a = root;
            if (a == nullPtr) return 0;
            if (!a->compare(x)) return smaller_count(x, l(a));
            return smaller_count(x, r(a)) + size(l(a)) + 1;
        }

        /// @param x the NodePtr for comparing.
        /// @param a which subtree we are focused.
        ///
        /// @return number of nodes that (key) bigger than NodePtr x.
        size_t bigger_count(NodePtr x, NodePtr a = 0) {
            if (a == 0) a = root;
            if (a == nullPtr) return 0;
            if (!x->compare(a)) return bigger_count(x, r(a));
            return bigger_count(x, l(a)) + size(r(a)) + 1;
        }
        /// @param x the NodePtr for comparing.
        /// @param a which subtree we are focused.
        ///
        /// @return first NodePtr smaller than NodePtr x.
        NodePtr smaller(NodePtr x, NodePtr a = 0) {
            if (a == 0) a = root;
            if (a == nullPtr) return 0;
            if (!a->compare(x)) return smaller(x, l(a));
            else {
                NodePtr b = smaller(x, r(a));
                return b == 0 ? a : b;
            }
        }
        /// @param x the NodePtr for comparing.
        /// @param a which subtree we are focused.
        ///
        /// @return first NodePtr bigger than NodePtr x.
        NodePtr bigger(NodePtr x, NodePtr a = 0) {
            if (a == 0) a = root;
            if (a == nullPtr) return 0;
            if (!x->compare(a)) return bigger(x, r(a));
            else {
                NodePtr b = bigger(x, l(a));
                return b == 0 ? a : b;
            }
        }
        /// @return the minimum node
        NodePtr smallest(NodePtr a = 0) {
            if (a == 0) a = root;
            if (a == nullPtr || l(a) == nullPtr) return a;
            return smallest(l(a));
        }
        /// @return the maximum node
        NodePtr biggest(NodePtr a = 0) {
            if (a == 0) a = root;
            if (a == nullPtr || r(a) == nullPtr) return a;
            return biggest(r(a));
        }
        /// @return the n-th small node.
        NodePtr at(size_t n, NodePtr a = 0) {
            if (a == 0) a = root;
            size_t ls = size(l(a));
            return ls == n ? a :
                   ls >  n ? at(n, l(a)) :
                   at(n - ls - 1, r(a));
        }
        /// @return the node equal to x.
        NodePtr find(NodePtr x, NodePtr a = 0) {
            if (a == 0) a = root;
            return a == nullPtr  ? 0 :
                   x->compare(a) ? find(x, l(a)) :
                   a->compare(x) ? find(x, r(a)) : a;
        }
};

} // namespace intrusive
} // namespace sbl
#endif
<commit_msg>OrderStatisticTree: does not need nullPtr anymore.<commit_after>#ifndef _sbl_order_statistic_tree_intrusive
#define _sbl_order_statistic_tree_intrusive
#include<cstddef>
#include<cstdlib>
#include<cassert>

/** \brief This is a intrusive data structure version of order statistic
 * tree.
 *
 * User must provide the node type, manage the memory, and guarantee:
 *
 * Member variant OrderStatisticTreeNode<NodePtr> node record the
 * information.
 *
 * Member function bool less_than(NodePtr other) to use for all comparisons
 * of keys
 */

namespace sbl {
namespace intrusive {

template < class NodePtr >
class OrderStatisticTree;

template<class NodePtr>
class OrderStatisticTreeNode {
        friend class OrderStatisticTree<NodePtr>;
        NodePtr child[2];
        size_t size;
        size_t priority;
        size_t random() {
            size_t c = rand() * rand() + 1;
            return c;
        }
    public:
        OrderStatisticTreeNode(): size(1), priority(random()) {
            child[0] = child[1] = NULL;
        }
};

/** @brief order statistic tree is a data structure described in Introduction
 * to Algorithm.
 *
 * This is an augmenting data structure, which add size attribute to every tree
 * nodes.  Size attribute represent how many nodes in current subtree (treat the
 * node we focus as root). For more information, read CLRS Chapter 14.
 *
 *
 * @tparam NodePtr a pointer to the node which defined by user.
 */

template < class NodePtr >
class OrderStatisticTree {
        /// This data structure implement by using Treap.
        /// Treap is a binary search tree.
    private:

        /// get the node information from NodePtr
        OrderStatisticTreeNode<NodePtr> &get_node(NodePtr a) {
            return a->node;
        }

        /// get the node information from NodePtr, const version
        const OrderStatisticTreeNode<NodePtr> &get_node(NodePtr a) const {
            return a->node;
        }

        /// @return number of nodes in subtree a.
        const size_t &size(NodePtr a) const {
            static const size_t zero = 0;
            if (a == NULL) return zero;
            return get_node(a).size;
        }

        /// change size attribute.
        void set_size(NodePtr a, size_t value) {
            if (a == NULL) return;
            get_node(a).size = value;
        }

        /// get priority from a NodePtr for treap
        const size_t &priority(NodePtr a) const {
            static const size_t zero = 0;
            if (a == NULL) return zero;
            return get_node(a).priority;
        }

        /// get the child according index.
        ///
        /// @param a father
        /// @param index 0 represent left child, 1 represent right child.
        ///
        /// @return const reference of child
        const NodePtr &child(NodePtr a, size_t idx) const {
            static const NodePtr kNullPtr = NULL;
            if (a == NULL) return kNullPtr;
            return get_node(a).child[idx];
            assert(false && "OrderStatisticTree:: subscript range error");
        }

        /// get the reference of child according index.
        ///
        /// @param a father, must not be NULL
        /// @param index 0 represent left child, 1 represent right child.
        ///
        /// @return reference of child
        NodePtr &child_references(NodePtr a, size_t idx) {
            assert(a != NULL);
            return get_node(a).child[idx];
            assert(false and "OrderStatisticTree:: subscript range error");
        }

        /// change child
        void set_child(NodePtr a, size_t idx, NodePtr b) {
            if (a == NULL) return;
            get_node(a).child[idx] = b;
        }

        /// get the left child from a NodePtr
        const NodePtr &l(NodePtr a) const {
            return child(a, 0);
        }

        /// get the right child from a NodePtr
        const NodePtr &r(NodePtr a) const {
            return child(a, 1);
        }

        /// update the size of current NodePtr
        void update_size(NodePtr a) {
            set_size(a, size(l(a)) + size(r(a)) + 1);
        }

        /// Swap a NodePtr with her father.
        NodePtr rotate(NodePtr t, size_t idx) {
            assert(idx == 0 or idx == 1);
            NodePtr s = child(t, idx);
            set_child(t, idx, child(s, 1 - idx));
            set_child(s, 1 - idx, t);
            update_size(t);
            update_size(s);
            return s;
        }

        /// Add NodePtr x to subtree a.
        void add(NodePtr x, NodePtr &a) {
            if (a == NULL) {
                a = x;
            } else {
                size_t idx = x->less_than(a) ? 0 : 1;
                add(x, child_references(a, idx));
                if (priority(child(a, idx)) <= priority(a))
                    update_size(a);
                else
                    a = rotate(a, idx);
            }

        }

        /// Delete NodePtr a from subtree x.
        NodePtr del(NodePtr x, NodePtr &a) {
            if (a == NULL) return 0;
            size_t idx = x->less_than(a) ? 0 : a->less_than(x) ? 1 : 2;
            if (idx == 2) {
                // x and a are equivalence
                if (l(a) == r(a) and r(a) == NULL) {
                    NodePtr ret = a;
                    a = NULL;
                    return ret;
                }
                idx = priority(l(a)) > priority(r(a)) ? 1 : 0;
                a = rotate(a, 1 - idx);
            }
            NodePtr ret = del(x, child_references(a, idx));
            if (ret != 0)
                update_size(a);
            return ret;
        }

        /// @return number of nodes in subtree a smaller than x.
        size_t smaller_count(NodePtr x, NodePtr a) const {
            if (a == NULL)
                return 0;
            else if (not a->less_than(x))
                return smaller_count(x, l(a));
            else
                return smaller_count(x, r(a)) + size(l(a)) + 1;
        }

        /// @return number of nodes in subtree a bigger than x.
        size_t bigger_count(NodePtr x, NodePtr a) const {
            if (a == NULL)
                return 0;
            else if (not x->less_than(a))
                return bigger_count(x, r(a));
            else
                return bigger_count(x, l(a)) + size(r(a)) + 1;
        }

        /// @return node in subtree a smaller than x.
        NodePtr smaller(NodePtr x, NodePtr a) const {
            if (a == NULL)
                return 0;
            else if (not a->less_than(x)) {
                return smaller(x, l(a));
            } else {
                NodePtr b = smaller(x, r(a));
                return b == NULL ? a : b;
            }
        }

        /// @return node in subtree a bigger than x.
        NodePtr bigger(NodePtr x, NodePtr a) const {
            if (a == NULL)
                return 0;
            else if (not x->less_than(a)) {
                return bigger(x, r(a));
            } else {
                NodePtr b = bigger(x, l(a));
                return b == NULL ? a : b;
            }
        }

        /// @return smallest node in subtree a
        NodePtr smallest(NodePtr a) const {
            if (a == NULL || l(a) == NULL) return a;
            return smallest(l(a));
        }
        /// @return biggest node in subtree a
        NodePtr biggest(NodePtr a) const {
            if (a == NULL || r(a) == NULL) return a;
            return biggest(r(a));
        }

        /// @return n-th small node in subtree a.
        NodePtr at(size_t n, NodePtr a) const {
            if (a == 0) a = root;
            size_t ls = size(l(a));
            return ls == n ? a :
                   ls >  n ? at(n, l(a)) :
                   at(n - ls - 1, r(a));
        }

        /// @return equivalence of x in subtree a.
        NodePtr find(NodePtr x, NodePtr a) const {
            if (a == 0) a = root;
            return a == NULL  ? 0 :
                   x->less_than(a) ? find(x, l(a)) :
                   a->less_than(x) ? find(x, r(a)) : a;
        }

        NodePtr root;
    public:

        /// construct an empty OrderStatisticTree
        OrderStatisticTree(): root(NULL) {}

        /// @return number of all nodes.
        size_t size() const {
            return size(root);
        }

        /// add NodePtr x to root.
        void insert(NodePtr x) {
            add(x, root);
        }

        /// remove NodePtr from root.
        NodePtr erase(NodePtr x) {
            return del(x, root);
        }

        /// @return number of nodes that smaller than NodePtr x.
        size_t smaller_count(NodePtr x) const {
            return smaller_count(x, root);
        }

        /// @return number of nodes that bigger than NodePtr x.
        size_t bigger_count(NodePtr x) const {
            return bigger_count(x, root);
        }
        /// @return first NodePtr smaller than NodePtr x.
        NodePtr smaller(NodePtr x) const {
            return smaller(x, root);
        }
        /// @return first NodePtr bigger than NodePtr x.
        NodePtr bigger(NodePtr x) const {
            return bigger(x, root);
        }
        /// @return the minimum node.
        NodePtr smallest() const {
            return smallest(root);
        }
        /// @return the maximum node.
        NodePtr biggest() const {
            return biggest(root);
        }
        /// @return the n-th small node.
        NodePtr at(size_t n) const {
            return at(n, root);
        }
        /// @return equivalence node of x.
        NodePtr find(NodePtr x) const {
            return find(x, root);
        }
        /// @return remove all node in OrderStatisticTree
        void clear() {
            root = NULL;
        }
};

} // namespace intrusive
} // namespace sbl
#endif
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.9  2000/03/02 19:55:08  roddey
 * This checkin includes many changes done while waiting for the
 * 1.1.0 code to be finished. I can't list them all here, but a list is
 * available elsewhere.
 *
 * Revision 1.8  2000/02/22 01:00:48  aruna1
 * GNUGDefs references removed. Now only GCCDefs is used instead
 *
 * Revision 1.7  2000/02/06 07:48:17  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.6  2000/01/14 02:08:29  abagchi
 * Sorry GCC does not support long strings
 *
 * Revision 1.5  2000/01/14 01:55:09  abagchi
 * Added XML_LSTRSUPPORT
 *
 * Revision 1.4  2000/01/13 01:39:11  abagchi
 * Changed unsigned short to wchar_t for XMLCh
 *
 * Revision 1.3  1999/11/12 20:36:54  rahulj
 * Changed library name to xerces-c.lib.
 *
 * Revision 1.1.1.1  1999/11/09 01:07:32  twl
 * Initial checkin
 *
 * Revision 1.2  1999/11/08 20:45:23  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

// ---------------------------------------------------------------------------
// Define these away for this platform
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT
#define PLATFORM_IMPORT

// ---------------------------------------------------------------------------
// Indicate that we do not support native bools
// ---------------------------------------------------------------------------
//#define NO_NATIVE_BOOL

// ---------------------------------------------------------------------------
//  GCC does not support "L" for long strings. So we do nothing.
// ---------------------------------------------------------------------------
// #define XML_LSTRSUPPORT

// ---------------------------------------------------------------------------
//  Define our version of the XML character
// ---------------------------------------------------------------------------
// typedef unsigned short XMLCh; // is another option, now considered old
typedef wchar_t XMLCh;

// ---------------------------------------------------------------------------
//  Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short  XMLUInt16;
typedef unsigned int    XMLUInt32;

// ---------------------------------------------------------------------------
//  Force on the Xerces debug token if it was on in the build environment
// ---------------------------------------------------------------------------
#if 0
#define XERCES_DEBUG
#endif

// ---------------------------------------------------------------------------
//  Provide some common string ops that are different/notavail on GCC
// ---------------------------------------------------------------------------
inline char toupper(const char toUpper)
{
    if ((toUpper >= 'a') && (toUpper <= 'z'))
        return char(toUpper - 0x20);
    return toUpper;
}

inline char tolower(const char toLower)
{
    if ((toLower >= 'A') && (toLower <= 'Z'))
        return char(toLower + 0x20);
    return toLower;
}

int stricmp(const char* const str1, const char* const  str2);
int strnicmp(const char* const str1, const char* const  str2, const unsigned int count);

// ---------------------------------------------------------------------------
//  The name of the DLL that is built by the GCC version of the system.
// ---------------------------------------------------------------------------
const char* const Xerces_DLLName = "libxerces-c";
<commit_msg>Added header guards to include inlines only once<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.10  2000/03/09 01:22:29  abagchi
 * Added header guards to include inlines only once
 *
 * Revision 1.9  2000/03/02 19:55:08  roddey
 * This checkin includes many changes done while waiting for the
 * 1.1.0 code to be finished. I can't list them all here, but a list is
 * available elsewhere.
 *
 * Revision 1.8  2000/02/22 01:00:48  aruna1
 * GNUGDefs references removed. Now only GCCDefs is used instead
 *
 * Revision 1.7  2000/02/06 07:48:17  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.6  2000/01/14 02:08:29  abagchi
 * Sorry GCC does not support long strings
 *
 * Revision 1.5  2000/01/14 01:55:09  abagchi
 * Added XML_LSTRSUPPORT
 *
 * Revision 1.4  2000/01/13 01:39:11  abagchi
 * Changed unsigned short to wchar_t for XMLCh
 *
 * Revision 1.3  1999/11/12 20:36:54  rahulj
 * Changed library name to xerces-c.lib.
 *
 * Revision 1.1.1.1  1999/11/09 01:07:32  twl
 * Initial checkin
 *
 * Revision 1.2  1999/11/08 20:45:23  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

#if !defined(GCCDEFS_HPP)
#define GCCDEFS_HPP

// ---------------------------------------------------------------------------
// Define these away for this platform
// ---------------------------------------------------------------------------
#define PLATFORM_EXPORT
#define PLATFORM_IMPORT

// ---------------------------------------------------------------------------
// Indicate that we do not support native bools
// ---------------------------------------------------------------------------
//#define NO_NATIVE_BOOL

// ---------------------------------------------------------------------------
//  GCC does not support "L" for long strings. So we do nothing.
// ---------------------------------------------------------------------------
// #define XML_LSTRSUPPORT

// ---------------------------------------------------------------------------
//  Define our version of the XML character
// ---------------------------------------------------------------------------
// typedef unsigned short XMLCh; // is another option, now considered old
typedef wchar_t XMLCh;

// ---------------------------------------------------------------------------
//  Define unsigned 16 and 32 bits integers
// ---------------------------------------------------------------------------
typedef unsigned short  XMLUInt16;
typedef unsigned int    XMLUInt32;

// ---------------------------------------------------------------------------
//  Force on the Xerces debug token if it was on in the build environment
// ---------------------------------------------------------------------------
#if 0
#define XERCES_DEBUG
#endif

// ---------------------------------------------------------------------------
//  Provide some common string ops that are different/notavail on GCC
// ---------------------------------------------------------------------------
inline char toupper(const char toUpper)
{
    if ((toUpper >= 'a') && (toUpper <= 'z'))
        return char(toUpper - 0x20);
    return toUpper;
}

inline char tolower(const char toLower)
{
    if ((toLower >= 'A') && (toLower <= 'Z'))
        return char(toLower + 0x20);
    return toLower;
}

int stricmp(const char* const str1, const char* const  str2);
int strnicmp(const char* const str1, const char* const  str2, const unsigned int count);

// ---------------------------------------------------------------------------
//  The name of the DLL that is built by the GCC version of the system.
// ---------------------------------------------------------------------------
const char* const Xerces_DLLName = "libxerces-c";

#endif  // GCCDEFS_HPP

<|endoftext|>


<commit_before>#include <UnitTest++.h>

#include "../../common.h"
#include "../../gamefw/gamefw.h"
#include "../objfile.h"

#include <physfs.h>
#include <boost/concept_check.hpp>

using namespace gamefw;

struct ObjFileFixture
{
    ObjFileFixture()
    {
        FileService* fileservice = new FileService();
        Locator::registerFileService(*fileservice);
    }

    ~ObjFileFixture()
    {
        FileService& fileservice = Locator::getFileService();
        delete &fileservice;
    }
};

TEST_FIXTURE(ObjFileFixture, TestLoadSimpleObj)
{
    string path = Locator::getFileService().getRealPath("src/gamefw/util/tests/simple.obj");
    ObjFile model(path);
    CHECK_EQUAL(model.getNumMaterials(), 2); // +1 for the default mtl.
    CHECK_EQUAL(model.getNumNormals(), 1);
    CHECK_EQUAL(model.getNumPositions(), 3);
    CHECK_EQUAL(model.getNumTexcoords(), 3);
    CHECK_EQUAL(model.getNumTriangles(), 1);

    float positions[] = {1.0f, -1.0f, 1.0f,
                         -1.0f, -1.0f, 1.0f,
                         -1.0f, -1.0f, -1.0f};

    float normals[] = {0.0f, -1.0f, 0.0f};

    float texcoords[] = {0.0f, 0.5f,
                         0.5f, 0.0f,
                         1.0f, 0.5f};

    CHECK_ARRAY_CLOSE(model.getPositions(), positions, 9, 0.00);
    CHECK_ARRAY_CLOSE(model.getNormals(), normals, 3, 0.00);
    CHECK_ARRAY_CLOSE(model.getTexCoords(), texcoords, 6, 0.00);

    t_obj_triangle triangle1 = {
        {1, 2, 3},
        {1, 2, 3},
        {1, 1, 1},
        1
    };

    t_obj_triangle triangle2 = *model.getTriangles();

    CHECK_ARRAY_EQUAL(triangle1.pindices, triangle2.pindices, 3);
    CHECK_ARRAY_EQUAL(triangle1.nindices, triangle2.nindices, 3);
    CHECK_ARRAY_EQUAL(triangle1.tindices, triangle2.tindices, 3);
    CHECK_EQUAL(triangle1.material, triangle2.material);

    t_obj_mtl material1 = {
        {0.64f, 0.64f, 0.64f, 1.0f},
        {0.5f, 0.5f, 0.5f, 1.0f},
        128.0,
        {0.0f, 0.0f, 0.0f}
    };

    t_obj_mtl material2 = model.getMaterials()[1];

    CHECK_ARRAY_CLOSE(material1.diffuse, material2.diffuse, 4, 0.00);
    CHECK_ARRAY_CLOSE(material1.specular, material2.specular, 4, 0.00);
    CHECK_CLOSE(material1.shininess, material2.shininess, 0.00);
}

int main(int argc, char* argv[])
{
    PHYSFS_init(argv[0]);

    return UnitTest::RunAllTests();
    return 0;
}<commit_msg>Fix testobjfile.<commit_after>#include <UnitTest++.h>

#include "../../common.h"
#include "../../gamefw/gamefw.h"
#include "../objfile.h"

#include <physfs.h>
#include <boost/concept_check.hpp>

using namespace gamefw;

struct ObjFileFixture
{
    ObjFileFixture()
    {
        FileService* fileservice = new FileService();
        Locator::registerFileService(*fileservice);
    }

    ~ObjFileFixture()
    {
        FileService& fileservice = Locator::getFileService();
        delete &fileservice;
    }
};

TEST_FIXTURE(ObjFileFixture, TestLoadSimpleObj)
{
    string path = Locator::getFileService().getRealPath("src/util/tests/simple.obj");
    ObjFile model(path);
    CHECK_EQUAL(model.getNumMaterials(), 2); // +1 for the default mtl.
    CHECK_EQUAL(model.getNumNormals(), 1);
    CHECK_EQUAL(model.getNumPositions(), 3);
    CHECK_EQUAL(model.getNumTexcoords(), 3);
    CHECK_EQUAL(model.getNumTriangles(), 1);

    float positions[] = {1.0f, -1.0f, 1.0f,
                         -1.0f, -1.0f, 1.0f,
                         -1.0f, -1.0f, -1.0f};

    float normals[] = {0.0f, -1.0f, 0.0f};

    float texcoords[] = {0.0f, 0.5f,
                         0.5f, 0.0f,
                         1.0f, 0.5f};

    CHECK_ARRAY_CLOSE(model.getPositions(), positions, 9, 0.00);
    CHECK_ARRAY_CLOSE(model.getNormals(), normals, 3, 0.00);
    CHECK_ARRAY_CLOSE(model.getTexCoords(), texcoords, 6, 0.00);

    // Indexes should be -1 from the .obj.
    t_obj_triangle triangle1 = {
        {0, 1, 2},
        {0, 0, 0},
        {0, 1, 2},
        1 // Except for the material, because there's a default one on index 0.
    };

    t_obj_triangle triangle2 = *model.getTriangles();

    CHECK_ARRAY_EQUAL(triangle1.pindices, triangle2.pindices, 3);
    CHECK_ARRAY_EQUAL(triangle1.nindices, triangle2.nindices, 3);
    CHECK_ARRAY_EQUAL(triangle1.tindices, triangle2.tindices, 3);
    CHECK_EQUAL(triangle1.material, triangle2.material);

    t_obj_mtl material1 = {
        {0.64f, 0.64f, 0.64f, 1.0f},
        {0.5f, 0.5f, 0.5f, 1.0f},
        128.0,
        {0.0f, 0.0f, 0.0f}
    };

    t_obj_mtl material2 = model.getMaterials()[1];

    CHECK_ARRAY_CLOSE(material1.diffuse, material2.diffuse, 4, 0.00);
    CHECK_ARRAY_CLOSE(material1.specular, material2.specular, 4, 0.00);
    CHECK_CLOSE(material1.shininess, material2.shininess, 0.00);
}

int main(int argc, char* argv[])
{
    PHYSFS_init(argv[0]);

    return UnitTest::RunAllTests();
    return 0;
}<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include "model.h"

Model::Model(std::string filename){
    this->readBitmap(filename);
    rand = std::make_shared<RandomStream>(0, this->colBM*this->rowBM-1);
}

Model::~Model(){
    for (int i = 0; i < rowBM; i++ ){
        delete[] bitmap[i];
    }

    delete[] bitmap;
}

void Model::run(int action){
    switch(action){
        case 0:
            if (!this->isOnObstacle(currState.rowIdx - 1, currState.colIdx)){
                oldState = currState;
                currState.rowIdx -=1;
            }
            break;
        case 1:
            if (!this->isOnObstacle(currState.rowIdx + 1, currState.colIdx)){
                oldState = currState;
                currState.rowIdx +=1;
            }
            break;
        case 2:
            if (!this->isOnObstacle(currState.rowIdx, currState.colIdx - 1)){
                oldState = currState;
                currState.colIdx -=1;
            }
            break;
        case 3:
            if (!this->isOnObstacle(currState.rowIdx, currState.colIdx + 1)){
                oldState = currState;
                currState.colIdx +=1;
            }
            break;
        default:break;
    }
}

void Model::createInitialState(){
    int col;
    int row;

    while( true ){
    int index = rand->nextInt();
    col = index % this->colBM;
    row = index / this->rowBM;
    if (!this->isOnObstacle(row,col)) break;
    }
    currState.colIdx = col;
    currState.rowIdx = row;
}

bool Model::isOnObstacle(int i,int j){

    if (i >= 0 && j >> 0 && i < rowBM && j < colBM){
        return (bitmap[i][j] == 0);
    }
    return true;
}

void Model::readBitmap(std::string s) {

    std::ifstream is;
    is.open(s);
    std::string line;
    std::string data;
    int lineNum = 0;
    int row = 0;
    int temp;
    while (getline(is, line)) {
        lineNum++;
        std::stringstream linestream(line);

        if (lineNum == 1) {
            linestream>>rowBM;
            std::cout << "The number of rows of the matrix are: " << rowBM << std::endl;
        } else if (lineNum == 2) {
            linestream>>colBM;
            std::cout << "The number of rows of the matrix are: " << colBM << std::endl;
            bitmap = new int*[rowBM];
            for (int i = 0; i < rowBM; i++) {
                bitmap[i] = new int[colBM];
            }
        } else {

            for (int i = 0; i < colBM; i++) {
                linestream>>temp;
                bitmap[row][i] = temp;
            }
            row++;
        }
    }
    std::ofstream os;
    os.open(s + "mapdata.txt");
    for (int i = 0; i < rowBM; i++) {
        for (int j = 0; j < colBM; j++) {
            if (bitmap[i][j] == 1) os << j << "\t" << i << std::endl;
            ;
        }
    }
    os.close();
    is.close();

    os.open(s + "walldata.txt");
    int count = 0;
    for (double i = -1; i <= rowBM; i += 0.5) {
        for (double j = -1; j <= colBM; j += 0.5) {
            if ((int) round(i) >= 0 && (int) round(i) < rowBM && (int) round(j) >= 0 && (int) round(j) < colBM) {
                if (bitmap[(int) round(i)][(int) round(j)] == 0) {
                    count++;
                    os << count << "\t" << j << "\t" << i << std::endl;
                }
            } else if (abs(i + 1) < 0.25 || abs(i - rowBM) < 0.25 ||
                    abs(j + 1) < 0.25 || abs(j - colBM) < 0.25) {
                count++;
                os << count << "\t" << j << "\t" << i << std::endl;
            }
        }

    }
    os.close();
}<commit_msg>fix a bug<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include "model.h"

Model::Model(std::string filename){
    this->readBitmap(filename);
    rand = std::make_shared<RandomStream>(0, this->colBM*this->rowBM-1);
}

Model::~Model(){
    for (int i = 0; i < rowBM; i++ ){
        delete[] bitmap[i];
    }

    delete[] bitmap;
}

void Model::run(int action){
    switch(action){
        case 0:
            if (!this->isOnObstacle(currState.rowIdx - 1, currState.colIdx)){
                oldState = currState;
                currState.rowIdx -=1;
            }
            break;
        case 1:
            if (!this->isOnObstacle(currState.rowIdx + 1, currState.colIdx)){
                oldState = currState;
                currState.rowIdx +=1;
            }
            break;
        case 2:
            if (!this->isOnObstacle(currState.rowIdx, currState.colIdx - 1)){
                oldState = currState;
                currState.colIdx -=1;
            }
            break;
        case 3:
            if (!this->isOnObstacle(currState.rowIdx, currState.colIdx + 1)){
                oldState = currState;
                currState.colIdx +=1;
            }
            break;
        default:break;
    }
}

void Model::createInitialState(){
    int col;
    int row;

    while( true ){
    int index = rand->nextInt();
    col = index % this->colBM;
    row = index / this->rowBM;
    if (!this->isOnObstacle(row,col)) break;
    }
    currState.colIdx = col;
    currState.rowIdx = row;
}

bool Model::isOnObstacle(int i,int j){

    if (i >= 0 && j >= 0 && i < rowBM && j < colBM){
        return (bitmap[i][j] == 0);
    }
    return true;
}

void Model::readBitmap(std::string s) {

    std::ifstream is;
    is.open(s);
    std::string line;
    std::string data;
    int lineNum = 0;
    int row = 0;
    int temp;
    while (getline(is, line)) {
        lineNum++;
        std::stringstream linestream(line);

        if (lineNum == 1) {
            linestream>>rowBM;
            std::cout << "The number of rows of the matrix are: " << rowBM << std::endl;
        } else if (lineNum == 2) {
            linestream>>colBM;
            std::cout << "The number of rows of the matrix are: " << colBM << std::endl;
            bitmap = new int*[rowBM];
            for (int i = 0; i < rowBM; i++) {
                bitmap[i] = new int[colBM];
            }
        } else {

            for (int i = 0; i < colBM; i++) {
                linestream>>temp;
                bitmap[row][i] = temp;
            }
            row++;
        }
    }
    std::ofstream os;
    os.open(s + "mapdata.txt");
    for (int i = 0; i < rowBM; i++) {
        for (int j = 0; j < colBM; j++) {
            if (bitmap[i][j] == 1) os << j << "\t" << i << std::endl;
            ;
        }
    }
    os.close();
    is.close();

    os.open(s + "walldata.txt");
    int count = 0;
    for (double i = -1; i <= rowBM; i += 0.5) {
        for (double j = -1; j <= colBM; j += 0.5) {
            if ((int) round(i) >= 0 && (int) round(i) < rowBM && (int) round(j) >= 0 && (int) round(j) < colBM) {
                if (bitmap[(int) round(i)][(int) round(j)] == 0) {
                    count++;
                    os << count << "\t" << j << "\t" << i << std::endl;
                }
            } else if (abs(i + 1) < 0.25 || abs(i - rowBM) < 0.25 ||
                    abs(j + 1) < 0.25 || abs(j - colBM) < 0.25) {
                count++;
                os << count << "\t" << j << "\t" << i << std::endl;
            }
        }

    }
    os.close();
}
<|endoftext|>