<commit_before>// File:      NCollection_IncAllocator.cxx
// Created:   12.04.02 21:16:26
// Author:    Alexander GRIGORIEV
// Copyright: Open Cascade 2002

#include <NCollection_IncAllocator.hxx>
#include <NCollection_DataMap.hxx>
#include <NCollection_Map.hxx>
#include <Standard_Mutex.hxx>
#include <Standard_OutOfMemory.hxx>
#include <stdio.h>

IMPLEMENT_STANDARD_HANDLE  (NCollection_IncAllocator,NCollection_BaseAllocator)
IMPLEMENT_STANDARD_RTTIEXT (NCollection_IncAllocator,NCollection_BaseAllocator)

#define IMEM_SIZE(_size) ((((_size) - 1)/sizeof(aligned_t)) + 1)
#define IMEM_FREE(p_bl) ((unsigned int)(p_bl->p_end_block - p_bl->p_free_space))
#define IMEM_ALIGN(_addr) (sizeof(aligned_t)* IMEM_SIZE((unsigned long)(_addr)))

#define MaxLookup 16

static Standard_Boolean IS_DEBUG = Standard_False;

//=======================================================================
/**
 * Static data map (address -> AllocatorID)
 */
//=======================================================================
static NCollection_DataMap<Standard_Address, Standard_Size>& StorageIDMap()
{
  static NCollection_DataMap<Standard_Address, Standard_Size> TheMap;
  return TheMap;
}

//=======================================================================
/**
 * Static map (AllocatorID)
 */
//=======================================================================
static NCollection_Map<Standard_Size>& StorageIDSet()
{
  static NCollection_Map<Standard_Size> TheMap;
  return TheMap;
}

//=======================================================================
//function : IncAllocator_SetDebugFlag
//purpose  : Turn on/off debugging of memory allocation
//=======================================================================

Standard_EXPORT void IncAllocator_SetDebugFlag(const Standard_Boolean theDebug)
{
  IS_DEBUG = theDebug;
}

//=======================================================================
/**
 * Static value of the current allocation ID. It provides unique
 * numbering of allocators.
 */
//=======================================================================
static Standard_Size CurrentID = 0;
static Standard_Size CATCH_ID = 0;

//=======================================================================
//function : Debug_Create
//purpose  : Store the allocator address in the internal maps
//=======================================================================

static void Debug_Create(Standard_Address theAlloc)
{
  static Standard_Mutex aMutex;
  Standard_Boolean isReentrant = Standard::IsReentrant();
  if (isReentrant)
    aMutex.Lock();
  StorageIDMap().Bind(theAlloc, ++CurrentID);
  StorageIDSet().Add(CurrentID);
  if (isReentrant)
    aMutex.Unlock();
  if (CurrentID == CATCH_ID)
  {
    // Place for break point for creation of investigated allocator
    int a = 1;
  }
}

//=======================================================================
//function : Debug_Destroy
//purpose  : Forget the allocator address from the internal maps
//=======================================================================

static void Debug_Destroy(Standard_Address theAlloc)
{
  static Standard_Mutex aMutex;
  Standard_Boolean isReentrant = Standard::IsReentrant();
  if (isReentrant)
    aMutex.Lock();
  if (StorageIDMap().IsBound(theAlloc))
  {
    Standard_Size anID = StorageIDMap()(theAlloc);
    StorageIDSet().Remove(anID);
    StorageIDMap().UnBind(theAlloc);
  }
  if (isReentrant)
    aMutex.Unlock();
}

//=======================================================================
//function : IncAllocator_PrintAlive
//purpose  : Outputs the alive numbers to the file inc_alive.d
//=======================================================================

Standard_EXPORT void IncAllocator_PrintAlive()
{
  if (!StorageIDSet().IsEmpty())
  {
    FILE * ff = fopen("inc_alive.d", "wt");
    if (ff == NULL)
    {
      cout << "failure writing file inc_alive.d" << endl;
    }
    else
    {
      fprintf(ff, "Alive IncAllocators (number, size in Kb)\n");
      NCollection_DataMap<Standard_Address, Standard_Size>::Iterator
        itMap(StorageIDMap());
      Standard_Size aTotSize = 0;
      Standard_Integer nbAlloc = 0;
      for (; itMap.More(); itMap.Next())
      {
        NCollection_IncAllocator* anAlloc =
          static_cast<NCollection_IncAllocator*>(itMap.Key());
        Standard_Size anID = itMap.Value();
        Standard_Size aSize = anAlloc->GetMemSize();
        aTotSize += aSize;
        nbAlloc++;
        fprintf(ff, "%-8d %8.1f\n", anID, double(aSize)/1024);
      }
      fprintf(ff, "Total:\n%-8d %8.1f\n", nbAlloc, double(aTotSize)/1024);
      fclose(ff);
    }
  }
}

//=======================================================================
//function : NCollection_IncAllocator()
//purpose  : Constructor
//=======================================================================

NCollection_IncAllocator::NCollection_IncAllocator (const size_t theBlockSize)
{
#ifdef ALLOC_TRACK_USAGE
  printf ("\n..NCollection_IncAllocator: Created (%x)\n",this);
#endif
#ifdef DEB
  if (IS_DEBUG)
    Debug_Create(this);
#endif
  const size_t aSize = IMEM_SIZE(sizeof(IBlock)) +
      IMEM_SIZE((theBlockSize > 2*sizeof(IBlock)) ? theBlockSize : 24600);
  IBlock * const aBlock = (IBlock *) malloc (aSize * sizeof(aligned_t));
  myFirstBlock = aBlock;
  mySize = aSize;
  myMemSize = aSize * sizeof(aligned_t);
  if (aBlock == NULL)
    Standard_OutOfMemory::Raise("NCollection_IncAllocator: out of memory");
  aBlock -> p_free_space = (aligned_t *) IMEM_ALIGN (&aBlock[1]);
  aBlock -> p_end_block  = ((aligned_t *) aBlock) + aSize;
  aBlock -> p_next       = NULL;
}

//=======================================================================
//function : ~NCollection_IncAllocator
//purpose  : Destructor
//=======================================================================

NCollection_IncAllocator::~NCollection_IncAllocator ()
{
#ifdef DEB
  if (IS_DEBUG)
    Debug_Destroy(this);
#endif
  Clean();
  free (myFirstBlock);
}

//=======================================================================
//function : Allocate
//purpose  : allocate a memory
//remark   : returns NULL if allocation fails
//=======================================================================

void * NCollection_IncAllocator::Allocate (const size_t aSize)
{
  aligned_t * aResult = NULL;
  const size_t cSize = aSize ? IMEM_SIZE(aSize) : 0;

  if (cSize > mySize) {
    /* If the requested size exceeds normal allocation size, allocate
       a separate block and place it as the head of the list              */
    aResult = (aligned_t *) allocateNewBlock (cSize+1);
    if (aResult)
      myFirstBlock -> p_free_space = myFirstBlock -> p_end_block;
  } else
    if (cSize <= IMEM_FREE(myFirstBlock)) {
      /* If the requested size fits into the free space in the 1st block  */
      aResult = myFirstBlock -> allocateInBlock (cSize);
    } else {
      /* Search for a block in the list with enough free space            */
      int aMaxLookup = MaxLookup;   /* limit the number of blocks to query */
      IBlock * aCurrentBlock = myFirstBlock -> p_next;
      while (aCurrentBlock && aMaxLookup--) {
        if (cSize <= IMEM_FREE(aCurrentBlock)) {
          aResult = aCurrentBlock -> allocateInBlock (cSize);
          break;
        }
        aCurrentBlock = aCurrentBlock -> p_next;
      }
      if (aResult == NULL) {
        /* There is no available block with enough free space. Create a new
           one and place it in the head of the list                       */
        aResult = (aligned_t *) allocateNewBlock (mySize);
        if (aResult)
          myFirstBlock -> p_free_space = aResult + cSize;
      }
    }
  return aResult;
}

//=======================================================================
//function : Reallocate
//purpose  :
//=======================================================================

void * NCollection_IncAllocator::Reallocate (void         * theAddress,
                                             const size_t oldSize,
                                             const size_t newSize)
{
// Check that the dummy parameters are OK
  if (theAddress == NULL || oldSize == 0)
    return Allocate (newSize);
  const size_t cOldSize = IMEM_SIZE(oldSize);
  const size_t cNewSize = newSize ? IMEM_SIZE(newSize) : 0;
  aligned_t * anAddress = (aligned_t *) theAddress;

// We check only the LAST allocation to do the real extension/contraction
  if (anAddress + cOldSize == myFirstBlock -> p_free_space) {
    myFirstBlock -> p_free_space = anAddress;
// If the new size fits into the memory block => OK
// This also includes any case of contraction
    if (cNewSize <= IMEM_FREE(myFirstBlock)) {
      myFirstBlock -> p_free_space += cNewSize;
      return anAddress;
    }
  }
// In case of contraction of non-terminating allocation, do nothing
  else if (cOldSize >= cNewSize)
    return anAddress;
// Extension of non-terminated allocation if there is enough room in the
// current memory block
  if (cNewSize <= IMEM_FREE(myFirstBlock)) {
    aligned_t * aResult = myFirstBlock -> allocateInBlock (cNewSize);
    if (aResult)
      for (unsigned i = 0; i < cOldSize; i++)
        aResult[i] = anAddress[i];
    return aResult;
  }

// This is either of the cases:
//   - extension of non-terminating allocation, or
//   - extension of terminating allocation when the new size is too big
// In both cases create a new memory block, allocate memory and copy there
// the reallocated memory.
  aligned_t * aResult = (aligned_t *) allocateNewBlock (mySize);
  if (aResult) {
    myFirstBlock -> p_free_space = aResult + cNewSize;
    for (unsigned i = 0; i < cOldSize; i++)
      aResult[i] = anAddress[i];
  }
  return aResult;
}

//=======================================================================
//function : Free
//purpose  :
//=======================================================================

void NCollection_IncAllocator::Free (void *)
{}

//=======================================================================
//function : Clean
//purpose  :
//=======================================================================

void NCollection_IncAllocator::Clean ()
{
#ifdef ALLOC_TRACK_USAGE
  printf ("\n..NCollection_IncAllocator: Memory size to clean:%8.1f kB (%x)\n",
           double(GetMemSize())/1024, this);
#endif
  IBlock * aBlock = myFirstBlock;
  if (aBlock) {
    aBlock -> p_free_space = (aligned_t *) &aBlock[1];
    aBlock = aBlock -> p_next;
    while (aBlock) {
      IBlock * aNext = aBlock -> p_next;
      free (aBlock);
      aBlock = aNext;
    }
    myFirstBlock -> p_next = NULL;
  }
  myMemSize = 0;
}

//=======================================================================
//function : Reset
//purpose  :
//=======================================================================

void NCollection_IncAllocator::Reset (const Standard_Boolean doReleaseMem)
{
  if (doReleaseMem)
    Clean();
  else {
    Standard_Integer aBlockCount(0);
    IBlock * aBlock = myFirstBlock;
    while (aBlock)
      if (aBlockCount++ < MaxLookup) {
        aBlock -> p_free_space = (aligned_t *) &aBlock[1];
        if (aBlockCount < MaxLookup)
          aBlock = aBlock -> p_next;
        else {
          IBlock * aNext = aBlock -> p_next;
          aBlock -> p_next = NULL;
          aBlock = aNext;
        }
      } else {
        IBlock * aNext = aBlock -> p_next;
        myMemSize -= (aBlock -> p_end_block - (aligned_t *) aBlock) * sizeof (aligned_t);
        free (aBlock);
        aBlock = aNext;
      }
  }
}

//=======================================================================
//function : GetMemSize
//purpose  : diagnostic utility
//=======================================================================

size_t NCollection_IncAllocator::GetMemSize () const
{
//   size_t aResult = 0;
//   IBlock * aBlock = myFirstBlock;
//   while (aBlock) {
//     aResult += (aBlock -> p_end_block - (aligned_t *) aBlock);
//     aBlock = aBlock -> p_next;
//   }
//   return aResult * sizeof (aligned_t);
  return myMemSize;
}

//=======================================================================
//function : allocateNewBlock
//purpose  :
//=======================================================================

void * NCollection_IncAllocator::allocateNewBlock (const size_t cSize)
{
  aligned_t * aResult = 0L;
  const size_t aSz = cSize + IMEM_SIZE(sizeof(IBlock));
  IBlock * aBlock = (IBlock *) malloc (aSz * sizeof(aligned_t));
  if (aBlock) {
    aBlock -> p_end_block  = ((aligned_t *)aBlock) + aSz;
    aBlock -> p_next = myFirstBlock;
    myFirstBlock = aBlock;
    aResult = (aligned_t *) IMEM_ALIGN(&aBlock[1]);
    myMemSize += aSz * sizeof(aligned_t);
  }
  else
    Standard_OutOfMemory::Raise("NCollection_IncAllocator: out of memory");
  return aResult;
}
<commit_msg>[warning-fix][unused-function] Unused functions Debug_Create and Debug_Destroy defined in NCollection_IncAllocator.cxx. These functions may be useful for debugging. As a consequence, they are not compiled anymore in Release mode, only in Debug mode.<commit_after>// File:      NCollection_IncAllocator.cxx
// Created:   12.04.02 21:16:26
// Author:    Alexander GRIGORIEV
// Copyright: Open Cascade 2002

#include <NCollection_IncAllocator.hxx>
#include <NCollection_DataMap.hxx>
#include <NCollection_Map.hxx>
#include <Standard_Mutex.hxx>
#include <Standard_OutOfMemory.hxx>
#include <stdio.h>

IMPLEMENT_STANDARD_HANDLE  (NCollection_IncAllocator,NCollection_BaseAllocator)
IMPLEMENT_STANDARD_RTTIEXT (NCollection_IncAllocator,NCollection_BaseAllocator)

#define IMEM_SIZE(_size) ((((_size) - 1)/sizeof(aligned_t)) + 1)
#define IMEM_FREE(p_bl) ((unsigned int)(p_bl->p_end_block - p_bl->p_free_space))
#define IMEM_ALIGN(_addr) (sizeof(aligned_t)* IMEM_SIZE((unsigned long)(_addr)))

#define MaxLookup 16

static Standard_Boolean IS_DEBUG = Standard_False;

//=======================================================================
/**
 * Static data map (address -> AllocatorID)
 */
//=======================================================================
static NCollection_DataMap<Standard_Address, Standard_Size>& StorageIDMap()
{
  static NCollection_DataMap<Standard_Address, Standard_Size> TheMap;
  return TheMap;
}

//=======================================================================
/**
 * Static map (AllocatorID)
 */
//=======================================================================
static NCollection_Map<Standard_Size>& StorageIDSet()
{
  static NCollection_Map<Standard_Size> TheMap;
  return TheMap;
}

//=======================================================================
//function : IncAllocator_SetDebugFlag
//purpose  : Turn on/off debugging of memory allocation
//=======================================================================

Standard_EXPORT void IncAllocator_SetDebugFlag(const Standard_Boolean theDebug)
{
  IS_DEBUG = theDebug;
}

//=======================================================================
/**
 * Static value of the current allocation ID. It provides unique
 * numbering of allocators.
 */
//=======================================================================
#ifdef DEBUG
static Standard_Size CurrentID = 0;
static Standard_Size CATCH_ID = 0;

//=======================================================================
//function : Debug_Create
//purpose  : Store the allocator address in the internal maps
//=======================================================================
static void Debug_Create(Standard_Address theAlloc)
{
  static Standard_Mutex aMutex;
  Standard_Boolean isReentrant = Standard::IsReentrant();
  if (isReentrant)
    aMutex.Lock();
  StorageIDMap().Bind(theAlloc, ++CurrentID);
  StorageIDSet().Add(CurrentID);
  if (isReentrant)
    aMutex.Unlock();
  if (CurrentID == CATCH_ID)
  {
    // Place for break point for creation of investigated allocator
    int a = 1;
  }
}

//=======================================================================
//function : Debug_Destroy
//purpose  : Forget the allocator address from the internal maps
//=======================================================================
static void Debug_Destroy(Standard_Address theAlloc)
{
  static Standard_Mutex aMutex;
  Standard_Boolean isReentrant = Standard::IsReentrant();
  if (isReentrant)
    aMutex.Lock();
  if (StorageIDMap().IsBound(theAlloc))
  {
    Standard_Size anID = StorageIDMap()(theAlloc);
    StorageIDSet().Remove(anID);
    StorageIDMap().UnBind(theAlloc);
  }
  if (isReentrant)
    aMutex.Unlock();
}
#endif
//=======================================================================
//function : IncAllocator_PrintAlive
//purpose  : Outputs the alive numbers to the file inc_alive.d
//=======================================================================

Standard_EXPORT void IncAllocator_PrintAlive()
{
  if (!StorageIDSet().IsEmpty())
  {
    FILE * ff = fopen("inc_alive.d", "wt");
    if (ff == NULL)
    {
      cout << "failure writing file inc_alive.d" << endl;
    }
    else
    {
      fprintf(ff, "Alive IncAllocators (number, size in Kb)\n");
      NCollection_DataMap<Standard_Address, Standard_Size>::Iterator
        itMap(StorageIDMap());
      Standard_Size aTotSize = 0;
      Standard_Integer nbAlloc = 0;
      for (; itMap.More(); itMap.Next())
      {
        NCollection_IncAllocator* anAlloc =
          static_cast<NCollection_IncAllocator*>(itMap.Key());
        Standard_Size anID = itMap.Value();
        Standard_Size aSize = anAlloc->GetMemSize();
        aTotSize += aSize;
        nbAlloc++;
        fprintf(ff, "%-8d %8.1f\n", anID, double(aSize)/1024);
      }
      fprintf(ff, "Total:\n%-8d %8.1f\n", nbAlloc, double(aTotSize)/1024);
      fclose(ff);
    }
  }
}

//=======================================================================
//function : NCollection_IncAllocator()
//purpose  : Constructor
//=======================================================================

NCollection_IncAllocator::NCollection_IncAllocator (const size_t theBlockSize)
{
#ifdef ALLOC_TRACK_USAGE
  printf ("\n..NCollection_IncAllocator: Created (%x)\n",this);
#endif
#ifdef DEB
  if (IS_DEBUG)
    Debug_Create(this);
#endif
  const size_t aSize = IMEM_SIZE(sizeof(IBlock)) +
      IMEM_SIZE((theBlockSize > 2*sizeof(IBlock)) ? theBlockSize : 24600);
  IBlock * const aBlock = (IBlock *) malloc (aSize * sizeof(aligned_t));
  myFirstBlock = aBlock;
  mySize = aSize;
  myMemSize = aSize * sizeof(aligned_t);
  if (aBlock == NULL)
    Standard_OutOfMemory::Raise("NCollection_IncAllocator: out of memory");
  aBlock -> p_free_space = (aligned_t *) IMEM_ALIGN (&aBlock[1]);
  aBlock -> p_end_block  = ((aligned_t *) aBlock) + aSize;
  aBlock -> p_next       = NULL;
}

//=======================================================================
//function : ~NCollection_IncAllocator
//purpose  : Destructor
//=======================================================================

NCollection_IncAllocator::~NCollection_IncAllocator ()
{
#ifdef DEB
  if (IS_DEBUG)
    Debug_Destroy(this);
#endif
  Clean();
  free (myFirstBlock);
}

//=======================================================================
//function : Allocate
//purpose  : allocate a memory
//remark   : returns NULL if allocation fails
//=======================================================================

void * NCollection_IncAllocator::Allocate (const size_t aSize)
{
  aligned_t * aResult = NULL;
  const size_t cSize = aSize ? IMEM_SIZE(aSize) : 0;

  if (cSize > mySize) {
    /* If the requested size exceeds normal allocation size, allocate
       a separate block and place it as the head of the list              */
    aResult = (aligned_t *) allocateNewBlock (cSize+1);
    if (aResult)
      myFirstBlock -> p_free_space = myFirstBlock -> p_end_block;
  } else
    if (cSize <= IMEM_FREE(myFirstBlock)) {
      /* If the requested size fits into the free space in the 1st block  */
      aResult = myFirstBlock -> allocateInBlock (cSize);
    } else {
      /* Search for a block in the list with enough free space            */
      int aMaxLookup = MaxLookup;   /* limit the number of blocks to query */
      IBlock * aCurrentBlock = myFirstBlock -> p_next;
      while (aCurrentBlock && aMaxLookup--) {
        if (cSize <= IMEM_FREE(aCurrentBlock)) {
          aResult = aCurrentBlock -> allocateInBlock (cSize);
          break;
        }
        aCurrentBlock = aCurrentBlock -> p_next;
      }
      if (aResult == NULL) {
        /* There is no available block with enough free space. Create a new
           one and place it in the head of the list                       */
        aResult = (aligned_t *) allocateNewBlock (mySize);
        if (aResult)
          myFirstBlock -> p_free_space = aResult + cSize;
      }
    }
  return aResult;
}

//=======================================================================
//function : Reallocate
//purpose  :
//=======================================================================

void * NCollection_IncAllocator::Reallocate (void         * theAddress,
                                             const size_t oldSize,
                                             const size_t newSize)
{
// Check that the dummy parameters are OK
  if (theAddress == NULL || oldSize == 0)
    return Allocate (newSize);
  const size_t cOldSize = IMEM_SIZE(oldSize);
  const size_t cNewSize = newSize ? IMEM_SIZE(newSize) : 0;
  aligned_t * anAddress = (aligned_t *) theAddress;

// We check only the LAST allocation to do the real extension/contraction
  if (anAddress + cOldSize == myFirstBlock -> p_free_space) {
    myFirstBlock -> p_free_space = anAddress;
// If the new size fits into the memory block => OK
// This also includes any case of contraction
    if (cNewSize <= IMEM_FREE(myFirstBlock)) {
      myFirstBlock -> p_free_space += cNewSize;
      return anAddress;
    }
  }
// In case of contraction of non-terminating allocation, do nothing
  else if (cOldSize >= cNewSize)
    return anAddress;
// Extension of non-terminated allocation if there is enough room in the
// current memory block
  if (cNewSize <= IMEM_FREE(myFirstBlock)) {
    aligned_t * aResult = myFirstBlock -> allocateInBlock (cNewSize);
    if (aResult)
      for (unsigned i = 0; i < cOldSize; i++)
        aResult[i] = anAddress[i];
    return aResult;
  }

// This is either of the cases:
//   - extension of non-terminating allocation, or
//   - extension of terminating allocation when the new size is too big
// In both cases create a new memory block, allocate memory and copy there
// the reallocated memory.
  aligned_t * aResult = (aligned_t *) allocateNewBlock (mySize);
  if (aResult) {
    myFirstBlock -> p_free_space = aResult + cNewSize;
    for (unsigned i = 0; i < cOldSize; i++)
      aResult[i] = anAddress[i];
  }
  return aResult;
}

//=======================================================================
//function : Free
//purpose  :
//=======================================================================

void NCollection_IncAllocator::Free (void *)
{}

//=======================================================================
//function : Clean
//purpose  :
//=======================================================================

void NCollection_IncAllocator::Clean ()
{
#ifdef ALLOC_TRACK_USAGE
  printf ("\n..NCollection_IncAllocator: Memory size to clean:%8.1f kB (%x)\n",
           double(GetMemSize())/1024, this);
#endif
  IBlock * aBlock = myFirstBlock;
  if (aBlock) {
    aBlock -> p_free_space = (aligned_t *) &aBlock[1];
    aBlock = aBlock -> p_next;
    while (aBlock) {
      IBlock * aNext = aBlock -> p_next;
      free (aBlock);
      aBlock = aNext;
    }
    myFirstBlock -> p_next = NULL;
  }
  myMemSize = 0;
}

//=======================================================================
//function : Reset
//purpose  :
//=======================================================================

void NCollection_IncAllocator::Reset (const Standard_Boolean doReleaseMem)
{
  if (doReleaseMem)
    Clean();
  else {
    Standard_Integer aBlockCount(0);
    IBlock * aBlock = myFirstBlock;
    while (aBlock)
      if (aBlockCount++ < MaxLookup) {
        aBlock -> p_free_space = (aligned_t *) &aBlock[1];
        if (aBlockCount < MaxLookup)
          aBlock = aBlock -> p_next;
        else {
          IBlock * aNext = aBlock -> p_next;
          aBlock -> p_next = NULL;
          aBlock = aNext;
        }
      } else {
        IBlock * aNext = aBlock -> p_next;
        myMemSize -= (aBlock -> p_end_block - (aligned_t *) aBlock) * sizeof (aligned_t);
        free (aBlock);
        aBlock = aNext;
      }
  }
}

//=======================================================================
//function : GetMemSize
//purpose  : diagnostic utility
//=======================================================================

size_t NCollection_IncAllocator::GetMemSize () const
{
//   size_t aResult = 0;
//   IBlock * aBlock = myFirstBlock;
//   while (aBlock) {
//     aResult += (aBlock -> p_end_block - (aligned_t *) aBlock);
//     aBlock = aBlock -> p_next;
//   }
//   return aResult * sizeof (aligned_t);
  return myMemSize;
}

//=======================================================================
//function : allocateNewBlock
//purpose  :
//=======================================================================

void * NCollection_IncAllocator::allocateNewBlock (const size_t cSize)
{
  aligned_t * aResult = 0L;
  const size_t aSz = cSize + IMEM_SIZE(sizeof(IBlock));
  IBlock * aBlock = (IBlock *) malloc (aSz * sizeof(aligned_t));
  if (aBlock) {
    aBlock -> p_end_block  = ((aligned_t *)aBlock) + aSz;
    aBlock -> p_next = myFirstBlock;
    myFirstBlock = aBlock;
    aResult = (aligned_t *) IMEM_ALIGN(&aBlock[1]);
    myMemSize += aSz * sizeof(aligned_t);
  }
  else
    Standard_OutOfMemory::Raise("NCollection_IncAllocator: out of memory");
  return aResult;
}
<|endoftext|>


<commit_before>#include "stdafx.h"

#include "ThreadManager.h"
#include "Ini.h"
#include "SceneThread.h"
#include "SceneManager.h"
#include "Config.h"

ThreadManager*    g_pThreadManager=NULL ;

ThreadManager::ThreadManager( )
{
__ENTER_FUNCTION

    m_pThreadPool = new ThreadPool ;
    Assert( m_pThreadPool ) ;

    m_pServerThread = new ServerThread ;
    Assert( m_pServerThread ) ;

    m_nThreads = 0 ;

__LEAVE_FUNCTION
}

ThreadManager::~ThreadManager( )
{
__ENTER_FUNCTION

    SAFE_DELETE( m_pThreadPool) ;
    SAFE_DELETE( m_pServerThread) ;

__LEAVE_FUNCTION
}

BOOL ThreadManager::Init( UINT MaxSceneCount )
{
__ENTER_FUNCTION

    BOOL ret = FALSE ;

    //根据配置文件读取需要使用的场景，为每个场景分配一个线程；
    //读取场景数量
    UINT count = MaxSceneCount ;

    Assert( count<=MAX_SCENE ) ;

    UINT uMaxThreadCount = 0 ;
    UINT i ;
    for( i=0; i<count; i++ )
    {
        //读取场景“i”
        SceneID_t SceneID = (SceneID_t)(g_Config.m_SceneInfo.m_pScene[i].m_SceneID) ;
        Assert( SceneID<MAX_SCENE ) ;

        UINT ServerID = g_Config.m_SceneInfo.m_pScene[i].m_ServerID ;
        if( ServerID != g_Config.m_ConfigInfo.m_ServerID )
        {//不是当前服务器的程序运行的场景
            continue ;
        }
        if( g_Config.m_SceneInfo.m_pScene[i].m_IsActive==0 )
        {//不是激活的场景
            continue ;
        }

        if( (ID_t)uMaxThreadCount<g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex )
        {
            uMaxThreadCount = g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex ;
        }
    }

    SceneThread* pSceneThread=NULL ;
    for( i=0; i<=uMaxThreadCount; i++ )
    {
        pSceneThread = new SceneThread ;
        Assert( pSceneThread ) ;

        LERR( "FILE: %s, i: %d", __FILE__, i )
        ret = m_pThreadPool->AddThread( i, pSceneThread ) ;
        Assert( ret ) ;

        m_nThreads ++ ;
    }

    for ( i = 0; i < uMaxThreadCount; i++ )
    {
        Thread** m_pThread = m_pThreadPool->GetThread();
        SceneThread* pSceneThread1 = (SceneThread*)( m_pThread[ i ] );
        LERR( "uThreadIndex: %d, obj: %d , sizeof( pSceneThread1 ):%d", i, pSceneThread1, sizeof( pSceneThread1 ) );
    }

    for( i=0; i<count; i++ )
    {
        //读取场景“i”
        SceneID_t SceneID = (SceneID_t)(g_Config.m_SceneInfo.m_pScene[i].m_SceneID) ;
        Assert( SceneID<MAX_SCENE ) ;

        UINT ServerID = g_Config.m_SceneInfo.m_pScene[i].m_ServerID ;
        if( ServerID != g_Config.m_ConfigInfo.m_ServerID )
        {//不是当前服务器的程序运行的场景
            continue ;
        }
        if( g_Config.m_SceneInfo.m_pScene[i].m_IsActive==0 )
        {//不是激活的场景
            continue ;
        }

        LERR( "FILE: %s, LINE: %d, m_ThreadIndex: %d", __FILE__, __LINE__, g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex );
        SceneThread* pSceneThread = (SceneThread*)(m_pThreadPool->GetThreadByIndex(g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex)) ;
        if( pSceneThread==NULL )
        {
            AssertEx(FALSE,"没有创建所需的线程") ;
        }
        else
        {

            Scene* pScene = g_pSceneManager->GetScene(SceneID) ;
            pSceneThread->AddScene( pScene );

    LERR( "FILE: %s, LINE: %d", __FILE__, __LINE__ );
        }
    }

    LERR( "FILE: %s, LINE: %d", __FILE__, __LINE__ );
    if( m_pServerThread->IsActive() )
    {
        m_nThreads ++ ;
    }

    return TRUE ;

__LEAVE_FUNCTION

    return FALSE ;
}

BOOL ThreadManager::Start( )
{
__ENTER_FUNCTION

    BOOL ret ;

    m_pServerThread->start() ;

    MySleep( 500 ) ;

    ret = m_pThreadPool->Start( ) ;

    return ret ;

__LEAVE_FUNCTION

    return FALSE ;
}

BOOL ThreadManager::Stop( )
{
__ENTER_FUNCTION

    if( m_pServerThread )
    {
        m_pServerThread->stop( ) ;
    }

    return m_pThreadPool->Stop( ) ;

__LEAVE_FUNCTION

    return FALSE ;
}

<commit_msg>fix some bug<commit_after>#include "stdafx.h"

#include "ThreadManager.h"
#include "Ini.h"
#include "SceneThread.h"
#include "SceneManager.h"
#include "Config.h"

ThreadManager*    g_pThreadManager=NULL ;

ThreadManager::ThreadManager( )
{
__ENTER_FUNCTION

    m_pThreadPool = new ThreadPool ;
    Assert( m_pThreadPool ) ;

    m_pServerThread = new ServerThread ;
    Assert( m_pServerThread ) ;

    m_nThreads = 0 ;

__LEAVE_FUNCTION
}

ThreadManager::~ThreadManager( )
{
__ENTER_FUNCTION

    SAFE_DELETE( m_pThreadPool) ;
    SAFE_DELETE( m_pServerThread) ;

__LEAVE_FUNCTION
}

BOOL ThreadManager::Init( UINT MaxSceneCount )
{
__ENTER_FUNCTION

    BOOL ret = FALSE ;

    //根据配置文件读取需要使用的场景，为每个场景分配一个线程；
    //读取场景数量
    UINT count = MaxSceneCount ;

    Assert( count<=MAX_SCENE ) ;

    UINT uMaxThreadCount = 0 ;
    UINT i ;
    for( i=0; i<count; i++ )
    {
        //读取场景“i”
        SceneID_t SceneID = (SceneID_t)(g_Config.m_SceneInfo.m_pScene[i].m_SceneID) ;
        Assert( SceneID<MAX_SCENE ) ;

        UINT ServerID = g_Config.m_SceneInfo.m_pScene[i].m_ServerID ;
        if( ServerID != g_Config.m_ConfigInfo.m_ServerID )
        {//不是当前服务器的程序运行的场景
            continue ;
        }
        if( g_Config.m_SceneInfo.m_pScene[i].m_IsActive==0 )
        {//不是激活的场景
            continue ;
        }

        if( (ID_t)uMaxThreadCount<g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex )
        {
            uMaxThreadCount = g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex ;
        }
    }

    SceneThread* pSceneThread=NULL ;
    for( i=0; i<=uMaxThreadCount; i++ )
    {
        pSceneThread = new SceneThread ;
        Assert( pSceneThread ) ;

        ret = m_pThreadPool->AddThread( i, pSceneThread ) ;
        Assert( ret ) ;

        m_nThreads ++ ;
    }

    /**
    for ( i = 0; i < uMaxThreadCount; i++ )
    {
        Thread** m_pThread = m_pThreadPool->GetThread();
        SceneThread* pSceneThread1 = (SceneThread*)( m_pThread[ i ] );
        LERR( "uThreadIndex: %d, obj: %d , sizeof( pSceneThread1 ):%d", i, pSceneThread1, sizeof( pSceneThread1 ) );
    }
    **/ //my debug

    for( i=0; i<count; i++ )
    {
        //读取场景“i”
        SceneID_t SceneID = (SceneID_t)(g_Config.m_SceneInfo.m_pScene[i].m_SceneID) ;
        Assert( SceneID<MAX_SCENE ) ;

        UINT ServerID = g_Config.m_SceneInfo.m_pScene[i].m_ServerID ;
        if( ServerID != g_Config.m_ConfigInfo.m_ServerID )
        {//不是当前服务器的程序运行的场景
            continue ;
        }
        if( g_Config.m_SceneInfo.m_pScene[i].m_IsActive==0 )
        {//不是激活的场景
            continue ;
        }

        SceneThread* pSceneThread = (SceneThread*)(m_pThreadPool->GetThreadByIndex(g_Config.m_SceneInfo.m_pScene[i].m_ThreadIndex)) ;
        if( pSceneThread==NULL )
        {
            AssertEx(FALSE,"没有创建所需的线程") ;
        }
        else
        {

            Scene* pScene = g_pSceneManager->GetScene(SceneID) ;
            pSceneThread->AddScene( pScene );

        }
    }

    if( m_pServerThread->IsActive() )
    {
        m_nThreads ++ ;
    }

    return TRUE ;

__LEAVE_FUNCTION

    return FALSE ;
}

BOOL ThreadManager::Start( )
{
__ENTER_FUNCTION

    BOOL ret ;

    m_pServerThread->start() ;

    MySleep( 500 ) ;

    ret = m_pThreadPool->Start( ) ;

    return ret ;

__LEAVE_FUNCTION

    return FALSE ;
}

BOOL ThreadManager::Stop( )
{
__ENTER_FUNCTION

    if( m_pServerThread )
    {
        m_pServerThread->stop( ) ;
    }

    return m_pThreadPool->Stop( ) ;

__LEAVE_FUNCTION

    return FALSE ;
}

<|endoftext|>


<commit_before>#ifndef STAN_MATH_HPP
#define STAN_MATH_HPP

  #include <stan/math/rev/mat.hpp>

#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.1-svn319952-1~exp1 (branches/release_50)<commit_after>#ifndef STAN_MATH_HPP
#define STAN_MATH_HPP

#include <stan/math/rev/mat.hpp>

#endif
<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** HttpServerHandler.cpp
**
** -------------------------------------------------------------------------*/

#include <iostream>

#include "HttpServerRequestHandler.h"

/* ---------------------------------------------------------------------------
**  Civet HTTP callback
** -------------------------------------------------------------------------*/
class RequestHandler : public CivetHandler
{
  public:
	bool handle(CivetServer *server, struct mg_connection *conn)
	{
		bool ret = false;
		const struct mg_request_info *req_info = mg_get_request_info(conn);

		HttpServerRequestHandler* httpServer = (HttpServerRequestHandler*)server;

		httpFunction fct = httpServer->getFunction(req_info->request_uri);
		if (fct != NULL)
		{
			Json::Value  jmessage;

			// read input
			long long tlen = req_info->content_length;
			if (tlen > 0)
			{
				std::string body;
				long long nlen = 0;
				char buf[1024];
				while (nlen < tlen) {
					long long rlen = tlen - nlen;
					if (rlen > sizeof(buf)) {
						rlen = sizeof(buf);
					}
					rlen = mg_read(conn, buf, (size_t)rlen);
					if (rlen <= 0) {
						break;
					}
					body.append(buf, rlen);

					nlen += rlen;
				}
				std::cout << "body:" << body << std::endl;

				// parse in
				Json::Reader reader;
				if (!reader.parse(body, jmessage))
				{
					RTC_LOG(WARNING) << "Received unknown message:" << body;
				}
			}

			// invoke API implementation
			Json::Value out(fct(req_info, jmessage));

			// fill out
			if (out.isNull() == false)
			{
				std::string answer(Json::StyledWriter().write(out));
				std::cout << "answer:" << answer << std::endl;

				mg_printf(conn,"HTTP/1.1 200 OK\r\n");
				mg_printf(conn,"Access-Control-Allow-Origin: *\r\n");
				mg_printf(conn,"Content-Type: application/json\r\n");
				mg_printf(conn,"Content-Length: %zd\r\n", answer.size());
				mg_printf(conn,"Connection: close\r\n");
				mg_printf(conn,"\r\n");
				mg_printf(conn,answer.c_str());

				ret = true;
			}
		}

		return ret;
	}
	bool handleGet(CivetServer *server, struct mg_connection *conn)
	{
		return handle(server, conn);
	}
	bool handlePost(CivetServer *server, struct mg_connection *conn)
	{
		return handle(server, conn);
	}
};

int log_message(const struct mg_connection *conn, const char *message)
{
	fprintf(stderr, "%s\n", message);
	return 0;
}

static struct CivetCallbacks _callbacks;
const struct CivetCallbacks * getCivetCallbacks()
{
	memset(&_callbacks, 0, sizeof(_callbacks));
	_callbacks.log_message = &log_message;
	return &_callbacks;
}

/* ---------------------------------------------------------------------------
**  Constructor
** -------------------------------------------------------------------------*/
HttpServerRequestHandler::HttpServerRequestHandler(PeerConnectionManager* webRtcServer, const std::vector<std::string>& options)
	: CivetServer(options, getCivetCallbacks()), m_webRtcServer(webRtcServer)
{
	// http api callbacks
	m_func["/api/getMediaList"]          = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		return m_webRtcServer->getMediaList();
	};

	m_func["/api/getVideoDeviceList"]    = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		return m_webRtcServer->getVideoDeviceList();
	};

	m_func["/api/getAudioDeviceList"]    = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		return m_webRtcServer->getAudioDeviceList();
	};

	m_func["/api/getIceServers"]         = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		return m_webRtcServer->getIceServers(req_info->remote_addr);
	};

	m_func["/api/call"]                  = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string peerid;
		std::string url;
		std::string audiourl;
		std::string options;
		if (req_info->query_string) {
            CivetServer::getParam(req_info->query_string, "peerid", peerid);
            CivetServer::getParam(req_info->query_string, "url", url);
            CivetServer::getParam(req_info->query_string, "audiourl", audiourl);
            CivetServer::getParam(req_info->query_string, "options", options);
        }
		return m_webRtcServer->call(peerid, url, audiourl, options, in);
	};

	m_func["/api/hangup"]                = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string peerid;
		if (req_info->query_string) {
            CivetServer::getParam(req_info->query_string, "peerid", peerid);
        }
		return m_webRtcServer->hangUp(peerid);
	};

	m_func["/api/createOffer"]           = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string peerid;
		std::string url;
		std::string audiourl;
		std::string options;
		if (req_info->query_string) {
            CivetServer::getParam(req_info->query_string, "peerid", peerid);
            CivetServer::getParam(req_info->query_string, "url", url);
            CivetServer::getParam(req_info->query_string, "audiourl", audiourl);
            CivetServer::getParam(req_info->query_string, "options", options);
        }
		return m_webRtcServer->createOffer(peerid, url, audiourl, options);
	};
	m_func["/api/setAnswer"]             = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string peerid;
		if (req_info->query_string) {
            CivetServer::getParam(req_info->query_string, "peerid", peerid);
        }
		m_webRtcServer->setAnswer(peerid, in);
		Json::Value answer(1);
		return answer;
	};

	m_func["/api/getIceCandidate"]       = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string peerid;
		if (req_info->query_string) {
            CivetServer::getParam(req_info->query_string, "peerid", peerid);
        }
		return m_webRtcServer->getIceCandidateList(peerid);
	};

	m_func["/api/addIceCandidate"]       = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string peerid;
		if (req_info->query_string) {
            CivetServer::getParam(req_info->query_string, "peerid", peerid);
        }
		return m_webRtcServer->addIceCandidate(peerid, in);
	};

	m_func["/api/getPeerConnectionList"] = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		return m_webRtcServer->getPeerConnectionList();
	};

	m_func["/api/getStreamList"] = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		return m_webRtcServer->getStreamList();
	};

	m_func["/api/help"]                  = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		Json::Value answer;
		for (auto it : m_func) {
			answer.append(it.first);
		}
		return answer;
	};

	m_func["/api/version"]                  = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		Json::Value answer(VERSION);
		return answer;
	};

	m_func["/api/log"]                      = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string loglevel;
		if (req_info->query_string) {
			CivetServer::getParam(req_info->query_string, "level", loglevel);
			if (!loglevel.empty()) {
				rtc::LogMessage::LogToDebug((rtc::LoggingSeverity)atoi(loglevel.c_str()));
			}
		}
		Json::Value answer(rtc::LogMessage::GetLogToDebug());
		return answer;
	};

	// register handlers
	for (auto it : m_func) {
		this->addHandler(it.first, new RequestHandler());
	}
}

httpFunction HttpServerRequestHandler::getFunction(const std::string& uri)
{
	httpFunction fct = NULL;
	std::map<std::string,httpFunction>::iterator it = m_func.find(uri);
	if (it != m_func.end())
	{
		fct = it->second;
	}

	return fct;
}

<commit_msg>fix warning<commit_after>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** HttpServerHandler.cpp
**
** -------------------------------------------------------------------------*/

#include <iostream>

#include "HttpServerRequestHandler.h"

/* ---------------------------------------------------------------------------
**  Civet HTTP callback
** -------------------------------------------------------------------------*/
class RequestHandler : public CivetHandler
{
  public:
	bool handle(CivetServer *server, struct mg_connection *conn)
	{
		bool ret = false;
		const struct mg_request_info *req_info = mg_get_request_info(conn);

		HttpServerRequestHandler* httpServer = (HttpServerRequestHandler*)server;

		httpFunction fct = httpServer->getFunction(req_info->request_uri);
		if (fct != NULL)
		{
			Json::Value  jmessage;

			// read input
			long long tlen = req_info->content_length;
			if (tlen > 0)
			{
				std::string body;
				long long nlen = 0;
				long long bufSize = 1024;
				char buf[bufSize];
				while (nlen < tlen) {
					long long rlen = tlen - nlen;
					if (rlen > bufSize) {
						rlen = bufSize;
					}
					rlen = mg_read(conn, buf, (size_t)rlen);
					if (rlen <= 0) {
						break;
					}
					body.append(buf, rlen);

					nlen += rlen;
				}
				std::cout << "body:" << body << std::endl;

				// parse in
				Json::Reader reader;
				if (!reader.parse(body, jmessage))
				{
					RTC_LOG(WARNING) << "Received unknown message:" << body;
				}
			}

			// invoke API implementation
			Json::Value out(fct(req_info, jmessage));

			// fill out
			if (out.isNull() == false)
			{
				std::string answer(Json::StyledWriter().write(out));
				std::cout << "answer:" << answer << std::endl;

				mg_printf(conn,"HTTP/1.1 200 OK\r\n");
				mg_printf(conn,"Access-Control-Allow-Origin: *\r\n");
				mg_printf(conn,"Content-Type: application/json\r\n");
				mg_printf(conn,"Content-Length: %zd\r\n", answer.size());
				mg_printf(conn,"Connection: close\r\n");
				mg_printf(conn,"\r\n");
				mg_printf(conn,"%s",answer.c_str());

				ret = true;
			}
		}

		return ret;
	}
	bool handleGet(CivetServer *server, struct mg_connection *conn)
	{
		return handle(server, conn);
	}
	bool handlePost(CivetServer *server, struct mg_connection *conn)
	{
		return handle(server, conn);
	}
};

int log_message(const struct mg_connection *conn, const char *message)
{
	fprintf(stderr, "%s\n", message);
	return 0;
}

static struct CivetCallbacks _callbacks;
const struct CivetCallbacks * getCivetCallbacks()
{
	memset(&_callbacks, 0, sizeof(_callbacks));
	_callbacks.log_message = &log_message;
	return &_callbacks;
}

/* ---------------------------------------------------------------------------
**  Constructor
** -------------------------------------------------------------------------*/
HttpServerRequestHandler::HttpServerRequestHandler(PeerConnectionManager* webRtcServer, const std::vector<std::string>& options)
	: CivetServer(options, getCivetCallbacks()), m_webRtcServer(webRtcServer)
{
	// http api callbacks
	m_func["/api/getMediaList"]          = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		return m_webRtcServer->getMediaList();
	};

	m_func["/api/getVideoDeviceList"]    = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		return m_webRtcServer->getVideoDeviceList();
	};

	m_func["/api/getAudioDeviceList"]    = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		return m_webRtcServer->getAudioDeviceList();
	};

	m_func["/api/getIceServers"]         = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		return m_webRtcServer->getIceServers(req_info->remote_addr);
	};

	m_func["/api/call"]                  = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string peerid;
		std::string url;
		std::string audiourl;
		std::string options;
		if (req_info->query_string) {
            CivetServer::getParam(req_info->query_string, "peerid", peerid);
            CivetServer::getParam(req_info->query_string, "url", url);
            CivetServer::getParam(req_info->query_string, "audiourl", audiourl);
            CivetServer::getParam(req_info->query_string, "options", options);
        }
		return m_webRtcServer->call(peerid, url, audiourl, options, in);
	};

	m_func["/api/hangup"]                = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string peerid;
		if (req_info->query_string) {
            CivetServer::getParam(req_info->query_string, "peerid", peerid);
        }
		return m_webRtcServer->hangUp(peerid);
	};

	m_func["/api/createOffer"]           = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string peerid;
		std::string url;
		std::string audiourl;
		std::string options;
		if (req_info->query_string) {
            CivetServer::getParam(req_info->query_string, "peerid", peerid);
            CivetServer::getParam(req_info->query_string, "url", url);
            CivetServer::getParam(req_info->query_string, "audiourl", audiourl);
            CivetServer::getParam(req_info->query_string, "options", options);
        }
		return m_webRtcServer->createOffer(peerid, url, audiourl, options);
	};
	m_func["/api/setAnswer"]             = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string peerid;
		if (req_info->query_string) {
            CivetServer::getParam(req_info->query_string, "peerid", peerid);
        }
		m_webRtcServer->setAnswer(peerid, in);
		Json::Value answer(1);
		return answer;
	};

	m_func["/api/getIceCandidate"]       = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string peerid;
		if (req_info->query_string) {
            CivetServer::getParam(req_info->query_string, "peerid", peerid);
        }
		return m_webRtcServer->getIceCandidateList(peerid);
	};

	m_func["/api/addIceCandidate"]       = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string peerid;
		if (req_info->query_string) {
            CivetServer::getParam(req_info->query_string, "peerid", peerid);
        }
		return m_webRtcServer->addIceCandidate(peerid, in);
	};

	m_func["/api/getPeerConnectionList"] = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		return m_webRtcServer->getPeerConnectionList();
	};

	m_func["/api/getStreamList"] = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		return m_webRtcServer->getStreamList();
	};

	m_func["/api/help"]                  = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		Json::Value answer;
		for (auto it : m_func) {
			answer.append(it.first);
		}
		return answer;
	};

	m_func["/api/version"]                  = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		Json::Value answer(VERSION);
		return answer;
	};

	m_func["/api/log"]                      = [this](const struct mg_request_info *req_info, const Json::Value & in) -> Json::Value {
		std::string loglevel;
		if (req_info->query_string) {
			CivetServer::getParam(req_info->query_string, "level", loglevel);
			if (!loglevel.empty()) {
				rtc::LogMessage::LogToDebug((rtc::LoggingSeverity)atoi(loglevel.c_str()));
			}
		}
		Json::Value answer(rtc::LogMessage::GetLogToDebug());
		return answer;
	};

	// register handlers
	for (auto it : m_func) {
		this->addHandler(it.first, new RequestHandler());
	}
}

httpFunction HttpServerRequestHandler::getFunction(const std::string& uri)
{
	httpFunction fct = NULL;
	std::map<std::string,httpFunction>::iterator it = m_func.find(uri);
	if (it != m_func.end())
	{
		fct = it->second;
	}

	return fct;
}

<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/lexical_cast.hpp"
#include "IECore/LRUCache.h"
#include "IECore/ObjectPool.h"

using namespace IECore;

////////////////////////////////////////////////////////////////////////
// MemberData
////////////////////////////////////////////////////////////////////////

struct ObjectPool::MemberData
{

	MemberData( size_t maxMemory ) : cache( getter, maxMemory )
	{
	}

	LRUCache< MurmurHash, ConstObjectPtr > cache;

	/// our getter always returns NULL
	static ConstObjectPtr getter( const MurmurHash &h, size_t &cost )
	{
		cost = 0;
		return NULL;
	}
};

//////////////////////////////////////////////////////////////////////////
// ObjectPool
//////////////////////////////////////////////////////////////////////////

ObjectPool::ObjectPool( size_t maxMemory )
	:	m_data( new MemberData(maxMemory) )
{
}

ObjectPool::~ObjectPool()
{
}

ConstObjectPtr ObjectPool::retrieve( const MurmurHash &hash ) const
{
	return m_data->cache.get(hash);
}

ConstObjectPtr ObjectPool::store( const Object *obj, StoreMode mode )
{
	MurmurHash h = obj->hash();

	// first tries to see if the object is already in the cache and return that one quickly.
	ConstObjectPtr cachedObj = m_data->cache.get(h);
	if ( cachedObj )
	{
		return cachedObj;
	}

	if ( mode == StoreCopy )
	{
		cachedObj = obj->copy();
		m_data->cache.set( h, cachedObj, obj->memoryUsage() );
		return cachedObj;
	}
	else if ( mode == StoreReference )
	{
		m_data->cache.set( h, obj, obj->memoryUsage() );
		return obj;
	}
	else
	{
		throw Exception( "Invalid store mode!" );
	}
}

bool ObjectPool::contains( const MurmurHash &hash ) const
{
	return m_data->cache.cached(hash);
}

void ObjectPool::clear()
{
	m_data->cache.clear();
}

bool ObjectPool::erase( const MurmurHash &hash )
{
	return m_data->cache.erase(hash);
}

void ObjectPool::setMaxMemoryUsage( size_t maxMemory )
{
	m_data->cache.setMaxCost(maxMemory);
}

size_t ObjectPool::getMaxMemoryUsage() const
{
	return m_data->cache.getMaxCost();
}

size_t ObjectPool::memoryUsage() const
{
	return m_data->cache.currentCost();
}

ObjectPoolPtr ObjectPool::defaultObjectPool()
{
	static ObjectPoolPtr c = 0;
	if( !c )
	{
		const char *m = getenv( "IECORE_OBJECTPOOL_MEMORY" );
		int mi = m ? boost::lexical_cast<int>( m ) : 500;
		c = new ObjectPool(1024 * 1024 * mi);
	}
	return c;
}

/// make sure the default pool is created at load time and avoid
/// running conditions on multi-threaded environments.
static ObjectPoolPtr initializer = ObjectPool::defaultObjectPool();

<commit_msg>Fixing default ObjectPool for larger sizes.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/lexical_cast.hpp"
#include "IECore/LRUCache.h"
#include "IECore/ObjectPool.h"

using namespace IECore;

////////////////////////////////////////////////////////////////////////
// MemberData
////////////////////////////////////////////////////////////////////////

struct ObjectPool::MemberData
{

	MemberData( size_t maxMemory ) : cache( getter, maxMemory )
	{
	}

	LRUCache< MurmurHash, ConstObjectPtr > cache;

	/// our getter always returns NULL
	static ConstObjectPtr getter( const MurmurHash &h, size_t &cost )
	{
		cost = 0;
		return NULL;
	}
};

//////////////////////////////////////////////////////////////////////////
// ObjectPool
//////////////////////////////////////////////////////////////////////////

ObjectPool::ObjectPool( size_t maxMemory )
	:	m_data( new MemberData(maxMemory) )
{
}

ObjectPool::~ObjectPool()
{
}

ConstObjectPtr ObjectPool::retrieve( const MurmurHash &hash ) const
{
	return m_data->cache.get(hash);
}

ConstObjectPtr ObjectPool::store( const Object *obj, StoreMode mode )
{
	MurmurHash h = obj->hash();

	// first tries to see if the object is already in the cache and return that one quickly.
	ConstObjectPtr cachedObj = m_data->cache.get(h);
	if ( cachedObj )
	{
		return cachedObj;
	}

	if ( mode == StoreCopy )
	{
		cachedObj = obj->copy();
		m_data->cache.set( h, cachedObj, obj->memoryUsage() );
		return cachedObj;
	}
	else if ( mode == StoreReference )
	{
		m_data->cache.set( h, obj, obj->memoryUsage() );
		return obj;
	}
	else
	{
		throw Exception( "Invalid store mode!" );
	}
}

bool ObjectPool::contains( const MurmurHash &hash ) const
{
	return m_data->cache.cached(hash);
}

void ObjectPool::clear()
{
	m_data->cache.clear();
}

bool ObjectPool::erase( const MurmurHash &hash )
{
	return m_data->cache.erase(hash);
}

void ObjectPool::setMaxMemoryUsage( size_t maxMemory )
{
	m_data->cache.setMaxCost(maxMemory);
}

size_t ObjectPool::getMaxMemoryUsage() const
{
	return m_data->cache.getMaxCost();
}

size_t ObjectPool::memoryUsage() const
{
	return m_data->cache.currentCost();
}

ObjectPoolPtr ObjectPool::defaultObjectPool()
{
	static ObjectPoolPtr c = 0;
	if( !c )
	{
		const char *m = getenv( "IECORE_OBJECTPOOL_MEMORY" );
		size_t mi = m ? boost::lexical_cast<size_t>( m ) : 500;
		c = new ObjectPool(1024 * 1024 * mi);
	}
	return c;
}

/// make sure the default pool is created at load time and avoid
/// running conditions on multi-threaded environments.
static ObjectPoolPtr initializer = ObjectPool::defaultObjectPool();

<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *           Copyright (C) 2008 by the OpenSG Forum                          *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * 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, version 2.                               *
 *                                                                           *
 * 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.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

#include "OSGAttachmentContainer.h"
#include "OSGFieldConnector.h"
#include "OSGConnectorAttachment.h"
#include "OSGNode.h"

OSG_BEGIN_NAMESPACE

/*---------------------------------------------------------------------*/
/*! \name Connection handling                                          */
/*! \{                                                                 */

/*! \ingroup GrpBaseFieldContainerConnector
    \relatesalso AttachmentContainer
 */

bool addConnection(      OSG::AttachmentContainer *pSrcContainer,
                   const OSG::Char8               *szSrcName,
                         OSG::FieldContainer      *pDstContainer,
                   const OSG::Char8               *szDstName    )
{
    if(pSrcContainer == NULL || szSrcName == NULL ||
       pDstContainer == NULL || szDstName == NULL  )
    {
        return false;
    }

    const FieldDescriptionBase *pSrcDesc = NULL;
    const FieldDescriptionBase *pDstDesc = NULL;

    GetFieldHandlePtr pSrcHnd = pSrcContainer->getField(szSrcName);
    GetFieldHandlePtr pDstHnd = pDstContainer->getField(szDstName);

    if(pSrcHnd != NULL && pSrcHnd->isValid() == true)
    {
        pSrcDesc = pSrcHnd->getDescription();
    }

    if(pDstHnd != NULL && pDstHnd->isValid() == true)
    {
        pDstDesc = pDstHnd->getDescription();
    }

    // check core for node
    if(pSrcDesc == NULL)
    {
        Node *pNode = dynamic_cast<Node *>(pSrcContainer);

        if(pNode != NULL && pNode->getCore() != NULL)
        {
            pSrcHnd = pNode->getCore()->getField(szSrcName);

            if(pSrcHnd != NULL && pSrcHnd->isValid() == true)
            {
                pSrcContainer = pNode  ->getCore       ();
                pSrcDesc      = pSrcHnd->getDescription();
            }
        }
    }

    // same here
    if(pDstDesc == NULL)
    {
        Node *pNode = dynamic_cast<Node *>(pDstContainer);

        if(pNode != NULL && pNode->getCore() != NULL)
        {
            pDstHnd = pNode->getCore()->getField(szDstName);

            if(pDstHnd != NULL && pDstHnd->isValid() == true)
            {
                pDstContainer = pNode  ->getCore       ();
                pDstDesc      = pDstHnd->getDescription();
            }
        }
    }

    if(pSrcDesc == NULL || pDstDesc == NULL)
    {
        FWARNING(("addConnection: Failed to obtain field descriptions for "
                  "source container [%p] field [%s] desc [%p] - "
                  "destination container [%p] field [%s] desc [%p]\n",
                  pSrcContainer, szSrcName, pSrcDesc,
                  pDstContainer, szDstName, pDstDesc));

        return false;
    }

    const Field *pSrcField = pSrcHnd->getField();
          Field *pDstField = const_cast<Field *>(pDstHnd->getField());

    if(pSrcContainer == NULL || pDstContainer == NULL)
    {
        FWARNING(("addConnection: Failed to obtain field handles for "
                  "source container [%p] - destination container [%p]\n",
                  pSrcContainer, pDstContainer));

        return false;
    }

    BasicFieldConnector *pConn = pSrcDesc->createConnector(pSrcField,
                                                           pDstDesc,
                                                           pDstField);

    if(pConn != NULL)
    {
        pConn->setTargetContainer(pDstContainer);

        addConnector(pSrcContainer, pConn);
    }

    return true;
}

/*! \ingroup GrpBaseFieldContainerConnector
    \relatesalso AttachmentContainer
 */

bool subConnection(      OSG::AttachmentContainer *pSrcContainer,
                   const OSG::Char8               *szSrcName,
                         OSG::FieldContainer      *pDstContainer,
                   const OSG::Char8               *szDstName    )
{
    if(pSrcContainer == NULL)
    {
        return false;
    }

    const FieldDescriptionBase *pSrcDesc = NULL;

    GetFieldHandlePtr pSrcHnd;

    if(szSrcName != NULL)
    {
        pSrcHnd = pSrcContainer->getField(szSrcName);

        if(pSrcHnd != NULL && pSrcHnd->isValid() == true)
        {
            pSrcDesc = pSrcHnd->getDescription();
        }

        // check core for node
        if(pSrcDesc == NULL)
        {
            Node *pNode = dynamic_cast<Node *>(pSrcContainer);

            if(pNode != NULL && pNode->getCore() != NULL)
            {
                pSrcHnd = pNode->getCore()->getField(szSrcName);

                if(pSrcHnd != NULL && pSrcHnd->isValid() == true)
                {
                    pSrcContainer = pNode  ->getCore       ();
                    pSrcDesc      = pSrcHnd->getDescription();
                }
            }
        }
    }

    const FieldDescriptionBase *pDstDesc = NULL;

    GetFieldHandlePtr pDstHnd;

    if(pDstContainer != NULL && szDstName != NULL)
    {
        pDstHnd = pDstContainer->getField(szDstName);

        if(pDstHnd != NULL && pDstHnd->isValid() == true)
        {
            pDstDesc = pDstHnd->getDescription();
        }

        // same here
        if(pDstDesc == NULL)
        {
            Node *pNode = dynamic_cast<Node *>(pDstContainer);

            if(pNode != NULL && pNode->getCore() != NULL)
            {
                pDstHnd = pNode->getCore()->getField(szDstName);

                if(pDstHnd != NULL && pDstHnd->isValid() == true)
                {
                    pDstContainer = pNode  ->getCore       ();
                    pDstDesc      = pDstHnd->getDescription();
                }
            }
        }
    }

    if(pSrcDesc == NULL)
    {
        FWARNING(("subConnection: Failed to obtain field description for: "
                  "source container [%p] field [%s]\n",
                  pSrcContainer, szSrcName));

        return false;
    }

    BitVector bSrcMask = TypeTraits<BitVector>::BitsClear;
    BitVector bDstMask = TypeTraits<BitVector>::BitsClear;

    if(pSrcDesc != NULL)
    {
        bSrcMask = pSrcDesc->getFieldMask();
    }
    else if(szSrcName == NULL)
    {
        bSrcMask = TypeTraits<BitVector>::BitsSet;
    }

    if(pDstDesc != NULL)
    {
        bDstMask = pDstDesc->getFieldMask();
    }
    else if(szDstName == NULL)
    {
        bDstMask = TypeTraits<BitVector>::BitsSet;
    }

    subConnector(pSrcContainer, bSrcMask,
                 pDstContainer, bDstMask);

    return false;
}

/*! \}                                                                 */
/*---------------------------------------------------------------------*/

OSG_END_NAMESPACE
<commit_msg>fixed: connections to decorated fields<commit_after>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *           Copyright (C) 2008 by the OpenSG Forum                          *
 *                                                                           *
 *                            www.opensg.org                                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * 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, version 2.                               *
 *                                                                           *
 * 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.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

#include "OSGAttachmentContainer.h"
#include "OSGFieldConnector.h"
#include "OSGConnectorAttachment.h"
#include "OSGNode.h"

OSG_BEGIN_NAMESPACE

/*---------------------------------------------------------------------*/
/*! \name Connection handling                                          */
/*! \{                                                                 */

/*! \ingroup GrpBaseFieldContainerConnector
    \relatesalso AttachmentContainer
 */

bool addConnection(      OSG::AttachmentContainer *pSrcContainer,
                   const OSG::Char8               *szSrcName,
                         OSG::FieldContainer      *pDstContainer,
                   const OSG::Char8               *szDstName    )
{
    if(pSrcContainer == NULL || szSrcName == NULL ||
       pDstContainer == NULL || szDstName == NULL  )
    {
        return false;
    }

    const FieldDescriptionBase *pSrcDesc = NULL;
    const FieldDescriptionBase *pDstDesc = NULL;

    GetFieldHandlePtr pSrcHnd = pSrcContainer->getField(szSrcName);
    GetFieldHandlePtr pDstHnd = pDstContainer->getField(szDstName);

    if(pSrcHnd != NULL && pSrcHnd->isValid() == true)
    {
        pSrcDesc = pSrcHnd->getDescription();
    }

    if(pDstHnd != NULL && pDstHnd->isValid() == true)
    {
        pDstDesc = pDstHnd->getDescription();
    }

    // check core for node
    if(pSrcDesc == NULL)
    {
        Node *pNode = dynamic_cast<Node *>(pSrcContainer);

        if(pNode != NULL && pNode->getCore() != NULL)
        {
            pSrcHnd = pNode->getCore()->getField(szSrcName);

            if(pSrcHnd != NULL && pSrcHnd->isValid() == true)
            {
                pSrcDesc = pSrcHnd->getDescription();
            }
        }
    }

    // same here
    if(pDstDesc == NULL)
    {
        Node *pNode = dynamic_cast<Node *>(pDstContainer);

        if(pNode != NULL && pNode->getCore() != NULL)
        {
            pDstHnd = pNode->getCore()->getField(szDstName);

            if(pDstHnd != NULL && pDstHnd->isValid() == true)
            {
                pDstDesc = pDstHnd->getDescription();
            }
        }
    }

    if(pSrcDesc == NULL || pDstDesc == NULL)
    {
        FWARNING(("addConnection: Failed to obtain field descriptions for "
                  "source container [%p] field [%s] desc [%p] - "
                  "destination container [%p] field [%s] desc [%p]\n",
                  pSrcContainer, szSrcName, pSrcDesc,
                  pDstContainer, szDstName, pDstDesc));

        return false;
    }

    const Field *pSrcField = pSrcHnd->getField();
          Field *pDstField = const_cast<Field *>(pDstHnd->getField());

    pSrcContainer =
              dynamic_cast<AttachmentContainer *>(pSrcHnd->getContainer());

    pDstContainer =
              dynamic_cast<AttachmentContainer *>(pDstHnd->getContainer());

    if(pSrcContainer == NULL || pDstContainer == NULL)
    {
        FWARNING(("addConnection: Failed to obtain field handles for "
                  "source container [%p] - destination container [%p]\n",
                  pSrcContainer, pDstContainer));

        return false;
    }

    BasicFieldConnector *pConn = pSrcDesc->createConnector(pSrcField,
                                                           pDstDesc,
                                                           pDstField);

    if(pConn != NULL)
    {
        pConn->setTargetContainer(pDstContainer);

        addConnector(pSrcContainer, pConn);
    }

    return true;
}

/*! \ingroup GrpBaseFieldContainerConnector
    \relatesalso AttachmentContainer
 */

bool subConnection(      OSG::AttachmentContainer *pSrcContainer,
                   const OSG::Char8               *szSrcName,
                         OSG::FieldContainer      *pDstContainer,
                   const OSG::Char8               *szDstName    )
{
    if(pSrcContainer == NULL)
    {
        return false;
    }

    const FieldDescriptionBase *pSrcDesc = NULL;

    GetFieldHandlePtr pSrcHnd;

    if(szSrcName != NULL)
    {
        pSrcHnd = pSrcContainer->getField(szSrcName);

        if(pSrcHnd != NULL && pSrcHnd->isValid() == true)
        {
            pSrcDesc = pSrcHnd->getDescription();
        }

        // check core for node
        if(pSrcDesc == NULL)
        {
            Node *pNode = dynamic_cast<Node *>(pSrcContainer);

            if(pNode != NULL && pNode->getCore() != NULL)
            {
                pSrcHnd = pNode->getCore()->getField(szSrcName);

                if(pSrcHnd != NULL && pSrcHnd->isValid() == true)
                {
                    pSrcDesc = pSrcHnd->getDescription();
                }
            }
        }
    }

    const FieldDescriptionBase *pDstDesc = NULL;

    GetFieldHandlePtr pDstHnd;

    if(pDstContainer != NULL && szDstName != NULL)
    {
        pDstHnd = pDstContainer->getField(szDstName);

        if(pDstHnd != NULL && pDstHnd->isValid() == true)
        {
            pDstDesc = pDstHnd->getDescription();
        }

        // same here
        if(pDstDesc == NULL)
        {
            Node *pNode = dynamic_cast<Node *>(pDstContainer);

            if(pNode != NULL && pNode->getCore() != NULL)
            {
                pDstHnd = pNode->getCore()->getField(szDstName);

                if(pDstHnd != NULL && pDstHnd->isValid() == true)
                {
                    pDstDesc = pDstHnd->getDescription();
                }
            }
        }
    }

#if 0
    if(pSrcDesc == NULL)
    {
        FWARNING(("subConnection: Failed to obtain field description for: "
                  "source container [%p] field [%s]\n",
                  pSrcContainer, szSrcName));

        return false;
    }
#endif

    BitVector bSrcMask = TypeTraits<BitVector>::BitsClear;
    BitVector bDstMask = TypeTraits<BitVector>::BitsClear;

    if(pSrcDesc != NULL)
    {
        bSrcMask = pSrcDesc->getFieldMask();

        pSrcContainer =
            dynamic_cast<AttachmentContainer *>(pSrcHnd->getContainer());
    }
    else if(szSrcName == NULL)
    {
        bSrcMask = TypeTraits<BitVector>::BitsSet;
    }

    if(pDstDesc != NULL)
    {
        bDstMask = pDstDesc->getFieldMask();

        pDstContainer =
            dynamic_cast<AttachmentContainer *>(pDstHnd->getContainer());
    }
    else if(szDstName == NULL)
    {
        bDstMask = TypeTraits<BitVector>::BitsSet;
    }

    subConnector(pSrcContainer, bSrcMask,
                 pDstContainer, bDstMask);

    return false;
}

/*! \}                                                                 */
/*---------------------------------------------------------------------*/

OSG_END_NAMESPACE
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: mapnik_python.cc 27 2005-03-30 21:45:40Z pavlenko $

#include <boost/python.hpp>
#include <boost/get_pointer.hpp>
#include <boost/python/detail/api_placeholder.hpp>

void export_color();
void export_layer();
void export_parameters();
void export_envelope();
void export_query();
void export_image();
void export_map();
void export_python();
void export_filter();
void export_rule();
void export_style();
void export_stroke();
void export_datasource_cache();
void export_point_symbolizer();
void export_line_symbolizer();
void export_line_pattern_symbolizer();
void export_polygon_symbolizer();
void export_polygon_pattern_symbolizer();
void export_raster_symbolizer();
void export_text_symbolizer();
void export_font_engine();

#include <mapnik/map.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/save_map.hpp>

void render_to_file(const mapnik::Map& map,
                    const std::string& file,
                    const std::string& format)
{
    mapnik::Image32 image(map.getWidth(),map.getHeight());
    mapnik::agg_renderer<mapnik::Image32> ren(map,image);
    ren.apply();
    image.saveToFile(file,format);
}

void render(const mapnik::Map& map,mapnik::Image32& image)
{
    mapnik::agg_renderer<mapnik::Image32> ren(map,image);
    ren.apply();
}

namespace
{
    //user-friendly wrapper that uses Python dictionary
    using namespace boost::python;
    boost::shared_ptr<mapnik::datasource> create_datasource(const dict& d)
    {
        mapnik::parameters params;
        boost::python::list keys=d.keys();
        for (int i=0; i<len(keys); ++i)
        {
            std::string key=extract<std::string>(keys[i]);
            std::string value=extract<std::string>(d[key]);
            params[key] = value;
        }

        return mapnik::datasource_cache::create(params);
    }
}

BOOST_PYTHON_MODULE(_mapnik)
{
    using namespace boost::python;
    using mapnik::Featureset;
    using mapnik::featureset_ptr;
    using mapnik::datasource;
    using mapnik::coord;
    using mapnik::filter_ptr;
    using mapnik::load_map;
    using mapnik::save_map;

    export_query();

    class_<Featureset,featureset_ptr,boost::noncopyable>("FeatureSet",no_init)
      ;

    class_<datasource,boost::shared_ptr<datasource>,
        boost::noncopyable>("Datasource",no_init)
        .def("envelope",&datasource::envelope,
             return_value_policy<reference_existing_object>())
        .def("features",&datasource::features)
        .def("params",&datasource::params,return_value_policy<reference_existing_object>(),
             "The configuration parameters of the data source. "
             "These vary depending on the type of data source.")
        ;

    def("CreateDatasource",&create_datasource);

    export_parameters();
    export_color();
    export_envelope();
    export_image();
    export_filter();
    export_rule();
    export_style();
    export_layer();
    export_stroke();
    export_datasource_cache();
    export_point_symbolizer();
    export_line_symbolizer();
    export_line_pattern_symbolizer();
    export_polygon_symbolizer();
    export_polygon_pattern_symbolizer();
    export_raster_symbolizer();
    export_text_symbolizer();
    export_font_engine();

    class_<coord<double,2> >("Coord",init<double,double>())
        .def_readwrite("x", &coord<double,2>::x)
        .def_readwrite("y", &coord<double,2>::y)
        ;

    export_map();

    def("render_to_file",&render_to_file);
    def("render",&render);

    def("load_map",&load_map,"load Map object from XML");
    def("save_map",&load_map,"sace Map object to XML");

    register_ptr_to_python<filter_ptr>();
}
<commit_msg>check if can extract std::string from dict.<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: mapnik_python.cc 27 2005-03-30 21:45:40Z pavlenko $

#include <boost/python.hpp>
#include <boost/get_pointer.hpp>
#include <boost/python/detail/api_placeholder.hpp>

void export_color();
void export_layer();
void export_parameters();
void export_envelope();
void export_query();
void export_image();
void export_map();
void export_python();
void export_filter();
void export_rule();
void export_style();
void export_stroke();
void export_datasource_cache();
void export_point_symbolizer();
void export_line_symbolizer();
void export_line_pattern_symbolizer();
void export_polygon_symbolizer();
void export_polygon_pattern_symbolizer();
void export_raster_symbolizer();
void export_text_symbolizer();
void export_font_engine();

#include <mapnik/map.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/save_map.hpp>

void render_to_file(const mapnik::Map& map,
                    const std::string& file,
                    const std::string& format)
{
    mapnik::Image32 image(map.getWidth(),map.getHeight());
    mapnik::agg_renderer<mapnik::Image32> ren(map,image);
    ren.apply();
    image.saveToFile(file,format);
}

void render(const mapnik::Map& map,mapnik::Image32& image)
{
    mapnik::agg_renderer<mapnik::Image32> ren(map,image);
    ren.apply();
}

namespace
{
    //user-friendly wrapper that uses Python dictionary
    using namespace boost::python;
    boost::shared_ptr<mapnik::datasource> create_datasource(const dict& d)
    {
        mapnik::parameters params;
        boost::python::list keys=d.keys();
        for (int i=0; i<len(keys); ++i)
        {
            std::string key = extract<std::string>(keys[i]);
            object obj = d[key];
            extract<std::string> ex(obj);
            if (ex.check())
            {
                params[key] = ex();
            }
        }

        return mapnik::datasource_cache::create(params);
    }
}

BOOST_PYTHON_MODULE(_mapnik)
{
    using namespace boost::python;
    using mapnik::Featureset;
    using mapnik::featureset_ptr;
    using mapnik::datasource;
    using mapnik::coord;
    using mapnik::filter_ptr;
    using mapnik::load_map;
    using mapnik::save_map;

    export_query();

    class_<Featureset,featureset_ptr,boost::noncopyable>("FeatureSet",no_init)
      ;

    class_<datasource,boost::shared_ptr<datasource>,
        boost::noncopyable>("Datasource",no_init)
        .def("envelope",&datasource::envelope,
             return_value_policy<reference_existing_object>())
        .def("features",&datasource::features)
        .def("params",&datasource::params,return_value_policy<reference_existing_object>(),
             "The configuration parameters of the data source. "
             "These vary depending on the type of data source.")
        ;

    def("CreateDatasource",&create_datasource);

    export_parameters();
    export_color();
    export_envelope();
    export_image();
    export_filter();
    export_rule();
    export_style();
    export_layer();
    export_stroke();
    export_datasource_cache();
    export_point_symbolizer();
    export_line_symbolizer();
    export_line_pattern_symbolizer();
    export_polygon_symbolizer();
    export_polygon_pattern_symbolizer();
    export_raster_symbolizer();
    export_text_symbolizer();
    export_font_engine();

    class_<coord<double,2> >("Coord",init<double,double>())
        .def_readwrite("x", &coord<double,2>::x)
        .def_readwrite("y", &coord<double,2>::y)
        ;

    export_map();

    def("render_to_file",&render_to_file);
    def("render",&render);

    def("load_map",&load_map,"load Map object from XML");
    def("save_map",&load_map,"sace Map object to XML");

    register_ptr_to_python<filter_ptr>();
}
<|endoftext|>