<commit_before>#include <stdlib.h>
#include <pthread.h>

#include "NanoWinEvents.h"
#include "NanoWinError.h"
#include "NanoWinWaitableTimer.h"

typedef struct
{
  LONG       milsTimeout;
  LONG       milsDue;
  pthread_t  wtThread;
  HANDLE     eventHandle;
  HANDLE     interEventHandle;
  bool       exitFlag;
} NanoWinWaitableTimer;

extern HANDLE WINAPI CreateWaitableTimerA     (LPSECURITY_ATTRIBUTES lpTimerAttributes,
                                               BOOL                  bManualReset,
                                               LPCSTR                lpTimerName)
{
  HANDLE result = NULL;

  if (lpTimerAttributes != NULL) // not supported
  {
    NanoWinSetLastError(ERROR_NOT_SUPPORTED);

    return NULL;
  }

  if (lpTimerName != NULL) // not supported
  {
    NanoWinSetLastError(ERROR_NOT_SUPPORTED);

    return NULL;
  }

  NanoWinWaitableTimer *waitableTimer = (NanoWinWaitableTimer*)malloc(sizeof(NanoWinWaitableTimer));

  if (waitableTimer != NULL)
  {
    waitableTimer->wtThread    = NULL;
    waitableTimer->milsTimeout = 200;
    waitableTimer->exitFlag    = false;

    waitableTimer->eventHandle = CreateEventA(NULL, bManualReset, FALSE, NULL);

    if (waitableTimer->eventHandle != NULL)
    {
      waitableTimer->interEventHandle = CreateEventA(NULL, FALSE, TRUE, NULL);

      if (waitableTimer->interEventHandle != NULL)
      {
        result = (HANDLE)waitableTimer;
      }
      else
      {
        CloseEventHandle(waitableTimer->eventHandle);
      }
    }

    if (result == NULL)
    {
      free(waitableTimer);
    }
  }
  else
  {
    NanoWinSetLastError(ERROR_NOT_ENOUGH_MEMORY);
  }

  return result;
}

extern HANDLE WINAPI CreateWaitableTimerW     (LPSECURITY_ATTRIBUTES lpTimerAttributes,
                                               BOOL                  bManualReset,
                                               LPCWSTR               lpTimerName)
{
  if (lpTimerName != NULL) // not supported
  {
    NanoWinSetLastError(ERROR_NOT_SUPPORTED);

    return NULL;
  }

  return CreateWaitableTimerA(lpTimerAttributes,bManualReset,NULL);
}

static void *WaitableTimerThreadRoutine (void *paramPtr) throw ()
{
  NanoWinWaitableTimer *waitableTimer = (NanoWinWaitableTimer*)paramPtr;
  DWORD waitMils = waitableTimer->milsDue;

  //ENABLING THE CANCEL FUNCTIONALITY
  int prevType;

  #ifndef __ANDROID_API__
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &prevType);
  #endif

  while (!waitableTimer->exitFlag)
  {
    DWORD res = WaitForSingleEvent(waitableTimer->interEventHandle, waitMils);
    waitMils = waitableTimer->milsTimeout;

    ResetEvent(waitableTimer->interEventHandle);

    if (waitableTimer->exitFlag)
    {
      break;
    }
    else if ((res == WAIT_TIMEOUT) || (res == WAIT_OBJECT_0))
    {
      SetEvent(waitableTimer->eventHandle);
    }
    else // error
    {
       break;
    }
  }

  return NULL;
}

extern BOOL WINAPI   SetWaitableTimer         (HANDLE                hTimer,
                                               const LARGE_INTEGER  *pDueTime,
                                               LONG                  lPeriod,
                                               PTIMERAPCROUTINE      pfnCompletionRoutine,
                                               LPVOID                lpArgToCompletionRoutine,
                                               BOOL                  fResume)
{
  if (((pDueTime != NULL) &&  (pDueTime->QuadPart > 0L)) || // absolute utc time not supported yet
      pfnCompletionRoutine != NULL     ||
      lpArgToCompletionRoutine != NULL ||
      fResume) // not supported
  {
    NanoWinSetLastError(ERROR_NOT_SUPPORTED);

    return FALSE;
  }

  NanoWinWaitableTimer *waitableTimer = (NanoWinWaitableTimer*)hTimer;

  if (pDueTime != NULL)
  {
    waitableTimer->milsDue = -(pDueTime->QuadPart) / 10000;
  }
  else
  {
    waitableTimer->milsDue = lPeriod;
  }

  waitableTimer->milsTimeout = lPeriod;

  if (waitableTimer->wtThread != NULL)
  {
    SetEvent(waitableTimer->interEventHandle);
  }
  else
  {
    int res = pthread_create(&waitableTimer->wtThread, NULL, WaitableTimerThreadRoutine, waitableTimer);

    if (res != 0)
    {
      NanoWinSetLastError(NanoWinErrorByErrnoAtFail(res));

      return FALSE;
    }
  }

  return TRUE;
}

extern BOOL WINAPI   CloseWaitableTimerHandle (HANDLE                hObject)
{
  if (hObject == NULL)
  {
    return TRUE;
  }

  NanoWinWaitableTimer *waitableTimer = (NanoWinWaitableTimer*)hObject;

  if (waitableTimer->wtThread != NULL)
  {
    waitableTimer->exitFlag = true;
    #ifdef WAITABLE_TIMER_CANCELABLE  // if defined appearing "no rethrow" exception (compiler dependent)
    pthread_cancel(waitableTimer->wtThread);
    pthread_join(waitableTimer->wtThread, NULL); // Future idea?
    #else // stable version
    SetEvent(waitableTimer->interEventHandle);
    pthread_join(waitableTimer->wtThread, NULL);
    #endif
    waitableTimer->wtThread = NULL;
  }

  if (waitableTimer->eventHandle != NULL)
  {
     CloseEventHandle(waitableTimer->eventHandle);
     waitableTimer->eventHandle = NULL;
  }

  if (waitableTimer->interEventHandle != NULL)
  {
     CloseEventHandle(waitableTimer->interEventHandle);
     waitableTimer->interEventHandle = NULL;
  }

  free(waitableTimer);

  return TRUE;
}

//NOTE: this function is NanoWin-specific and does not exist in WinAPI
extern HANDLE        GetEventByWaitableTimer  (HANDLE                hTimer)
{
  return ((NanoWinWaitableTimer*)hTimer)->eventHandle;
}

<commit_msg>Cosmetic: Fixed compilation warning in waitable timer implementation<commit_after>#include <stdlib.h>
#include <pthread.h>

#include "NanoWinEvents.h"
#include "NanoWinError.h"
#include "NanoWinWaitableTimer.h"

typedef struct
{
  LONG       milsTimeout;
  LONG       milsDue;
  pthread_t  wtThread;
  HANDLE     eventHandle;
  HANDLE     interEventHandle;
  bool       exitFlag;
} NanoWinWaitableTimer;

#define PTHREAD_T_NULL ((pthread_t)(NULL))    // NULL value for pthread_t

extern HANDLE WINAPI CreateWaitableTimerA     (LPSECURITY_ATTRIBUTES lpTimerAttributes,
                                               BOOL                  bManualReset,
                                               LPCSTR                lpTimerName)
{
  HANDLE result = NULL;

  if (lpTimerAttributes != NULL) // not supported
  {
    NanoWinSetLastError(ERROR_NOT_SUPPORTED);

    return NULL;
  }

  if (lpTimerName != NULL) // not supported
  {
    NanoWinSetLastError(ERROR_NOT_SUPPORTED);

    return NULL;
  }

  NanoWinWaitableTimer *waitableTimer = (NanoWinWaitableTimer*)malloc(sizeof(NanoWinWaitableTimer));

  if (waitableTimer != NULL)
  {
    waitableTimer->wtThread    = PTHREAD_T_NULL;
    waitableTimer->milsTimeout = 200;
    waitableTimer->exitFlag    = false;

    waitableTimer->eventHandle = CreateEventA(NULL, bManualReset, FALSE, NULL);

    if (waitableTimer->eventHandle != NULL)
    {
      waitableTimer->interEventHandle = CreateEventA(NULL, FALSE, TRUE, NULL);

      if (waitableTimer->interEventHandle != NULL)
      {
        result = (HANDLE)waitableTimer;
      }
      else
      {
        CloseEventHandle(waitableTimer->eventHandle);
      }
    }

    if (result == NULL)
    {
      free(waitableTimer);
    }
  }
  else
  {
    NanoWinSetLastError(ERROR_NOT_ENOUGH_MEMORY);
  }

  return result;
}

extern HANDLE WINAPI CreateWaitableTimerW     (LPSECURITY_ATTRIBUTES lpTimerAttributes,
                                               BOOL                  bManualReset,
                                               LPCWSTR               lpTimerName)
{
  if (lpTimerName != NULL) // not supported
  {
    NanoWinSetLastError(ERROR_NOT_SUPPORTED);

    return NULL;
  }

  return CreateWaitableTimerA(lpTimerAttributes,bManualReset,NULL);
}

static void *WaitableTimerThreadRoutine (void *paramPtr) throw ()
{
  NanoWinWaitableTimer *waitableTimer = (NanoWinWaitableTimer*)paramPtr;
  DWORD waitMils = waitableTimer->milsDue;

  //ENABLING THE CANCEL FUNCTIONALITY
  int prevType;

  #ifndef __ANDROID_API__
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &prevType);
  #endif

  while (!waitableTimer->exitFlag)
  {
    DWORD res = WaitForSingleEvent(waitableTimer->interEventHandle, waitMils);
    waitMils = waitableTimer->milsTimeout;

    ResetEvent(waitableTimer->interEventHandle);

    if (waitableTimer->exitFlag)
    {
      break;
    }
    else if ((res == WAIT_TIMEOUT) || (res == WAIT_OBJECT_0))
    {
      SetEvent(waitableTimer->eventHandle);
    }
    else // error
    {
       break;
    }
  }

  return NULL;
}

extern BOOL WINAPI   SetWaitableTimer         (HANDLE                hTimer,
                                               const LARGE_INTEGER  *pDueTime,
                                               LONG                  lPeriod,
                                               PTIMERAPCROUTINE      pfnCompletionRoutine,
                                               LPVOID                lpArgToCompletionRoutine,
                                               BOOL                  fResume)
{
  if (((pDueTime != NULL) &&  (pDueTime->QuadPart > 0L)) || // absolute utc time not supported yet
      pfnCompletionRoutine != NULL     ||
      lpArgToCompletionRoutine != NULL ||
      fResume) // not supported
  {
    NanoWinSetLastError(ERROR_NOT_SUPPORTED);

    return FALSE;
  }

  NanoWinWaitableTimer *waitableTimer = (NanoWinWaitableTimer*)hTimer;

  if (pDueTime != NULL)
  {
    waitableTimer->milsDue = -(pDueTime->QuadPart) / 10000;
  }
  else
  {
    waitableTimer->milsDue = lPeriod;
  }

  waitableTimer->milsTimeout = lPeriod;

  if (waitableTimer->wtThread != PTHREAD_T_NULL)
  {
    SetEvent(waitableTimer->interEventHandle);
  }
  else
  {
    int res = pthread_create(&waitableTimer->wtThread, NULL, WaitableTimerThreadRoutine, waitableTimer);

    if (res != 0)
    {
      NanoWinSetLastError(NanoWinErrorByErrnoAtFail(res));

      return FALSE;
    }
  }

  return TRUE;
}

extern BOOL WINAPI   CloseWaitableTimerHandle (HANDLE                hObject)
{
  if (hObject == NULL)
  {
    return TRUE;
  }

  NanoWinWaitableTimer *waitableTimer = (NanoWinWaitableTimer*)hObject;

  if (waitableTimer->wtThread != PTHREAD_T_NULL)
  {
    waitableTimer->exitFlag = true;
    #ifdef WAITABLE_TIMER_CANCELABLE  // if defined appearing "no rethrow" exception (compiler dependent)
    pthread_cancel(waitableTimer->wtThread);
    pthread_join(waitableTimer->wtThread, NULL); // Future idea?
    #else // stable version
    SetEvent(waitableTimer->interEventHandle);
    pthread_join(waitableTimer->wtThread, NULL);
    #endif
    waitableTimer->wtThread = PTHREAD_T_NULL;
  }

  if (waitableTimer->eventHandle != NULL)
  {
     CloseEventHandle(waitableTimer->eventHandle);
     waitableTimer->eventHandle = NULL;
  }

  if (waitableTimer->interEventHandle != NULL)
  {
     CloseEventHandle(waitableTimer->interEventHandle);
     waitableTimer->interEventHandle = NULL;
  }

  free(waitableTimer);

  return TRUE;
}

//NOTE: this function is NanoWin-specific and does not exist in WinAPI
extern HANDLE        GetEventByWaitableTimer  (HANDLE                hTimer)
{
  return ((NanoWinWaitableTimer*)hTimer)->eventHandle;
}

<|endoftext|>


<commit_before>/**
	This software was developed by the University of Tennessee as part of the
	Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
	project funded by the US National Science Foundation.

	If you use DANSE applications to do scientific research that leads to
	publication, we ask that you acknowledge the use of the software with the
	following sentence:

	"This work benefited from DANSE software developed under NSF award DMR-0520547."

	copyright 2008, University of Tennessee
 */

/**
 * Scattering model classes
 * The classes use the IGOR library found in
 *   sansmodels/src/libigor
 *
 *	TODO: refactor so that we pull in the old sansmodels.c_extensions
 *	TODO: add 2d
 */

#include <math.h>
#include "parameters.hh"
#include <stdio.h>
using namespace std;
#include "stacked_disks.h"

extern "C" {
#include "libCylinder.h"
#include "libStructureFactor.h"
}

typedef struct {
  double scale;
  double radius;
  double core_thick;
  double layer_thick;
  double core_sld;
  double layer_sld;
  double solvent_sld;
  double n_stacking;
  double sigma_d;
  double background;
  double axis_theta;
  double axis_phi;
} StackedDisksParameters;

/**
 * Function to evaluate 2D scattering function
 * @param pars: parameters of the staked disks
 * @param q: q-value
 * @param q_x: q_x / q
 * @param q_y: q_y / q
 * @return: function value
 */
static double stacked_disks_analytical_2D_scaled(StackedDisksParameters *pars, double q, double q_x, double q_y) {
  double cyl_x, cyl_y, cyl_z;
  double q_z;
  double alpha, vol, cos_val;
  double d, dum, halfheight;
  double answer;

  // parallelepiped orientation
  cyl_x = sin(pars->axis_theta) * cos(pars->axis_phi);
  cyl_y = sin(pars->axis_theta) * sin(pars->axis_phi);
  cyl_z = cos(pars->axis_theta);

  // q vector
  q_z = 0;

  // Compute the angle btw vector q and the
  // axis of the parallelepiped
  cos_val = cyl_x*q_x + cyl_y*q_y + cyl_z*q_z;

  // The following test should always pass
  if (fabs(cos_val)>1.0) {
    printf("parallel_ana_2D: Unexpected error: cos(alpha)>1\n");
    return 0;
  }

  // Note: cos(alpha) = 0 and 1 will get an
  // undefined value from Stackdisc_kern
  alpha = acos( cos_val );

  // Call the IGOR library function to get the kernel
  d = 2 * pars->layer_thick + pars->core_thick;
  halfheight = pars->core_thick/2.0;
  dum =alpha ;
  answer = Stackdisc_kern(q, pars->radius, pars->core_sld,pars->layer_sld,
      pars->solvent_sld, halfheight, pars->layer_thick, dum, pars->sigma_d, d, pars->n_stacking)/sin(alpha);

  // Multiply by contrast^2
  //answer *= pars->contrast*pars->contrast;

  //normalize by staked disks volume
  vol = acos(-1.0) * pars->radius * pars->radius * d * pars->n_stacking;
  answer /= vol;

  //convert to [cm-1]
  answer *= 1.0e8;

  //Scale
  answer *= pars->scale;

  // add in the background
  answer += pars->background;

  return answer;
}

/**
 * Function to evaluate 2D scattering function
 * @param pars: parameters of the staked disks
 * @param q: q-value
 * @return: function value
 */
static double stacked_disks_analytical_2DXY(StackedDisksParameters *pars, double qx, double qy) {
  double q;
  q = sqrt(qx*qx+qy*qy);
  return stacked_disks_analytical_2D_scaled(pars, q, qx/q, qy/q);
}

StackedDisksModel :: StackedDisksModel() {
  scale      = Parameter(1.0);
  radius     = Parameter(3000.0, true);
  radius.set_min(0.0);
  core_thick  = Parameter(10.0, true);
  core_thick.set_min(0.0);
  layer_thick     = Parameter(15.0);
  layer_thick.set_min(0.0);
  core_sld = Parameter(4.0e-6);
  layer_sld  = Parameter(-4.0e-7);
  solvent_sld  = Parameter(5.0e-6);
  n_stacking   = Parameter(1);
  sigma_d   = Parameter(0);
  background = Parameter(0.001);
  axis_theta  = Parameter(0.0, true);
  axis_phi    = Parameter(0.0, true);
}

/**
 * Function to evaluate 1D scattering function
 * The NIST IGOR library is used for the actual calculation.
 * @param q: q-value
 * @return: function value
 */
double StackedDisksModel :: operator()(double q) {
  double dp[10];

  // Fill parameter array for IGOR library
  // Add the background after averaging
  dp[0] = scale();
  dp[1] = radius();
  dp[2] = core_thick();
  dp[3] = layer_thick();
  dp[4] = core_sld();
  dp[5] = layer_sld();
  dp[6] = solvent_sld();
  dp[7] = n_stacking();
  dp[8] = sigma_d();
  dp[9] = 0.0;

  // Get the dispersion points for the radius
  vector<WeightPoint> weights_radius;
  radius.get_weights(weights_radius);

  // Get the dispersion points for the core_thick
  vector<WeightPoint> weights_core_thick;
  core_thick.get_weights(weights_core_thick);

  // Get the dispersion points for the layer_thick
  vector<WeightPoint> weights_layer_thick;
  layer_thick.get_weights(weights_layer_thick);

  // Perform the computation, with all weight points
  double sum = 0.0;
  double norm = 0.0;
  double vol = 0.0;

  // Loop over length weight points
  for(int i=0; i< (int)weights_radius.size(); i++) {
    dp[1] = weights_radius[i].value;

    // Loop over radius weight points
    for(int j=0; j< (int)weights_core_thick.size(); j++) {
      dp[2] = weights_core_thick[j].value;

      // Loop over thickness weight points
      for(int k=0; k< (int)weights_layer_thick.size(); k++) {
        dp[3] = weights_layer_thick[k].value;
        //Un-normalize by volume
        sum += weights_radius[i].weight
            * weights_core_thick[j].weight * weights_layer_thick[k].weight* StackedDiscs(dp, q)
        *pow(weights_radius[i].value,2)*(weights_core_thick[j].value+2*weights_layer_thick[k].value);
        //Find average volume
        vol += weights_radius[i].weight
            * weights_core_thick[j].weight * weights_layer_thick[k].weight
            *pow(weights_radius[i].value,2)*(weights_core_thick[j].value+2*weights_layer_thick[k].value);
        norm += weights_radius[i].weight
            * weights_core_thick[j].weight* weights_layer_thick[k].weight;
      }
    }
  }
  if (vol != 0.0 && norm != 0.0) {
    //Re-normalize by avg volume
    sum = sum/(vol/norm);}

  return sum/norm + background();
}

/**
 * Function to evaluate 2D scattering function
 * @param q_x: value of Q along x
 * @param q_y: value of Q along y
 * @return: function value
 */
double StackedDisksModel :: operator()(double qx, double qy) {
  StackedDisksParameters dp;
  // Fill parameter array
  dp.scale      = scale();
  dp.core_thick    = core_thick();
  dp.radius	  = radius();
  dp.layer_thick  = layer_thick();
  dp.core_sld   = core_sld();
  dp.layer_sld  = layer_sld();
  dp.solvent_sld= solvent_sld();
  dp.n_stacking	  = n_stacking();
  dp.sigma_d   = sigma_d();
  dp.background = 0.0;
  dp.axis_theta = axis_theta();
  dp.axis_phi   = axis_phi();

  // Get the dispersion points for the length
  vector<WeightPoint> weights_core_thick;
  core_thick.get_weights(weights_core_thick);

  // Get the dispersion points for the radius
  vector<WeightPoint> weights_radius;
  radius.get_weights(weights_radius);

  // Get the dispersion points for the thickness
  vector<WeightPoint> weights_layer_thick;
  layer_thick.get_weights(weights_layer_thick);

  // Get angular averaging for theta
  vector<WeightPoint> weights_theta;
  axis_theta.get_weights(weights_theta);

  // Get angular averaging for phi
  vector<WeightPoint> weights_phi;
  axis_phi.get_weights(weights_phi);

  // Perform the computation, with all weight points
  double sum = 0.0;
  double norm = 0.0;
  double norm_vol = 0.0;
  double vol = 0.0;

  // Loop over length weight points
  for(int i=0; i< (int)weights_core_thick.size(); i++) {
    dp.core_thick = weights_core_thick[i].value;

    // Loop over radius weight points
    for(int j=0; j< (int)weights_radius.size(); j++) {
      dp.radius = weights_radius[j].value;

      // Loop over thickness weight points
      for(int k=0; k< (int)weights_layer_thick.size(); k++) {
        dp.layer_thick = weights_layer_thick[k].value;

        for(int l=0; l< (int)weights_theta.size(); l++) {
          dp.axis_theta = weights_theta[l].value;

          // Average over phi distribution
          for(int m=0; m <(int)weights_phi.size(); m++) {
            dp.axis_phi = weights_phi[m].value;

            //Un-normalize by volume
            double _ptvalue = weights_core_thick[i].weight
                * weights_radius[j].weight
                * weights_layer_thick[k].weight
                * weights_theta[l].weight
                * weights_phi[m].weight
                * stacked_disks_analytical_2DXY(&dp, qx, qy)
            *pow(weights_radius[j].value,2)*(weights_core_thick[i].value+2*weights_layer_thick[k].value);
            if (weights_theta.size()>1) {
              _ptvalue *= fabs(sin(weights_theta[l].value));
            }
            sum += _ptvalue;
            //Find average volume
            vol += weights_radius[j].weight
                * weights_core_thick[i].weight * weights_layer_thick[k].weight
                *pow(weights_radius[j].value,2)*(weights_core_thick[i].value+2*weights_layer_thick[k].value);
            //Find norm for volume
            norm_vol += weights_radius[j].weight
                * weights_core_thick[i].weight * weights_layer_thick[k].weight;

            norm += weights_core_thick[i].weight
                * weights_radius[j].weight
                * weights_layer_thick[k].weight
                * weights_theta[l].weight
                * weights_phi[m].weight;
          }
        }
      }
    }
  }
  // Averaging in theta needs an extra normalization
  // factor to account for the sin(theta) term in the
  // integration (see documentation).
  if (weights_theta.size()>1) norm = norm / asin(1.0);
  if (vol != 0.0 && norm_vol != 0.0) {
    //Re-normalize by avg volume
    sum = sum/(vol/norm_vol);}
  return sum/norm + background();
}

/**
 * Function to evaluate 2D scattering function
 * @param pars: parameters of the triaxial ellipsoid
 * @param q: q-value
 * @param phi: angle phi
 * @return: function value
 */
double StackedDisksModel :: evaluate_rphi(double q, double phi) {
  double qx = q*cos(phi);
  double qy = q*sin(phi);
  return (*this).operator()(qx, qy);
}
/**
 * Function to calculate effective radius
 * @return: effective radius value
 */
double StackedDisksModel :: calculate_ER() {
  StackedDisksParameters dp;

  dp.core_thick    = core_thick();
  dp.radius	  = radius();
  dp.layer_thick  = layer_thick();
  dp.n_stacking	  = n_stacking();

  double rad_out = 0.0;
  if (dp.n_stacking <= 0.0){
    return rad_out;
  }

  // Perform the computation, with all weight points
  double sum = 0.0;
  double norm = 0.0;

  // Get the dispersion points for the length
  vector<WeightPoint> weights_core_thick;
  core_thick.get_weights(weights_core_thick);

  // Get the dispersion points for the radius
  vector<WeightPoint> weights_radius;
  radius.get_weights(weights_radius);

  // Get the dispersion points for the thickness
  vector<WeightPoint> weights_layer_thick;
  layer_thick.get_weights(weights_layer_thick);

  // Loop over major shell weight points
  for(int i=0; i< (int)weights_core_thick.size(); i++) {
    dp.core_thick = weights_core_thick[i].value;
    for(int j=0; j< (int)weights_layer_thick.size(); j++) {
      dp.layer_thick = weights_layer_thick[j].value;
      for(int k=0; k< (int)weights_radius.size(); k++) {
        dp.radius = weights_radius[k].value;
        //Note: output of "DiamCyl(dp.length,dp.radius)" is DIAMETER.
        sum +=weights_core_thick[i].weight*weights_layer_thick[j].weight
            * weights_radius[k].weight*DiamCyl(dp.n_stacking*(dp.layer_thick*2.0+dp.core_thick),dp.radius)/2.0;
        norm += weights_core_thick[i].weight*weights_layer_thick[j].weight* weights_radius[k].weight;
      }
    }
  }
  if (norm != 0){
    //return the averaged value
    rad_out =  sum/norm;}
  else{
    //return normal value
    //Note: output of "DiamCyl(dp.length,dp.radius)" is DIAMETER.
    rad_out = DiamCyl(dp.n_stacking*(dp.layer_thick*2.0+dp.core_thick),dp.radius)/2.0;}

  return rad_out;
}
double StackedDisksModel :: calculate_VR() {
  return 1.0;
}
<commit_msg>stackeddisc: 2d angle unit problem fixed<commit_after>/**
	This software was developed by the University of Tennessee as part of the
	Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
	project funded by the US National Science Foundation.

	If you use DANSE applications to do scientific research that leads to
	publication, we ask that you acknowledge the use of the software with the
	following sentence:

	"This work benefited from DANSE software developed under NSF award DMR-0520547."

	copyright 2008, University of Tennessee
 */

/**
 * Scattering model classes
 * The classes use the IGOR library found in
 *   sansmodels/src/libigor
 *
 *	TODO: refactor so that we pull in the old sansmodels.c_extensions
 *	TODO: add 2d
 */

#include <math.h>
#include "parameters.hh"
#include <stdio.h>
using namespace std;
#include "stacked_disks.h"

extern "C" {
#include "libCylinder.h"
#include "libStructureFactor.h"
}

typedef struct {
  double scale;
  double radius;
  double core_thick;
  double layer_thick;
  double core_sld;
  double layer_sld;
  double solvent_sld;
  double n_stacking;
  double sigma_d;
  double background;
  double axis_theta;
  double axis_phi;
} StackedDisksParameters;

/**
 * Function to evaluate 2D scattering function
 * @param pars: parameters of the staked disks
 * @param q: q-value
 * @param q_x: q_x / q
 * @param q_y: q_y / q
 * @return: function value
 */
static double stacked_disks_analytical_2D_scaled(StackedDisksParameters *pars, double q, double q_x, double q_y) {
  double cyl_x, cyl_y, cyl_z;
  double q_z;
  double alpha, vol, cos_val;
  double d, dum, halfheight;
  double answer;
  double theta = pars->axis_theta * pi/180.0;
  double phi = pars->axis_phi * pi/180.0;

  // parallelepiped orientation
  cyl_x = sin(theta) * cos(phi);
  cyl_y = sin(theta) * sin(phi);
  cyl_z = cos(theta);

  // q vector
  q_z = 0;

  // Compute the angle btw vector q and the
  // axis of the parallelepiped
  cos_val = cyl_x*q_x + cyl_y*q_y + cyl_z*q_z;

  // The following test should always pass
  if (fabs(cos_val)>1.0) {
    printf("parallel_ana_2D: Unexpected error: cos(alpha)>1\n");
    return 0;
  }

  // Note: cos(alpha) = 0 and 1 will get an
  // undefined value from Stackdisc_kern
  alpha = acos( cos_val );

  // Call the IGOR library function to get the kernel
  d = 2 * pars->layer_thick + pars->core_thick;
  halfheight = pars->core_thick/2.0;
  dum =alpha ;
  answer = Stackdisc_kern(q, pars->radius, pars->core_sld,pars->layer_sld,
      pars->solvent_sld, halfheight, pars->layer_thick, dum, pars->sigma_d, d, pars->n_stacking)/sin(alpha);

  // Multiply by contrast^2
  //answer *= pars->contrast*pars->contrast;

  //normalize by staked disks volume
  vol = acos(-1.0) * pars->radius * pars->radius * d * pars->n_stacking;
  answer /= vol;

  //convert to [cm-1]
  answer *= 1.0e8;

  //Scale
  answer *= pars->scale;

  // add in the background
  answer += pars->background;

  return answer;
}

/**
 * Function to evaluate 2D scattering function
 * @param pars: parameters of the staked disks
 * @param q: q-value
 * @return: function value
 */
static double stacked_disks_analytical_2DXY(StackedDisksParameters *pars, double qx, double qy) {
  double q;
  q = sqrt(qx*qx+qy*qy);
  return stacked_disks_analytical_2D_scaled(pars, q, qx/q, qy/q);
}

StackedDisksModel :: StackedDisksModel() {
  scale      = Parameter(1.0);
  radius     = Parameter(3000.0, true);
  radius.set_min(0.0);
  core_thick  = Parameter(10.0, true);
  core_thick.set_min(0.0);
  layer_thick     = Parameter(15.0);
  layer_thick.set_min(0.0);
  core_sld = Parameter(4.0e-6);
  layer_sld  = Parameter(-4.0e-7);
  solvent_sld  = Parameter(5.0e-6);
  n_stacking   = Parameter(1);
  sigma_d   = Parameter(0);
  background = Parameter(0.001);
  axis_theta  = Parameter(0.0, true);
  axis_phi    = Parameter(0.0, true);
}

/**
 * Function to evaluate 1D scattering function
 * The NIST IGOR library is used for the actual calculation.
 * @param q: q-value
 * @return: function value
 */
double StackedDisksModel :: operator()(double q) {
  double dp[10];

  // Fill parameter array for IGOR library
  // Add the background after averaging
  dp[0] = scale();
  dp[1] = radius();
  dp[2] = core_thick();
  dp[3] = layer_thick();
  dp[4] = core_sld();
  dp[5] = layer_sld();
  dp[6] = solvent_sld();
  dp[7] = n_stacking();
  dp[8] = sigma_d();
  dp[9] = 0.0;

  // Get the dispersion points for the radius
  vector<WeightPoint> weights_radius;
  radius.get_weights(weights_radius);

  // Get the dispersion points for the core_thick
  vector<WeightPoint> weights_core_thick;
  core_thick.get_weights(weights_core_thick);

  // Get the dispersion points for the layer_thick
  vector<WeightPoint> weights_layer_thick;
  layer_thick.get_weights(weights_layer_thick);

  // Perform the computation, with all weight points
  double sum = 0.0;
  double norm = 0.0;
  double vol = 0.0;

  // Loop over length weight points
  for(int i=0; i< (int)weights_radius.size(); i++) {
    dp[1] = weights_radius[i].value;

    // Loop over radius weight points
    for(int j=0; j< (int)weights_core_thick.size(); j++) {
      dp[2] = weights_core_thick[j].value;

      // Loop over thickness weight points
      for(int k=0; k< (int)weights_layer_thick.size(); k++) {
        dp[3] = weights_layer_thick[k].value;
        //Un-normalize by volume
        sum += weights_radius[i].weight
            * weights_core_thick[j].weight * weights_layer_thick[k].weight* StackedDiscs(dp, q)
        *pow(weights_radius[i].value,2)*(weights_core_thick[j].value+2*weights_layer_thick[k].value);
        //Find average volume
        vol += weights_radius[i].weight
            * weights_core_thick[j].weight * weights_layer_thick[k].weight
            *pow(weights_radius[i].value,2)*(weights_core_thick[j].value+2*weights_layer_thick[k].value);
        norm += weights_radius[i].weight
            * weights_core_thick[j].weight* weights_layer_thick[k].weight;
      }
    }
  }
  if (vol != 0.0 && norm != 0.0) {
    //Re-normalize by avg volume
    sum = sum/(vol/norm);}

  return sum/norm + background();
}

/**
 * Function to evaluate 2D scattering function
 * @param q_x: value of Q along x
 * @param q_y: value of Q along y
 * @return: function value
 */
double StackedDisksModel :: operator()(double qx, double qy) {
  StackedDisksParameters dp;
  // Fill parameter array
  dp.scale      = scale();
  dp.core_thick    = core_thick();
  dp.radius	  = radius();
  dp.layer_thick  = layer_thick();
  dp.core_sld   = core_sld();
  dp.layer_sld  = layer_sld();
  dp.solvent_sld= solvent_sld();
  dp.n_stacking	  = n_stacking();
  dp.sigma_d   = sigma_d();
  dp.background = 0.0;
  dp.axis_theta = axis_theta();
  dp.axis_phi   = axis_phi();

  // Get the dispersion points for the length
  vector<WeightPoint> weights_core_thick;
  core_thick.get_weights(weights_core_thick);

  // Get the dispersion points for the radius
  vector<WeightPoint> weights_radius;
  radius.get_weights(weights_radius);

  // Get the dispersion points for the thickness
  vector<WeightPoint> weights_layer_thick;
  layer_thick.get_weights(weights_layer_thick);

  // Get angular averaging for theta
  vector<WeightPoint> weights_theta;
  axis_theta.get_weights(weights_theta);

  // Get angular averaging for phi
  vector<WeightPoint> weights_phi;
  axis_phi.get_weights(weights_phi);

  // Perform the computation, with all weight points
  double sum = 0.0;
  double norm = 0.0;
  double norm_vol = 0.0;
  double vol = 0.0;

  // Loop over length weight points
  for(int i=0; i< (int)weights_core_thick.size(); i++) {
    dp.core_thick = weights_core_thick[i].value;

    // Loop over radius weight points
    for(int j=0; j< (int)weights_radius.size(); j++) {
      dp.radius = weights_radius[j].value;

      // Loop over thickness weight points
      for(int k=0; k< (int)weights_layer_thick.size(); k++) {
        dp.layer_thick = weights_layer_thick[k].value;

        for(int l=0; l< (int)weights_theta.size(); l++) {
          dp.axis_theta = weights_theta[l].value;

          // Average over phi distribution
          for(int m=0; m <(int)weights_phi.size(); m++) {
            dp.axis_phi = weights_phi[m].value;

            //Un-normalize by volume
            double _ptvalue = weights_core_thick[i].weight
                * weights_radius[j].weight
                * weights_layer_thick[k].weight
                * weights_theta[l].weight
                * weights_phi[m].weight
                * stacked_disks_analytical_2DXY(&dp, qx, qy)
            *pow(weights_radius[j].value,2)*(weights_core_thick[i].value+2*weights_layer_thick[k].value);
            if (weights_theta.size()>1) {
              _ptvalue *= fabs(sin(weights_theta[l].value));
            }
            sum += _ptvalue;
            //Find average volume
            vol += weights_radius[j].weight
                * weights_core_thick[i].weight * weights_layer_thick[k].weight
                *pow(weights_radius[j].value,2)*(weights_core_thick[i].value+2*weights_layer_thick[k].value);
            //Find norm for volume
            norm_vol += weights_radius[j].weight
                * weights_core_thick[i].weight * weights_layer_thick[k].weight;

            norm += weights_core_thick[i].weight
                * weights_radius[j].weight
                * weights_layer_thick[k].weight
                * weights_theta[l].weight
                * weights_phi[m].weight;
          }
        }
      }
    }
  }
  // Averaging in theta needs an extra normalization
  // factor to account for the sin(theta) term in the
  // integration (see documentation).
  if (weights_theta.size()>1) norm = norm / asin(1.0);
  if (vol != 0.0 && norm_vol != 0.0) {
    //Re-normalize by avg volume
    sum = sum/(vol/norm_vol);}
  return sum/norm + background();
}

/**
 * Function to evaluate 2D scattering function
 * @param pars: parameters of the triaxial ellipsoid
 * @param q: q-value
 * @param phi: angle phi
 * @return: function value
 */
double StackedDisksModel :: evaluate_rphi(double q, double phi) {
  double qx = q*cos(phi);
  double qy = q*sin(phi);
  return (*this).operator()(qx, qy);
}
/**
 * Function to calculate effective radius
 * @return: effective radius value
 */
double StackedDisksModel :: calculate_ER() {
  StackedDisksParameters dp;

  dp.core_thick    = core_thick();
  dp.radius	  = radius();
  dp.layer_thick  = layer_thick();
  dp.n_stacking	  = n_stacking();

  double rad_out = 0.0;
  if (dp.n_stacking <= 0.0){
    return rad_out;
  }

  // Perform the computation, with all weight points
  double sum = 0.0;
  double norm = 0.0;

  // Get the dispersion points for the length
  vector<WeightPoint> weights_core_thick;
  core_thick.get_weights(weights_core_thick);

  // Get the dispersion points for the radius
  vector<WeightPoint> weights_radius;
  radius.get_weights(weights_radius);

  // Get the dispersion points for the thickness
  vector<WeightPoint> weights_layer_thick;
  layer_thick.get_weights(weights_layer_thick);

  // Loop over major shell weight points
  for(int i=0; i< (int)weights_core_thick.size(); i++) {
    dp.core_thick = weights_core_thick[i].value;
    for(int j=0; j< (int)weights_layer_thick.size(); j++) {
      dp.layer_thick = weights_layer_thick[j].value;
      for(int k=0; k< (int)weights_radius.size(); k++) {
        dp.radius = weights_radius[k].value;
        //Note: output of "DiamCyl(dp.length,dp.radius)" is DIAMETER.
        sum +=weights_core_thick[i].weight*weights_layer_thick[j].weight
            * weights_radius[k].weight*DiamCyl(dp.n_stacking*(dp.layer_thick*2.0+dp.core_thick),dp.radius)/2.0;
        norm += weights_core_thick[i].weight*weights_layer_thick[j].weight* weights_radius[k].weight;
      }
    }
  }
  if (norm != 0){
    //return the averaged value
    rad_out =  sum/norm;}
  else{
    //return normal value
    //Note: output of "DiamCyl(dp.length,dp.radius)" is DIAMETER.
    rad_out = DiamCyl(dp.n_stacking*(dp.layer_thick*2.0+dp.core_thick),dp.radius)/2.0;}

  return rad_out;
}
double StackedDisksModel :: calculate_VR() {
  return 1.0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DAVSession.hxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 18:19:27 $
 *
 *  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 _DAVSESSION_HXX_
#define _DAVSESSION_HXX_

#include <memory>

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif

#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
#ifndef _DAVPROPERTIES_HXX_
#include "DAVProperties.hxx"
#endif
#ifndef _DAVRESOURCE_HXX_
#include "DAVResource.hxx"
#endif
#ifndef _DAVSESSIONFACTORY_HXX_
#include "DAVSessionFactory.hxx"
#endif
#ifndef _DAVTYPES_HXX_
#include "DAVTypes.hxx"
#endif
#ifndef _DAVREQUESTENVIRONMENT_HXX_
#include "DAVRequestEnvironment.hxx"
#endif

namespace webdav_ucp
{

class DAVAuthListener;

class DAVSession
{
public:
    inline void acquire() SAL_THROW(())
    {
        osl_incrementInterlockedCount( &m_nRefCount );
    }

    void release() SAL_THROW(())
    {
        if ( osl_decrementInterlockedCount( &m_nRefCount ) == 0 )
        {
            m_xFactory->releaseElement( this );
            delete this;
        }
    }

    virtual sal_Bool CanUse( const ::rtl::OUString & inPath ) = 0;

    virtual sal_Bool UsesProxy() = 0;

    // DAV methods
    //

    virtual void OPTIONS( const ::rtl::OUString &  inPath,
                          DAVCapabilities & outCapabilities,
                          const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    // allprop & named
    virtual void PROPFIND( const ::rtl::OUString &                inPath,
                           const Depth                            inDepth,
                           const std::vector< ::rtl::OUString > & inPropertyNames,
                           std::vector< DAVResource > &           ioResources,
                           const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    // propnames
    virtual void PROPFIND( const ::rtl::OUString &          inPath,
                           const Depth                      inDepth,
                           std::vector< DAVResourceInfo > & ioResInfo,
                           const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void PROPPATCH( const ::rtl::OUString &               inPath,
                             const std::vector< ProppatchValue > & inValues,
                            const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void HEAD( const ::rtl::OUString &  inPath,
                       const std::vector< ::rtl::OUString > & inHeaderNames,
                       DAVResource & ioResource,
                       const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
                    GET( const ::rtl::OUString & inPath,
                         const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    GET( const ::rtl::OUString & inPath,
        com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o,
        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
                    GET( const ::rtl::OUString & inPath,
                         const std::vector< ::rtl::OUString > & inHeaderNames,
                         DAVResource & ioResource,
                         const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    GET( const ::rtl::OUString & inPath,
        com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o,
        const std::vector< ::rtl::OUString > & inHeaderNames,
        DAVResource & ioResource,
        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    PUT( const ::rtl::OUString & inPath,
        const com::sun::star::uno::Reference<
            com::sun::star::io::XInputStream >& s,
        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
                    POST( const rtl::OUString & inPath,
                          const rtl::OUString & rContentType,
                          const rtl::OUString & rReferer,
                          const com::sun::star::uno::Reference<
                           com::sun::star::io::XInputStream > & inInputStream,
                          const DAVRequestEnvironment & rEnv )
        throw ( DAVException ) = 0;

    virtual void POST( const rtl::OUString & inPath,
                       const rtl::OUString & rContentType,
                       const rtl::OUString & rReferer,
                       const com::sun::star::uno::Reference<
                        com::sun::star::io::XInputStream > & inInputStream,
                       com::sun::star::uno::Reference<
                        com::sun::star::io::XOutputStream > & oOutputStream,
                       const DAVRequestEnvironment & rEnv )
        throw ( DAVException ) = 0;

    virtual void    MKCOL( const ::rtl::OUString & inPath,
                           const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    COPY( const ::rtl::OUString & inSource,
                          const ::rtl::OUString & inDestination,
                          const DAVRequestEnvironment & rEnv,
                          sal_Bool inOverwrite = false )
        throw( DAVException ) = 0;

    virtual void    MOVE( const ::rtl::OUString & inSource,
                          const ::rtl::OUString & inDestination,
                          const DAVRequestEnvironment & rEnv,
                          sal_Bool inOverwrite = false )
        throw( DAVException ) = 0;

    virtual void    DESTROY( const ::rtl::OUString & inPath,
                             const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    // Note: Uncomment the following if locking support is required
    /*
    virtual void LOCK ( const Lock & inLock,
                        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void UNLOCK ( const Lock & inLock,
                          const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;
    */
protected:
    rtl::Reference< DAVSessionFactory > m_xFactory;

    DAVSession( rtl::Reference< DAVSessionFactory > const & rFactory )
    : m_xFactory( rFactory ), m_nRefCount( 0 ) {}

    virtual ~DAVSession() {}

private:
    DAVSessionFactory::Map::iterator m_aContainerIt;
    oslInterlockedCount m_nRefCount;

    friend class DAVSessionFactory;
#if defined WNT && _MSC_VER < 1310
    friend struct std::auto_ptr< DAVSession >;
    // work around compiler bug...
#else // WNT
    friend class std::auto_ptr< DAVSession >;
#endif // WNT
};

} // namespace webdav_ucp

#endif // _DAVSESSION_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.19.72); FILE MERGED 2008/04/01 16:02:25 thb 1.19.72.3: #i85898# Stripping all external header guards 2008/04/01 12:58:25 thb 1.19.72.2: #i85898# Stripping all external header guards 2008/03/31 15:30:30 rt 1.19.72.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: DAVSession.hxx,v $
 * $Revision: 1.20 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _DAVSESSION_HXX_
#define _DAVSESSION_HXX_

#include <memory>
#include <rtl/ustring.hxx>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include "DAVException.hxx"
#include "DAVProperties.hxx"
#include "DAVResource.hxx"
#include "DAVSessionFactory.hxx"
#include "DAVTypes.hxx"
#include "DAVRequestEnvironment.hxx"

namespace webdav_ucp
{

class DAVAuthListener;

class DAVSession
{
public:
    inline void acquire() SAL_THROW(())
    {
        osl_incrementInterlockedCount( &m_nRefCount );
    }

    void release() SAL_THROW(())
    {
        if ( osl_decrementInterlockedCount( &m_nRefCount ) == 0 )
        {
            m_xFactory->releaseElement( this );
            delete this;
        }
    }

    virtual sal_Bool CanUse( const ::rtl::OUString & inPath ) = 0;

    virtual sal_Bool UsesProxy() = 0;

    // DAV methods
    //

    virtual void OPTIONS( const ::rtl::OUString &  inPath,
                          DAVCapabilities & outCapabilities,
                          const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    // allprop & named
    virtual void PROPFIND( const ::rtl::OUString &                inPath,
                           const Depth                            inDepth,
                           const std::vector< ::rtl::OUString > & inPropertyNames,
                           std::vector< DAVResource > &           ioResources,
                           const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    // propnames
    virtual void PROPFIND( const ::rtl::OUString &          inPath,
                           const Depth                      inDepth,
                           std::vector< DAVResourceInfo > & ioResInfo,
                           const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void PROPPATCH( const ::rtl::OUString &               inPath,
                             const std::vector< ProppatchValue > & inValues,
                            const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void HEAD( const ::rtl::OUString &  inPath,
                       const std::vector< ::rtl::OUString > & inHeaderNames,
                       DAVResource & ioResource,
                       const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
                    GET( const ::rtl::OUString & inPath,
                         const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    GET( const ::rtl::OUString & inPath,
        com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o,
        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
                    GET( const ::rtl::OUString & inPath,
                         const std::vector< ::rtl::OUString > & inHeaderNames,
                         DAVResource & ioResource,
                         const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    GET( const ::rtl::OUString & inPath,
        com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o,
        const std::vector< ::rtl::OUString > & inHeaderNames,
        DAVResource & ioResource,
        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    PUT( const ::rtl::OUString & inPath,
        const com::sun::star::uno::Reference<
            com::sun::star::io::XInputStream >& s,
        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
                    POST( const rtl::OUString & inPath,
                          const rtl::OUString & rContentType,
                          const rtl::OUString & rReferer,
                          const com::sun::star::uno::Reference<
                           com::sun::star::io::XInputStream > & inInputStream,
                          const DAVRequestEnvironment & rEnv )
        throw ( DAVException ) = 0;

    virtual void POST( const rtl::OUString & inPath,
                       const rtl::OUString & rContentType,
                       const rtl::OUString & rReferer,
                       const com::sun::star::uno::Reference<
                        com::sun::star::io::XInputStream > & inInputStream,
                       com::sun::star::uno::Reference<
                        com::sun::star::io::XOutputStream > & oOutputStream,
                       const DAVRequestEnvironment & rEnv )
        throw ( DAVException ) = 0;

    virtual void    MKCOL( const ::rtl::OUString & inPath,
                           const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    COPY( const ::rtl::OUString & inSource,
                          const ::rtl::OUString & inDestination,
                          const DAVRequestEnvironment & rEnv,
                          sal_Bool inOverwrite = false )
        throw( DAVException ) = 0;

    virtual void    MOVE( const ::rtl::OUString & inSource,
                          const ::rtl::OUString & inDestination,
                          const DAVRequestEnvironment & rEnv,
                          sal_Bool inOverwrite = false )
        throw( DAVException ) = 0;

    virtual void    DESTROY( const ::rtl::OUString & inPath,
                             const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    // Note: Uncomment the following if locking support is required
    /*
    virtual void LOCK ( const Lock & inLock,
                        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void UNLOCK ( const Lock & inLock,
                          const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;
    */
protected:
    rtl::Reference< DAVSessionFactory > m_xFactory;

    DAVSession( rtl::Reference< DAVSessionFactory > const & rFactory )
    : m_xFactory( rFactory ), m_nRefCount( 0 ) {}

    virtual ~DAVSession() {}

private:
    DAVSessionFactory::Map::iterator m_aContainerIt;
    oslInterlockedCount m_nRefCount;

    friend class DAVSessionFactory;
#if defined WNT && _MSC_VER < 1310
    friend struct std::auto_ptr< DAVSession >;
    // work around compiler bug...
#else // WNT
    friend class std::auto_ptr< DAVSession >;
#endif // WNT
};

} // namespace webdav_ucp

#endif // _DAVSESSION_HXX_

<|endoftext|>


<commit_before>// This is sometimes required to support the full curses API
#define _XOPEN_SOURCE
#define _XOPEN_SOURCE_EXTENDED

// Enable printf and scanf argument checking
#define GCC_PRINTF
#define	GCC_SCANF

#include <curses.h>
#include <climits>
#include <cstdio>

#include <QString>

#include "lirch_constants.h"
#include "plugins/lirch_plugin.h"
#include "core/core_messages.h"

using namespace std;

template <class... args>
string strprintf(const string &format, args... a)
{
	int size=snprintf(NULL, 0, format.c_str(), a...);
	//Add padding for the terminating byte
	char *s=new char[size+1];
	//We can use sprintf instead of snprintf because we know the buffer is large enough
	sprintf(s, format.c_str(), a...);
	return s;
}

//Same as wprintf, but handles unicode characters properly
template <class... args>
wprintu(WINDOW *w, const string &format, args... a)
{
	string s=strprintf(format, a);
	for (unsigned char c : s)
		waddch(w, c|(c>0x7f ? A_ALTCHARSET : 0));
}

void runplugin(plugin_pipe &p, const string &name)
{
	QString input;
	int maxx, maxy;
	getmaxyx(stdscr, maxy, maxx);
	//10000 lines of scrollback should be enough for anyone
	auto channel_output=newpad(10000, maxx);
	//Let the output scroll
	scrollok(channel_output, TRUE);
	//p.write(registration_message::create(-30000, name, "display"));
	while (true)
	{
		/*while (p.has_message())
		{
			message m=p.read();
		}*/
		wint_t key;
		int rc=get_wch(&key);
		if (rc==OK)
		{
			input.push_back(QString::fromUcs4(&key, 1));
			//add_wch(key);
			wprintw(channel_output, "%s: %x: ", QString::fromUcs4(&key, 1).toLocal8Bit().constData(), key);
			for (auto &i : QString::fromUcs4(&key, 1).toLocal8Bit())
				wprintw(channel_output, "%02x ", (unsigned char)i);
			wprintw(channel_output, ": ");
			//addch(ACS_HLINE);
			for (auto &i : QString::fromUcs4(&key, 1).toLocal8Bit())
				waddch(channel_output, (unsigned char)i|(A_ALTCHARSET*((unsigned char)i>0x7f)));
				//addch(i&~(/*A_ALTCHARSET|*/A_BLINK|A_BOLD/*|A_DIM|A_INVIS|A_PROTECT*/));
			waddch(channel_output, '\n');
		}
		else if (rc==KEY_CODE_YES)
		{
			break;
		}
		else
		{
			wprintw(channel_output, "No key pressed\n");
		}
		int x,y;
		getyx(channel_output, y, x);
		prefresh(channel_output, max(y-maxy,0), 0, 0,0,maxy-2,maxx-1);
	}
	p.write(core_quit_message::create());
}

void run(plugin_pipe p, string name)
{
	//Set the delay when hitting escape to 10 milliseconds, unless it was
	//already set.  The ESCDELAY variable is not supported in all curses
	//implementations, but should not cause problems in implementations
	//that ignore it.
	setenv("ESCDELAY", "10", 0);
	//Initialize curses
	initscr();
	//Don't buffer typed characters
	cbreak();
	//Wain no more than a tenth of a second for input
	timeout(100);
	noecho();
	//Makes enter return \r instead of \n
	nonl();
	//Flush the input buffer if an interrupt key is pressed.  This ensures
	//we don't miss keystrokes in the event of a SIGSTOP
	intrflush(stdscr, FALSE);
	//Enable keycodes
	keypad(stdscr, TRUE);
	runplugin(p, name);
	//Make sure to always restore the terminal to a sane configuration
	endwin();
	return;
}
<commit_msg>Miscelaneous fixes<commit_after>// This is sometimes required to support the full curses API
#define _XOPEN_SOURCE
#define _XOPEN_SOURCE_EXTENDED

#ifdef __GNUC__
	// Enable printf and scanf argument checking
	#define GCC_PRINTF
	#define	GCC_SCANF
#endif

#include <curses.h>
#include <climits>
#include <cstdio>

#include <QString>

#include "lirch_constants.h"
#include "plugins/lirch_plugin.h"
#include "core/core_messages.h"

using namespace std;

template <class... args>
string strprintf(const string &format, args... a)
{
	//Thankfully, the C++ standard grabbed the definition from POSIX
	//instead of Windows, so I don't have to binary-search the correct
	//string size.
	int size=snprintf(NULL, 0, format.c_str(), a...);
	//Add padding for the terminating byte
	vector<char> s(size+1);
	//We can use sprintf instead of snprintf because we know the buffer is large enough
	sprintf(s.data(), format.c_str(), a...);
	return s.data();
}

//Same as wprintf, but handles unicode characters properly
template <class... args>
void wprintu(WINDOW *w, const string &format, args... a)
{
	string s=strprintf(format, a...);
	for (unsigned char c : s)
		waddch(w, c|(c>0x7f ? A_ALTCHARSET : 0));
}

void runplugin(plugin_pipe &p, const string &name)
{
	QString input;
	int maxx, maxy;
	getmaxyx(stdscr, maxy, maxx);
	//10000 lines of scrollback should be enough for anyone
	auto channel_output=newpad(10000, maxx);
	//Let the output scroll
	scrollok(channel_output, TRUE);
	//p.write(registration_message::create(-30000, name, "display"));
	while (true)
	{
		/*while (p.has_message())
		{
			message m=p.read();
		}*/
		wint_t key;
		int rc=get_wch(&key);
		if (rc==OK)
		{
			input.push_back(QString::fromUcs4(&key, 1));
			//add_wch(key);
			wprintw(channel_output, "%s: %x: ", QString::fromUcs4(&key, 1).toLocal8Bit().constData(), key);
			for (auto &i : QString::fromUcs4(&key, 1).toLocal8Bit())
				wprintw(channel_output, "%02x ", (unsigned char)i);
			wprintw(channel_output, ": ");
			//addch(ACS_HLINE);
			for (auto &i : QString::fromUcs4(&key, 1).toLocal8Bit())
				waddch(channel_output, (unsigned char)i|(A_ALTCHARSET*((unsigned char)i>0x7f)));
				//addch(i&~(/*A_ALTCHARSET|*/A_BLINK|A_BOLD/*|A_DIM|A_INVIS|A_PROTECT*/));
			waddch(channel_output, '\n');
		}
		else if (rc==KEY_CODE_YES)
		{
			break;
		}
		else
		{
			wprintw(channel_output, "No key pressed\n");
		}
		int x,y;
		getyx(channel_output, y, x);
		prefresh(channel_output, max(y-maxy,0), 0, 0,0,maxy-2,maxx-1);
	}
	p.write(core_quit_message::create());
}

void run(plugin_pipe p, string name)
{
	//Set the delay when hitting escape to 10 milliseconds, unless it was
	//already set.  The ESCDELAY variable is not supported in all curses
	//implementations, but should not cause problems in implementations
	//that ignore it.
	setenv("ESCDELAY", "10", 0);
	//Initialize curses
	initscr();
	//Don't buffer typed characters
	cbreak();
	//Wain no more than a tenth of a second for input
	timeout(100);
	noecho();
	//Makes enter return \r instead of \n
	nonl();
	//Flush the input buffer if an interrupt key is pressed.  This ensures
	//we don't miss keystrokes in the event of a SIGSTOP
	intrflush(stdscr, FALSE);
	//Enable keycodes
	keypad(stdscr, TRUE);
	runplugin(p, name);
	//Make sure to always restore the terminal to a sane configuration
	endwin();
	return;
}
<|endoftext|>


<commit_before>#include "acquisition.hpp"
#include <fstream>
#include <opencv2/ts/ts.hpp>

#ifndef SAMPLES_DIR
#define SAMPLES_DIR ""
#endif
CV_TEST_MAIN (".");

TEST (acquisition_cam_count, acquisition) {
    acquisition ac_test;
    ASSERT_EQ (ac_test.cam_count (), 10);
}

TEST (acquisition_file_fail, acquisition) {
    acquisition ac_test;
    ASSERT_THROW (ac_test.source ("./random_file"), std::ifstream::failure);
}

TEST (acquisition_file_no_fail_video, acquisition) {
    acquisition ac_test;
    ASSERT_NO_THROW (ac_test.source (
    std::string (SAMPLES_DIR) + std::string ("/3_marker_with_border.webm")));
}

TEST (acquisition_file_no_fail_image, acquisition) {
    acquisition ac_test;
    ASSERT_NO_THROW (ac_test.source (
    std::string (SAMPLES_DIR) + std::string ("/arctichare.png")));
}

TEST (acquisition_capture_file_set, acquisition) {
    acquisition ac_test;
    ASSERT_NO_THROW (ac_test.source (
    std::string (SAMPLES_DIR) + std::string ("/arctichare.png")));
    ASSERT_NO_THROW (ac_test.capture ());
}

TEST (acquisition_capture_file_wrong_set, acquisition) {
    acquisition ac_test;
    ASSERT_THROW (ac_test.source ("./random_file"), std::ifstream::failure);
    ASSERT_THROW (ac_test.capture (), std::runtime_error);
}
<commit_msg>add messages to tests<commit_after>#include "acquisition.hpp"
#include <fstream>
#include <opencv2/ts/ts.hpp>

#ifndef SAMPLES_DIR
#define SAMPLES_DIR ""
#endif
CV_TEST_MAIN (".");

TEST (acquisition_cam_count, acquisition) {
    acquisition ac_test;
    ASSERT_EQ (ac_test.cam_count (), 10) << "camera count is wrong";
}

TEST (acquisition_file_fail, acquisition) {
    acquisition ac_test;
    ASSERT_THROW (ac_test.source ("./random_file"), std::ifstream::failure)
    << "a random file that doesn't exist should throw an error";
}

TEST (acquisition_file_no_fail_video, acquisition) {
    acquisition ac_test;
    ASSERT_NO_THROW (ac_test.source (
    std::string (SAMPLES_DIR) + std::string ("/3_marker_with_border.webm")))
    << "the sample video file cannot be read";
}

TEST (acquisition_file_no_fail_image, acquisition) {
    acquisition ac_test;
    ASSERT_NO_THROW (ac_test.source (std::string (SAMPLES_DIR) + std::string ("/arctichare.png")))
    << "the sample image file cannot be read";
}

TEST (acquisition_capture_file_set, acquisition) {
    acquisition ac_test;
    ASSERT_NO_THROW (ac_test.source (std::string (SAMPLES_DIR) + std::string ("/arctichare.png")))
    << "the sample file cannot be read";
    ASSERT_NO_THROW (ac_test.capture ()) << "the file cannot be captured";
}

TEST (acquisition_capture_file_wrong_set, acquisition) {
    acquisition ac_test;
    ASSERT_THROW (ac_test.source ("./random_file"), std::ifstream::failure)
    << "the file does not exists, so an error should be thrown";
    ASSERT_THROW (ac_test.capture (), std::runtime_error)
    << "the file is not set correctly, so an error should be thrown";
}
<|endoftext|>


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

Portions (c) Copyright 2005 Brigham and Women\"s Hospital (BWH) All Rights Reserved.

See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.

Program:   3D Slicer
Module:    $RCSfile: vtkMRMLVolumeDisplayNode.cxx,v $
Date:      $Date: 2006/03/17 15:10:10 $
Version:   $Revision: 1.2 $

=========================================================================auto=*/
#include "vtkMRMLRegionTypeDisplayNode.h"
//#include "vtkMRMLProceduralColorNode.h"
#include "vtkMRMLScene.h"

#include "vtkMRMLRegionTypeNode.h"
#include "vtkMRMLColorNode.h"

// VTK includes
#include <vtkImageData.h>
#include <vtkImageMapToColors.h>
#include <vtkLookupTable.h>
#include <vtkObjectFactory.h>

// STD includes
#include <cassert>
#include <math.h>
#include <vnl/vnl_math.h>

//----------------------------------------------------------------------------
vtkMRMLNodeNewMacro(vtkMRMLRegionTypeDisplayNode);

//----------------------------------------------------------------------------
vtkMRMLRegionTypeDisplayNode::vtkMRMLRegionTypeDisplayNode()
{
}

//----------------------------------------------------------------------------
vtkMRMLRegionTypeDisplayNode::~vtkMRMLRegionTypeDisplayNode()
{
}

//----------------------------------------------------------------------------
void vtkMRMLRegionTypeDisplayNode::PrintSelf(ostream& os, vtkIndent indent)
{
  Superclass::PrintSelf(os,indent);
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::SetRegionTypeVisibility(unsigned char region, unsigned char type,
                                                             int visibility, double regionTypeColorBlend)
{
  vtkMRMLColorNode* colorNode = vtkMRMLColorNode::SafeDownCast( this->GetColorNode() );
  if (colorNode == 0)
  {
    return;
  }

  vtkLookupTable *lut = colorNode->GetLookupTable();
  if (lut == 0)
  {
    return;
  }

  double color[4];
  double typeColor[4];
  double regionColor[4];
  cip::ChestConventions cc;
  cc.GetChestTypeColor(type, typeColor);
  cc.GetChestRegionColor(region, regionColor);
  for (int i=0; i<4; i++)
  {
    color[i] = (1.0 - regionTypeColorBlend) * regionColor[i] +
                      regionTypeColorBlend * typeColor[i];
  }
  color[3] = visibility;
  int index = this->GetLUTIndex(region, type);
  lut->SetTableValue(index, color);
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::HideAllRegionTypes(vtkMRMLRegionTypeNode* node)
{
  std::vector<unsigned char> regions = node->GetAvailableRegions();
  std::vector<unsigned char> types = node->GetAvailableTypes();
  for (size_t t=0; t<types.size(); t++)
  {
    for (size_t r=0; r<regions.size(); r++)
    {
      this->SetRegionTypeVisibility(regions[r], types[t], 0, 0);
    }
  }
  this->Modified();
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::ShowAllRegionTypes(vtkMRMLRegionTypeNode* node, double regionTypeColorBlend)
{
  std::vector<unsigned char> regions = node->GetAvailableRegions();
  std::vector<unsigned char> types = node->GetAvailableTypes();
  for (size_t t=0; t<types.size(); t++)
  {
    for (size_t r=0; r<regions.size(); r++)
    {
      this->SetRegionTypeVisibility(regions[r], types[t], 1, regionTypeColorBlend);
    }
  }
  this->Modified();
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::ShowSelectedRegionType(vtkMRMLRegionTypeNode* node,
                                                            unsigned char region, unsigned char type,
                                                            double regionTypeColorBlend)
{
  this->HideAllRegionTypes(node);
  this->SetRegionTypeVisibility(region, type, 1, regionTypeColorBlend);
  this->Modified();
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::ShowAllRegions(vtkMRMLRegionTypeNode* node,
                                                    unsigned char type,
                                                    double regionTypeColorBlend)
{
  this->HideAllRegionTypes(node);
  std::vector<unsigned char> regions = node->GetAvailableRegions();
  for (size_t r=0; r<regions.size(); r++)
  {
    this->SetRegionTypeVisibility(regions[r], type, 1, regionTypeColorBlend);
  }
  this->Modified();
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::ShowAllTypes(vtkMRMLRegionTypeNode* node,
                                                  unsigned char region,
                                                  double regionTypeColorBlend)
{
  this->HideAllRegionTypes(node);
  std::vector<unsigned char> types = node->GetAvailableTypes();
  for (size_t t=0; t<types.size(); t++)
  {
    this->SetRegionTypeVisibility(region, types[t], 1, regionTypeColorBlend);
  }
  this->Modified();
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::InitializeLookupTable(vtkMRMLRegionTypeNode* node, double regionTypeColorBlend)
{
  vtkMRMLColorNode* colorNode = vtkMRMLColorNode::SafeDownCast( this->GetColorNode() );
  if (colorNode == 0)
  {
    return;
  }

  vtkLookupTable *lut = colorNode->GetLookupTable();
  if (lut == 0)
  {
    return;
  }

  std::vector<unsigned char> regions = node->GetAvailableRegions();
  std::vector<unsigned char> types = node->GetAvailableTypes();

  int index;
  int maxIndex = 0;
  for (size_t t=0; t<types.size(); t++)
  {
    for (size_t r=0; r<regions.size(); r++)
    {
      index = this->GetLUTIndex(regions[r], types[t]);
      maxIndex = index > maxIndex? index : maxIndex;
    }
  }
  lut = colorNode->GetLookupTable();
  lut->SetNumberOfTableValues(maxIndex);
  lut->SetTableRange(0,maxIndex);
}
<commit_msg>COMP: vtkMRMLRegionTypeDisplayNode: Fix unused parameter warning<commit_after>/*=auto=========================================================================

Portions (c) Copyright 2005 Brigham and Women\"s Hospital (BWH) All Rights Reserved.

See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.

Program:   3D Slicer
Module:    $RCSfile: vtkMRMLVolumeDisplayNode.cxx,v $
Date:      $Date: 2006/03/17 15:10:10 $
Version:   $Revision: 1.2 $

=========================================================================auto=*/
#include "vtkMRMLRegionTypeDisplayNode.h"
//#include "vtkMRMLProceduralColorNode.h"
#include "vtkMRMLScene.h"

#include "vtkMRMLRegionTypeNode.h"
#include "vtkMRMLColorNode.h"

// VTK includes
#include <vtkImageData.h>
#include <vtkImageMapToColors.h>
#include <vtkLookupTable.h>
#include <vtkObjectFactory.h>

// STD includes
#include <cassert>
#include <math.h>
#include <vnl/vnl_math.h>

//----------------------------------------------------------------------------
vtkMRMLNodeNewMacro(vtkMRMLRegionTypeDisplayNode);

//----------------------------------------------------------------------------
vtkMRMLRegionTypeDisplayNode::vtkMRMLRegionTypeDisplayNode()
{
}

//----------------------------------------------------------------------------
vtkMRMLRegionTypeDisplayNode::~vtkMRMLRegionTypeDisplayNode()
{
}

//----------------------------------------------------------------------------
void vtkMRMLRegionTypeDisplayNode::PrintSelf(ostream& os, vtkIndent indent)
{
  Superclass::PrintSelf(os,indent);
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::SetRegionTypeVisibility(unsigned char region, unsigned char type,
                                                             int visibility, double regionTypeColorBlend)
{
  vtkMRMLColorNode* colorNode = vtkMRMLColorNode::SafeDownCast( this->GetColorNode() );
  if (colorNode == 0)
  {
    return;
  }

  vtkLookupTable *lut = colorNode->GetLookupTable();
  if (lut == 0)
  {
    return;
  }

  double color[4];
  double typeColor[4];
  double regionColor[4];
  cip::ChestConventions cc;
  cc.GetChestTypeColor(type, typeColor);
  cc.GetChestRegionColor(region, regionColor);
  for (int i=0; i<4; i++)
  {
    color[i] = (1.0 - regionTypeColorBlend) * regionColor[i] +
                      regionTypeColorBlend * typeColor[i];
  }
  color[3] = visibility;
  int index = this->GetLUTIndex(region, type);
  lut->SetTableValue(index, color);
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::HideAllRegionTypes(vtkMRMLRegionTypeNode* node)
{
  std::vector<unsigned char> regions = node->GetAvailableRegions();
  std::vector<unsigned char> types = node->GetAvailableTypes();
  for (size_t t=0; t<types.size(); t++)
  {
    for (size_t r=0; r<regions.size(); r++)
    {
      this->SetRegionTypeVisibility(regions[r], types[t], 0, 0);
    }
  }
  this->Modified();
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::ShowAllRegionTypes(vtkMRMLRegionTypeNode* node, double regionTypeColorBlend)
{
  std::vector<unsigned char> regions = node->GetAvailableRegions();
  std::vector<unsigned char> types = node->GetAvailableTypes();
  for (size_t t=0; t<types.size(); t++)
  {
    for (size_t r=0; r<regions.size(); r++)
    {
      this->SetRegionTypeVisibility(regions[r], types[t], 1, regionTypeColorBlend);
    }
  }
  this->Modified();
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::ShowSelectedRegionType(vtkMRMLRegionTypeNode* node,
                                                            unsigned char region, unsigned char type,
                                                            double regionTypeColorBlend)
{
  this->HideAllRegionTypes(node);
  this->SetRegionTypeVisibility(region, type, 1, regionTypeColorBlend);
  this->Modified();
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::ShowAllRegions(vtkMRMLRegionTypeNode* node,
                                                    unsigned char type,
                                                    double regionTypeColorBlend)
{
  this->HideAllRegionTypes(node);
  std::vector<unsigned char> regions = node->GetAvailableRegions();
  for (size_t r=0; r<regions.size(); r++)
  {
    this->SetRegionTypeVisibility(regions[r], type, 1, regionTypeColorBlend);
  }
  this->Modified();
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::ShowAllTypes(vtkMRMLRegionTypeNode* node,
                                                  unsigned char region,
                                                  double regionTypeColorBlend)
{
  this->HideAllRegionTypes(node);
  std::vector<unsigned char> types = node->GetAvailableTypes();
  for (size_t t=0; t<types.size(); t++)
  {
    this->SetRegionTypeVisibility(region, types[t], 1, regionTypeColorBlend);
  }
  this->Modified();
}

//-------------------------------------------
void vtkMRMLRegionTypeDisplayNode::InitializeLookupTable(
  vtkMRMLRegionTypeNode* node, double vtkNotUsed(regionTypeColorBlend))
{
  vtkMRMLColorNode* colorNode = vtkMRMLColorNode::SafeDownCast( this->GetColorNode() );
  if (colorNode == 0)
  {
    return;
  }

  vtkLookupTable *lut = colorNode->GetLookupTable();
  if (lut == 0)
  {
    return;
  }

  std::vector<unsigned char> regions = node->GetAvailableRegions();
  std::vector<unsigned char> types = node->GetAvailableTypes();

  int index;
  int maxIndex = 0;
  for (size_t t=0; t<types.size(); t++)
  {
    for (size_t r=0; r<regions.size(); r++)
    {
      index = this->GetLUTIndex(regions[r], types[t]);
      maxIndex = index > maxIndex? index : maxIndex;
    }
  }
  lut = colorNode->GetLookupTable();
  lut->SetNumberOfTableValues(maxIndex);
  lut->SetTableRange(0,maxIndex);
}
<|endoftext|>


<commit_before>/*
 * (C) Copyright 2013 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * 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.
 *
 */

#include "MediaSet.hpp"
#include "types/MediaPipeline.hpp"
#include "types/MediaElement.hpp"
#include "types/MediaSrc.hpp"
#include "types/Mixer.hpp"
#include "types/UriEndPoint.hpp"
#include "types/HttpEndPoint.hpp"
#include "types/SdpEndPoint.hpp"
#include "types/Filter.hpp"

#include "KmsMediaServer_constants.h"
#include "KmsMediaErrorCodes_constants.h"
#include "utils/utils.hpp"

#define GST_CAT_DEFAULT kurento_media_set
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoMediaSet"

using namespace kurento;

struct _AutoReleaseData {
  guint timeoutId;
  MediaSet *mediaSet;
  KmsMediaObjectId objectId;
  bool forceRemoving;
};

static gboolean
auto_release (gpointer dataPointer)
{
  AutoReleaseData *data = (AutoReleaseData *) dataPointer;

  GST_TRACE ("Auto release media object %" G_GINT64_FORMAT ", force: %d",
             data->objectId, data->forceRemoving);
  data->mediaSet->remove (data->objectId, data->forceRemoving);
  return TRUE;
}

namespace kurento
{

bool
MediaSet::canBeAutoreleased (const KmsMediaObjectRef &mediaObject)
{
  try {
    getMediaObject<MediaPad> (mediaObject);
    return false;
  } catch (const KmsMediaServerException &e) {
    return true;
  }
}

void
MediaSet::keepAlive (const KmsMediaObjectRef &mediaObject)
throw (KmsMediaServerException)
{
  std::shared_ptr<MediaObjectImpl> mo;
  std::shared_ptr<AutoReleaseData> data;
  std::map<KmsMediaObjectId, std::shared_ptr<AutoReleaseData>>::iterator it;

  if (!canBeAutoreleased (mediaObject) ) {
    GST_DEBUG ("MediaObject %" G_GINT64_FORMAT " is not auto releasable", mediaObject.id);
    return;
  }

  /* Check that object exists and it is not exluded from GC */
  mo = getMediaObject<MediaObjectImpl> (mediaObject);

  if (mo->getExcludeFromGC () ) {
    GST_DEBUG ("MediaObject %" G_GINT64_FORMAT " is excluded from GC", mediaObject.id);
    return;
  }

  mutex.lock();
  it = mediaObjectsAlive.find (mediaObject.id);

  if (it != mediaObjectsAlive.end() ) {
    data = it->second;

    if (data->timeoutId != 0)
      g_source_remove (data->timeoutId);
  }

  data->timeoutId = g_timeout_add_seconds_full (G_PRIORITY_DEFAULT,
                    mo->getGarbageCollectorPeriod() * 2, auto_release,
                    (gpointer) data.get (), NULL);
  mutex.unlock();
}

static bool
isForceRemoving (std::shared_ptr<MediaObjectImpl> mediaObject)
{
  return ! std::dynamic_pointer_cast<MediaPipeline> (mediaObject);
}

void
MediaSet::put (std::shared_ptr<MediaObjectImpl> mediaObject)
{
  std::shared_ptr<AutoReleaseData> data;
  std::map<KmsMediaObjectId, std::shared_ptr<std::set<KmsMediaObjectId>> >::iterator it;
  std::shared_ptr<std::set<KmsMediaObjectId>> children;

  if (!mediaObject->getExcludeFromGC () ) {
    data = std::shared_ptr<AutoReleaseData> (new AutoReleaseData() );
    data->mediaSet = this;
    data->objectId = mediaObject->id;
    data->forceRemoving = isForceRemoving (mediaObject);
  }

  mutex.lock();

  if (mediaObject->parent != NULL) {
    it = childrenMap.find (mediaObject->parent->id);

    if (it != childrenMap.end() ) {
      children = it->second;
    } else {
      children = std::shared_ptr<std::set<KmsMediaObjectId>> (new std::set<KmsMediaObjectId>() );
      childrenMap[mediaObject->parent->id] = children;
    }

    children->insert (mediaObject->id);
  }

  mediaObjectsMap[mediaObject->id] = mediaObject;

  if (!mediaObject->getExcludeFromGC () ) {
    mediaObjectsAlive[mediaObject->id] = data;
    keepAlive (*mediaObject);
  }

  mutex.unlock();
}

void
MediaSet::removeAutoRelease (const KmsMediaObjectId &id)
{
  std::shared_ptr<AutoReleaseData> data;
  std::map<KmsMediaObjectId, std::shared_ptr<AutoReleaseData>>::iterator it;

  mutex.lock();
  it = mediaObjectsAlive.find (id);

  if (it != mediaObjectsAlive.end() ) {
    data = it->second;

    if (data->timeoutId != 0)
      g_source_remove (data->timeoutId);
  }

  mediaObjectsAlive.erase (id);
  mutex.unlock();
}

void
MediaSet::remove (const KmsMediaObjectRef &mediaObject, bool force)
{
  remove (mediaObject.id, force);
}

void
MediaSet::remove (const KmsMediaObjectId &id, bool force)
{
  std::map<KmsMediaObjectId, std::shared_ptr<MediaObjectImpl> >::iterator mediaObjectsMapIt;
  std::shared_ptr<MediaObjectImpl> mo = NULL;
  std::map<KmsMediaObjectId, std::shared_ptr<std::set<KmsMediaObjectId>> >::iterator childrenMapIt;
  std::shared_ptr<std::set<KmsMediaObjectId>> children;
  std::set<KmsMediaObjectId>::iterator childrenIt;

  mutex.lock();

  childrenMapIt = childrenMap.find (id);

  if (childrenMapIt != childrenMap.end() ) {
    children = std::shared_ptr<std::set<KmsMediaObjectId>> (new std::set<KmsMediaObjectId> (* (childrenMapIt->second) ) );

    if (!force && !children->empty () ) {
      GST_DEBUG ("Media Object %ld has children and not is forcing, so it will not be removed.", id);
      mutex.unlock();
      return;
    }

    for (childrenIt = children->begin(); childrenIt != children->end(); childrenIt++) {
      remove (*childrenIt, force);
    }

    childrenMap.erase (id);
  }

  mediaObjectsMapIt = mediaObjectsMap.find (id);

  if (mediaObjectsMapIt != mediaObjectsMap.end() )
    mo = mediaObjectsMapIt->second;

  if (mo != NULL) {
    if (mo->parent != NULL) {
      childrenMapIt = childrenMap.find (mo->parent->id);

      if (childrenMapIt != childrenMap.end() ) {
        children = childrenMapIt->second;
        children->erase (mo->id);
      }
    }
  }

  mediaObjectsMap.erase (id);
  removeAutoRelease (id);
  mutex.unlock();
}

int
MediaSet::size ()
{
  int size;

  mutex.lock();
  size = mediaObjectsMap.size();
  mutex.unlock();

  return size;
}

template std::shared_ptr<MediaObjectImpl>
MediaSet::getMediaObject<MediaObjectImpl> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<MediaPipeline>
MediaSet::getMediaObject<MediaPipeline> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<MediaElement>
MediaSet::getMediaObject<MediaElement> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<MediaPad>
MediaSet::getMediaObject<MediaPad> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<MediaSrc>
MediaSet::getMediaObject<MediaSrc> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<MediaSink>
MediaSet::getMediaObject<MediaSink> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<Mixer>
MediaSet::getMediaObject<Mixer> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<UriEndPoint>
MediaSet::getMediaObject<UriEndPoint> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<HttpEndPoint>
MediaSet::getMediaObject<HttpEndPoint> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<SdpEndPoint>
MediaSet::getMediaObject<SdpEndPoint> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<Filter>
MediaSet::getMediaObject<Filter> (const KmsMediaObjectRef &mediaObject);

template <class T> std::shared_ptr<T>
MediaSet::getMediaObject (const KmsMediaObjectRef &mediaObject)
throw (KmsMediaServerException)
{
  std::map<KmsMediaObjectId, std::shared_ptr<MediaObjectImpl> >::iterator it;
  std::shared_ptr<KmsMediaObjectRef> mo = NULL;
  std::shared_ptr<T> typedMo;

  mutex.lock();
  it = mediaObjectsMap.find (mediaObject.id);

  if (it != mediaObjectsMap.end() )
    mo = it->second;

  mutex.unlock();

  if (mo == NULL) {
    KmsMediaServerException except;

    createKmsMediaServerException (except, g_KmsMediaErrorCodes_constants.MEDIA_OBJECT_NOT_FOUND, "Media object not found");
    throw except;
  }

  typedMo = std::dynamic_pointer_cast<T> (mo);

  if (typedMo == NULL) {
    KmsMediaServerException except;

    createKmsMediaServerException (except, g_KmsMediaErrorCodes_constants.MEDIA_OBJECT_CAST_ERROR, "Media Object found is not of requested type");
    throw except;
  }

  return typedMo;
}

MediaSet::StaticConstructor MediaSet::staticConstructor;

MediaSet::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} // kurento
<commit_msg>MediaSet: make put method idempotent<commit_after>/*
 * (C) Copyright 2013 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * 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.
 *
 */

#include "MediaSet.hpp"
#include "types/MediaPipeline.hpp"
#include "types/MediaElement.hpp"
#include "types/MediaSrc.hpp"
#include "types/Mixer.hpp"
#include "types/UriEndPoint.hpp"
#include "types/HttpEndPoint.hpp"
#include "types/SdpEndPoint.hpp"
#include "types/Filter.hpp"

#include "KmsMediaServer_constants.h"
#include "KmsMediaErrorCodes_constants.h"
#include "utils/utils.hpp"

#define GST_CAT_DEFAULT kurento_media_set
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoMediaSet"

using namespace kurento;

struct _AutoReleaseData {
  guint timeoutId;
  MediaSet *mediaSet;
  KmsMediaObjectId objectId;
  bool forceRemoving;
};

static gboolean
auto_release (gpointer dataPointer)
{
  AutoReleaseData *data = (AutoReleaseData *) dataPointer;

  GST_TRACE ("Auto release media object %" G_GINT64_FORMAT ", force: %d",
             data->objectId, data->forceRemoving);
  data->mediaSet->remove (data->objectId, data->forceRemoving);
  return TRUE;
}

namespace kurento
{

bool
MediaSet::canBeAutoreleased (const KmsMediaObjectRef &mediaObject)
{
  try {
    getMediaObject<MediaPad> (mediaObject);
    return false;
  } catch (const KmsMediaServerException &e) {
    return true;
  }
}

void
MediaSet::keepAlive (const KmsMediaObjectRef &mediaObject)
throw (KmsMediaServerException)
{
  std::shared_ptr<MediaObjectImpl> mo;
  std::shared_ptr<AutoReleaseData> data;
  std::map<KmsMediaObjectId, std::shared_ptr<AutoReleaseData>>::iterator it;

  if (!canBeAutoreleased (mediaObject) ) {
    GST_DEBUG ("MediaObject %" G_GINT64_FORMAT " is not auto releasable", mediaObject.id);
    return;
  }

  /* Check that object exists and it is not exluded from GC */
  mo = getMediaObject<MediaObjectImpl> (mediaObject);

  if (mo->getExcludeFromGC () ) {
    GST_DEBUG ("MediaObject %" G_GINT64_FORMAT " is excluded from GC", mediaObject.id);
    return;
  }

  mutex.lock();
  it = mediaObjectsAlive.find (mediaObject.id);

  if (it != mediaObjectsAlive.end() ) {
    data = it->second;

    if (data->timeoutId != 0)
      g_source_remove (data->timeoutId);
  }

  data->timeoutId = g_timeout_add_seconds_full (G_PRIORITY_DEFAULT,
                    mo->getGarbageCollectorPeriod() * 2, auto_release,
                    (gpointer) data.get (), NULL);
  mutex.unlock();
}

static bool
isForceRemoving (std::shared_ptr<MediaObjectImpl> mediaObject)
{
  return ! std::dynamic_pointer_cast<MediaPipeline> (mediaObject);
}

void
MediaSet::put (std::shared_ptr<MediaObjectImpl> mediaObject)
{
  std::shared_ptr<AutoReleaseData> data;
  std::map<KmsMediaObjectId, std::shared_ptr<std::set<KmsMediaObjectId>> >::iterator it;
  std::shared_ptr<std::set<KmsMediaObjectId>> children;

  mutex.lock();

  auto findIt = mediaObjectsMap.find (mediaObject->id);

  if (findIt != mediaObjectsMap.end() && findIt->second != NULL) {
    // The object is already in the mediaset
    mutex.unlock();
    return;
  }

  if (!mediaObject->getExcludeFromGC () ) {
    data = std::shared_ptr<AutoReleaseData> (new AutoReleaseData() );
    data->mediaSet = this;
    data->objectId = mediaObject->id;
    data->forceRemoving = isForceRemoving (mediaObject);
  }

  if (mediaObject->parent != NULL) {
    it = childrenMap.find (mediaObject->parent->id);

    if (it != childrenMap.end() ) {
      children = it->second;
    } else {
      children = std::shared_ptr<std::set<KmsMediaObjectId>> (new std::set<KmsMediaObjectId>() );
      childrenMap[mediaObject->parent->id] = children;
    }

    children->insert (mediaObject->id);
  }

  mediaObjectsMap[mediaObject->id] = mediaObject;

  if (!mediaObject->getExcludeFromGC () ) {
    mediaObjectsAlive[mediaObject->id] = data;
    keepAlive (*mediaObject);
  }

  mutex.unlock();
}

void
MediaSet::removeAutoRelease (const KmsMediaObjectId &id)
{
  std::shared_ptr<AutoReleaseData> data;
  std::map<KmsMediaObjectId, std::shared_ptr<AutoReleaseData>>::iterator it;

  mutex.lock();
  it = mediaObjectsAlive.find (id);

  if (it != mediaObjectsAlive.end() ) {
    data = it->second;

    if (data->timeoutId != 0)
      g_source_remove (data->timeoutId);
  }

  mediaObjectsAlive.erase (id);
  mutex.unlock();
}

void
MediaSet::remove (const KmsMediaObjectRef &mediaObject, bool force)
{
  remove (mediaObject.id, force);
}

void
MediaSet::remove (const KmsMediaObjectId &id, bool force)
{
  std::map<KmsMediaObjectId, std::shared_ptr<MediaObjectImpl> >::iterator mediaObjectsMapIt;
  std::shared_ptr<MediaObjectImpl> mo = NULL;
  std::map<KmsMediaObjectId, std::shared_ptr<std::set<KmsMediaObjectId>> >::iterator childrenMapIt;
  std::shared_ptr<std::set<KmsMediaObjectId>> children;
  std::set<KmsMediaObjectId>::iterator childrenIt;

  mutex.lock();

  childrenMapIt = childrenMap.find (id);

  if (childrenMapIt != childrenMap.end() ) {
    children = std::shared_ptr<std::set<KmsMediaObjectId>> (new std::set<KmsMediaObjectId> (* (childrenMapIt->second) ) );

    if (!force && !children->empty () ) {
      GST_DEBUG ("Media Object %ld has children and not is forcing, so it will not be removed.", id);
      mutex.unlock();
      return;
    }

    for (childrenIt = children->begin(); childrenIt != children->end(); childrenIt++) {
      remove (*childrenIt, force);
    }

    childrenMap.erase (id);
  }

  mediaObjectsMapIt = mediaObjectsMap.find (id);

  if (mediaObjectsMapIt != mediaObjectsMap.end() )
    mo = mediaObjectsMapIt->second;

  if (mo != NULL) {
    if (mo->parent != NULL) {
      childrenMapIt = childrenMap.find (mo->parent->id);

      if (childrenMapIt != childrenMap.end() ) {
        children = childrenMapIt->second;
        children->erase (mo->id);
      }
    }
  }

  mediaObjectsMap.erase (id);
  removeAutoRelease (id);
  mutex.unlock();
}

int
MediaSet::size ()
{
  int size;

  mutex.lock();
  size = mediaObjectsMap.size();
  mutex.unlock();

  return size;
}

template std::shared_ptr<MediaObjectImpl>
MediaSet::getMediaObject<MediaObjectImpl> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<MediaPipeline>
MediaSet::getMediaObject<MediaPipeline> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<MediaElement>
MediaSet::getMediaObject<MediaElement> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<MediaPad>
MediaSet::getMediaObject<MediaPad> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<MediaSrc>
MediaSet::getMediaObject<MediaSrc> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<MediaSink>
MediaSet::getMediaObject<MediaSink> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<Mixer>
MediaSet::getMediaObject<Mixer> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<UriEndPoint>
MediaSet::getMediaObject<UriEndPoint> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<HttpEndPoint>
MediaSet::getMediaObject<HttpEndPoint> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<SdpEndPoint>
MediaSet::getMediaObject<SdpEndPoint> (const KmsMediaObjectRef &mediaObject);

template std::shared_ptr<Filter>
MediaSet::getMediaObject<Filter> (const KmsMediaObjectRef &mediaObject);

template <class T> std::shared_ptr<T>
MediaSet::getMediaObject (const KmsMediaObjectRef &mediaObject)
throw (KmsMediaServerException)
{
  std::map<KmsMediaObjectId, std::shared_ptr<MediaObjectImpl> >::iterator it;
  std::shared_ptr<KmsMediaObjectRef> mo = NULL;
  std::shared_ptr<T> typedMo;

  mutex.lock();
  it = mediaObjectsMap.find (mediaObject.id);

  if (it != mediaObjectsMap.end() )
    mo = it->second;

  mutex.unlock();

  if (mo == NULL) {
    KmsMediaServerException except;

    createKmsMediaServerException (except, g_KmsMediaErrorCodes_constants.MEDIA_OBJECT_NOT_FOUND, "Media object not found");
    throw except;
  }

  typedMo = std::dynamic_pointer_cast<T> (mo);

  if (typedMo == NULL) {
    KmsMediaServerException except;

    createKmsMediaServerException (except, g_KmsMediaErrorCodes_constants.MEDIA_OBJECT_CAST_ERROR, "Media Object found is not of requested type");
    throw except;
  }

  return typedMo;
}

MediaSet::StaticConstructor MediaSet::staticConstructor;

MediaSet::StaticConstructor::StaticConstructor()
{
  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                           GST_DEFAULT_NAME);
}

} // kurento
<|endoftext|>


<commit_before>#include <ostream>
#include <string>

#include <ppl.h>
#include <boost/filesystem.hpp>

#include <CapricaConfig.h>

#include <papyrus/PapyrusResolutionContext.h>
#include <papyrus/PapyrusScript.h>
#include <papyrus/parser/PapyrusParser.h>

#include <pex/PexAsmWriter.h>
#include <pex/PexReader.h>
#include <pex/PexWriter.h>
#include <pex/parser/PexAsmParser.h>

void compileScript(std::string filename) {
  printf("Compiling %s\n", filename.c_str());
  if (boost::filesystem::extension(filename) == ".psc") {
    auto parser = new caprica::papyrus::parser::PapyrusParser(filename);
    auto a = parser->parseScript();
    delete parser;
    auto ctx = new caprica::papyrus::PapyrusResolutionContext();
    a->semantic(ctx);
    auto pex = a->buildPex();
    delete ctx;
    delete a;
    std::ofstream strm(boost::filesystem::basename(filename) + ".pex", std::ofstream::binary);
    caprica::pex::PexWriter wtr(strm);
    pex->write(wtr);

    if (caprica::CapricaConfig::dumpPexAsm) {
      std::ofstream asmStrm(boost::filesystem::basename(filename) + ".pas", std::ofstream::binary);
      caprica::pex::PexAsmWriter asmWtr(asmStrm);
      pex->writeAsm(asmWtr);
    }

    delete pex;
  } else if (boost::filesystem::extension(filename) == ".pas") {
    auto parser = new caprica::pex::parser::PexAsmParser(filename);
    auto pex = parser->parseFile();
    delete parser;
    std::ofstream strm(boost::filesystem::basename(filename) + ".pex", std::ofstream::binary);
    caprica::pex::PexWriter wtr(strm);
    pex->write(wtr);
    delete pex;
  } else if (boost::filesystem::extension(filename) == ".pex") {
    caprica::pex::PexReader rdr(filename);
    auto pex = caprica::pex::PexFile::read(rdr);
    std::ofstream asmStrm(boost::filesystem::basename(filename) + ".pas", std::ofstream::binary);
    caprica::pex::PexAsmWriter asmWtr(asmStrm);
    pex->writeAsm(asmWtr);
    delete pex;
  } else {
    printf("Don't know how to compile %s!\n", filename.c_str());
  }
}

int main(int argc, char* argv[])
{
  if (argc != 2) {
    printf("Invoke like: caprica.exe myFile.psc");
  }

  printf("Caprica Papyrus Compiler v0.0.5\n");

#ifdef NDEBUG
  try {
#endif
    std::string file = argv[1];
    if (boost::filesystem::is_directory(file)) {
      std::vector<std::string> files;
      boost::system::error_code ec;
      for (auto e : boost::filesystem::directory_iterator(file, ec)) {
        if (boost::filesystem::extension(e.path()) == ".psc" || boost::filesystem::extension(e.path()) == ".pas")
          files.push_back(e.path().string());
      }

      if (caprica::CapricaConfig::compileInParallel) {
        concurrency::parallel_for_each(files.begin(), files.end(), [](std::string fl) {
          compileScript(fl);
        });
      } else {
        for (auto& file : files)
          compileScript(file);
      }
    } else {
      compileScript(file);
    }
#ifdef NDEBUG
  } catch (std::runtime_error err) {
    printf("%s", err.what());
    getchar();
  }
#endif

  return 0;
}

<commit_msg>Bump the version number.<commit_after>#include <ostream>
#include <string>

#include <ppl.h>
#include <boost/filesystem.hpp>

#include <CapricaConfig.h>

#include <papyrus/PapyrusResolutionContext.h>
#include <papyrus/PapyrusScript.h>
#include <papyrus/parser/PapyrusParser.h>

#include <pex/PexAsmWriter.h>
#include <pex/PexReader.h>
#include <pex/PexWriter.h>
#include <pex/parser/PexAsmParser.h>

void compileScript(std::string filename) {
  printf("Compiling %s\n", filename.c_str());
  if (boost::filesystem::extension(filename) == ".psc") {
    auto parser = new caprica::papyrus::parser::PapyrusParser(filename);
    auto a = parser->parseScript();
    delete parser;
    auto ctx = new caprica::papyrus::PapyrusResolutionContext();
    a->semantic(ctx);
    auto pex = a->buildPex();
    delete ctx;
    delete a;
    std::ofstream strm(boost::filesystem::basename(filename) + ".pex", std::ofstream::binary);
    caprica::pex::PexWriter wtr(strm);
    pex->write(wtr);

    if (caprica::CapricaConfig::dumpPexAsm) {
      std::ofstream asmStrm(boost::filesystem::basename(filename) + ".pas", std::ofstream::binary);
      caprica::pex::PexAsmWriter asmWtr(asmStrm);
      pex->writeAsm(asmWtr);
    }

    delete pex;
  } else if (boost::filesystem::extension(filename) == ".pas") {
    auto parser = new caprica::pex::parser::PexAsmParser(filename);
    auto pex = parser->parseFile();
    delete parser;
    std::ofstream strm(boost::filesystem::basename(filename) + ".pex", std::ofstream::binary);
    caprica::pex::PexWriter wtr(strm);
    pex->write(wtr);
    delete pex;
  } else if (boost::filesystem::extension(filename) == ".pex") {
    caprica::pex::PexReader rdr(filename);
    auto pex = caprica::pex::PexFile::read(rdr);
    std::ofstream asmStrm(boost::filesystem::basename(filename) + ".pas", std::ofstream::binary);
    caprica::pex::PexAsmWriter asmWtr(asmStrm);
    pex->writeAsm(asmWtr);
    delete pex;
  } else {
    printf("Don't know how to compile %s!\n", filename.c_str());
  }
}

int main(int argc, char* argv[])
{
  if (argc != 2) {
    printf("Invoke like: caprica.exe myFile.psc");
  }

  printf("Caprica Papyrus Compiler v0.0.6\n");

#ifdef NDEBUG
  try {
#endif
    std::string file = argv[1];
    if (boost::filesystem::is_directory(file)) {
      std::vector<std::string> files;
      boost::system::error_code ec;
      for (auto e : boost::filesystem::directory_iterator(file, ec)) {
        if (boost::filesystem::extension(e.path()) == ".psc" || boost::filesystem::extension(e.path()) == ".pas")
          files.push_back(e.path().string());
      }

      if (caprica::CapricaConfig::compileInParallel) {
        concurrency::parallel_for_each(files.begin(), files.end(), [](std::string fl) {
          compileScript(fl);
        });
      } else {
        for (auto& file : files)
          compileScript(file);
      }
    } else {
      compileScript(file);
    }
#ifdef NDEBUG
  } catch (std::runtime_error err) {
    printf("%s", err.what());
    getchar();
  }
#endif

  return 0;
}

<|endoftext|>


<commit_before>#include "ofApp.h"

const float eyeRadius = 14, corneaScale = .5;
void drawEye(ofVec3f position, ofVec2f orientation = ofVec2f()) {
	ofPushMatrix();
	ofTranslate(position);
	// i'm not sure if this rotation is mapped correctly
	ofRotateY(orientation.y);
	ofRotateX(orientation.x);
	ofSphere(eyeRadius);
	ofTranslate(0, 0, -eyeRadius * (1.1 - corneaScale));
	ofSphere(eyeRadius * corneaScale);
	ofPopMatrix();
}

void ofApp::setup() {
	ofSetDrawBitmapMode(OF_BITMAPMODE_MODEL_BILLBOARD);
	ofSetVerticalSync(true);
	faceShift.setup();
	faceShift.import("export");

	light.enable();
	light.setPosition(+500, +500, +500);
}

void ofApp::update() {
	faceShift.update();
}

void ofApp::draw(){
	ofBackground(128);
	ofSetColor(255);

	cam.begin();
	glEnable(GL_DEPTH_TEST);
	ofFill();
	ofRotateX(180);
	ofTranslate(faceShift.getPosition());
	ofScale(-1, 1, 1); // for some reason the rotation matrix x is flipped
	glMultMatrixf((GLfloat*) faceShift.getRotationMatrix().getPtr());
	ofScale(-1, 1, 1); // then we flip it back

	ofEnableLighting();
	faceShift.getBlendMesh().draw();
	drawEye(faceShift.getLeftEyeOffset(), faceShift.getLeftEyeRotation());
	drawEye(faceShift.getRightEyeOffset(), faceShift.getRightEyeRotation());

	ofDisableLighting();
	ofSetColor(0);
	faceShift.getBlendMesh().drawWireframe();

	cam.end();
}
<commit_msg>removed eyes, simplified a bit<commit_after>#include "ofApp.h"

void ofApp::setup() {
	ofSetVerticalSync(true);
	faceShift.setup();
	faceShift.import("export");

	light.enable();
	light.setPosition(+500, +500, +500);
}

void ofApp::update() {
	faceShift.update();
}

void ofApp::draw(){
	ofBackground(128);

	cam.begin();
	glEnable(GL_DEPTH_TEST);
	ofRotateX(180);
	ofTranslate(faceShift.getPosition());
	ofScale(-1, 1, 1); // for some reason the rotation matrix x is flipped
	glMultMatrixf((GLfloat*) faceShift.getRotationMatrix().getPtr());
	ofScale(-1, 1, 1); // then we flip it back

	ofEnableLighting();
	ofSetColor(255);
	faceShift.getBlendMesh().draw();

	ofDisableLighting();
	ofSetColor(0);
	faceShift.getBlendMesh().drawWireframe();

	cam.end();
}
<|endoftext|>