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

  Program:   Visualization Toolkit
  Module:    vtkBYUWriter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkBYUWriter.h"
#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkBYUWriter, "1.42");
vtkStandardNewMacro(vtkBYUWriter);

// Create object so that it writes displacement, scalar, and texture files
// (if data is available).
vtkBYUWriter::vtkBYUWriter()
{
  this->GeometryFileName = NULL;
  this->DisplacementFileName = NULL;
  this->ScalarFileName = NULL;
  this->TextureFileName = NULL;

  this->WriteDisplacement = 1;
  this->WriteScalar = 1;
  this->WriteTexture = 1;
}

vtkBYUWriter::~vtkBYUWriter()
{
  if ( this->GeometryFileName )
    {
    delete [] this->GeometryFileName;
    }
  if ( this->DisplacementFileName )
    {
    delete [] this->DisplacementFileName;
    }
  if ( this->ScalarFileName )
    {
    delete [] this->ScalarFileName;
    }
  if ( this->TextureFileName )
    {
    delete [] this->TextureFileName;
    }
}

// Write out data in MOVIE.BYU format.
void vtkBYUWriter::WriteData()
{
  FILE *geomFp;
  vtkPolyData *input= this->GetInput();
  int numPts=input->GetNumberOfPoints();

  if ( numPts < 1 )
    {
    vtkErrorMacro(<<"No data to write!");
    return;
    }

  if ((geomFp = fopen(this->GeometryFileName, "w")) == NULL)
    {
    vtkErrorMacro(<< "Couldn't open geometry file: " << this->GeometryFileName);
    return;
    }
  else
    {
    this->WriteGeometryFile(geomFp,numPts);
    }

  this->WriteDisplacementFile(numPts);
  this->WriteScalarFile(numPts);
  this->WriteTextureFile(numPts);

  // Close the file
  fclose (geomFp);
}

void vtkBYUWriter::WriteGeometryFile(FILE *geomFile, int numPts)
{
  int numPolys, numEdges;
  int i;
  float *x;
  vtkIdType npts;
  vtkIdType *pts;
  vtkPoints *inPts;
  vtkCellArray *inPolys;
  vtkPolyData *input= this->GetInput();
  //
  // Check input
  //
  inPolys=input->GetPolys();
  if ( (inPts=input->GetPoints()) == NULL || inPolys == NULL )
    {
    vtkErrorMacro(<<"No data to write!");
    return;
    }
//
// Write header (not using fixed format! - potential problem in some files.)
//
  numPolys = input->GetPolys()->GetNumberOfCells();
  for (numEdges=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); )
    {
    numEdges += npts;
    }

  fprintf (geomFile, "%d %d %d %d\n", 1, numPts, numPolys, numEdges);
  fprintf (geomFile, "%d %d\n", 1, numPolys);
//
// Write data
//
  // write point coordinates
  for (i=0; i < numPts; i++)
    {
    x = inPts->GetPoint(i);
    fprintf(geomFile, "%e %e %e ", x[0], x[1], x[2]);
    if ( (i % 2) )
      {
      fprintf(geomFile, "\n");
      }
    }
  if ( (numPts % 2) )
    {
    fprintf(geomFile, "\n");
    }

  // write poly data. Remember 1-offset.
  for (inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); )
    {
    // write this polygon
    // treating vtkIdType as int
    for (i=0; i < (npts-1); i++)
      {
      fprintf (geomFile, "%d ", (int)(pts[i]+1));
      }
    fprintf (geomFile, "%d\n", (int)(-(pts[npts-1]+1)));
    }

  vtkDebugMacro(<<"Wrote " << numPts << " points, " << numPolys << " polygons");
}

void vtkBYUWriter::WriteDisplacementFile(int numPts)
{
  FILE *dispFp;
  int i;
  float *v;
  vtkDataArray *inVectors;
  vtkPolyData *input= this->GetInput();

  if ( this->WriteDisplacement && this->DisplacementFileName &&
  (inVectors = input->GetPointData()->GetVectors()) != NULL )
    {
    if ( !(dispFp = fopen(this->DisplacementFileName, "w")) )
      {
      vtkErrorMacro (<<"Couldn't open displacement file");
      return;
      }
    }
  else
    {
    return;
    }
  //
  // Write data
  //
  for (i=0; i < numPts; i++)
    {
    v = inVectors->GetTuple(i);
    fprintf(dispFp, "%e %e %e", v[0], v[1], v[2]);
    if ( (i % 2) )
      {
      fprintf (dispFp, "\n");
      }
    }

  vtkDebugMacro(<<"Wrote " << numPts << " displacements");
  fclose (dispFp);
}

void vtkBYUWriter::WriteScalarFile(int numPts)
{
  FILE *scalarFp;
  int i;
  float s;
  vtkDataArray *inScalars;
  vtkPolyData *input= this->GetInput();

  if ( this->WriteScalar && this->ScalarFileName &&
  (inScalars = input->GetPointData()->GetScalars()) != NULL )
    {
    if ( !(scalarFp = fopen(this->ScalarFileName, "w")) )
      {
      vtkErrorMacro (<<"Couldn't open scalar file");
      return;
      }
    }
  else
    {
    return;
    }
  //
  // Write data
  //
  for (i=0; i < numPts; i++)
    {
    s = inScalars->GetComponent(i,0);
    fprintf(scalarFp, "%e ", s);
    if ( i != 0 && !(i % 6) )
      {
      fprintf (scalarFp, "\n");
      }
    }

  fclose (scalarFp);
  vtkDebugMacro(<<"Wrote " << numPts << " scalars");
}

void vtkBYUWriter::WriteTextureFile(int numPts)
{
  FILE *textureFp;
  int i;
  float *t;
  vtkDataArray *inTCoords;
  vtkPolyData *input= this->GetInput();

  if ( this->WriteTexture && this->TextureFileName &&
  (inTCoords = input->GetPointData()->GetTCoords()) != NULL )
    {
    if ( !(textureFp = fopen(this->TextureFileName, "w")) )
      {
      vtkErrorMacro (<<"Couldn't open texture file");
      return;
      }
    }
  else
    {
    return;
    }
  //
  // Write data
  //
  for (i=0; i < numPts; i++)
    {
    if ( i != 0 && !(i % 3) )
      {
      fprintf (textureFp, "\n");
      }
    t = inTCoords->GetTuple(i);
    fprintf(textureFp, "%e %e", t[0], t[1]);
    }

  fclose (textureFp);
  vtkDebugMacro(<<"Wrote " << numPts << " texture coordinates");
}

void vtkBYUWriter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Geometry File Name: "
     << (this->GeometryFileName ? this->GeometryFileName : "(none)") << "\n";

  os << indent << "Write Displacement: " << (this->WriteDisplacement ? "On\n" : "Off\n");
  os << indent << "Displacement File Name: "
     << (this->DisplacementFileName ? this->DisplacementFileName : "(none)") << "\n";

  os << indent << "Write Scalar: " << (this->WriteScalar ? "On\n" : "Off\n");
  os << indent << "Scalar File Name: "
     << (this->ScalarFileName ? this->ScalarFileName : "(none)") << "\n";

  os << indent << "Write Texture: " << (this->WriteTexture ? "On\n" : "Off\n");
  os << indent << "Texture File Name: "
     << (this->TextureFileName ? this->TextureFileName : "(none)") << "\n";
}

<commit_msg>Add error checking<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkBYUWriter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkBYUWriter.h"
#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkBYUWriter, "1.43");
vtkStandardNewMacro(vtkBYUWriter);

// Create object so that it writes displacement, scalar, and texture files
// (if data is available).
vtkBYUWriter::vtkBYUWriter()
{
  this->GeometryFileName = NULL;
  this->DisplacementFileName = NULL;
  this->ScalarFileName = NULL;
  this->TextureFileName = NULL;

  this->WriteDisplacement = 1;
  this->WriteScalar = 1;
  this->WriteTexture = 1;
}

vtkBYUWriter::~vtkBYUWriter()
{
  if ( this->GeometryFileName )
    {
    delete [] this->GeometryFileName;
    }
  if ( this->DisplacementFileName )
    {
    delete [] this->DisplacementFileName;
    }
  if ( this->ScalarFileName )
    {
    delete [] this->ScalarFileName;
    }
  if ( this->TextureFileName )
    {
    delete [] this->TextureFileName;
    }
}

// Write out data in MOVIE.BYU format.
void vtkBYUWriter::WriteData()
{
  FILE *geomFp;
  vtkPolyData *input= this->GetInput();
  int numPts=input->GetNumberOfPoints();

  if ( numPts < 1 )
    {
    vtkErrorMacro(<<"No data to write!");
    return;
    }

  if ( !this->GeometryFileName )
    {
    vtkErrorMacro(<< "Geometry file name was not specified");
    return;
    }

  if ((geomFp = fopen(this->GeometryFileName, "w")) == NULL)
    {
    vtkErrorMacro(<< "Couldn't open geometry file: " << this->GeometryFileName);
    return;
    }
  else
    {
    this->WriteGeometryFile(geomFp,numPts);
    }

  this->WriteDisplacementFile(numPts);
  this->WriteScalarFile(numPts);
  this->WriteTextureFile(numPts);

  // Close the file
  fclose (geomFp);
}

void vtkBYUWriter::WriteGeometryFile(FILE *geomFile, int numPts)
{
  int numPolys, numEdges;
  int i;
  float *x;
  vtkIdType npts;
  vtkIdType *pts;
  vtkPoints *inPts;
  vtkCellArray *inPolys;
  vtkPolyData *input= this->GetInput();
  //
  // Check input
  //
  inPolys=input->GetPolys();
  if ( (inPts=input->GetPoints()) == NULL || inPolys == NULL )
    {
    vtkErrorMacro(<<"No data to write!");
    return;
    }
//
// Write header (not using fixed format! - potential problem in some files.)
//
  numPolys = input->GetPolys()->GetNumberOfCells();
  for (numEdges=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); )
    {
    numEdges += npts;
    }

  fprintf (geomFile, "%d %d %d %d\n", 1, numPts, numPolys, numEdges);
  fprintf (geomFile, "%d %d\n", 1, numPolys);
//
// Write data
//
  // write point coordinates
  for (i=0; i < numPts; i++)
    {
    x = inPts->GetPoint(i);
    fprintf(geomFile, "%e %e %e ", x[0], x[1], x[2]);
    if ( (i % 2) )
      {
      fprintf(geomFile, "\n");
      }
    }
  if ( (numPts % 2) )
    {
    fprintf(geomFile, "\n");
    }

  // write poly data. Remember 1-offset.
  for (inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); )
    {
    // write this polygon
    // treating vtkIdType as int
    for (i=0; i < (npts-1); i++)
      {
      fprintf (geomFile, "%d ", (int)(pts[i]+1));
      }
    fprintf (geomFile, "%d\n", (int)(-(pts[npts-1]+1)));
    }

  vtkDebugMacro(<<"Wrote " << numPts << " points, " << numPolys << " polygons");
}

void vtkBYUWriter::WriteDisplacementFile(int numPts)
{
  FILE *dispFp;
  int i;
  float *v;
  vtkDataArray *inVectors;
  vtkPolyData *input= this->GetInput();

  if ( this->WriteDisplacement && this->DisplacementFileName &&
  (inVectors = input->GetPointData()->GetVectors()) != NULL )
    {
    if ( !(dispFp = fopen(this->DisplacementFileName, "w")) )
      {
      vtkErrorMacro (<<"Couldn't open displacement file");
      return;
      }
    }
  else
    {
    return;
    }
  //
  // Write data
  //
  for (i=0; i < numPts; i++)
    {
    v = inVectors->GetTuple(i);
    fprintf(dispFp, "%e %e %e", v[0], v[1], v[2]);
    if ( (i % 2) )
      {
      fprintf (dispFp, "\n");
      }
    }

  vtkDebugMacro(<<"Wrote " << numPts << " displacements");
  fclose (dispFp);
}

void vtkBYUWriter::WriteScalarFile(int numPts)
{
  FILE *scalarFp;
  int i;
  float s;
  vtkDataArray *inScalars;
  vtkPolyData *input= this->GetInput();

  if ( this->WriteScalar && this->ScalarFileName &&
  (inScalars = input->GetPointData()->GetScalars()) != NULL )
    {
    if ( !(scalarFp = fopen(this->ScalarFileName, "w")) )
      {
      vtkErrorMacro (<<"Couldn't open scalar file");
      return;
      }
    }
  else
    {
    return;
    }
  //
  // Write data
  //
  for (i=0; i < numPts; i++)
    {
    s = inScalars->GetComponent(i,0);
    fprintf(scalarFp, "%e ", s);
    if ( i != 0 && !(i % 6) )
      {
      fprintf (scalarFp, "\n");
      }
    }

  fclose (scalarFp);
  vtkDebugMacro(<<"Wrote " << numPts << " scalars");
}

void vtkBYUWriter::WriteTextureFile(int numPts)
{
  FILE *textureFp;
  int i;
  float *t;
  vtkDataArray *inTCoords;
  vtkPolyData *input= this->GetInput();

  if ( this->WriteTexture && this->TextureFileName &&
  (inTCoords = input->GetPointData()->GetTCoords()) != NULL )
    {
    if ( !(textureFp = fopen(this->TextureFileName, "w")) )
      {
      vtkErrorMacro (<<"Couldn't open texture file");
      return;
      }
    }
  else
    {
    return;
    }
  //
  // Write data
  //
  for (i=0; i < numPts; i++)
    {
    if ( i != 0 && !(i % 3) )
      {
      fprintf (textureFp, "\n");
      }
    t = inTCoords->GetTuple(i);
    fprintf(textureFp, "%e %e", t[0], t[1]);
    }

  fclose (textureFp);
  vtkDebugMacro(<<"Wrote " << numPts << " texture coordinates");
}

void vtkBYUWriter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Geometry File Name: "
     << (this->GeometryFileName ? this->GeometryFileName : "(none)") << "\n";

  os << indent << "Write Displacement: " << (this->WriteDisplacement ? "On\n" : "Off\n");
  os << indent << "Displacement File Name: "
     << (this->DisplacementFileName ? this->DisplacementFileName : "(none)") << "\n";

  os << indent << "Write Scalar: " << (this->WriteScalar ? "On\n" : "Off\n");
  os << indent << "Scalar File Name: "
     << (this->ScalarFileName ? this->ScalarFileName : "(none)") << "\n";

  os << indent << "Write Texture: " << (this->WriteTexture ? "On\n" : "Off\n");
  os << indent << "Texture File Name: "
     << (this->TextureFileName ? this->TextureFileName : "(none)") << "\n";
}

<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "Framework.h"
#include "ModuleManager.h"
#include "ConfigurationManager.h"

namespace fs = boost::filesystem;

namespace Foundation
{
    ModuleManager::ModuleManager(Framework *framework) :
        framework_(framework)
      , DEFAULT_MODULES_PATH(framework->GetDefaultConfig().DeclareSetting("ModuleManager", "Default_Modules_Path", "./modules"))
    {
    }

    ModuleManager::~ModuleManager()
    {
    }

    void ModuleManager::DeclareStaticModule(ModuleInterface *module)
    {
        assert (module);
        if (IsExcluded(module->Name()) == false && HasModule(module) == false)
        {
            Module::Entry entry = { module, module->Name(), Module::SharedLibraryPtr() };
            modules_.push_back(entry);
#ifndef _DEBUG
                // make it so debug messages are not logged in release mode
                std::string log_level = framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "log_level");
                Poco::Logger::get(module->Name()).setLevel(log_level);
#endif
            module->SetFramework(framework_);
            module->LoadInternal();
        } else
        {
            Foundation::RootLogInfo("Module: " + module->Name() + " is excluded and not loaded.");
        }
    }

    void ModuleManager::LoadAvailableModules()
    {
        // Find all shared modules and load them
        Core::StringVectorPtr files;
        try
        {
            files = GetXmlFiles(DEFAULT_MODULES_PATH);
        } catch (Core::Exception)
        {
            throw Core::Exception("Failed to load modules, modules directory not found."); // can be considered fatal
        }

        for (size_t i = 0 ; i < files->size() ; ++i)
        {
            const fs::path path((*files)[i]);

            try
            {
                LoadModule(path, files);
            } catch (std::exception &e) // may not be fatal, depending on which module failed
            {
                Foundation::RootLogError(std::string("Exception: ") + e.what());
                Foundation::RootLogError("Failed to load module.");
            }
        }
    }

    void ModuleManager::InitializeModules()
    {
        for (size_t i=0 ; i<modules_.size() ; ++i)
        {
            PreInitializeModule(modules_[i].module_);
        }

        for (size_t i=0 ; i<modules_.size() ; ++i)
        {
            InitializeModule(modules_[i].module_);
        }

        for (size_t i=0 ; i<modules_.size() ; ++i)
        {
            PostInitializeModule(modules_[i].module_);
        }
    }

    void ModuleManager::UninitializeModules()
    {
        for (ModuleVector::reverse_iterator it = modules_.rbegin() ;
             it != modules_.rend() ;
             ++it)
        {
            UninitializeModule(it->module_);
        }
    }

    void ModuleManager::UpdateModules(Core::f64 frametime)
    {
        for (size_t i=0 ; i<modules_.size() ; ++i)
        {
            modules_[i].module_->Update(frametime);
        }
    }

    bool ModuleManager::LoadModuleByName(const std::string &lib, const std::string &module)
    {
        assert (lib.empty() == false);
        assert (module.empty() == false);

        Core::StringVector current_modules;
        for (size_t i = 0 ; i < modules_.size() ; ++i)
            current_modules.push_back(modules_[i].entry_);

        Core::StringVectorPtr files = GetXmlFiles(DEFAULT_MODULES_PATH);
        for (size_t i = 0 ; i < files->size() ; ++i)
        {
            fs::path path((*files)[i]);
            const fs::path orig_path = path;

            path.replace_extension("");
            std::string filename = path.filename();
            if (filename == lib)
            {
                LoadModule(orig_path, files);
                break;
            }
        }

        for (size_t i = 0 ; i < modules_.size() ; ++i)
        {
            if (modules_[i].module_->State() == Module::MS_Loaded && std::find(current_modules.begin(), current_modules.end(), modules_[i].entry_) == current_modules.end())
            {
                modules_[i].module_->PreInitialize();
                modules_[i].module_->InitializeInternal();
                modules_[i].module_->PostInitialize();

                if (modules_[i].entry_ == module)
                    return true;
            }
        }
        return false;
    }

    bool ModuleManager::UnloadModuleByName(const std::string &module)
    {
        for ( ModuleVector::iterator it = modules_.begin() ;
             it != modules_.end() ;
             ++it )
        {
            if (it->module_->Name() == module)
            {
                UninitializeModule(it->module_);
                UnloadModule(*it);
                modules_.erase(it);
                return true;
            }
        }

        return false;
    }

    void ModuleManager::LoadModule(const fs::path &path, Core::StringVectorPtr all_files)
    {
        assert (path.has_filename());

        std::string ext = path.extension();
        boost::algorithm::to_lower(ext);
        if (ext == ".xml")
        {
            Foundation::RootLogInfo("Attempting to load module definition file: " + path.file_string());
            fs::path modulePath(path);
            modulePath.replace_extension("");

            Core::StringVector entries;
            Core::StringVector dependencies;

            Poco::AutoPtr<Poco::Util::XMLConfiguration> config;
            try
            {
                config = new Poco::Util::XMLConfiguration(path.native_directory_string());
                Poco::Util::AbstractConfiguration::Keys keys;
	            config->keys(keys);

                for ( Poco::Util::AbstractConfiguration::Keys::const_iterator it = keys.begin() ;
                      it != keys.end() ;
                      it++ )
                {
                    if ((*it).find("entry") != std::string::npos)
                        entries.push_back( config->getString(*it) );

                   if ((*it).find("dependency") != std::string::npos)
                        dependencies.push_back( config->getString(*it) );
                }
            }
            catch(std::exception)
            {
            }

            if (entries.empty())
                entries.push_back(modulePath.filename());

            // Recurse to load dependencies (if any)
            for ( Core::StringVector::const_iterator it = dependencies.begin() ;
              it != dependencies.end() ; ++it )
            {
                bool found = false;
                // Try to find the dependency from the all module paths list
                for (Core::StringVector::const_iterator it2 = all_files->begin();
                    it2 != all_files->end(); ++it2)
                {
                    if ((*it2).find((*it)) != std::string::npos)
                    {
                        const fs::path path((*it2));
                        LoadModule(path, all_files);

                        found = true;
                    }
                }
                if (!found)
                    Foundation::RootLogWarning("Failed to find dependency " + *it + ".");
            }

            // Then load the module itself
            LoadModule(modulePath.native_directory_string(), entries);
        }
    }

    void ModuleManager::LoadModule(const std::string &moduleName, const Core::StringVector &entries)
    {
        assert(moduleName.empty() == false);

        std::string path(moduleName);
        path.append(Poco::SharedLibrary::suffix());

        Module::SharedLibraryPtr library;

        // See if shared library is already loaded, and if it is, use it
        for ( ModuleVector::const_iterator it = modules_.begin() ;
              it != modules_.end() ;
              ++it )
        {
            if (it->shared_library_ && it->shared_library_->path_ == path)
            {
                library = it->shared_library_;
            }
        }

        if (!library)
        {
            try
            {
                library = Module::SharedLibraryPtr(new Module::SharedLibrary(path));
            } catch (std::exception &e)
            {
                Foundation::RootLogError(e.what());
                Foundation::RootLogError("Failed to load dynamic library: " + moduleName + ".");
                return;
            }
        }

        for ( Core::StringVector::const_iterator it = entries.begin() ;
              it != entries.end() ;
              ++it )
        {
            if (HasModuleEntry(*it))
            {
                Foundation::RootLogDebug("Module " + *it + " already loaded.");
                continue;
            }

            Foundation::RootLogInfo("Attempting to load module: " + *it + ".");

            if (library->cl_.findClass(*it) == NULL)
            {
                throw Core::Exception("Entry class not found from module.");
            }

            ModuleInterface* module = library->cl_.create(*it);

            if (IsExcluded(module->Name()) == false)
            {
                assert (HasModule(module) == false);

#ifndef _DEBUG
                // make it so debug messages are not logged in release mode
                std::string log_level = framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "log_level");
                Poco::Logger::get(module->Name()).setLevel(log_level);
#endif

                module->SetFramework(framework_);
                module->LoadInternal();

                Module::Entry entry = { module, *it, library };

                modules_.push_back(entry);

                Foundation::RootLogInfo("Module " + *it + " loaded.");
            } else
            {
                Foundation::RootLogInfo("Module " + module->Name() + " is excluded and not loaded.");
                SAFE_DELETE (module);
            }
        }
    }

    void ModuleManager::UnloadModules()
    {
        for (ModuleVector::reverse_iterator it = modules_.rbegin() ;
             it != modules_.rend() ;
             ++it)
        {
            UnloadModule(*it);
        }

        modules_.clear();
        assert (modules_.empty());
    }

    void ModuleManager::PreInitializeModule(ModuleInterface *module)
    {
        assert(module);
        module->PreInitialize();
    }

    void ModuleManager::InitializeModule(ModuleInterface *module)
    {
        assert(module);
        Foundation::RootLogInfo("Initializing module " + module->Name() + ".");
        module->InitializeInternal();
    }

    void ModuleManager::PostInitializeModule(ModuleInterface *module)
    {
        assert(module);
        module->PostInitialize();
    }

    void ModuleManager::UninitializeModule(ModuleInterface *module)
    {
        assert(module);
        Foundation::RootLogInfo("Uninitializing module " + module->Name() + ".");
        module->UninitializeInternal();
    }

    void ModuleManager::UnloadModule(Module::Entry &entry)
    {
        assert(entry.module_);

        entry.module_->UnloadInternal();
        if (!entry.shared_library_)
        {
            delete entry.module_;
        }
        else
        {
            entry.shared_library_->cl_.destroy(entry.entry_, entry.module_);
            SAFE_DELETE(entry.module_);
        }
    }

    bool ModuleManager::HasModule(ModuleInterface *module) const
    {
        assert (module);

        for ( ModuleVector::const_iterator it = modules_.begin() ;
              it != modules_.end() ;
              ++it )
        {
            if (it->module_->Name() == module->Name())
                return true;
        }
        return false;
    }

    Core::StringVectorPtr ModuleManager::GetXmlFiles(const std::string &path)
    {
        Core::StringVectorPtr files(new Core::StringVector);

        // Find all xml files recursively
        fs::path full_path = fs::system_complete(fs::path(DEFAULT_MODULES_PATH));
        if ( !fs::exists( full_path ) || !fs::is_directory( full_path ))
            throw Core::Exception("Path not found!"); // can be considered fatal

        fs::recursive_directory_iterator iter( full_path );
        fs::recursive_directory_iterator end_iter;
        for ( ; iter != end_iter ; ++iter )
        {
            if ( fs::is_regular_file( iter->status() ) )
            {
                std::string ext = iter->path().extension();
                boost::algorithm::to_lower(ext);
                if (ext == ".xml")
                {
                    files->push_back(iter->path().string());
                }
            }
        }

        return files;
    }
}
<commit_msg>[FIX] Cleared out one memory leak --> added UnloadModules() into ModuleManager class destructor. Fix does not clear out all memory leaks. <commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "Framework.h"
#include "ModuleManager.h"
#include "ConfigurationManager.h"

namespace fs = boost::filesystem;

namespace Foundation
{
    ModuleManager::ModuleManager(Framework *framework) :
        framework_(framework)
      , DEFAULT_MODULES_PATH(framework->GetDefaultConfig().DeclareSetting("ModuleManager", "Default_Modules_Path", "./modules"))
    {
    }

    ModuleManager::~ModuleManager()
    {
		//Unload all loaded modules if object is truely destroyed.
		UnloadModules();
    }

    void ModuleManager::DeclareStaticModule(ModuleInterface *module)
    {
        assert (module);
        if (IsExcluded(module->Name()) == false && HasModule(module) == false)
        {
            Module::Entry entry = { module, module->Name(), Module::SharedLibraryPtr() };
            modules_.push_back(entry);
#ifndef _DEBUG
                // make it so debug messages are not logged in release mode
                std::string log_level = framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "log_level");
                Poco::Logger::get(module->Name()).setLevel(log_level);
#endif
            module->SetFramework(framework_);
            module->LoadInternal();
        } else
        {
            Foundation::RootLogInfo("Module: " + module->Name() + " is excluded and not loaded.");
        }
    }

    void ModuleManager::LoadAvailableModules()
    {
        // Find all shared modules and load them
        Core::StringVectorPtr files;
        try
        {
            files = GetXmlFiles(DEFAULT_MODULES_PATH);
        } catch (Core::Exception)
        {
            throw Core::Exception("Failed to load modules, modules directory not found."); // can be considered fatal
        }

        for (size_t i = 0 ; i < files->size() ; ++i)
        {
            const fs::path path((*files)[i]);

            try
            {
                LoadModule(path, files);
            } catch (std::exception &e) // may not be fatal, depending on which module failed
            {
                Foundation::RootLogError(std::string("Exception: ") + e.what());
                Foundation::RootLogError("Failed to load module.");
            }
        }
    }

    void ModuleManager::InitializeModules()
    {
        for (size_t i=0 ; i<modules_.size() ; ++i)
        {
            PreInitializeModule(modules_[i].module_);
        }

        for (size_t i=0 ; i<modules_.size() ; ++i)
        {
            InitializeModule(modules_[i].module_);
        }

        for (size_t i=0 ; i<modules_.size() ; ++i)
        {
            PostInitializeModule(modules_[i].module_);
        }
    }

    void ModuleManager::UninitializeModules()
    {
        for (ModuleVector::reverse_iterator it = modules_.rbegin() ;
             it != modules_.rend() ;
             ++it)
        {
            UninitializeModule(it->module_);
        }
    }

    void ModuleManager::UpdateModules(Core::f64 frametime)
    {
        for (size_t i=0 ; i<modules_.size() ; ++i)
        {
            modules_[i].module_->Update(frametime);
        }
    }

    bool ModuleManager::LoadModuleByName(const std::string &lib, const std::string &module)
    {
        assert (lib.empty() == false);
        assert (module.empty() == false);

        Core::StringVector current_modules;
        for (size_t i = 0 ; i < modules_.size() ; ++i)
            current_modules.push_back(modules_[i].entry_);

        Core::StringVectorPtr files = GetXmlFiles(DEFAULT_MODULES_PATH);
        for (size_t i = 0 ; i < files->size() ; ++i)
        {
            fs::path path((*files)[i]);
            const fs::path orig_path = path;

            path.replace_extension("");
            std::string filename = path.filename();
            if (filename == lib)
            {
                LoadModule(orig_path, files);
                break;
            }
        }

        for (size_t i = 0 ; i < modules_.size() ; ++i)
        {
            if (modules_[i].module_->State() == Module::MS_Loaded && std::find(current_modules.begin(), current_modules.end(), modules_[i].entry_) == current_modules.end())
            {
                modules_[i].module_->PreInitialize();
                modules_[i].module_->InitializeInternal();
                modules_[i].module_->PostInitialize();

                if (modules_[i].entry_ == module)
                    return true;
            }
        }
        return false;
    }

    bool ModuleManager::UnloadModuleByName(const std::string &module)
    {
        for ( ModuleVector::iterator it = modules_.begin() ;
             it != modules_.end() ;
             ++it )
        {
            if (it->module_->Name() == module)
            {
                UninitializeModule(it->module_);
                UnloadModule(*it);
                modules_.erase(it);
                return true;
            }
        }

        return false;
    }

    void ModuleManager::LoadModule(const fs::path &path, Core::StringVectorPtr all_files)
    {
        assert (path.has_filename());

        std::string ext = path.extension();
        boost::algorithm::to_lower(ext);
        if (ext == ".xml")
        {
            Foundation::RootLogInfo("Attempting to load module definition file: " + path.file_string());
            fs::path modulePath(path);
            modulePath.replace_extension("");

            Core::StringVector entries;
            Core::StringVector dependencies;

            Poco::AutoPtr<Poco::Util::XMLConfiguration> config;
            try
            {
                config = new Poco::Util::XMLConfiguration(path.native_directory_string());
                Poco::Util::AbstractConfiguration::Keys keys;
	            config->keys(keys);

                for ( Poco::Util::AbstractConfiguration::Keys::const_iterator it = keys.begin() ;
                      it != keys.end() ;
                      it++ )
                {
                    if ((*it).find("entry") != std::string::npos)
                        entries.push_back( config->getString(*it) );

                   if ((*it).find("dependency") != std::string::npos)
                        dependencies.push_back( config->getString(*it) );
                }
            }
            catch(std::exception)
            {
            }

            if (entries.empty())
                entries.push_back(modulePath.filename());

            // Recurse to load dependencies (if any)
            for ( Core::StringVector::const_iterator it = dependencies.begin() ;
              it != dependencies.end() ; ++it )
            {
                bool found = false;
                // Try to find the dependency from the all module paths list
                for (Core::StringVector::const_iterator it2 = all_files->begin();
                    it2 != all_files->end(); ++it2)
                {
                    if ((*it2).find((*it)) != std::string::npos)
                    {
                        const fs::path path((*it2));
                        LoadModule(path, all_files);

                        found = true;
                    }
                }
                if (!found)
                    Foundation::RootLogWarning("Failed to find dependency " + *it + ".");
            }

            // Then load the module itself
            LoadModule(modulePath.native_directory_string(), entries);
        }
    }

    void ModuleManager::LoadModule(const std::string &moduleName, const Core::StringVector &entries)
    {
        assert(moduleName.empty() == false);

        std::string path(moduleName);
        path.append(Poco::SharedLibrary::suffix());

        Module::SharedLibraryPtr library;

        // See if shared library is already loaded, and if it is, use it
        for ( ModuleVector::const_iterator it = modules_.begin() ;
              it != modules_.end() ;
              ++it )
        {
            if (it->shared_library_ && it->shared_library_->path_ == path)
            {
                library = it->shared_library_;
            }
        }

        if (!library)
        {
            try
            {
                library = Module::SharedLibraryPtr(new Module::SharedLibrary(path));
            } catch (std::exception &e)
            {
                Foundation::RootLogError(e.what());
                Foundation::RootLogError("Failed to load dynamic library: " + moduleName + ".");
                return;
            }
        }

        for ( Core::StringVector::const_iterator it = entries.begin() ;
              it != entries.end() ;
              ++it )
        {
            if (HasModuleEntry(*it))
            {
                Foundation::RootLogDebug("Module " + *it + " already loaded.");
                continue;
            }

            Foundation::RootLogInfo("Attempting to load module: " + *it + ".");

            if (library->cl_.findClass(*it) == NULL)
            {
                throw Core::Exception("Entry class not found from module.");
            }

            ModuleInterface* module = library->cl_.create(*it);

            if (IsExcluded(module->Name()) == false)
            {
                assert (HasModule(module) == false);

#ifndef _DEBUG
                // make it so debug messages are not logged in release mode
                std::string log_level = framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "log_level");
                Poco::Logger::get(module->Name()).setLevel(log_level);
#endif

                module->SetFramework(framework_);
                module->LoadInternal();

                Module::Entry entry = { module, *it, library };

                modules_.push_back(entry);

                Foundation::RootLogInfo("Module " + *it + " loaded.");
            } else
            {
                Foundation::RootLogInfo("Module " + module->Name() + " is excluded and not loaded.");
                SAFE_DELETE (module);
            }
        }
    }

    void ModuleManager::UnloadModules()
    {
        for (ModuleVector::reverse_iterator it = modules_.rbegin() ;
             it != modules_.rend() ;
             ++it)
        {
            UnloadModule(*it);
        }

        modules_.clear();
        assert (modules_.empty());
    }

    void ModuleManager::PreInitializeModule(ModuleInterface *module)
    {
        assert(module);
        module->PreInitialize();
    }

    void ModuleManager::InitializeModule(ModuleInterface *module)
    {
        assert(module);
        Foundation::RootLogInfo("Initializing module " + module->Name() + ".");
        module->InitializeInternal();
    }

    void ModuleManager::PostInitializeModule(ModuleInterface *module)
    {
        assert(module);
        module->PostInitialize();
    }

    void ModuleManager::UninitializeModule(ModuleInterface *module)
    {
        assert(module);
        Foundation::RootLogInfo("Uninitializing module " + module->Name() + ".");
        module->UninitializeInternal();
    }

    void ModuleManager::UnloadModule(Module::Entry &entry)
    {
        assert(entry.module_);

        entry.module_->UnloadInternal();
        if (!entry.shared_library_)
        {
            delete entry.module_;
        }
        else
        {
            entry.shared_library_->cl_.destroy(entry.entry_, entry.module_);
            SAFE_DELETE(entry.module_);
        }
    }

    bool ModuleManager::HasModule(ModuleInterface *module) const
    {
        assert (module);

        for ( ModuleVector::const_iterator it = modules_.begin() ;
              it != modules_.end() ;
              ++it )
        {
            if (it->module_->Name() == module->Name())
                return true;
        }
        return false;
    }

    Core::StringVectorPtr ModuleManager::GetXmlFiles(const std::string &path)
    {
        Core::StringVectorPtr files(new Core::StringVector);

        // Find all xml files recursively
        fs::path full_path = fs::system_complete(fs::path(DEFAULT_MODULES_PATH));
        if ( !fs::exists( full_path ) || !fs::is_directory( full_path ))
            throw Core::Exception("Path not found!"); // can be considered fatal

        fs::recursive_directory_iterator iter( full_path );
        fs::recursive_directory_iterator end_iter;
        for ( ; iter != end_iter ; ++iter )
        {
            if ( fs::is_regular_file( iter->status() ) )
            {
                std::string ext = iter->path().extension();
                boost::algorithm::to_lower(ext);
                if (ext == ".xml")
                {
                    files->push_back(iter->path().string());
                }
            }
        }

        return files;
    }
}
<|endoftext|>


<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2004
*
*This library is free software; you can redistribute it and/or
*modify it under the terms of the GNU Lesser General Public
*License as published by the Free Software Foundation; either
*version 2.1 of the License, or (at your option) any later version.
*
*This library is distributed in the hope that it will be useful,
*but WITHOUT ANY WARRANTY; without even the implied warranty of
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*Lesser General Public License for more details.
*
*You should have received a copy of the GNU Lesser General Public
*License along with this library; if not, write to the Free Software
*Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: taskStaticContainer.cpp,v 1.14 2006/10/09 09:08:03 bjeram Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* bjeram  2004-09-27  created
*/

#include <acsContainerServices.h>
#include "taskStaticContainer.h"
#include "taskComponentS.h"
#include <acscomponentImpl.h>
#include <maciContainerServices.h>
#include "taskStaticContainerServices.h"

#ifdef _TASK_LIB
extern "C" PortableServer::Servant ConstructComponent(  maci::Handle h,
							const char * name,
							const char * type,
							maci::ContainerServices * containerServices
    );

#endif //_TASK_LIB

StaticContainer::StaticContainer():
    m_logger(0), services_m(true)
{
}

void StaticContainer::initCORBA(int &argc, char **argv)
{
    ACE_TRACE("StaticContainer::initCORBA");

    try
	{
	orb_m = CORBA::ORB_init(argc, argv);
	if(orb_m.ptr() == CORBA::ORB::_nil())
	    return; //TBD: EH

	CORBA::Object_var objRootPOA =
	    orb_m->resolve_initial_references("RootPOA");
	poaRoot_m = PortableServer::POA::_narrow(objRootPOA.in());
	if (poaRoot_m.ptr() == PortableServer::POA::_nil())
	    return; //TBD: EH
	poaManager_m = poaRoot_m->the_POAManager();

	PortableServer::IdAssignmentPolicy_var user_id_policy =
	    poaRoot_m->create_id_assignment_policy(PortableServer::USER_ID);

	CORBA::PolicyList policies;
	policies.length(1);
	policies[0] = PortableServer::IdAssignmentPolicy::_duplicate(user_id_policy.in());

	componentPOA_m = poaRoot_m->create_POA("ContainerPOA",
					 poaManager_m.in(),
					 policies);
	if (componentPOA_m.ptr() == PortableServer::POA::_nil())
	    return;  //TBD: EH

	user_id_policy->destroy();

	poaManager_m->activate();
	}
    catch(...)
	{
	printf("exception in initCORBA\n");
	}
}

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

void StaticContainer::doneCORBA()
{
    ACE_TRACE("StaticContainer::doneCORBA");
    try
	{

	if(poaRoot_m.ptr() != PortableServer::POA::_nil())
	    {
	    poaRoot_m->destroy(1, 1);
	    }

	if(orb_m.ptr() != CORBA::ORB::_nil())
	    {
	    orb_m->destroy();
	    }
	}
    catch(CORBA::Exception &ex)
	{
	ex._tao_print_exception ("occured in StaticContainer::doneCORBA");
	}
    catch(...)
	{
	ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::doneCORBA",
		(LM_ERROR, "Unexpected exception"));
	}
}

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

void StaticContainer::init(int argc, char **argv, const char *containerName)
{
    if ( containerName!=0 && ACE_OS::strlen(containerName)!=0 )
	{
	containerName_m = containerName;
	}
    else
	{
	ACE_Time_Value tv = ACE_OS::gettimeofday();
	char timeBuf[25];
	sprintf(timeBuf, "%ld", tv.sec());

	containerName_m += "Container-";
	containerName_m += timeBuf;
	}//if-else
//TBD: container name from cmd line

   containerArgv.add(argv[0]);
   containerArgv.add(containerName_m.c_str()); //first comes container name

    for(int i=1; i<argc; i++)
	{
	if (ACE_OS::strcmp(argv[i], "-nosvcs") == 0)
	    {
	    services_m = false;
	    }
	else
	    {
	    containerArgv.add(argv[i]);
	    ACE_OS::printf("argv[%d]=%s\n", i, argv[i]);
	    }///if

	}//for

    try
	{
	if ((services_m == true) && container_m.init(containerArgv.argc(), containerArgv.argv())==true )
	    {
		container_m.connect(); //error handling
		services_m = true;
		componentPOA_m = container_m.getContainerPOA();
	        orb_m = container_m.getContainerORB();
	    }
	else
	    {
	    services_m = false;
	    m_logger = new LoggingProxy(0, 0, 31);
	    LoggingProxy::init (m_logger);
	    ACSError::init();
	    initCORBA(argc, argv);
	    }//if-else
	}
    catch(...)
	{
	ACS_LOG(LM_RUNTIME_CONTEXT, "StaicContainer::init", (LM_ERROR, "unknown exception"));
	}
}

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

void StaticContainer::done()
{
    ACE_TRACE("StaticContainer::done");
if ( services_m == true)
    {
/*	    ACS_DEBUG_PARAM("main", "deactivating the component %s", componentName.c_str());
	    servant->_remove_ref();
	    container.deactivateCORBAObject(obj);
*/
    container_m.shutdown(CONTAINER_EXIT << 8);
    container_m.done();
    }
else
    {
/*	    ACS_DEBUG_PARAM("main", "deleting the component %s", argv[1]);
*/
    doneCORBA();
    m_logger->flush();
    LoggingProxy::done();
    delete m_logger;
    ACS_TRACE("szxsadasdasd");
    ACSError::done();
    }
}
/*****************************************************************************/

CORBA::Object_ptr StaticContainer::createComponentWithName(const char *name)
{
    const char *libname;
    if ( ACE_OS::strlen(name) == 0 )
	{
#ifndef _TASK_LIB
	ACS_LOG(LM_RUNTIME_CONTEXT, "StaticComponenet::createComponentWithName",
		    (LM_ERROR, "component could not be created just with name (name of library needed)"));
	return CORBA::Object::_nil();
#else
	ACE_CString compName = "Component-";
	ACE_Time_Value tv = ACE_OS::gettimeofday();
	char timeBuf[25];
	sprintf(timeBuf, "%ld", tv.sec());
	compName+=timeBuf;

	libname = 0; // here libray name can be  NULL since the library is linked by linker and nota loaded on demand

	return createComponent(compName.c_str(), libname);
#endif
	}
    else
	{
	// reteive libname from CDB
	libname = "SDFSDS";
	return createComponent(name, libname);
	}
}
/*****************************************************************************/

CORBA::Object_ptr StaticContainer::createComponent(const char *libname)
{
    ACE_CString compName = "Component-";
    ACE_Time_Value tv = ACE_OS::gettimeofday();
    char timeBuf[25];
    sprintf(timeBuf, "%ld", tv.sec());
    compName+=timeBuf;

    return createComponent(compName.c_str(), libname);
}

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

CORBA::Object_ptr StaticContainer::createComponent(const char* compName, const char *libname)
    {
     CORBA::Object_var obj = CORBA::Object::_nil();
     ACE_CString cn = "Component-";

     ACE_TRACE("StaticContainer::createComponent");
     if ( ACE_OS::strlen(compName)!=0 )
	 {
#ifndef _TASK_LIB
	 if (ACE_OS::strlen(libname)==0)
	     {
	     if (services_m == true )
		 {
		 // try to read libname  from CDB
		 }
	     else
		 {
		 ACS_LOG(LM_RUNTIME_CONTEXT, "StaticComponenet::createComponent",
		    (LM_ERROR, "component could not be created w/o providing library name"));
		 return obj._retn();
		 }
	     }
#endif
	 }
     else
	 {
#ifndef _TASK_LIB
	 if (ACE_OS::strlen(libname) == 0 )
	     {
	     ACS_LOG(LM_RUNTIME_CONTEXT, "StaticComponenet::createComponent",
		     (LM_ERROR, "component could not be created w/o providing library name"));
	     return obj._retn();
	     }
#endif
	 // create unique component name
	 ACE_Time_Value tv = ACE_OS::gettimeofday();
	 char timeBuf[25];
	 sprintf(timeBuf, "%ld", tv.sec());
	 cn+=timeBuf;
	 compName = cn.c_str();
	 }

#ifndef _TASK_LIB
    if (services_m==true) // if we have services (i.e. also the manager) we can create and activate the component by using concept of dynamic component
     {
     ACS_DEBUG("StaticContainer::createComponent", "Activating component");

     ComponentSpec_var compSpec = new ComponentSpec();
     compSpec->component_name = CORBA::string_dup(compName);
     compSpec->component_type = CORBA::string_dup("IDL:alma/ACS/Task:1.0"); //TBD:: IFR ?
     compSpec->component_code = CORBA::string_dup(libname);
     compSpec->container_name = CORBA::string_dup(containerName_m.c_str());
/// @todo  get_dynamic_component can throw an exception which should be caught!
     ComponentInfo_var compInfo  =
	 container_m.getManager()->get_dynamic_component(container_m.getHandle(),
							 compSpec.in(),
							 false);
     // at this point we have done everything so we can return
     return compInfo->reference._retn();
     }//if

    // otherwise we have to load the library and find ConstructComponent function in the library
    ACS_DEBUG_PARAM("StaticContainer::createComponent", "loading library: %s", libname);
    ACE_CString strDLLPath(ACE_OS::getenv ("LD_LIBRARY_PATH"));
    dllmgr_m.setSearchPath(strDLLPath.c_str());

    int libHandle = 0;

    libHandle = dllmgr_m.load(libname);

    if (libHandle == 0)
	{
	printf("error loading the library\n");
	return 0; // -1;
	}

    ACS_DEBUG_PARAM("StaticContainer::createComponent", "Library: %s has been loaded", libname);

    ConstructComponentFunc ConstructComponent =
	(ConstructComponentFunc)(dllmgr_m.getSymbol(libHandle, "ConstructComponent"));
    if (ConstructComponent == 0)
	{
	printf("error finding the constructor for the component\n");
	return 0;// -1;
	}
#endif //!_TASK_LIB

    ACS_DEBUG_PARAM("StaticContainer::createComponent", "Creating component: %s", compName);
    ContainerServices* acsCS = 0;
    ACE_CString cmpName(compName);

    if (services_m == true)
	{
	acsCS =   new MACIContainerServices(0/*handel*/, cmpName, container_m.getContainerPOA().in());
	if (acsCS==0)
	    {
	    ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::createComponent",
		    (LM_ERROR,  "Error creating the ContainerServices"));
	    return 0;
	    }
	}
    else
	{

	acsCS =   new StaticContainerServices(0/*handel*/, cmpName, container_m.getContainerPOA().in(), orb_m.in());
	if (acsCS==0)
	    {
	    ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::createComponent",
		    (LM_ERROR,  "Error creating the ContainerServices"));
	    return 0;
	    }
	}

    PortableServer::Servant servant = ConstructComponent(0/*handel*/, compName, "ANY", acsCS);
    if (servant == 0)
	{
	printf("error constructing the component\n");
	return 0;// -1;
	}

       // life cycle
    ACS_DEBUG("StaticContainer::createComponent", "Component Life Cycle");
    acscomponent::ACSComponentImpl *acsComponent =
	dynamic_cast<acscomponent::ACSComponentImpl*>(servant);

    acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_INITIALIZING);
    acsComponent->__initialize();
    acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_INITIALIZED);
    acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_OPERATIONAL);
    acsComponent->__execute();

    ACS_DEBUG("StaticContainer::createComponent", "Activating the component");

    try
	{
	if (services_m==true )
	    {
	    obj = container_m.activateCORBAObject(servant, componentName_m.c_str());
	    }
	else
	    {

	    PortableServer::ObjectId_var id =
		PortableServer::string_to_ObjectId(componentName_m.c_str());

	    componentPOA_m->activate_object_with_id(id.in(), servant);

	    obj = componentPOA_m->servant_to_reference(servant);

	    servant->_remove_ref();
	    }
	}
    catch(CORBA::Exception &ex)
	{
	 ex._tao_print_exception ("occured");
	 return CORBA::Object::_nil();
	}
    return obj._retn();
}//createComponent

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

void StaticContainer::destroyComponent(CORBA::Object_ptr obj)
{
    ACS::ACSComponent_var acscomp;
    try
	{
	acscomp = ACS::ACSComponent::_narrow(obj);
	if ( acscomp.ptr() == ACS::ACSComponent::_nil() )
	    {
	    }
	}
    catch(...)
	{
	}
#ifndef _TASK_LIB
    if ( services_m == true )
	{
	ACE_CString compNam = acscomp->name();
	ACS_DEBUG_PARAM("StaticContainer::destroyComponent", "releasing the component %s via the manager", compNam.c_str());
	container_m.getManager()->release_component(container_m.getHandle(), acscomp->name());
	return;
	}
#endif  // !_TASK_LIB

    PortableServer::Servant servant;
    servant = componentPOA_m->reference_to_servant(obj);

 // life cycle
    ACS_DEBUG("StaticContainer::destroyComponent", "Component Life Cycle");
    acscomponent::ACSComponentImpl *acsComponent =
	dynamic_cast<acscomponent::ACSComponentImpl*>(servant);
    acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_DESTROYING);
    acsComponent->__cleanUp();
    acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_DEFUNCT);
// ContainerServices is deleted in the destructor of ComponentImpl

    if ( services_m == true)
	{
	ACS_DEBUG_PARAM("StaticContainer::destroyComponent", "deactivating the component %s", acscomp->name());
	container_m.deactivateCORBAObject(obj);
	}
    else
	{
	ACS_DEBUG_PARAM("StaticContainer::destroyComponent", "deleting the component %s", acscomp->name());
	servant->_remove_ref();
	}//if-else
}//destroyComponenet

/*___oOo___*/

<commit_msg>Replaced non portable comparing with _nil() with CORBA::is_nil(x)<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2004
*
*This library is free software; you can redistribute it and/or
*modify it under the terms of the GNU Lesser General Public
*License as published by the Free Software Foundation; either
*version 2.1 of the License, or (at your option) any later version.
*
*This library is distributed in the hope that it will be useful,
*but WITHOUT ANY WARRANTY; without even the implied warranty of
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
*Lesser General Public License for more details.
*
*You should have received a copy of the GNU Lesser General Public
*License along with this library; if not, write to the Free Software
*Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: taskStaticContainer.cpp,v 1.15 2008/07/15 06:44:51 bjeram Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* bjeram  2004-09-27  created
*/

#include <acsContainerServices.h>
#include "taskStaticContainer.h"
#include "taskComponentS.h"
#include <acscomponentImpl.h>
#include <maciContainerServices.h>
#include "taskStaticContainerServices.h"

#ifdef _TASK_LIB
extern "C" PortableServer::Servant ConstructComponent(  maci::Handle h,
							const char * name,
							const char * type,
							maci::ContainerServices * containerServices
    );

#endif //_TASK_LIB

StaticContainer::StaticContainer():
    m_logger(0), services_m(true)
{
}

void StaticContainer::initCORBA(int &argc, char **argv)
{
    ACE_TRACE("StaticContainer::initCORBA");

    try
	{
	orb_m = CORBA::ORB_init(argc, argv);
	if(CORBA::is_nil(orb_m.ptr()))
	    return; //TBD: EH

	CORBA::Object_var objRootPOA =
	    orb_m->resolve_initial_references("RootPOA");
	poaRoot_m = PortableServer::POA::_narrow(objRootPOA.in());
	if (CORBA::is_nil(poaRoot_m.ptr()))
	    return; //TBD: EH
	poaManager_m = poaRoot_m->the_POAManager();

	PortableServer::IdAssignmentPolicy_var user_id_policy =
	    poaRoot_m->create_id_assignment_policy(PortableServer::USER_ID);

	CORBA::PolicyList policies;
	policies.length(1);
	policies[0] = PortableServer::IdAssignmentPolicy::_duplicate(user_id_policy.in());

	componentPOA_m = poaRoot_m->create_POA("ContainerPOA",
					 poaManager_m.in(),
					 policies);
	if (CORBA::is_nil(componentPOA_m.ptr()))
	    return;  //TBD: EH

	user_id_policy->destroy();

	poaManager_m->activate();
	}
    catch(...)
	{
	printf("exception in initCORBA\n");
	}
}

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

void StaticContainer::doneCORBA()
{
    ACE_TRACE("StaticContainer::doneCORBA");
    try
	{

	if(poaRoot_m.ptr() != PortableServer::POA::_nil())
	    {
	    poaRoot_m->destroy(1, 1);
	    }

	if(orb_m.ptr() != CORBA::ORB::_nil())
	    {
	    orb_m->destroy();
	    }
	}
    catch(CORBA::Exception &ex)
	{
	ex._tao_print_exception ("occured in StaticContainer::doneCORBA");
	}
    catch(...)
	{
	ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::doneCORBA",
		(LM_ERROR, "Unexpected exception"));
	}
}

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

void StaticContainer::init(int argc, char **argv, const char *containerName)
{
    if ( containerName!=0 && ACE_OS::strlen(containerName)!=0 )
	{
	containerName_m = containerName;
	}
    else
	{
	ACE_Time_Value tv = ACE_OS::gettimeofday();
	char timeBuf[25];
	sprintf(timeBuf, "%ld", tv.sec());

	containerName_m += "Container-";
	containerName_m += timeBuf;
	}//if-else
//TBD: container name from cmd line

   containerArgv.add(argv[0]);
   containerArgv.add(containerName_m.c_str()); //first comes container name

    for(int i=1; i<argc; i++)
	{
	if (ACE_OS::strcmp(argv[i], "-nosvcs") == 0)
	    {
	    services_m = false;
	    }
	else
	    {
	    containerArgv.add(argv[i]);
	    ACE_OS::printf("argv[%d]=%s\n", i, argv[i]);
	    }///if

	}//for

    try
	{
	if ((services_m == true) && container_m.init(containerArgv.argc(), containerArgv.argv())==true )
	    {
		container_m.connect(); //error handling
		services_m = true;
		componentPOA_m = container_m.getContainerPOA();
	        orb_m = container_m.getContainerORB();
	    }
	else
	    {
	    services_m = false;
	    m_logger = new LoggingProxy(0, 0, 31);
	    LoggingProxy::init (m_logger);
	    ACSError::init();
	    initCORBA(argc, argv);
	    }//if-else
	}
    catch(...)
	{
	ACS_LOG(LM_RUNTIME_CONTEXT, "StaicContainer::init", (LM_ERROR, "unknown exception"));
	}
}

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

void StaticContainer::done()
{
    ACE_TRACE("StaticContainer::done");
if ( services_m == true)
    {
/*	    ACS_DEBUG_PARAM("main", "deactivating the component %s", componentName.c_str());
	    servant->_remove_ref();
	    container.deactivateCORBAObject(obj);
*/
    container_m.shutdown(CONTAINER_EXIT << 8);
    container_m.done();
    }
else
    {
/*	    ACS_DEBUG_PARAM("main", "deleting the component %s", argv[1]);
*/
    doneCORBA();
    m_logger->flush();
    LoggingProxy::done();
    delete m_logger;
    ACS_TRACE("szxsadasdasd");
    ACSError::done();
    }
}
/*****************************************************************************/

CORBA::Object_ptr StaticContainer::createComponentWithName(const char *name)
{
    const char *libname;
    if ( ACE_OS::strlen(name) == 0 )
	{
#ifndef _TASK_LIB
	ACS_LOG(LM_RUNTIME_CONTEXT, "StaticComponenet::createComponentWithName",
		    (LM_ERROR, "component could not be created just with name (name of library needed)"));
	return CORBA::Object::_nil();
#else
	ACE_CString compName = "Component-";
	ACE_Time_Value tv = ACE_OS::gettimeofday();
	char timeBuf[25];
	sprintf(timeBuf, "%ld", tv.sec());
	compName+=timeBuf;

	libname = 0; // here libray name can be  NULL since the library is linked by linker and nota loaded on demand

	return createComponent(compName.c_str(), libname);
#endif
	}
    else
	{
	// reteive libname from CDB
	libname = "SDFSDS";
	return createComponent(name, libname);
	}
}
/*****************************************************************************/

CORBA::Object_ptr StaticContainer::createComponent(const char *libname)
{
    ACE_CString compName = "Component-";
    ACE_Time_Value tv = ACE_OS::gettimeofday();
    char timeBuf[25];
    sprintf(timeBuf, "%ld", tv.sec());
    compName+=timeBuf;

    return createComponent(compName.c_str(), libname);
}

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

CORBA::Object_ptr StaticContainer::createComponent(const char* compName, const char *libname)
    {
     CORBA::Object_var obj = CORBA::Object::_nil();
     ACE_CString cn = "Component-";

     ACE_TRACE("StaticContainer::createComponent");
     if ( ACE_OS::strlen(compName)!=0 )
	 {
#ifndef _TASK_LIB
	 if (ACE_OS::strlen(libname)==0)
	     {
	     if (services_m == true )
		 {
		 // try to read libname  from CDB
		 }
	     else
		 {
		 ACS_LOG(LM_RUNTIME_CONTEXT, "StaticComponenet::createComponent",
		    (LM_ERROR, "component could not be created w/o providing library name"));
		 return obj._retn();
		 }
	     }
#endif
	 }
     else
	 {
#ifndef _TASK_LIB
	 if (ACE_OS::strlen(libname) == 0 )
	     {
	     ACS_LOG(LM_RUNTIME_CONTEXT, "StaticComponenet::createComponent",
		     (LM_ERROR, "component could not be created w/o providing library name"));
	     return obj._retn();
	     }
#endif
	 // create unique component name
	 ACE_Time_Value tv = ACE_OS::gettimeofday();
	 char timeBuf[25];
	 sprintf(timeBuf, "%ld", tv.sec());
	 cn+=timeBuf;
	 compName = cn.c_str();
	 }

#ifndef _TASK_LIB
    if (services_m==true) // if we have services (i.e. also the manager) we can create and activate the component by using concept of dynamic component
     {
     ACS_DEBUG("StaticContainer::createComponent", "Activating component");

     ComponentSpec_var compSpec = new ComponentSpec();
     compSpec->component_name = CORBA::string_dup(compName);
     compSpec->component_type = CORBA::string_dup("IDL:alma/ACS/Task:1.0"); //TBD:: IFR ?
     compSpec->component_code = CORBA::string_dup(libname);
     compSpec->container_name = CORBA::string_dup(containerName_m.c_str());
/// @todo  get_dynamic_component can throw an exception which should be caught!
     ComponentInfo_var compInfo  =
	 container_m.getManager()->get_dynamic_component(container_m.getHandle(),
							 compSpec.in(),
							 false);
     // at this point we have done everything so we can return
     return compInfo->reference._retn();
     }//if

    // otherwise we have to load the library and find ConstructComponent function in the library
    ACS_DEBUG_PARAM("StaticContainer::createComponent", "loading library: %s", libname);
    ACE_CString strDLLPath(ACE_OS::getenv ("LD_LIBRARY_PATH"));
    dllmgr_m.setSearchPath(strDLLPath.c_str());

    int libHandle = 0;

    libHandle = dllmgr_m.load(libname);

    if (libHandle == 0)
	{
	printf("error loading the library\n");
	return 0; // -1;
	}

    ACS_DEBUG_PARAM("StaticContainer::createComponent", "Library: %s has been loaded", libname);

    ConstructComponentFunc ConstructComponent =
	(ConstructComponentFunc)(dllmgr_m.getSymbol(libHandle, "ConstructComponent"));
    if (ConstructComponent == 0)
	{
	printf("error finding the constructor for the component\n");
	return 0;// -1;
	}
#endif //!_TASK_LIB

    ACS_DEBUG_PARAM("StaticContainer::createComponent", "Creating component: %s", compName);
    ContainerServices* acsCS = 0;
    ACE_CString cmpName(compName);

    if (services_m == true)
	{
	acsCS =   new MACIContainerServices(0/*handel*/, cmpName, container_m.getContainerPOA().in());
	if (acsCS==0)
	    {
	    ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::createComponent",
		    (LM_ERROR,  "Error creating the ContainerServices"));
	    return 0;
	    }
	}
    else
	{

	acsCS =   new StaticContainerServices(0/*handel*/, cmpName, container_m.getContainerPOA().in(), orb_m.in());
	if (acsCS==0)
	    {
	    ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::createComponent",
		    (LM_ERROR,  "Error creating the ContainerServices"));
	    return 0;
	    }
	}

    PortableServer::Servant servant = ConstructComponent(0/*handel*/, compName, "ANY", acsCS);
    if (servant == 0)
	{
	printf("error constructing the component\n");
	return 0;// -1;
	}

       // life cycle
    ACS_DEBUG("StaticContainer::createComponent", "Component Life Cycle");
    acscomponent::ACSComponentImpl *acsComponent =
	dynamic_cast<acscomponent::ACSComponentImpl*>(servant);

    acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_INITIALIZING);
    acsComponent->__initialize();
    acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_INITIALIZED);
    acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_OPERATIONAL);
    acsComponent->__execute();

    ACS_DEBUG("StaticContainer::createComponent", "Activating the component");

    try
	{
	if (services_m==true )
	    {
	    obj = container_m.activateCORBAObject(servant, componentName_m.c_str());
	    }
	else
	    {

	    PortableServer::ObjectId_var id =
		PortableServer::string_to_ObjectId(componentName_m.c_str());

	    componentPOA_m->activate_object_with_id(id.in(), servant);

	    obj = componentPOA_m->servant_to_reference(servant);

	    servant->_remove_ref();
	    }
	}
    catch(CORBA::Exception &ex)
	{
	 ex._tao_print_exception ("occured");
	 return CORBA::Object::_nil();
	}
    return obj._retn();
}//createComponent

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

void StaticContainer::destroyComponent(CORBA::Object_ptr obj)
{
    ACS::ACSComponent_var acscomp;
    try
	{
	acscomp = ACS::ACSComponent::_narrow(obj);
	if ( CORBA::is_nil(acscomp.ptr()) )
	    {
	    ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::destroyComponent",
			    (LM_ERROR,  "component narrowed to nil!!"));
	    }
	}
    catch(...)
	{
	}
#ifndef _TASK_LIB
    if ( services_m == true )
	{
	ACE_CString compNam = acscomp->name();
	ACS_DEBUG_PARAM("StaticContainer::destroyComponent", "releasing the component %s via the manager", compNam.c_str());
	container_m.getManager()->release_component(container_m.getHandle(), acscomp->name());
	return;
	}
#endif  // !_TASK_LIB

    PortableServer::Servant servant;
    servant = componentPOA_m->reference_to_servant(obj);

 // life cycle
    ACS_DEBUG("StaticContainer::destroyComponent", "Component Life Cycle");
    acscomponent::ACSComponentImpl *acsComponent =
	dynamic_cast<acscomponent::ACSComponentImpl*>(servant);
    acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_DESTROYING);
    acsComponent->__cleanUp();
    acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_DEFUNCT);
// ContainerServices is deleted in the destructor of ComponentImpl

    if ( services_m == true)
	{
	ACS_DEBUG_PARAM("StaticContainer::destroyComponent", "deactivating the component %s", acscomp->name());
	container_m.deactivateCORBAObject(obj);
	}
    else
	{
	ACS_DEBUG_PARAM("StaticContainer::destroyComponent", "deleting the component %s", acscomp->name());
	servant->_remove_ref();
	}//if-else
}//destroyComponenet

/*___oOo___*/

<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#ifndef __otbInverseCosSpectralAngleKernelFunctor_txx
#define __otbInverseCosSpectralAngleKernelFunctor_txx

#include <cmath>
#include <cfloat>

#include "otbInverseCosSpectralAngleKernelFunctor.h"

namespace otb {

InverseCosSpectralAngleKernelFunctor
::InverseCosSpectralAngleKernelFunctor ()
		: GenericKernelFunctorBase ()
{
	m_Coef = 2.0;

	SetValue( "Coef", m_Coef );
}

void
InverseCosSpectralAngleKernelFunctor
::Update ()
{
	m_Coef = GetValue<double>( "Coef" );
}

double
InverseCosSpectralAngleKernelFunctor
::operator()( const svm_node * x, const svm_node * y,
				const svm_parameter & param ) const
{
	double mq = m_Coef + SAM( x, y );

	if ( mq == 0.0 )
		return DBL_MAX;

	return 1.0 / sqrt( mq );
}

double
InverseCosSpectralAngleKernelFunctor
::SAM ( const svm_node * x, const svm_node * y ) const
{
	double den = dot(x,x) * dot(y,y);
	if ( den <= 0.0 )
		return 0.0;

	double ss = dot(x,y);
	return /*acos*/( ss / sqrt( den ) );
}

}

#endif

<commit_msg>ENH: inverse cos SAM real computation<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#ifndef __otbInverseCosSpectralAngleKernelFunctor_txx
#define __otbInverseCosSpectralAngleKernelFunctor_txx

#include <cmath>
#include <cfloat>

#include "otbInverseCosSpectralAngleKernelFunctor.h"

namespace otb {

InverseCosSpectralAngleKernelFunctor
::InverseCosSpectralAngleKernelFunctor ()
		: GenericKernelFunctorBase ()
{
	m_Coef = 1.0;

	SetValue( "Coef", m_Coef );
}

void
InverseCosSpectralAngleKernelFunctor
::Update ()
{
	m_Coef = GetValue<double>( "Coef" );
}

double
InverseCosSpectralAngleKernelFunctor
::operator()( const svm_node * x, const svm_node * y,
				const svm_parameter & param ) const
{
	double mq = m_Coef - vcl_cos( SAM( x, y ));

	if ( mq == 0.0 )
		return DBL_MAX;

	return 1.0 / sqrt( mq );
}

double
InverseCosSpectralAngleKernelFunctor
::SAM ( const svm_node * x, const svm_node * y ) const
{
	double den = dot(x,x) * dot(y,y);
	if ( den <= 0.0 )
		return 0.0;

	double ss = dot(x,y);
	return /*acos*/( ss / sqrt( den ) );
}

}

#endif

<|endoftext|>


<commit_before>#include "Result.h"
#include "ResultText.h"
#include "MonsterFadeInEffect.h"
#include "../../Button/ButtonManager.h"
#include "../../Drawable/DrawableAssetTexture.h"
#include "../../Button/TextureAssetButton.h"

using namespace scene::result;

scene::result::Result::Result()
{
}

void Result::init()
{
    auto changeScene = [this](String sceneName) {
		SoundAsset(L"Result_ButtonSE").play();
        (this->*&Scene::changeScene)(sceneName, 500, false);
        ButtonManager::clearAll();
		SoundAsset(L"Result_BGM").stop();
    };
    // {^̏
    ButtonManager::clearAll();
    ButtonManager::update();
    std::shared_ptr<TextureAssetButton> button;
    button = std::make_shared<TextureAssetButton>(Vec2(300, 610), L"Result_RetryButton", [changeScene]() {
        changeScene(L"Battle");
    });
    ButtonManager::add(button);
    drawables_m.add(button, 2);
    button = std::make_shared<TextureAssetButton>(Vec2(980, 610), L"Result_TitleButton", [changeScene]() {
        changeScene(L"Title");
    });
    ButtonManager::add(button);
    drawables_m.add(button, 2);
    // wi̐ݒ
    drawables_m.add(std::make_shared<DrawableAssetTexture>(L"Result_Background", Window::Center()), 0);
    // eLXg̏
    int numOfdefeatedEnemy = static_cast<int>(m_data->defeatedEnemyList.size());
    int remainingTime = m_data->time;
    drawables_m.add(std::make_shared<DrawableAssetTexture>(L"Result_Logo", Window::Center().moveBy(0, -230), 0.7), 3);
    drawables_m.add(std::make_shared<ResultText>(L"|G: ", L"Result_Font", Window::Center().moveBy(-50, -80)), 3);
    enemyNum_m = std::make_shared<ResultText>(Format(numOfdefeatedEnemy), L"Result_Font", Window::Center().moveBy(150, -80));
    drawables_m.add(enemyNum_m, 3);
    enemyNum_m->hide();
    drawables_m.add(std::make_shared<ResultText>(L"c莞: ", L"Result_Font", Window::Center().moveBy(-50, 20)), 3);
	drawables_m.add(std::make_shared<ResultText>(Format(remainingTime / 100, L".", Pad(remainingTime % 100, {2, L'0'})), L"Result_Font", Window::Center().moveBy(150, 20)), 3);
    score_m = std::make_shared<ResultText>(Format(numOfdefeatedEnemy, L" ~ 100 + ", remainingTime , L" = ", numOfdefeatedEnemy * 100 + remainingTime), L"Result_Font", Window::Center().moveBy(0, 120));
    drawables_m.add(score_m, 3);
    score_m->hide();
    // ^C}[n
    stopwatch_m.start();
	// BGMĐ
	SoundAsset(L"Result_BGM").play();
}

void Result::update()
{
    static int counter = 0;
    // GtFNg
    if(counter < m_data->defeatedEnemyList.size()) {
        if(stopwatch_m.elapsed() >= 150ms) {
            effect_m.add<MonsterFadeInEffect>(TextureAsset(Format(L"Enemy", m_data->defeatedEnemyList[counter])));
            stopwatch_m.restart();
            ++counter;
        }
    }
    else {
        if(effect_m.num_effects == 0) {
            enemyNum_m->show();
            score_m->show();
            stopwatch_m.reset();
            counter = 0;
        }
    }
}

void Result::draw() const
{
    drawables_m.drawAll();
    effect_m.update();
}<commit_msg>残り時間表示を修正<commit_after>#include "Result.h"
#include "ResultText.h"
#include "MonsterFadeInEffect.h"
#include "../../Button/ButtonManager.h"
#include "../../Drawable/DrawableAssetTexture.h"
#include "../../Button/TextureAssetButton.h"

using namespace scene::result;

scene::result::Result::Result()
{
}

void Result::init()
{
    auto changeScene = [this](String sceneName) {
		SoundAsset(L"Result_ButtonSE").play();
        (this->*&Scene::changeScene)(sceneName, 500, false);
        ButtonManager::clearAll();
		SoundAsset(L"Result_BGM").stop();
    };
    // {^̏
    ButtonManager::clearAll();
    ButtonManager::update();
    std::shared_ptr<TextureAssetButton> button;
    button = std::make_shared<TextureAssetButton>(Vec2(300, 610), L"Result_RetryButton", [changeScene]() {
        changeScene(L"Battle");
    });
    ButtonManager::add(button);
    drawables_m.add(button, 2);
    button = std::make_shared<TextureAssetButton>(Vec2(980, 610), L"Result_TitleButton", [changeScene]() {
        changeScene(L"Title");
    });
    ButtonManager::add(button);
    drawables_m.add(button, 2);
    // wi̐ݒ
    drawables_m.add(std::make_shared<DrawableAssetTexture>(L"Result_Background", Window::Center()), 0);
    // eLXg̏
    int numOfdefeatedEnemy = static_cast<int>(m_data->defeatedEnemyList.size());
    int remainingTime = m_data->time;
    drawables_m.add(std::make_shared<DrawableAssetTexture>(L"Result_Logo", Window::Center().moveBy(0, -230), 0.7), 3);
    drawables_m.add(std::make_shared<ResultText>(L"|G: ", L"Result_Font", Window::Center().moveBy(-50, -80)), 3);
    enemyNum_m = std::make_shared<ResultText>(Format(numOfdefeatedEnemy), L"Result_Font", Window::Center().moveBy(150, -80));
    drawables_m.add(enemyNum_m, 3);
    enemyNum_m->hide();
    drawables_m.add(std::make_shared<ResultText>(L"c莞: ", L"Result_Font", Window::Center().moveBy(-50, 20)), 3);
    if(remainingTime == 0) {
        drawables_m.add(std::make_shared<ResultText>(L"0", L"Result_Font", Window::Center().moveBy(150, 20)), 3);
    }
    else {
        drawables_m.add(std::make_shared<ResultText>(Format(remainingTime / 100, L".", Pad(remainingTime % 100, {2, L'0'})), L"Result_Font", Window::Center().moveBy(150, 20)), 3);
    }
    score_m = std::make_shared<ResultText>(Format(numOfdefeatedEnemy, L" ~ 100 + ", remainingTime , L" = ", numOfdefeatedEnemy * 100 + remainingTime), L"Result_Font", Window::Center().moveBy(0, 120));
    drawables_m.add(score_m, 3);
    score_m->hide();
    // ^C}[n
    stopwatch_m.start();
	// BGMĐ
	SoundAsset(L"Result_BGM").play();
}

void Result::update()
{
    static int counter = 0;
    // GtFNg
    if(counter < m_data->defeatedEnemyList.size()) {
        if(stopwatch_m.elapsed() >= 150ms) {
            effect_m.add<MonsterFadeInEffect>(TextureAsset(Format(L"Enemy", m_data->defeatedEnemyList[counter])));
            stopwatch_m.restart();
            ++counter;
        }
    }
    else {
        if(effect_m.num_effects == 0) {
            enemyNum_m->show();
            score_m->show();
            stopwatch_m.reset();
            counter = 0;
        }
    }
}

void Result::draw() const
{
    drawables_m.drawAll();
    effect_m.update();
}<|endoftext|>


<commit_before>/*
  Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
  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. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS 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 COPYRIGHT OWNER OR 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.
*/
#pragma once

#include "jdksavdecc-c/include/jdksavdecc.h"
#include "jdksavdecc-c/include/jdksavdecc_print.h"
#include "jdksavdecc-c/include/jdksavdecc_pdu_print.h"

#if defined(__AVR__)
#include "SPI.h"

inline jdksavdecc_timestamp_in_milliseconds GetTimeInMs() {
    return millis();
}
#elif defined(__APPLE__) || defined(__linux__)
#include <sys/time.h>
#include <iostream>
#include <iomanip>
inline jdksavdecc_timestamp_in_milliseconds GetTimeInMs() {
    timeval tv;

    gettimeofday(&tv,0);
    return jdksavdecc_timestamp_in_milliseconds(tv.tv_usec/1000) +
        jdksavdecc_timestamp_in_milliseconds(tv.tv_sec*1000);
}
#elif defined(WIN32)
#include <iostream>
#include <iomanip>
inline jdksavdecc_timestamp_in_milliseconds GetTimeInMs() {
    return jdksavdecc_timestamp_in_milliseconds(GetTickCount());
}
#endif

#if defined(__AVR__)
extern "C" {
void avr_debug_log(const char *str, uint16_t v );
}
#endif

<commit_msg>Add jdks include to top level<commit_after>/*
  Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
  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. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS 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 COPYRIGHT OWNER OR 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.
*/
#pragma once

#include "jdksavdecc-c/include/jdksavdecc.h"
#include "jdksavdecc-c/include/jdksavdecc_jdks.h"
#include "jdksavdecc-c/include/jdksavdecc_print.h"
#include "jdksavdecc-c/include/jdksavdecc_pdu_print.h"

#if defined(__AVR__)
#include "SPI.h"

inline jdksavdecc_timestamp_in_milliseconds GetTimeInMs() {
    return millis();
}
#elif defined(__APPLE__) || defined(__linux__)
#include <sys/time.h>
#include <iostream>
#include <iomanip>
inline jdksavdecc_timestamp_in_milliseconds GetTimeInMs() {
    timeval tv;

    gettimeofday(&tv,0);
    return jdksavdecc_timestamp_in_milliseconds(tv.tv_usec/1000) +
        jdksavdecc_timestamp_in_milliseconds(tv.tv_sec*1000);
}
#elif defined(WIN32)
#include <iostream>
#include <iomanip>
inline jdksavdecc_timestamp_in_milliseconds GetTimeInMs() {
    return jdksavdecc_timestamp_in_milliseconds(GetTickCount());
}
#endif

#if defined(__AVR__)
extern "C" {
void avr_debug_log(const char *str, uint16_t v );
}
#endif

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkExtractEdges.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * 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.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS 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 AUTHORS OR 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.

=========================================================================*/
#include "vtkExtractEdges.h"
#include "vtkEdgeTable.h"
#include "vtkMergePoints.h"
#include "vtkObjectFactory.h"

//-------------------------------------------------------------------------
vtkExtractEdges* vtkExtractEdges::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkExtractEdges");
  if(ret)
    {
    return (vtkExtractEdges*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkExtractEdges;
}

// Construct object.
vtkExtractEdges::vtkExtractEdges()
{
  this->Locator = NULL;
}

vtkExtractEdges::~vtkExtractEdges()
{
  if ( this->Locator )
    {
    this->Locator->UnRegister(this);
    this->Locator = NULL;
    }
}

// Generate feature edges for mesh
void vtkExtractEdges::Execute()
{
  vtkDataSet *input= this->GetInput();
  vtkPolyData *output= this->GetOutput();
  vtkPoints *newPts;
  vtkCellArray *newLines;
  vtkIdType numCells, cellNum, numPts, newId;
  int edgeNum, numEdgePts, numCellEdges;
  int i;
  vtkIdType pts[2];
  vtkIdType pt1 = 0, pt2;
  float *x;
  vtkEdgeTable *edgeTable;
  vtkCell *cell, *edge;
  vtkPointData *pd, *outPD;
  vtkCellData *cd, *outCD;

  vtkDebugMacro(<<"Executing edge extractor");

  //  Check input
  //
  numPts=input->GetNumberOfPoints();
  if ( (numCells=input->GetNumberOfCells()) < 1 || numPts < 1 )
    {
    vtkErrorMacro(<<"No input data!");
    return;
    }

  // Set up processing
  //
  edgeTable = vtkEdgeTable::New();
  edgeTable->InitEdgeInsertion(numPts);
  newPts = vtkPoints::New();
  newPts->Allocate(numPts);
  newLines = vtkCellArray::New();
  newLines->EstimateSize(numPts*4,2);

  pd = input->GetPointData();
  outPD = output->GetPointData();
  outPD->CopyAllocate(pd,numPts);

  cd = input->GetCellData();
  outCD = output->GetCellData();
  outCD->CopyAllocate(cd,numCells);

  // Get our locator for merging points
  //
  if ( this->Locator == NULL )
    {
    this->CreateDefaultLocator();
    }
  this->Locator->InitPointInsertion (newPts, input->GetBounds());

  // Loop over all cells, extracting non-visited edges.
  //
  for (cellNum=0; cellNum < numCells; cellNum++ )
    {
    if ( ! (cellNum % 10000) ) //manage progress reports / early abort
      {
      this->UpdateProgress ((float)cellNum / numCells);
      if ( this->GetAbortExecute() )
        {
        break;
        }
      }

    cell = input->GetCell(cellNum);
    numCellEdges = cell->GetNumberOfEdges();
    for (edgeNum=0; edgeNum < numCellEdges; edgeNum++ )
      {
      edge = cell->GetEdge(edgeNum);
      numEdgePts = edge->GetNumberOfPoints();

      for ( i=0; i < numEdgePts; i++, pt1=pt2, pts[0]=pts[1] )
        {
        pt2 = edge->PointIds->GetId(i);
        x = input->GetPoint(pt2);
        if ( this->Locator->InsertUniquePoint(x, pts[1]) )
          {
          outPD->CopyData (pd,pt2,pts[1]);
          }
        if ( i > 0 && edgeTable->IsEdge(pt1,pt2) == -1 )
          {
          edgeTable->InsertEdge(pt1, pt2);
          newId = newLines->InsertNextCell(2,pts);
          outCD->CopyData(cd, cellNum, newId);
          }
        }
      }//for all edges of cell
    }//for all cells

  vtkDebugMacro(<<"Created " << newLines->GetNumberOfCells() << " edges");

  //  Update ourselves.
  //
  edgeTable->Delete();

  output->SetPoints(newPts);
  newPts->Delete();

  output->SetLines(newLines);
  newLines->Delete();

  output->Squeeze();
}

// Specify a spatial locator for merging points. By
// default an instance of vtkMergePoints is used.
void vtkExtractEdges::SetLocator(vtkPointLocator *locator)
{
  if ( this->Locator == locator )
    {
    return;
    }
  if ( this->Locator )
    {
    this->Locator->UnRegister(this);
    this->Locator = NULL;
    }
  if ( locator )
    {
    locator->Register(this);
    }
  this->Locator = locator;
  this->Modified();
}

void vtkExtractEdges::CreateDefaultLocator()
{
  if ( this->Locator == NULL )
    {
    this->Locator = vtkMergePoints::New();
    }
}

void vtkExtractEdges::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkDataSetToPolyDataFilter::PrintSelf(os,indent);

  if ( this->Locator )
    {
    os << indent << "Locator: " << this->Locator << "\n";
    }
  else
    {
    os << indent << "Locator: (none)\n";
    }
}

unsigned long int vtkExtractEdges::GetMTime()
{
  unsigned long mTime=this-> vtkDataSetToPolyDataFilter::GetMTime();
  unsigned long time;

  if ( this->Locator != NULL )
    {
    time = this->Locator->GetMTime();
    mTime = ( time > mTime ? time : mTime );
    }
  return mTime;
}

<commit_msg>ENH:Updated GetCell method for thread safety<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkExtractEdges.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * 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.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS 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 AUTHORS OR 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.

=========================================================================*/
#include "vtkExtractEdges.h"
#include "vtkEdgeTable.h"
#include "vtkMergePoints.h"
#include "vtkObjectFactory.h"

//-------------------------------------------------------------------------
vtkExtractEdges* vtkExtractEdges::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkExtractEdges");
  if(ret)
    {
    return (vtkExtractEdges*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkExtractEdges;
}

// Construct object.
vtkExtractEdges::vtkExtractEdges()
{
  this->Locator = NULL;
}

vtkExtractEdges::~vtkExtractEdges()
{
  if ( this->Locator )
    {
    this->Locator->UnRegister(this);
    this->Locator = NULL;
    }
}

// Generate feature edges for mesh
void vtkExtractEdges::Execute()
{
  vtkDataSet *input= this->GetInput();
  vtkPolyData *output= this->GetOutput();
  vtkPoints *newPts;
  vtkCellArray *newLines;
  vtkIdType numCells, cellNum, numPts, newId;
  int edgeNum, numEdgePts, numCellEdges;
  int i;
  vtkIdType pts[2];
  vtkIdType pt1 = 0, pt2;
  float *x;
  vtkEdgeTable *edgeTable;
  vtkGenericCell *cell;
  vtkCell *edge;
  vtkPointData *pd, *outPD;
  vtkCellData *cd, *outCD;

  vtkDebugMacro(<<"Executing edge extractor");

  //  Check input
  //
  numPts=input->GetNumberOfPoints();
  if ( (numCells=input->GetNumberOfCells()) < 1 || numPts < 1 )
    {
    vtkErrorMacro(<<"No input data!");
    return;
    }

  // Set up processing
  //
  edgeTable = vtkEdgeTable::New();
  edgeTable->InitEdgeInsertion(numPts);
  newPts = vtkPoints::New();
  newPts->Allocate(numPts);
  newLines = vtkCellArray::New();
  newLines->EstimateSize(numPts*4,2);

  pd = input->GetPointData();
  outPD = output->GetPointData();
  outPD->CopyAllocate(pd,numPts);

  cd = input->GetCellData();
  outCD = output->GetCellData();
  outCD->CopyAllocate(cd,numCells);

  cell = vtkGenericCell::New();

  // Get our locator for merging points
  //
  if ( this->Locator == NULL )
    {
    this->CreateDefaultLocator();
    }
  this->Locator->InitPointInsertion (newPts, input->GetBounds());

  // Loop over all cells, extracting non-visited edges.
  //
  for (cellNum=0; cellNum < numCells; cellNum++ )
    {
    if ( ! (cellNum % 10000) ) //manage progress reports / early abort
      {
      this->UpdateProgress ((float)cellNum / numCells);
      if ( this->GetAbortExecute() )
        {
        break;
        }
      }

    input->GetCell(cellNum,cell);
    numCellEdges = cell->GetNumberOfEdges();
    for (edgeNum=0; edgeNum < numCellEdges; edgeNum++ )
      {
      edge = cell->GetEdge(edgeNum);
      numEdgePts = edge->GetNumberOfPoints();

      for ( i=0; i < numEdgePts; i++, pt1=pt2, pts[0]=pts[1] )
        {
        pt2 = edge->PointIds->GetId(i);
        x = input->GetPoint(pt2);
        if ( this->Locator->InsertUniquePoint(x, pts[1]) )
          {
          outPD->CopyData (pd,pt2,pts[1]);
          }
        if ( i > 0 && edgeTable->IsEdge(pt1,pt2) == -1 )
          {
          edgeTable->InsertEdge(pt1, pt2);
          newId = newLines->InsertNextCell(2,pts);
          outCD->CopyData(cd, cellNum, newId);
          }
        }
      }//for all edges of cell
    }//for all cells

  vtkDebugMacro(<<"Created " << newLines->GetNumberOfCells() << " edges");

  //  Update ourselves.
  //
  edgeTable->Delete();
  cell->Delete();

  output->SetPoints(newPts);
  newPts->Delete();

  output->SetLines(newLines);
  newLines->Delete();

  output->Squeeze();
}

// Specify a spatial locator for merging points. By
// default an instance of vtkMergePoints is used.
void vtkExtractEdges::SetLocator(vtkPointLocator *locator)
{
  if ( this->Locator == locator )
    {
    return;
    }
  if ( this->Locator )
    {
    this->Locator->UnRegister(this);
    this->Locator = NULL;
    }
  if ( locator )
    {
    locator->Register(this);
    }
  this->Locator = locator;
  this->Modified();
}

void vtkExtractEdges::CreateDefaultLocator()
{
  if ( this->Locator == NULL )
    {
    this->Locator = vtkMergePoints::New();
    }
}

void vtkExtractEdges::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkDataSetToPolyDataFilter::PrintSelf(os,indent);

  if ( this->Locator )
    {
    os << indent << "Locator: " << this->Locator << "\n";
    }
  else
    {
    os << indent << "Locator: (none)\n";
    }
}

unsigned long int vtkExtractEdges::GetMTime()
{
  unsigned long mTime=this-> vtkDataSetToPolyDataFilter::GetMTime();
  unsigned long time;

  if ( this->Locator != NULL )
    {
    time = this->Locator->GetMTime();
    mTime = ( time > mTime ? time : mTime );
    }
  return mTime;
}

<|endoftext|>