<commit_before>/**
 * \file
 * <!--
 * Copyright 2015 Develer S.r.l. (http://www.develer.com/)
 * -->
 *
 * \brief OutputManager class implementation
 *
 * \author Aurelien Rainone <aurelien@develer.org>
 */

#include "outputmanager.h"

OutputManager::OutputManager(QObject *parent) : QObject(parent)
{

}

void OutputManager::operator << (const QByteArray &data)
{
    // append raw data to the session buffer
    _buffer.append(data);

    // notify that we have new data (in display format)
    emit dataConverted(QString::fromLocal8Bit(data));
}

const QByteArray& OutputManager::buffer()
{
    return _buffer;
}

void OutputManager::clear()
{
    _buffer.clear();
}
<commit_msg>fix incorrect number of line jumps in output<commit_after>/**
 * \file
 * <!--
 * Copyright 2015 Develer S.r.l. (http://www.develer.com/)
 * -->
 *
 * \brief OutputManager class implementation
 *
 * \author Aurelien Rainone <aurelien@develer.org>
 */

#include "outputmanager.h"

#include <algorithm>
#include <iterator>

OutputManager::OutputManager(QObject *parent) : QObject(parent)
{

}

void OutputManager::operator << (const QByteArray &data)
{
    // problem : if a buffer ending with "\r\n" happens to be cut between '\r' and '\n'
    //           the 2 resulting QString will be interpreted as having 2 line jumps,
    //           instead of 1, if displayed in a QTextEdit.
    //           To avoid this, final '\r' are removed from the received buffer,
    //           and prepended to the next one

    // flag indicating that the previously received buffer ended with CR
    static bool prev_ends_with_CR = false;

    // append raw data to the buffer, untouched
    _buffer.append(data);

    QString to_send;
    if (prev_ends_with_CR)
    {
        // CR was removed at the previous buffer, so now we prepend it
        to_send.append('\r');
        prev_ends_with_CR = false;
    }

    if (data.size() > 0)
    {
        QByteArray::const_iterator end_cit = data.cend();
        if (data.endsWith('\r'))
        {
            // if buffer ends with CR, we don't copy it
            end_cit--;
            prev_ends_with_CR = true;
        }
        std::copy(data.begin(), end_cit, std::back_inserter(to_send));
    }

    // notify that we have new data
    emit dataConverted(to_send);
}

const QByteArray& OutputManager::buffer()
{
    return _buffer;
}

void OutputManager::clear()
{
    _buffer.clear();
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS chart19 (1.5.10); FILE MERGED 2008/01/08 12:14:59 iha 1.5.10.3: #i37823# clockwise pie charts 2007/12/18 13:45:20 bm 1.5.10.2: RESYNC: (1.5-1.6); FILE MERGED 2007/12/15 13:00:58 iha 1.5.10.1: #i16776# starting angle for pie charts<commit_after><|endoftext|>


<commit_before>#include "mitkImageMapper2D.h"
#include "mitkRenderWindow.h"
#include "widget.h"
#include "picimage.h"
#include "pic2vtk.h"
#include "PlaneGeometry.h"
#include "BaseRenderer.h"
#include "DataTreeNode.h"
#include "mitkColorProperty.h"
#include "mitkLevelWindowProperty.h"
#include "mitkFloatProperty.h"

#include <vtkImageReslice.h>
#include <vtkTransform.h>
#include <vtkMatrix4x4.h>

int mitk::ImageMapper2D::numRenderer = 0;

mitk::ImageMapper2D::ImageMapper2D() : m_SliceSelector(NULL)
{
	// Modify superclass default values, can be overridden by subclasses
	this->SetNumberOfRequiredInputs(1);

    m_SliceSelector = ImageSliceSelector::New();
    m_Reslicer = vtkImageReslice::New();

}

//##ModelId=3E32DCF60043
mitk::ImageMapper2D::~ImageMapper2D()
{
    //FIXME: durch die folgende Zeile sollte doch wohl der desctructor von RendererInfo aufgerufen werden. Das passiert aber nie. Deshalb wird bei der Programm-Beendung auch das iilImage und damit die textur nicht rechtzeitig freigegeben und das Programm crashed.
    m_RendererInfo.clear();
}

//##ModelId=3E3D834B003A
void mitk::ImageMapper2D::GenerateData()
{

}

void mitk::ImageMapper2D::Paint(mitk::BaseRenderer * renderer)
{
	RendererInfo& renderinfo=m_RendererInfo[renderer];
	DataTreeNode* node=GetDataTreeNode();

    if( (renderinfo.m_LastUpdateTime < renderer->GetMTime()) ||
		(renderinfo.m_LastUpdateTime < node->GetMTime()) ||
		(renderinfo.m_LastUpdateTime < node->GetPropertyList()->GetMTime())
	  )
		GenerateData(renderer);

	iilPicImage*& image = renderinfo.m_iilImage;

	const mitk::DisplayGeometry* displayGeometry = renderer->GetDisplayGeometry();

	Point2D topLeft=displayGeometry->GetOriginInUnits();
	Point2D bottomRight=displayGeometry->GetOriginInUnits()+displayGeometry->GetSizeInUnits();
	Point2D topLeftGL(topLeft.x, displayGeometry->GetWorldGeometry()->GetHeightInUnits()-topLeft.y);
	Point2D bottomRightGL(bottomRight.x, displayGeometry->GetWorldGeometry()->GetHeightInUnits()-bottomRight.y);

	glMatrixMode (GL_PROJECTION);
	glLoadIdentity ();
	// fixed images upside down bug, original line seemed to be correct...
	gluOrtho2D(topLeftGL.x, bottomRightGL.x, bottomRightGL.y, topLeftGL.y );
	// workaround, FIXME  !!!
	//gluOrtho2D(topLeftGL.x, bottomRightGL.x, topLeftGL.y, bottomRightGL.y );
	glMatrixMode( GL_MODELVIEW );

	Vector2D bottom(0, image->height());
	displayGeometry->UnitsToDisplay(bottom, bottom);
	assert(bottom.y >= 0);
	renderer->GetRenderWindow()->m_CurHeightInDisplayUnits = (unsigned int)(bottom.y);

	GLdouble eqn0[4] = {0.0, 1.0, 0.0, 0.0};
	GLdouble eqn1[4] = {1.0, 0.0, 0.0, 0.0};
	GLdouble eqn2[4] = {-1.0, 0.0 , 0.0, image->width()};
	GLdouble eqn3[4] = {0, -1.0, 0.0, image->height() };

	glClipPlane (GL_CLIP_PLANE0, eqn0);
	glEnable (GL_CLIP_PLANE0);
	glClipPlane (GL_CLIP_PLANE1, eqn1);
	glEnable (GL_CLIP_PLANE1);
	glClipPlane (GL_CLIP_PLANE2, eqn2);
	glEnable (GL_CLIP_PLANE2);
	glClipPlane (GL_CLIP_PLANE3, eqn3);
	glEnable (GL_CLIP_PLANE3);

	image->display(renderer->GetRenderWindow());

	glDisable (GL_CLIP_PLANE0);
	glDisable (GL_CLIP_PLANE1);
	glDisable (GL_CLIP_PLANE2);
	glDisable (GL_CLIP_PLANE3);

	glPushMatrix ();
	glMatrixMode (GL_PROJECTION);
	glLoadIdentity ();
	gluOrtho2D(0, displayGeometry->GetDisplayWidth(), 0, displayGeometry->GetDisplayHeight() );
	glMatrixMode( GL_MODELVIEW );
	glPopMatrix ();
}

//##ModelId=3E3D834B0008
const mitk::ImageMapper2D::InputImageType *mitk::ImageMapper2D::GetInput(void)
{
	if (this->GetNumberOfInputs() < 1)
	{
		return 0;
	}

	return static_cast<const mitk::ImageMapper2D::InputImageType * >
        ( GetData() );
}

//##ModelId=3E6E83B00343
int mitk::ImageMapper2D::GetAssociatedChannelNr(mitk::BaseRenderer *renderer)
{
	RendererInfo& renderinfo=m_RendererInfo[renderer];
    if(renderinfo.m_RendererId < 0)
        renderinfo.m_RendererId = ImageMapper2D::numRenderer++;

    return renderinfo.m_RendererId;
}

//##ModelId=3E8607D20380
void mitk::ImageMapper2D::GenerateOutputInformation()
{
   	mitk::Image::Pointer output = this->GetOutput();
	mitk::PixelType pt(typeid(int));
	unsigned int dim[]={256,256};
	output->Initialize(mitk::PixelType(typeid(short int)), 2, dim, 10);
}

//##ModelId=3ED932B00140
void mitk::ImageMapper2D::GenerateData(mitk::BaseRenderer *renderer)
{
	RendererInfo& renderinfo=m_RendererInfo[renderer];

    iilPicImage*& image = renderinfo.m_iilImage;

    mitk::Image::Pointer input  = const_cast<mitk::ImageMapper2D::InputImageType *>(this->GetInput());

    if(image!= NULL)
    {
        delete image;
        image = NULL;
    }

    if(renderinfo.m_Pic)
    {
        ipPicFree(renderinfo.m_Pic);
        renderinfo.m_Pic = NULL;
    }

    if(renderinfo.m_RendererId < 0)
        renderinfo.m_RendererId = ImageMapper2D::numRenderer++;

    if(input.IsNotNull())
    {
        // #define DEBUG

//        input->Update();
        vtkImageData* inputData = input->GetVtkImageData();

        vtkMatrix4x4* geometry = vtkMatrix4x4::New();
        geometry->Identity();

        vtkTransform* transform = vtkTransform::New();
        transform->Identity();

        m_Reslicer->SetInput(inputData);
        m_Reslicer->SetOutputDimensionality(2);
	m_Reslicer->SetOutputSpacing(1.0,1.0,1.0);
 	m_Reslicer->SetOutputOrigin(0,0,0);
        m_Reslicer->SetBackgroundLevel(-1024);
        PlaneGeometry* myPlaneGeom =
            dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(renderer->GetWorldGeometry()));
        assert(myPlaneGeom);
        assert(myPlaneGeom->GetPlaneView().normal.length()>0.1);

        double origin[3];
        origin[0]=myPlaneGeom->GetPlaneView().point.x;
        origin[1]=myPlaneGeom->GetPlaneView().point.y;
        origin[2]=myPlaneGeom->GetPlaneView().point.z;

        m_Reslicer->SetResliceAxes(geometry);
        m_Reslicer->SetResliceAxesOrigin(origin);
//        m_Reslicer->SetInterpolationModeToLinear();
        double cosines[9];
        Vector3f orient1 = myPlaneGeom->GetPlaneView().getOrientation1();
        orient1.normalize();

        Vector3f orient2 = myPlaneGeom->GetPlaneView().getOrientation2();
        orient2.normalize();

	// Richtung der X-Achse der Ergebnisschicht im Volumen,
        cosines[0]=orient1.x;
        cosines[1]=orient1.y;
        cosines[2]=orient1.z;

	//Richtung der Y-Achse der Ergebnisschicht im Volumen
        cosines[3]=orient2.x;
        cosines[4]=orient2.y;
        cosines[5]=orient2.z;

	// Schichtfolge/Projektionsrichtung
        cosines[6]= myPlaneGeom->GetPlaneView().normal.x;
        cosines[7]= myPlaneGeom->GetPlaneView().normal.y;
        cosines[8]= myPlaneGeom->GetPlaneView().normal.z;
        m_Reslicer->SetResliceAxesDirectionCosines(cosines);

        m_Reslicer->Update();

		vtkImageData* vtkoutput = m_Reslicer->GetOutput();

        assert(vtkoutput);

		//	std::cout << vtkoutput <<std::endl;
        ipPicDescriptor* pic = Pic2vtk::convert(vtkoutput);
        assert(pic);
        if(pic->dim==1)
        {
            pic->dim=2;
            pic->n[1]=1;
        }

        renderinfo.m_Pic = pic;

        //std::cout << "Pic dimensions:" << pic->dim << std::endl;

        image = new iilPicImage(NULL, "ll", 512);

		image->setImage(pic, iilImage::INTENSITY_ALPHA);
        image->setInterpolation(true);
		image->setExtrema(0, 255);
        assert(pic->dim == 2);

        //query and set color
        const mitk::DataTreeNode* node=GetDataTreeNode();
        float rgba[4]={1.0f,1.0f,1.0f,1.0f};
        if(node!=NULL)
        {
            // check for color prop and use it for rendering if it exists
			mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList()->GetProperty("color").GetPointer());
            if(colorprop.IsNotNull())
                memcpy(rgba, colorprop->GetColor().GetDataPointer(), 3*sizeof(float));

			// check for opacity prop and use it for rendering if it exists
            mitk::FloatProperty::Pointer opacityprop = dynamic_cast<mitk::FloatProperty*>(node->GetPropertyList()->GetProperty("opacity").GetPointer());
            if(opacityprop.IsNotNull())
                rgba[3]=opacityprop->GetValue();

			// check for level window prop and use it for display if it exists
			mitk::LevelWindowProperty::Pointer levWinProp = dynamic_cast<mitk::LevelWindowProperty*>(node->GetPropertyList()->GetProperty("levelwindow").GetPointer());
			if(levWinProp.IsNotNull()) {
				image->setExtrema(levWinProp->GetLevelWindow().GetMin(),levWinProp->GetLevelWindow().GetMax());
			}
		}

		image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]);
		image->setRegion(0,0,pic->n[0],pic->n[1]);

		mitk::Image::Pointer output = this->GetOutput();

		//if(renderinfo.m_RendererId < 10)
		//	output->SetPicSlice(pic,0,0,renderinfo.m_RendererId);
		output->Modified();
		renderinfo.m_LastUpdateTime=output->GetMTime();
    }
	return;
}

void mitk::ImageMapper2D::GenerateAllData()
{
	std::map<mitk::BaseRenderer*,RendererInfo>::iterator it=m_RendererInfo.begin();
	for(;it!=m_RendererInfo.end();++it)
	{
		RendererInfo& renderinfo=it->second;
		DataTreeNode* node=GetDataTreeNode();
		if( (renderinfo.m_LastUpdateTime < it->first->GetMTime()) ||
			(renderinfo.m_LastUpdateTime < node->GetMTime()) ||
			(renderinfo.m_LastUpdateTime < node->GetPropertyList()->GetMTime())
		  )
			GenerateData(it->first);
	}
}
<commit_msg>output size of reslice is now according to PlaneGeometry-SizeInUnits.<commit_after>#include "mitkImageMapper2D.h"
#include "mitkRenderWindow.h"
#include "widget.h"
#include "picimage.h"
#include "pic2vtk.h"
#include "PlaneGeometry.h"
#include "BaseRenderer.h"
#include "DataTreeNode.h"
#include "mitkColorProperty.h"
#include "mitkLevelWindowProperty.h"
#include "mitkFloatProperty.h"

#include <vtkImageReslice.h>
#include <vtkTransform.h>
#include <vtkMatrix4x4.h>

int mitk::ImageMapper2D::numRenderer = 0;

mitk::ImageMapper2D::ImageMapper2D() : m_SliceSelector(NULL)
{
	// Modify superclass default values, can be overridden by subclasses
	this->SetNumberOfRequiredInputs(1);

    m_SliceSelector = ImageSliceSelector::New();
    m_Reslicer = vtkImageReslice::New();

}

//##ModelId=3E32DCF60043
mitk::ImageMapper2D::~ImageMapper2D()
{
    //FIXME: durch die folgende Zeile sollte doch wohl der desctructor von RendererInfo aufgerufen werden. Das passiert aber nie. Deshalb wird bei der Programm-Beendung auch das iilImage und damit die textur nicht rechtzeitig freigegeben und das Programm crashed.
    m_RendererInfo.clear();
}

//##ModelId=3E3D834B003A
void mitk::ImageMapper2D::GenerateData()
{

}

void mitk::ImageMapper2D::Paint(mitk::BaseRenderer * renderer)
{
	RendererInfo& renderinfo=m_RendererInfo[renderer];
	DataTreeNode* node=GetDataTreeNode();

    if( (renderinfo.m_LastUpdateTime < renderer->GetMTime()) ||
		(renderinfo.m_LastUpdateTime < node->GetMTime()) ||
		(renderinfo.m_LastUpdateTime < node->GetPropertyList()->GetMTime())
	  )
		GenerateData(renderer);

	iilPicImage*& image = renderinfo.m_iilImage;

	const mitk::DisplayGeometry* displayGeometry = renderer->GetDisplayGeometry();

	Point2D topLeft=displayGeometry->GetOriginInUnits();
	Point2D bottomRight=displayGeometry->GetOriginInUnits()+displayGeometry->GetSizeInUnits();
	Point2D topLeftGL(topLeft.x, displayGeometry->GetWorldGeometry()->GetHeightInUnits()-topLeft.y);
	Point2D bottomRightGL(bottomRight.x, displayGeometry->GetWorldGeometry()->GetHeightInUnits()-bottomRight.y);

	glMatrixMode (GL_PROJECTION);
	glLoadIdentity ();
	// fixed images upside down bug, original line seemed to be correct...
	gluOrtho2D(topLeftGL.x, bottomRightGL.x, bottomRightGL.y, topLeftGL.y );
	// workaround, FIXME  !!!
	//gluOrtho2D(topLeftGL.x, bottomRightGL.x, topLeftGL.y, bottomRightGL.y );
	glMatrixMode( GL_MODELVIEW );

	Vector2D bottom(0, image->height());
	displayGeometry->UnitsToDisplay(bottom, bottom);
	assert(bottom.y >= 0);
	renderer->GetRenderWindow()->m_CurHeightInDisplayUnits = (unsigned int)(bottom.y);

	GLdouble eqn0[4] = {0.0, 1.0, 0.0, 0.0};
	GLdouble eqn1[4] = {1.0, 0.0, 0.0, 0.0};
	GLdouble eqn2[4] = {-1.0, 0.0 , 0.0, image->width()};
	GLdouble eqn3[4] = {0, -1.0, 0.0, image->height() };

	glClipPlane (GL_CLIP_PLANE0, eqn0);
	glEnable (GL_CLIP_PLANE0);
	glClipPlane (GL_CLIP_PLANE1, eqn1);
	glEnable (GL_CLIP_PLANE1);
	glClipPlane (GL_CLIP_PLANE2, eqn2);
	glEnable (GL_CLIP_PLANE2);
	glClipPlane (GL_CLIP_PLANE3, eqn3);
	glEnable (GL_CLIP_PLANE3);

	image->display(renderer->GetRenderWindow());

	glDisable (GL_CLIP_PLANE0);
	glDisable (GL_CLIP_PLANE1);
	glDisable (GL_CLIP_PLANE2);
	glDisable (GL_CLIP_PLANE3);

	glPushMatrix ();
	glMatrixMode (GL_PROJECTION);
	glLoadIdentity ();
	gluOrtho2D(0, displayGeometry->GetDisplayWidth(), 0, displayGeometry->GetDisplayHeight() );
	glMatrixMode( GL_MODELVIEW );
	glPopMatrix ();
}

//##ModelId=3E3D834B0008
const mitk::ImageMapper2D::InputImageType *mitk::ImageMapper2D::GetInput(void)
{
	if (this->GetNumberOfInputs() < 1)
	{
		return 0;
	}

	return static_cast<const mitk::ImageMapper2D::InputImageType * >
        ( GetData() );
}

//##ModelId=3E6E83B00343
int mitk::ImageMapper2D::GetAssociatedChannelNr(mitk::BaseRenderer *renderer)
{
	RendererInfo& renderinfo=m_RendererInfo[renderer];
    if(renderinfo.m_RendererId < 0)
        renderinfo.m_RendererId = ImageMapper2D::numRenderer++;

    return renderinfo.m_RendererId;
}

//##ModelId=3E8607D20380
void mitk::ImageMapper2D::GenerateOutputInformation()
{
   	mitk::Image::Pointer output = this->GetOutput();
	mitk::PixelType pt(typeid(int));
	unsigned int dim[]={256,256};
	output->Initialize(mitk::PixelType(typeid(short int)), 2, dim, 10);
}

//##ModelId=3ED932B00140
void mitk::ImageMapper2D::GenerateData(mitk::BaseRenderer *renderer)
{
	RendererInfo& renderinfo=m_RendererInfo[renderer];

    iilPicImage*& image = renderinfo.m_iilImage;

    mitk::Image::Pointer input  = const_cast<mitk::ImageMapper2D::InputImageType *>(this->GetInput());

    if(image!= NULL)
    {
        delete image;
        image = NULL;
    }

    if(renderinfo.m_Pic)
    {
        ipPicFree(renderinfo.m_Pic);
        renderinfo.m_Pic = NULL;
    }

    if(renderinfo.m_RendererId < 0)
        renderinfo.m_RendererId = ImageMapper2D::numRenderer++;

    if(input.IsNotNull())
    {
        // #define DEBUG

//        input->Update();
        vtkImageData* inputData = input->GetVtkImageData();

        vtkMatrix4x4* geometry = vtkMatrix4x4::New();
        geometry->Identity();

        vtkTransform* transform = vtkTransform::New();
        transform->Identity();

        m_Reslicer->SetInput(inputData);
        m_Reslicer->SetOutputDimensionality(2);
 	m_Reslicer->SetOutputOrigin(0,0,0);

        m_Reslicer->SetBackgroundLevel(-1024);
        PlaneGeometry* myPlaneGeom =
            dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(renderer->GetWorldGeometry()));
        assert(myPlaneGeom);
        assert(myPlaneGeom->GetPlaneView().normal.length()>0.1);

    	m_Reslicer->SetOutputSpacing(myPlaneGeom->GetPlaneView().getLengthOfOrientation1()/myPlaneGeom->GetWidthInUnits(), myPlaneGeom->GetPlaneView().getLengthOfOrientation2()/myPlaneGeom->GetHeightInUnits(),1.0);
        m_Reslicer->SetOutputExtent(0.0, myPlaneGeom->GetWidthInUnits()-1, 0.0, myPlaneGeom->GetHeightInUnits()-1, 0.0, 1.0);

        double origin[3];
        origin[0]=myPlaneGeom->GetPlaneView().point.x;
        origin[1]=myPlaneGeom->GetPlaneView().point.y;
        origin[2]=myPlaneGeom->GetPlaneView().point.z;

        m_Reslicer->SetResliceAxes(geometry);
        m_Reslicer->SetResliceAxesOrigin(origin);
//        m_Reslicer->SetInterpolationModeToLinear();
        double cosines[9];
        Vector3f orient1 = myPlaneGeom->GetPlaneView().getOrientation1();
        orient1.normalize();

        Vector3f orient2 = myPlaneGeom->GetPlaneView().getOrientation2();
        orient2.normalize();

	// Richtung der X-Achse der Ergebnisschicht im Volumen,
        cosines[0]=orient1.x;
        cosines[1]=orient1.y;
        cosines[2]=orient1.z;

	//Richtung der Y-Achse der Ergebnisschicht im Volumen
        cosines[3]=orient2.x;
        cosines[4]=orient2.y;
        cosines[5]=orient2.z;

	// Schichtfolge/Projektionsrichtung
        cosines[6]= myPlaneGeom->GetPlaneView().normal.x;
        cosines[7]= myPlaneGeom->GetPlaneView().normal.y;
        cosines[8]= myPlaneGeom->GetPlaneView().normal.z;
        m_Reslicer->SetResliceAxesDirectionCosines(cosines);

        m_Reslicer->Update();

		vtkImageData* vtkoutput = m_Reslicer->GetOutput();

        assert(vtkoutput);

		//	std::cout << vtkoutput <<std::endl;
        ipPicDescriptor* pic = Pic2vtk::convert(vtkoutput);
        assert(pic);
        if(pic->dim==1)
        {
            pic->dim=2;
            pic->n[1]=1;
        }

        renderinfo.m_Pic = pic;

        //std::cout << "Pic dimensions:" << pic->dim << std::endl;

        image = new iilPicImage(NULL, "ll", 512);

		image->setImage(pic, iilImage::INTENSITY_ALPHA);
        image->setInterpolation(true);
		image->setExtrema(0, 255);
        assert(pic->dim == 2);

        //query and set color
        const mitk::DataTreeNode* node=GetDataTreeNode();
        float rgba[4]={1.0f,1.0f,1.0f,1.0f};
        if(node!=NULL)
        {
            // check for color prop and use it for rendering if it exists
			mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(node->GetPropertyList()->GetProperty("color").GetPointer());
            if(colorprop.IsNotNull())
                memcpy(rgba, colorprop->GetColor().GetDataPointer(), 3*sizeof(float));

			// check for opacity prop and use it for rendering if it exists
            mitk::FloatProperty::Pointer opacityprop = dynamic_cast<mitk::FloatProperty*>(node->GetPropertyList()->GetProperty("opacity").GetPointer());
            if(opacityprop.IsNotNull())
                rgba[3]=opacityprop->GetValue();

			// check for level window prop and use it for display if it exists
			mitk::LevelWindowProperty::Pointer levWinProp = dynamic_cast<mitk::LevelWindowProperty*>(node->GetPropertyList()->GetProperty("levelwindow").GetPointer());
			if(levWinProp.IsNotNull()) {
				image->setExtrema(levWinProp->GetLevelWindow().GetMin(),levWinProp->GetLevelWindow().GetMax());
			}
		}

		image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]);
		image->setRegion(0,0,pic->n[0],pic->n[1]);

		mitk::Image::Pointer output = this->GetOutput();

		//if(renderinfo.m_RendererId < 10)
		//	output->SetPicSlice(pic,0,0,renderinfo.m_RendererId);
		output->Modified();
		renderinfo.m_LastUpdateTime=output->GetMTime();
    }
	return;
}

void mitk::ImageMapper2D::GenerateAllData()
{
	std::map<mitk::BaseRenderer*,RendererInfo>::iterator it=m_RendererInfo.begin();
	for(;it!=m_RendererInfo.end();++it)
	{
		RendererInfo& renderinfo=it->second;
		DataTreeNode* node=GetDataTreeNode();
		if( (renderinfo.m_LastUpdateTime < it->first->GetMTime()) ||
			(renderinfo.m_LastUpdateTime < node->GetMTime()) ||
			(renderinfo.m_LastUpdateTime < node->GetPropertyList()->GetMTime())
		  )
			GenerateData(it->first);
	}
}
<|endoftext|>


<commit_before>/*
 Copyright (C) 2012-2014 Soomla Inc.

 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 "Soomla/domain/CCPurchasableVirtualItem.h"

#include <Soomla/CCJsonHelper.h>

#include "Soomla/PurchaseTypes/CCPurchaseWithMarket.h"
#include "Soomla/PurchaseTypes/CCPurchaseWithVirtualItem.h"

namespace soomla {

using namespace cocos2d;

bool CCPurchasableVirtualItem::init(const std::string& name,
                                    const std::string& description,
                                    const std::string& itemId,
                                    soomla::CCPurchaseType* purchaseType) {
    bool bRet = CCVirtualItem::init(itemId, name, description);
    if (bRet) {
        setPurchaseType(purchaseType);
        purchaseType->setAssociatedItemId(getItemId());
    }
    return bRet;
}

bool CCPurchasableVirtualItem::initWithValueMap(const cocos2d::ValueMap& map) {
    bool bRet = CCVirtualItem::initWithValueMap(map);
    if (bRet) {
        fillPurchaseTypeFromValueMap(map);
        return true;
    } else {
        return false;
    }
}

CCPurchasableVirtualItem::~CCPurchasableVirtualItem() {
    CC_SAFE_RELEASE(mPurchaseType);
}

ValueMap CCPurchasableVirtualItem::toValueMap() {
    auto&& map = CCVirtualItem::toValueMap();
    putPurchaseTypeToValueMap(map);
    return map;
}

bool CCPurchasableVirtualItem::canAfford(CCError** error) {
    return getPurchaseType()->canAfford(error);
}

void CCPurchasableVirtualItem::buy(const std::string& payload, CCError** error) {
    if (!canBuy()) {
        return;
    }

    getPurchaseType()->buy(payload, error);
}

void CCPurchasableVirtualItem::fillPurchaseTypeFromValueMap(
    const cocos2d::ValueMap& dict) {
    CC_ASSERT(dict.count(CCStoreConsts::JSON_PURCHASABLE_ITEM));
    auto& purchasableDict =
        dict.at(CCStoreConsts::JSON_PURCHASABLE_ITEM).asValueMap();
    CCASSERT(purchasableDict.count(CCStoreConsts::JSON_PURCHASE_TYPE),
             "invalid object type in dictionary");
    auto&& purchaseTypeStr =
        purchasableDict.at(CCStoreConsts::JSON_PURCHASE_TYPE).asString();

    if (purchaseTypeStr.compare(CCStoreConsts::JSON_PURCHASE_TYPE_MARKET) ==
        0) {
        CC_ASSERT(purchasableDict.count(CCStoreConsts::JSON_PURCHASE_MARKET_ITEM));
        auto& marketItemDict =
            purchasableDict.at(CCStoreConsts::JSON_PURCHASE_MARKET_ITEM).asValueMap();

        setPurchaseType(CCPurchaseWithMarket::createWithMarketItem(
            CCMarketItem::createWithValueMap(marketItemDict)));
    } else if (purchaseTypeStr.compare(CCStoreConsts::JSON_PURCHASE_TYPE_VI) ==
               0) {
        CC_ASSERT(
            purchasableDict.count(CCStoreConsts::JSON_PURCHASE_VI_ITEM_ID));
        auto&& itemId =
            purchasableDict.at(CCStoreConsts::JSON_PURCHASE_VI_ITEM_ID)
                .asString();
        CC_ASSERT(
            purchasableDict.count(CCStoreConsts::JSON_PURCHASE_VI_AMOUNT));
        auto amount =
            purchasableDict.at(CCStoreConsts::JSON_PURCHASE_VI_AMOUNT).asInt();

        setPurchaseType(CCPurchaseWithVirtualItem::create(itemId, amount));
    } else {
        CC_ASSERT(false);
        cocos2d::log(
            "Couldn't determine what type of class is the given purchaseType.");
    }

    CCPurchaseType* purchaseType = getPurchaseType();
    if (purchaseType != nullptr) {
        purchaseType->setAssociatedItemId(getItemId());
    }
}

void CCPurchasableVirtualItem::putPurchaseTypeToValueMap(
    cocos2d::ValueMap& dict) {
    ValueMap purchasableObj;

    if (dynamic_cast<CCPurchaseWithMarket*>(mPurchaseType)) {
        purchasableObj[CCStoreConsts::JSON_PURCHASE_TYPE] =
            CCStoreConsts::JSON_PURCHASE_TYPE_MARKET;

        CCPurchaseWithMarket* purchaseWithMarket =
            (CCPurchaseWithMarket*)mPurchaseType;
        CCMarketItem* mi = purchaseWithMarket->getMarketItem();
        purchasableObj[CCStoreConsts::JSON_PURCHASE_MARKET_ITEM] =
            mi->toValueMap();
    } else if (dynamic_cast<CCPurchaseWithVirtualItem*>(mPurchaseType)) {
        CCPurchaseWithVirtualItem* purchaseWithVirtualItem =
            (CCPurchaseWithVirtualItem*)mPurchaseType;
        purchasableObj[CCStoreConsts::JSON_PURCHASE_TYPE] =
            CCStoreConsts::JSON_PURCHASE_TYPE_VI;
        purchasableObj[CCStoreConsts::JSON_PURCHASE_VI_ITEM_ID] =
            purchaseWithVirtualItem->getItemId();
        purchasableObj[CCStoreConsts::JSON_PURCHASE_VI_AMOUNT] =
            purchaseWithVirtualItem->getAmount();
    } else {
        CC_ASSERT(false);
    }

    dict[CCStoreConsts::JSON_PURCHASABLE_ITEM] = purchasableObj;
}
} // namespace soomla
<commit_msg>Fix optimize copy.<commit_after>/*
 Copyright (C) 2012-2014 Soomla Inc.

 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 "Soomla/domain/CCPurchasableVirtualItem.h"

#include <Soomla/CCJsonHelper.h>

#include "Soomla/PurchaseTypes/CCPurchaseWithMarket.h"
#include "Soomla/PurchaseTypes/CCPurchaseWithVirtualItem.h"

namespace soomla {

using namespace cocos2d;

bool CCPurchasableVirtualItem::init(const std::string& name,
                                    const std::string& description,
                                    const std::string& itemId,
                                    soomla::CCPurchaseType* purchaseType) {
    bool bRet = CCVirtualItem::init(itemId, name, description);
    if (bRet) {
        setPurchaseType(purchaseType);
        purchaseType->setAssociatedItemId(getItemId());
    }
    return bRet;
}

bool CCPurchasableVirtualItem::initWithValueMap(const cocos2d::ValueMap& map) {
    bool bRet = CCVirtualItem::initWithValueMap(map);
    if (bRet) {
        fillPurchaseTypeFromValueMap(map);
        return true;
    } else {
        return false;
    }
}

CCPurchasableVirtualItem::~CCPurchasableVirtualItem() {
    CC_SAFE_RELEASE(mPurchaseType);
}

ValueMap CCPurchasableVirtualItem::toValueMap() {
    auto map = CCVirtualItem::toValueMap();
    putPurchaseTypeToValueMap(map);
    return map;
}

bool CCPurchasableVirtualItem::canAfford(CCError** error) {
    return getPurchaseType()->canAfford(error);
}

void CCPurchasableVirtualItem::buy(const std::string& payload, CCError** error) {
    if (!canBuy()) {
        return;
    }

    getPurchaseType()->buy(payload, error);
}

void CCPurchasableVirtualItem::fillPurchaseTypeFromValueMap(
    const cocos2d::ValueMap& dict) {
    CC_ASSERT(dict.count(CCStoreConsts::JSON_PURCHASABLE_ITEM));
    auto& purchasableDict =
        dict.at(CCStoreConsts::JSON_PURCHASABLE_ITEM).asValueMap();
    CCASSERT(purchasableDict.count(CCStoreConsts::JSON_PURCHASE_TYPE),
             "invalid object type in dictionary");
    auto&& purchaseTypeStr =
        purchasableDict.at(CCStoreConsts::JSON_PURCHASE_TYPE).asString();

    if (purchaseTypeStr.compare(CCStoreConsts::JSON_PURCHASE_TYPE_MARKET) ==
        0) {
        CC_ASSERT(purchasableDict.count(CCStoreConsts::JSON_PURCHASE_MARKET_ITEM));
        auto& marketItemDict =
            purchasableDict.at(CCStoreConsts::JSON_PURCHASE_MARKET_ITEM).asValueMap();

        setPurchaseType(CCPurchaseWithMarket::createWithMarketItem(
            CCMarketItem::createWithValueMap(marketItemDict)));
    } else if (purchaseTypeStr.compare(CCStoreConsts::JSON_PURCHASE_TYPE_VI) ==
               0) {
        CC_ASSERT(
            purchasableDict.count(CCStoreConsts::JSON_PURCHASE_VI_ITEM_ID));
        auto&& itemId =
            purchasableDict.at(CCStoreConsts::JSON_PURCHASE_VI_ITEM_ID)
                .asString();
        CC_ASSERT(
            purchasableDict.count(CCStoreConsts::JSON_PURCHASE_VI_AMOUNT));
        auto amount =
            purchasableDict.at(CCStoreConsts::JSON_PURCHASE_VI_AMOUNT).asInt();

        setPurchaseType(CCPurchaseWithVirtualItem::create(itemId, amount));
    } else {
        CC_ASSERT(false);
        cocos2d::log(
            "Couldn't determine what type of class is the given purchaseType.");
    }

    CCPurchaseType* purchaseType = getPurchaseType();
    if (purchaseType != nullptr) {
        purchaseType->setAssociatedItemId(getItemId());
    }
}

void CCPurchasableVirtualItem::putPurchaseTypeToValueMap(
    cocos2d::ValueMap& dict) {
    ValueMap purchasableObj;

    if (dynamic_cast<CCPurchaseWithMarket*>(mPurchaseType)) {
        purchasableObj[CCStoreConsts::JSON_PURCHASE_TYPE] =
            CCStoreConsts::JSON_PURCHASE_TYPE_MARKET;

        CCPurchaseWithMarket* purchaseWithMarket =
            (CCPurchaseWithMarket*)mPurchaseType;
        CCMarketItem* mi = purchaseWithMarket->getMarketItem();
        purchasableObj[CCStoreConsts::JSON_PURCHASE_MARKET_ITEM] =
            mi->toValueMap();
    } else if (dynamic_cast<CCPurchaseWithVirtualItem*>(mPurchaseType)) {
        CCPurchaseWithVirtualItem* purchaseWithVirtualItem =
            (CCPurchaseWithVirtualItem*)mPurchaseType;
        purchasableObj[CCStoreConsts::JSON_PURCHASE_TYPE] =
            CCStoreConsts::JSON_PURCHASE_TYPE_VI;
        purchasableObj[CCStoreConsts::JSON_PURCHASE_VI_ITEM_ID] =
            purchaseWithVirtualItem->getItemId();
        purchasableObj[CCStoreConsts::JSON_PURCHASE_VI_AMOUNT] =
            purchaseWithVirtualItem->getAmount();
    } else {
        CC_ASSERT(false);
    }

    dict[CCStoreConsts::JSON_PURCHASABLE_ITEM] = purchasableObj;
}
} // namespace soomla
<|endoftext|>


<commit_before>#ifndef __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POSITIVE_ORDERED_HPP__
#define __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POSITIVE_ORDERED_HPP__

#include <sstream>
#include <stan/math/matrix/Eigen.hpp>
#include <stan/math/error_handling/raise_domain_error.hpp>

namespace stan {
  namespace math {

    /**
     * Return true if the specified vector contains
     * only non-negative values and is sorted into increasing order.
     * There may be duplicate values.  Otherwise, raise a domain
     * error according to the specified policy.
     *
     * @param function
     * @param y Vector to test.
     * @param name
     * @param result
     * @return true if the vector has positive, ordered
     * values.
     */
    template <typename T_y, typename T_result>
    bool check_positive_ordered(const char* function,
                                const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                                const char* name,
                                T_result* result) {
      using stan::math::policies::raise_domain_error;
      typedef typename Eigen::Matrix<T_y,Eigen::Dynamic,1>::size_type size_t;
      if (y.size() == 0) {
        return true;
      }
      if (y[0] < 0) {
        std::ostringstream stream;
        stream << name << " is not a valid positive_ordered vector."
               << " The element at 0 is %1%, but should be postive.";
        T_result tmp = raise_domain_error<T_result,T_y>(function,
                                                        stream.str().c_str(),
                                                        y[0]);
        if (result != 0)
          *result = tmp;
        return false;
      }
      for (size_t n = 1; n < y.size(); n++) {
        if (!(y[n] > y[n-1])) {
          std::ostringstream stream;
          stream << name << " is not a valid ordered vector."
                 << " The element at " << n
                 << " is %1%, but should be greater than the previous element, "
                 << y[n-1];
          T_result tmp = raise_domain_error<T_result,T_y>(function,
                                                          stream.str().c_str(),
                                                          y[n]);
          if (result != 0)
            *result = tmp;
          return false;
        }
      }
      return true;
    }
    template <typename T>
    bool check_positive_ordered(const char* function,
                                const Eigen::Matrix<T,Eigen::Dynamic,1>& y,
                                const char* name,
                                T* result = 0) {
      return check_positive_ordered<T,T>(function,y,name,result);
    }

  }
}
#endif
<commit_msg>policies_refactor: updating matrix/check_positive_ordered<commit_after>#ifndef __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POSITIVE_ORDERED_HPP__
#define __STAN__MATH__ERROR_HANDLING__MATRIX__CHECK_POSITIVE_ORDERED_HPP__

#include <sstream>
#include <stan/math/error_handling/dom_err.hpp>
#include <stan/math/matrix/Eigen.hpp>

namespace stan {
  namespace math {

    /**
     * Return true if the specified vector contains
     * only non-negative values and is sorted into increasing order.
     * There may be duplicate values.  Otherwise, raise a domain
     * error according to the specified policy.
     *
     * @param function
     * @param y Vector to test.
     * @param name
     * @param result
     * @return true if the vector has positive, ordered
     * values.
     */
    template <typename T_y, typename T_result>
    bool check_positive_ordered(const char* function,
                                const Eigen::Matrix<T_y,Eigen::Dynamic,1>& y,
                                const char* name,
                                T_result* result) {
      using stan::math::policies::raise_domain_error;
      typedef typename Eigen::Matrix<T_y,Eigen::Dynamic,1>::size_type size_t;
      if (y.size() == 0) {
        return true;
      }
      if (y[0] < 0) {
        std::ostringstream stream;
        stream << name << " is not a valid positive_ordered vector."
               << " The element at 0 is %1%, but should be postive.";
        return dom_err(function,y[0],name,
                       stream.str().c_str(),"",
                       result);
      }
      for (size_t n = 1; n < y.size(); n++) {
        if (!(y[n] > y[n-1])) {
          std::ostringstream stream;
          stream << name << " is not a valid ordered vector."
                 << " The element at " << n
                 << " is %1%, but should be greater than the previous element, "
                 << y[n-1];
          return dom_err(function,y[n],name,
                         stream.str().c_str(),"",
                         result);
        }
      }
      return true;
    }
    template <typename T>
    bool check_positive_ordered(const char* function,
                                const Eigen::Matrix<T,Eigen::Dynamic,1>& y,
                                const char* name,
                                T* result = 0) {
      return check_positive_ordered<T,T>(function,y,name,result);
    }

  }
}
#endif
<|endoftext|>


<commit_before>/*
    csPerfThread.hpp:

    Copyright (C) 2005 Istvan Varga

    This file is part of Csound.

    The Csound Library is free software; you can redistribute it
    and/or modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    Csound 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 Csound; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
    02111-1307 USA
*/

#ifndef CSOUND_CSPERFTHREAD_HPP
#define CSOUND_CSPERFTHREAD_HPP

#include <pthread.h>

class CsoundPerformanceThreadMessage;
class CsPerfThread_PerformScore;

#ifdef SWIG
%include <std_string.i>
#else
#include <string>
#endif

/**
 * CsoundPerformanceThread(Csound *)
 * CsoundPerformanceThread(CSOUND *)
 *
 * Performs a score in a separate thread until the end of score is reached,
 * the playback (which is paused by default) is stopped by calling
 * CsoundPerformanceThread::Stop(), or an error occurs.
 * The constructor takes a Csound instance pointer as argument; it assumes
 * that csoundCompile() was called successfully before creating the
 * performance thread. Once the playback is stopped for one of the above
 * mentioned reasons, the performance thread calls csoundCleanup() and
 * returns.

  An example program using the CsoundPerformanceThread class

#include <stdio.h>
#include "csound.hpp"
#include "csPerfThread.hpp"

int main(int argc, char *argv[])
{
 int result=0;
 Csound cs;
 result = cs.Compile(argc,argv);

 if(!result)
 {
   CsoundPerformanceThread perfThread(cs.GetCsound());
   perfThread.Play(); // Starts performance
   while(perfThread.GetStatus() == 0);
                       // nothing to do here...
                       // but you could process input events, graphics etc
   perfThread.Stop();  // Stops performance. In fact, performance should have
                       // already finished, so this is just an example of how
                       //to stop if you need
   perfThread.Join();  // always call Join() after Stop() as a rule of thumb.
 }
 else{
   printf("csoundCompile returned an error\n");
   return 1;
 }

 return 0;
}

 */

#ifdef SWIGPYTHON
struct PUBLIC pycallbackdata {
  PyObject *func;
  PyObject *data;
};
#endif

typedef struct {
    void *cbuf;
    void *sfile;
    void *thread;
    bool running;
    pthread_cond_t condvar;
    pthread_mutex_t mutex;
} recordData_t;

class PUBLIC CsoundPerformanceThread {
 private:
    CSOUND  *csound;
    volatile CsoundPerformanceThreadMessage *firstMessage;
    CsoundPerformanceThreadMessage *lastMessage;
    void    *queueLock;         // this is actually a mutex
    void    *pauseLock;
    void    *flushLock;
    void    *perfThread;
    int     paused;
    int     status;
    void    *cdata;
    recordData_t recordData;
    int  running;
    void (*processcallback)(void *cdata);
    int  Perform();
    void csPerfThread_constructor(CSOUND *);
    void QueueMessage(CsoundPerformanceThreadMessage *);
 public:
    int isRunning() { return running;}
#ifdef SWIGPYTHON
  PyThreadState *_tstate;
  pycallbackdata pydata;
#endif
  /**
  * Returns the process callback as a void pointer
  */
  void *GetProcessCallback() { return (void *)processcallback; }

  /**
   * Sets the process callback.
   */
   void SetProcessCallback(void (*Callback)(void *), void *cbdata){
    processcallback = Callback;
    cdata = cbdata;
   }
    /**
     * Returns the Csound instance pointer.
     */
    CSOUND *GetCsound()
    {
      return csound;
    }
    /**
     * Returns the current status, zero if still playing, positive if
     * the end of score was reached or performance was stopped, and
     * negative if an error occured.
     */
    int GetStatus()
    {
      return status;
    }
    /**
     * Continues performance if it was paused.
     */
    void Play();
    /**
     * Pauses performance (can be continued by calling Play()).
     */
    void Pause();
    /**
     * Pauses performance unless it is already paused, in which case
     * it is continued.
     */
    void TogglePause();
    /**
     * Stops performance (cannot be continued).
     */
    void Stop();
    /**
     * Starts recording the output from Csound. The sample rate and number
     * of channels are taken directly from the running Csound instance.
     */
    void Record(std::string filename, int numbufs = 4);
    /**
     * Stops recording and closes audio file.
     */
    void StopRecord();
    /**
     * Sends a score event of type 'opcod' (e.g. 'i' for a note event), with
     * 'pcnt' p-fields in array 'p' (p[0] is p1). If absp2mode is non-zero,
     * the start time of the event is measured from the beginning of
     * performance, instead of the default of relative to the current time.
     */
    void ScoreEvent(int absp2mode, char opcod, int pcnt, const MYFLT *p);
    /**
     * Sends a score event as a string, similarly to line events (-L).
     */
    void InputMessage(const char *s);
    /**
     * Sets the playback time pointer to the specified value (in seconds).
     */
    void SetScoreOffsetSeconds(double timeVal);
    /**
     * Waits until the performance is finished or fails, and returns a
     * positive value if the end of score was reached or Stop() was called,
     * and a negative value if an error occured. Also releases any resources
     * associated with the performance thread object.
     */
    int Join();
    /**
     * Waits until all pending messages (pause, send score event, etc.)
     * are actually received by the performance thread.
     */
    void FlushMessageQueue();
    // --------
    CsoundPerformanceThread(Csound *);
    CsoundPerformanceThread(CSOUND *);
    ~CsoundPerformanceThread();
    // --------
    friend class CsoundPerformanceThreadMessage;
    friend class CsPerfThread_PerformScore;
};

#endif  // CSOUND_CSPERFTHREAD_HPP
<commit_msg>fixed pthread.h include only if not using SWIG<commit_after>/*
    csPerfThread.hpp:

    Copyright (C) 2005 Istvan Varga

    This file is part of Csound.

    The Csound Library is free software; you can redistribute it
    and/or modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    Csound 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 Csound; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
    02111-1307 USA
*/

#ifndef CSOUND_CSPERFTHREAD_HPP
#define CSOUND_CSPERFTHREAD_HPP

class CsoundPerformanceThreadMessage;
class CsPerfThread_PerformScore;

#ifdef SWIG
%include <std_string.i>
#else
#include <string>
#include <pthread.h>
#endif

/**
 * CsoundPerformanceThread(Csound *)
 * CsoundPerformanceThread(CSOUND *)
 *
 * Performs a score in a separate thread until the end of score is reached,
 * the playback (which is paused by default) is stopped by calling
 * CsoundPerformanceThread::Stop(), or an error occurs.
 * The constructor takes a Csound instance pointer as argument; it assumes
 * that csoundCompile() was called successfully before creating the
 * performance thread. Once the playback is stopped for one of the above
 * mentioned reasons, the performance thread calls csoundCleanup() and
 * returns.

  An example program using the CsoundPerformanceThread class

#include <stdio.h>
#include "csound.hpp"
#include "csPerfThread.hpp"

int main(int argc, char *argv[])
{
 int result=0;
 Csound cs;
 result = cs.Compile(argc,argv);

 if(!result)
 {
   CsoundPerformanceThread perfThread(cs.GetCsound());
   perfThread.Play(); // Starts performance
   while(perfThread.GetStatus() == 0);
                       // nothing to do here...
                       // but you could process input events, graphics etc
   perfThread.Stop();  // Stops performance. In fact, performance should have
                       // already finished, so this is just an example of how
                       //to stop if you need
   perfThread.Join();  // always call Join() after Stop() as a rule of thumb.
 }
 else{
   printf("csoundCompile returned an error\n");
   return 1;
 }

 return 0;
}

 */

#ifdef SWIGPYTHON
struct PUBLIC pycallbackdata {
  PyObject *func;
  PyObject *data;
};
#endif

typedef struct {
    void *cbuf;
    void *sfile;
    void *thread;
    bool running;
    pthread_cond_t condvar;
    pthread_mutex_t mutex;
} recordData_t;

class PUBLIC CsoundPerformanceThread {
 private:
    CSOUND  *csound;
    volatile CsoundPerformanceThreadMessage *firstMessage;
    CsoundPerformanceThreadMessage *lastMessage;
    void    *queueLock;         // this is actually a mutex
    void    *pauseLock;
    void    *flushLock;
    void    *perfThread;
    int     paused;
    int     status;
    void    *cdata;
    recordData_t recordData;
    int  running;
    void (*processcallback)(void *cdata);
    int  Perform();
    void csPerfThread_constructor(CSOUND *);
    void QueueMessage(CsoundPerformanceThreadMessage *);
 public:
    int isRunning() { return running;}
#ifdef SWIGPYTHON
  PyThreadState *_tstate;
  pycallbackdata pydata;
#endif
  /**
  * Returns the process callback as a void pointer
  */
  void *GetProcessCallback() { return (void *)processcallback; }

  /**
   * Sets the process callback.
   */
   void SetProcessCallback(void (*Callback)(void *), void *cbdata){
    processcallback = Callback;
    cdata = cbdata;
   }
    /**
     * Returns the Csound instance pointer.
     */
    CSOUND *GetCsound()
    {
      return csound;
    }
    /**
     * Returns the current status, zero if still playing, positive if
     * the end of score was reached or performance was stopped, and
     * negative if an error occured.
     */
    int GetStatus()
    {
      return status;
    }
    /**
     * Continues performance if it was paused.
     */
    void Play();
    /**
     * Pauses performance (can be continued by calling Play()).
     */
    void Pause();
    /**
     * Pauses performance unless it is already paused, in which case
     * it is continued.
     */
    void TogglePause();
    /**
     * Stops performance (cannot be continued).
     */
    void Stop();
    /**
     * Starts recording the output from Csound. The sample rate and number
     * of channels are taken directly from the running Csound instance.
     */
    void Record(std::string filename, int numbufs = 4);
    /**
     * Stops recording and closes audio file.
     */
    void StopRecord();
    /**
     * Sends a score event of type 'opcod' (e.g. 'i' for a note event), with
     * 'pcnt' p-fields in array 'p' (p[0] is p1). If absp2mode is non-zero,
     * the start time of the event is measured from the beginning of
     * performance, instead of the default of relative to the current time.
     */
    void ScoreEvent(int absp2mode, char opcod, int pcnt, const MYFLT *p);
    /**
     * Sends a score event as a string, similarly to line events (-L).
     */
    void InputMessage(const char *s);
    /**
     * Sets the playback time pointer to the specified value (in seconds).
     */
    void SetScoreOffsetSeconds(double timeVal);
    /**
     * Waits until the performance is finished or fails, and returns a
     * positive value if the end of score was reached or Stop() was called,
     * and a negative value if an error occured. Also releases any resources
     * associated with the performance thread object.
     */
    int Join();
    /**
     * Waits until all pending messages (pause, send score event, etc.)
     * are actually received by the performance thread.
     */
    void FlushMessageQueue();
    // --------
    CsoundPerformanceThread(Csound *);
    CsoundPerformanceThread(CSOUND *);
    ~CsoundPerformanceThread();
    // --------
    friend class CsoundPerformanceThreadMessage;
    friend class CsPerfThread_PerformScore;
};

#endif  // CSOUND_CSPERFTHREAD_HPP
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016+     AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version.
 * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
 */

#include "blackwing_lair.h"
#include "GameObject.h"
#include "InstanceScript.h"
#include "Map.h"
#include "MotionMaster.h"
#include "Player.h"
#include "ScriptedCreature.h"
#include "ScriptMgr.h"
#include "SpellAuraEffects.h"
#include "SpellScript.h"
#include "TemporarySummon.h"

DoorData const doorData[] =
{
    { GO_PORTCULLIS_RAZORGORE,    DATA_RAZORGORE_THE_UNTAMED,  DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 175946 || GUID 7230
    { GO_PORTCULLIS_VAELASTRASZ,  DATA_VAELASTRAZ_THE_CORRUPT, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 175185 || GUID 7229
    { GO_PORTCULLIS_BROODLORD,    DATA_BROODLORD_LASHLAYER,    DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179365 || GUID 75159
    { GO_PORTCULLIS_THREEDRAGONS, DATA_FIREMAW,                DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179115 || GUID 75165
    { GO_PORTCULLIS_THREEDRAGONS, DATA_EBONROC,                DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179115 || GUID 75165
    { GO_PORTCULLIS_THREEDRAGONS, DATA_FLAMEGOR,               DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179115 || GUID 75165
    { GO_PORTCULLIS_CHROMAGGUS,   DATA_CHROMAGGUS,             DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179116 || GUID 75161
    { GO_PORTCULLIS_NEFARIAN,     DATA_NEFARIAN,               DOOR_TYPE_ROOM, BOUNDARY_NONE},    // ID 179117 || GUID 75164
    { 0,                         0,                            DOOR_TYPE_ROOM, BOUNDARY_NONE}     // END
};

Position const SummonPosition[8] =
{
    {-7661.207520f, -1043.268188f, 407.199554f, 6.280452f},
    {-7644.145020f, -1065.628052f, 407.204956f, 0.501492f},
    {-7624.260742f, -1095.196899f, 407.205017f, 0.544694f},
    {-7608.501953f, -1116.077271f, 407.199921f, 0.816443f},
    {-7531.841797f, -1063.765381f, 407.199615f, 2.874187f},
    {-7547.319336f, -1040.971924f, 407.205078f, 3.789175f},
    {-7568.547852f, -1013.112488f, 407.204926f, 3.773467f},
    {-7584.175781f, -989.6691289f, 407.199585f, 4.527447f},
};

uint32 const Entry[5] = {12422, 12458, 12416, 12420, 12459};

class instance_blackwing_lair : public InstanceMapScript
{
public:
    instance_blackwing_lair() : InstanceMapScript(BWLScriptName, 469) { }

    struct instance_blackwing_lair_InstanceMapScript : public InstanceScript
    {
        instance_blackwing_lair_InstanceMapScript(Map* map) : InstanceScript(map)
        {
            //SetHeaders(DataHeader);
            SetBossNumber(EncounterCount);
            LoadDoorData(doorData);
            //LoadObjectData(creatureData, gameObjectData);
        }

        void Initialize() override
        {
            // Razorgore
            EggCount = 0;
            EggEvent = 0;
        }

        void OnCreatureCreate(Creature* creature) override
        {
            InstanceScript::OnCreatureCreate(creature);

            switch (creature->GetEntry())
            {
                case NPC_BLACKWING_DRAGON:
                case NPC_BLACKWING_TASKMASTER:
                case NPC_BLACKWING_LEGIONAIRE:
                case NPC_BLACKWING_WARLOCK:
                    if (Creature* razor = instance->GetCreature(GetGuidData(DATA_RAZORGORE_THE_UNTAMED)))
                        if (CreatureAI* razorAI = razor->AI())
                            razorAI->JustSummoned(creature);
                    break;
                default:
                    break;
            }
        }

        void OnGameObjectCreate(GameObject* go) override
        {
            InstanceScript::OnGameObjectCreate(go);

            switch(go->GetEntry())
            {
                case GO_BLACK_DRAGON_EGG:
                    if (GetBossState(DATA_FIREMAW) == DONE)
                        go->SetPhaseMask(2, true);
                    else
                        EggList.push_back(go->GetGUID());
                    break;

                case GO_PORTCULLIS_RAZORGORE:
                case GO_PORTCULLIS_VAELASTRASZ:
                case GO_PORTCULLIS_BROODLORD:
                case GO_PORTCULLIS_THREEDRAGONS:
                case GO_PORTCULLIS_CHROMAGGUS:
                case GO_PORTCULLIS_NEFARIAN:
                    AddDoor(go, true);
                    break;
                default:
                    break;
            }
        }

        void OnGameObjectRemove(GameObject* go) override
        {
            InstanceScript::OnGameObjectRemove(go);

            if (go->GetEntry() == GO_BLACK_DRAGON_EGG)
                EggList.remove(go->GetGUID());

            switch (go->GetEntry())
            {
            case GO_PORTCULLIS_RAZORGORE:
            case GO_PORTCULLIS_VAELASTRASZ:
            case GO_PORTCULLIS_BROODLORD:
            case GO_PORTCULLIS_THREEDRAGONS:
            case GO_PORTCULLIS_CHROMAGGUS:
            case GO_PORTCULLIS_NEFARIAN:
                AddDoor(go, false);
                break;
            default:
                break;
            }
        }

        bool CheckRequiredBosses(uint32 bossId, Player const* /* player */) const override
        {
            switch (bossId)
            {
                case DATA_BROODLORD_LASHLAYER:
                    if (GetBossState(DATA_VAELASTRAZ_THE_CORRUPT) != DONE)
                        return false;
                    break;
                case DATA_FIREMAW:
                case DATA_EBONROC:
                case DATA_FLAMEGOR:
                    if (GetBossState(DATA_BROODLORD_LASHLAYER) != DONE)
                        return false;
                    break;
                case DATA_CHROMAGGUS:
                    if (GetBossState(DATA_FIREMAW) != DONE
                        || GetBossState(DATA_EBONROC) != DONE
                        || GetBossState(DATA_FLAMEGOR) != DONE)
                        return false;
                    break;
                default:
                    break;
            }

            return true;
        }

        bool SetBossState(uint32 type, EncounterState state) override
        {
            if (!InstanceScript::SetBossState(type, state))
                return false;

            switch (type)
            {
                case DATA_RAZORGORE_THE_UNTAMED:
                    if (state == DONE)
                    {
                        for (ObjectGuid const& guid : EggList)
                            if (GameObject* egg = instance->GetGameObject(guid))
                                egg->SetPhaseMask(2, true);
                    }
                    SetData(DATA_EGG_EVENT, NOT_STARTED);
                    break;
                case DATA_NEFARIAN:
                    switch (state)
                    {
                        case NOT_STARTED:
                            if (Creature* nefarian = instance->GetCreature(GetGuidData(DATA_NEFARIAN)))
                                nefarian->DespawnOrUnsummon();
                            break;
                        case FAIL:
                            _events.ScheduleEvent(EVENT_RESPAWN_NEFARIUS, 15 * 60 * IN_MILLISECONDS); //15min
                            SetBossState(DATA_NEFARIAN, NOT_STARTED);
                            break;
                        default:
                            break;
                    }
                    break;
            }
            return true;
        }

        void SetData(uint32 type, uint32 data) override
        {
            if (type == DATA_EGG_EVENT)
            {
                switch (data)
                {
                    case IN_PROGRESS:
                        _events.ScheduleEvent(EVENT_RAZOR_SPAWN, 45000);
                        EggEvent = data;
                        EggCount = 0;
                        break;
                    case NOT_STARTED:
                        _events.CancelEvent(EVENT_RAZOR_SPAWN);
                        EggEvent = data;
                        EggCount = 0;
                        break;
                    case SPECIAL:
                        if (++EggCount == 15)
                        {
                            if (Creature* razor = instance->GetCreature(GetGuidData(DATA_RAZORGORE_THE_UNTAMED)))
                            {
                                SetData(DATA_EGG_EVENT, DONE);
                                razor->RemoveAurasDueToSpell(42013); // MindControl
                                DoRemoveAurasDueToSpellOnPlayers(42013);
                            }
                            _events.ScheduleEvent(EVENT_RAZOR_PHASE_TWO, 1000);
                            _events.CancelEvent(EVENT_RAZOR_SPAWN);
                        }
                        if (EggEvent == NOT_STARTED)
                            SetData(DATA_EGG_EVENT, IN_PROGRESS);
                        break;
                }
            }
        }

        void OnUnitDeath(Unit* unit) override
        {
            //! HACK, needed because of buggy CreatureAI after charm
            if (unit->GetEntry() == NPC_RAZORGORE && GetBossState(DATA_RAZORGORE_THE_UNTAMED) != DONE)
                SetBossState(DATA_RAZORGORE_THE_UNTAMED, DONE);
        }

        void Update(uint32 diff) override
        {
            if (_events.Empty())
                return;

            _events.Update(diff);

            while (uint32 eventId = _events.ExecuteEvent())
            {
                switch (eventId)
                {
                    case EVENT_RAZOR_SPAWN:
                        for (uint8 i = urand(2, 5); i > 0; --i)
                            if (Creature* summon = instance->SummonCreature(Entry[urand(0, 4)], SummonPosition[urand(0, 7)]))
                                summon->AI()->DoZoneInCombat();
                        _events.ScheduleEvent(EVENT_RAZOR_SPAWN, 12000, 17000);
                        break;
                    case EVENT_RAZOR_PHASE_TWO:
                        _events.CancelEvent(EVENT_RAZOR_SPAWN);
                        if (Creature* razor = instance->GetCreature(GetGuidData(DATA_RAZORGORE_THE_UNTAMED)))
                            razor->AI()->DoAction(ACTION_PHASE_TWO);
                        break;
                    case EVENT_RESPAWN_NEFARIUS:
                        if (Creature* nefarius = instance->GetCreature(GetGuidData(DATA_LORD_VICTOR_NEFARIUS)))
                        {
                            nefarius->SetPhaseMask(1, true);
                            nefarius->setActive(true);
                            nefarius->Respawn();
                            nefarius->GetMotionMaster()->MoveTargetedHome();
                        }
                        break;
                }
            }
        }

    protected:
        // Misc
        EventMap _events;

        // Razorgore
        uint8 EggCount;
        uint32 EggEvent;
        GuidList EggList;
    };

    InstanceScript* GetInstanceScript(InstanceMap* map) const
    {
        return new instance_blackwing_lair_InstanceMapScript(map);
    }
};

enum ShadowFlame
{
    SPELL_ONYXIA_SCALE_CLOAK = 22683,
    SPELL_SHADOW_FLAME_DOT = 22682
};

// 22539 - Shadowflame (used in Blackwing Lair)
class spell_bwl_shadowflame : public SpellScriptLoader
{
public:
    spell_bwl_shadowflame() : SpellScriptLoader("spell_bwl_shadowflame") { }

    class spell_bwl_shadowflame_SpellScript : public SpellScript
    {
        PrepareSpellScript(spell_bwl_shadowflame_SpellScript);

        bool Validate(SpellInfo const* /*spellInfo*/) override
        {
            return ValidateSpellInfo({ SPELL_ONYXIA_SCALE_CLOAK, SPELL_SHADOW_FLAME_DOT });
        }

        void HandleEffectScriptEffect(SpellEffIndex /*effIndex*/)
        {
            // If the victim of the spell does not have "Onyxia Scale Cloak" - add the Shadow Flame DoT (22682)
            if (Unit* victim = GetHitUnit())
                if (!victim->HasAura(SPELL_ONYXIA_SCALE_CLOAK))
                    victim->AddAura(SPELL_SHADOW_FLAME_DOT, victim);
        }

        void Register() override
        {
            OnEffectHitTarget += SpellEffectFn(spell_bwl_shadowflame_SpellScript::HandleEffectScriptEffect, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE);
        }
    };

    SpellScript* GetSpellScript() const
    {
        return new spell_bwl_shadowflame_SpellScript;
    }
};

void AddSC_instance_blackwing_lair()
{
    new instance_blackwing_lair();
    new spell_bwl_shadowflame();
}
<commit_msg>fix(Scripts/BWL): drakes in Blackwing Lair can't attack (#7303)<commit_after>/*
 * Copyright (C) 2016+     AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version.
 * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/>
 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
 */

#include "blackwing_lair.h"
#include "GameObject.h"
#include "InstanceScript.h"
#include "Map.h"
#include "MotionMaster.h"
#include "Player.h"
#include "ScriptedCreature.h"
#include "ScriptMgr.h"
#include "SpellAuraEffects.h"
#include "SpellScript.h"
#include "TemporarySummon.h"

DoorData const doorData[] =
{
    { GO_PORTCULLIS_RAZORGORE,    DATA_RAZORGORE_THE_UNTAMED,  DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 175946 || GUID 7230
    { GO_PORTCULLIS_VAELASTRASZ,  DATA_VAELASTRAZ_THE_CORRUPT, DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 175185 || GUID 7229
    { GO_PORTCULLIS_BROODLORD,    DATA_BROODLORD_LASHLAYER,    DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179365 || GUID 75159
    { GO_PORTCULLIS_THREEDRAGONS, DATA_FIREMAW,                DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179115 || GUID 75165
    { GO_PORTCULLIS_THREEDRAGONS, DATA_EBONROC,                DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179115 || GUID 75165
    { GO_PORTCULLIS_THREEDRAGONS, DATA_FLAMEGOR,               DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179115 || GUID 75165
    { GO_PORTCULLIS_CHROMAGGUS,   DATA_CHROMAGGUS,             DOOR_TYPE_PASSAGE, BOUNDARY_NONE}, // ID 179116 || GUID 75161
    { GO_PORTCULLIS_NEFARIAN,     DATA_NEFARIAN,               DOOR_TYPE_ROOM, BOUNDARY_NONE},    // ID 179117 || GUID 75164
    { 0,                         0,                            DOOR_TYPE_ROOM, BOUNDARY_NONE}     // END
};

Position const SummonPosition[8] =
{
    {-7661.207520f, -1043.268188f, 407.199554f, 6.280452f},
    {-7644.145020f, -1065.628052f, 407.204956f, 0.501492f},
    {-7624.260742f, -1095.196899f, 407.205017f, 0.544694f},
    {-7608.501953f, -1116.077271f, 407.199921f, 0.816443f},
    {-7531.841797f, -1063.765381f, 407.199615f, 2.874187f},
    {-7547.319336f, -1040.971924f, 407.205078f, 3.789175f},
    {-7568.547852f, -1013.112488f, 407.204926f, 3.773467f},
    {-7584.175781f, -989.6691289f, 407.199585f, 4.527447f},
};

uint32 const Entry[5] = {12422, 12458, 12416, 12420, 12459};

class instance_blackwing_lair : public InstanceMapScript
{
public:
    instance_blackwing_lair() : InstanceMapScript(BWLScriptName, 469) { }

    struct instance_blackwing_lair_InstanceMapScript : public InstanceScript
    {
        instance_blackwing_lair_InstanceMapScript(Map* map) : InstanceScript(map)
        {
            //SetHeaders(DataHeader);
            SetBossNumber(EncounterCount);
            LoadDoorData(doorData);
            //LoadObjectData(creatureData, gameObjectData);
        }

        void Initialize() override
        {
            // Razorgore
            EggCount = 0;
            EggEvent = 0;
        }

        void OnCreatureCreate(Creature* creature) override
        {
            InstanceScript::OnCreatureCreate(creature);

            switch (creature->GetEntry())
            {
                case NPC_BLACKWING_DRAGON:
                case NPC_BLACKWING_TASKMASTER:
                case NPC_BLACKWING_LEGIONAIRE:
                case NPC_BLACKWING_WARLOCK:
                    if (Creature* razor = instance->GetCreature(GetGuidData(DATA_RAZORGORE_THE_UNTAMED)))
                        if (CreatureAI* razorAI = razor->AI())
                            razorAI->JustSummoned(creature);
                    break;
                default:
                    break;
            }
        }

        void OnGameObjectCreate(GameObject* go) override
        {
            InstanceScript::OnGameObjectCreate(go);

            switch(go->GetEntry())
            {
                case GO_BLACK_DRAGON_EGG:
                    if (GetBossState(DATA_FIREMAW) == DONE)
                        go->SetPhaseMask(2, true);
                    else
                        EggList.push_back(go->GetGUID());
                    break;

                case GO_PORTCULLIS_RAZORGORE:
                case GO_PORTCULLIS_VAELASTRASZ:
                case GO_PORTCULLIS_BROODLORD:
                case GO_PORTCULLIS_THREEDRAGONS:
                case GO_PORTCULLIS_CHROMAGGUS:
                case GO_PORTCULLIS_NEFARIAN:
                    AddDoor(go, true);
                    break;
                default:
                    break;
            }
        }

        void OnGameObjectRemove(GameObject* go) override
        {
            InstanceScript::OnGameObjectRemove(go);

            if (go->GetEntry() == GO_BLACK_DRAGON_EGG)
                EggList.remove(go->GetGUID());

            switch (go->GetEntry())
            {
            case GO_PORTCULLIS_RAZORGORE:
            case GO_PORTCULLIS_VAELASTRASZ:
            case GO_PORTCULLIS_BROODLORD:
            case GO_PORTCULLIS_THREEDRAGONS:
            case GO_PORTCULLIS_CHROMAGGUS:
            case GO_PORTCULLIS_NEFARIAN:
                AddDoor(go, false);
                break;
            default:
                break;
            }
        }

        bool CheckRequiredBosses(uint32 bossId, Player const* /* player */) const override
        {
            switch (bossId)
            {
                case DATA_BROODLORD_LASHLAYER:
                    if (GetBossState(DATA_VAELASTRAZ_THE_CORRUPT) != DONE)
                        return false;
                    break;
                case DATA_CHROMAGGUS:
                    if (GetBossState(DATA_FIREMAW) != DONE
                        || GetBossState(DATA_EBONROC) != DONE
                        || GetBossState(DATA_FLAMEGOR) != DONE)
                        return false;
                    break;
                default:
                    break;
            }

            return true;
        }

        bool SetBossState(uint32 type, EncounterState state) override
        {
            if (!InstanceScript::SetBossState(type, state))
                return false;

            switch (type)
            {
                case DATA_RAZORGORE_THE_UNTAMED:
                    if (state == DONE)
                    {
                        for (ObjectGuid const& guid : EggList)
                            if (GameObject* egg = instance->GetGameObject(guid))
                                egg->SetPhaseMask(2, true);
                    }
                    SetData(DATA_EGG_EVENT, NOT_STARTED);
                    break;
                case DATA_NEFARIAN:
                    switch (state)
                    {
                        case NOT_STARTED:
                            if (Creature* nefarian = instance->GetCreature(GetGuidData(DATA_NEFARIAN)))
                                nefarian->DespawnOrUnsummon();
                            break;
                        case FAIL:
                            _events.ScheduleEvent(EVENT_RESPAWN_NEFARIUS, 15 * 60 * IN_MILLISECONDS); //15min
                            SetBossState(DATA_NEFARIAN, NOT_STARTED);
                            break;
                        default:
                            break;
                    }
                    break;
            }
            return true;
        }

        void SetData(uint32 type, uint32 data) override
        {
            if (type == DATA_EGG_EVENT)
            {
                switch (data)
                {
                    case IN_PROGRESS:
                        _events.ScheduleEvent(EVENT_RAZOR_SPAWN, 45000);
                        EggEvent = data;
                        EggCount = 0;
                        break;
                    case NOT_STARTED:
                        _events.CancelEvent(EVENT_RAZOR_SPAWN);
                        EggEvent = data;
                        EggCount = 0;
                        break;
                    case SPECIAL:
                        if (++EggCount == 15)
                        {
                            if (Creature* razor = instance->GetCreature(GetGuidData(DATA_RAZORGORE_THE_UNTAMED)))
                            {
                                SetData(DATA_EGG_EVENT, DONE);
                                razor->RemoveAurasDueToSpell(42013); // MindControl
                                DoRemoveAurasDueToSpellOnPlayers(42013);
                            }
                            _events.ScheduleEvent(EVENT_RAZOR_PHASE_TWO, 1000);
                            _events.CancelEvent(EVENT_RAZOR_SPAWN);
                        }
                        if (EggEvent == NOT_STARTED)
                            SetData(DATA_EGG_EVENT, IN_PROGRESS);
                        break;
                }
            }
        }

        void OnUnitDeath(Unit* unit) override
        {
            //! HACK, needed because of buggy CreatureAI after charm
            if (unit->GetEntry() == NPC_RAZORGORE && GetBossState(DATA_RAZORGORE_THE_UNTAMED) != DONE)
                SetBossState(DATA_RAZORGORE_THE_UNTAMED, DONE);
        }

        void Update(uint32 diff) override
        {
            if (_events.Empty())
                return;

            _events.Update(diff);

            while (uint32 eventId = _events.ExecuteEvent())
            {
                switch (eventId)
                {
                    case EVENT_RAZOR_SPAWN:
                        for (uint8 i = urand(2, 5); i > 0; --i)
                            if (Creature* summon = instance->SummonCreature(Entry[urand(0, 4)], SummonPosition[urand(0, 7)]))
                                summon->AI()->DoZoneInCombat();
                        _events.ScheduleEvent(EVENT_RAZOR_SPAWN, 12000, 17000);
                        break;
                    case EVENT_RAZOR_PHASE_TWO:
                        _events.CancelEvent(EVENT_RAZOR_SPAWN);
                        if (Creature* razor = instance->GetCreature(GetGuidData(DATA_RAZORGORE_THE_UNTAMED)))
                            razor->AI()->DoAction(ACTION_PHASE_TWO);
                        break;
                    case EVENT_RESPAWN_NEFARIUS:
                        if (Creature* nefarius = instance->GetCreature(GetGuidData(DATA_LORD_VICTOR_NEFARIUS)))
                        {
                            nefarius->SetPhaseMask(1, true);
                            nefarius->setActive(true);
                            nefarius->Respawn();
                            nefarius->GetMotionMaster()->MoveTargetedHome();
                        }
                        break;
                }
            }
        }

    protected:
        // Misc
        EventMap _events;

        // Razorgore
        uint8 EggCount;
        uint32 EggEvent;
        GuidList EggList;
    };

    InstanceScript* GetInstanceScript(InstanceMap* map) const
    {
        return new instance_blackwing_lair_InstanceMapScript(map);
    }
};

enum ShadowFlame
{
    SPELL_ONYXIA_SCALE_CLOAK = 22683,
    SPELL_SHADOW_FLAME_DOT = 22682
};

// 22539 - Shadowflame (used in Blackwing Lair)
class spell_bwl_shadowflame : public SpellScriptLoader
{
public:
    spell_bwl_shadowflame() : SpellScriptLoader("spell_bwl_shadowflame") { }

    class spell_bwl_shadowflame_SpellScript : public SpellScript
    {
        PrepareSpellScript(spell_bwl_shadowflame_SpellScript);

        bool Validate(SpellInfo const* /*spellInfo*/) override
        {
            return ValidateSpellInfo({ SPELL_ONYXIA_SCALE_CLOAK, SPELL_SHADOW_FLAME_DOT });
        }

        void HandleEffectScriptEffect(SpellEffIndex /*effIndex*/)
        {
            // If the victim of the spell does not have "Onyxia Scale Cloak" - add the Shadow Flame DoT (22682)
            if (Unit* victim = GetHitUnit())
                if (!victim->HasAura(SPELL_ONYXIA_SCALE_CLOAK))
                    victim->AddAura(SPELL_SHADOW_FLAME_DOT, victim);
        }

        void Register() override
        {
            OnEffectHitTarget += SpellEffectFn(spell_bwl_shadowflame_SpellScript::HandleEffectScriptEffect, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE);
        }
    };

    SpellScript* GetSpellScript() const
    {
        return new spell_bwl_shadowflame_SpellScript;
    }
};

void AddSC_instance_blackwing_lair()
{
    new instance_blackwing_lair();
    new spell_bwl_shadowflame();
}
<|endoftext|>


<commit_before>/*
 * Unit tests for the TTAverage Object for Jamoma DSP
 * Copyright © 2011, Nils Peters, Tim Place
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTAverage.h"

TTErr TTAverage::test(TTValue& returnedTestInfo)
{
	int					errorCount = 0;
	int					testAssertionCount = 0;
	int					badSampleCount = 0;
	TTAudioSignalPtr	input = NULL;
	TTAudioSignalPtr	output = NULL;

	// create 1 channel audio signal objects
	TTObjectInstantiate(kTTSym_audiosignal, &input, 1);
	TTObjectInstantiate(kTTSym_audiosignal, &output, 1);
	input->allocWithVectorSize(64);
	output->allocWithVectorSize(64);

	// create an impulse
	input->clear();						// set all samples to zero
	input->mSampleVectors[0][0] = -2.0;	// set the first sample to -2
	input->mSampleVectors[0][1] = -2.0;	// set the second sample to -2

	// setup the delay
	this->setAttributeValue(TT("interval"), 20);
	//this->setAttributeValue(TT("delayInSamples"), 1);
	this->setAttributeValue(TT("mode"), TT("bipolar")),
	this->process(input, output);

	TTFloat64 expectedImpulseResponse[64] = {
		-0.10,
		-0.05,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00
	};

	for (int i=0; i<64; i++) {
		TTBoolean result = TTTestFloatEquivalence(output->mSampleVectors[0][i], expectedImpulseResponse[i]);
		badSampleCount += !result;
		if (result)
			TTTestLog("BAD SAMPLE @ i=%i  ( value=%.10f   expected=%.10f )", i, output->mSampleVectors[0][i], expectedImpulseResponse[i]);
	}

	TTTestAssertion("Produces correct impulse response for a delay of 1 sample",
					badSampleCount == 0,
					testAssertionCount,
					errorCount);
	if (badSampleCount)
		TTTestLog("badSampleCount is %i", badSampleCount);

	TTObjectRelease(&input);
	TTObjectRelease(&output);

	// Wrap up the test results to pass back to whoever called this test
	return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}

<commit_msg>TTAverage: unit test fix (but unit test still fails -- i think there is a redmine ticket for this)<commit_after>/*
 * Unit tests for the TTAverage Object for Jamoma DSP
 * Copyright © 2011, Nils Peters, Tim Place
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTAverage.h"

TTErr TTAverage::test(TTValue& returnedTestInfo)
{
	int					errorCount = 0;
	int					testAssertionCount = 0;
	int					badSampleCount = 0;
	TTAudioSignalPtr	input = NULL;
	TTAudioSignalPtr	output = NULL;

	// create 1 channel audio signal objects
	TTObjectInstantiate(kTTSym_audiosignal, &input, 1);
	TTObjectInstantiate(kTTSym_audiosignal, &output, 1);
	input->allocWithVectorSize(64);
	output->allocWithVectorSize(64);

	// create an impulse
	input->clear();						// set all samples to zero
	input->mSampleVectors[0][0] = -2.0;	// set the first sample to -2
	input->mSampleVectors[0][1] = -2.0;	// set the second sample to -2

	// setup the delay
	this->setAttributeValue(TT("interval"), 20);
	//this->setAttributeValue(TT("delayInSamples"), 1);
	this->setAttributeValue(TT("mode"), TT("bipolar")),
	this->process(input, output);

	TTFloat64 expectedImpulseResponse[64] = {
		-0.10,
		-0.05,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00,
		0.0000000000000000e+00
	};

	for (int i=0; i<64; i++) {
		TTBoolean result = TTTestFloatEquivalence(output->mSampleVectors[0][i], expectedImpulseResponse[i]);
		badSampleCount += !result;
		if (!result)
			TTTestLog("BAD SAMPLE @ i=%i  ( value=%.10f   expected=%.10f )", i, output->mSampleVectors[0][i], expectedImpulseResponse[i]);
	}

	TTTestAssertion("Produces correct impulse response for a delay of 1 sample",
					badSampleCount == 0,
					testAssertionCount,
					errorCount);
	if (badSampleCount)
		TTTestLog("badSampleCount is %i", badSampleCount);

	TTObjectRelease(&input);
	TTObjectRelease(&output);

	// Wrap up the test results to pass back to whoever called this test
	return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}

<|endoftext|>