<commit_before>//---------------------------------------------------------------------------
//              E L E N A   p r o j e c t
//                Command line DSA script terminal main file
//                                              (C)2011-2020, by Alexei Rakov
//---------------------------------------------------------------------------

#include "elena.h"
//---------------------------------------------------------------------------
#include <stdarg.h>
#include "elenamachine.h"
#include "elenasm.h"
#include "elenavm.h"

using namespace _ELENA_;

#define MAX_LINE           256
#define MAX_SCRIPT         4096
#define ELT_BUILD_NUMBER   13

// global variables
ProgramHeader  _header;
int            _encoding = feAnsi;
pos_t          _tlsIndex = 0;
GCTable        _table = { 0 };
SystemEnv      _env = { 0 };
int            _sehTable = 0;

IdentifierString prefix;
IdentifierString postfix;

DynamicString<char> body;

void loadTemplate(path_t path)
{
   char buff[512];

   TextFileReader reader(path, feUTF8, false);

   if (reader.isOpened()) {
      IdentifierString content;
      reader.readAll(content, buff);

      int index = content.ident().find("$1");
      if (index != NOTFOUND_POS) {
         prefix.copy(content.ident(), index);
         postfix.copy(content.c_str() + index + 2);
      }
      else prefix.copy(content.ident());
   }
}

void print(const char* str, ...)
{
   va_list argptr;
   va_start(argptr, str);

   vprintf(str, argptr);
   va_end(argptr);

   fflush(stdout);
}

const char* trim(const char* s)
{
   while(s[0]==0x20)s++;

   return s;
}

void printHelp()
{
   print("-q                   - quit\n");
   print("-h                   - help\n");
   print("-l <path>            - execute a script from file\n");
   print("<script>             - execute script\n");
}

void executeTape(void* tape)
{
   int retVal = EvaluateTape(&_env, &_sehTable, tape);
   Release(tape);

   // copy vm error if retVal is zero
   if (!retVal) {
      ident_t error = GetVMLastError();
      if (!emptystr(error)) {
         printf("\nFailed:%s", (const char*)error);
      }
   }
}

void executeScript(const char* script)
{
   void* tape = InterpretScript(script);
   if (tape == NULL) {
      char error[0x200];
      int length = GetStatus(error, 0x200);
      error[length] = 0;
      if (!emptystr(error)) {
         printf("\nFailed:%s", error);
      }
      return;
   }
   else executeTape(tape);
}

void loadScript(const char* path)
{
   path = trim(path);

   void* tape = InterpretFile(path, _encoding, false);
   if (tape == NULL) {
      char error[0x200];
      int length = GetStatus(error, 0x200);
      error[length] = 0;
      if (!emptystr(error)) {
         printf("\nFailed:%s", error);
      }
      return;
   }
   else executeTape(tape);

}

bool executeCommand(const char* line, bool& running)
{
   if (getlength(line)<2)
      return false;

   // check commands
   if(line[1] == 'q') {
      running = false;
   }
   else if(line[1] == 'h') {
      printHelp();
   }
   else if(line[1] == 'l') {
      loadScript(line + 2);
   }
   else return false;

   return true;
}

bool executeCommand(const char* line)
{
   bool dummy;
   return executeCommand(line, dummy);
}

void executeCommandLine(const char* line)
{
   DynamicString<char> command;

   command.append(body.str());
   command.append('\n');
   command.append(prefix);
   command.append(line);
   command.append(postfix);

   executeScript(command);

   body.clear();
}

void runSession()
{
   char          buffer[MAX_LINE];
   IdentifierString line;
   bool             running = true;

   do {
      try {
         print("\n>");

         fgets(buffer, MAX_LINE, stdin);
         IdentifierString line(buffer, getlength(buffer));

         while (!emptystr(line) && line[getlength(line) - 1]=='\r' || line[getlength(line) - 1]=='\n')
            line[getlength(line) - 1] = 0;

         while (!emptystr(line) && line[getlength(line) - 1]==' ')
            line[getlength(line) - 1] = 0;

         if (line[0]=='-') {
            if(!executeCommand(line, running))
               print("Invalid command, use -h to get the list of the commands\n");
         }
         else if (!emptystr(line) && line[getlength(line) - 1]==';') {
            line[getlength(line) - 1] = 0;

            body.append(line.c_str());
         }
         else executeCommandLine(line);
      }
      catch(...) {
         print("Invalid operation");
      }
   }
   while(running);
}

int main(int argc, char* argv[])
{
   print("ELENA command line VM terminal %d.%d.%d (C)2011-2020 by Alexei Rakov\n", ENGINE_MAJOR_VERSION, ENGINE_MINOR_VERSION, ELT_BUILD_NUMBER);

   Path commandPath("command.es");
   loadTemplate(commandPath.c_str());

   _env.MaxThread = 1;
   _env.Table = &_table;
   _env.TLSIndex = &_tlsIndex;
   _env.GCMGSize = 0x54000;
   _env.GCYGSize = 0x15000;

   InitializeVMSTA(&_sehTable, &_env, nullptr, nullptr, nullptr, &_header);

   loadScript("~\\elt.es");
   loadScript("~\\scripts\\grammar.es");
   loadScript("~\\scripts\\tscript.es");

   // load script passed via command line arguments
   if (argc > 1) {
      for (int i = 1 ; i < argc ; i++) {
         if (argv[i][0] == '-') {
            // check exit command
            if (argv[i][1] == 'q')
               return 0;

            executeCommand(argv[i]);
         }
         else executeScript(argv[i]);
      }
   }

   runSession();
}
<commit_msg>some housekeeping<commit_after>//---------------------------------------------------------------------------
//              E L E N A   p r o j e c t
//                Command line DSA script terminal main file
//                                              (C)2011-2020, by Alexei Rakov
//---------------------------------------------------------------------------

#include "elena.h"
//---------------------------------------------------------------------------
#include <stdarg.h>
#include "elenamachine.h"
#include "elenasm.h"
#include "elenavm.h"

using namespace _ELENA_;

#define MAX_LINE           256
#define MAX_SCRIPT         4096
#define ELT_BUILD_NUMBER   14

// global variables
ProgramHeader  _header;
int            _encoding = feAnsi;
pos_t          _tlsIndex = 0;
GCTable        _table = { 0 };
SystemEnv      _env = { 0 };
int            _sehTable = 0;

IdentifierString prefix;
IdentifierString postfix;

DynamicString<char> body;

void loadTemplate(path_t path)
{
   char buff[512];

   TextFileReader reader(path, feUTF8, false);

   if (reader.isOpened()) {
      IdentifierString content;
      reader.readAll(content, buff);

      int index = content.ident().find("$1");
      if (index != NOTFOUND_POS) {
         prefix.copy(content.ident(), index);
         postfix.copy(content.c_str() + index + 2);
      }
      else prefix.copy(content.ident());
   }
}

void print(const char* str, ...)
{
   va_list argptr;
   va_start(argptr, str);

   vprintf(str, argptr);
   va_end(argptr);

   fflush(stdout);
}

const char* trim(const char* s)
{
   while(s[0]==0x20)s++;

   return s;
}

void printHelp()
{
   print("-q                   - quit\n");
   print("-h                   - help\n");
   print("-l <path>            - execute a script from file\n");
   print("<script>             - execute script\n");
}

void executeTape(void* tape)
{
   int retVal = EvaluateTape(&_env, &_sehTable, tape);
   Release(tape);

   // copy vm error if retVal is zero
   if (!retVal) {
      ident_t error = GetVMLastError();
      if (!emptystr(error)) {
         printf("\nFailed:%s", (const char*)error);
      }
   }
}

void executeScript(const char* script)
{
   void* tape = InterpretScript(script);
   if (tape == NULL) {
      char error[0x200];
      int length = GetStatus(error, 0x200);
      error[length] = 0;
      if (!emptystr(error)) {
         printf("\nFailed:%s", error);
      }
      return;
   }
   else executeTape(tape);
}

void loadScript(const char* path)
{
   path = trim(path);

   void* tape = InterpretFile(path, _encoding, false);
   if (tape == NULL) {
      char error[0x200];
      int length = GetStatus(error, 0x200);
      error[length] = 0;
      if (!emptystr(error)) {
         printf("\nFailed:%s", error);
      }
      return;
   }
   else executeTape(tape);

}

bool executeCommand(const char* line, bool& running)
{
   if (getlength(line)<2)
      return false;

   // check commands
   if(line[1] == 'q') {
      running = false;
   }
   else if(line[1] == 'h') {
      printHelp();
   }
   else if(line[1] == 'l') {
      loadScript(line + 2);
   }
   else return false;

   return true;
}

bool executeCommand(const char* line)
{
   bool dummy;
   return executeCommand(line, dummy);
}

void executeCommandLine(const char* line)
{
   DynamicString<char> command;

   command.append(body.str());
   command.append('\n');
   command.append(prefix);
   command.append(line);
   command.append(postfix);

   executeScript(command);
}

void runSession()
{
   char          buffer[MAX_LINE];
   IdentifierString line;
   bool             running = true;

   do {
      try {
         print("\n>");

         fgets(buffer, MAX_LINE, stdin);
         IdentifierString line(buffer, getlength(buffer));

         while (!emptystr(line) && line[getlength(line) - 1]=='\r' || line[getlength(line) - 1]=='\n')
            line[getlength(line) - 1] = 0;

         while (!emptystr(line) && line[getlength(line) - 1]==' ')
            line[getlength(line) - 1] = 0;

         if (line[0]=='-') {
            if(!executeCommand(line, running))
               print("Invalid command, use -h to get the list of the commands\n");
         }
         else if (!emptystr(line) && line[getlength(line) - 1]==';') {
            line[getlength(line) - 1] = 0;

            body.append(line.c_str());
         }
         else executeCommandLine(line);
      }
      catch(...) {
         print("Invalid operation");
      }
   }
   while(running);
}

int main(int argc, char* argv[])
{
   print("ELENA command line VM terminal %d.%d.%d (C)2011-2020 by Alexei Rakov\n", ENGINE_MAJOR_VERSION, ENGINE_MINOR_VERSION, ELT_BUILD_NUMBER);

   Path commandPath("command.es");
   loadTemplate(commandPath.c_str());

   _env.MaxThread = 1;
   _env.Table = &_table;
   _env.TLSIndex = &_tlsIndex;
   _env.GCMGSize = 0x54000;
   _env.GCYGSize = 0x15000;

   InitializeVMSTA(&_sehTable, &_env, nullptr, nullptr, nullptr, &_header);

   loadScript("~\\elt.es");
   loadScript("~\\scripts\\grammar.es");
   loadScript("~\\scripts\\tscript.es");

   // load script passed via command line arguments
   if (argc > 1) {
      for (int i = 1 ; i < argc ; i++) {
         if (argv[i][0] == '-') {
            // check exit command
            if (argv[i][1] == 'q')
               return 0;

            executeCommand(argv[i]);
         }
         else executeScript(argv[i]);
      }
   }

   runSession();
}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkDiffusionCoreObjectFactory.h"

#include "mitkProperties.h"
#include "mitkBaseRenderer.h"
#include "mitkDataNode.h"

#include "mitkNrrdDiffusionImageIOFactory.h"
#include "mitkNrrdDiffusionImageWriterFactory.h"
#include "mitkNrrdDiffusionImageWriter.h"
#include "mitkDiffusionImage.h"

#include "mitkNrrdQBallImageIOFactory.h"
#include "mitkNrrdQBallImageWriterFactory.h"
#include "mitkNrrdQBallImageWriter.h"

#include "mitkNrrdTensorImageIOFactory.h"
#include "mitkNrrdTensorImageWriterFactory.h"
#include "mitkNrrdTensorImageWriter.h"

#include "mitkCompositeMapper.h"
#include "mitkDiffusionImageMapper.h"
#include "mitkGPUVolumeMapper3D.h"
#include "mitkVolumeDataVtkMapper3D.h"

#include "mitkPlanarFigureMapper3D.h"

typedef short DiffusionPixelType;

typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageShort;
typedef std::multimap<std::string, std::string> MultimapType;

mitk::DiffusionCoreObjectFactory::DiffusionCoreObjectFactory()
  :CoreObjectFactoryBase()
{

  static bool alreadyDone = false;
  if (!alreadyDone)
  {
    MITK_DEBUG << "DiffusionCoreObjectFactory c'tor" << std::endl;
    RegisterIOFactories();

    mitk::NrrdDiffusionImageIOFactory::RegisterOneFactory();
    mitk::NrrdQBallImageIOFactory::RegisterOneFactory();
    mitk::NrrdTensorImageIOFactory::RegisterOneFactory();

    mitk::NrrdDiffusionImageWriterFactory::RegisterOneFactory();
    mitk::NrrdQBallImageWriterFactory::RegisterOneFactory();
    mitk::NrrdTensorImageWriterFactory::RegisterOneFactory();

    m_FileWriters.push_back( NrrdDiffusionImageWriter<DiffusionPixelType>::New().GetPointer() );
    m_FileWriters.push_back( NrrdQBallImageWriter::New().GetPointer() );
    m_FileWriters.push_back( NrrdTensorImageWriter::New().GetPointer() );

    mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(this);
    CreateFileExtensionsMap();

    alreadyDone = true;
  }

}

mitk::Mapper::Pointer mitk::DiffusionCoreObjectFactory::CreateMapper(mitk::DataNode* node, MapperSlotId id)
{
  mitk::Mapper::Pointer newMapper=NULL;

  if ( id == mitk::BaseRenderer::Standard2D )
  {
    std::string classname("QBallImage");
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::CompositeMapper::New();
      newMapper->SetDataNode(node);
      node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper());
    }
    classname = "TensorImage";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::CompositeMapper::New();
      newMapper->SetDataNode(node);
      node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper());
    }

    classname = "DiffusionImage";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::DiffusionImageMapper<short>::New();
      newMapper->SetDataNode(node);
    }

  }
  else if ( id == mitk::BaseRenderer::Standard3D )
  {
    std::string classname("QBallImage");
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::GPUVolumeMapper3D::New();
      newMapper->SetDataNode(node);
    }
    classname = "TensorImage";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::GPUVolumeMapper3D::New();
      newMapper->SetDataNode(node);
    }
    classname = "DiffusionImage";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::GPUVolumeMapper3D::New();
      newMapper->SetDataNode(node);
    }

    classname =  "PlanarRectangle";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::PlanarFigureMapper3D::New();
      newMapper->SetDataNode(node);
    }

    classname =  "PlanarCircle";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::PlanarFigureMapper3D::New();
      newMapper->SetDataNode(node);
    }

    classname =  "PlanarEllipse";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::PlanarFigureMapper3D::New();
      newMapper->SetDataNode(node);
    }

    classname = "PlanarPolygon";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::PlanarFigureMapper3D::New();
      newMapper->SetDataNode(node);
    }

  }

  return newMapper;
}

void mitk::DiffusionCoreObjectFactory::SetDefaultProperties(mitk::DataNode* node)
{
  std::string classname = "QBallImage";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::CompositeMapper::SetDefaultProperties(node);
    mitk::GPUVolumeMapper3D::SetDefaultProperties(node);
  }

  classname = "TensorImage";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::CompositeMapper::SetDefaultProperties(node);
    mitk::GPUVolumeMapper3D::SetDefaultProperties(node);
  }

  classname = "DiffusionImage";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::DiffusionImageMapper<short>::SetDefaultProperties(node);
    mitk::GPUVolumeMapper3D::SetDefaultProperties(node);
  }

  classname = "PlanarRectangle";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::PlanarFigureMapper3D::SetDefaultProperties(node);
  }

  classname = "PlanarEllipse";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::PlanarFigureMapper3D::SetDefaultProperties(node);
  }

  classname = "PlanarCircle";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::PlanarFigureMapper3D::SetDefaultProperties(node);
  }

  classname = "PlanarPolygon";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::PlanarFigureMapper3D::SetDefaultProperties(node);
  }

}

const char* mitk::DiffusionCoreObjectFactory::GetFileExtensions()
{
  std::string fileExtension;
  this->CreateFileExtensions(m_FileExtensionsMap, fileExtension);
  return fileExtension.c_str();
}

mitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetFileExtensionsMap()
{
  return m_FileExtensionsMap;
}

const char* mitk::DiffusionCoreObjectFactory::GetSaveFileExtensions()
{
  std::string fileExtension;
  this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension);
  return fileExtension.c_str();
}

mitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetSaveFileExtensionsMap()
{
  return m_SaveFileExtensionsMap;
}

void mitk::DiffusionCoreObjectFactory::CreateFileExtensionsMap()
{
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.dwi", "Diffusion Weighted Images"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdwi", "Diffusion Weighted Images"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.nii", "Diffusion Weighted Images for FSL"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.fsl", "Diffusion Weighted Images for FSL"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.fslgz", "Diffusion Weighted Images for FSL"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.qbi", "Q-Ball Images"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.hqbi", "Q-Ball Images"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.dti", "Tensor Images"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdti", "Tensor Images"));
  //  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.pf", "Planar Figure File"));

  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.dwi", "Diffusion Weighted Images"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdwi", "Diffusion Weighted Images"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.nii", "Diffusion Weighted Images for FSL"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.fsl", "Diffusion Weighted Images for FSL"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.fslgz", "Diffusion Weighted Images for FSL"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.qbi", "Q-Ball Images"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.hqbi", "Q-Ball Images"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.dti", "Tensor Images"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdti", "Tensor Images"));
  // m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.pf", "Planar Figure File"));

}

void mitk::DiffusionCoreObjectFactory::RegisterIOFactories()
{
}

struct RegisterDiffusionCoreObjectFactory{
  RegisterDiffusionCoreObjectFactory()
    : m_Factory( mitk::DiffusionCoreObjectFactory::New() )
  {
    mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory( m_Factory );
  }

  ~RegisterDiffusionCoreObjectFactory()
  {
    mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory( m_Factory );
  }

  mitk::DiffusionCoreObjectFactory::Pointer m_Factory;
};

static RegisterDiffusionCoreObjectFactory registerPlanarFigureObjectFactory;

<commit_msg>rename static registerFactory variable<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkDiffusionCoreObjectFactory.h"

#include "mitkProperties.h"
#include "mitkBaseRenderer.h"
#include "mitkDataNode.h"

#include "mitkNrrdDiffusionImageIOFactory.h"
#include "mitkNrrdDiffusionImageWriterFactory.h"
#include "mitkNrrdDiffusionImageWriter.h"
#include "mitkDiffusionImage.h"

#include "mitkNrrdQBallImageIOFactory.h"
#include "mitkNrrdQBallImageWriterFactory.h"
#include "mitkNrrdQBallImageWriter.h"

#include "mitkNrrdTensorImageIOFactory.h"
#include "mitkNrrdTensorImageWriterFactory.h"
#include "mitkNrrdTensorImageWriter.h"

#include "mitkCompositeMapper.h"
#include "mitkDiffusionImageMapper.h"
#include "mitkGPUVolumeMapper3D.h"
#include "mitkVolumeDataVtkMapper3D.h"

#include "mitkPlanarFigureMapper3D.h"

typedef short DiffusionPixelType;

typedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageShort;
typedef std::multimap<std::string, std::string> MultimapType;

mitk::DiffusionCoreObjectFactory::DiffusionCoreObjectFactory()
  :CoreObjectFactoryBase()
{

  static bool alreadyDone = false;
  if (!alreadyDone)
  {
    MITK_DEBUG << "DiffusionCoreObjectFactory c'tor" << std::endl;
    RegisterIOFactories();

    mitk::NrrdDiffusionImageIOFactory::RegisterOneFactory();
    mitk::NrrdQBallImageIOFactory::RegisterOneFactory();
    mitk::NrrdTensorImageIOFactory::RegisterOneFactory();

    mitk::NrrdDiffusionImageWriterFactory::RegisterOneFactory();
    mitk::NrrdQBallImageWriterFactory::RegisterOneFactory();
    mitk::NrrdTensorImageWriterFactory::RegisterOneFactory();

    m_FileWriters.push_back( NrrdDiffusionImageWriter<DiffusionPixelType>::New().GetPointer() );
    m_FileWriters.push_back( NrrdQBallImageWriter::New().GetPointer() );
    m_FileWriters.push_back( NrrdTensorImageWriter::New().GetPointer() );

    mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(this);
    CreateFileExtensionsMap();

    alreadyDone = true;
  }

}

mitk::Mapper::Pointer mitk::DiffusionCoreObjectFactory::CreateMapper(mitk::DataNode* node, MapperSlotId id)
{
  mitk::Mapper::Pointer newMapper=NULL;

  if ( id == mitk::BaseRenderer::Standard2D )
  {
    std::string classname("QBallImage");
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::CompositeMapper::New();
      newMapper->SetDataNode(node);
      node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper());
    }
    classname = "TensorImage";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::CompositeMapper::New();
      newMapper->SetDataNode(node);
      node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper());
    }

    classname = "DiffusionImage";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::DiffusionImageMapper<short>::New();
      newMapper->SetDataNode(node);
    }

  }
  else if ( id == mitk::BaseRenderer::Standard3D )
  {
    std::string classname("QBallImage");
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::GPUVolumeMapper3D::New();
      newMapper->SetDataNode(node);
    }
    classname = "TensorImage";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::GPUVolumeMapper3D::New();
      newMapper->SetDataNode(node);
    }
    classname = "DiffusionImage";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::GPUVolumeMapper3D::New();
      newMapper->SetDataNode(node);
    }

    classname =  "PlanarRectangle";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::PlanarFigureMapper3D::New();
      newMapper->SetDataNode(node);
    }

    classname =  "PlanarCircle";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::PlanarFigureMapper3D::New();
      newMapper->SetDataNode(node);
    }

    classname =  "PlanarEllipse";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::PlanarFigureMapper3D::New();
      newMapper->SetDataNode(node);
    }

    classname = "PlanarPolygon";
    if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
    {
      newMapper = mitk::PlanarFigureMapper3D::New();
      newMapper->SetDataNode(node);
    }

  }

  return newMapper;
}

void mitk::DiffusionCoreObjectFactory::SetDefaultProperties(mitk::DataNode* node)
{
  std::string classname = "QBallImage";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::CompositeMapper::SetDefaultProperties(node);
    mitk::GPUVolumeMapper3D::SetDefaultProperties(node);
  }

  classname = "TensorImage";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::CompositeMapper::SetDefaultProperties(node);
    mitk::GPUVolumeMapper3D::SetDefaultProperties(node);
  }

  classname = "DiffusionImage";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::DiffusionImageMapper<short>::SetDefaultProperties(node);
    mitk::GPUVolumeMapper3D::SetDefaultProperties(node);
  }

  classname = "PlanarRectangle";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::PlanarFigureMapper3D::SetDefaultProperties(node);
  }

  classname = "PlanarEllipse";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::PlanarFigureMapper3D::SetDefaultProperties(node);
  }

  classname = "PlanarCircle";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::PlanarFigureMapper3D::SetDefaultProperties(node);
  }

  classname = "PlanarPolygon";
  if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)
  {
    mitk::PlanarFigureMapper3D::SetDefaultProperties(node);
  }

}

const char* mitk::DiffusionCoreObjectFactory::GetFileExtensions()
{
  std::string fileExtension;
  this->CreateFileExtensions(m_FileExtensionsMap, fileExtension);
  return fileExtension.c_str();
}

mitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetFileExtensionsMap()
{
  return m_FileExtensionsMap;
}

const char* mitk::DiffusionCoreObjectFactory::GetSaveFileExtensions()
{
  std::string fileExtension;
  this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension);
  return fileExtension.c_str();
}

mitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetSaveFileExtensionsMap()
{
  return m_SaveFileExtensionsMap;
}

void mitk::DiffusionCoreObjectFactory::CreateFileExtensionsMap()
{
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.dwi", "Diffusion Weighted Images"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdwi", "Diffusion Weighted Images"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.nii", "Diffusion Weighted Images for FSL"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.fsl", "Diffusion Weighted Images for FSL"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.fslgz", "Diffusion Weighted Images for FSL"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.qbi", "Q-Ball Images"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.hqbi", "Q-Ball Images"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.dti", "Tensor Images"));
  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdti", "Tensor Images"));
  //  m_FileExtensionsMap.insert(std::pair<std::string, std::string>("*.pf", "Planar Figure File"));

  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.dwi", "Diffusion Weighted Images"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdwi", "Diffusion Weighted Images"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.nii", "Diffusion Weighted Images for FSL"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.fsl", "Diffusion Weighted Images for FSL"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.fslgz", "Diffusion Weighted Images for FSL"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.qbi", "Q-Ball Images"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.hqbi", "Q-Ball Images"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.dti", "Tensor Images"));
  m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.hdti", "Tensor Images"));
  // m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>("*.pf", "Planar Figure File"));

}

void mitk::DiffusionCoreObjectFactory::RegisterIOFactories()
{
}

struct RegisterDiffusionCoreObjectFactory{
  RegisterDiffusionCoreObjectFactory()
    : m_Factory( mitk::DiffusionCoreObjectFactory::New() )
  {
    mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory( m_Factory );
  }

  ~RegisterDiffusionCoreObjectFactory()
  {
    mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory( m_Factory );
  }

  mitk::DiffusionCoreObjectFactory::Pointer m_Factory;
};

static RegisterDiffusionCoreObjectFactory registerDiffusionCoreObjectFactory;

<|endoftext|>


<commit_before>//
//  TriggerElevationChange.cpp
//  Created by Matt Kaufmann on 02/15/14.
//

#include "ExampleGame/Components/Grid/GameGrid.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Grid/GridNavigator.h"
#include "ExampleGame/Components/Grid/GridZone.h"
#include "ExampleGame/Components/ShadyCamera/ShadyCamera.h"
#include "ExampleGame/Components/Triggers/TriggerElevationChange.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "ExampleGame/Messages/Declarations.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
#include "Vajra/Engine/MessageHub/MessageHub.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Engine/Tween/Tween.h"

#include "Libraries/glm/gtx/vector_angle.hpp"

void elevationChangeTweenCallback(ObjectIdType gameObjectId, std::string /*tweenClipName*/) {
	GameObject* caller = ENGINE->GetSceneGraph3D()->GetGameObjectById(gameObjectId);

	// Make sure the switch is still around
	if (caller != nullptr) {
		TriggerElevationChange* triggerComp = caller->GetComponent<TriggerElevationChange>();
		ASSERT(triggerComp != nullptr, "elevationChangeNumberTweenCallback: Object %d has TriggerElevationChange component", gameObjectId);
		if (triggerComp != nullptr) {
			// Update the grid cells
			triggerComp->changeCellElevations(triggerComp->isToggled);
			triggerComp->setCellsInGridZonePassable(true);

			// Navigators need to update their pathfinding
			MessageChunk gridNavMessage = ENGINE->GetMessageHub()->GetOneFreeMessage();
			gridNavMessage->SetMessageType(MESSAGE_TYPE_GRID_NAVIGATION_REFRESH);
			ENGINE->GetMessageHub()->SendMulticastMessage(gridNavMessage, SINGLETONS->GetGridManagerObject()->GetId());

			// Unchild all units in zone
			for (auto iter = triggerComp->unitsInZone.begin(); iter != triggerComp->unitsInZone.end(); ++iter) {
				GameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(*iter);
				ASSERT(gObj != nullptr, "Object exists with id %d", *iter);
				if (gObj != nullptr) {
					gObj->GetParentSceneGraph()->GetRootGameObject()->AddChild_maintainTransform(*iter);

				}
			}
		}
	}
}

TriggerElevationChange::TriggerElevationChange() : Triggerable() {
	this->init();
}

TriggerElevationChange::TriggerElevationChange(Object* object_) : Triggerable(object_) {
	this->init();
}

TriggerElevationChange::~TriggerElevationChange() {
	this->destroy();
}

void TriggerElevationChange::init() {
	this->gameObjectRef = (GameObject*)this->GetObject();
	ASSERT(this->gameObjectRef->GetClassType() & CLASS_TYPE_GAMEOBJECT, "Object is a game object");

	this->elevationChange = 1;
	this->transitTime     = 1.0f;

	this->addSubscriptionToMessageType(MESSAGE_TYPE_GRID_ZONE_ENTERED, this->GetTypeId(), true);
	this->addSubscriptionToMessageType(MESSAGE_TYPE_GRID_ZONE_EXITED, this->GetTypeId(), true);
	this->addSubscriptionToMessageType(MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT, this->GetTypeId(), true);
}

void TriggerElevationChange::destroy() {
	this->removeSubscriptionToAllMessageTypes(this->GetTypeId());
}

void TriggerElevationChange::SetTriggerType(std::string typeStr) {
	Triggerable::SetTriggerType(typeStr);
}

void TriggerElevationChange::HandleMessage(MessageChunk messageChunk) {
	Triggerable::HandleMessage(messageChunk);

	switch (messageChunk->GetMessageType()) {
		case MESSAGE_TYPE_GRID_ZONE_ENTERED:
			this->onUnitEnteredZone(messageChunk->messageData.iv1.x);
			break;

		case MESSAGE_TYPE_GRID_ZONE_EXITED:
			this->onUnitExitedZone(messageChunk->messageData.iv1.x);
			break;

		case MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT:
			for (auto iter = this->unitsInZone.begin(); iter != this->unitsInZone.end(); ++iter) {
				// If it's the selected unit the camera should follow it up
				if(*iter != SINGLETONS->GetGridManager()->GetSelectedUnitId()) {
					continue;
				}
				SINGLETONS->GetGridManager()->GetShadyCamera()->FollowGameObjectDirectly(this->GetObject()->GetId());
			}
			break;
	}
}

void TriggerElevationChange::SubscribeToMySwitch() {
	Triggerable::SubscribeToMySwitch();
}

void TriggerElevationChange::SubscribeToParentSwitch() {
	Triggerable::SubscribeToParentSwitch();
}

void TriggerElevationChange::onSwitchToggled(bool /*switchState*/) {
	this->startTransition(!this->isToggled);
}

void TriggerElevationChange::onUnitEnteredZone(ObjectIdType id) {
	auto it = std::find(this->unitsInZone.begin(), this->unitsInZone.end(), id);
	if (it == this->unitsInZone.end()) {
		GameObject* unitObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(id);
		ASSERT(unitObj != nullptr, "Object exists with id %d", id);
		if (unitObj != nullptr) {
			this->unitsInZone.push_back(id);
		}
	}
	else {
		FRAMEWORK->GetLogger()->dbglog("Unit with id %d is already in zone %d", id, this->GetObject()->GetId());
	}
}

void TriggerElevationChange::onUnitExitedZone(ObjectIdType id) {
	auto it = std::find(this->unitsInZone.begin(), this->unitsInZone.end(), id);
	if (it != this->unitsInZone.end()) {
		GameObject* unitObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(id);
		ASSERT(unitObj != nullptr, "Object exists with id %d", id);
		if (unitObj != nullptr) {
			this->unitsInZone.erase(it);
		}
	}
	else {
		FRAMEWORK->GetLogger()->dbglog("Warning: Unit with id %d left zone %d without being in it", id, this->GetObject()->GetId());
	}
}

void TriggerElevationChange::startTransition(bool raised) {
	if (raised != this->isToggled) {
		this->startPositionTween(raised);
		this->setCellsInGridZonePassable(false);

		this->isToggled = raised;
	}
}

void TriggerElevationChange::startPositionTween(bool raised) {
	ObjectIdType myId = this->GetObject()->GetId();
	Transform* trans = this->GetObject()->GetComponent<Transform>();

	// Check if there's already a tween going on.
	OnGoingTransformTweenDetails* translationDetails = ENGINE->GetTween()->GetOnGoingTransformTweenDetails(myId, TRANSFORM_TWEEN_TARGET_POSITION);
	if (translationDetails == nullptr) {
		// Child all units in zone to this object before tweening.
		// glm::vec3 myPos = this->gameObjectRef->GetTransform()->GetPositionWorld();
		for (auto iter = this->unitsInZone.begin(); iter != this->unitsInZone.end(); ++iter) {

			GameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(*iter);
			ASSERT(gObj != nullptr, "Object exists with id %d", *iter);
			if (gObj != nullptr) {

				this->gameObjectRef->AddChild_maintainTransform(gObj->GetId());

				// If it's a unit that's moving, stop it:
				GridNavigator* gNav = gObj->GetComponent<GridNavigator>();
				if (gNav != nullptr) {
					gNav->StopNavigation();
				}
			}
		}

		glm::vec3 finalPosition = this->GetObject()->GetComponent<Transform>()->GetPosition();
		if (raised) {
			finalPosition.y += SINGLETONS->GetGridManager()->GetGrid()->ConvertElevationToWorldY(this->elevationChange);
		}
		else {
			finalPosition.y -= SINGLETONS->GetGridManager()->GetGrid()->ConvertElevationToWorldY(this->elevationChange);
		}

		float tweenTime = this->transitTime;

		ENGINE->GetTween()->TweenPosition(
			myId,
			finalPosition,
			tweenTime,
			true,
			TWEEN_TRANSLATION_CURVE_TYPE_LINEAR,
			false,
			elevationChangeTweenCallback
		);
	}
	else {
		// Reverse the current tween
		float tweenTime = this->transitTime - translationDetails->totalTime + translationDetails->currentTime;
		glm::vec3 diff = glm::vec3(0.0f, SINGLETONS->GetGridManager()->GetGrid()->ConvertElevationToWorldY(this->elevationChange), 0.0f);
		if (raised) {
			diff = diff * (tweenTime / this->transitTime);
		}
		else {
			diff = diff * (-tweenTime / this->transitTime);
		}

		glm::vec3 finalPosition = trans->GetPosition() + diff;

		ENGINE->GetTween()->TweenPosition(
			myId,
			finalPosition,
			tweenTime,
			true,
			TWEEN_TRANSLATION_CURVE_TYPE_LINEAR,
			false,
			elevationChangeTweenCallback
		);
	}
}

void TriggerElevationChange::setCellsInGridZonePassable(bool pass) {
	int west, east, south, north;
	// Get the grid zone component on this object.
	GridZone* zone = this->GetObject()->GetComponent<GridZone>();
	ASSERT(zone != nullptr, "Object %d with TriggerElevationChange component also has GridZone component", this->GetObject()->GetId());

	zone->GetZoneBounds(west, east, south, north);

	GameGrid* grid = SINGLETONS->GetGridManager()->GetGrid();
	for (int x = west; x <= east; ++x) {
		for (int z = south; z <= north; ++z) {
			int elevation = grid->GetCellGroundLevel(x, z);
			grid->SetCellPassableAtElevation(x, z, elevation, pass);
		}
	}

	// Navigators need to update their pathfinding
	MessageChunk gridNavMessage = ENGINE->GetMessageHub()->GetOneFreeMessage();
	gridNavMessage->SetMessageType(MESSAGE_TYPE_GRID_NAVIGATION_REFRESH);
	ENGINE->GetMessageHub()->SendMulticastMessage(gridNavMessage, SINGLETONS->GetGridManagerObject()->GetId());
}

void TriggerElevationChange::changeCellElevations(bool raised) {
	int west, east, south, north;
	// Get the grid zone component on this object.
	GridZone* zone = this->GetObject()->GetComponent<GridZone>();
	ASSERT(zone != nullptr, "Object %d with TriggerElevationChange component also has GridZone component", this->GetObject()->GetId());

	zone->GetZoneBounds(west, east, south, north);

	GameGrid* grid = SINGLETONS->GetGridManager()->GetGrid();
	int diff;
	if (raised) {
		diff = this->elevationChange;
	}
	else {
		diff = -this->elevationChange;
	}
	for (int x = west; x <= east; ++x) {
		for (int z = south; z <= north; ++z) {
			grid->ChangeCellGroundLevel(x, z, diff);
		}
	}
}
<commit_msg>Fixing a crash with the elevators.<commit_after>//
//  TriggerElevationChange.cpp
//  Created by Matt Kaufmann on 02/15/14.
//

#include "ExampleGame/Components/Grid/GameGrid.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Grid/GridNavigator.h"
#include "ExampleGame/Components/Grid/GridZone.h"
#include "ExampleGame/Components/ShadyCamera/ShadyCamera.h"
#include "ExampleGame/Components/Triggers/TriggerElevationChange.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "ExampleGame/Messages/Declarations.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
#include "Vajra/Engine/MessageHub/MessageHub.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Engine/Tween/Tween.h"

#include "Libraries/glm/gtx/vector_angle.hpp"

void elevationChangeTweenCallback(ObjectIdType gameObjectId, std::string /*tweenClipName*/) {
	GameObject* caller = ENGINE->GetSceneGraph3D()->GetGameObjectById(gameObjectId);

	// Make sure the switch is still around
	if (caller != nullptr) {
		TriggerElevationChange* triggerComp = caller->GetComponent<TriggerElevationChange>();
		ASSERT(triggerComp != nullptr, "elevationChangeNumberTweenCallback: Object %d has TriggerElevationChange component", gameObjectId);
		if (triggerComp != nullptr) {
			// Update the grid cells
			triggerComp->setCellsInGridZonePassable(true);

			// Navigators need to update their pathfinding
			MessageChunk gridNavMessage = ENGINE->GetMessageHub()->GetOneFreeMessage();
			gridNavMessage->SetMessageType(MESSAGE_TYPE_GRID_NAVIGATION_REFRESH);
			ENGINE->GetMessageHub()->SendMulticastMessage(gridNavMessage, SINGLETONS->GetGridManagerObject()->GetId());

			// Unchild all units in zone
			for (auto iter = triggerComp->unitsInZone.begin(); iter != triggerComp->unitsInZone.end(); ++iter) {
				GameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(*iter);
				ASSERT(gObj != nullptr, "Object exists with id %d", *iter);
				if (gObj != nullptr) {
					gObj->GetParentSceneGraph()->GetRootGameObject()->AddChild_maintainTransform(*iter);

				}
			}
		}
	}
}

TriggerElevationChange::TriggerElevationChange() : Triggerable() {
	this->init();
}

TriggerElevationChange::TriggerElevationChange(Object* object_) : Triggerable(object_) {
	this->init();
}

TriggerElevationChange::~TriggerElevationChange() {
	this->destroy();
}

void TriggerElevationChange::init() {
	this->gameObjectRef = (GameObject*)this->GetObject();
	ASSERT(this->gameObjectRef->GetClassType() & CLASS_TYPE_GAMEOBJECT, "Object is a game object");

	this->elevationChange = 1;
	this->transitTime     = 1.0f;

	this->addSubscriptionToMessageType(MESSAGE_TYPE_GRID_ZONE_ENTERED, this->GetTypeId(), true);
	this->addSubscriptionToMessageType(MESSAGE_TYPE_GRID_ZONE_EXITED, this->GetTypeId(), true);
	this->addSubscriptionToMessageType(MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT, this->GetTypeId(), true);
}

void TriggerElevationChange::destroy() {
	this->removeSubscriptionToAllMessageTypes(this->GetTypeId());
}

void TriggerElevationChange::SetTriggerType(std::string typeStr) {
	Triggerable::SetTriggerType(typeStr);
}

void TriggerElevationChange::HandleMessage(MessageChunk messageChunk) {
	Triggerable::HandleMessage(messageChunk);

	switch (messageChunk->GetMessageType()) {
		case MESSAGE_TYPE_GRID_ZONE_ENTERED:
			this->onUnitEnteredZone(messageChunk->messageData.iv1.x);
			break;

		case MESSAGE_TYPE_GRID_ZONE_EXITED:
			this->onUnitExitedZone(messageChunk->messageData.iv1.x);
			break;

		case MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT:
			for (auto iter = this->unitsInZone.begin(); iter != this->unitsInZone.end(); ++iter) {
				// If it's the selected unit the camera should follow it up
				if(*iter != SINGLETONS->GetGridManager()->GetSelectedUnitId()) {
					continue;
				}
				SINGLETONS->GetGridManager()->GetShadyCamera()->FollowGameObjectDirectly(this->GetObject()->GetId());
			}
			break;
	}
}

void TriggerElevationChange::SubscribeToMySwitch() {
	Triggerable::SubscribeToMySwitch();
}

void TriggerElevationChange::SubscribeToParentSwitch() {
	Triggerable::SubscribeToParentSwitch();
}

void TriggerElevationChange::onSwitchToggled(bool /*switchState*/) {
	this->startTransition(!this->isToggled);
}

void TriggerElevationChange::onUnitEnteredZone(ObjectIdType id) {
	auto it = std::find(this->unitsInZone.begin(), this->unitsInZone.end(), id);
	if (it == this->unitsInZone.end()) {
		GameObject* unitObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(id);
		ASSERT(unitObj != nullptr, "Object exists with id %d", id);
		if (unitObj != nullptr) {
			this->unitsInZone.push_back(id);
		}
	}
	else {
		FRAMEWORK->GetLogger()->dbglog("Unit with id %d is already in zone %d", id, this->GetObject()->GetId());
	}
}

void TriggerElevationChange::onUnitExitedZone(ObjectIdType id) {
	auto it = std::find(this->unitsInZone.begin(), this->unitsInZone.end(), id);
	if (it != this->unitsInZone.end()) {
		GameObject* unitObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(id);
		ASSERT(unitObj != nullptr, "Object exists with id %d", id);
		if (unitObj != nullptr) {
			this->unitsInZone.erase(it);
		}
	}
	else {
		FRAMEWORK->GetLogger()->dbglog("Warning: Unit with id %d left zone %d without being in it", id, this->GetObject()->GetId());
	}
}

void TriggerElevationChange::startTransition(bool raised) {
	if (raised != this->isToggled) {
		this->startPositionTween(raised);
		this->changeCellElevations(raised);
		this->setCellsInGridZonePassable(false);

		this->isToggled = raised;
	}
}

void TriggerElevationChange::startPositionTween(bool raised) {
	ObjectIdType myId = this->GetObject()->GetId();
	Transform* trans = this->GetObject()->GetComponent<Transform>();

	// Check if there's already a tween going on.
	OnGoingTransformTweenDetails* translationDetails = ENGINE->GetTween()->GetOnGoingTransformTweenDetails(myId, TRANSFORM_TWEEN_TARGET_POSITION);
	if (translationDetails == nullptr) {
		// Child all units in zone to this object before tweening.
		// glm::vec3 myPos = this->gameObjectRef->GetTransform()->GetPositionWorld();
		for (auto iter = this->unitsInZone.begin(); iter != this->unitsInZone.end(); ++iter) {

			GameObject* gObj = ENGINE->GetSceneGraph3D()->GetGameObjectById(*iter);
			ASSERT(gObj != nullptr, "Object exists with id %d", *iter);
			if (gObj != nullptr) {

				this->gameObjectRef->AddChild_maintainTransform(gObj->GetId());

				// If it's a unit that's moving, stop it:
				GridNavigator* gNav = gObj->GetComponent<GridNavigator>();
				if (gNav != nullptr) {
					gNav->StopNavigation();
				}
			}
		}

		glm::vec3 finalPosition = this->GetObject()->GetComponent<Transform>()->GetPosition();
		if (raised) {
			finalPosition.y += SINGLETONS->GetGridManager()->GetGrid()->ConvertElevationToWorldY(this->elevationChange);
		}
		else {
			finalPosition.y -= SINGLETONS->GetGridManager()->GetGrid()->ConvertElevationToWorldY(this->elevationChange);
		}

		float tweenTime = this->transitTime;

		ENGINE->GetTween()->TweenPosition(
			myId,
			finalPosition,
			tweenTime,
			true,
			TWEEN_TRANSLATION_CURVE_TYPE_LINEAR,
			false,
			elevationChangeTweenCallback
		);
	}
	else {
		// Reverse the current tween
		float tweenTime = this->transitTime - translationDetails->totalTime + translationDetails->currentTime;
		glm::vec3 diff = glm::vec3(0.0f, SINGLETONS->GetGridManager()->GetGrid()->ConvertElevationToWorldY(this->elevationChange), 0.0f);
		if (raised) {
			diff = diff * (tweenTime / this->transitTime);
		}
		else {
			diff = diff * (-tweenTime / this->transitTime);
		}

		glm::vec3 finalPosition = trans->GetPosition() + diff;

		ENGINE->GetTween()->TweenPosition(
			myId,
			finalPosition,
			tweenTime,
			true,
			TWEEN_TRANSLATION_CURVE_TYPE_LINEAR,
			false,
			elevationChangeTweenCallback
		);
	}
}

void TriggerElevationChange::setCellsInGridZonePassable(bool pass) {
	int west, east, south, north;
	// Get the grid zone component on this object.
	GridZone* zone = this->GetObject()->GetComponent<GridZone>();
	ASSERT(zone != nullptr, "Object %d with TriggerElevationChange component also has GridZone component", this->GetObject()->GetId());

	zone->GetZoneBounds(west, east, south, north);

	GameGrid* grid = SINGLETONS->GetGridManager()->GetGrid();
	for (int x = west; x <= east; ++x) {
		for (int z = south; z <= north; ++z) {
			int elevation = grid->GetCellGroundLevel(x, z);
			grid->SetCellPassableAtElevation(x, z, elevation, pass);
		}
	}

	// Navigators need to update their pathfinding
	MessageChunk gridNavMessage = ENGINE->GetMessageHub()->GetOneFreeMessage();
	gridNavMessage->SetMessageType(MESSAGE_TYPE_GRID_NAVIGATION_REFRESH);
	ENGINE->GetMessageHub()->SendMulticastMessage(gridNavMessage, SINGLETONS->GetGridManagerObject()->GetId());
}

void TriggerElevationChange::changeCellElevations(bool raised) {
	int west, east, south, north;
	// Get the grid zone component on this object.
	GridZone* zone = this->GetObject()->GetComponent<GridZone>();
	ASSERT(zone != nullptr, "Object %d with TriggerElevationChange component also has GridZone component", this->GetObject()->GetId());

	zone->GetZoneBounds(west, east, south, north);

	GameGrid* grid = SINGLETONS->GetGridManager()->GetGrid();
	int diff;
	if (raised) {
		diff = this->elevationChange;
	}
	else {
		diff = -this->elevationChange;
	}
	for (int x = west; x <= east; ++x) {
		for (int z = south; z <= north; ++z) {
			grid->ChangeCellGroundLevel(x, z, diff);
		}
	}
}
<|endoftext|>


<commit_before>
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <sstream>
#include <string>

#include "tensorflow/c/kernels/tensor_shape_utils.h"
#include "tensorflow/c/kernels.h"
#include "tensorflow/c/tf_tensor.h"
#include "tensorflow/c/tf_status.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/tstring.h"
#include "tensorflow/core/platform/strcat.h"
#include "tensorflow/core/framework/selective_registration.h"
#include "tensorflow/core/framework/summary.pb.h"
#include "tensorflow/core/framework/types.h"

namespace {

// Struct that stores the status and TF_Tensor inputs to the opkernel.
// Used to delete tensor and status in its destructor upon kernel return.
struct Params {
  TF_Tensor* tags;
  TF_Tensor* values;
  TF_Status* status;
  explicit Params(TF_OpKernelContext* ctx) : tags(nullptr),
                                             values(nullptr),
                                             status(nullptr) {
    status = TF_NewStatus();
    TF_GetInput(ctx, 0, &tags, status);
    if (TF_GetCode(status) == TF_OK) {
      TF_GetInput(ctx, 1, &values, status);
    }
  }
  ~Params() {
    TF_DeleteStatus(status);
    TF_DeleteTensor(tags);
    TF_DeleteTensor(values);
  }
};

// dummy functions used for kernel registration
void* ScalarSummaryOp_Create(TF_OpKernelConstruction* ctx) {
  return nullptr;
}

void ScalarSummaryOp_Delete(void* kernel) {}

// Helper functions for compute method
bool IsSameSize(TF_Tensor* tensor1, TF_Tensor* tensor2);
// Returns a string representation of a single tag or empty string if there
// are multiple tags
std::string SingleTag(TF_Tensor* tags);

template<typename T>
void ScalarSummaryOp_Compute(void* kernel, TF_OpKernelContext* ctx) {
  Params params(ctx);
  if (TF_GetCode(params.status) != TF_OK) {
    TF_OpKernelContext_Failure(ctx, params.status);
    return;
  }
  if (!IsSameSize(params.tags, params.values)) {
    std::ostringstream err;
    err << "tags and values are not the same shape: "
        << tensorflow::ShapeDebugString(params.tags) << " != "
        << tensorflow::ShapeDebugString(params.values)
        << SingleTag(params.tags);
    TF_SetStatus(params.status, TF_INVALID_ARGUMENT, err.str().c_str());
    TF_OpKernelContext_Failure(ctx, params.status);
    return;
  }
  // Convert tags and values tensor to array to access elements by index
  tensorflow::Summary s;
  auto tags_array = static_cast<tensorflow::tstring*>(
      TF_TensorData(params.tags));
  auto values_array = static_cast<T*>(TF_TensorData(params.values));
  // Copy tags and values into summary protobuf
  for (int i = 0; i < TF_TensorElementCount(params.tags); ++i) {
    tensorflow::Summary::Value* v = s.add_value();
    const tensorflow::tstring& Ttags_i = tags_array[i];
    v->set_tag(Ttags_i.data(), Ttags_i.size());
    v->set_simple_value(static_cast<float>(values_array[i]));
  }
  TF_Tensor* summary_tensor = TF_AllocateOutput(ctx, 0,
      TF_ExpectedOutputDataType(ctx, 0), nullptr, 0,
      sizeof(tensorflow::tstring), params.status);
  if (TF_GetCode(params.status) != TF_OK){
    TF_DeleteTensor(summary_tensor);
    TF_OpKernelContext_Failure(ctx, params.status);
    return;
  }
  tensorflow::tstring* output_tstring = reinterpret_cast<tensorflow::tstring*>(
      TF_TensorData(summary_tensor));
  CHECK(SerializeToTString(s, output_tstring));
  TF_DeleteTensor(summary_tensor);
}

bool IsSameSize(TF_Tensor* tensor1, TF_Tensor* tensor2) {
  if (TF_NumDims(tensor1) != TF_NumDims(tensor2)) {
    return false;
  }
  for (int d = 0; d < TF_NumDims(tensor1); d++) {
    if (TF_Dim(tensor1, d) != TF_Dim(tensor2, d)) {
      return false;
    }
  }
  return true;
}

std::string SingleTag(TF_Tensor* tags) {
  if (TF_TensorElementCount(tags) == 1) {
    const char* single_tag = static_cast<tensorflow::tstring*>(
        TF_TensorData(tags))->c_str();
    return tensorflow::strings::StrCat(" (tag '", single_tag, "')");
  }
  else {
    return "";
  }
}

template <typename T>
void RegisterScalarSummaryOpKernel() {
  TF_Status* status = TF_NewStatus();
  {
    auto* builder = TF_NewKernelBuilder("ScalarSummary",
                                        tensorflow::DEVICE_CPU,
                                        &ScalarSummaryOp_Create,
                                        &ScalarSummaryOp_Compute<T>,
                                        &ScalarSummaryOp_Delete);
    TF_KernelBuilder_TypeConstraint(builder, "T",
        static_cast<TF_DataType>(tensorflow::DataTypeToEnum<T>::v()), status);
    CHECK_EQ(TF_OK, TF_GetCode(status))
        << "Error while adding type constraint";
    TF_RegisterKernelBuilder("ScalarSummary", builder, status);
    CHECK_EQ(TF_OK, TF_GetCode(status))
        << "Error while registering Scalar Summmary kernel";
  }
  TF_DeleteStatus(status);
}

// A dummy static variable initialized by a lambda whose side-effect is to
// register the ScalarSummary kernel.
TF_ATTRIBUTE_UNUSED bool  IsScalarSummaryOpKernelRegistered = []() {
  if (SHOULD_REGISTER_OP_KERNEL("ScalarSummary")) {
    RegisterScalarSummaryOpKernel<tensorflow::int64>();
    RegisterScalarSummaryOpKernel<tensorflow::uint64>();
    RegisterScalarSummaryOpKernel<tensorflow::int32>();
    RegisterScalarSummaryOpKernel<tensorflow::uint32>();
    RegisterScalarSummaryOpKernel<tensorflow::uint16>();
    RegisterScalarSummaryOpKernel<tensorflow::int16>();
    RegisterScalarSummaryOpKernel<tensorflow::int8>();
    RegisterScalarSummaryOpKernel<tensorflow::uint8>();
    RegisterScalarSummaryOpKernel<Eigen::half>();
    RegisterScalarSummaryOpKernel<tensorflow::bfloat16>();
    RegisterScalarSummaryOpKernel<float>();
    RegisterScalarSummaryOpKernel<double>();
  }
  return true;
}();
} // namespace
<commit_msg>added includes for realnumbertypes<commit_after>
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <sstream>
#include <string>

#include "tensorflow/c/kernels/tensor_shape_utils.h"
#include "tensorflow/c/kernels.h"
#include "tensorflow/c/tf_tensor.h"
#include "tensorflow/c/tf_status.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/tstring.h"
#include "tensorflow/core/platform/strcat.h"
#include "tensorflow/core/platform/default/integral_types.h"
#include "tensorflow/core/framework/selective_registration.h"
#include "tensorflow/core/framework/summary.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/lib/bfloat16/bfloat16.h"

namespace {

// Struct that stores the status and TF_Tensor inputs to the opkernel.
// Used to delete tensor and status in its destructor upon kernel return.
struct Params {
  TF_Tensor* tags;
  TF_Tensor* values;
  TF_Status* status;
  explicit Params(TF_OpKernelContext* ctx) : tags(nullptr),
                                             values(nullptr),
                                             status(nullptr) {
    status = TF_NewStatus();
    TF_GetInput(ctx, 0, &tags, status);
    if (TF_GetCode(status) == TF_OK) {
      TF_GetInput(ctx, 1, &values, status);
    }
  }
  ~Params() {
    TF_DeleteStatus(status);
    TF_DeleteTensor(tags);
    TF_DeleteTensor(values);
  }
};

// dummy functions used for kernel registration
void* ScalarSummaryOp_Create(TF_OpKernelConstruction* ctx) {
  return nullptr;
}

void ScalarSummaryOp_Delete(void* kernel) {}

// Helper functions for compute method
bool IsSameSize(TF_Tensor* tensor1, TF_Tensor* tensor2);
// Returns a string representation of a single tag or empty string if there
// are multiple tags
std::string SingleTag(TF_Tensor* tags);

template<typename T>
void ScalarSummaryOp_Compute(void* kernel, TF_OpKernelContext* ctx) {
  Params params(ctx);
  if (TF_GetCode(params.status) != TF_OK) {
    TF_OpKernelContext_Failure(ctx, params.status);
    return;
  }
  if (!IsSameSize(params.tags, params.values)) {
    std::ostringstream err;
    err << "tags and values are not the same shape: "
        << tensorflow::ShapeDebugString(params.tags) << " != "
        << tensorflow::ShapeDebugString(params.values)
        << SingleTag(params.tags);
    TF_SetStatus(params.status, TF_INVALID_ARGUMENT, err.str().c_str());
    TF_OpKernelContext_Failure(ctx, params.status);
    return;
  }
  // Convert tags and values tensor to array to access elements by index
  tensorflow::Summary s;
  auto tags_array = static_cast<tensorflow::tstring*>(
      TF_TensorData(params.tags));
  auto values_array = static_cast<T*>(TF_TensorData(params.values));
  // Copy tags and values into summary protobuf
  for (int i = 0; i < TF_TensorElementCount(params.tags); ++i) {
    tensorflow::Summary::Value* v = s.add_value();
    const tensorflow::tstring& Ttags_i = tags_array[i];
    v->set_tag(Ttags_i.data(), Ttags_i.size());
    v->set_simple_value(static_cast<float>(values_array[i]));
  }
  TF_Tensor* summary_tensor = TF_AllocateOutput(ctx, 0,
      TF_ExpectedOutputDataType(ctx, 0), nullptr, 0,
      sizeof(tensorflow::tstring), params.status);
  if (TF_GetCode(params.status) != TF_OK){
    TF_DeleteTensor(summary_tensor);
    TF_OpKernelContext_Failure(ctx, params.status);
    return;
  }
  tensorflow::tstring* output_tstring = reinterpret_cast<tensorflow::tstring*>(
      TF_TensorData(summary_tensor));
  CHECK(SerializeToTString(s, output_tstring));
  TF_DeleteTensor(summary_tensor);
}

bool IsSameSize(TF_Tensor* tensor1, TF_Tensor* tensor2) {
  if (TF_NumDims(tensor1) != TF_NumDims(tensor2)) {
    return false;
  }
  for (int d = 0; d < TF_NumDims(tensor1); d++) {
    if (TF_Dim(tensor1, d) != TF_Dim(tensor2, d)) {
      return false;
    }
  }
  return true;
}

std::string SingleTag(TF_Tensor* tags) {
  if (TF_TensorElementCount(tags) == 1) {
    const char* single_tag = static_cast<tensorflow::tstring*>(
        TF_TensorData(tags))->c_str();
    return tensorflow::strings::StrCat(" (tag '", single_tag, "')");
  }
  else {
    return "";
  }
}

template <typename T>
void RegisterScalarSummaryOpKernel() {
  TF_Status* status = TF_NewStatus();
  {
    auto* builder = TF_NewKernelBuilder("ScalarSummary",
                                        tensorflow::DEVICE_CPU,
                                        &ScalarSummaryOp_Create,
                                        &ScalarSummaryOp_Compute<T>,
                                        &ScalarSummaryOp_Delete);
    TF_KernelBuilder_TypeConstraint(builder, "T",
        static_cast<TF_DataType>(tensorflow::DataTypeToEnum<T>::v()), status);
    CHECK_EQ(TF_OK, TF_GetCode(status))
        << "Error while adding type constraint";
    TF_RegisterKernelBuilder("ScalarSummary", builder, status);
    CHECK_EQ(TF_OK, TF_GetCode(status))
        << "Error while registering Scalar Summmary kernel";
  }
  TF_DeleteStatus(status);
}

// A dummy static variable initialized by a lambda whose side-effect is to
// register the ScalarSummary kernel.
TF_ATTRIBUTE_UNUSED bool  IsScalarSummaryOpKernelRegistered = []() {
  if (SHOULD_REGISTER_OP_KERNEL("ScalarSummary")) {
    RegisterScalarSummaryOpKernel<tensorflow::int64>();
    RegisterScalarSummaryOpKernel<tensorflow::uint64>();
    RegisterScalarSummaryOpKernel<tensorflow::int32>();
    RegisterScalarSummaryOpKernel<tensorflow::uint32>();
    RegisterScalarSummaryOpKernel<tensorflow::uint16>();
    RegisterScalarSummaryOpKernel<tensorflow::int16>();
    RegisterScalarSummaryOpKernel<tensorflow::int8>();
    RegisterScalarSummaryOpKernel<tensorflow::uint8>();
    RegisterScalarSummaryOpKernel<Eigen::half>();
    RegisterScalarSummaryOpKernel<tensorflow::bfloat16>();
    RegisterScalarSummaryOpKernel<float>();
    RegisterScalarSummaryOpKernel<double>();
  }
  return true;
}();
} // namespace
<|endoftext|>


<commit_before>#ifndef __FACTOR_MASTER_H__
#define __FACTOR_MASTER_H__

#define _THREAD_SAFE
#define _REENTRANT

#ifndef WINCE
#include <errno.h>
#endif

#ifdef FACTOR_DEBUG
#include <assert.h>
#endif

/* C headers */
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

/* C++ headers */
#include <vector>

#if __GNUC__ == 4
        #include <tr1/unordered_map>
        #define unordered_map std::tr1::unordered_map
#elif __GNUC__ == 3
        #include <boost/unordered_map.hpp>
        #define unordered_map boost::unordered_map
#else
        #error Factor requires GCC 3.x or later
#endif

/* Factor headers */
#include "layouts.hpp"
#include "platform.hpp"
#include "primitives.hpp"
#include "stacks.hpp"
#include "segments.hpp"
#include "contexts.hpp"
#include "run.hpp"
#include "profiler.hpp"
#include "errors.hpp"
#include "bignumint.hpp"
#include "bignum.hpp"
#include "code_block.hpp"
#include "data_heap.hpp"
#include "write_barrier.hpp"
#include "data_gc.hpp"
#include "debug.hpp"
#include "strings.hpp"
#include "tuples.hpp"
#include "words.hpp"
#include "float_bits.hpp"
#include "io.hpp"
#include "heap.hpp"
#include "image.hpp"
#include "alien.hpp"
#include "vm.hpp"
#include "tagged.hpp"
#include "local_roots.hpp"
#include "callstack.hpp"
#include "generic_arrays.hpp"
#include "arrays.hpp"
#include "math.hpp"
#include "booleans.hpp"
#include "code_heap.hpp"
#include "byte_arrays.hpp"
#include "jit.hpp"
#include "quotations.hpp"
#include "dispatch.hpp"
#include "inline_cache.hpp"
#include "factor.hpp"
#include "utilities.hpp"

#endif /* __FACTOR_MASTER_H__ */
<commit_msg>import std::tr1/boost ::unordered_map into the factor namespace instead of using #define<commit_after>#ifndef __FACTOR_MASTER_H__
#define __FACTOR_MASTER_H__

#define _THREAD_SAFE
#define _REENTRANT

#ifndef WINCE
#include <errno.h>
#endif

#ifdef FACTOR_DEBUG
#include <assert.h>
#endif

/* C headers */
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

/* C++ headers */
#include <vector>

#if __GNUC__ == 4
        #include <tr1/unordered_map>

namespace factor {
    using std::tr1::unordered_map;
}
#elif __GNUC__ == 3
        #include <boost/unordered_map.hpp>

namespace factor {
    using boost::unordered_map;
}
#else
        #error Factor requires GCC 3.x or later
#endif

/* Factor headers */
#include "layouts.hpp"
#include "platform.hpp"
#include "primitives.hpp"
#include "stacks.hpp"
#include "segments.hpp"
#include "contexts.hpp"
#include "run.hpp"
#include "profiler.hpp"
#include "errors.hpp"
#include "bignumint.hpp"
#include "bignum.hpp"
#include "code_block.hpp"
#include "data_heap.hpp"
#include "write_barrier.hpp"
#include "data_gc.hpp"
#include "debug.hpp"
#include "strings.hpp"
#include "tuples.hpp"
#include "words.hpp"
#include "float_bits.hpp"
#include "io.hpp"
#include "heap.hpp"
#include "image.hpp"
#include "alien.hpp"
#include "vm.hpp"
#include "tagged.hpp"
#include "local_roots.hpp"
#include "callstack.hpp"
#include "generic_arrays.hpp"
#include "arrays.hpp"
#include "math.hpp"
#include "booleans.hpp"
#include "code_heap.hpp"
#include "byte_arrays.hpp"
#include "jit.hpp"
#include "quotations.hpp"
#include "dispatch.hpp"
#include "inline_cache.hpp"
#include "factor.hpp"
#include "utilities.hpp"

#endif /* __FACTOR_MASTER_H__ */
<|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.

=========================================================================*/
#include "otbWrapperComplexOutputImageParameter.h"
#include "itkUnaryFunctorImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkVectorCastImageFilter.h"

#ifdef OTB_USE_MPI

#include "otbMPIConfig.h"
#include "otbMPIVrtWriter.h"

#ifdef OTB_USE_SPTW
#include "otbSimpleParallelTiffWriter.h"
#endif

#endif

namespace otb
{
namespace Wrapper
{

ComplexOutputImageParameter::ComplexOutputImageParameter()
  : m_ComplexPixelType(ComplexImagePixelType_float),
    m_DefaultComplexPixelType(ComplexImagePixelType_float),
    m_RAMValue(0)
{
  this->SetName("Complex Output Image");
  this->SetKey("cout");
}

ComplexOutputImageParameter::~ComplexOutputImageParameter()
{
}

std::string
ComplexOutputImageParameter::ConvertPixelTypeToString(ComplexImagePixelType type)
{
  std::string ret;
  switch(type)
    {
    case ComplexImagePixelType_float:
      {
      ret = "cfloat";
      break;
      }
    case ComplexImagePixelType_double:
      {
      ret = "cdouble";
      break;
      }
    }
  return ret;
}

void ComplexOutputImageParameter::InitializeWriters()
{
  m_ComplexFloatWriter = ComplexFloatWriterType::New();
  m_ComplexDoubleWriter = ComplexDoubleWriterType::New();

  m_ComplexVectorFloatWriter = ComplexVectorFloatWriterType::New();
  m_ComplexVectorDoubleWriter = ComplexVectorDoubleWriterType::New();
}

template <typename TInput, typename TOutput> void CastAndWriteImage(itk::ImageBase<2> * in, otb::ImageFileWriter<TOutput> * writer, const std::string & filename, const unsigned int & ramValue)
{
  typedef itk::CastImageFilter<TInput, TOutput> ClampFilterType;
  typename ClampFilterType::Pointer clampFilter = ClampFilterType::New();
  clampFilter->SetInput( dynamic_cast<TInput*>(in));

  bool useStandardWriter = true;

  #ifdef OTB_USE_MPI

  otb::MPIConfig::Pointer mpiConfig = otb::MPIConfig::Instance();

  if (mpiConfig->GetNbProcs() > 1)
    {
    useStandardWriter = false;

    // Get file extension
    std::string extension = itksys::SystemTools::GetFilenameExtension(filename);

    if(extension == ".vrt")
      {
      // Use the WriteMPI function
      WriteMPI(clampFilter->GetOutput(),filename,ramValue);
      }
    #ifdef OTB_USE_SPTW
    else if (extension == ".tif")
      {
      // Use simple parallel tiff writer
      typedef otb::SimpleParallelTiffWriter<TOutput> SPTWriterType;

      typename SPTWriterType::Pointer sptWriter = SPTWriterType::New();
      sptWriter->SetFileName(filename);
      sptWriter->SetInput(clampFilter->GetOutput());
      sptWriter->SetAutomaticAdaptativeStreaming(ramValue);
      sptWriter->Update();
      }

    #endif
    else
      {
      itkGenericExceptionMacro("File format "<<extension<<" not supported for parallel writing with MPI. Supported formats are .vrt and .tif. Extended filenames are not supported.");
      }

    }

  #endif

  if(useStandardWriter)
    {

    writer->SetFileName( filename );
    writer->SetInput(clampFilter->GetOutput());
    writer->SetAutomaticAdaptativeStreaming(ramValue);
    writer->Update();
    }
}

template <class TInputImageType>
void
ComplexOutputImageParameter::SwitchImageWrite()
{
  switch(m_ComplexPixelType )
    {
    case ComplexImagePixelType_float:
    {
    CastAndWriteImage<TInputImageType,ComplexFloatImageType>(m_Image,m_ComplexFloatWriter,m_FileName,m_RAMValue);
    break;
    }
    case ComplexImagePixelType_double:
    {
    CastAndWriteImage<TInputImageType,ComplexDoubleImageType>(m_Image,m_ComplexDoubleWriter,m_FileName,m_RAMValue);
    break;
    }
    }
}

template <class TInputVectorImageType>
void
ComplexOutputImageParameter::SwitchVectorImageWrite()
  {
  switch(m_ComplexPixelType )
    {
    case ComplexImagePixelType_float:
    {
    CastAndWriteImage<TInputVectorImageType,ComplexFloatVectorImageType>(m_Image,m_ComplexVectorFloatWriter,m_FileName,m_RAMValue);
    break;
    }
    case ComplexImagePixelType_double:
    {
    CastAndWriteImage<TInputVectorImageType,ComplexDoubleVectorImageType>(m_Image,m_ComplexVectorDoubleWriter,m_FileName,m_RAMValue);
    break;
    }
    }
  }

void
ComplexOutputImageParameter::Write()
{
  m_Image->UpdateOutputInformation();

  if (dynamic_cast<ComplexFloatImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<ComplexFloatImageType>();
    }
  else if (dynamic_cast<ComplexDoubleImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<ComplexDoubleImageType>();
    }
  else if (dynamic_cast<ComplexFloatVectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<ComplexFloatVectorImageType>();
    }
  else if (dynamic_cast<ComplexDoubleVectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<ComplexDoubleVectorImageType>();
    }
  else
    {
    itkExceptionMacro("Unknown complex image type");
    }
  }

itk::ProcessObject*
ComplexOutputImageParameter::GetWriter()
{
  int type = 0;
  // 0 : image
  // 1 : VectorImage

  if ( dynamic_cast<FloatVectorImageType*>( m_Image.GetPointer()) ||
       dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()))
    {
    type = 1;
    }

  itk::ProcessObject* writer = ITK_NULLPTR;
  switch ( GetComplexPixelType() )
    {
    case ComplexImagePixelType_float:
    {
    if( type == 1 )
      writer = m_ComplexVectorFloatWriter;
    else
      writer = m_ComplexFloatWriter;
    break;
    }
    case ComplexImagePixelType_double:
    {
    if( type == 1 )
      writer = m_ComplexVectorDoubleWriter;
    else
      writer = m_ComplexDoubleWriter;
    break;
    }
    }
  return writer;
}

ComplexOutputImageParameter::ImageBaseType*
ComplexOutputImageParameter::GetValue( )
{
  return m_Image;
}

void
ComplexOutputImageParameter::SetValue(ImageBaseType* image)
{
  m_Image = image;
  SetActive(true);
}

bool
ComplexOutputImageParameter::HasValue() const
{
  std::string filename(this->GetFileName());
  return !filename.empty();
}

}
}
<commit_msg>BUG: missing progress for complex output<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.

=========================================================================*/
#include "otbWrapperComplexOutputImageParameter.h"
#include "itkUnaryFunctorImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkVectorCastImageFilter.h"

#ifdef OTB_USE_MPI

#include "otbMPIConfig.h"
#include "otbMPIVrtWriter.h"

#ifdef OTB_USE_SPTW
#include "otbSimpleParallelTiffWriter.h"
#endif

#endif

namespace otb
{
namespace Wrapper
{

ComplexOutputImageParameter::ComplexOutputImageParameter()
  : m_ComplexPixelType(ComplexImagePixelType_float),
    m_DefaultComplexPixelType(ComplexImagePixelType_float),
    m_RAMValue(0)
{
  this->SetName("Complex Output Image");
  this->SetKey("cout");
}

ComplexOutputImageParameter::~ComplexOutputImageParameter()
{
}

std::string
ComplexOutputImageParameter::ConvertPixelTypeToString(ComplexImagePixelType type)
{
  std::string ret;
  switch(type)
    {
    case ComplexImagePixelType_float:
      {
      ret = "cfloat";
      break;
      }
    case ComplexImagePixelType_double:
      {
      ret = "cdouble";
      break;
      }
    }
  return ret;
}

void ComplexOutputImageParameter::InitializeWriters()
{
  m_ComplexFloatWriter = ComplexFloatWriterType::New();
  m_ComplexDoubleWriter = ComplexDoubleWriterType::New();

  m_ComplexVectorFloatWriter = ComplexVectorFloatWriterType::New();
  m_ComplexVectorDoubleWriter = ComplexVectorDoubleWriterType::New();
}

template <typename TInput, typename TOutput> void CastAndWriteImage(itk::ImageBase<2> * in, otb::ImageFileWriter<TOutput> * writer, const std::string & filename, const unsigned int & ramValue)
{
  typedef itk::CastImageFilter<TInput, TOutput> ClampFilterType;
  typename ClampFilterType::Pointer clampFilter = ClampFilterType::New();
  clampFilter->SetInput( dynamic_cast<TInput*>(in));

  bool useStandardWriter = true;

  #ifdef OTB_USE_MPI

  otb::MPIConfig::Pointer mpiConfig = otb::MPIConfig::Instance();

  if (mpiConfig->GetNbProcs() > 1)
    {
    useStandardWriter = false;

    // Get file extension
    std::string extension = itksys::SystemTools::GetFilenameExtension(filename);

    if(extension == ".vrt")
      {
      // Use the WriteMPI function
      WriteMPI(clampFilter->GetOutput(),filename,ramValue);
      }
    #ifdef OTB_USE_SPTW
    else if (extension == ".tif")
      {
      // Use simple parallel tiff writer
      typedef otb::SimpleParallelTiffWriter<TOutput> SPTWriterType;

      typename SPTWriterType::Pointer sptWriter = SPTWriterType::New();
      sptWriter->SetFileName(filename);
      sptWriter->SetInput(clampFilter->GetOutput());
      sptWriter->SetAutomaticAdaptativeStreaming(ramValue);
      sptWriter->Update();
      }

    #endif
    else
      {
      itkGenericExceptionMacro("File format "<<extension<<" not supported for parallel writing with MPI. Supported formats are .vrt and .tif. Extended filenames are not supported.");
      }

    }

  #endif

  if(useStandardWriter)
    {

    writer->SetFileName( filename );
    writer->SetInput(clampFilter->GetOutput());
    writer->SetAutomaticAdaptativeStreaming(ramValue);
    writer->Update();
    }
}

template <class TInputImageType>
void
ComplexOutputImageParameter::SwitchImageWrite()
{
  switch(m_ComplexPixelType )
    {
    case ComplexImagePixelType_float:
    {
    CastAndWriteImage<TInputImageType,ComplexFloatImageType>(m_Image,m_ComplexFloatWriter,m_FileName,m_RAMValue);
    break;
    }
    case ComplexImagePixelType_double:
    {
    CastAndWriteImage<TInputImageType,ComplexDoubleImageType>(m_Image,m_ComplexDoubleWriter,m_FileName,m_RAMValue);
    break;
    }
    }
}

template <class TInputVectorImageType>
void
ComplexOutputImageParameter::SwitchVectorImageWrite()
  {
  switch(m_ComplexPixelType )
    {
    case ComplexImagePixelType_float:
    {
    CastAndWriteImage<TInputVectorImageType,ComplexFloatVectorImageType>(m_Image,m_ComplexVectorFloatWriter,m_FileName,m_RAMValue);
    break;
    }
    case ComplexImagePixelType_double:
    {
    CastAndWriteImage<TInputVectorImageType,ComplexDoubleVectorImageType>(m_Image,m_ComplexVectorDoubleWriter,m_FileName,m_RAMValue);
    break;
    }
    }
  }

void
ComplexOutputImageParameter::Write()
{
  m_Image->UpdateOutputInformation();

  if (dynamic_cast<ComplexFloatImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<ComplexFloatImageType>();
    }
  else if (dynamic_cast<ComplexDoubleImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<ComplexDoubleImageType>();
    }
  else if (dynamic_cast<ComplexFloatVectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<ComplexFloatVectorImageType>();
    }
  else if (dynamic_cast<ComplexDoubleVectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<ComplexDoubleVectorImageType>();
    }
  else
    {
    itkExceptionMacro("Unknown complex image type");
    }
  }

itk::ProcessObject*
ComplexOutputImageParameter::GetWriter()
{
  int type = 0;
  // 0 : image
  // 1 : VectorImage

  if ( dynamic_cast<ComplexFloatVectorImageType*>( m_Image.GetPointer()) ||
       dynamic_cast<ComplexDoubleVectorImageType*>(m_Image.GetPointer()))
    {
    type = 1;
    }

  itk::ProcessObject* writer = ITK_NULLPTR;
  switch ( GetComplexPixelType() )
    {
    case ComplexImagePixelType_float:
    {
    if( type == 1 )
      writer = m_ComplexVectorFloatWriter;
    else
      writer = m_ComplexFloatWriter;
    break;
    }
    case ComplexImagePixelType_double:
    {
    if( type == 1 )
      writer = m_ComplexVectorDoubleWriter;
    else
      writer = m_ComplexDoubleWriter;
    break;
    }
    }
  return writer;
}

ComplexOutputImageParameter::ImageBaseType*
ComplexOutputImageParameter::GetValue( )
{
  return m_Image;
}

void
ComplexOutputImageParameter::SetValue(ImageBaseType* image)
{
  m_Image = image;
  SetActive(true);
}

bool
ComplexOutputImageParameter::HasValue() const
{
  std::string filename(this->GetFileName());
  return !filename.empty();
}

}
}
<|endoftext|>