<commit_before>/*
 * InitWeights.cpp
 *
 *  Created on: Aug 5, 2011
 *      Author: kpeterson
 */

#include "InitWeights.hpp"

#include <stdlib.h>

#include "../include/default_params.h"
#include "../io/ConnectionProbe.hpp"
#include "../io/io.h"
#include "../io/fileio.hpp"
#include "../utils/conversions.h"
#include "../utils/pv_random.h"
#include "../columns/InterColComm.hpp"
#include "InitGauss2DWeightsParams.hpp"

namespace PV {

InitWeights::InitWeights()
{
   initialize_base();
}

//InitWeights::InitWeights(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
//      ChannelType channel)
//{
//   initialize_base();
//   initialize(name, hc, pre, post, channel);
//}

InitWeights::~InitWeights()
{
   // TODO Auto-generated destructor stub
}

/*This method does the three steps involved in initializing weights.  Subclasses shouldn't touch this method.
 * Subclasses should only generate their own versions of calcWeights to do their own type of weight initialization.
 *
 * This method first calls XXX to create an unshrunk patch.  Then it calls calcWeights to initialize
 * the weights for that unshrunk patch.  Finally it copies the weights back to the original, possibly shrunk patch.
 */
PVPatch ** InitWeights::initializeWeights(PVPatch ** patches, int numPatches, const char * filename, HyPerConn * callingConn) {

   //parentConn = callingConn;

   InitWeightsParams *weightParams = createNewWeightParams(callingConn);

   if( filename != NULL ) {
      //check status?
      readWeights(patches, numPatches, filename, callingConn);
   }
   else {
      //allocate unshrunk patch method
      for (int patchIndex = 0; patchIndex < numPatches; patchIndex++) {

         //create full sized patch:
         PVPatch * wp_tmp = createUnShrunkenPatch(callingConn, patches[patchIndex]);

         //calc weights for patch:
         int successFlag = calcWeights(wp_tmp, patchIndex, weightParams);
         if (successFlag != 1) {
            fprintf(stderr, "Failed to create weights! Exiting...");
            exit(1);
         }

         //copy back to unshrunk patch:
         copyToOriginalPatch(patches[patchIndex], wp_tmp);

      }

      //call copy weights to original possibly shrunk patch method...
   }

   delete(weightParams);
   return patches;

}

InitWeightsParams * InitWeights::createNewWeightParams(HyPerConn * callingConn) {
   InitWeightsParams * tempPtr = new InitGauss2DWeightsParams(callingConn);
   return tempPtr;
}

int InitWeights::calcWeights(PVPatch * patch, int patchIndex,
                               InitWeightsParams *weightParams) {

    InitGauss2DWeightsParams *weightParamPtr = dynamic_cast<InitGauss2DWeightsParams*> (weightParams);

    if(weightParamPtr==NULL) {
       fprintf(stderr, "Failed to recast pointer to weightsParam!  Exiting...");
       exit(1);
    }

    weightParamPtr->calcOtherParams(patch, patchIndex);

    //calculate the weights:
    gauss2DCalcWeights(patch, weightParamPtr);

    return 1;
}

int InitWeights::initialize_base() {

   return 1;
}

//int InitWeights::initialize(const char * name, HyPerCol * hc,
//               HyPerLayer * pre, HyPerLayer * post,
//               ChannelType channel) {
//   int status = PV_SUCCESS;
//
//   this->parent = hc;
//   this->pre = pre;
//   this->post = post;
//   this->channel = channel;
//
//   this->name = strdup(name);
//
//   return status;
//
//}
//
int InitWeights::readWeights(PVPatch ** patches, int numPatches, const char * filename, HyPerConn * callingConn)
{
   HyPerCol *parent = callingConn->getParent();
   HyPerLayer *pre = callingConn->getPre();
   double time;
   int status = PV::readWeights(patches, numPatches, filename, parent->icCommunicator(),
                                &time, pre->getLayerLoc(), true);

   if (status != 0) {
      fprintf(stderr, "PV::HyPerConn::readWeights: problem reading weight file %s, SHUTTING DOWN\n", filename);
      exit(1);
   }

   return 1;
}

/*
 * Create a full sized patch for a potentially shrunken patch. This full sized patch will be used for initializing weights and will later be copied back to
 * the original.
 *
 */
PVPatch * InitWeights::createUnShrunkenPatch(HyPerConn * callingConn, PVPatch * wp) {
   // get dimensions of (potentially shrunken patch)
   const int nxPatch = wp->nx;
   const int nyPatch = wp->ny;
   const int nfPatch = wp->nf;
   if (nxPatch * nyPatch * nfPatch == 0) {
      return 0; // reduced patch size is zero
   }

   // get strides of (potentially shrunken) patch
   const int sx = wp->sx;
   assert(sx == nfPatch);
   //const int sy = wp->sy; // no assert here because patch may be shrunken
   const int sf = wp->sf;
   assert(sf == 1);

   // make full sized temporary patch, positioned around center of unit cell
   PVPatch * wp_tmp;
   wp_tmp = pvpatch_inplace_new(callingConn->xPatchSize(), callingConn->yPatchSize(), callingConn->fPatchSize());

   return wp_tmp;
}

/*
 * Copy from full sized patch back to potentially shrunken patch.
 *
 */
int InitWeights::copyToOriginalPatch(PVPatch * wp, PVPatch * wp_tmp) {
   // copy weights from full sized temporary patch to (possibly shrunken) patch
   pvdata_t * w = wp->data;
   const int nxPatch = wp->nx;
   const int nyPatch = wp->ny;
   const int nfPatch = wp->nf;

   const int sy = wp->sy; // no assert here because patch may be shrunken
   const int sy_tmp = wp_tmp->sy;

   pvdata_t * data_head =  (pvdata_t *) ((char*) wp + sizeof(PVPatch));
   size_t data_offset = w - data_head;
   pvdata_t * w_tmp = &wp_tmp->data[data_offset];
   int nk = nxPatch * nfPatch;
   for (int ky = 0; ky < nyPatch; ky++) {
      for (int iWeight = 0; iWeight < nk; iWeight++) {
         w[iWeight] = w_tmp[iWeight];
      }
      w += sy;
      w_tmp += sy_tmp;
   }

   free(wp_tmp);

   return 1;
}

/**
 * calculate gaussian weights to segment lines
 */
int InitWeights::gauss2DCalcWeights(PVPatch * patch, InitGauss2DWeightsParams * weightParamPtr) {

   //load necessary params:
   int nfPatch_tmp = weightParamPtr->getnfPatch_tmp();
   int nyPatch_tmp = weightParamPtr->getnyPatch_tmp();
   int nxPatch_tmp = weightParamPtr->getnxPatch_tmp();
   float aspect=weightParamPtr->getaspect();
   float shift=weightParamPtr->getshift();
   int numFlanks=weightParamPtr->getnumFlanks();
   float sigma=weightParamPtr->getsigma();
   int sx_tmp=weightParamPtr->getsx_tmp();
   int sy_tmp=weightParamPtr->getsy_tmp();
   int sf_tmp=weightParamPtr->getsf_tmp();
   float r2Max=weightParamPtr->getr2Max();

   pvdata_t * w_tmp = patch->data;

   // loop over all post-synaptic cells in temporary patch
   for (int fPost = 0; fPost < nfPatch_tmp; fPost++) {
      float thPost = weightParamPtr->calcThPost(fPost);
      //TODO: add additional weight factor for difference between thPre and thPost
      if(weightParamPtr->checkTheta(thPost)) continue;
      for (int jPost = 0; jPost < nyPatch_tmp; jPost++) {
         float yDelta = weightParamPtr->calcYDelta(jPost);
         for (int iPost = 0; iPost < nxPatch_tmp; iPost++) {
            float xDelta = weightParamPtr->calcXDelta(iPost);

            if(weightParamPtr->isSameLocOrSelf(xDelta, yDelta, fPost)) continue;

            // rotate the reference frame by th (change sign of thPost?)
            float xp = +xDelta * cosf(thPost) + yDelta * sinf(thPost);
            float yp = -xDelta * sinf(thPost) + yDelta * cosf(thPost);

            if(weightParamPtr->checkBowtieAngle(yp, xp)) continue;

            // include shift to flanks
            float d2 = xp * xp + (aspect * (yp - shift) * aspect * (yp - shift));
            int index = iPost * sx_tmp + jPost * sy_tmp + fPost * sf_tmp;
            w_tmp[index] = 0;
            if (d2 <= r2Max) {
               w_tmp[index] += expf(-d2 / (2.0f * sigma * sigma));
            }
            if (numFlanks > 1) {
               // shift in opposite direction
               d2 = xp * xp + (aspect * (yp + shift) * aspect * (yp + shift));
               if (d2 <= r2Max) {
                  w_tmp[index] += expf(-d2 / (2.0f * sigma * sigma));
               }
            }
         }
      }
   }

   return 0;
}

} /* namespace PV */
<commit_msg>moved creation of weight params object into if block for Gauss2D weights, avoids warning when init from file<commit_after>/*
 * InitWeights.cpp
 *
 *  Created on: Aug 5, 2011
 *      Author: kpeterson
 */

#include "InitWeights.hpp"

#include <stdlib.h>

#include "../include/default_params.h"
#include "../io/ConnectionProbe.hpp"
#include "../io/io.h"
#include "../io/fileio.hpp"
#include "../utils/conversions.h"
#include "../utils/pv_random.h"
#include "../columns/InterColComm.hpp"
#include "InitGauss2DWeightsParams.hpp"

namespace PV {

InitWeights::InitWeights()
{
   initialize_base();
}

//InitWeights::InitWeights(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
//      ChannelType channel)
//{
//   initialize_base();
//   initialize(name, hc, pre, post, channel);
//}

InitWeights::~InitWeights()
{
   // TODO Auto-generated destructor stub
}

/*This method does the three steps involved in initializing weights.  Subclasses shouldn't touch this method.
 * Subclasses should only generate their own versions of calcWeights to do their own type of weight initialization.
 *
 * This method first calls XXX to create an unshrunk patch.  Then it calls calcWeights to initialize
 * the weights for that unshrunk patch.  Finally it copies the weights back to the original, possibly shrunk patch.
 */
PVPatch ** InitWeights::initializeWeights(PVPatch ** patches, int numPatches, const char * filename, HyPerConn * callingConn) {

   //parentConn = callingConn;

   InitWeightsParams *weightParams = NULL;

   if( filename != NULL ) {
      //check status?
      readWeights(patches, numPatches, filename, callingConn);
   }
   else {
      weightParams = createNewWeightParams(callingConn);
      //allocate unshrunk patch method
      for (int patchIndex = 0; patchIndex < numPatches; patchIndex++) {

         //create full sized patch:
         PVPatch * wp_tmp = createUnShrunkenPatch(callingConn, patches[patchIndex]);

         //calc weights for patch:
         int successFlag = calcWeights(wp_tmp, patchIndex, weightParams);
         if (successFlag != 1) {
            fprintf(stderr, "Failed to create weights! Exiting...");
            exit(1);
         }

         //copy back to unshrunk patch:
         copyToOriginalPatch(patches[patchIndex], wp_tmp);

      }

      delete(weightParams);
   }

   return patches;

}

InitWeightsParams * InitWeights::createNewWeightParams(HyPerConn * callingConn) {
   InitWeightsParams * tempPtr = new InitGauss2DWeightsParams(callingConn);
   return tempPtr;
}

int InitWeights::calcWeights(PVPatch * patch, int patchIndex,
                               InitWeightsParams *weightParams) {

    InitGauss2DWeightsParams *weightParamPtr = dynamic_cast<InitGauss2DWeightsParams*> (weightParams);

    if(weightParamPtr==NULL) {
       fprintf(stderr, "Failed to recast pointer to weightsParam!  Exiting...");
       exit(1);
    }

    weightParamPtr->calcOtherParams(patch, patchIndex);

    //calculate the weights:
    gauss2DCalcWeights(patch, weightParamPtr);

    return 1;
}

int InitWeights::initialize_base() {

   return 1;
}

//int InitWeights::initialize(const char * name, HyPerCol * hc,
//               HyPerLayer * pre, HyPerLayer * post,
//               ChannelType channel) {
//   int status = PV_SUCCESS;
//
//   this->parent = hc;
//   this->pre = pre;
//   this->post = post;
//   this->channel = channel;
//
//   this->name = strdup(name);
//
//   return status;
//
//}
//
int InitWeights::readWeights(PVPatch ** patches, int numPatches, const char * filename, HyPerConn * callingConn)
{
   HyPerCol *parent = callingConn->getParent();
   HyPerLayer *pre = callingConn->getPre();
   double time;
   int status = PV::readWeights(patches, numPatches, filename, parent->icCommunicator(),
                                &time, pre->getLayerLoc(), true);

   if (status != 0) {
      fprintf(stderr, "PV::HyPerConn::readWeights: problem reading weight file %s, SHUTTING DOWN\n", filename);
      exit(1);
   }

   return 1;
}

/*
 * Create a full sized patch for a potentially shrunken patch. This full sized patch will be used for initializing weights and will later be copied back to
 * the original.
 *
 */
PVPatch * InitWeights::createUnShrunkenPatch(HyPerConn * callingConn, PVPatch * wp) {
   // get dimensions of (potentially shrunken patch)
   const int nxPatch = wp->nx;
   const int nyPatch = wp->ny;
   const int nfPatch = wp->nf;
   if (nxPatch * nyPatch * nfPatch == 0) {
      return 0; // reduced patch size is zero
   }

   // get strides of (potentially shrunken) patch
   const int sx = wp->sx;
   assert(sx == nfPatch);
   //const int sy = wp->sy; // no assert here because patch may be shrunken
   const int sf = wp->sf;
   assert(sf == 1);

   // make full sized temporary patch, positioned around center of unit cell
   PVPatch * wp_tmp;
   wp_tmp = pvpatch_inplace_new(callingConn->xPatchSize(), callingConn->yPatchSize(), callingConn->fPatchSize());

   return wp_tmp;
}

/*
 * Copy from full sized patch back to potentially shrunken patch.
 *
 */
int InitWeights::copyToOriginalPatch(PVPatch * wp, PVPatch * wp_tmp) {
   // copy weights from full sized temporary patch to (possibly shrunken) patch
   pvdata_t * w = wp->data;
   const int nxPatch = wp->nx;
   const int nyPatch = wp->ny;
   const int nfPatch = wp->nf;

   const int sy = wp->sy; // no assert here because patch may be shrunken
   const int sy_tmp = wp_tmp->sy;

   pvdata_t * data_head =  (pvdata_t *) ((char*) wp + sizeof(PVPatch));
   size_t data_offset = w - data_head;
   pvdata_t * w_tmp = &wp_tmp->data[data_offset];
   int nk = nxPatch * nfPatch;
   for (int ky = 0; ky < nyPatch; ky++) {
      for (int iWeight = 0; iWeight < nk; iWeight++) {
         w[iWeight] = w_tmp[iWeight];
      }
      w += sy;
      w_tmp += sy_tmp;
   }

   free(wp_tmp);

   return 1;
}

/**
 * calculate gaussian weights to segment lines
 */
int InitWeights::gauss2DCalcWeights(PVPatch * patch, InitGauss2DWeightsParams * weightParamPtr) {

   //load necessary params:
   int nfPatch_tmp = weightParamPtr->getnfPatch_tmp();
   int nyPatch_tmp = weightParamPtr->getnyPatch_tmp();
   int nxPatch_tmp = weightParamPtr->getnxPatch_tmp();
   float aspect=weightParamPtr->getaspect();
   float shift=weightParamPtr->getshift();
   int numFlanks=weightParamPtr->getnumFlanks();
   float sigma=weightParamPtr->getsigma();
   int sx_tmp=weightParamPtr->getsx_tmp();
   int sy_tmp=weightParamPtr->getsy_tmp();
   int sf_tmp=weightParamPtr->getsf_tmp();
   float r2Max=weightParamPtr->getr2Max();

   pvdata_t * w_tmp = patch->data;

   // loop over all post-synaptic cells in temporary patch
   for (int fPost = 0; fPost < nfPatch_tmp; fPost++) {
      float thPost = weightParamPtr->calcThPost(fPost);
      //TODO: add additional weight factor for difference between thPre and thPost
      if(weightParamPtr->checkTheta(thPost)) continue;
      for (int jPost = 0; jPost < nyPatch_tmp; jPost++) {
         float yDelta = weightParamPtr->calcYDelta(jPost);
         for (int iPost = 0; iPost < nxPatch_tmp; iPost++) {
            float xDelta = weightParamPtr->calcXDelta(iPost);

            if(weightParamPtr->isSameLocOrSelf(xDelta, yDelta, fPost)) continue;

            // rotate the reference frame by th (change sign of thPost?)
            float xp = +xDelta * cosf(thPost) + yDelta * sinf(thPost);
            float yp = -xDelta * sinf(thPost) + yDelta * cosf(thPost);

            if(weightParamPtr->checkBowtieAngle(yp, xp)) continue;

            // include shift to flanks
            float d2 = xp * xp + (aspect * (yp - shift) * aspect * (yp - shift));
            int index = iPost * sx_tmp + jPost * sy_tmp + fPost * sf_tmp;
            w_tmp[index] = 0;
            if (d2 <= r2Max) {
               w_tmp[index] += expf(-d2 / (2.0f * sigma * sigma));
            }
            if (numFlanks > 1) {
               // shift in opposite direction
               d2 = xp * xp + (aspect * (yp + shift) * aspect * (yp + shift));
               if (d2 <= r2Max) {
                  w_tmp[index] += expf(-d2 / (2.0f * sigma * sigma));
               }
            }
         }
      }
   }

   return 0;
}

} /* namespace PV */
<|endoftext|>


<commit_before>// Fill out your copyright notice in the Description page of Project Settings.

#include "UE4_TurnBased.h"
#include "TB_AimComponent.h"
#include "TB_Character.h"
#include "TB_Weapon.h"
#include "TB_Library.h"

#include <algorithm>
#include <cmath>

void UTB_AimComponent::UpdateValues()
{
	Character = (ATB_Character *)GetAttachmentRootActor();
	Weapon = Character->Weapon;

	if (EnemyTarget && Weapon)
	{
		// Base Values
		FinalHitChance = Character->RangedAttackSkill;
		FinalDamage = Weapon->BaseDamage;

		// Range
		RangeToTarget = Character->GetDistanceTo(EnemyTarget);
		RangeHitModifier = Weapon->HitModifier(RangeToTarget);
		FinalHitChance += RangeHitModifier;
		RangeDamageModifier = Weapon->DamageModifier(RangeToTarget);
		FinalDamage += RangeDamageModifier;

		// Cover
		CoverHitModifier = CoverModifier(EnemyTarget);
		FinalHitChance += CoverHitModifier;
		CoverDamageModifier = 0;

		// Final sanity check
		FinalHitChance = std::max(0, FinalHitChance);
		if (FinalDamage < 0)
		{
			FinalDamage = 0;
		}
	}
	else
	{
		RangeToTarget = 0;

		RangeHitModifier = 0;
		RangeDamageModifier = 0;
		CoverHitModifier = 0;
		CoverDamageModifier = 0;

		FinalHitChance = 0;
		FinalDamage = 0;
	}
}

int32 UTB_AimComponent::CoverModifier(ATB_Character *Target)
{
	UWorld *World = GetWorld();

	// Ignore collisions with the aiming character and its weapon
	FCollisionQueryParams Params;
	Params.bTraceComplex = true;
	Params.AddIgnoredActor(Character);
	if (Weapon)
	{
		Params.AddIgnoredActor(Weapon);
	}
	if (Target->Weapon)
	{
		Params.AddIgnoredActor(Target->Weapon);
	}

	// uncomment to draw debug lines
	/*
	FName TraceTag("CoverTrace");
	World->DebugDrawTraceTag = TraceTag;
	Params.TraceTag = TraceTag;
	*/
	FCollisionObjectQueryParams ObjectParams;

	FHitResult HitResult;
	TArray<FVector> HitLocations;
	Target->GetHitLocations(HitLocations);
	FVector StartLocation = GetComponentLocation();

	int Hidden = 0;
	for (auto HitLocation : HitLocations)
	{
		bool HitSomething = World->LineTraceSingle(HitResult, StartLocation, HitLocation, Params, ObjectParams);
		if (HitSomething && Target->GetUniqueID() != HitResult.Actor->GetUniqueID())
		{
			Hidden++;
		}
	}

	if (Hidden < HitLocations.Num())
	{
		// reduce cover by half if we can see the enemy at all
		// a penalty above 60 makes an enemy virtually impossible to hit
		Hidden -= (Hidden / 3);
	}
	return (Hidden * -100) / std::max(HitLocations.Num(), 1);
}

void UTB_AimComponent::TargetNextEnemy()
{

	if (VisibleEnemies.Num())
	{
		int32 Index = VisibleEnemies.Find(EnemyTarget); //INDEX_NONE (-1) if not found
		Index = (Index + 1) % VisibleEnemies.Num();
		EnemyTarget = VisibleEnemies[Index];
	}
	else
	{
		EnemyTarget = NULL;
	}
}

void UTB_AimComponent::UpdateVisibleEnemies()
{
	VisibleEnemies.Empty();
	Character = (ATB_Character *)GetAttachmentRootActor();
	Weapon = Character->Weapon;

	bool EnemyTargetVisible = false;

	for (TActorIterator<ATB_Character> Iter(GetWorld(), ATB_Character::StaticClass()); Iter; ++Iter)
	{
		ATB_Character *Enemy = *Iter;
		if (Enemy->HitPoints > 0 &&
			Enemy->TeamName != Character->TeamName &&
			CoverModifier(Enemy) > -100)
		{
			VisibleEnemies.Add(Enemy);
			if (Enemy == EnemyTarget)
			{
				EnemyTargetVisible = true;
			}
		}
	}

	if (!EnemyTargetVisible)
	{
		EnemyTarget = NULL;
	}
}

void UTB_AimComponent::HitLineTrace(FHitResult &OutHit)
{
	if (!EnemyTarget)
	{
		UE_LOG(TB_Log, Error, TEXT("HitLineTrace(): EnemyTarget == NULL"));
		return;
	}

	//find the hit locations
	TArray<FVector> HitLocations;
	EnemyTarget->GetHitLocations(HitLocations);

	// shuffle them and do line traces until we get a hit
	UTB_Library::Shuffle(HitLocations);

	FCollisionQueryParams Params;
	InitCollisionQueryParams(Params);
	FCollisionObjectQueryParams ObjectParams;
	FVector StartLocation = GetComponentLocation();

	for (auto HitLocation : HitLocations)
	{
		bool HitSomething = World->LineTraceSingle(OutHit, StartLocation, HitLocation, Params, ObjectParams);
		if (HitSomething && EnemyTarget->GetUniqueID() == OutHit.Actor->GetUniqueID())
		{
			return;
		}
	}
	UE_LOG(TB_Log, Error, TEXT("HitLineTrace(): Could not find a hitting line trace"));
}

bool UTB_AimComponent::MissLineTrace(FHitResult &OutHit)
{
	if (!EnemyTarget)
	{
		UE_LOG(TB_Log, Error, TEXT("MissLineTrace(): EnemyTarget == NULL"));
		return false;
	}

	//Pick a HitLocation at random
	TArray<FVector> HitLocations;
	EnemyTarget->GetHitLocations(HitLocations);
	UTB_Library::Shuffle(HitLocations);

	FCollisionQueryParams Params;
	InitCollisionQueryParams(Params);
	FCollisionObjectQueryParams ObjectParams;
	FVector StartLocation = GetComponentLocation();

	float Offset = 30;

	for (auto HitLocation : HitLocations)
	{
		bool HitSomething = World->LineTraceSingle(OutHit, StartLocation, HitLocation, Params, ObjectParams);
		if (HitSomething)
		{
			if (EnemyTarget->GetUniqueID() != OutHit.Actor->GetUniqueID())
			{
				//we've hit something we didn't aim for \o/
				return true;
			}
			else
			{
				//get our direction and rotate it so we miss by Offest UUs
				FVector Direction;
				float Length;
				(StartLocation - HitLocation).ToDirectionAndLength(Direction, Length);
				float OffsetRad = atan2f(Offset, Length);
				FRotator Rotator(0, OffsetRad * 180 / PI, 0);
				if (FMath::FRand() < 0.5f)
				{
					Rotator *= -1;
				}
				FVector AdjustedDirection = Rotator.RotateVector(Direction);
				//use the weapon range as length
				AdjustedDirection *= Weapon->MaxRange;
				//ensure that we dont hit the target
				HitSomething = World->LineTraceSingle(OutHit, StartLocation, StartLocation + AdjustedDirection, Params, ObjectParams);
				if (HitSomething && EnemyTarget->GetUniqueID() != OutHit.Actor->GetUniqueID())
				{
					//we're still hitting the target, pray that we'll miss it when we look at the other targetpoints
					continue;
				}
				else
				{
					return HitSomething;
				}

			}
		}
	}

	UE_LOG(TB_Log, Warning, TEXT("MissLineTrace(): Can't find a way to miss"));
	return false;
}
void UTB_AimComponent::InitCollisionQueryParams(FCollisionQueryParams &Params)
{
	// remember to set the physical material in phat for skeletal meshes
	// (the collision channels for the character might also need to be tuned)
	Params.bTraceComplex = true;
	Params.bReturnPhysicalMaterial = true;

	// Ignore collisions with the aiming character and its weapon
	Params.AddIgnoredActor(Character);
	if (Weapon)
	{
		Params.AddIgnoredActor(Weapon);
	}
	if (EnemyTarget->Weapon)
	{
		Params.AddIgnoredActor(EnemyTarget->Weapon);
	}
}<commit_msg>a working MissLineTrace()<commit_after>// Fill out your copyright notice in the Description page of Project Settings.

#include "UE4_TurnBased.h"
#include "TB_AimComponent.h"
#include "TB_Character.h"
#include "TB_Weapon.h"
#include "TB_Library.h"

#include <algorithm>
#include <cmath>

void UTB_AimComponent::UpdateValues()
{
	Character = (ATB_Character *)GetAttachmentRootActor();
	Weapon = Character->Weapon;

	if (EnemyTarget && Weapon)
	{
		// Base Values
		FinalHitChance = Character->RangedAttackSkill;
		FinalDamage = Weapon->BaseDamage;

		// Range
		RangeToTarget = Character->GetDistanceTo(EnemyTarget);
		RangeHitModifier = Weapon->HitModifier(RangeToTarget);
		FinalHitChance += RangeHitModifier;
		RangeDamageModifier = Weapon->DamageModifier(RangeToTarget);
		FinalDamage += RangeDamageModifier;

		// Cover
		CoverHitModifier = CoverModifier(EnemyTarget);
		FinalHitChance += CoverHitModifier;
		CoverDamageModifier = 0;

		// Final sanity check
		FinalHitChance = std::max(0, FinalHitChance);
		if (FinalDamage < 0)
		{
			FinalDamage = 0;
		}
	}
	else
	{
		RangeToTarget = 0;

		RangeHitModifier = 0;
		RangeDamageModifier = 0;
		CoverHitModifier = 0;
		CoverDamageModifier = 0;

		FinalHitChance = 0;
		FinalDamage = 0;
	}
}

int32 UTB_AimComponent::CoverModifier(ATB_Character *Target)
{
	UWorld *World = GetWorld();

	// Ignore collisions with the aiming character and its weapon
	FCollisionQueryParams Params;
	Params.bTraceComplex = true;
	Params.AddIgnoredActor(Character);
	if (Weapon)
	{
		Params.AddIgnoredActor(Weapon);
	}
	if (Target->Weapon)
	{
		Params.AddIgnoredActor(Target->Weapon);
	}

	// uncomment to draw debug lines
	/*
	FName TraceTag("CoverTrace");
	World->DebugDrawTraceTag = TraceTag;
	Params.TraceTag = TraceTag;
	*/
	FCollisionObjectQueryParams ObjectParams;

	FHitResult HitResult;
	TArray<FVector> HitLocations;
	Target->GetHitLocations(HitLocations);
	FVector StartLocation = GetComponentLocation();

	int Hidden = 0;
	for (auto HitLocation : HitLocations)
	{
		bool HitSomething = World->LineTraceSingle(HitResult, StartLocation, HitLocation, Params, ObjectParams);
		if (HitSomething && Target->GetUniqueID() != HitResult.Actor->GetUniqueID())
		{
			Hidden++;
		}
	}

	if (Hidden < HitLocations.Num())
	{
		// reduce cover by half if we can see the enemy at all
		// a penalty above 60 makes an enemy virtually impossible to hit
		Hidden -= (Hidden / 3);
	}
	return (Hidden * -100) / std::max(HitLocations.Num(), 1);
}

void UTB_AimComponent::TargetNextEnemy()
{

	if (VisibleEnemies.Num())
	{
		int32 Index = VisibleEnemies.Find(EnemyTarget); //INDEX_NONE (-1) if not found
		Index = (Index + 1) % VisibleEnemies.Num();
		EnemyTarget = VisibleEnemies[Index];
	}
	else
	{
		EnemyTarget = NULL;
	}
}

void UTB_AimComponent::UpdateVisibleEnemies()
{
	VisibleEnemies.Empty();
	Character = (ATB_Character *)GetAttachmentRootActor();
	Weapon = Character->Weapon;

	bool EnemyTargetVisible = false;

	for (TActorIterator<ATB_Character> Iter(GetWorld(), ATB_Character::StaticClass()); Iter; ++Iter)
	{
		ATB_Character *Enemy = *Iter;
		if (Enemy->HitPoints > 0 &&
			Enemy->TeamName != Character->TeamName &&
			CoverModifier(Enemy) > -100)
		{
			VisibleEnemies.Add(Enemy);
			if (Enemy == EnemyTarget)
			{
				EnemyTargetVisible = true;
			}
		}
	}

	if (!EnemyTargetVisible)
	{
		EnemyTarget = NULL;
	}
}

void UTB_AimComponent::HitLineTrace(FHitResult &OutHit)
{
	if (!EnemyTarget)
	{
		UE_LOG(TB_Log, Error, TEXT("HitLineTrace(): EnemyTarget == NULL"));
		return;
	}

	//find the hit locations
	TArray<FVector> HitLocations;
	EnemyTarget->GetHitLocations(HitLocations);

	// shuffle them and do line traces until we get a hit
	UTB_Library::Shuffle(HitLocations);

	FCollisionQueryParams Params;
	InitCollisionQueryParams(Params);
	FCollisionObjectQueryParams ObjectParams;
	FVector StartLocation = GetComponentLocation();

	for (auto HitLocation : HitLocations)
	{
		bool HitSomething = World->LineTraceSingle(OutHit, StartLocation, HitLocation, Params, ObjectParams);
		if (HitSomething && EnemyTarget->GetUniqueID() == OutHit.Actor->GetUniqueID())
		{
			return;
		}
	}
	UE_LOG(TB_Log, Error, TEXT("HitLineTrace(): Could not find a hitting line trace"));
}

bool UTB_AimComponent::MissLineTrace(FHitResult &OutHit)
{
	if (!EnemyTarget)
	{
		UE_LOG(TB_Log, Error, TEXT("MissLineTrace(): EnemyTarget == NULL"));
		return false;
	}

	//Pick a HitLocation at random
	TArray<FVector> HitLocations;
	EnemyTarget->GetHitLocations(HitLocations);
	UTB_Library::Shuffle(HitLocations);

	FCollisionQueryParams Params;
	InitCollisionQueryParams(Params);
	FCollisionObjectQueryParams ObjectParams;
	FVector StartLocation = GetComponentLocation();

	float Offset = 30;

	for (auto HitLocation : HitLocations)
	{
		bool HitSomething = World->LineTraceSingle(OutHit, StartLocation, HitLocation, Params, ObjectParams);
		if (HitSomething)
		{
			if (EnemyTarget->GetUniqueID() != OutHit.Actor->GetUniqueID())
			{
				//we've hit something we didn't aim for \o/
				return true;
			}
			else
			{
				//we need to adjust the trace so it misses the target

				// Create a new vector for the trace
				FVector TraceVector = HitLocation - StartLocation;
				TraceVector.Normalize();
				TraceVector *= Weapon->MaxRange;
				UE_LOG(TB_Log, Warning, TEXT("MissLineTrace(): TraceVector.Size() == %f"), TraceVector.Size());

				// Rotate it by 0-5 deg in all directions
				FRotator Offset(FMath::FRand() * 1000, FMath::FRand() * 1000, 0);
				if (FMath::FRand() < 0.5)
				{
					Offset.Yaw *= -1;
				}
				if (FMath::FRand() < 0.5)
				{
					Offset.Pitch *= -1;
				}
				TraceVector = Offset.RotateVector(TraceVector);

				HitSomething = World->LineTraceSingle(OutHit, StartLocation, StartLocation + TraceVector, Params, ObjectParams);
				if (HitSomething && EnemyTarget->GetUniqueID() == OutHit.Actor->GetUniqueID())
				{
					//we're still hitting the target, pray that we'll miss it when we look at the other targetpoints
					continue;
				}
				else
				{
					return HitSomething;
				}

			}
		}
	}

	UE_LOG(TB_Log, Warning, TEXT("MissLineTrace(): Can't find a way to miss"));
	return false;
}
void UTB_AimComponent::InitCollisionQueryParams(FCollisionQueryParams &Params)
{
	// remember to set the physical material in phat for skeletal meshes
	// (the collision channels for the character might also need to be tuned)
	Params.bTraceComplex = true;
	Params.bReturnPhysicalMaterial = true;

	// Ignore collisions with the aiming character and its weapon
	Params.AddIgnoredActor(Character);
	if (Weapon)
	{
		Params.AddIgnoredActor(Weapon);
	}
	if (EnemyTarget->Weapon)
	{
		Params.AddIgnoredActor(EnemyTarget->Weapon);
	}
}<|endoftext|>


<commit_before>/*
 *  Copyright 2013 David Farrell
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include "LightingManager.h"

LightType LightingManager::light_types[NUM_LIGHT_TYPES];
Light LightingManager::lights[NUM_LIGHTS];
Material LightingManager::materials[NUM_MATERIALS];

void LightingManager::UploadLightTypes(GLuint program_id)
{
    // clear error
    glGetError();

    GLuint binding = 1;
    GLuint block_index = glGetUniformBlockIndex(program_id, "LightTypesBlock");
    glUniformBlockBinding(program_id, block_index, binding);

    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_UNIFORM_BUFFER, buffer);
    glBufferData(GL_UNIFORM_BUFFER, sizeof(light_types), light_types, GL_DYNAMIC_DRAW);
    glBindBufferBase(GL_UNIFORM_BUFFER, binding, buffer);

    GLenum err;
    if((err = glGetError()) != GL_NO_ERROR) fprintf(stderr, "UploadLightTypes: error: 0x%x\n", err);
}

void LightingManager::UploadLights(GLuint program_id)
{
    printf("size=%llu\n", sizeof(GLboolean));
    // clear error
    glGetError();

    GLuint binding = 2;
    GLuint block_index = glGetUniformBlockIndex(program_id, "LightsBlock");
    glUniformBlockBinding(program_id, block_index, binding);

    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_UNIFORM_BUFFER, buffer);
    glBufferData(GL_UNIFORM_BUFFER, sizeof(lights), lights, GL_DYNAMIC_DRAW);
    glBindBufferBase(GL_UNIFORM_BUFFER, binding, buffer);

    GLenum err;
    if((err = glGetError()) != GL_NO_ERROR) fprintf(stderr, "UploadLights: error: 0x%x\n", err);
}

void LightingManager::UploadMaterials(GLuint program_id)
{
    // clear error
    glGetError();

    GLuint binding = 3;
    GLuint block_index = glGetUniformBlockIndex(program_id, "MaterialsBlock");
    glUniformBlockBinding(program_id, block_index, binding);

    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_UNIFORM_BUFFER, buffer);
    glBufferData(GL_UNIFORM_BUFFER, sizeof(materials), materials, GL_DYNAMIC_DRAW);
    glBindBufferBase(GL_UNIFORM_BUFFER, binding, buffer);

    GLenum err;
    if((err = glGetError()) != GL_NO_ERROR) fprintf(stderr, "UploadMaterials: error: 0x%x\n", err);
}
<commit_msg>Removed debug output.<commit_after>/*
 *  Copyright 2013 David Farrell
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include "LightingManager.h"

LightType LightingManager::light_types[NUM_LIGHT_TYPES];
Light LightingManager::lights[NUM_LIGHTS];
Material LightingManager::materials[NUM_MATERIALS];

void LightingManager::UploadLightTypes(GLuint program_id)
{
    // clear error
    glGetError();

    GLuint binding = 1;
    GLuint block_index = glGetUniformBlockIndex(program_id, "LightTypesBlock");
    glUniformBlockBinding(program_id, block_index, binding);

    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_UNIFORM_BUFFER, buffer);
    glBufferData(GL_UNIFORM_BUFFER, sizeof(light_types), light_types, GL_DYNAMIC_DRAW);
    glBindBufferBase(GL_UNIFORM_BUFFER, binding, buffer);

    GLenum err;
    if((err = glGetError()) != GL_NO_ERROR) fprintf(stderr, "UploadLightTypes: error: 0x%x\n", err);
}

void LightingManager::UploadLights(GLuint program_id)
{
    // clear error
    glGetError();

    GLuint binding = 2;
    GLuint block_index = glGetUniformBlockIndex(program_id, "LightsBlock");
    glUniformBlockBinding(program_id, block_index, binding);

    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_UNIFORM_BUFFER, buffer);
    glBufferData(GL_UNIFORM_BUFFER, sizeof(lights), lights, GL_DYNAMIC_DRAW);
    glBindBufferBase(GL_UNIFORM_BUFFER, binding, buffer);

    GLenum err;
    if((err = glGetError()) != GL_NO_ERROR) fprintf(stderr, "UploadLights: error: 0x%x\n", err);
}

void LightingManager::UploadMaterials(GLuint program_id)
{
    // clear error
    glGetError();

    GLuint binding = 3;
    GLuint block_index = glGetUniformBlockIndex(program_id, "MaterialsBlock");
    glUniformBlockBinding(program_id, block_index, binding);

    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_UNIFORM_BUFFER, buffer);
    glBufferData(GL_UNIFORM_BUFFER, sizeof(materials), materials, GL_DYNAMIC_DRAW);
    glBindBufferBase(GL_UNIFORM_BUFFER, binding, buffer);

    GLenum err;
    if((err = glGetError()) != GL_NO_ERROR) fprintf(stderr, "UploadMaterials: error: 0x%x\n", err);
}
<|endoftext|>


<commit_before>#include <windows.h>

#include "..\..\unicode_far\vc10.cpp"<commit_msg>fix example build<commit_after>#include <windows.h>

#include "..\..\..\unicode_far\vc10.cpp"<|endoftext|>


<commit_before>/*
 * SessionConsoleProcessSocketTests.cpp
 *
 * Copyright (C) 2009-17 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include <session/SessionConsoleProcessSocket.hpp>

#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/lexical_cast.hpp>

#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>

#include <tests/TestThat.hpp>

namespace rstudio {
namespace session {
namespace console_process {

using namespace console_process;

namespace {

void blockingwait(int ms)
{
   boost::asio::io_service io;
   boost::asio::deadline_timer timer(io, boost::posix_time::milliseconds(ms));
   timer.wait();
}

// Wrapper for ConsoleProcessSocket, the class we're testing. Primarily
// converts Error codes into true/false, and accumulates input.
class SocketHarness : public boost::enable_shared_from_this<SocketHarness>
{
public:
   SocketHarness() {}
   ~SocketHarness() {}

   bool ensureServerRunning()
   {
      core::Error err = socket_.ensureServerRunning();
      return (!err);
   }

   bool stopServer()
   {
      blockingwait(50);
      socket_.stopServer();
      return true;
   }

   bool listen(const std::string& terminalHandle,
               const ConsoleProcessSocketConnectionCallbacks& callbacks)
   {
      core::Error err = socket_.listen(terminalHandle, callbacks);
      return (!err);
   }

   bool stopListening(const std::string& terminalHandle)
   {
      core::Error err = socket_.stopListening(terminalHandle);
      return (!err);
   }

   bool sendText(const std::string& terminalHandle,
                 const std::string& message)
   {
      core::Error err = socket_.sendText(terminalHandle, message);
      return (!err);
   }

   int port() { return socket_.port(); }

private:
   ConsoleProcessSocket socket_;
};

// Server-side connection test harness; each server-side connection needs one
// of these created and listening before a client can connect to the websocket
class SocketConnection : public boost::enable_shared_from_this<SocketConnection>
{
public:
   SocketConnection(const std::string& handle,
                    boost::shared_ptr<SocketHarness> pServerSocket)
      :
        handle_(handle),
        pServerSocket_(pServerSocket),
        didClose_(false),
        didOpen_(false)

   {}

   void onReceivedInput(const std::string& input)
   {
      received_ += input;
   }

   void onConnectionOpened()
   {
      didOpen_ = true;
   }

   void onConnectionClosed()
   {
      didClose_ = true;
   }

   ConsoleProcessSocketConnectionCallbacks createConsoleProcessSocketConnectionCallbacks()
   {
      using boost::bind;
      ConsoleProcessSocketConnectionCallbacks cb;
      cb.onReceivedInput =
            bind(&SocketConnection::onReceivedInput, SocketConnection::shared_from_this(), _1);
      cb.onConnectionOpened =
            bind(&SocketConnection::onConnectionOpened, SocketConnection::shared_from_this());
      cb.onConnectionClosed =
            bind(&SocketConnection::onConnectionClosed, SocketConnection::shared_from_this());
      return cb;
   }

   // listen informs the server to watch for incoming connections with a unique
   // handle, and callbacks to issue for activity on that connection
   bool listen()
   {
      return pServerSocket_->listen(handle_,
                                    createConsoleProcessSocketConnectionCallbacks());
   }

   // tell server to no longer recognize connections/activity on a given handle
   bool stopListening()
   {
      return pServerSocket_->stopListening(handle_);
   }

   // send a message to client of this connection
   bool sendMessage(const std::string& msg)
   {
      return pServerSocket_->sendText(handle_, msg);
   }

   std::string getReceived() const
   {
      blockingwait(50);
      return received_;
   }

   bool didClose() const { return didClose_; }
   bool didOpen() const { return didOpen_; }

private:
   std::string handle_;
   std::string received_;
   boost::shared_ptr<SocketHarness> pServerSocket_;
   bool didClose_;
   bool didOpen_;
};

typedef websocketpp::client<websocketpp::config::asio_client> client;
typedef client::message_ptr message_ptr;

// Client-side websocket connection test class; used to verify a client
// can connect to the websocket and send/receive data over the socket
class SocketClient : public boost::enable_shared_from_this<SocketClient>
{
public:
   SocketClient(const std::string& handle, int port)
      :
        handle_(handle),
        port_(port),
        gotOpened_(false),
        gotClosed_(false),
        gotFailed_(false),
        clientRunning_(false)
   {}

   ~SocketClient()
   {
      try
      {
         disconnectFromServer();
      }
      catch (...) {}
   }

   void on_message(client* c, websocketpp::connection_hdl hdl, message_ptr msg)
   {
      if (msg->get_opcode() == websocketpp::frame::opcode::text)
      {
         input_ += msg->get_payload();
      }
      else
      {
         std::cerr << "Unsupported websocket message type" << std::endl;
      }
   }

   void on_open(client* c, websocketpp::connection_hdl hdl)
   {
      gotOpened_ = true;
      hdl_ = hdl;
      client::connection_ptr con = c->get_con_from_hdl(hdl);
      server_ = con->get_response_header("Server");
    }

   void on_fail(client* c, websocketpp::connection_hdl hdl)
   {
      gotFailed_ = true;
      client::connection_ptr con = c->get_con_from_hdl(hdl);
      server_ = con->get_response_header("Server");
      errorReason_ = con->get_ec().message();
   }

   bool connectToServer()
   {
      using websocketpp::lib::placeholders::_1;
      using websocketpp::lib::placeholders::_2;
      using websocketpp::lib::bind;

      try {
         std::string uri = "http://localhost:" +
               boost::lexical_cast<std::string>(port_) +
               "/terminal/" + handle_ + "/";

         // don't clutter up unit test runs with warnings
         client_.set_access_channels(websocketpp::log::alevel::none);
         client_.set_error_channels(websocketpp::log::alevel::none);

         // Initialize ASIO
         client_.init_asio();

         // Register our message handler
         client_.set_message_handler(bind(&SocketClient::on_message,
                                          SocketClient::shared_from_this(),
                                          &client_, ::_1, ::_2));
         client_.set_open_handler(bind(&SocketClient::on_open,
                                       SocketClient::shared_from_this(),
                                       &client_, ::_1));
         client_.set_fail_handler(bind(&SocketClient::on_fail,
                                       SocketClient::shared_from_this(),
                                       &client_, ::_1));

         websocketpp::lib::error_code ec;
         client::connection_ptr con = client_.get_connection(uri, ec);
         if (ec)
            return false;

         // Note that connect here only requests a connection. No network
         // messages are exchanged until the event loop starts running in
         // the thread.
         client_.connect(con);

         // Start the ASIO io_service run loop in a separate thread; allows
         // us to perform multiple operations as part of the test.
         core::thread::safeLaunchThread(
                  boost::bind(&SocketClient::watchSocket, this),
                  &clientSocketThread_);
      }
      catch (websocketpp::exception const & e)
      {
         return false;
      }
      return true;
   }

   bool disconnectFromServer()
   {
      if (clientRunning_)
      {
         client_.stop();
         clientRunning_ = false;
         clientSocketThread_.join();
      }
      return true;
   }

   bool sendText(const std::string& str)
   {
      websocketpp::lib::error_code ec;
      client_.send(hdl_, str, websocketpp::frame::opcode::text, ec);
      if (ec)
      {
         std::string error = ec.message();
         std::cerr << "Client sendText failed because: " << error << std::endl;
         return false;
      }
      return true;
   }

   std::string getInput() { blockingwait(50); return input_; }
   bool gotOpened() { return gotOpened_; }
   bool gotClosed() { return gotClosed_; }
   bool gotFailed() { return gotFailed_; }
   std::string getServer() { return server_; }
   std::string getErrorReason() { return errorReason_; }

private:
   void watchSocket() { client_.run(); }

   std::string handle_;
   int port_;

   std::string input_;
   bool gotOpened_;
   bool gotClosed_;
   bool gotFailed_;
   std::string server_;
   std::string errorReason_;

   client client_;
   boost::thread clientSocketThread_;
   bool clientRunning_;
   websocketpp::connection_hdl hdl_;
};

} // anonymous namespace

context("websocket for interactive terminals")
{
   const std::string handle1 = "abcd";
   const std::string handle2 = "defg";
   const std::string msgString1 = "Hello World Howya Doing?";
   const std::string msgString2 = "Here's another message I sent.";
   using boost::make_shared;
   using boost::shared_ptr;

   test_that("port for new socket object is zero")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->port() == 0);
   }

   test_that("ok to stop a non-running server")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->stopServer());
   }

   test_that("server port returned correctly when started")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->ensureServerRunning());
      expect_true(pSocket->port() > 0);

      expect_true(pSocket->stopServer());
   }

   test_that("can start and stop listening to a handle")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->ensureServerRunning());

      shared_ptr<SocketConnection> pConnection =
            make_shared<SocketConnection>(handle1, pSocket);
      expect_true(pConnection->listen());

      expect_true(pConnection->stopListening());
      expect_true(pSocket->stopServer());
   }

   test_that("client can connect to server then disconnect")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->ensureServerRunning());

      shared_ptr<SocketConnection> pConnection = make_shared<SocketConnection>(handle1, pSocket);
      shared_ptr<SocketClient> pClient = make_shared<SocketClient>(handle1, pSocket->port());
      expect_true(pConnection->listen());
      expect_true(pClient->connectToServer());

      while (!pClient->gotOpened() && !pClient->gotFailed())
      {
      }

      expect_true(pClient->gotOpened());
      expect_false(pClient->gotFailed());

      expect_true(pClient->disconnectFromServer());
      expect_true(pSocket->stopServer());
   }

   test_that("client can send text to server and server receives it")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->ensureServerRunning());

      shared_ptr<SocketConnection> pConnection = make_shared<SocketConnection>(handle1, pSocket);
      shared_ptr<SocketClient> pClient = make_shared<SocketClient>(handle1, pSocket->port());
      expect_true(pConnection->listen());
      expect_true(pClient->connectToServer());

      while (!pClient->gotOpened() && !pClient->gotFailed())
      {
      }

      expect_true(pClient->gotOpened());
      expect_false(pClient->gotFailed());

      expect_true(pClient->sendText(msgString1));
      expect_true(pConnection->getReceived().compare(msgString1) == 0);

      expect_true(pClient->disconnectFromServer());
      expect_true(pSocket->stopServer());
   }

   test_that("server can send text to client and client receives it")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->ensureServerRunning());

      shared_ptr<SocketConnection> pConnection = make_shared<SocketConnection>(handle1, pSocket);
      shared_ptr<SocketClient> pClient = make_shared<SocketClient>(handle1, pSocket->port());
      expect_true(pConnection->listen());
      expect_true(pClient->connectToServer());

      while (!pClient->gotOpened() && !pClient->gotFailed())
      {
      }

      expect_true(pClient->gotOpened());
      expect_false(pClient->gotFailed());

      expect_true(pConnection->sendMessage(msgString1));
      expect_true(pClient->getInput().compare(msgString1) == 0);

      expect_true(pClient->disconnectFromServer());
      expect_true(pSocket->stopServer());
   }

   test_that("client can make multiple connections to server")
   {
      // ---- one socket on server ----
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->ensureServerRunning());

      // ---- first connection ----
      shared_ptr<SocketConnection> pConnection1 =
            make_shared<SocketConnection>(handle1, pSocket);

      shared_ptr<SocketClient> pClient1 = make_shared<SocketClient>(handle1, pSocket->port());
      expect_true(pConnection1->listen());
      expect_true(pClient1->connectToServer());

      while (!pClient1->gotOpened() && !pClient1->gotFailed())
      {
      }
      expect_true(pClient1->gotOpened());
      expect_false(pClient1->gotFailed());

      // ---- second connection ----
      shared_ptr<SocketConnection> pConnection2 =
            make_shared<SocketConnection>(handle2, pSocket);

      shared_ptr<SocketClient> pClient2 = make_shared<SocketClient>(handle2, pSocket->port());
      expect_true(pConnection2->listen());
      expect_true(pClient2->connectToServer());

      while (!pClient2->gotOpened() && !pClient2->gotFailed())
      {
      }
      expect_true(pClient2->gotOpened());
      expect_false(pClient2->gotFailed());

      // ---- send message to first connection ----
      expect_true(pConnection1->sendMessage(msgString1));
      expect_true(pClient1->getInput().compare(msgString1) == 0);

      // ---- send message to second connection ----
      expect_true(pConnection2->sendMessage(msgString2));
      expect_true(pClient2->getInput().compare(msgString2) == 0);

      // ---- cleanup ----
      expect_true(pClient1->disconnectFromServer());
      expect_true(pClient2->disconnectFromServer());
      expect_true(pSocket->stopServer());
   }
}

} // namespace console_process
} // namespace session
} // namespace rstudio
<commit_msg>explicitly qualify make_shared()<commit_after>/*
 * SessionConsoleProcessSocketTests.cpp
 *
 * Copyright (C) 2009-17 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include <session/SessionConsoleProcessSocket.hpp>

#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/lexical_cast.hpp>

#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>

#include <tests/TestThat.hpp>

namespace rstudio {
namespace session {
namespace console_process {

using namespace console_process;

namespace {

void blockingwait(int ms)
{
   boost::asio::io_service io;
   boost::asio::deadline_timer timer(io, boost::posix_time::milliseconds(ms));
   timer.wait();
}

// Wrapper for ConsoleProcessSocket, the class we're testing. Primarily
// converts Error codes into true/false, and accumulates input.
class SocketHarness : public boost::enable_shared_from_this<SocketHarness>
{
public:
   SocketHarness() {}
   ~SocketHarness() {}

   bool ensureServerRunning()
   {
      core::Error err = socket_.ensureServerRunning();
      return (!err);
   }

   bool stopServer()
   {
      blockingwait(50);
      socket_.stopServer();
      return true;
   }

   bool listen(const std::string& terminalHandle,
               const ConsoleProcessSocketConnectionCallbacks& callbacks)
   {
      core::Error err = socket_.listen(terminalHandle, callbacks);
      return (!err);
   }

   bool stopListening(const std::string& terminalHandle)
   {
      core::Error err = socket_.stopListening(terminalHandle);
      return (!err);
   }

   bool sendText(const std::string& terminalHandle,
                 const std::string& message)
   {
      core::Error err = socket_.sendText(terminalHandle, message);
      return (!err);
   }

   int port() { return socket_.port(); }

private:
   ConsoleProcessSocket socket_;
};

// Server-side connection test harness; each server-side connection needs one
// of these created and listening before a client can connect to the websocket
class SocketConnection : public boost::enable_shared_from_this<SocketConnection>
{
public:
   SocketConnection(const std::string& handle,
                    boost::shared_ptr<SocketHarness> pServerSocket)
      :
        handle_(handle),
        pServerSocket_(pServerSocket),
        didClose_(false),
        didOpen_(false)

   {}

   void onReceivedInput(const std::string& input)
   {
      received_ += input;
   }

   void onConnectionOpened()
   {
      didOpen_ = true;
   }

   void onConnectionClosed()
   {
      didClose_ = true;
   }

   ConsoleProcessSocketConnectionCallbacks createConsoleProcessSocketConnectionCallbacks()
   {
      using boost::bind;
      ConsoleProcessSocketConnectionCallbacks cb;
      cb.onReceivedInput =
            bind(&SocketConnection::onReceivedInput, SocketConnection::shared_from_this(), _1);
      cb.onConnectionOpened =
            bind(&SocketConnection::onConnectionOpened, SocketConnection::shared_from_this());
      cb.onConnectionClosed =
            bind(&SocketConnection::onConnectionClosed, SocketConnection::shared_from_this());
      return cb;
   }

   // listen informs the server to watch for incoming connections with a unique
   // handle, and callbacks to issue for activity on that connection
   bool listen()
   {
      return pServerSocket_->listen(handle_,
                                    createConsoleProcessSocketConnectionCallbacks());
   }

   // tell server to no longer recognize connections/activity on a given handle
   bool stopListening()
   {
      return pServerSocket_->stopListening(handle_);
   }

   // send a message to client of this connection
   bool sendMessage(const std::string& msg)
   {
      return pServerSocket_->sendText(handle_, msg);
   }

   std::string getReceived() const
   {
      blockingwait(50);
      return received_;
   }

   bool didClose() const { return didClose_; }
   bool didOpen() const { return didOpen_; }

private:
   std::string handle_;
   std::string received_;
   boost::shared_ptr<SocketHarness> pServerSocket_;
   bool didClose_;
   bool didOpen_;
};

typedef websocketpp::client<websocketpp::config::asio_client> client;
typedef client::message_ptr message_ptr;

// Client-side websocket connection test class; used to verify a client
// can connect to the websocket and send/receive data over the socket
class SocketClient : public boost::enable_shared_from_this<SocketClient>
{
public:
   SocketClient(const std::string& handle, int port)
      :
        handle_(handle),
        port_(port),
        gotOpened_(false),
        gotClosed_(false),
        gotFailed_(false),
        clientRunning_(false)
   {}

   ~SocketClient()
   {
      try
      {
         disconnectFromServer();
      }
      catch (...) {}
   }

   void on_message(client* c, websocketpp::connection_hdl hdl, message_ptr msg)
   {
      if (msg->get_opcode() == websocketpp::frame::opcode::text)
      {
         input_ += msg->get_payload();
      }
      else
      {
         std::cerr << "Unsupported websocket message type" << std::endl;
      }
   }

   void on_open(client* c, websocketpp::connection_hdl hdl)
   {
      gotOpened_ = true;
      hdl_ = hdl;
      client::connection_ptr con = c->get_con_from_hdl(hdl);
      server_ = con->get_response_header("Server");
    }

   void on_fail(client* c, websocketpp::connection_hdl hdl)
   {
      gotFailed_ = true;
      client::connection_ptr con = c->get_con_from_hdl(hdl);
      server_ = con->get_response_header("Server");
      errorReason_ = con->get_ec().message();
   }

   bool connectToServer()
   {
      using websocketpp::lib::placeholders::_1;
      using websocketpp::lib::placeholders::_2;
      using websocketpp::lib::bind;

      try {
         std::string uri = "http://localhost:" +
               boost::lexical_cast<std::string>(port_) +
               "/terminal/" + handle_ + "/";

         // don't clutter up unit test runs with warnings
         client_.set_access_channels(websocketpp::log::alevel::none);
         client_.set_error_channels(websocketpp::log::alevel::none);

         // Initialize ASIO
         client_.init_asio();

         // Register our message handler
         client_.set_message_handler(bind(&SocketClient::on_message,
                                          SocketClient::shared_from_this(),
                                          &client_, ::_1, ::_2));
         client_.set_open_handler(bind(&SocketClient::on_open,
                                       SocketClient::shared_from_this(),
                                       &client_, ::_1));
         client_.set_fail_handler(bind(&SocketClient::on_fail,
                                       SocketClient::shared_from_this(),
                                       &client_, ::_1));

         websocketpp::lib::error_code ec;
         client::connection_ptr con = client_.get_connection(uri, ec);
         if (ec)
            return false;

         // Note that connect here only requests a connection. No network
         // messages are exchanged until the event loop starts running in
         // the thread.
         client_.connect(con);

         // Start the ASIO io_service run loop in a separate thread; allows
         // us to perform multiple operations as part of the test.
         core::thread::safeLaunchThread(
                  boost::bind(&SocketClient::watchSocket, this),
                  &clientSocketThread_);
      }
      catch (websocketpp::exception const & e)
      {
         return false;
      }
      return true;
   }

   bool disconnectFromServer()
   {
      if (clientRunning_)
      {
         client_.stop();
         clientRunning_ = false;
         clientSocketThread_.join();
      }
      return true;
   }

   bool sendText(const std::string& str)
   {
      websocketpp::lib::error_code ec;
      client_.send(hdl_, str, websocketpp::frame::opcode::text, ec);
      if (ec)
      {
         std::string error = ec.message();
         std::cerr << "Client sendText failed because: " << error << std::endl;
         return false;
      }
      return true;
   }

   std::string getInput() { blockingwait(50); return input_; }
   bool gotOpened() { return gotOpened_; }
   bool gotClosed() { return gotClosed_; }
   bool gotFailed() { return gotFailed_; }
   std::string getServer() { return server_; }
   std::string getErrorReason() { return errorReason_; }

private:
   void watchSocket() { client_.run(); }

   std::string handle_;
   int port_;

   std::string input_;
   bool gotOpened_;
   bool gotClosed_;
   bool gotFailed_;
   std::string server_;
   std::string errorReason_;

   client client_;
   boost::thread clientSocketThread_;
   bool clientRunning_;
   websocketpp::connection_hdl hdl_;
};

} // anonymous namespace

context("websocket for interactive terminals")
{
   const std::string handle1 = "abcd";
   const std::string handle2 = "defg";
   const std::string msgString1 = "Hello World Howya Doing?";
   const std::string msgString2 = "Here's another message I sent.";
   using boost::make_shared;
   using boost::shared_ptr;

   test_that("port for new socket object is zero")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->port() == 0);
   }

   test_that("ok to stop a non-running server")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->stopServer());
   }

   test_that("server port returned correctly when started")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->ensureServerRunning());
      expect_true(pSocket->port() > 0);

      expect_true(pSocket->stopServer());
   }

   test_that("can start and stop listening to a handle")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->ensureServerRunning());

      shared_ptr<SocketConnection> pConnection =
            boost::make_shared<SocketConnection>(handle1, pSocket);
      expect_true(pConnection->listen());

      expect_true(pConnection->stopListening());
      expect_true(pSocket->stopServer());
   }

   test_that("client can connect to server then disconnect")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->ensureServerRunning());

      shared_ptr<SocketConnection> pConnection = boost::make_shared<SocketConnection>(handle1, pSocket);
      shared_ptr<SocketClient> pClient = boost::make_shared<SocketClient>(handle1, pSocket->port());
      expect_true(pConnection->listen());
      expect_true(pClient->connectToServer());

      while (!pClient->gotOpened() && !pClient->gotFailed())
      {
      }

      expect_true(pClient->gotOpened());
      expect_false(pClient->gotFailed());

      expect_true(pClient->disconnectFromServer());
      expect_true(pSocket->stopServer());
   }

   test_that("client can send text to server and server receives it")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->ensureServerRunning());

      shared_ptr<SocketConnection> pConnection = boost::make_shared<SocketConnection>(handle1, pSocket);
      shared_ptr<SocketClient> pClient = boost::make_shared<SocketClient>(handle1, pSocket->port());
      expect_true(pConnection->listen());
      expect_true(pClient->connectToServer());

      while (!pClient->gotOpened() && !pClient->gotFailed())
      {
      }

      expect_true(pClient->gotOpened());
      expect_false(pClient->gotFailed());

      expect_true(pClient->sendText(msgString1));
      expect_true(pConnection->getReceived().compare(msgString1) == 0);

      expect_true(pClient->disconnectFromServer());
      expect_true(pSocket->stopServer());
   }

   test_that("server can send text to client and client receives it")
   {
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->ensureServerRunning());

      shared_ptr<SocketConnection> pConnection = boost::make_shared<SocketConnection>(handle1, pSocket);
      shared_ptr<SocketClient> pClient = boost::make_shared<SocketClient>(handle1, pSocket->port());
      expect_true(pConnection->listen());
      expect_true(pClient->connectToServer());

      while (!pClient->gotOpened() && !pClient->gotFailed())
      {
      }

      expect_true(pClient->gotOpened());
      expect_false(pClient->gotFailed());

      expect_true(pConnection->sendMessage(msgString1));
      expect_true(pClient->getInput().compare(msgString1) == 0);

      expect_true(pClient->disconnectFromServer());
      expect_true(pSocket->stopServer());
   }

   test_that("client can make multiple connections to server")
   {
      // ---- one socket on server ----
      shared_ptr<SocketHarness> pSocket = make_shared<SocketHarness>();
      expect_true(pSocket->ensureServerRunning());

      // ---- first connection ----
      shared_ptr<SocketConnection> pConnection1 =
            boost::make_shared<SocketConnection>(handle1, pSocket);

      shared_ptr<SocketClient> pClient1 = boost::make_shared<SocketClient>(handle1, pSocket->port());
      expect_true(pConnection1->listen());
      expect_true(pClient1->connectToServer());

      while (!pClient1->gotOpened() && !pClient1->gotFailed())
      {
      }
      expect_true(pClient1->gotOpened());
      expect_false(pClient1->gotFailed());

      // ---- second connection ----
      shared_ptr<SocketConnection> pConnection2 =
            boost::make_shared<SocketConnection>(handle2, pSocket);

      shared_ptr<SocketClient> pClient2 = boost::make_shared<SocketClient>(handle2, pSocket->port());
      expect_true(pConnection2->listen());
      expect_true(pClient2->connectToServer());

      while (!pClient2->gotOpened() && !pClient2->gotFailed())
      {
      }
      expect_true(pClient2->gotOpened());
      expect_false(pClient2->gotFailed());

      // ---- send message to first connection ----
      expect_true(pConnection1->sendMessage(msgString1));
      expect_true(pClient1->getInput().compare(msgString1) == 0);

      // ---- send message to second connection ----
      expect_true(pConnection2->sendMessage(msgString2));
      expect_true(pClient2->getInput().compare(msgString2) == 0);

      // ---- cleanup ----
      expect_true(pClient1->disconnectFromServer());
      expect_true(pClient2->disconnectFromServer());
      expect_true(pSocket->stopServer());
   }
}

} // namespace console_process
} // namespace session
} // namespace rstudio
<|endoftext|>


<commit_before>#include <chili/task.h>
#include <chili/plugin.xpm>
#include <chili/qclightbox.h>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qptrlist.h>
#include <qbuttongroup.h>
#include <mitkDataTree.h>
#include <QmitkStdMultiWidget.h>
#include <mitkLightBoxImageReader.h>
#include "SampleApp.h"
#include "QcMITKSamplePlugin.h"
#include "mitkProperties.h"
#include "mitkLevelWindowProperty.h"
#include "ToolBar.h"

QcMITKSamplePlugin::QcMITKSamplePlugin( QWidget *parent )
  : QcPlugin( parent )
{
  task = new QcTask( xpm(), parent, name() );

  ap = new SampleApp(task,"sample",0);
  toolbar =new ToolBar(task,this);
  toolbar->SetWidget(ap);

  QButtonGroup* tb;
  tb=toolbar->GetToolBar();

  connect(toolbar,SIGNAL(LightboxSelected(QcLightbox*)),this,SLOT(selectSerie(QcLightbox*)));
  connect(toolbar,SIGNAL(ChangeWidget()),this,SLOT(CreateNewSampleApp()));
  activated =false;

  itkGenericOutputMacro(<<"hallo");

}

QString
QcMITKSamplePlugin::name()
{
  return QString( "SampleApp" );
}

const char **
QcMITKSamplePlugin::xpm()
{
  return (const char **)plugin_xpm;
}

QcMITKSamplePlugin::~QcMITKSamplePlugin ()
{
  task->deleteLater();
}

extern "C" QcEXPORT QObject *
create( QWidget *parent )
{
return new QcMITKSamplePlugin( parent );
}

void 	QcMITKSamplePlugin::lightboxFilled (QcLightbox* lightbox)
{
  itkGenericOutputMacro(<<"lightbox filled");
  QcLightboxManager *lbm=lightboxManager();
  QPtrList<QcLightbox> list;
  list=lbm->getLightboxes();
  QButtonGroup* tb;
  tb=toolbar->GetToolBar();
  int id=tb->id(tb->selected());
  if (id>0)
  {
    if (!tb->find(6)->isOn())
      if (activated&&(list.take(id-1))->isActive())
          selectSerie(lightbox);
  }
  else
    if (tb->find((list.find(lightbox))+1)->isOn())
          selectSerie(lightbox);

}

void 	QcMITKSamplePlugin::lightboxTiles (QcLightboxManager *lbm, int tiles)
{
  itkGenericOutputMacro(<<"lightbox tiles: "<<tiles);
  toolbar->ConnectButton(tiles);

}

void QcMITKSamplePlugin::selectSerie (QcLightbox* lightbox)
{
  itkGenericOutputMacro(<<"selectSerie");
  activated=true;
  if(lightbox->getFrames()==0)
    return;

  mitk::Image::Pointer image = mitk::Image::New();

  mitk::LightBoxImageReader::Pointer reader=mitk::LightBoxImageReader::New();
  reader->SetLightBox(lightbox);

  image=reader->GetOutput();
  image->Update();
  mitk::DataTree::Pointer tree = ap->GetTree();

  mitk::DataTreePreOrderIterator it(tree);

  mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();

  node->SetData(image);

  it.Add(node);

  mitk::LevelWindowProperty::Pointer levWinProp = new mitk::LevelWindowProperty();
  mitk::LevelWindow levelwindow;
  levelwindow.SetAuto( reader->GetOutput()->GetPic() );
  levWinProp->SetLevelWindow( levelwindow );
  node->GetPropertyList()->SetProperty( "levelwindow", levWinProp );
  node->SetProperty( "volumerendering", new mitk::BoolProperty( false ) );

  ap->getMultiWidget()->texturizePlaneSubTree(&it);
  ap->getMultiWidget()->updateMitkWidgets();
  ap->getMultiWidget()->fit();
}

void QcMITKSamplePlugin::CreateNewSampleApp()
{
  ap = new SampleApp(task,"sample",0);
  toolbar->SetWidget(ap);
}
<commit_msg>CHG: test code for writing<commit_after>#include <chili/task.h>
#include <chili/plugin.xpm>
#include <chili/qclightbox.h>
#include <qlayout.h>
#include <qpushbutton.h>
#include <qptrlist.h>
#include <qbuttongroup.h>
#include <mitkDataTree.h>
#include <QmitkStdMultiWidget.h>
#include <mitkLightBoxImageReader.h>
#include "SampleApp.h"
#include "QcMITKSamplePlugin.h"
#include "mitkProperties.h"
#include "mitkLevelWindowProperty.h"
#include "mitkStringProperty.h"
#include "ToolBar.h"

#include "ipFunc.h"

#include <crtdbg.h>

QcPlugin* QcMITKSamplePlugin::s_PluginInstance = NULL;

QcMITKSamplePlugin::QcMITKSamplePlugin( QWidget *parent )
  : QcPlugin( parent )
{
  task = new QcTask( xpm(), parent, name() );

  ap = new SampleApp(task,"sample",0);
  toolbar =new ToolBar(task,this);
  toolbar->SetWidget(ap);

  QButtonGroup* tb;
  tb=toolbar->GetToolBar();

  connect(toolbar,SIGNAL(LightboxSelected(QcLightbox*)),this,SLOT(selectSerie(QcLightbox*)));
  connect(toolbar,SIGNAL(ChangeWidget()),this,SLOT(CreateNewSampleApp()));
  activated =false;

  itkGenericOutputMacro(<<"hallo");

  s_PluginInstance = this;
}

QString
QcMITKSamplePlugin::name()
{
  return QString( "SampleApp" );
}

const char **
QcMITKSamplePlugin::xpm()
{
  return (const char **)plugin_xpm;
}

QcMITKSamplePlugin::~QcMITKSamplePlugin ()
{
  task->deleteLater();
}

extern "C" QcEXPORT QObject *
create( QWidget *parent )
{
return new QcMITKSamplePlugin( parent );
}

void 	QcMITKSamplePlugin::lightboxFilled (QcLightbox* lightbox)
{
  itkGenericOutputMacro(<<"lightbox filled");
  QcLightboxManager *lbm=lightboxManager();
  QPtrList<QcLightbox> list;
  list=lbm->getLightboxes();
  QButtonGroup* tb;
  tb=toolbar->GetToolBar();
  int id=tb->id(tb->selected());
  if (id>0)
  {
    if (!tb->find(6)->isOn())
      if (activated&&(list.take(id-1))->isActive())
          selectSerie(lightbox);
  }
  else
    if (tb->find((list.find(lightbox))+1)->isOn())
          selectSerie(lightbox);

}

void 	QcMITKSamplePlugin::lightboxTiles (QcLightboxManager *lbm, int tiles)
{
  itkGenericOutputMacro(<<"lightbox tiles: "<<tiles);
  toolbar->ConnectButton(tiles);

}

void QcMITKSamplePlugin::selectSerie (QcLightbox* lightbox)
{
  itkGenericOutputMacro(<<"selectSerie");
  activated=true;
  if(lightbox->getFrames()==0)
    return;

  mitk::Image::Pointer image = mitk::Image::New();

  mitk::LightBoxImageReader::Pointer reader=mitk::LightBoxImageReader::New();
  reader->SetLightBox(lightbox);

  image=reader->GetOutput();
  image->Update();
  mitk::DataTree::Pointer tree = ap->GetTree();

  mitk::DataTreePreOrderIterator it(tree);

  mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New();

  node->SetData(image);

  it.Add(node);

  mitk::LevelWindowProperty::Pointer levWinProp = new mitk::LevelWindowProperty();
  mitk::LevelWindow levelwindow;
  levelwindow.SetAuto( reader->GetOutput()->GetPic() );
  levWinProp->SetLevelWindow( levelwindow );
  node->GetPropertyList()->SetProperty( "levelwindow", levWinProp );
  node->SetProperty( "volumerendering", new mitk::BoolProperty( false ) );
  node->SetProperty("LoadedFromChili", new mitk::BoolProperty( true ) );
  node->SetProperty("name", new mitk::StringProperty( "1" ) );

itkGenericOutputMacro(<<"before thresh: ");
  ipPicDescriptor *cur, *tmp;
  cur = ipFuncThresh( image->GetPic(), 100, NULL );
itkGenericOutputMacro(<<"before convert: ");
  cur = ipFuncConvert( cur, ipPicUInt, 8 );
  if(cur!=NULL)
  {
    itkGenericOutputMacro(<<"before multc: ");
      tmp = ipFuncMultC( cur, 100, ipFuncKeep, NULL );
    itkGenericOutputMacro(<<"before free: ");
      ipPicFree( cur );
  ipPicPut("c:\\atest2.pic",cur);
      cur=tmp;
    itkGenericOutputMacro(<<"after thresh: ");
      mitk::Image::Pointer result = mitk::Image::New();
      if(cur->dim>3) cur->dim=3;
      result->Initialize(cur);
      result->SetGeometry(static_cast<mitk::Geometry3D*>(image->GetGeometry()->Clone().GetPointer()));
      result->SetPicVolume(cur);
      int pos=it.ChildPosition(node);
      if(pos<0) pos=0;
      it.GoToChild( pos );
    itkGenericOutputMacro(<<"after gotoch: "<<pos);
      mitk::DataTreeNode::Pointer resultnode = mitk::DataTreeNode::New();
      resultnode->SetData(result);
    itkGenericOutputMacro(<<"before lv: ");
      levelwindow.SetAuto( cur );
      levWinProp->SetLevelWindow( levelwindow );
      resultnode->GetPropertyList()->SetProperty( "levelwindow", levWinProp );
itkGenericOutputMacro(<<"lv: "<<levelwindow.GetMin() <<" "<<levelwindow.GetMax());
    itkGenericOutputMacro(<<"before vr: ");
      resultnode->SetProperty( "volumerendering", new mitk::BoolProperty( false ) );
    itkGenericOutputMacro(<<"before addr: ");
      resultnode->SetProperty("name", new mitk::StringProperty( "2" ) );
      it.Add(resultnode);
    itkGenericOutputMacro(<<"done: ");
  }

  ap->getMultiWidget()->texturizePlaneSubTree(&it);
  ap->getMultiWidget()->updateMitkWidgets();
  ap->getMultiWidget()->fit();
}

void QcMITKSamplePlugin::CreateNewSampleApp()
{
  ap = new SampleApp(task,"sample",0);
  toolbar->SetWidget(ap);
}
<|endoftext|>


<commit_before>/** This file is part of Contacts daemon
 **
 ** Copyright (c) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
 **
 ** Contact:  Nokia Corporation (info@qt.nokia.com)
 **
 ** GNU Lesser General Public License Usage
 ** This file may be used under the terms of the GNU Lesser General Public License
 ** version 2.1 as published by the Free Software Foundation and appearing in the
 ** file LICENSE.LGPL included in the packaging of this file.  Please review the
 ** following information to ensure the GNU Lesser General Public License version
 ** 2.1 requirements will be met:
 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
 **
 ** In addition, as a special exception, Nokia gives you certain additional rights.
 ** These rights are described in the Nokia Qt LGPL Exception version 1.1, included
 ** in the file LGPL_EXCEPTION.txt in this package.
 **
 ** Other Usage
 ** Alternatively, this file may be used in accordance with the terms and
 ** conditions contained in a signed written agreement between you and Nokia.
 **/

#include <QStringBuilder>

#include <QContactName>
#include <QContactBirthday>

#include <MLocale>

#include <recurrencerule.h>

#include "cdbirthdaycalendar.h"
#include "debug.h"

using namespace Contactsd;

// A random ID.
const QLatin1String calNotebookId("b1376da7-5555-1111-2222-227549c4e570");

CDBirthdayCalendar::CDBirthdayCalendar(SyncMode syncMode, QObject *parent) :
    QObject(parent),
    mCalendar(0),
    mStorage(0)
{
    mCalendar = mKCal::ExtendedCalendar::Ptr(new mKCal::ExtendedCalendar(KDateTime::Spec::LocalZone()));
    mStorage = mKCal::ExtendedCalendar::defaultStorage(mCalendar);

    MLocale * const locale = new MLocale(this);

    if (not locale->isInstalledTrCatalog(QLatin1String("calendar"))) {
        locale->installTrCatalog(QLatin1String("calendar"));
    }

    locale->connectSettings();
    connect(locale, SIGNAL(settingsChanged()), this, SLOT(onLocaleChanged()));

    MLocale::setDefault(*locale);

    mStorage->open();

    mKCal::Notebook::Ptr notebook = mStorage->notebook(calNotebookId);

    if (notebook.isNull()) {
        notebook = createNotebook();
        mStorage->addNotebook(notebook);
    } else {
        // Clear the calendar database if and only if restoring from a backup.
        switch(syncMode) {
        case Incremental:
            // Force calendar name update, if a locale change happened while contactsd was not running.
            onLocaleChanged();
            break;

        case FullSync:
            mStorage->deleteNotebook(notebook);
            notebook = createNotebook();
            mStorage->addNotebook(notebook);
            break;
        }
    }
}

CDBirthdayCalendar::~CDBirthdayCalendar()
{
    if (mStorage) {
        mStorage->close();
    }

    debug() << "Destroyed birthday calendar";
}

mKCal::Notebook::Ptr CDBirthdayCalendar::createNotebook()
{
    return mKCal::Notebook::Ptr(new mKCal::Notebook(calNotebookId,
                                                    qtTrId("qtn_caln_birthdays"),
                                                    QLatin1String(""),
                                                    QLatin1String("#ff0000"),
                                                    false, // Not shared.
                                                    true, // Is master.
                                                    false, // Not synced to Ovi.
                                                    false, // Writable.
                                                    true, // Visible.
                                                    QLatin1String("Birthday-Nokia"),
                                                    QLatin1String(""),
                                                    0));
}

void CDBirthdayCalendar::updateBirthday(const QContact &contact)
{
    // Retrieve contact details.
    const QContactDisplayLabel displayName = contact.detail<QContactDisplayLabel>();
    const QContactBirthday contactBirthday = contact.detail<QContactBirthday>();

    if (displayName.isEmpty() || contactBirthday.isEmpty()) {
        warning() << Q_FUNC_INFO << "Contact without name or birthday, local ID: "
                  << contact.localId();
        return;
    }

    // Retrieve birthday event.
    if (not mStorage->isValidNotebook(calNotebookId)) {
        warning() << Q_FUNC_INFO << "Invalid notebook ID: " << calNotebookId;
        return;
    }

    KCalCore::Event::Ptr event = calendarEvent(contact.localId());

    if (event.isNull()) {
        // Add a new event.
        event = KCalCore::Event::Ptr(new KCalCore::Event());
        event->startUpdates();
        event->setUid(calendarEventId(contact.localId()));
        event->setAllDay(true);

        // Ensure events appear as birthdays in the calendar, NB#259710.
        event->setCategories(QStringList() << QLatin1String("BIRTHDAY"));

        if (not mCalendar->addEvent(event, calNotebookId)) {
            warning() << Q_FUNC_INFO << "Failed to add event to calendar";
            return;
        }
    } else {
        // Update the existing event.
        event->setReadOnly(false);
        event->startUpdates();
    }

    // Transfer birthday details from contact to calendar event.
    event->setSummary(displayName.label());

    // Event has only date information, no time.
    event->setDtStart(KDateTime(contactBirthday.date(), QTime(), KDateTime::ClockTime));
    event->setDtEnd(KDateTime(contactBirthday.date().addDays(1), QTime(), KDateTime::ClockTime));

    // Must always set the recurrence as it depends on the event date.
    KCalCore::Recurrence * const rule = event->recurrence();
    rule->setStartDateTime(event->dtStart());

    // This is not a boolean, but the frequency of the recurrence: every 1 year.
    rule->setYearly(1);

    // Set the alarms on the event
    event->clearAlarms();
    KCalCore::Alarm::Ptr alarm = event->newAlarm();
    alarm->setDisplayAlarm(event->summary());
    alarm->setStartOffset(KCalCore::Duration(-1, KCalCore::Duration::Days));

    event->setReadOnly(true);
    event->endUpdates();

    // Commit calendar changes.
    if (not mStorage->save()) {
        warning() << Q_FUNC_INFO << "Failed to save event in calendar";
        return;
    }

    debug() << "Updated birthday event in calendar, local ID: " << contact.localId();
}

void CDBirthdayCalendar::deleteBirthday(QContactLocalId contactId)
{
    KCalCore::Event::Ptr event = calendarEvent(contactId);

    if (event.isNull()) {
        debug() << Q_FUNC_INFO << "Not found in calendar:" << contactId;
        return;
    }

    mCalendar->deleteEvent(event);

    if (not mStorage->save()) {
        warning() << Q_FUNC_INFO << "Failed to delete event from calendar";
        return;
    }

    debug() << "Deleted birthday event in calendar, local ID: " << event->uid();
}

QDate CDBirthdayCalendar::birthdayDate(QContactLocalId contactId)
{
    KCalCore::Event::Ptr event = calendarEvent(contactId);

    if (event.isNull()) {
        return QDate();
    }

    return event->dtStart().date();
}

QString CDBirthdayCalendar::summary(QContactLocalId contactId)
{
    KCalCore::Event::Ptr event = calendarEvent(contactId);

    if (event.isNull()) {
        return QString();
    }

    return event->summary();
}

QString CDBirthdayCalendar::calendarEventId(QContactLocalId contactId)
{
    static const QLatin1String calIdExtension("com.nokia.birthday/");
    return calIdExtension + QString::number(contactId);
}

KCalCore::Event::Ptr CDBirthdayCalendar::calendarEvent(QContactLocalId contactId)
{
    const QString eventId = calendarEventId(contactId);

    if (not mStorage->load(eventId)) {
        warning() << Q_FUNC_INFO << "Unable to load event from calendar";
        return KCalCore::Event::Ptr();
    }

    KCalCore::Event::Ptr event = mCalendar->event(eventId);

    if (event.isNull()) {
        debug() << Q_FUNC_INFO << "Not found in calendar:" << contactId;
    }

    return event;
}

void CDBirthdayCalendar::onLocaleChanged()
{
    mKCal::Notebook::Ptr notebook = mStorage->notebook(calNotebookId);

    if (notebook.isNull()) {
        warning() << Q_FUNC_INFO << "Calendar not found while changing locale";
        return;
    }

    const QString name = qtTrId("qtn_caln_birthdays");

    debug() << Q_FUNC_INFO << "Updating calendar name to" << name;
    notebook->setName(name);

    if (not mStorage->updateNotebook(notebook)) {
        warning() << Q_FUNC_INFO << "Could not save calendar";
    }
}
<commit_msg>birthday: Precise all reminder parameters<commit_after>/** This file is part of Contacts daemon
 **
 ** Copyright (c) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
 **
 ** Contact:  Nokia Corporation (info@qt.nokia.com)
 **
 ** GNU Lesser General Public License Usage
 ** This file may be used under the terms of the GNU Lesser General Public License
 ** version 2.1 as published by the Free Software Foundation and appearing in the
 ** file LICENSE.LGPL included in the packaging of this file.  Please review the
 ** following information to ensure the GNU Lesser General Public License version
 ** 2.1 requirements will be met:
 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
 **
 ** In addition, as a special exception, Nokia gives you certain additional rights.
 ** These rights are described in the Nokia Qt LGPL Exception version 1.1, included
 ** in the file LGPL_EXCEPTION.txt in this package.
 **
 ** Other Usage
 ** Alternatively, this file may be used in accordance with the terms and
 ** conditions contained in a signed written agreement between you and Nokia.
 **/

#include <QStringBuilder>

#include <QContactName>
#include <QContactBirthday>

#include <MLocale>

#include <recurrencerule.h>

#include "cdbirthdaycalendar.h"
#include "debug.h"

using namespace Contactsd;

// A random ID.
const QLatin1String calNotebookId("b1376da7-5555-1111-2222-227549c4e570");

CDBirthdayCalendar::CDBirthdayCalendar(SyncMode syncMode, QObject *parent) :
    QObject(parent),
    mCalendar(0),
    mStorage(0)
{
    mCalendar = mKCal::ExtendedCalendar::Ptr(new mKCal::ExtendedCalendar(KDateTime::Spec::LocalZone()));
    mStorage = mKCal::ExtendedCalendar::defaultStorage(mCalendar);

    MLocale * const locale = new MLocale(this);

    if (not locale->isInstalledTrCatalog(QLatin1String("calendar"))) {
        locale->installTrCatalog(QLatin1String("calendar"));
    }

    locale->connectSettings();
    connect(locale, SIGNAL(settingsChanged()), this, SLOT(onLocaleChanged()));

    MLocale::setDefault(*locale);

    mStorage->open();

    mKCal::Notebook::Ptr notebook = mStorage->notebook(calNotebookId);

    if (notebook.isNull()) {
        notebook = createNotebook();
        mStorage->addNotebook(notebook);
    } else {
        // Clear the calendar database if and only if restoring from a backup.
        switch(syncMode) {
        case Incremental:
            // Force calendar name update, if a locale change happened while contactsd was not running.
            onLocaleChanged();
            break;

        case FullSync:
            mStorage->deleteNotebook(notebook);
            notebook = createNotebook();
            mStorage->addNotebook(notebook);
            break;
        }
    }
}

CDBirthdayCalendar::~CDBirthdayCalendar()
{
    if (mStorage) {
        mStorage->close();
    }

    debug() << "Destroyed birthday calendar";
}

mKCal::Notebook::Ptr CDBirthdayCalendar::createNotebook()
{
    return mKCal::Notebook::Ptr(new mKCal::Notebook(calNotebookId,
                                                    qtTrId("qtn_caln_birthdays"),
                                                    QLatin1String(""),
                                                    QLatin1String("#ff0000"),
                                                    false, // Not shared.
                                                    true, // Is master.
                                                    false, // Not synced to Ovi.
                                                    false, // Writable.
                                                    true, // Visible.
                                                    QLatin1String("Birthday-Nokia"),
                                                    QLatin1String(""),
                                                    0));
}

void CDBirthdayCalendar::updateBirthday(const QContact &contact)
{
    // Retrieve contact details.
    const QContactDisplayLabel displayName = contact.detail<QContactDisplayLabel>();
    const QContactBirthday contactBirthday = contact.detail<QContactBirthday>();

    if (displayName.isEmpty() || contactBirthday.isEmpty()) {
        warning() << Q_FUNC_INFO << "Contact without name or birthday, local ID: "
                  << contact.localId();
        return;
    }

    // Retrieve birthday event.
    if (not mStorage->isValidNotebook(calNotebookId)) {
        warning() << Q_FUNC_INFO << "Invalid notebook ID: " << calNotebookId;
        return;
    }

    KCalCore::Event::Ptr event = calendarEvent(contact.localId());

    if (event.isNull()) {
        // Add a new event.
        event = KCalCore::Event::Ptr(new KCalCore::Event());
        event->startUpdates();
        event->setUid(calendarEventId(contact.localId()));
        event->setAllDay(true);

        // Ensure events appear as birthdays in the calendar, NB#259710.
        event->setCategories(QStringList() << QLatin1String("BIRTHDAY"));

        if (not mCalendar->addEvent(event, calNotebookId)) {
            warning() << Q_FUNC_INFO << "Failed to add event to calendar";
            return;
        }
    } else {
        // Update the existing event.
        event->setReadOnly(false);
        event->startUpdates();
    }

    // Transfer birthday details from contact to calendar event.
    event->setSummary(displayName.label());

    // Event has only date information, no time.
    event->setDtStart(KDateTime(contactBirthday.date(), QTime(), KDateTime::ClockTime));
    event->setDtEnd(KDateTime(contactBirthday.date().addDays(1), QTime(), KDateTime::ClockTime));

    // Must always set the recurrence as it depends on the event date.
    KCalCore::Recurrence * const rule = event->recurrence();
    rule->setStartDateTime(event->dtStart());

    // This is not a boolean, but the frequency of the recurrence: every 1 year.
    rule->setYearly(1);

    // Set the alarms on the event
    event->clearAlarms();
    KCalCore::Alarm::Ptr alarm = event->newAlarm();
    alarm->setType(KCalCore::Alarm::Audio);
    alarm->setEnabled(true);
    alarm->setDisplayAlarm(event->summary());
    alarm->setStartOffset(KCalCore::Duration(-1, KCalCore::Duration::Days));

    event->setReadOnly(true);
    event->endUpdates();

    // Commit calendar changes.
    if (not mStorage->save()) {
        warning() << Q_FUNC_INFO << "Failed to save event in calendar";
        return;
    }

    debug() << "Updated birthday event in calendar, local ID: " << contact.localId();
}

void CDBirthdayCalendar::deleteBirthday(QContactLocalId contactId)
{
    KCalCore::Event::Ptr event = calendarEvent(contactId);

    if (event.isNull()) {
        debug() << Q_FUNC_INFO << "Not found in calendar:" << contactId;
        return;
    }

    mCalendar->deleteEvent(event);

    if (not mStorage->save()) {
        warning() << Q_FUNC_INFO << "Failed to delete event from calendar";
        return;
    }

    debug() << "Deleted birthday event in calendar, local ID: " << event->uid();
}

QDate CDBirthdayCalendar::birthdayDate(QContactLocalId contactId)
{
    KCalCore::Event::Ptr event = calendarEvent(contactId);

    if (event.isNull()) {
        return QDate();
    }

    return event->dtStart().date();
}

QString CDBirthdayCalendar::summary(QContactLocalId contactId)
{
    KCalCore::Event::Ptr event = calendarEvent(contactId);

    if (event.isNull()) {
        return QString();
    }

    return event->summary();
}

QString CDBirthdayCalendar::calendarEventId(QContactLocalId contactId)
{
    static const QLatin1String calIdExtension("com.nokia.birthday/");
    return calIdExtension + QString::number(contactId);
}

KCalCore::Event::Ptr CDBirthdayCalendar::calendarEvent(QContactLocalId contactId)
{
    const QString eventId = calendarEventId(contactId);

    if (not mStorage->load(eventId)) {
        warning() << Q_FUNC_INFO << "Unable to load event from calendar";
        return KCalCore::Event::Ptr();
    }

    KCalCore::Event::Ptr event = mCalendar->event(eventId);

    if (event.isNull()) {
        debug() << Q_FUNC_INFO << "Not found in calendar:" << contactId;
    }

    return event;
}

void CDBirthdayCalendar::onLocaleChanged()
{
    mKCal::Notebook::Ptr notebook = mStorage->notebook(calNotebookId);

    if (notebook.isNull()) {
        warning() << Q_FUNC_INFO << "Calendar not found while changing locale";
        return;
    }

    const QString name = qtTrId("qtn_caln_birthdays");

    debug() << Q_FUNC_INFO << "Updating calendar name to" << name;
    notebook->setName(name);

    if (not mStorage->updateNotebook(notebook)) {
        warning() << Q_FUNC_INFO << "Could not save calendar";
    }
}
<|endoftext|>