<commit_before>/*
  Copyright (C) 2008 by Marten Svanfeldt

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 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
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"

#include "csutil/ref.h"
#include "iengine/engine.h"
#include "imap/services.h"
#include "imesh/animesh.h"
#include "imesh/object.h"
#include "iutil/stringarray.h"
#include "iutil/document.h"
#include "iutil/plugin.h"
#include "ivaria/reporter.h"
#include "imap/ldrctxt.h"
#include "iengine/mesh.h"
#include "imesh/skeleton2.h"
#include "imesh/skeleton2anim.h"

#include "animeshldr.h"

CS_IMPLEMENT_PLUGIN

CS_PLUGIN_NAMESPACE_BEGIN(Animeshldr)
{
  SCF_IMPLEMENT_FACTORY(AnimeshFactoryLoader);
  SCF_IMPLEMENT_FACTORY(AnimeshObjectLoader);
  SCF_IMPLEMENT_FACTORY(AnimeshFactorySaver);
  SCF_IMPLEMENT_FACTORY(AnimeshObjectSaver);

  AnimeshFactoryLoader::AnimeshFactoryLoader (iBase* parent)
    : scfImplementationType (this, parent)
  {
  }

  static const char* msgidFactory = "crystalspace.animeshfactoryloader";

  csPtr<iBase> AnimeshFactoryLoader::Parse (iDocumentNode* node,
    iStreamSource* ssource, iLoaderContext* ldr_context,
    iBase* context, iStringArray* failed)
  {
    csRef<iMeshObjectType> type = csLoadPluginCheck<iMeshObjectType> (
      object_reg, "crystalspace.mesh.object.animesh", false);

    if (!type)
    {
      synldr->ReportError (msgidFactory, node,
        "Could not load the animesh object plugin!");
      return 0;
    }

    // Create a factory
    csRef<iMeshObjectFactory> fact = type->NewFactory ();
    csRef<iAnimatedMeshFactory> amfact =
      scfQueryInterfaceSafe<iAnimatedMeshFactory> (fact);

    if (!amfact)
    {
      synldr->ReportError (msgidFactory, node,
        "Could not load the animesh object plugin!");
      return 0;
    }

    csRef<iDocumentNodeIterator> it = node->GetNodes ();
    while (it->HasNext ())
    {
      csRef<iDocumentNode> child = it->Next ();
      if (child->GetType () != CS_NODE_ELEMENT) continue;
      const char* value = child->GetValue ();
      csStringID id = xmltokens.Request (value);
      switch (id)
      {
      case XMLTOKEN_MATERIAL:
        {
          const char* matname = child->GetContentsValue ();
          iMaterialWrapper* mat = ldr_context->FindMaterial (matname);
          if (!mat)
          {
            synldr->ReportError (msgidFactory, child, "Couldn't find material '%s'!",
              matname);
            return 0;
          }
          fact->SetMaterialWrapper (mat);
        }
        break;
      case XMLTOKEN_MIXMODE:
        {
          uint mm;
          if (!synldr->ParseMixmode (child, mm))
            return 0;
          fact->SetMixMode (mm);
        }
        break;
      case XMLTOKEN_VERTEX:
        {
          csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
          if (!rb)
          {
            synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
            return 0;
          }
          amfact->SetVertices (rb);
        }
        break;
      case XMLTOKEN_TEXCOORD:
        {
          csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
          if (!rb)
          {
            synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
            return 0;
          }
          amfact->SetTexCoords (rb);
        }
        break;
      case XMLTOKEN_NORMAL:
        {
          csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
          if (!rb)
          {
            synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
            return 0;
          }
          amfact->SetNormals (rb);
        }
        break;
      case XMLTOKEN_TANGENT:
        {
          csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
          if (!rb)
          {
            synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
            return 0;
          }
          amfact->SetTangents (rb);
        }
        break;
      case XMLTOKEN_BINORMAL:
        {
          csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
          if (!rb)
          {
            synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
            return 0;
          }
          amfact->SetBinormals (rb);
        }
        break;
      case XMLTOKEN_COLOR:
        {
          csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
          if (!rb)
          {
            synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
            return 0;
          }
          amfact->SetColors (rb);
        }
        break;
      case XMLTOKEN_BONEINFLUENCES:
        {
          int wantedPerVertex = child->GetAttributeValueAsInt ("bonespervertex");
          if (!wantedPerVertex)
            amfact->SetBoneInfluencesPerVertex (wantedPerVertex);

          int realPerVertex = amfact->GetBoneInfluencesPerVertex ();
          int numVerts = amfact->GetVertexCount ();
          int currInfl = 0;

          csAnimatedMeshBoneInfluence* bi = amfact->GetBoneInfluences ();

          csRef<iDocumentNodeIterator> it = child->GetNodes ();
          while (it->HasNext ())
          {
            csRef<iDocumentNode> child2 = it->Next ();
            if (child2->GetType () != CS_NODE_ELEMENT) continue;
            const char* value = child2->GetValue ();
            csStringID id = xmltokens.Request (value);
            switch (id)
            {
            case XMLTOKEN_BI:
              {
                if (currInfl > numVerts*realPerVertex)
                {
                  synldr->ReportError (msgidFactory, child,
                    "Too many bone vertex influences %d, expected %d", currInfl, numVerts*realPerVertex);
                  return 0;
                }

                bi[currInfl].bone = child2->GetAttributeValueAsInt("bone");
                bi[currInfl].influenceWeight = child2->GetAttributeValueAsFloat ("weight");
                currInfl++;
              }
              break;
            default:
              synldr->ReportBadToken (child2);
              return 0;
            }
          }
        }
        break;
      case XMLTOKEN_SUBMESH:
        {
          // Handle submesh
          csRef<iRenderBuffer> indexBuffer;

          csRef<iDocumentNodeIterator> it = child->GetNodes ();
          while (it->HasNext ())
          {
            csRef<iDocumentNode> child2 = it->Next ();
            if (child2->GetType () != CS_NODE_ELEMENT) continue;
            const char* value = child2->GetValue ();
            csStringID id = xmltokens.Request (value);
            switch (id)
            {
            case XMLTOKEN_INDEX:
              {
                indexBuffer = synldr->ParseRenderBuffer (child2);
                if (!indexBuffer)
                {
                  synldr->ReportError (msgidFactory, child2, "Could not parse render buffer!");
                  return 0;
                }
              }
              break;
            default:
              synldr->ReportBadToken (child2);
              return 0;
            }
          }

          if (indexBuffer)
          {
            amfact->CreateSubMesh (indexBuffer);
          }
        }
        break;
      case XMLTOKEN_SKELETON:
        {
          if (!skelMgr)
          {
            skelMgr = csQueryRegistry<iSkeletonManager2> (object_reg);

            if (!skelMgr)
            {
              synldr->ReportError (msgidFactory, child, "Could not find any loaded skeletons");
              return 0;
            }
          }

          const char* skelName = child->GetContentsValue ();
          iSkeletonFactory2* skelFact = skelMgr->FindSkeletonFactory (skelName);
          if (!skelFact)
          {
            synldr->ReportError (msgidFactory, child, "Could not find skeleton %s", skelName);
            return 0;
          }

          amfact->SetSkeletonFactory (skelFact);
        }
        break;
      case XMLTOKEN_MORPHTARGET:
        if (!ParseMorphTarget (child, amfact))
	  return 0;
	break;
      default:
        synldr->ReportBadToken (child);
        return 0;
      }
    }

    // Recalc stuff
    amfact->Invalidate ();

    return csPtr<iBase> (fact);
  }

  bool AnimeshFactoryLoader::ParseMorphTarget (iDocumentNode* child,
					       iAnimatedMeshFactory* amfact)
  {
    const char* name = child->GetAttributeValue ("name");

    csRef<iRenderBuffer> offsetsBuffer;

    csRef<iDocumentNodeIterator> it = child->GetNodes ();
    while (it->HasNext ())
    {
      csRef<iDocumentNode> child2 = it->Next ();
      if (child2->GetType () != CS_NODE_ELEMENT) continue;
      const char* value = child2->GetValue ();
      csStringID id = xmltokens.Request (value);
      switch (id)
      {
      case XMLTOKEN_OFFSETS:
	{
	  offsetsBuffer = synldr->ParseRenderBuffer (child2);
	  if (!offsetsBuffer)
	  {
	    synldr->ReportError (msgidFactory, child2, "Could not parse render buffer!");
	    return false;
	  }
	}
	break;
      default:
	synldr->ReportBadToken (child2);
	return false;
      }
    }

    iAnimatedMeshMorphTarget* morphTarget = amfact->CreateMorphTarget (name);
    morphTarget->SetVertexOffsets (offsetsBuffer);
    morphTarget->Invalidate();
    return true;
  }

  bool AnimeshFactoryLoader::Initialize (iObjectRegistry* objReg)
  {
    object_reg = objReg;

    synldr = csQueryRegistry<iSyntaxService> (object_reg);

    InitTokenTable (xmltokens);
    return true;
  }

  //-------------------------------------------------------------------------

  AnimeshFactorySaver::AnimeshFactorySaver (iBase* parent)
    : scfImplementationType (this, parent)
  {}

  bool AnimeshFactorySaver::WriteDown (iBase *obj, iDocumentNode* parent,
    iStreamSource*)
  {
    return false;
  }

  bool AnimeshFactorySaver::Initialize (iObjectRegistry*)
  {
    return false;
  }

  AnimeshObjectLoader::AnimeshObjectLoader (iBase* parent)
    : scfImplementationType (this, parent)
  {}

  csPtr<iBase> AnimeshObjectLoader::Parse (iDocumentNode* node,
    iStreamSource* ssource, iLoaderContext* ldr_context,
    iBase* context, iStringArray* failedMeshFacts)
  {
    static const char* msgid = "crystalspace.animeshloader";

    csRef<iMeshObject> mesh;
    csRef<iAnimatedMesh> ammesh;

    csRef<iDocumentNodeIterator> it = node->GetNodes ();
    while (it->HasNext ())
    {
      csRef<iDocumentNode> child = it->Next ();
      if (child->GetType () != CS_NODE_ELEMENT) continue;
      const char* value = child->GetValue ();
      csStringID id = xmltokens.Request (value);
      switch (id)
      {
      case XMLTOKEN_FACTORY:
        {
          const char* factname = child->GetContentsValue ();
          iMeshFactoryWrapper* fact = ldr_context->FindMeshFactory (factname);

          if(failedMeshFacts)
          {
            // Check for failed meshfact load.
            int i = 0;
            while(!fact)
            {
              if(failedMeshFacts->GetSize() != 0 &&
                !strcmp(failedMeshFacts->Get(i), factname))
              {
                synldr->ReportError (msgid, child,
                  "Couldn't find factory '%s'!", factname);
                return 0;
              }

              if(i >= (int)(failedMeshFacts->GetSize()-1))
              {
                fact = ldr_context->FindMeshFactory (factname);
                i = 0;
              }
              else
              {
                i++;
              }
            }
          }
          else if(!fact)
          {
            synldr->ReportError (msgid, child,
              "Couldn't find factory '%s'!", factname);
            return 0;
          }

          csRef<iAnimatedMeshFactory> amfact =
            scfQueryInterface<iAnimatedMeshFactory> (fact->GetMeshObjectFactory ());
          if (!amfact)
          {
            synldr->ReportError (msgid, child,
              "Factory '%s' doesn't appear to be a animesh factory!", factname);
            return 0;
          }

          mesh = fact->GetMeshObjectFactory ()->NewInstance ();
          ammesh = scfQueryInterface<iAnimatedMesh> (mesh);
          if (!ammesh)
          {
            synldr->ReportError (msgid, child,
              "Factory '%s' doesn't appear to be a animesh factory!", factname);
            return 0;
          }
        }
        break;
      case XMLTOKEN_MATERIAL:
        {
          const char* matname = child->GetContentsValue ();
          iMaterialWrapper* mat = ldr_context->FindMaterial (matname);
          if (!mat)
          {
            synldr->ReportError (msgid, child, "Couldn't find material '%s'!",
              matname);
            return 0;
          }
          mesh->SetMaterialWrapper (mat);
        }
        break;
      case XMLTOKEN_MIXMODE:
        {
          uint mm;
          if (!synldr->ParseMixmode (child, mm))
            return 0;
          mesh->SetMixMode (mm);
        }
        break;
      case XMLTOKEN_SKELETON:
        {
          if (!skelMgr)
          {
            skelMgr = csQueryRegistry<iSkeletonManager2> (object_reg);

            if (!skelMgr)
            {
              synldr->ReportError (msgid, child, "Could not find any loaded skeletons");
              return 0;
            }
          }

          const char* skelName = child->GetContentsValue ();
          iSkeletonFactory2* skelFact = skelMgr->FindSkeletonFactory (skelName);
          if (!skelFact)
          {
            synldr->ReportError (msgid, child, "Could not find skeleton %s", skelName);
            return 0;
          }

          csRef<iSkeleton2> skeleton = skelFact->CreateSkeleton ();
          ammesh->SetSkeleton (skeleton);
        }
        break;
      case XMLTOKEN_ANIMATIONPACKET:
        {
          if (!skelMgr)
          {
            skelMgr = csQueryRegistry<iSkeletonManager2> (object_reg);

            if (!skelMgr)
            {
              synldr->ReportError (msgid, child, "Could not find any loaded skeletons");
              return 0;
            }
          }

          iSkeleton2* skeleton = ammesh->GetSkeleton ();
          if (!skeleton)
          {
            synldr->ReportError (msgid, child, "Mesh does not have a skeleton");
            return 0;
          }

          const char* packetName = child->GetContentsValue ();
          iSkeletonAnimPacketFactory2* packetFact = skelMgr->FindAnimPacketFactory (packetName);
          if (!packetFact)
          {
            synldr->ReportError (msgid, child, "Could not find animation packet %s", packetName);
            return 0;
          }

          csRef<iSkeletonAnimPacket2> packet = packetFact->CreateInstance (skeleton);
          skeleton->SetAnimationPacket (packet);
        }
        break;
      default:
        synldr->ReportBadToken (child);
        return 0;
      }
    }

    return csPtr<iBase> (mesh);
  }

  bool AnimeshObjectLoader::Initialize (iObjectRegistry* objReg)
  {
    object_reg = objReg;

    synldr = csQueryRegistry<iSyntaxService> (object_reg);

    InitTokenTable (xmltokens);
    return true;
  }

  AnimeshObjectSaver::AnimeshObjectSaver (iBase* parent)
    : scfImplementationType (this, parent)
  {}

  bool AnimeshObjectSaver::WriteDown (iBase *obj, iDocumentNode* parent,
    iStreamSource*)
  {
    return false;
  }

  bool AnimeshObjectSaver::Initialize (iObjectRegistry*)
  {
    return false;
  }

}
CS_PLUGIN_NAMESPACE_END(Animeshldr)

<commit_msg>Remove another "busy mesh factory wait"<commit_after>/*
  Copyright (C) 2008 by Marten Svanfeldt

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 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
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public
  License along with this library; if not, write to the Free
  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"

#include "csutil/ref.h"
#include "iengine/engine.h"
#include "imap/services.h"
#include "imesh/animesh.h"
#include "imesh/object.h"
#include "iutil/stringarray.h"
#include "iutil/document.h"
#include "iutil/plugin.h"
#include "ivaria/reporter.h"
#include "imap/ldrctxt.h"
#include "iengine/mesh.h"
#include "imesh/skeleton2.h"
#include "imesh/skeleton2anim.h"

#include "animeshldr.h"

CS_IMPLEMENT_PLUGIN

CS_PLUGIN_NAMESPACE_BEGIN(Animeshldr)
{
  SCF_IMPLEMENT_FACTORY(AnimeshFactoryLoader);
  SCF_IMPLEMENT_FACTORY(AnimeshObjectLoader);
  SCF_IMPLEMENT_FACTORY(AnimeshFactorySaver);
  SCF_IMPLEMENT_FACTORY(AnimeshObjectSaver);

  AnimeshFactoryLoader::AnimeshFactoryLoader (iBase* parent)
    : scfImplementationType (this, parent)
  {
  }

  static const char* msgidFactory = "crystalspace.animeshfactoryloader";

  csPtr<iBase> AnimeshFactoryLoader::Parse (iDocumentNode* node,
    iStreamSource* ssource, iLoaderContext* ldr_context,
    iBase* context, iStringArray* failed)
  {
    csRef<iMeshObjectType> type = csLoadPluginCheck<iMeshObjectType> (
      object_reg, "crystalspace.mesh.object.animesh", false);

    if (!type)
    {
      synldr->ReportError (msgidFactory, node,
        "Could not load the animesh object plugin!");
      return 0;
    }

    // Create a factory
    csRef<iMeshObjectFactory> fact = type->NewFactory ();
    csRef<iAnimatedMeshFactory> amfact =
      scfQueryInterfaceSafe<iAnimatedMeshFactory> (fact);

    if (!amfact)
    {
      synldr->ReportError (msgidFactory, node,
        "Could not load the animesh object plugin!");
      return 0;
    }

    csRef<iDocumentNodeIterator> it = node->GetNodes ();
    while (it->HasNext ())
    {
      csRef<iDocumentNode> child = it->Next ();
      if (child->GetType () != CS_NODE_ELEMENT) continue;
      const char* value = child->GetValue ();
      csStringID id = xmltokens.Request (value);
      switch (id)
      {
      case XMLTOKEN_MATERIAL:
        {
          const char* matname = child->GetContentsValue ();
          iMaterialWrapper* mat = ldr_context->FindMaterial (matname);
          if (!mat)
          {
            synldr->ReportError (msgidFactory, child, "Couldn't find material '%s'!",
              matname);
            return 0;
          }
          fact->SetMaterialWrapper (mat);
        }
        break;
      case XMLTOKEN_MIXMODE:
        {
          uint mm;
          if (!synldr->ParseMixmode (child, mm))
            return 0;
          fact->SetMixMode (mm);
        }
        break;
      case XMLTOKEN_VERTEX:
        {
          csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
          if (!rb)
          {
            synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
            return 0;
          }
          amfact->SetVertices (rb);
        }
        break;
      case XMLTOKEN_TEXCOORD:
        {
          csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
          if (!rb)
          {
            synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
            return 0;
          }
          amfact->SetTexCoords (rb);
        }
        break;
      case XMLTOKEN_NORMAL:
        {
          csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
          if (!rb)
          {
            synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
            return 0;
          }
          amfact->SetNormals (rb);
        }
        break;
      case XMLTOKEN_TANGENT:
        {
          csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
          if (!rb)
          {
            synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
            return 0;
          }
          amfact->SetTangents (rb);
        }
        break;
      case XMLTOKEN_BINORMAL:
        {
          csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
          if (!rb)
          {
            synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
            return 0;
          }
          amfact->SetBinormals (rb);
        }
        break;
      case XMLTOKEN_COLOR:
        {
          csRef<iRenderBuffer> rb = synldr->ParseRenderBuffer (child);
          if (!rb)
          {
            synldr->ReportError (msgidFactory, child, "Could not parse render buffer!");
            return 0;
          }
          amfact->SetColors (rb);
        }
        break;
      case XMLTOKEN_BONEINFLUENCES:
        {
          int wantedPerVertex = child->GetAttributeValueAsInt ("bonespervertex");
          if (!wantedPerVertex)
            amfact->SetBoneInfluencesPerVertex (wantedPerVertex);

          int realPerVertex = amfact->GetBoneInfluencesPerVertex ();
          int numVerts = amfact->GetVertexCount ();
          int currInfl = 0;

          csAnimatedMeshBoneInfluence* bi = amfact->GetBoneInfluences ();

          csRef<iDocumentNodeIterator> it = child->GetNodes ();
          while (it->HasNext ())
          {
            csRef<iDocumentNode> child2 = it->Next ();
            if (child2->GetType () != CS_NODE_ELEMENT) continue;
            const char* value = child2->GetValue ();
            csStringID id = xmltokens.Request (value);
            switch (id)
            {
            case XMLTOKEN_BI:
              {
                if (currInfl > numVerts*realPerVertex)
                {
                  synldr->ReportError (msgidFactory, child,
                    "Too many bone vertex influences %d, expected %d", currInfl, numVerts*realPerVertex);
                  return 0;
                }

                bi[currInfl].bone = child2->GetAttributeValueAsInt("bone");
                bi[currInfl].influenceWeight = child2->GetAttributeValueAsFloat ("weight");
                currInfl++;
              }
              break;
            default:
              synldr->ReportBadToken (child2);
              return 0;
            }
          }
        }
        break;
      case XMLTOKEN_SUBMESH:
        {
          // Handle submesh
          csRef<iRenderBuffer> indexBuffer;

          csRef<iDocumentNodeIterator> it = child->GetNodes ();
          while (it->HasNext ())
          {
            csRef<iDocumentNode> child2 = it->Next ();
            if (child2->GetType () != CS_NODE_ELEMENT) continue;
            const char* value = child2->GetValue ();
            csStringID id = xmltokens.Request (value);
            switch (id)
            {
            case XMLTOKEN_INDEX:
              {
                indexBuffer = synldr->ParseRenderBuffer (child2);
                if (!indexBuffer)
                {
                  synldr->ReportError (msgidFactory, child2, "Could not parse render buffer!");
                  return 0;
                }
              }
              break;
            default:
              synldr->ReportBadToken (child2);
              return 0;
            }
          }

          if (indexBuffer)
          {
            amfact->CreateSubMesh (indexBuffer);
          }
        }
        break;
      case XMLTOKEN_SKELETON:
        {
          if (!skelMgr)
          {
            skelMgr = csQueryRegistry<iSkeletonManager2> (object_reg);

            if (!skelMgr)
            {
              synldr->ReportError (msgidFactory, child, "Could not find any loaded skeletons");
              return 0;
            }
          }

          const char* skelName = child->GetContentsValue ();
          iSkeletonFactory2* skelFact = skelMgr->FindSkeletonFactory (skelName);
          if (!skelFact)
          {
            synldr->ReportError (msgidFactory, child, "Could not find skeleton %s", skelName);
            return 0;
          }

          amfact->SetSkeletonFactory (skelFact);
        }
        break;
      case XMLTOKEN_MORPHTARGET:
        if (!ParseMorphTarget (child, amfact))
	  return 0;
	break;
      default:
        synldr->ReportBadToken (child);
        return 0;
      }
    }

    // Recalc stuff
    amfact->Invalidate ();

    return csPtr<iBase> (fact);
  }

  bool AnimeshFactoryLoader::ParseMorphTarget (iDocumentNode* child,
					       iAnimatedMeshFactory* amfact)
  {
    const char* name = child->GetAttributeValue ("name");

    csRef<iRenderBuffer> offsetsBuffer;

    csRef<iDocumentNodeIterator> it = child->GetNodes ();
    while (it->HasNext ())
    {
      csRef<iDocumentNode> child2 = it->Next ();
      if (child2->GetType () != CS_NODE_ELEMENT) continue;
      const char* value = child2->GetValue ();
      csStringID id = xmltokens.Request (value);
      switch (id)
      {
      case XMLTOKEN_OFFSETS:
	{
	  offsetsBuffer = synldr->ParseRenderBuffer (child2);
	  if (!offsetsBuffer)
	  {
	    synldr->ReportError (msgidFactory, child2, "Could not parse render buffer!");
	    return false;
	  }
	}
	break;
      default:
	synldr->ReportBadToken (child2);
	return false;
      }
    }

    iAnimatedMeshMorphTarget* morphTarget = amfact->CreateMorphTarget (name);
    morphTarget->SetVertexOffsets (offsetsBuffer);
    morphTarget->Invalidate();
    return true;
  }

  bool AnimeshFactoryLoader::Initialize (iObjectRegistry* objReg)
  {
    object_reg = objReg;

    synldr = csQueryRegistry<iSyntaxService> (object_reg);

    InitTokenTable (xmltokens);
    return true;
  }

  //-------------------------------------------------------------------------

  AnimeshFactorySaver::AnimeshFactorySaver (iBase* parent)
    : scfImplementationType (this, parent)
  {}

  bool AnimeshFactorySaver::WriteDown (iBase *obj, iDocumentNode* parent,
    iStreamSource*)
  {
    return false;
  }

  bool AnimeshFactorySaver::Initialize (iObjectRegistry*)
  {
    return false;
  }

  AnimeshObjectLoader::AnimeshObjectLoader (iBase* parent)
    : scfImplementationType (this, parent)
  {}

  csPtr<iBase> AnimeshObjectLoader::Parse (iDocumentNode* node,
    iStreamSource* ssource, iLoaderContext* ldr_context,
    iBase* context, iStringArray* failedMeshFacts)
  {
    static const char* msgid = "crystalspace.animeshloader";

    csRef<iMeshObject> mesh;
    csRef<iAnimatedMesh> ammesh;

    csRef<iDocumentNodeIterator> it = node->GetNodes ();
    while (it->HasNext ())
    {
      csRef<iDocumentNode> child = it->Next ();
      if (child->GetType () != CS_NODE_ELEMENT) continue;
      const char* value = child->GetValue ();
      csStringID id = xmltokens.Request (value);
      switch (id)
      {
      case XMLTOKEN_FACTORY:
        {
          const char* factname = child->GetContentsValue ();
          iMeshFactoryWrapper* fact = ldr_context->FindMeshFactory (factname);

          if(!fact)
          {
            synldr->ReportError (msgid, child,
              "Couldn't find factory '%s'!", factname);
            return 0;
          }

          csRef<iAnimatedMeshFactory> amfact =
            scfQueryInterface<iAnimatedMeshFactory> (fact->GetMeshObjectFactory ());
          if (!amfact)
          {
            synldr->ReportError (msgid, child,
              "Factory '%s' doesn't appear to be a animesh factory!", factname);
            return 0;
          }

          mesh = fact->GetMeshObjectFactory ()->NewInstance ();
          ammesh = scfQueryInterface<iAnimatedMesh> (mesh);
          if (!ammesh)
          {
            synldr->ReportError (msgid, child,
              "Factory '%s' doesn't appear to be a animesh factory!", factname);
            return 0;
          }
        }
        break;
      case XMLTOKEN_MATERIAL:
        {
          const char* matname = child->GetContentsValue ();
          iMaterialWrapper* mat = ldr_context->FindMaterial (matname);
          if (!mat)
          {
            synldr->ReportError (msgid, child, "Couldn't find material '%s'!",
              matname);
            return 0;
          }
          mesh->SetMaterialWrapper (mat);
        }
        break;
      case XMLTOKEN_MIXMODE:
        {
          uint mm;
          if (!synldr->ParseMixmode (child, mm))
            return 0;
          mesh->SetMixMode (mm);
        }
        break;
      case XMLTOKEN_SKELETON:
        {
          if (!skelMgr)
          {
            skelMgr = csQueryRegistry<iSkeletonManager2> (object_reg);

            if (!skelMgr)
            {
              synldr->ReportError (msgid, child, "Could not find any loaded skeletons");
              return 0;
            }
          }

          const char* skelName = child->GetContentsValue ();
          iSkeletonFactory2* skelFact = skelMgr->FindSkeletonFactory (skelName);
          if (!skelFact)
          {
            synldr->ReportError (msgid, child, "Could not find skeleton %s", skelName);
            return 0;
          }

          csRef<iSkeleton2> skeleton = skelFact->CreateSkeleton ();
          ammesh->SetSkeleton (skeleton);
        }
        break;
      case XMLTOKEN_ANIMATIONPACKET:
        {
          if (!skelMgr)
          {
            skelMgr = csQueryRegistry<iSkeletonManager2> (object_reg);

            if (!skelMgr)
            {
              synldr->ReportError (msgid, child, "Could not find any loaded skeletons");
              return 0;
            }
          }

          iSkeleton2* skeleton = ammesh->GetSkeleton ();
          if (!skeleton)
          {
            synldr->ReportError (msgid, child, "Mesh does not have a skeleton");
            return 0;
          }

          const char* packetName = child->GetContentsValue ();
          iSkeletonAnimPacketFactory2* packetFact = skelMgr->FindAnimPacketFactory (packetName);
          if (!packetFact)
          {
            synldr->ReportError (msgid, child, "Could not find animation packet %s", packetName);
            return 0;
          }

          csRef<iSkeletonAnimPacket2> packet = packetFact->CreateInstance (skeleton);
          skeleton->SetAnimationPacket (packet);
        }
        break;
      default:
        synldr->ReportBadToken (child);
        return 0;
      }
    }

    return csPtr<iBase> (mesh);
  }

  bool AnimeshObjectLoader::Initialize (iObjectRegistry* objReg)
  {
    object_reg = objReg;

    synldr = csQueryRegistry<iSyntaxService> (object_reg);

    InitTokenTable (xmltokens);
    return true;
  }

  AnimeshObjectSaver::AnimeshObjectSaver (iBase* parent)
    : scfImplementationType (this, parent)
  {}

  bool AnimeshObjectSaver::WriteDown (iBase *obj, iDocumentNode* parent,
    iStreamSource*)
  {
    return false;
  }

  bool AnimeshObjectSaver::Initialize (iObjectRegistry*)
  {
    return false;
  }

}
CS_PLUGIN_NAMESPACE_END(Animeshldr)

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: generictoolboxcontroller.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:53:38 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __SVTOOLS_GENERICTOOLBOXCONTROLLER_HXX_
#include "generictoolboxcontroller.hxx"
#endif

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;

namespace svt
{

struct ExecuteInfo
{
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >     xDispatch;
    ::com::sun::star::util::URL                                                aTargetURL;
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >  aArgs;
};

GenericToolboxController::GenericToolboxController( const Reference< XMultiServiceFactory >& rServiceManager,
                                                    const Reference< XFrame >&               rFrame,
                                                    ToolBox*                                 pToolbox,
                                                    USHORT                                   nID,
                                                    const OUString&                          aCommand ) :
    svt::ToolboxController( rServiceManager, rFrame, aCommand )
    ,   m_pToolbox( pToolbox )
    ,   m_nID( nID )
{
    // Initialization is done through ctor
    m_bInitialized = sal_True;

    // insert main command to our listener map
    if ( m_aCommandURL.getLength() )
        m_aListenerMap.insert( URLToDispatchMap::value_type( aCommand, Reference< XDispatch >() ));
}

GenericToolboxController::~GenericToolboxController()
{
}

void SAL_CALL GenericToolboxController::dispose()
throw ( RuntimeException )
{
    vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

    svt::ToolboxController::dispose();

    m_pToolbox = 0;
    m_nID = 0;
}

void SAL_CALL GenericToolboxController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
    Reference< XDispatch >       xDispatch;
    Reference< XURLTransformer > xURLTransformer;
    OUString                     aCommandURL;

    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

        if ( m_bDisposed )
            throw DisposedException();

        if ( m_bInitialized &&
             m_xFrame.is() &&
             m_xServiceManager.is() &&
             m_aCommandURL.getLength() )
        {
            xURLTransformer = Reference< XURLTransformer >( m_xServiceManager->createInstance(
                                                                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))),
                                                            UNO_QUERY );

            aCommandURL = m_aCommandURL;
            URLToDispatchMap::iterator pIter = m_aListenerMap.find( m_aCommandURL );
            if ( pIter != m_aListenerMap.end() )
                xDispatch = pIter->second;
        }
    }

    if ( xDispatch.is() && xURLTransformer.is() )
    {
        com::sun::star::util::URL aTargetURL;
        Sequence<PropertyValue>   aArgs;

        aTargetURL.Complete = aCommandURL;
        xURLTransformer->parseStrict( aTargetURL );

        // Execute dispatch asynchronously
        ExecuteInfo* pExecuteInfo = new ExecuteInfo;
        pExecuteInfo->xDispatch     = xDispatch;
        pExecuteInfo->aTargetURL    = aTargetURL;
        pExecuteInfo->aArgs         = aArgs;
        Application::PostUserEvent( STATIC_LINK(0, GenericToolboxController , ExecuteHdl_Impl), pExecuteInfo );
    }
}

void GenericToolboxController::statusChanged( const FeatureStateEvent& Event )
throw ( RuntimeException )
{
    vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

    if ( m_bDisposed )
        return;

    if ( m_pToolbox )
    {
        m_pToolbox->EnableItem( m_nID, Event.IsEnabled );

        USHORT nItemBits = m_pToolbox->GetItemBits( m_nID );
        nItemBits &= ~TIB_CHECKABLE;
        TriState eTri = STATE_NOCHECK;

        sal_Bool        bValue;
        rtl::OUString   aStrValue;
        ItemStatus      aItemState;

        if ( Event.State >>= bValue )
        {
            // Boolean, treat it as checked/unchecked
            m_pToolbox->SetItemBits( m_nID, nItemBits );
            m_pToolbox->CheckItem( m_nID, bValue );
            if ( bValue )
                eTri = STATE_CHECK;
            nItemBits |= TIB_CHECKABLE;
        }
        else if ( Event.State >>= aStrValue )
        {
            m_pToolbox->SetItemText( m_nID, aStrValue );
        }
        else if ( Event.State >>= aItemState )
        {
            eTri = STATE_DONTKNOW;
            nItemBits |= TIB_CHECKABLE;
        }

        m_pToolbox->SetItemState( m_nID, eTri );
        m_pToolbox->SetItemBits( m_nID, nItemBits );
    }
}

IMPL_STATIC_LINK( GenericToolboxController, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo )
{
   try
   {
       // Asynchronous execution as this can lead to our own destruction!
       // Framework can recycle our current frame and the layout manager disposes all user interface
       // elements if a component gets detached from its frame!
       pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs );
   }
   catch ( Exception& )
   {
   }
   delete pExecuteInfo;
   return 0;
}

} // namespace
<commit_msg>INTEGRATION: CWS warnings01 (1.3.62); FILE MERGED 2005/11/15 19:56:06 pl 1.3.62.1: #i55991# removed warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: generictoolboxcontroller.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 21:28:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __SVTOOLS_GENERICTOOLBOXCONTROLLER_HXX_
#include "generictoolboxcontroller.hxx"
#endif

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

using namespace ::rtl;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;

namespace svt
{

struct ExecuteInfo
{
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >     xDispatch;
    ::com::sun::star::util::URL                                                aTargetURL;
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >  aArgs;
};

GenericToolboxController::GenericToolboxController( const Reference< XMultiServiceFactory >& rServiceManager,
                                                    const Reference< XFrame >&               rFrame,
                                                    ToolBox*                                 pToolbox,
                                                    USHORT                                   nID,
                                                    const OUString&                          aCommand ) :
    svt::ToolboxController( rServiceManager, rFrame, aCommand )
    ,   m_pToolbox( pToolbox )
    ,   m_nID( nID )
{
    // Initialization is done through ctor
    m_bInitialized = sal_True;

    // insert main command to our listener map
    if ( m_aCommandURL.getLength() )
        m_aListenerMap.insert( URLToDispatchMap::value_type( aCommand, Reference< XDispatch >() ));
}

GenericToolboxController::~GenericToolboxController()
{
}

void SAL_CALL GenericToolboxController::dispose()
throw ( RuntimeException )
{
    vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

    svt::ToolboxController::dispose();

    m_pToolbox = 0;
    m_nID = 0;
}

void SAL_CALL GenericToolboxController::execute( sal_Int16 /*KeyModifier*/ )
throw ( RuntimeException )
{
    Reference< XDispatch >       xDispatch;
    Reference< XURLTransformer > xURLTransformer;
    OUString                     aCommandURL;

    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

        if ( m_bDisposed )
            throw DisposedException();

        if ( m_bInitialized &&
             m_xFrame.is() &&
             m_xServiceManager.is() &&
             m_aCommandURL.getLength() )
        {
            xURLTransformer = Reference< XURLTransformer >( m_xServiceManager->createInstance(
                                                                rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))),
                                                            UNO_QUERY );

            aCommandURL = m_aCommandURL;
            URLToDispatchMap::iterator pIter = m_aListenerMap.find( m_aCommandURL );
            if ( pIter != m_aListenerMap.end() )
                xDispatch = pIter->second;
        }
    }

    if ( xDispatch.is() && xURLTransformer.is() )
    {
        com::sun::star::util::URL aTargetURL;
        Sequence<PropertyValue>   aArgs;

        aTargetURL.Complete = aCommandURL;
        xURLTransformer->parseStrict( aTargetURL );

        // Execute dispatch asynchronously
        ExecuteInfo* pExecuteInfo = new ExecuteInfo;
        pExecuteInfo->xDispatch     = xDispatch;
        pExecuteInfo->aTargetURL    = aTargetURL;
        pExecuteInfo->aArgs         = aArgs;
        Application::PostUserEvent( STATIC_LINK(0, GenericToolboxController , ExecuteHdl_Impl), pExecuteInfo );
    }
}

void GenericToolboxController::statusChanged( const FeatureStateEvent& Event )
throw ( RuntimeException )
{
    vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

    if ( m_bDisposed )
        return;

    if ( m_pToolbox )
    {
        m_pToolbox->EnableItem( m_nID, Event.IsEnabled );

        USHORT nItemBits = m_pToolbox->GetItemBits( m_nID );
        nItemBits &= ~TIB_CHECKABLE;
        TriState eTri = STATE_NOCHECK;

        sal_Bool        bValue;
        rtl::OUString   aStrValue;
        ItemStatus      aItemState;

        if ( Event.State >>= bValue )
        {
            // Boolean, treat it as checked/unchecked
            m_pToolbox->SetItemBits( m_nID, nItemBits );
            m_pToolbox->CheckItem( m_nID, bValue );
            if ( bValue )
                eTri = STATE_CHECK;
            nItemBits |= TIB_CHECKABLE;
        }
        else if ( Event.State >>= aStrValue )
        {
            m_pToolbox->SetItemText( m_nID, aStrValue );
        }
        else if ( Event.State >>= aItemState )
        {
            eTri = STATE_DONTKNOW;
            nItemBits |= TIB_CHECKABLE;
        }

        m_pToolbox->SetItemState( m_nID, eTri );
        m_pToolbox->SetItemBits( m_nID, nItemBits );
    }
}

IMPL_STATIC_LINK_NOINSTANCE( GenericToolboxController, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo )
{
   try
   {
       // Asynchronous execution as this can lead to our own destruction!
       // Framework can recycle our current frame and the layout manager disposes all user interface
       // elements if a component gets detached from its frame!
       pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs );
   }
   catch ( Exception& )
   {
   }
   delete pExecuteInfo;
   return 0;
}

} // namespace
<|endoftext|>


<commit_before>/// @file
/// @version 2.5
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause

#include <stdint.h>

#include <gtypes/Rectangle.h>
#include <gtypes/Vector2.h>
#include <hltypes/harray.h>
#include <hltypes/hmap.h>
#include <hltypes/hsbase.h>
#include <hltypes/hstring.h>
#include <hltypes/hversion.h>

#include "liteser.h"
#include "Serializable.h"
#include "SerializeXml.h"
#include "Type.h"
#include "Utility.h"
#include "Variable.h"

#define WRITE_NODE(string) \
	stream->writeLine(_indent + "<" + hstr(string) + "/>");
#define OPEN_NODE(string) \
	stream->writeLine(_indent + "<" + hstr(string) + ">"); \
	_indent += "\t";
#define CLOSE_NODE(string) \
	_indent = _indent(0, _indent.size() - 1); \
	stream->writeLine(_indent + "</" + hstr(string) + ">");
#define START_LINE(string) \
	stream->write(_indent + "<" + hstr(string));
#define FINISH_LINE(string) \
	stream->writeLine(hstr(string) + "/>");

namespace liteser
{
	namespace xml
	{
		inline void __dumpVariableStart(Variable* variable)
		{
			if (variable->type->value == Type::HARRAY || variable->type->value == Type::HMAP)
			{
				harray<hstr> types;
				foreach (Type*, it, variable->type->subTypes)
				{
					types += hsprintf("%02X", (*it)->value);
				}
				if (variable->containerSize > 0)
				{
					OPEN_NODE(hsprintf("Variable name=\"%s\" type=\"%02X\" sub_types=\"%s\"", variable->name.cStr(), variable->type->value, types.joined(',').cStr()));
				}
				else
				{
					WRITE_NODE(hsprintf("Variable name=\"%s\" type=\"%02X\" sub_types=\"%s\"", variable->name.cStr(), variable->type->value, types.joined(',').cStr()));
				}
			}
			else if (variable->type->value == Type::OBJECT || variable->type->value == Type::OBJPTR)
			{
				OPEN_NODE(hsprintf("Variable name=\"%s\" type=\"%02X\"", variable->name.cStr(), variable->type->value));
			}
			else
			{
				START_LINE(hsprintf("Variable name=\"%s\" type=\"%02X\" value=\"", variable->name.cStr(), variable->type->value));
			}
		}

		inline void __dumpVariableFinish(Variable* variable)
		{
			if (variable->type->value == Type::HARRAY || variable->type->value == Type::HMAP)
			{
				if (variable->containerSize > 0)
				{
					CLOSE_NODE("Variable");
				}
			}
			else if (variable->type->value == Type::OBJECT || variable->type->value == Type::OBJPTR)
			{
				CLOSE_NODE("Variable");
			}
			else
			{
				FINISH_LINE("\"");
			}
		}

		inline void __dumpVariable(Variable* variable)
		{
			switch (variable->type->value)
			{
			case Type::INT8:		stream->write((int)*variable->value<char>());				break;
			case Type::UINT8:		stream->write(*variable->value<unsigned char>());			break;
			case Type::INT16:		stream->write(*variable->value<short>());					break;
			case Type::UINT16:		stream->write(*variable->value<unsigned short>());			break;
			case Type::INT32:		stream->write(*variable->value<int>());						break;
			case Type::UINT32:		stream->write(*variable->value<unsigned int>());			break;
			case Type::INT64:		stream->write(*variable->value<int64_t>());					break;
			case Type::UINT64:		stream->write(*variable->value<uint64_t>());				break;
			case Type::FLOAT:		stream->write(hsprintf("%g", *variable->value<float>()));	break;
			case Type::DOUBLE:		stream->write(hsprintf("%g", *variable->value<double>()));	break;
			case Type::BOOL:		stream->write(*variable->value<bool>());					break;
			case Type::HSTR:		_dump(variable->value<hstr>());								break;
			case Type::HVERSION:	_dump(variable->value<hversion>());							break;
			case Type::HENUM:		_dump(variable->value<henum>());							break;
			case Type::GRECT:		_dump(variable->value<grect>());							break;
			case Type::GVEC2:		_dump(variable->value<gvec2>());							break;
			case Type::GVEC3:		_dump(variable->value<gvec3>());							break;
			case Type::OBJECT:		_dump(variable->value<Serializable>());						break;
			case Type::OBJPTR:		_dump(variable->value<Serializable*>());					break;
			case Type::HARRAY:		__dumpContainer(variable);									break;
			case Type::HMAP:		__dumpContainer(variable);									break;
			default:																			break;
			}
		}

		inline void __dumpContainerVariableStart(Variable* variable)
		{
			if (variable->type->value == Type::HARRAY || variable->type->value == Type::HMAP)
			{
				harray<hstr> types;
				foreach(Type*, it, variable->type->subTypes)
				{
					types += hsprintf("%02X", (*it)->value);
				}
				if (variable->containerSize > 0)
				{
					OPEN_NODE(hsprintf("Container sub_types=\"%s\"", types.joined(',').cStr()));
				}
				else
				{
					WRITE_NODE(hsprintf("Container sub_types=\"%s\"", types.joined(',').cStr()));
				}
			}
			else if (variable->type->value != Type::OBJECT && variable->type->value != Type::OBJPTR)
			{
				START_LINE("Element value=\"");
			}
		}

		inline void __dumpContainerVariableFinish(Variable* variable)
		{
			if (variable->type->value == Type::HARRAY || variable->type->value == Type::HMAP)
			{
				if (variable->containerSize > 0)
				{
					CLOSE_NODE("Container");
				}
			}
			else if (variable->type->value != Type::OBJECT && variable->type->value != Type::OBJPTR)
			{
				FINISH_LINE("\"");
			}
		}

		inline void __dumpContainer(Variable* variable)
		{
			if (variable->containerSize > 0)
			{
				foreach (Variable*, it, variable->subVariables)
				{
					__dumpContainerVariableStart(*it);
					__dumpVariable(*it);
					__dumpContainerVariableFinish(*it);
				}
			}
		}

		void _dump(hstr* value)
		{
			stream->write(*value);
		}

		void _dump(hversion* value)
		{
			stream->write(value->toString(4));
		}

		void _dump(henum* value)
		{
			stream->write(value->value);
		}

		void _dump(grect* value)
		{
			stream->write(hsprintf("%g,%g,%g,%g", value->x, value->y, value->w, value->h));
		}

		void _dump(gvec2* value)
		{
			stream->write(hsprintf("%g,%g", value->x, value->y));
		}

		void _dump(gvec3* value)
		{
			stream->write(hsprintf("%g,%g,%g", value->x, value->y, value->z));
		}

		void _dump(Serializable* value)
		{
			unsigned int id;
			if (__tryMapObject(&id, value))
			{
				hstr name = value->_lsName();
				harray<Variable*> variables = value->_lsVars();
				int variablesSize = variables.size();
				if (variablesSize > 0)
				{
					OPEN_NODE(hsprintf("Object name=\"%s\" id=\"%d\"", name.cStr(), id));
					foreach (Variable*, it, variables)
					{
						__dumpVariableStart(*it);
						__dumpVariable(*it);
						__dumpVariableFinish(*it);
						delete (*it);
					}
					CLOSE_NODE("Object");
				}
				else
				{
					WRITE_NODE(hsprintf("Object name=\"%s\" id=\"%d\"", name.cStr(), id));
				}
			}
			else
			{
				WRITE_NODE(hsprintf("Object id=\"%d\"", id));
			}
		}

		void _dump(Serializable** value)
		{
			_dump(*value);
		}

		void _dumpHarray(harray<Serializable*>* value)
		{
			foreach (Serializable*, it, *value)
			{
				_dump(*it);
			}
		}

		void _dumpHarray(harray<char>* value)
		{
			foreach (char, it, *value)
			{
				START_LINE("Element value=\"");
				stream->write((int)(*it));
				FINISH_LINE("\"");
			}
		}

#define DEFINE_DUMP_HARRAY(type) \
		void _dumpHarray(harray<type>* value) \
		{ \
			foreach (type, it, *value) \
			{ \
				START_LINE("Element value=\""); \
				stream->write(*it); \
				FINISH_LINE("\""); \
			} \
		}

#define DEFINE_DUMP_HARRAY_C(type) \
		void _dumpHarray(harray<type>* value) \
		{ \
			foreach (type, it, *value) \
			{ \
				START_LINE("Element value=\""); \
				_dump(&(*it)); \
				FINISH_LINE("\""); \
			} \
		}

		DEFINE_DUMP_HARRAY(unsigned char);
		DEFINE_DUMP_HARRAY(short);
		DEFINE_DUMP_HARRAY(unsigned short);
		DEFINE_DUMP_HARRAY(int);
		DEFINE_DUMP_HARRAY(unsigned int);
		DEFINE_DUMP_HARRAY(int64_t);
		DEFINE_DUMP_HARRAY(uint64_t);
		DEFINE_DUMP_HARRAY(float);
		DEFINE_DUMP_HARRAY(double);
		DEFINE_DUMP_HARRAY_C(hstr);
		DEFINE_DUMP_HARRAY_C(hversion);
		DEFINE_DUMP_HARRAY_C(henum);
		DEFINE_DUMP_HARRAY_C(grect);
		DEFINE_DUMP_HARRAY_C(gvec2);
		DEFINE_DUMP_HARRAY_C(gvec3);
	}

}
<commit_msg>- small update<commit_after>/// @file
/// @version 2.5
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause

#include <stdint.h>

#include <gtypes/Rectangle.h>
#include <gtypes/Vector2.h>
#include <hltypes/harray.h>
#include <hltypes/hmap.h>
#include <hltypes/hsbase.h>
#include <hltypes/hstring.h>
#include <hltypes/hversion.h>

#include "liteser.h"
#include "Serializable.h"
#include "SerializeXml.h"
#include "Type.h"
#include "Utility.h"
#include "Variable.h"

#define WRITE_NODE(string) \
	stream->writeLine(_indent + "<" + hstr(string) + "/>");
#define OPEN_NODE(string) \
	stream->writeLine(_indent + "<" + hstr(string) + ">"); \
	_indent += "\t";
#define CLOSE_NODE(string) \
	_indent = _indent(0, _indent.size() - 1); \
	stream->writeLine(_indent + "</" + hstr(string) + ">");
#define START_LINE(string) \
	stream->write(_indent + "<" + hstr(string));
#define FINISH_LINE(string) \
	stream->writeLine(hstr(string) + "/>");

namespace liteser
{
	namespace xml
	{
		inline void __dumpVariableStart(Variable* variable)
		{
			if (variable->type->value == Type::HARRAY || variable->type->value == Type::HMAP)
			{
				harray<hstr> types;
				foreach (Type*, it, variable->type->subTypes)
				{
					types += hsprintf("%02X", (*it)->value);
				}
				if (variable->containerSize > 0)
				{
					OPEN_NODE(hsprintf("Variable name=\"%s\" type=\"%02X\" sub_types=\"%s\"", variable->name.cStr(), variable->type->value, types.joined(',').cStr()));
				}
				else
				{
					WRITE_NODE(hsprintf("Variable name=\"%s\" type=\"%02X\" sub_types=\"%s\"", variable->name.cStr(), variable->type->value, types.joined(',').cStr()));
				}
			}
			else if (variable->type->value == Type::OBJECT || variable->type->value == Type::OBJPTR)
			{
				OPEN_NODE(hsprintf("Variable name=\"%s\" type=\"%02X\"", variable->name.cStr(), variable->type->value));
			}
			else
			{
				START_LINE(hsprintf("Variable name=\"%s\" type=\"%02X\" value=\"", variable->name.cStr(), variable->type->value));
			}
		}

		inline void __dumpVariableFinish(Variable* variable)
		{
			if (variable->type->value == Type::HARRAY || variable->type->value == Type::HMAP)
			{
				if (variable->containerSize > 0)
				{
					CLOSE_NODE("Variable");
				}
			}
			else if (variable->type->value == Type::OBJECT || variable->type->value == Type::OBJPTR)
			{
				CLOSE_NODE("Variable");
			}
			else
			{
				FINISH_LINE("\"");
			}
		}

		inline void __dumpVariable(Variable* variable)
		{
			switch (variable->type->value)
			{
			case Type::INT8:		stream->write((int)*variable->value<char>());				break;
			case Type::UINT8:		stream->write(*variable->value<unsigned char>());			break;
			case Type::INT16:		stream->write(*variable->value<short>());					break;
			case Type::UINT16:		stream->write(*variable->value<unsigned short>());			break;
			case Type::INT32:		stream->write(*variable->value<int>());						break;
			case Type::UINT32:		stream->write(*variable->value<unsigned int>());			break;
			case Type::INT64:		stream->write(*variable->value<int64_t>());					break;
			case Type::UINT64:		stream->write(*variable->value<uint64_t>());				break;
			case Type::FLOAT:		stream->write(hsprintf("%g", *variable->value<float>()));	break;
			case Type::DOUBLE:		stream->write(hsprintf("%g", *variable->value<double>()));	break;
			case Type::BOOL:		stream->write(*variable->value<bool>());					break;
			case Type::HSTR:		_dump(variable->value<hstr>());								break;
			case Type::HVERSION:	_dump(variable->value<hversion>());							break;
			case Type::HENUM:		_dump(variable->value<henum>());							break;
			case Type::GRECT:		_dump(variable->value<grect>());							break;
			case Type::GVEC2:		_dump(variable->value<gvec2>());							break;
			case Type::GVEC3:		_dump(variable->value<gvec3>());							break;
			case Type::OBJECT:		_dump(variable->value<Serializable>());						break;
			case Type::OBJPTR:		_dump(variable->value<Serializable*>());					break;
			case Type::HARRAY:		__dumpContainer(variable);									break;
			case Type::HMAP:		__dumpContainer(variable);									break;
			default:																			break;
			}
		}

		inline void __dumpContainerVariableStart(Variable* variable)
		{
			if (variable->type->value == Type::HARRAY || variable->type->value == Type::HMAP)
			{
				harray<hstr> types;
				foreach (Type*, it, variable->type->subTypes)
				{
					types += hsprintf("%02X", (*it)->value);
				}
				if (variable->containerSize > 0)
				{
					OPEN_NODE(hsprintf("Container sub_types=\"%s\"", types.joined(',').cStr()));
				}
				else
				{
					WRITE_NODE(hsprintf("Container sub_types=\"%s\"", types.joined(',').cStr()));
				}
			}
			else if (variable->type->value != Type::OBJECT && variable->type->value != Type::OBJPTR)
			{
				START_LINE("Element value=\"");
			}
		}

		inline void __dumpContainerVariableFinish(Variable* variable)
		{
			if (variable->type->value == Type::HARRAY || variable->type->value == Type::HMAP)
			{
				if (variable->containerSize > 0)
				{
					CLOSE_NODE("Container");
				}
			}
			else if (variable->type->value != Type::OBJECT && variable->type->value != Type::OBJPTR)
			{
				FINISH_LINE("\"");
			}
		}

		inline void __dumpContainer(Variable* variable)
		{
			if (variable->containerSize > 0)
			{
				foreach (Variable*, it, variable->subVariables)
				{
					__dumpContainerVariableStart(*it);
					__dumpVariable(*it);
					__dumpContainerVariableFinish(*it);
				}
			}
		}

		void _dump(hstr* value)
		{
			stream->write(*value);
		}

		void _dump(hversion* value)
		{
			stream->write(value->toString(4));
		}

		void _dump(henum* value)
		{
			stream->write(value->value);
		}

		void _dump(grect* value)
		{
			stream->write(hsprintf("%g,%g,%g,%g", value->x, value->y, value->w, value->h));
		}

		void _dump(gvec2* value)
		{
			stream->write(hsprintf("%g,%g", value->x, value->y));
		}

		void _dump(gvec3* value)
		{
			stream->write(hsprintf("%g,%g,%g", value->x, value->y, value->z));
		}

		void _dump(Serializable* value)
		{
			unsigned int id;
			if (__tryMapObject(&id, value))
			{
				hstr name = value->_lsName();
				harray<Variable*> variables = value->_lsVars();
				int variablesSize = variables.size();
				if (variablesSize > 0)
				{
					OPEN_NODE(hsprintf("Object name=\"%s\" id=\"%d\"", name.cStr(), id));
					foreach (Variable*, it, variables)
					{
						__dumpVariableStart(*it);
						__dumpVariable(*it);
						__dumpVariableFinish(*it);
						delete (*it);
					}
					CLOSE_NODE("Object");
				}
				else
				{
					WRITE_NODE(hsprintf("Object name=\"%s\" id=\"%d\"", name.cStr(), id));
				}
			}
			else
			{
				WRITE_NODE(hsprintf("Object id=\"%d\"", id));
			}
		}

		void _dump(Serializable** value)
		{
			_dump(*value);
		}

		void _dumpHarray(harray<Serializable*>* value)
		{
			foreach (Serializable*, it, *value)
			{
				_dump(*it);
			}
		}

		void _dumpHarray(harray<char>* value)
		{
			foreach (char, it, *value)
			{
				START_LINE("Element value=\"");
				stream->write((int)(*it));
				FINISH_LINE("\"");
			}
		}

#define DEFINE_DUMP_HARRAY(type) \
		void _dumpHarray(harray<type>* value) \
		{ \
			foreach (type, it, *value) \
			{ \
				START_LINE("Element value=\""); \
				stream->write(*it); \
				FINISH_LINE("\""); \
			} \
		}

#define DEFINE_DUMP_HARRAY_C(type) \
		void _dumpHarray(harray<type>* value) \
		{ \
			foreach (type, it, *value) \
			{ \
				START_LINE("Element value=\""); \
				_dump(&(*it)); \
				FINISH_LINE("\""); \
			} \
		}

		DEFINE_DUMP_HARRAY(unsigned char);
		DEFINE_DUMP_HARRAY(short);
		DEFINE_DUMP_HARRAY(unsigned short);
		DEFINE_DUMP_HARRAY(int);
		DEFINE_DUMP_HARRAY(unsigned int);
		DEFINE_DUMP_HARRAY(int64_t);
		DEFINE_DUMP_HARRAY(uint64_t);
		DEFINE_DUMP_HARRAY(float);
		DEFINE_DUMP_HARRAY(double);
		DEFINE_DUMP_HARRAY_C(hstr);
		DEFINE_DUMP_HARRAY_C(hversion);
		DEFINE_DUMP_HARRAY_C(henum);
		DEFINE_DUMP_HARRAY_C(grect);
		DEFINE_DUMP_HARRAY_C(gvec2);
		DEFINE_DUMP_HARRAY_C(gvec3);
	}

}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageFileWriterPastingTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

#include <fstream>
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

int itkImageFileWriterPastingTest1(int argc, char* argv[])
{
  if( argc < 3 )
    {
    std::cerr << "Usage: " << argv[0] << " input output" << std::endl;
    return EXIT_FAILURE;
    }

  // We remove the output file
  itksys::SystemTools::RemoveFile(argv[2]);

  typedef unsigned char            PixelType;
  typedef itk::Image<PixelType,3>   ImageType;

  typedef itk::ImageFileReader<ImageType>         ReaderType;
  typedef itk::ImageFileWriter< ImageType >  WriterType;

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );
  reader->SetUseStreaming( true );

  ImageType::RegionType region;
  ImageType::SizeType size;
  ImageType::SizeType fullsize;
  ImageType::IndexType index;

  unsigned int m_NumberOfPieces = 10;

  // We decide how we want to read the image and we split accordingly
  // The image is read slice by slice
  reader->GenerateOutputInformation();
  fullsize = reader->GetOutput()->GetLargestPossibleRegion().GetSize();

  index.Fill(0);
  size[0] = fullsize[0];
  size[1] = fullsize[1];
  size[2] = 0;

  unsigned int zsize = fullsize[2]/m_NumberOfPieces;

  // Setup the writer
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(argv[2]);

  for(unsigned int i=0;i<m_NumberOfPieces;i++)
    {
    std::cout << "Reading piece " << i+1 << " of " << m_NumberOfPieces << std::endl;

    index[2] += size[2];

    // At the end we need to adjust the size to make sure
    // we are reading everything
    if(i == m_NumberOfPieces-1)
      {
      size[2] = fullsize[2]-index[2];
      }
    else
      {
      size[2] = zsize;
      }

    region.SetIndex(index);
    region.SetSize(size);
    reader->GetOutput()->SetRequestedRegion(region);
    try
      {
      reader->Update();
      }
    catch (itk::ExceptionObject &ex)
      {
      std::cout << "ERROR : " << ex << std::endl;
      return EXIT_FAILURE;
      }

    // Write the image
    itk::ImageIORegion  ioregion(3);
    itk::ImageIORegion::IndexType index2;
    index2.push_back(region.GetIndex()[0]);
    index2.push_back(region.GetIndex()[1]);
    index2.push_back(region.GetIndex()[2]);
    ioregion.SetIndex(index2);
    itk::ImageIORegion::SizeType size2;
    size2.push_back(region.GetSize()[0]);
    size2.push_back(region.GetSize()[1]);
    size2.push_back(region.GetSize()[2]);
    ioregion.SetSize(size2);
    writer->SetIORegion(ioregion);
    writer->SetInput(reader->GetOutput());

    try
      {
      writer->Update();
      }
    catch( itk::ExceptionObject & err )
      {
      std::cerr << "ExceptionObject caught !" << std::endl;
      std::cerr << err << std::endl;
      return EXIT_FAILURE;
      }
    } // end for pieces

  return EXIT_SUCCESS;
}
<commit_msg>ENH: Updated to the so ImageFileWrite dives the pipeline and not manual<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageFileWriterPastingTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

#include <fstream>
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

int itkImageFileWriterPastingTest1(int argc, char* argv[])
{
  if( argc < 3 )
    {
    std::cerr << "Usage: " << argv[0] << " input output" << std::endl;
    return EXIT_FAILURE;
    }

  // We remove the output file
  itksys::SystemTools::RemoveFile(argv[2]);

  typedef unsigned char            PixelType;
  typedef itk::Image<PixelType,3>   ImageType;

  typedef itk::ImageFileReader<ImageType>         ReaderType;
  typedef itk::ImageFileWriter< ImageType >  WriterType;

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[1] );
  reader->SetUseStreaming( true );

  ImageType::RegionType region;
  ImageType::SizeType size;
  ImageType::SizeType fullsize;
  ImageType::IndexType index;

  unsigned int m_NumberOfPieces = 10;

  // We decide how we want to read the image and we split accordingly
  // The image is read slice by slice
  reader->GenerateOutputInformation();
  fullsize = reader->GetOutput()->GetLargestPossibleRegion().GetSize();

  index.Fill(0);
  size[0] = fullsize[0];
  size[1] = fullsize[1];
  size[2] = 0;

  unsigned int zsize = fullsize[2]/m_NumberOfPieces;

  // Setup the writer
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(argv[2]);

  for(unsigned int i=0;i<m_NumberOfPieces;i++)
    {
    std::cout << "Reading piece " << i+1 << " of " << m_NumberOfPieces << std::endl;

    index[2] += size[2];

    // At the end we need to adjust the size to make sure
    // we are reading everything
    if(i == m_NumberOfPieces-1)
      {
      size[2] = fullsize[2]-index[2];
      }
    else
      {
      size[2] = zsize;
      }

    region.SetIndex(index);
    region.SetSize(size);

    // Write the image
    itk::ImageIORegion  ioregion(3);
    itk::ImageIORegionAdaptor<ImageType::ImageDimension>::
        Convert( region, ioregion);

    writer->SetIORegion(ioregion);
    writer->SetInput(reader->GetOutput());

    try
      {
      writer->Update();
      }
    catch( itk::ExceptionObject & err )
      {
      std::cerr << "ExceptionObject caught !" << std::endl;
      std::cerr << err << std::endl;
      return EXIT_FAILURE;
      }
    } // end for pieces

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////
//
//            Copyright (c) 2016 Ronnie Brohn (EpicBrownie)
//
//                Distributed under The MIT License (MIT).
//             (See accompanying file License.txt or copy at
//                 https://opensource.org/licenses/MIT)
//
//           Please report any bugs, typos, or suggestions to
//              https://github.com/epicbrownie/Epic/issues
//
//////////////////////////////////////////////////////////////////////////////

#pragma once

#include <type_traits>

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

// Sequence<T>
namespace Epic::TMP
{
	template<typename T, T... Items>
	using Sequence = std::integer_sequence<T, Items...>;

	template<typename T, T N>
	using MakeSequence = std::make_integer_sequence<T, N>;
}

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

// ForEach - Iterate over a Sequence<T>
namespace Epic::TMP
{
	template<class Seq>
	struct ForEach;

	template<typename T, T Item, T... Items>
	struct ForEach<Sequence<T, Item, Items...>>
	{
		template<class Function, class... Args>
		static void Apply(Function fn, Args&&... args)
		{
			fn(Item, std::forward<Args>(args)...);

			ForEach<Sequence<T, Items...>>
				::Apply(fn, std::forward<Args>(args)...);
		}
	};

	template<typename T, T Item>
	struct ForEach<Sequence<T, Item>>
	{
		template<class Function, class... Args>
		static void Apply(Function fn, Args&&... args)
		{
			fn(Item, std::forward<Args>(args)...);
		}
	};
}

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

// ForEach2 - Iterate over 2 Sequence<T> simultaneously
namespace Epic::TMP
{
	template<class Seq1, class Seq2>
	struct ForEach2;

	template<typename T, T Item1, T Item2, T... Items1, T... Items2>
	struct ForEach2<Sequence<T, Item1, Items1...>, Sequence<T, Item2, Items2...>>
	{
		template<class Function, class... Args>
		static void Apply(Function fn, Args&&... args)
		{
			fn(Item1, Item2, std::forward<Args>(args)...);

			ForEach2<Sequence<T, Items1...>, Sequence<T, Items2...>>
				::Apply(fn, std::forward<Args>(args)...);
		}
	};

	template<typename T, T Item1, T Item2>
	struct ForEach2<Sequence<T, Item1>, Sequence<T, Item2>>
	{
		template<class Function, class... Args>
		static void Apply(Function fn, Args&&... args)
		{
			fn(Item1, Item2, std::forward<Args>(args)...);
		}
	};

	template<typename T, T... ExtraItems>
	struct ForEach2<Sequence<T, ExtraItems...>, Sequence<T>>
	{
		template<class Function, class... Args>
		static void Apply(Function, Args&&...)
		{
			/* The first sequence had too many items. */
		}
	};

	template<typename T, T... ExtraItems>
	struct ForEach2<Sequence<T>, Sequence<T, ExtraItems...>>
	{
		template<class Function, class... Args>
		static void Apply(Function, Args&&...)
		{
			/* The second sequence had too many items. */
		}
	};
}

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

// SequenceContains - Determine whether Query is contained within a Sequence<T>
namespace Epic::TMP
{
	template<typename T, T Query, class Seq>
	struct SequenceContains : public std::false_type
	{ };

	template<typename T, T Query, T Item, T... Items>
	struct SequenceContains<T, Query, Sequence<T, Item, Items...>>
		: public std::conditional_t<
			((Query == Item) || SequenceContains<T, Query, Sequence<T, Items...>>::value),
			std::true_type,
			std::false_type>
	{ };
}

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

// IsSequenceUnique - Determine whether every T within a Sequence<T> is unique
namespace Epic::TMP
{
	template<class Seq>
	struct IsSequenceUnique : public std::true_type
	{ };

	template<typename T, T Item, T... Items>
	struct IsSequenceUnique<Sequence<T, Item, Items...>>
		: public std::conditional_t<
			(!SequenceContains<T, Item, Sequence<T, Items...>>::value &&
				IsSequenceUnique<Sequence<T, Items...>>::value),
			std::true_type,
			std::false_type>
	{ };

	template<typename T, T Item, T Last>
	struct IsSequenceUnique<Sequence<T, Item, Last>>
		: public std::conditional_t<Item != Last, std::true_type, std::false_type>
	{ };
}
<commit_msg>Added ForEachN<commit_after>//////////////////////////////////////////////////////////////////////////////
//
//            Copyright (c) 2016 Ronnie Brohn (EpicBrownie)
//
//                Distributed under The MIT License (MIT).
//             (See accompanying file License.txt or copy at
//                 https://opensource.org/licenses/MIT)
//
//           Please report any bugs, typos, or suggestions to
//              https://github.com/epicbrownie/Epic/issues
//
//////////////////////////////////////////////////////////////////////////////

#pragma once

#include <type_traits>

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

// Sequence<T>
namespace Epic::TMP
{
	template<typename T, T... Items>
	using Sequence = std::integer_sequence<T, Items...>;

	template<typename T, T N>
	using MakeSequence = std::make_integer_sequence<T, N>;
}

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

// ForEach - Iterate over a Sequence<T>
namespace Epic::TMP
{
	template<class Seq>
	struct ForEach;

	template<typename T, T Item, T... Items>
	struct ForEach<Sequence<T, Item, Items...>>
	{
		template<class Function, class... Args>
		static void Apply(Function fn, Args&&... args)
		{
			fn(Item, std::forward<Args>(args)...);

			ForEach<Sequence<T, Items...>>
				::Apply(fn, std::forward<Args>(args)...);
		}
	};

	template<typename T, T Item>
	struct ForEach<Sequence<T, Item>>
	{
		template<class Function, class... Args>
		static void Apply(Function fn, Args&&... args)
		{
			fn(Item, std::forward<Args>(args)...);
		}
	};

	template<size_t N>
	struct ForEachN
	{
		template<class Function, class... Args>
		static void Apply(Function fn, Args&&... args)
		{
			ForEach<MakeSequence<size_t, N>>::Apply(fn, std::forward<Args>(args)...);
		}
	};
}

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

// ForEach2 - Iterate over 2 Sequence<T> simultaneously
namespace Epic::TMP
{
	template<class Seq1, class Seq2>
	struct ForEach2;

	template<typename T, T Item1, T Item2, T... Items1, T... Items2>
	struct ForEach2<Sequence<T, Item1, Items1...>, Sequence<T, Item2, Items2...>>
	{
		template<class Function, class... Args>
		static void Apply(Function fn, Args&&... args)
		{
			fn(Item1, Item2, std::forward<Args>(args)...);

			ForEach2<Sequence<T, Items1...>, Sequence<T, Items2...>>
				::Apply(fn, std::forward<Args>(args)...);
		}
	};

	template<typename T, T Item1, T Item2>
	struct ForEach2<Sequence<T, Item1>, Sequence<T, Item2>>
	{
		template<class Function, class... Args>
		static void Apply(Function fn, Args&&... args)
		{
			fn(Item1, Item2, std::forward<Args>(args)...);
		}
	};

	template<typename T, T... ExtraItems>
	struct ForEach2<Sequence<T, ExtraItems...>, Sequence<T>>
	{
		template<class Function, class... Args>
		static void Apply(Function, Args&&...)
		{
			/* The first sequence had too many items. */
		}
	};

	template<typename T, T... ExtraItems>
	struct ForEach2<Sequence<T>, Sequence<T, ExtraItems...>>
	{
		template<class Function, class... Args>
		static void Apply(Function, Args&&...)
		{
			/* The second sequence had too many items. */
		}
	};
}

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

// SequenceContains - Determine whether Query is contained within a Sequence<T>
namespace Epic::TMP
{
	template<typename T, T Query, class Seq>
	struct SequenceContains : public std::false_type
	{ };

	template<typename T, T Query, T Item, T... Items>
	struct SequenceContains<T, Query, Sequence<T, Item, Items...>>
		: public std::conditional_t<
			((Query == Item) || SequenceContains<T, Query, Sequence<T, Items...>>::value),
			std::true_type,
			std::false_type>
	{ };
}

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

// IsSequenceUnique - Determine whether every T within a Sequence<T> is unique
namespace Epic::TMP
{
	template<class Seq>
	struct IsSequenceUnique : public std::true_type
	{ };

	template<typename T, T Item, T... Items>
	struct IsSequenceUnique<Sequence<T, Item, Items...>>
		: public std::conditional_t<
			(!SequenceContains<T, Item, Sequence<T, Items...>>::value &&
				IsSequenceUnique<Sequence<T, Items...>>::value),
			std::true_type,
			std::false_type>
	{ };

	template<typename T, T Item, T Last>
	struct IsSequenceUnique<Sequence<T, Item, Last>>
		: public std::conditional_t<Item != Last, std::true_type, std::false_type>
	{ };
}
<|endoftext|>


<commit_before>/*
 *   Copyright (C) 2014 Pelagicore AB
 *   All rights reserved.
 */
#include "CommandLineParser.h"
#include "debug.h"
#include "paminterface.h"
#include "pelagicontain.h"
#include "pelagicontaintodbusadapter.h"
#include "dbusmainloop.h"
#include "generators.h" /* used for gen_ct_name */
#include "pulsegateway.h"
#include "networkgateway.h"
#include "dbusgateway.h"
#include <sys/stat.h>
#include "systemcallinterface.h"
#include "devicenodegateway.h"

LOG_DEFINE_APP_IDS("PCON", "Pelagicontain");
LOG_DECLARE_CONTEXT(Pelagicontain_DefaultLogContext, "PCON", "Main context");

#ifndef CONFIG
    #error Must define CONFIG; path to configuration file (/etc/pelagicontain?)
#endif

int main(int argc, char **argv)
{

    const char *summary = "Pelagicore container utility. "
                          "Requires an absolute path to the container root, "
                          "the command to run inside the container and "
                          "an alphanumerical cookie string as first, second and"
                          "third argument respectively";
    const char *paramsDescription = "[container root directory (abs path)] "
                                    "[command] [cookie]";

    pelagicore::CommandLineParser commandLineParser(summary,
                                                    paramsDescription,
                                                    PACKAGE_VERSION,
                                                    "");

    std::string containerRoot;
    std::string containedCommand;
    std::string cookie;
    const char* configFilePath = CONFIG;
    commandLineParser.addOption(configFilePath,
                                "with-config-file",
                                'c',
                                "Config file");

    if (commandLineParser.parse(argc, argv)) {
        return -1;
    }

    if (argc < 4) {
        log_error("Invalid arguments");
        commandLineParser.printHelp();
        return -1;
    } else {
        containerRoot = std::string(argv[1]);
        containedCommand = std::string(argv[2]);
        cookie = std::string(argv[3]);
    }

    if (containerRoot.c_str()[0] != '/') {
        log_error("Path to container root must be absolute");
        commandLineParser.printHelp();
        return -1;
    }

    std::string containerName = gen_ct_name();
    std::string containerConfig(configFilePath);

    // Create gateway directory for container in containerRoot/gateways.
    // This dir will contain various sockets etc acting as gateways
    // in/out of the container.
    std::string containerDir = containerRoot + "/" + containerName;
    std::string gatewayDir = containerDir + "/gateways";
    if (mkdir(containerDir.c_str(), S_IRWXU) == -1) {
        log_error("Could not create container directory %s, %s.",
                  containerDir.c_str(),
                  strerror(errno));
        exit(-1);
    }
    if (mkdir(gatewayDir.c_str(), S_IRWXU) == -1) {
        log_error("Could not create gateway directory %s, %s.",
                  gatewayDir.c_str(),
                  strerror(errno));
        exit(-1);
    }

    { // Create a new scope so that we can do a clean up after dtors
        DBus::BusDispatcher dispatcher;
        DBus::default_dispatcher = &dispatcher;
        DBus::Connection bus = DBus::Connection::SessionBus();

        /* Pelagicontain needs an interface to the mainloop so it can
         * exit it when we are to clean up and shut down
         */
        DBusMainloop dbusmainloop(&dispatcher);

        /* The request_name call does not return anything but raises an
         * exception if the name cannot be requested.
         */
        bus.request_name("com.pelagicore.Pelagicontain");

        PAMInterface pamInterface(bus);
        ControllerInterface controllerInterface(gatewayDir);
        SystemcallInterface systemCallInterface;
        Pelagicontain pelagicontain(&pamInterface,
                                    &dbusmainloop,
                                    &controllerInterface,
                                    cookie);

        std::string baseObjPath("/com/pelagicore/Pelagicontain/");
        std::string fullObjPath = baseObjPath + cookie;

        PelagicontainToDBusAdapter pcAdapter(bus, fullObjPath, pelagicontain);

        pelagicontain.addGateway(new NetworkGateway(&controllerInterface,
                                                    &systemCallInterface));

        pelagicontain.addGateway(new PulseGateway(gatewayDir, containerName));

        pelagicontain.addGateway(new DeviceNodeGateway(&controllerInterface));

        pelagicontain.addGateway(new DBusGateway(&controllerInterface,
                                                 &systemCallInterface,
                                                 DBusGateway::SessionProxy,
                                                 gatewayDir,
                                                 containerName));

        pelagicontain.addGateway(new DBusGateway(&controllerInterface,
                                                 &systemCallInterface,
                                                 DBusGateway::SystemProxy,
                                                 gatewayDir,
                                                 containerName));

        pid_t pcPid = pelagicontain.preload(containerName,
                                            containerConfig,
                                            containerRoot,
                                            containedCommand);

        log_debug("Started Pelagicontain with PID: %d", pcPid);

        dbusmainloop.enter();
        log_debug("Exited dbusmainloop.");
    }

    // remove instance specific dirs again
    if (rmdir(gatewayDir.c_str()) == -1) {
        log_error("Cannot delete dir %s, %s",
                  gatewayDir.c_str(),
                  strerror(errno));
    }

    if (rmdir(containerDir.c_str()) == -1) {
        log_error("Cannot delete dir %s, %s",
                  gatewayDir.c_str(),
                  strerror(errno));
    }
}
<commit_msg>main: changed variable name<commit_after>/*
 *   Copyright (C) 2014 Pelagicore AB
 *   All rights reserved.
 */
#include "CommandLineParser.h"
#include "debug.h"
#include "paminterface.h"
#include "pelagicontain.h"
#include "pelagicontaintodbusadapter.h"
#include "dbusmainloop.h"
#include "generators.h" /* used for gen_ct_name */
#include "pulsegateway.h"
#include "networkgateway.h"
#include "dbusgateway.h"
#include <sys/stat.h>
#include "systemcallinterface.h"
#include "devicenodegateway.h"

LOG_DEFINE_APP_IDS("PCON", "Pelagicontain");
LOG_DECLARE_CONTEXT(Pelagicontain_DefaultLogContext, "PCON", "Main context");

#ifndef CONFIG
    #error Must define CONFIG; path to configuration file (/etc/pelagicontain?)
#endif

int main(int argc, char **argv)
{

    const char *summary = "Pelagicore container utility. "
                          "Requires an absolute path to the container root, "
                          "the command to run inside the container and "
                          "an alphanumerical cookie string as first, second and"
                          "third argument respectively";
    const char *paramsDescription = "[container root directory (abs path)] "
                                    "[command] [cookie]";

    pelagicore::CommandLineParser commandLineParser(summary,
                                                    paramsDescription,
                                                    PACKAGE_VERSION,
                                                    "");

    std::string containerRoot;
    std::string containedCommand;
    std::string cookie;
    const char* configFilePath = CONFIG;
    commandLineParser.addOption(configFilePath,
                                "with-config-file",
                                'c',
                                "Config file");

    if (commandLineParser.parse(argc, argv)) {
        return -1;
    }

    if (argc < 4) {
        log_error("Invalid arguments");
        commandLineParser.printHelp();
        return -1;
    } else {
        containerRoot = std::string(argv[1]);
        containedCommand = std::string(argv[2]);
        cookie = std::string(argv[3]);
    }

    if (containerRoot.c_str()[0] != '/') {
        log_error("Path to container root must be absolute");
        commandLineParser.printHelp();
        return -1;
    }

    std::string containerName = gen_ct_name();
    std::string containerConfig(configFilePath);

    // Create gateway directory for container in containerRoot/gateways.
    // This dir will contain various sockets etc acting as gateways
    // in/out of the container.
    std::string containerDir = containerRoot + "/" + containerName;
    std::string gatewayDir = containerDir + "/gateways";
    if (mkdir(containerDir.c_str(), S_IRWXU) == -1) {
        log_error("Could not create container directory %s, %s.",
                  containerDir.c_str(),
                  strerror(errno));
        exit(-1);
    }
    if (mkdir(gatewayDir.c_str(), S_IRWXU) == -1) {
        log_error("Could not create gateway directory %s, %s.",
                  gatewayDir.c_str(),
                  strerror(errno));
        exit(-1);
    }

    { // Create a new scope so that we can do a clean up after dtors
        DBus::BusDispatcher dispatcher;
        DBus::default_dispatcher = &dispatcher;
        DBus::Connection bus = DBus::Connection::SessionBus();

        /* Pelagicontain needs an interface to the mainloop so it can
         * exit it when we are to clean up and shut down
         */
        DBusMainloop dbusmainloop(&dispatcher);

        /* The request_name call does not return anything but raises an
         * exception if the name cannot be requested.
         */
        bus.request_name("com.pelagicore.Pelagicontain");

        PAMInterface pamInterface(bus);
        ControllerInterface controllerInterface(gatewayDir);
        SystemcallInterface systemcallInterface;
        Pelagicontain pelagicontain(&pamInterface,
                                    &dbusmainloop,
                                    &controllerInterface,
                                    cookie);

        std::string baseObjPath("/com/pelagicore/Pelagicontain/");
        std::string fullObjPath = baseObjPath + cookie;

        PelagicontainToDBusAdapter pcAdapter(bus, fullObjPath, pelagicontain);

        pelagicontain.addGateway(new NetworkGateway(&controllerInterface,
                                                    &systemcallInterface));

        pelagicontain.addGateway(new PulseGateway(gatewayDir, containerName));

        pelagicontain.addGateway(new DeviceNodeGateway(&controllerInterface));

        pelagicontain.addGateway(new DBusGateway(&controllerInterface,
                                                 &systemcallInterface,
                                                 DBusGateway::SessionProxy,
                                                 gatewayDir,
                                                 containerName));

        pelagicontain.addGateway(new DBusGateway(&controllerInterface,
                                                 &systemcallInterface,
                                                 DBusGateway::SystemProxy,
                                                 gatewayDir,
                                                 containerName));

        pid_t pcPid = pelagicontain.preload(containerName,
                                            containerConfig,
                                            containerRoot,
                                            containedCommand);

        log_debug("Started Pelagicontain with PID: %d", pcPid);

        dbusmainloop.enter();
        log_debug("Exited dbusmainloop.");
    }

    // remove instance specific dirs again
    if (rmdir(gatewayDir.c_str()) == -1) {
        log_error("Cannot delete dir %s, %s",
                  gatewayDir.c_str(),
                  strerror(errno));
    }

    if (rmdir(containerDir.c_str()) == -1) {
        log_error("Cannot delete dir %s, %s",
                  gatewayDir.c_str(),
                  strerror(errno));
    }
}
<|endoftext|>


<commit_before>#include "photoeffects.hpp"
#include <vector>

using namespace cv;
using namespace std;

namespace
{
    Point topleftFind(Point firstPoint, Point secondPoint, int &xsize, int &ysize)
    {
        Point topleft(0, 0);
        if(xsize < 0)
        {
            topleft.x = firstPoint.x;
            xsize = -xsize;
        }
        else
        {
            topleft.x = secondPoint.x;
        }
        if(ysize < 0)
        {
            topleft.y = secondPoint.y;
            ysize = -ysize;
        }
        else
        {
            topleft.y = firstPoint.y;
        }
        return topleft;
    }
}

int matte(InputArray src, OutputArray dst, Point firstPoint, Point secondPoint, float sigmaX,
            float sigmaY, Size ksize)
{
    CV_Assert((src.type() == CV_8UC3) || (src.type() == CV_32FC3));
    CV_Assert((sigmaX > 0.0f) || (sigmaY > 0.0f));
    Mat srcImg = src.getMat();
    CV_Assert(!(srcImg.empty()));
    if(srcImg.type() != CV_32FC3)
    {
        srcImg.convertTo(srcImg, CV_32FC3, 1.0f/255.0f);
    }
    int xsize = firstPoint.x - secondPoint.x;
    int ysize = firstPoint.y - secondPoint.y;
    Point topLeft = topleftFind(firstPoint, secondPoint, xsize, ysize);
    Scalar black = Scalar(0.0f,0.0f,0.0f);
    Scalar white = Scalar(1.0f,1.0f,1.0f);
    Mat mask(srcImg.rows, srcImg.cols, CV_32FC1, black);
    ellipse(mask, Point((topLeft.x+xsize/2),(topLeft.y-ysize/2)),
            Size(xsize/2,ysize/2), 0, 0, 360, white, -1);
    GaussianBlur(mask, mask, ksize, sigmaX, sigmaY);
    vector<Mat> ch_img;
    split(srcImg,ch_img);
    ch_img[0]=ch_img[0].mul(mask)+1.0f-mask;
    ch_img[1]=ch_img[1].mul(mask)+1.0f-mask;
    ch_img[2]=ch_img[2].mul(mask)+1.0f-mask;
    merge(ch_img,dst);
    return 0;
}
<commit_msg>Add const indentificator.<commit_after>#include "photoeffects.hpp"
#include <vector>

using namespace cv;
using namespace std;

namespace
{
    Point topleftFind(Point firstPoint, Point secondPoint, int &xsize, int &ysize)
    {
        Point topleft(0, 0);
        if(xsize < 0)
        {
            topleft.x = firstPoint.x;
            xsize = -xsize;
        }
        else
        {
            topleft.x = secondPoint.x;
        }
        if(ysize < 0)
        {
            topleft.y = secondPoint.y;
            ysize = -ysize;
        }
        else
        {
            topleft.y = firstPoint.y;
        }
        return topleft;
    }
}

int matte(InputArray src, OutputArray dst, Point firstPoint, Point secondPoint, float sigmaX,
            float sigmaY, Size ksize)
{
    CV_Assert((src.type() == CV_8UC3) || (src.type() == CV_32FC3));
    CV_Assert((sigmaX > 0.0f) || (sigmaY > 0.0f));
    Mat srcImg = src.getMat();
    CV_Assert(!(srcImg.empty()));
    if(srcImg.type() != CV_32FC3)
    {
        srcImg.convertTo(srcImg, CV_32FC3, 1.0f/255.0f);
    }
    int xsize = firstPoint.x - secondPoint.x;
    int ysize = firstPoint.y - secondPoint.y;
    Point topLeft = topleftFind(firstPoint, secondPoint, xsize, ysize);
    const Scalar black = Scalar(0.0f,0.0f,0.0f);
    const Scalar white = Scalar(1.0f,1.0f,1.0f);
    Mat mask(srcImg.rows, srcImg.cols, CV_32FC1, black);
    ellipse(mask, Point((topLeft.x+xsize/2),(topLeft.y-ysize/2)),
            Size(xsize/2,ysize/2), 0, 0, 360, white, -1);
    GaussianBlur(mask, mask, ksize, sigmaX, sigmaY);
    vector<Mat> ch_img;
    split(srcImg,ch_img);
    ch_img[0]=ch_img[0].mul(mask)+1.0f-mask;
    ch_img[1]=ch_img[1].mul(mask)+1.0f-mask;
    ch_img[2]=ch_img[2].mul(mask)+1.0f-mask;
    merge(ch_img,dst);
    return 0;
}
<|endoftext|>