<commit_before>/*
 * File: ExponentiallyDecaying.hpp
 * Part of commonpp.
 *
 * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2015 Thomas Sanchez.  All rights reserved.
 *
 */
#pragma once

#include <algorithm>
#include <random>
#include <chrono>
#include <mutex>
#include <cmath>

#include <map>

#include <mutex>
#include "types.hpp"

namespace commonpp
{
namespace metric
{
namespace reservoir
{

// Implementation from:
// https://github.com/dropwizard/metrics/blob/master/metrics-core/src/main/java/io/dropwizard/metrics/ExponentiallyDecayingReservoir.java

template <size_t size_ = 1028,
          size_t alpha_time_1000 = 15,
          typename clock_ = std::chrono::system_clock,
          typename Mutex = std::mutex>
class ExponentiallyDecaying
{

    template <typename K, typename V>
    using MapType = std::map<K, V>;

public:
    static const WeightedReservoirTag tag;

    static constexpr const double ALPHA = double(alpha_time_1000) * 0.001;
    using ElapsedTimeUnit = std::chrono::seconds;

    static constexpr const size_t MAX_SIZE = size_;
    using Clock = clock_;
    using Timepoint = typename Clock::time_point;
    using Weight = double;

    struct Sample
    {
        Weight weight;
        double value;
    };

    const std::chrono::hours RESCALE_INTERVAL{1};

public:
    ExponentiallyDecaying();
    ~ExponentiallyDecaying() = default;

    void pushValue(double value, Timepoint timepoint = Clock::now());

    template <typename Summary>
    auto visit() const -> decltype(Summary::createAccumulator(0, tag))
    {
        std::lock_guard<Mutex> lock(mutex_);
        auto acc = Summary::createAccumulator(size_unsafe(), tag);
        for (const auto& value : values_)
        {
            const auto& sample = value.second;
            acc(sample.weight, sample.value);
        }

        return acc;
    }

    size_t size() const;
    size_t size_unsafe() const;

private:
    void rescale();
    static Weight weight(ElapsedTimeUnit duration);

private:
    mutable Mutex mutex_;
    std::random_device random_;
    std::mt19937 gen_;
    std::uniform_real_distribution<> dis_;

    MapType<Weight, Sample> values_;
    Timepoint start_time_;
    Timepoint next_rescale_;
};

template <size_t s, size_t a, typename c, typename m>
ExponentiallyDecaying<s, a, c, m>::ExponentiallyDecaying()
: gen_(random_())
, dis_(0, 1)
{
    start_time_ = Clock::now();
    next_rescale_ = start_time_ + RESCALE_INTERVAL;
}

template <size_t s, size_t a, typename c, typename m>
typename ExponentiallyDecaying<s, a, c, m>::Weight
ExponentiallyDecaying<s, a, c, m>::weight(ElapsedTimeUnit duration)
{
    return ::exp(ALPHA * duration.count());
}

template <size_t s, size_t a, typename c, typename m>
size_t ExponentiallyDecaying<s, a, c, m>::size() const
{
    std::lock_guard<m> lock(mutex_);
    return values_.size();
}

template <size_t s, size_t a, typename c, typename m>
size_t ExponentiallyDecaying<s, a, c, m>::size_unsafe() const
{
    return values_.size();
}

template <size_t s, size_t a, typename c, typename m>
void ExponentiallyDecaying<s, a, c, m>::pushValue(double value, Timepoint timestamp)
{
    std::lock_guard<m> lock(mutex_);
    rescale();

    auto elapsed_time =
        std::chrono::duration_cast<ElapsedTimeUnit>(timestamp - start_time_);
    Sample sample{weight(elapsed_time), value};
    double priority = sample.weight / dis_(gen_);

    auto new_size = values_.size() + 1;
    if (new_size <= MAX_SIZE)
    {
        values_[priority] = sample;
    }
    else
    {
        auto it_first = values_.begin();
        if (it_first->first < priority && values_.emplace(priority, sample).second)
        {
            values_.erase(it_first);
        }
    }
}

template <size_t s, size_t a, typename c, typename m>
void ExponentiallyDecaying<s, a, c, m>::rescale()
{
    Timepoint now = Clock::now();

    if (now < next_rescale_)
    {
        return;
    }

    next_rescale_ = now + RESCALE_INTERVAL;
    auto old_start_time = start_time_;
    start_time_ = now;

    decltype(values_) values;
    values.swap(values_);

    const auto time =
        std::chrono::duration_cast<ElapsedTimeUnit>(start_time_ - old_start_time)
            .count();

    auto scale_factor = ::exp(-ALPHA * time);
    for (const auto& v : values)
    {
        auto key = v.first;
        auto const& sample = v.second;
        values_[key * scale_factor] = {sample.weight * scale_factor, sample.value};
    }
}

} // namespace reservoir
} // namespace metric
} // namespace commonpp
<commit_msg>Instantiate static constant<commit_after>/*
 * File: ExponentiallyDecaying.hpp
 * Part of commonpp.
 *
 * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2015 Thomas Sanchez.  All rights reserved.
 *
 */
#pragma once

#include <algorithm>
#include <random>
#include <chrono>
#include <mutex>
#include <cmath>

#include <map>

#include <mutex>
#include "types.hpp"

namespace commonpp
{
namespace metric
{
namespace reservoir
{

// Implementation from:
// https://github.com/dropwizard/metrics/blob/master/metrics-core/src/main/java/io/dropwizard/metrics/ExponentiallyDecayingReservoir.java

template <size_t size_ = 1028,
          size_t alpha_time_1000 = 15,
          typename clock_ = std::chrono::system_clock,
          typename Mutex = std::mutex>
class ExponentiallyDecaying
{

    template <typename K, typename V>
    using MapType = std::map<K, V>;

public:
    static const WeightedReservoirTag tag;

    static constexpr const double ALPHA = double(alpha_time_1000) * 0.001;
    using ElapsedTimeUnit = std::chrono::seconds;

    static constexpr const size_t MAX_SIZE = size_;
    using Clock = clock_;
    using Timepoint = typename Clock::time_point;
    using Weight = double;

    struct Sample
    {
        Weight weight;
        double value;
    };

    const std::chrono::hours RESCALE_INTERVAL{1};

public:
    ExponentiallyDecaying();
    ~ExponentiallyDecaying() = default;

    void pushValue(double value, Timepoint timepoint = Clock::now());

    template <typename Summary>
    auto visit() const -> decltype(Summary::createAccumulator(0, tag))
    {
        std::lock_guard<Mutex> lock(mutex_);
        auto acc = Summary::createAccumulator(size_unsafe(), tag);
        for (const auto& value : values_)
        {
            const auto& sample = value.second;
            acc(sample.weight, sample.value);
        }

        return acc;
    }

    size_t size() const;
    size_t size_unsafe() const;

private:
    void rescale();
    static Weight weight(ElapsedTimeUnit duration);

private:
    mutable Mutex mutex_;
    std::random_device random_;
    std::mt19937 gen_;
    std::uniform_real_distribution<> dis_;

    MapType<Weight, Sample> values_;
    Timepoint start_time_;
    Timepoint next_rescale_;
};

template <size_t s, size_t a, typename c, typename m>
const WeightedReservoirTag ExponentiallyDecaying<s, a, c, m>::tag = {};

template <size_t s, size_t a, typename c, typename m>
ExponentiallyDecaying<s, a, c, m>::ExponentiallyDecaying()
: gen_(random_())
, dis_(0, 1)
{
    start_time_ = Clock::now();
    next_rescale_ = start_time_ + RESCALE_INTERVAL;
}

template <size_t s, size_t a, typename c, typename m>
typename ExponentiallyDecaying<s, a, c, m>::Weight
ExponentiallyDecaying<s, a, c, m>::weight(ElapsedTimeUnit duration)
{
    return ::exp(ALPHA * duration.count());
}

template <size_t s, size_t a, typename c, typename m>
size_t ExponentiallyDecaying<s, a, c, m>::size() const
{
    std::lock_guard<m> lock(mutex_);
    return values_.size();
}

template <size_t s, size_t a, typename c, typename m>
size_t ExponentiallyDecaying<s, a, c, m>::size_unsafe() const
{
    return values_.size();
}

template <size_t s, size_t a, typename c, typename m>
void ExponentiallyDecaying<s, a, c, m>::pushValue(double value, Timepoint timestamp)
{
    std::lock_guard<m> lock(mutex_);
    rescale();

    auto elapsed_time =
        std::chrono::duration_cast<ElapsedTimeUnit>(timestamp - start_time_);
    Sample sample{weight(elapsed_time), value};
    double priority = sample.weight / dis_(gen_);

    auto new_size = values_.size() + 1;
    if (new_size <= MAX_SIZE)
    {
        values_[priority] = sample;
    }
    else
    {
        auto it_first = values_.begin();
        if (it_first->first < priority && values_.emplace(priority, sample).second)
        {
            values_.erase(it_first);
        }
    }
}

template <size_t s, size_t a, typename c, typename m>
void ExponentiallyDecaying<s, a, c, m>::rescale()
{
    Timepoint now = Clock::now();

    if (now < next_rescale_)
    {
        return;
    }

    next_rescale_ = now + RESCALE_INTERVAL;
    auto old_start_time = start_time_;
    start_time_ = now;

    decltype(values_) values;
    values.swap(values_);

    const auto time =
        std::chrono::duration_cast<ElapsedTimeUnit>(start_time_ - old_start_time)
            .count();

    auto scale_factor = ::exp(-ALPHA * time);
    for (const auto& v : values)
    {
        auto key = v.first;
        auto const& sample = v.second;
        values_[key * scale_factor] = {sample.weight * scale_factor, sample.value};
    }
}

} // namespace reservoir
} // namespace metric
} // namespace commonpp
<|endoftext|>


<commit_before>#ifndef VIRTUALROBOT_CPP
#define VIRTUALROBOT_CPP

#include <stdlib.h>
#include <stdio.h>
#include <GL/gl.h>
#include <string.h>

extern "C" {
	#include "logic/Robot.h"
	#include "logic/MazeAlgorithm.h"
	#include "logic/MazeMap.h"
}

#include "VirtualRobot.h"
#include "Display.h"

VirtualRobot::VirtualRobot(VirtualMaze* virtualMaze)
{
	// create the robot using a blank maze map
	MazeMap* robotMM = (MazeMap*)calloc(1, sizeof(MazeMap));
	robot = robot_create(0, 0, robotMM);

	// bind the robot maze map to the virtualmaze
	virtualMaze->bindRobotMap(robotMM);

	int blockWidthPX = VirtualMaze::getBlockWidthPX();

	int x = robot->xPos * blockWidthPX + blockWidthPX/2 - robotSizePX/2;
	int y = robot->yPos * blockWidthPX + blockWidthPX/2 - robotSizePX/2;

	this->rectangle = new Rectangle(x, y, robotSizePX, robotSizePX);

	// save the pointer to the virtual maze
	this->virtualMaze = virtualMaze;

	// compute the flood fill
	//malgo_floodfill_compute(virtualMaze->getMazeMap(), floodFillMap);
	//
	//robot->ffMap = floodFillMap;
}

void VirtualRobot::run() {

	// feed in the raw wall sensor input
	feedSensorData();

	// run the robot drive code
	robot_run(robot);

	// calculate and update the new position
	int blockWidthPX = VirtualMaze::getBlockWidthPX();
	int offset = blockWidthPX / 2 - robotSizePX / 2;

	int newX = blockWidthPX * robot->xPos + offset;
	int newY = blockWidthPX * robot->yPos + offset;
	rectangle->setPos(newX, newY);
}

void VirtualRobot::feedSensorData() {
	// get the full map
	MazeMap* virtualMap = virtualMaze->getMazeMap();
	int x = robot->xPos;
	int y = robot->yPos;

	// load in information about surroundings
	BOOL northWall = mazemap_does_wall_exist(virtualMap, x, y, NORTH);
	BOOL eastWall = mazemap_does_wall_exist(virtualMap, x, y, EAST);
	BOOL southWall = mazemap_does_wall_exist(virtualMap, x, y, SOUTH);
	BOOL westWall = mazemap_does_wall_exist(virtualMap, x, y, WEST);

	// plug the data from the virtual maze into the robot's maze map
	MazeMap* robotMap = robot->mazeMap;
	mazemap_set_wall(robotMap, northWall, x, y, NORTH);
	mazemap_set_wall(robotMap, eastWall, x, y, EAST);
	mazemap_set_wall(robotMap, southWall, x, y, SOUTH);
	mazemap_set_wall(robotMap, westWall, x, y, WEST);
}

void VirtualRobot::draw() {
	// draw the robot red
	rectangle->draw(1.0f, 0.0f, 0.0f);

	// draw the flood fill
	//ff_draw(robot->ffMap);

}

FFMapPtr VirtualRobot::getFloodFillMap() {
	return robot->ffMap;
}

VirtualRobot::~VirtualRobot() {
	// destroy the robot
	robot_destroy(robot);
}

#endif
<commit_msg>robot now yellow when exploring, red when solving VirtualRobot checks the robot->isExploring flag when drawing<commit_after>#ifndef VIRTUALROBOT_CPP
#define VIRTUALROBOT_CPP

#include <stdlib.h>
#include <stdio.h>
#include <GL/gl.h>
#include <string.h>

extern "C" {
	#include "logic/Robot.h"
	#include "logic/MazeAlgorithm.h"
	#include "logic/MazeMap.h"
}

#include "VirtualRobot.h"
#include "Display.h"

VirtualRobot::VirtualRobot(VirtualMaze* virtualMaze)
{
	// create the robot using a blank maze map
	MazeMap* robotMM = (MazeMap*)calloc(1, sizeof(MazeMap));
	robot = robot_create(0, 0, robotMM);

	// bind the robot maze map to the virtualmaze
	virtualMaze->bindRobotMap(robotMM);

	int blockWidthPX = VirtualMaze::getBlockWidthPX();

	int x = robot->xPos * blockWidthPX + blockWidthPX/2 - robotSizePX/2;
	int y = robot->yPos * blockWidthPX + blockWidthPX/2 - robotSizePX/2;

	this->rectangle = new Rectangle(x, y, robotSizePX, robotSizePX);

	// save the pointer to the virtual maze
	this->virtualMaze = virtualMaze;

	// compute the flood fill
	//malgo_floodfill_compute(virtualMaze->getMazeMap(), floodFillMap);
	//
	//robot->ffMap = floodFillMap;
}

void VirtualRobot::run() {

	// feed in the raw wall sensor input
	feedSensorData();

	// run the robot drive code
	robot_run(robot);

	// calculate and update the new position
	int blockWidthPX = VirtualMaze::getBlockWidthPX();
	int offset = blockWidthPX / 2 - robotSizePX / 2;

	int newX = blockWidthPX * robot->xPos + offset;
	int newY = blockWidthPX * robot->yPos + offset;
	rectangle->setPos(newX, newY);
}

void VirtualRobot::feedSensorData() {
	// get the full map
	MazeMap* virtualMap = virtualMaze->getMazeMap();
	int x = robot->xPos;
	int y = robot->yPos;

	// load in information about surroundings
	BOOL northWall = mazemap_does_wall_exist(virtualMap, x, y, NORTH);
	BOOL eastWall = mazemap_does_wall_exist(virtualMap, x, y, EAST);
	BOOL southWall = mazemap_does_wall_exist(virtualMap, x, y, SOUTH);
	BOOL westWall = mazemap_does_wall_exist(virtualMap, x, y, WEST);

	// plug the data from the virtual maze into the robot's maze map
	MazeMap* robotMap = robot->mazeMap;
	mazemap_set_wall(robotMap, northWall, x, y, NORTH);
	mazemap_set_wall(robotMap, eastWall, x, y, EAST);
	mazemap_set_wall(robotMap, southWall, x, y, SOUTH);
	mazemap_set_wall(robotMap, westWall, x, y, WEST);
}

void VirtualRobot::draw() {
	// draw the robot yellow if exploring, red if solving
	if (robot->isExploring) {
		rectangle->draw(1.0f, 1.0f, 0.0f);
	}
	else {
		rectangle->draw(1.0f, 0.0f, 0.0f);
	}
}

FFMapPtr VirtualRobot::getFloodFillMap() {
	return robot->ffMap;
}

VirtualRobot::~VirtualRobot() {
	// destroy the robot
	robot_destroy(robot);
}

#endif
<|endoftext|>


<commit_before>//
// open horizon -- undefined_darkness@outlook.com
//

#include "shared.h"
#include "memory/memory_reader.h"
#include "memory/tmp_buffer.h"
#include <assert.h>

namespace shared
{

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

namespace
{
    std::map<unsigned int,nya_scene::texture> textures;
}

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

void add_texture(unsigned int hash_id, const nya_scene::texture &tex)
{
    textures[hash_id] = tex;
}

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

unsigned int load_texture(const char *name)
{
    auto *res = nya_resources::get_resources_provider().access(name);
    if (!res)
        return 0;

    size_t size = res->get_size();
    nya_memory::tmp_buffer_scoped buf(size);
    res->read_all(buf.get_data());
    res->release();

    return load_texture(buf.get_data(), size);
}

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

unsigned int load_texture(const void *tex_data, size_t tex_size)
{
    assert(tex_data && tex_size);

    nya_memory::memory_reader reader(tex_data,tex_size);
    reader.seek(48);
    int offset = reader.read<int>();
    reader.seek(offset + 8);
    auto hash_id = reader.read<unsigned int>();
    //printf("%d\n", hash_id);
    reader.seek(offset + 16);

    if (reader.get_remained() < 128) //normal for ntxr
        return hash_id;
/*
    if(hash_id > 1000000000) //ToDo
    {
        unsigned int *mip_count = (unsigned int *)reader.get_data()+7;
        assert(*mip_count > 10);
        *mip_count = 5;
    }
*/
    nya_scene::shared_texture st;
    nya_scene::resource_data data(reader.get_remained());
    data.copy_from(reader.get_data(), reader.get_remained());
    nya_scene::texture::load_dds(st, data, "");
    data.free();
    nya_scene::texture tex;
    tex.create(st);
    shared::add_texture(hash_id, tex);

    return hash_id;
}

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

void clear_textures()
{
    textures.clear();
}

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

const nya_scene::texture &get_texture(unsigned int hash_id)
{
    auto tex = textures.find(hash_id);
    //assert(tex != textures.end());

    return tex->second;
}

const nya_scene::texture &get_black_texture()
{
    static nya_scene::texture black;
    static bool initialised=false;
    if(!initialised)
    {
        const unsigned char data[4]={0,0,0,0};
        nya_scene::shared_texture res;
        res.tex.build_texture(data,1,1,nya_render::texture::color_rgba);
        black.create(res);
        initialised=true;
    }

    return black;
}

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

nya_memory::tmp_buffer_ref load_resource(const char *name)
{
    nya_resources::resource_data *res = nya_resources::get_resources_provider().access(name);
    if (!res)
        return nya_memory::tmp_buffer_ref();

    nya_memory::tmp_buffer_ref buf(res->get_size());
    res->read_all(buf.get_data());
    res->release();

    return buf;
}

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

}
<commit_msg>land aniso<commit_after>//
// open horizon -- undefined_darkness@outlook.com
//

#include "shared.h"
#include "memory/memory_reader.h"
#include "memory/tmp_buffer.h"
#include <assert.h>

namespace shared
{

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

namespace
{
    std::map<unsigned int,nya_scene::texture> textures;
}

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

void add_texture(unsigned int hash_id, const nya_scene::texture &tex)
{
    textures[hash_id] = tex;
}

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

unsigned int load_texture(const char *name)
{
    auto *res = nya_resources::get_resources_provider().access(name);
    if (!res)
        return 0;

    size_t size = res->get_size();
    nya_memory::tmp_buffer_scoped buf(size);
    res->read_all(buf.get_data());
    res->release();

    return load_texture(buf.get_data(), size);
}

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

unsigned int load_texture(const void *tex_data, size_t tex_size)
{
    assert(tex_data && tex_size);

    nya_memory::memory_reader reader(tex_data,tex_size);
    reader.seek(48);
    int offset = reader.read<int>();
    reader.seek(offset + 8);
    auto hash_id = reader.read<unsigned int>();
    //printf("%d\n", hash_id);
    reader.seek(offset + 16);

    if (reader.get_remained() < 128) //normal for ntxr
        return hash_id;
/*
    if(hash_id > 1000000000) //ToDo
    {
        unsigned int *mip_count = (unsigned int *)reader.get_data()+7;
        assert(*mip_count > 10);
        *mip_count = 5;
    }
*/
    nya_scene::shared_texture st;
    nya_scene::resource_data data(reader.get_remained());
    data.copy_from(reader.get_data(), reader.get_remained());
    nya_scene::texture::load_dds(st, data, "");
    data.free();

    if(hash_id > 1000000000) //ToDo
        st.tex.set_aniso(16);

    nya_scene::texture tex;
    tex.create(st);
    shared::add_texture(hash_id, tex);

    return hash_id;
}

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

void clear_textures()
{
    textures.clear();
}

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

const nya_scene::texture &get_texture(unsigned int hash_id)
{
    auto tex = textures.find(hash_id);
    //assert(tex != textures.end());

    return tex->second;
}

const nya_scene::texture &get_black_texture()
{
    static nya_scene::texture black;
    static bool initialised=false;
    if(!initialised)
    {
        const unsigned char data[4]={0,0,0,0};
        nya_scene::shared_texture res;
        res.tex.build_texture(data,1,1,nya_render::texture::color_rgba);
        black.create(res);
        initialised=true;
    }

    return black;
}

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

nya_memory::tmp_buffer_ref load_resource(const char *name)
{
    nya_resources::resource_data *res = nya_resources::get_resources_provider().access(name);
    if (!res)
        return nya_memory::tmp_buffer_ref();

    nya_memory::tmp_buffer_ref buf(res->get_size());
    res->read_all(buf.get_data());
    res->release();

    return buf;
}

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

}
<|endoftext|>


<commit_before><commit_msg>Update CF471A<commit_after><|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qapplication.h"

#ifndef QT_NO_SOUND

#include "qsound.h"
#include "qpaintdevice.h"
#include "qwsdisplay_qws.h"
#include "qsound_p.h"

#include "qsoundqss_qws.h"

#include "qhash.h"
#include "qfileinfo.h"

#include "qbytearray.h"
#include "quuid.h"
#include "qdatastream.h"
#include "qcopchannel_qws.h"
#include "qbuffer.h"

QT_BEGIN_NAMESPACE

#ifdef MEDIA_SERVER

#define SERVER_CHANNEL "QPE/MediaServer"

class QCopMessage : public QDataStream
{
public:
    QCopMessage( const QString& channel, const QString& message )
        : QDataStream( new QBuffer ), m_channel( channel ), m_message( message )
    {
        device()->open( QIODevice::WriteOnly );
    }

    ~QCopMessage()
    {
        QCopChannel::send( m_channel, m_message, ((QBuffer*)device())->buffer() );
        delete device();
    }

private:
    QString m_channel;
    QString m_message;
};

#endif // MEDIA_SERVER

class QAuServerQWS;

class QAuBucketQWS : public QObject, public QAuBucket
{
    Q_OBJECT
public:
    QAuBucketQWS( QAuServerQWS*, QSound*, QObject* parent = 0 );

    ~QAuBucketQWS();

#ifndef MEDIA_SERVER
    int id() const { return id_; }
#endif

    QSound* sound() const { return sound_; }

#ifdef MEDIA_SERVER
    void play();

    void stop();
#endif

signals:
    // Only for Media Server
    void done( QAuBucketQWS* );

private slots:
    // Only for Media Server
    void processMessage( const QString& msg, const QByteArray& data );

private:
#ifdef MEDIA_SERVER
    QCopChannel *m_channel;
    QUuid m_id;
#endif

#ifndef MEDIA_SERVER
    int id_;
#endif
    QSound *sound_;
    QAuServerQWS *server_;

    static int next;
};

int QAuBucketQWS::next = 0;

class QAuServerQWS : public QAuServer
{
    Q_OBJECT
public:
    QAuServerQWS( QObject* parent );

    void init( QSound* s )
    {
        QAuBucketQWS *bucket = new QAuBucketQWS( this, s );
#ifdef MEDIA_SERVER
        connect( bucket, SIGNAL(done(QAuBucketQWS*)),
            this, SLOT(complete(QAuBucketQWS*)) );
#endif
        setBucket( s, bucket );
    }

#ifndef MEDIA_SERVER
    // Register bucket
    void insert( QAuBucketQWS *bucket )
    {
        buckets.insert( bucket->id(), bucket );
    }

    // Remove bucket from register
    void remove( QAuBucketQWS *bucket )
    {
        buckets.remove( bucket->id() );
    }
#endif

    void play( QSound* s )
    {
        QString filepath = QFileInfo( s->fileName() ).absoluteFilePath();
#if defined(QT_NO_QWS_SOUNDSERVER)
        server->playFile( bucket( s )->id(), filepath );
#elif defined(MEDIA_SERVER)
        bucket( s )->play();
#else
        client->play( bucket( s )->id(), filepath );
#endif
    }

    void stop( QSound* s )
    {
#if defined(QT_NO_QWS_SOUNDSERVER)
        server->stopFile( bucket( s )->id() );
#elif defined(MEDIA_SERVER)
        bucket( s )->stop();
#else
        client->stop( bucket( s )->id() );
#endif
    }

    bool okay() { return true; }

private slots:
    // Continue playing sound if loops remain
    void complete( int id )
    {
#ifndef MEDIA_SERVER
        QAuBucketQWS *bucket = find( id );
        if( bucket ) {
            QSound *sound = bucket->sound();
            if( decLoop( sound ) ) {
                play( sound );
            }
        }
#else
        Q_UNUSED(id);
#endif
    }

    // Only for Media Server
    void complete( QAuBucketQWS* bucket )
    {
#ifndef MEDIA_SERVER
        Q_UNUSED(bucket);
#else
        QSound *sound = bucket->sound();
        if( decLoop( sound ) ) {
            play( sound );
        }
#endif
    }

protected:
    QAuBucketQWS* bucket( QSound *s )
    {
        return (QAuBucketQWS*)QAuServer::bucket( s );
    }

private:
#ifndef MEDIA_SERVER
    // Find registered bucket with given id, return null if none found
    QAuBucketQWS* find( int id )
    {
        QHash<int, QAuBucketQWS*>::Iterator it = buckets.find( id );
        if( it != buckets.end() ) {
            return it.value();
        }

        return 0;
    }

    QHash<int, QAuBucketQWS*> buckets; // ### possible problem with overlapping keys

#ifdef QT_NO_QWS_SOUNDSERVER
    QWSSoundServer *server;
#else
    QWSSoundClient *client;
#endif

#endif // MEDIA_SERVER
};

QAuServerQWS::QAuServerQWS(QObject* parent) :
    QAuServer(parent)
{
#ifndef MEDIA_SERVER
    setObjectName(QLatin1String("qauserverqws"));

#ifdef QT_NO_QWS_SOUNDSERVER
    server = new QWSSoundServer( this ); // ### only suitable for single application

    connect( server, SIGNAL(soundCompleted(int)),
        this, SLOT(complete(int)) );
#else
    client = new QWSSoundClient( this ); // ### requires successful connection

    connect( client, SIGNAL(soundCompleted(int)),
        this, SLOT(complete(int)) );
#endif

#endif // MEDIA_SERVER
}

QAuBucketQWS::QAuBucketQWS( QAuServerQWS *server, QSound *sound, QObject* parent )
    : QObject( parent ), sound_( sound ), server_( server )
{
#ifdef MEDIA_SERVER
    m_id = QUuid::createUuid();

    sound->setObjectName( m_id.toString() );

    m_channel = new QCopChannel(QLatin1String("QPE/QSound/") + m_id ), this );
    connect( m_channel, SIGNAL(received(QString,QByteArray)),
        this, SLOT(processMessage(QString,QByteArray)) );

    {
        QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("subscribe(QUuid)") );
        message << m_id;
    }

    {
        QString filepath = QFileInfo( sound_->fileName() ).absoluteFilePath();
        QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("open(QUuid,QString)") );
        message << m_id << filepath;
    }
#else
    id_ = next++;
    server_->insert( this );
#endif
}

#ifdef MEDIA_SERVER
void QAuBucketQWS::play()
{
    QString filepath = QFileInfo( sound_->fileName() ).absoluteFilePath();

    QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("play(QUuid)") );
    message << m_id;
}

void QAuBucketQWS::stop()
{
    QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("stop(QUuid)") );
    message << m_id;
}
#endif // MEDIA_SERVER

void QAuBucketQWS::processMessage( const QString& msg, const QByteArray& data )
{
    Q_UNUSED(data);
#ifndef MEDIA_SERVER
    Q_UNUSED(msg);
#else
    if( msg == QLatin1String("done()") ) {
        emit done( this );
    }
#endif
}

QAuBucketQWS::~QAuBucketQWS()
{
#ifdef MEDIA_SERVER
    QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("revoke(QUuid)") );
    message << m_id;
#else
    server_->remove( this );
#endif
}

QAuServer* qt_new_audio_server()
{
    return new QAuServerQWS(qApp);
}

#include "qsound_qws.moc"

#endif // QT_NO_SOUND

QT_END_NAMESPACE
<commit_msg>Fix compile error in MEDIA_SERVER code.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, 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.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qapplication.h"

#ifndef QT_NO_SOUND

#include "qsound.h"
#include "qpaintdevice.h"
#include "qwsdisplay_qws.h"
#include "qsound_p.h"

#include "qsoundqss_qws.h"

#include "qhash.h"
#include "qfileinfo.h"

#include "qbytearray.h"
#include "quuid.h"
#include "qdatastream.h"
#include "qcopchannel_qws.h"
#include "qbuffer.h"

QT_BEGIN_NAMESPACE

#ifdef MEDIA_SERVER

#define SERVER_CHANNEL "QPE/MediaServer"

class QCopMessage : public QDataStream
{
public:
    QCopMessage( const QString& channel, const QString& message )
        : QDataStream( new QBuffer ), m_channel( channel ), m_message( message )
    {
        device()->open( QIODevice::WriteOnly );
    }

    ~QCopMessage()
    {
        QCopChannel::send( m_channel, m_message, ((QBuffer*)device())->buffer() );
        delete device();
    }

private:
    QString m_channel;
    QString m_message;
};

#endif // MEDIA_SERVER

class QAuServerQWS;

class QAuBucketQWS : public QObject, public QAuBucket
{
    Q_OBJECT
public:
    QAuBucketQWS( QAuServerQWS*, QSound*, QObject* parent = 0 );

    ~QAuBucketQWS();

#ifndef MEDIA_SERVER
    int id() const { return id_; }
#endif

    QSound* sound() const { return sound_; }

#ifdef MEDIA_SERVER
    void play();

    void stop();
#endif

signals:
    // Only for Media Server
    void done( QAuBucketQWS* );

private slots:
    // Only for Media Server
    void processMessage( const QString& msg, const QByteArray& data );

private:
#ifdef MEDIA_SERVER
    QCopChannel *m_channel;
    QUuid m_id;
#endif

#ifndef MEDIA_SERVER
    int id_;
#endif
    QSound *sound_;
    QAuServerQWS *server_;

    static int next;
};

int QAuBucketQWS::next = 0;

class QAuServerQWS : public QAuServer
{
    Q_OBJECT
public:
    QAuServerQWS( QObject* parent );

    void init( QSound* s )
    {
        QAuBucketQWS *bucket = new QAuBucketQWS( this, s );
#ifdef MEDIA_SERVER
        connect( bucket, SIGNAL(done(QAuBucketQWS*)),
            this, SLOT(complete(QAuBucketQWS*)) );
#endif
        setBucket( s, bucket );
    }

#ifndef MEDIA_SERVER
    // Register bucket
    void insert( QAuBucketQWS *bucket )
    {
        buckets.insert( bucket->id(), bucket );
    }

    // Remove bucket from register
    void remove( QAuBucketQWS *bucket )
    {
        buckets.remove( bucket->id() );
    }
#endif

    void play( QSound* s )
    {
        QString filepath = QFileInfo( s->fileName() ).absoluteFilePath();
#if defined(QT_NO_QWS_SOUNDSERVER)
        server->playFile( bucket( s )->id(), filepath );
#elif defined(MEDIA_SERVER)
        bucket( s )->play();
#else
        client->play( bucket( s )->id(), filepath );
#endif
    }

    void stop( QSound* s )
    {
#if defined(QT_NO_QWS_SOUNDSERVER)
        server->stopFile( bucket( s )->id() );
#elif defined(MEDIA_SERVER)
        bucket( s )->stop();
#else
        client->stop( bucket( s )->id() );
#endif
    }

    bool okay() { return true; }

private slots:
    // Continue playing sound if loops remain
    void complete( int id )
    {
#ifndef MEDIA_SERVER
        QAuBucketQWS *bucket = find( id );
        if( bucket ) {
            QSound *sound = bucket->sound();
            if( decLoop( sound ) ) {
                play( sound );
            }
        }
#else
        Q_UNUSED(id);
#endif
    }

    // Only for Media Server
    void complete( QAuBucketQWS* bucket )
    {
#ifndef MEDIA_SERVER
        Q_UNUSED(bucket);
#else
        QSound *sound = bucket->sound();
        if( decLoop( sound ) ) {
            play( sound );
        }
#endif
    }

protected:
    QAuBucketQWS* bucket( QSound *s )
    {
        return (QAuBucketQWS*)QAuServer::bucket( s );
    }

private:
#ifndef MEDIA_SERVER
    // Find registered bucket with given id, return null if none found
    QAuBucketQWS* find( int id )
    {
        QHash<int, QAuBucketQWS*>::Iterator it = buckets.find( id );
        if( it != buckets.end() ) {
            return it.value();
        }

        return 0;
    }

    QHash<int, QAuBucketQWS*> buckets; // ### possible problem with overlapping keys

#ifdef QT_NO_QWS_SOUNDSERVER
    QWSSoundServer *server;
#else
    QWSSoundClient *client;
#endif

#endif // MEDIA_SERVER
};

QAuServerQWS::QAuServerQWS(QObject* parent) :
    QAuServer(parent)
{
#ifndef MEDIA_SERVER
    setObjectName(QLatin1String("qauserverqws"));

#ifdef QT_NO_QWS_SOUNDSERVER
    server = new QWSSoundServer( this ); // ### only suitable for single application

    connect( server, SIGNAL(soundCompleted(int)),
        this, SLOT(complete(int)) );
#else
    client = new QWSSoundClient( this ); // ### requires successful connection

    connect( client, SIGNAL(soundCompleted(int)),
        this, SLOT(complete(int)) );
#endif

#endif // MEDIA_SERVER
}

QAuBucketQWS::QAuBucketQWS( QAuServerQWS *server, QSound *sound, QObject* parent )
    : QObject( parent ), sound_( sound ), server_( server )
{
#ifdef MEDIA_SERVER
    m_id = QUuid::createUuid();

    sound->setObjectName( m_id.toString() );

    m_channel = new QCopChannel(QLatin1String("QPE/QSound/") + m_id, this );
    connect( m_channel, SIGNAL(received(QString,QByteArray)),
        this, SLOT(processMessage(QString,QByteArray)) );

    {
        QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("subscribe(QUuid)") );
        message << m_id;
    }

    {
        QString filepath = QFileInfo( sound_->fileName() ).absoluteFilePath();
        QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("open(QUuid,QString)") );
        message << m_id << filepath;
    }
#else
    id_ = next++;
    server_->insert( this );
#endif
}

#ifdef MEDIA_SERVER
void QAuBucketQWS::play()
{
    QString filepath = QFileInfo( sound_->fileName() ).absoluteFilePath();

    QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("play(QUuid)") );
    message << m_id;
}

void QAuBucketQWS::stop()
{
    QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("stop(QUuid)") );
    message << m_id;
}
#endif // MEDIA_SERVER

void QAuBucketQWS::processMessage( const QString& msg, const QByteArray& data )
{
    Q_UNUSED(data);
#ifndef MEDIA_SERVER
    Q_UNUSED(msg);
#else
    if( msg == QLatin1String("done()") ) {
        emit done( this );
    }
#endif
}

QAuBucketQWS::~QAuBucketQWS()
{
#ifdef MEDIA_SERVER
    QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String("revoke(QUuid)") );
    message << m_id;
#else
    server_->remove( this );
#endif
}

QAuServer* qt_new_audio_server()
{
    return new QAuServerQWS(qApp);
}

#include "qsound_qws.moc"

#endif // QT_NO_SOUND

QT_END_NAMESPACE
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkPointSet.h"
#include "mitkOperation.h"
#include "mitkOperationActor.h"
#include "mitkPointOperation.h"
#include "mitkInteractionConst.h"
#include "mitkXMLWriter.h"
#include "mitkXMLReader.h"
#include "mitkPointSetWriter.h"
#include "mitkPointSetReader.h"
#include "mitkRenderingManager.h"

#include <itkSmartPointerForwardReference.txx>

mitk::PointSet::PointSet()
{
  m_Initialized = false;
  m_PointSetSeries.resize( 1 );

  m_PointSetSeries[0] = DataType::New();
  PointDataContainer::Pointer pointData = PointDataContainer::New();
  m_PointSetSeries[0]->SetPointData( pointData );

  this->Initialize( 1 );
}

mitk::PointSet::~PointSet()
{
}

void mitk::PointSet::Initialize( const mitk::Geometry3D *geometry )
{
  const mitk::TimeSlicedGeometry *timeGeometry =
    dynamic_cast< const mitk::TimeSlicedGeometry * >( geometry );

  if ( timeGeometry )
  {
    this->Initialize( timeGeometry->GetTimeSteps() );
  }

  this->SetGeometry( static_cast< Geometry3D * >(
    geometry->Clone().GetPointer() ) );

}

void mitk::PointSet::Initialize( int timeSteps )
{
  mitk::TimeSlicedGeometry::Pointer timeGeometry = this->GetTimeSlicedGeometry();

  mitk::Geometry3D::Pointer g3d = mitk::Geometry3D::New();
  g3d->Initialize();

  if ( timeSteps > 1 )
  {
    mitk::ScalarType timeBounds[] = {0.0, 1.0};
    g3d->SetTimeBounds( timeBounds );
  }

  //
  // The geometry is propagated automatically to the other items,
  // if EvenlyTimed is true...
  //
  timeGeometry->InitializeEvenlyTimed( g3d.GetPointer(), timeSteps );

  m_Initialized = true;
}

bool mitk::PointSet::IsEmpty(int t) const
{
  return IsInitialized() && (GetSize(t) <= 0);
}

void mitk::PointSet::AdaptPointSetSeriesSize( int timeSteps )
{
  // Check if the vector is long enouth to contain the new element
  // at the given position. If not, expand it with sufficient pre-initialized
  // elements.
  if ( timeSteps > m_PointSetSeries.size() )
  {
    int oldSize = m_PointSetSeries.size();
    m_PointSetSeries.resize( timeSteps );

    int i;
    for ( i = oldSize; i < timeSteps; ++i )
    {
      m_PointSetSeries[i] = DataType::New();
      PointDataContainer::Pointer pointData = PointDataContainer::New();
      m_PointSetSeries[i]->SetPointData( pointData );
    }

    this->Initialize( timeSteps );
  }
}

int mitk::PointSet::GetPointSetSeriesSize() const
{
  return m_PointSetSeries.size();
}

int mitk::PointSet::GetSize( int t ) const
{
  if ( t < m_PointSetSeries.size() )
  {
    return m_PointSetSeries[t]->GetNumberOfPoints();
  }
  else
  {
    return 0;
  }
}

mitk::PointSet::DataType::Pointer mitk::PointSet::GetPointSet( int t ) const
{
  if ( t < m_PointSetSeries.size() )
  {
    return m_PointSetSeries[t];
  }
  else
  {
    return NULL;
  }
}

int mitk::PointSet::SearchPoint( Point3D point, float distance, int t  )
{
  if ( t >= m_PointSetSeries.size() )
  {
    return -1;
  }

  // Out is the point which is checked to be the searched point
  PointType out;
  out.Fill( 0 );
  PointType indexPoint;

  this->GetGeometry( t )->WorldToIndex(point, indexPoint);

  // Searching the first point in the Set, that is +- distance far away fro
  // the given point
  unsigned int i;
  PointsContainer::Iterator it, end;
  end = m_PointSetSeries[t]->GetPoints()->End();
  int bestIndex = -1;
  distance = distance * distance;

  // To correct errors from converting index to world and world to index
  if (distance == 0.0)
  {
    distance = 0.000001;
  }

  ScalarType bestDist = distance;
  ScalarType dist, tmp;

  for ( it = m_PointSetSeries[t]->GetPoints()->Begin(), i = 0;
        it != end;
        ++it, ++i )
  {
    bool ok = m_PointSetSeries[t]->GetPoints()
      ->GetElementIfIndexExists( it->Index(), &out );

    if ( !ok )
    {
      return -1;
    }
    else if ( indexPoint == out ) //if totaly equal
    {
      return it->Index();
    }

    //distance calculation
    tmp = out[0] - indexPoint[0]; dist  = tmp * tmp;
    tmp = out[1] - indexPoint[1]; dist += tmp * tmp;
    tmp = out[2] - indexPoint[2]; dist += tmp * tmp;

    if ( dist < bestDist )
    {
      bestIndex = it->Index();
      bestDist  = dist;
    }
  }
  return bestIndex;
}

mitk::PointSet::PointType
mitk::PointSet::GetPoint( int position, int t ) const
{
  PointType out;
  out.Fill(0);

  if ( t >= m_PointSetSeries.size() )
  {
    return out;
  }

  if ( m_PointSetSeries[t]->GetPoints()->IndexExists(position) )
  {
    m_PointSetSeries[t]->GetPoint( position, &out );

    this->GetGeometry(t)->IndexToWorld( out, out );

    return out;
  }
  else
  {
    return out;
  }
}

bool
mitk::PointSet
::GetPointIfExists( PointIdentifier id, PointType* point, int t )
{
  if ( t >= m_PointSetSeries.size() )
  {
    return false;
  }

  if ( m_PointSetSeries[t]->GetPoints()->GetElementIfIndexExists(id, point) )
  {
    this->GetGeometry( t )->IndexToWorld( *point, *point );
    return true;
  }
  else
  {
    return false;
  }
}

void mitk::PointSet::SetPoint( PointIdentifier id, PointType point, int t )
{
  this->AdaptPointSetSeriesSize( t+1 );

  mitk::Point3D indexPoint;
  this->GetGeometry( t )->WorldToIndex( point, indexPoint );
  m_PointSetSeries[t]->SetPoint( id, indexPoint );
}

void mitk::PointSet::InsertPoint( PointIdentifier id, PointType point, int t )
{
  if ( t < m_PointSetSeries.size() )
  {
    mitk::Point3D indexPoint;
    this->GetGeometry( t )->WorldToIndex( point, indexPoint );
    m_PointSetSeries[t]->GetPoints()->InsertElement( id, indexPoint );
  }
}

bool mitk::PointSet::IndexExists( int position, int t )
{
  if ( t < m_PointSetSeries.size() )
  {
    return m_PointSetSeries[t]->GetPoints()->IndexExists( position );
  }
  else
  {
    return false;
  }
}

bool mitk::PointSet::GetSelectInfo( int position, int t )
{
  if ( this->IndexExists( position, t ) )
  {
    PointDataType pointData = { 0, false, PTUNDEFINED };
    m_PointSetSeries[t]->GetPointData( position, &pointData );
    return pointData.selected;
  }
  else
  {
    return false;
  }
}

const int mitk::PointSet::GetNumberOfSelected( int t )
{
  if ( t >= m_PointSetSeries.size() )
  {
    return 0;
  }

  int numberOfSelected = 0;
  PointDataIterator it;
  for ( it = m_PointSetSeries[t]->GetPointData()->Begin();
        it != m_PointSetSeries[t]->GetPointData()->End();
        it++ )
  {
    if (it->Value().selected == true)
    {
      ++numberOfSelected;
    }
  }

  return numberOfSelected;
}

int mitk::PointSet::SearchSelectedPoint( int t )
{
  if ( t >= m_PointSetSeries.size() )
  {
    return -1;
  }

  PointDataIterator it;
  for ( it = m_PointSetSeries[t]->GetPointData()->Begin();
        it != m_PointSetSeries[t]->GetPointData()->End();
        it++ )
  {
    if ( it->Value().selected == true )
    {
      return it->Index();
    }
  }
  return -1;
}

void mitk::PointSet::ExecuteOperation( Operation* operation )
{
  int timeStep = -1;

  mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

  if ( pointOp )
  {
    timeStep = this->GetTimeSlicedGeometry()
      ->MSToTimeStep( pointOp->GetTimeInMS() );
  }

  if ( timeStep == -1 )
  {
    // Time outside of PointSet time bounds
    return;
  }

  switch (operation->GetOperationType())
  {
  case OpNOTHING:
    break;

  case OpINSERT://inserts the point at the given position and selects it.
    {
      int position = pointOp->GetIndex();

      PointType pt;
      pt.CastFrom(pointOp->GetPoint());

      //transfer from world to index coordinates
      this->GetGeometry( timeStep )->WorldToIndex(pt, pt);

      m_PointSetSeries[timeStep]->GetPoints()->InsertElement(position, pt);

      PointDataType pointData =
      {
        pointOp->GetIndex(),
        pointOp->GetSelected(),
        pointOp->GetPointType()
      };

      m_PointSetSeries[timeStep]->GetPointData()
        ->InsertElement(position, pointData);

      this->Modified();
      ((const itk::Object*)this)->InvokeEvent( NewPointEvent() );
      this->OnPointSetChange();
    }
    break;

  case OpMOVE://moves the point given by index
    {
      PointType pt;
      pt.CastFrom(pointOp->GetPoint());

      //transfer from world to index coordinates
      this->GetGeometry( timeStep )->WorldToIndex(pt, pt);

      m_PointSetSeries[timeStep]->SetPoint(pointOp->GetIndex(), pt);

      this->OnPointSetChange();

      this->Modified();
    }
    break;

  case OpREMOVE://removes the point at given by position
    {
      m_PointSetSeries[timeStep]->GetPoints()
        ->DeleteIndex((unsigned)pointOp->GetIndex());
      m_PointSetSeries[timeStep]->GetPointData()
        ->DeleteIndex((unsigned)pointOp->GetIndex());

      this->OnPointSetChange();

      this->Modified();
     ((const itk::Object*)this)->InvokeEvent( RemovedPointEvent() );
    }
    break;

  case OpSELECTPOINT://select the given point
    {
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.selected = true;
      m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;

  case OpDESELECTPOINT://unselect the given point
    {
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.selected = false;
      m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;

  case OpSETPOINTTYPE:
    {
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.pointSpec = pointOp->GetPointType();
      m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;

  default:
    itkWarningMacro("mitkPointSet could not understrand the operation. Please check!");
    break;
  }

  //to tell the mappers, that the data is modifierd and has to be updated
  //only call modified if anything is done, so call in cases
  //this->Modified();

  mitk::OperationEndEvent endevent(operation);
  ((const itk::Object*)this)->InvokeEvent(endevent);

  //*todo has to be done here, cause of update-pipeline not working yet
  // As discussed lately, don't mess with the rendering from inside data structures
  //mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}

void mitk::PointSet::UpdateOutputInformation()
{
  if ( this->GetSource( ) )
  {
      this->GetSource( )->UpdateOutputInformation( );
  }
  const DataType::BoundingBoxType *bb = m_PointSetSeries[0]->GetBoundingBox();
  BoundingBox::BoundsArrayType itkBounds = bb->GetBounds();
  float mitkBounds[6];

  //for assignment see Geometry3d::SetBounds(const float bounds)
  mitkBounds[0] = itkBounds[0];
  mitkBounds[1] = itkBounds[1];
  mitkBounds[2] = itkBounds[2];
  mitkBounds[3] = itkBounds[3];
  mitkBounds[4] = itkBounds[4];
  mitkBounds[5] = itkBounds[5];

  GetGeometry()->SetBounds(itkBounds);
}

void mitk::PointSet::SetRequestedRegionToLargestPossibleRegion()
{
}

bool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion()
{
    return false;
}

bool mitk::PointSet::VerifyRequestedRegion()
{
    return true;
}

void mitk::PointSet::SetRequestedRegion( itk::DataObject * )
{
}

bool mitk::PointSet::WriteXMLData( XMLWriter& xmlWriter )
{
  BaseData::WriteXMLData( xmlWriter );
  std::string fileName = xmlWriter.GetRelativePath();
  if(!xmlWriter.IsFileExtension(".mps", fileName))
    fileName += ".mps";

  if(xmlWriter.SaveSourceFiles()){
    PointSetWriter::Pointer writer = PointSetWriter::New();
    fileName = xmlWriter.GetAbsolutePath();
    if(!xmlWriter.IsFileExtension(".mps", fileName))
      fileName += ".mps";
    writer->SetFileName( fileName.c_str() );
    writer->SetInput( this );
    writer->Update();
  }
  xmlWriter.WriteProperty( XMLReader::FILENAME, fileName.c_str() );
  return true;
}

bool mitk::PointSet::ReadXMLData( XMLReader& xmlReader )
{
  BaseData::ReadXMLData( xmlReader );

  std::string fileName;
  xmlReader.GetAttribute( XMLReader::FILENAME, fileName );

  if ( fileName.empty() )
    return false;

  PointSetReader::Pointer reader = PointSetReader::New();
  reader->SetFileName( fileName.c_str() );
  reader->Update();
  mitk::PointSet::Pointer psp =
    dynamic_cast<mitk::PointSet*>( reader->GetOutput() );
  if (psp.IsNotNull())
  {
    m_PointSetSeries[0] = psp->GetPointSet();
  }

  if ( m_PointSetSeries[0].IsNull() )
  {
    return false;
  }

  return true;
}
<commit_msg>FIX: Correct order for passing Geometry in initialization (cf. bug #460)<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkPointSet.h"
#include "mitkOperation.h"
#include "mitkOperationActor.h"
#include "mitkPointOperation.h"
#include "mitkInteractionConst.h"
#include "mitkXMLWriter.h"
#include "mitkXMLReader.h"
#include "mitkPointSetWriter.h"
#include "mitkPointSetReader.h"
#include "mitkRenderingManager.h"

#include <itkSmartPointerForwardReference.txx>

mitk::PointSet::PointSet()
{
  m_Initialized = false;
  m_PointSetSeries.resize( 1 );

  m_PointSetSeries[0] = DataType::New();
  PointDataContainer::Pointer pointData = PointDataContainer::New();
  m_PointSetSeries[0]->SetPointData( pointData );

  this->Initialize( 1 );
}

mitk::PointSet::~PointSet()
{
}

void mitk::PointSet::Initialize( const mitk::Geometry3D *geometry )
{
  this->SetGeometry( static_cast< Geometry3D * >(
    geometry->Clone().GetPointer() ) );

  const mitk::TimeSlicedGeometry *timeGeometry =
    dynamic_cast< const mitk::TimeSlicedGeometry * >( geometry );

  if ( timeGeometry )
  {
    this->Initialize( timeGeometry->GetTimeSteps() );
  }
  else
  {
    this->Initialize( 1 );
  }
}

void mitk::PointSet::Initialize( int timeSteps )
{
  mitk::TimeSlicedGeometry::Pointer timeGeometry = this->GetTimeSlicedGeometry();

  mitk::Geometry3D::Pointer g3d = mitk::Geometry3D::New();
  g3d->Initialize();

  if ( timeSteps > 1 )
  {
    mitk::ScalarType timeBounds[] = {0.0, 1.0};
    g3d->SetTimeBounds( timeBounds );
  }

  //
  // The geometry is propagated automatically to the other items,
  // if EvenlyTimed is true...
  //
  timeGeometry->InitializeEvenlyTimed( g3d.GetPointer(), timeSteps );

  m_Initialized = true;
}

bool mitk::PointSet::IsEmpty(int t) const
{
  return IsInitialized() && (GetSize(t) <= 0);
}

void mitk::PointSet::AdaptPointSetSeriesSize( int timeSteps )
{
  // Check if the vector is long enouth to contain the new element
  // at the given position. If not, expand it with sufficient pre-initialized
  // elements.
  if ( timeSteps > m_PointSetSeries.size() )
  {
    int oldSize = m_PointSetSeries.size();
    m_PointSetSeries.resize( timeSteps );

    int i;
    for ( i = oldSize; i < timeSteps; ++i )
    {
      m_PointSetSeries[i] = DataType::New();
      PointDataContainer::Pointer pointData = PointDataContainer::New();
      m_PointSetSeries[i]->SetPointData( pointData );
    }

    this->Initialize( timeSteps );
  }
}

int mitk::PointSet::GetPointSetSeriesSize() const
{
  return m_PointSetSeries.size();
}

int mitk::PointSet::GetSize( int t ) const
{
  if ( t < m_PointSetSeries.size() )
  {
    return m_PointSetSeries[t]->GetNumberOfPoints();
  }
  else
  {
    return 0;
  }
}

mitk::PointSet::DataType::Pointer mitk::PointSet::GetPointSet( int t ) const
{
  if ( t < m_PointSetSeries.size() )
  {
    return m_PointSetSeries[t];
  }
  else
  {
    return NULL;
  }
}

int mitk::PointSet::SearchPoint( Point3D point, float distance, int t  )
{
  if ( t >= m_PointSetSeries.size() )
  {
    return -1;
  }

  // Out is the point which is checked to be the searched point
  PointType out;
  out.Fill( 0 );
  PointType indexPoint;

  this->GetGeometry( t )->WorldToIndex(point, indexPoint);

  // Searching the first point in the Set, that is +- distance far away fro
  // the given point
  unsigned int i;
  PointsContainer::Iterator it, end;
  end = m_PointSetSeries[t]->GetPoints()->End();
  int bestIndex = -1;
  distance = distance * distance;

  // To correct errors from converting index to world and world to index
  if (distance == 0.0)
  {
    distance = 0.000001;
  }

  ScalarType bestDist = distance;
  ScalarType dist, tmp;

  for ( it = m_PointSetSeries[t]->GetPoints()->Begin(), i = 0;
        it != end;
        ++it, ++i )
  {
    bool ok = m_PointSetSeries[t]->GetPoints()
      ->GetElementIfIndexExists( it->Index(), &out );

    if ( !ok )
    {
      return -1;
    }
    else if ( indexPoint == out ) //if totaly equal
    {
      return it->Index();
    }

    //distance calculation
    tmp = out[0] - indexPoint[0]; dist  = tmp * tmp;
    tmp = out[1] - indexPoint[1]; dist += tmp * tmp;
    tmp = out[2] - indexPoint[2]; dist += tmp * tmp;

    if ( dist < bestDist )
    {
      bestIndex = it->Index();
      bestDist  = dist;
    }
  }
  return bestIndex;
}

mitk::PointSet::PointType
mitk::PointSet::GetPoint( int position, int t ) const
{
  PointType out;
  out.Fill(0);

  if ( t >= m_PointSetSeries.size() )
  {
    return out;
  }

  if ( m_PointSetSeries[t]->GetPoints()->IndexExists(position) )
  {
    m_PointSetSeries[t]->GetPoint( position, &out );

    this->GetGeometry(t)->IndexToWorld( out, out );

    return out;
  }
  else
  {
    return out;
  }
}

bool
mitk::PointSet
::GetPointIfExists( PointIdentifier id, PointType* point, int t )
{
  if ( t >= m_PointSetSeries.size() )
  {
    return false;
  }

  if ( m_PointSetSeries[t]->GetPoints()->GetElementIfIndexExists(id, point) )
  {
    this->GetGeometry( t )->IndexToWorld( *point, *point );
    return true;
  }
  else
  {
    return false;
  }
}

void mitk::PointSet::SetPoint( PointIdentifier id, PointType point, int t )
{
  this->AdaptPointSetSeriesSize( t+1 );

  mitk::Point3D indexPoint;
  this->GetGeometry( t )->WorldToIndex( point, indexPoint );
  m_PointSetSeries[t]->SetPoint( id, indexPoint );
}

void mitk::PointSet::InsertPoint( PointIdentifier id, PointType point, int t )
{
  if ( t < m_PointSetSeries.size() )
  {
    mitk::Point3D indexPoint;
    this->GetGeometry( t )->WorldToIndex( point, indexPoint );
    m_PointSetSeries[t]->GetPoints()->InsertElement( id, indexPoint );
  }
}

bool mitk::PointSet::IndexExists( int position, int t )
{
  if ( t < m_PointSetSeries.size() )
  {
    return m_PointSetSeries[t]->GetPoints()->IndexExists( position );
  }
  else
  {
    return false;
  }
}

bool mitk::PointSet::GetSelectInfo( int position, int t )
{
  if ( this->IndexExists( position, t ) )
  {
    PointDataType pointData = { 0, false, PTUNDEFINED };
    m_PointSetSeries[t]->GetPointData( position, &pointData );
    return pointData.selected;
  }
  else
  {
    return false;
  }
}

const int mitk::PointSet::GetNumberOfSelected( int t )
{
  if ( t >= m_PointSetSeries.size() )
  {
    return 0;
  }

  int numberOfSelected = 0;
  PointDataIterator it;
  for ( it = m_PointSetSeries[t]->GetPointData()->Begin();
        it != m_PointSetSeries[t]->GetPointData()->End();
        it++ )
  {
    if (it->Value().selected == true)
    {
      ++numberOfSelected;
    }
  }

  return numberOfSelected;
}

int mitk::PointSet::SearchSelectedPoint( int t )
{
  if ( t >= m_PointSetSeries.size() )
  {
    return -1;
  }

  PointDataIterator it;
  for ( it = m_PointSetSeries[t]->GetPointData()->Begin();
        it != m_PointSetSeries[t]->GetPointData()->End();
        it++ )
  {
    if ( it->Value().selected == true )
    {
      return it->Index();
    }
  }
  return -1;
}

void mitk::PointSet::ExecuteOperation( Operation* operation )
{
  int timeStep = -1;

  mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);

  if ( pointOp )
  {
    timeStep = this->GetTimeSlicedGeometry()
      ->MSToTimeStep( pointOp->GetTimeInMS() );
  }

  if ( timeStep == -1 )
  {
    // Time outside of PointSet time bounds
    return;
  }

  switch (operation->GetOperationType())
  {
  case OpNOTHING:
    break;

  case OpINSERT://inserts the point at the given position and selects it.
    {
      int position = pointOp->GetIndex();

      PointType pt;
      pt.CastFrom(pointOp->GetPoint());

      //transfer from world to index coordinates
      this->GetGeometry( timeStep )->WorldToIndex(pt, pt);

      m_PointSetSeries[timeStep]->GetPoints()->InsertElement(position, pt);

      PointDataType pointData =
      {
        pointOp->GetIndex(),
        pointOp->GetSelected(),
        pointOp->GetPointType()
      };

      m_PointSetSeries[timeStep]->GetPointData()
        ->InsertElement(position, pointData);

      this->Modified();
      ((const itk::Object*)this)->InvokeEvent( NewPointEvent() );
      this->OnPointSetChange();
    }
    break;

  case OpMOVE://moves the point given by index
    {
      PointType pt;
      pt.CastFrom(pointOp->GetPoint());

      //transfer from world to index coordinates
      this->GetGeometry( timeStep )->WorldToIndex(pt, pt);

      m_PointSetSeries[timeStep]->SetPoint(pointOp->GetIndex(), pt);

      this->OnPointSetChange();

      this->Modified();
    }
    break;

  case OpREMOVE://removes the point at given by position
    {
      m_PointSetSeries[timeStep]->GetPoints()
        ->DeleteIndex((unsigned)pointOp->GetIndex());
      m_PointSetSeries[timeStep]->GetPointData()
        ->DeleteIndex((unsigned)pointOp->GetIndex());

      this->OnPointSetChange();

      this->Modified();
     ((const itk::Object*)this)->InvokeEvent( RemovedPointEvent() );
    }
    break;

  case OpSELECTPOINT://select the given point
    {
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.selected = true;
      m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;

  case OpDESELECTPOINT://unselect the given point
    {
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.selected = false;
      m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;

  case OpSETPOINTTYPE:
    {
      PointDataType pointData = {0, false, PTUNDEFINED};
      m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);
      pointData.pointSpec = pointOp->GetPointType();
      m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);
      this->Modified();
    }
    break;

  default:
    itkWarningMacro("mitkPointSet could not understrand the operation. Please check!");
    break;
  }

  //to tell the mappers, that the data is modifierd and has to be updated
  //only call modified if anything is done, so call in cases
  //this->Modified();

  mitk::OperationEndEvent endevent(operation);
  ((const itk::Object*)this)->InvokeEvent(endevent);

  //*todo has to be done here, cause of update-pipeline not working yet
  // As discussed lately, don't mess with the rendering from inside data structures
  //mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}

void mitk::PointSet::UpdateOutputInformation()
{
  if ( this->GetSource( ) )
  {
      this->GetSource( )->UpdateOutputInformation( );
  }
  const DataType::BoundingBoxType *bb = m_PointSetSeries[0]->GetBoundingBox();
  BoundingBox::BoundsArrayType itkBounds = bb->GetBounds();
  float mitkBounds[6];

  //for assignment see Geometry3d::SetBounds(const float bounds)
  mitkBounds[0] = itkBounds[0];
  mitkBounds[1] = itkBounds[1];
  mitkBounds[2] = itkBounds[2];
  mitkBounds[3] = itkBounds[3];
  mitkBounds[4] = itkBounds[4];
  mitkBounds[5] = itkBounds[5];

  GetGeometry()->SetBounds(itkBounds);
}

void mitk::PointSet::SetRequestedRegionToLargestPossibleRegion()
{
}

bool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion()
{
    return false;
}

bool mitk::PointSet::VerifyRequestedRegion()
{
    return true;
}

void mitk::PointSet::SetRequestedRegion( itk::DataObject * )
{
}

bool mitk::PointSet::WriteXMLData( XMLWriter& xmlWriter )
{
  BaseData::WriteXMLData( xmlWriter );
  std::string fileName = xmlWriter.GetRelativePath();
  if(!xmlWriter.IsFileExtension(".mps", fileName))
    fileName += ".mps";

  if(xmlWriter.SaveSourceFiles()){
    PointSetWriter::Pointer writer = PointSetWriter::New();
    fileName = xmlWriter.GetAbsolutePath();
    if(!xmlWriter.IsFileExtension(".mps", fileName))
      fileName += ".mps";
    writer->SetFileName( fileName.c_str() );
    writer->SetInput( this );
    writer->Update();
  }
  xmlWriter.WriteProperty( XMLReader::FILENAME, fileName.c_str() );
  return true;
}

bool mitk::PointSet::ReadXMLData( XMLReader& xmlReader )
{
  BaseData::ReadXMLData( xmlReader );

  std::string fileName;
  xmlReader.GetAttribute( XMLReader::FILENAME, fileName );

  if ( fileName.empty() )
    return false;

  PointSetReader::Pointer reader = PointSetReader::New();
  reader->SetFileName( fileName.c_str() );
  reader->Update();
  mitk::PointSet::Pointer psp =
    dynamic_cast<mitk::PointSet*>( reader->GetOutput() );
  if (psp.IsNotNull())
  {
    m_PointSetSeries[0] = psp->GetPointSet();
  }

  if ( m_PointSetSeries[0].IsNull() )
  {
    return false;
  }

  return true;
}
<|endoftext|>


<commit_before>/*
 * SurveySessionImplementation.cpp
 *
 *  Created on: May 22, 2012
 *      Author: Kyle
 */

#include "server/zone/objects/player/sessions/survey/SurveySession.h"
#include "server/zone/Zone.h"
#include "server/zone/managers/player/PlayerManager.h"
#include "server/zone/managers/resource/ResourceManager.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/tangible/tool/SurveyTool.h"
#include "server/zone/packets/scene/PlayClientEffectLocMessage.h"
#include "server/zone/objects/creature/CreatureAttribute.h"
#include "server/zone/objects/player/sessions/survey/sui/SurveyGMinigameSuiCallback.h"
#include "server/zone/objects/player/sessions/survey/sui/SurveyCMinigameSuiCallback.h"
#include "server/zone/managers/resource/resourcespawner/SampleTask.h"
#include "server/zone/managers/resource/resourcespawner/SurveyTask.h"
#include "server/zone/managers/resource/resourcespawner/SampleResultsTask.h"

int SurveySessionImplementation::initializeSession(SurveyTool* tool) {

	activeSurveyTool = tool;
	surveyerGhost = surveyer.get()->getPlayerObject();
	return startSession();
}

int SurveySessionImplementation::startSession() {
	ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();
	ManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get();

	if(surveyer == NULL || activeSurveyTool == NULL || surveyerGhost == NULL) {
		cancelSession();
		return false;
	}

	resourceManager = surveyer->getZoneServer()->getResourceManager();
	if(resourceManager == NULL) {
		cancelSession();
		return false;
	}

	surveyer->addActiveSession(SessionFacadeType::SURVEY, _this.get());

	return true;
}

int SurveySessionImplementation::cancelSession() {
	ManagedReference<CreatureObject*> ref = surveyer.get();

	if(ref != NULL)
		ref->dropActiveSession(SessionFacadeType::SURVEY);

	return clearSession();
}

int SurveySessionImplementation::clearSession() {

	return 0;
}

void SurveySessionImplementation::startSurvey(const String& resname) {
	ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();
	ManagedReference<ResourceManager*> resourceManager = this->resourceManager.get();
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();

	if (activeSurveyTool == NULL) {
		error("surveyTool is NULL");
		return;
	}

	if (resourceManager == NULL) {
		error("ResourceManager is NULL");
		return;
	}

	if (surveyer == NULL) {
		error("surveyer is NULL");
		return;
	}

	if (surveyer->getParent() != NULL && surveyer->getParent().get()->isCellObject()) {
		surveyer->sendSystemMessage("@error_message:survey_in_structure"); //You cannot perform survey-related actions inside a structure.
		return;
	}

	if (surveyer->isSwimming()) {
		surveyer->sendSystemMessage("@error_message:survey_swimming");
		return;
	}

	if (surveyer->isRidingMount()) {
		if(surveyer->isInWater()) {
			surveyer->sendSystemMessage("@error_message:survey_cant");
			return;
		}
	} else {
		if(surveyer->getPosture() != CreaturePosture::UPRIGHT) {
			surveyer->sendSystemMessage("@error_message:survey_standing");
			return;
		}
	}

	//Get actual cost based upon player's Focus
	int mindCost = surveyer->calculateCostAdjustment(CreatureAttribute::FOCUS, 100);

	if (surveyer->getHAM(CreatureAttribute::MIND) < mindCost) {
		surveyer->setPosture(CreaturePosture::UPRIGHT, true);
		surveyer->sendSystemMessage("@error_message:survey_mind"); //You are exhausted. You nee to clear your head before you can survey again.
		return;
	}

	ManagedReference<ResourceSpawn*> spawn = resourceManager->getResourceSpawn(resname);
	if(spawn == NULL) {
		return;
	}

	if(spawn->getSurveyToolType() != activeSurveyTool->getToolType()) {
		StringIdChatParameter message("@survey:wrong_tool"); // %TO resources cannot be located with this tool
		message.setTO(spawn->getFinalClass());
		surveyer->sendSystemMessage(message);
		return;
	}

	PlayClientEffectLoc* effect = new PlayClientEffectLoc(activeSurveyTool->getSurveyAnimation(),
			surveyer->getZone()->getZoneName(),
			surveyer->getPositionX(), surveyer->getPositionZ(),
			surveyer->getPositionY());

	surveyer->broadcastMessage(effect, true);

	resourceManager->sendSurvey(surveyer, resname);
}

void SurveySessionImplementation::startSample(const String& resname) {

	ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();
	ManagedReference<ResourceManager*> resourceManager = this->resourceManager.get();
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();
	ManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get();

	if (activeSurveyTool == NULL) {
		error("surveyTool is NULL");
		return;
	}

	if (resourceManager == NULL) {
		info("ResourceManager is NULL");
		return;
	}

	if (surveyer == NULL) {
		info("surveyer is NULL");
		return;
	}

	if (!resname.isEmpty())
		 lastResourceSampleName = resname;

	ManagedReference<ResourceSpawn* > resourceSpawn = resourceManager->getResourceSpawn(lastResourceSampleName);
	if (resourceSpawn == NULL) {
		return;
	}

	if (surveyer->isInCombat()) {
		surveyer->sendSystemMessage("@survey:sample_cancel_attack"); //You can't take samples while under attack!
		return;
	}

	if (surveyer->getParent() != NULL && surveyer->getParent().get()->isCellObject()) {
		surveyer->sendSystemMessage("@error_message:survey_in_structure"); //You cannot perform survey-related actions inside a structure.
		return;
	}

	if (surveyer->isSwimming()) {
		surveyer->sendSystemMessage("@error_message:survey_swimming");
		return;
	}

	if (surveyer->isRidingMount()) {
		surveyer->sendSystemMessage("@error_message:survey_on_mount");
		return;
	}

	//Get actual cost based upon player's Quickness
	int actionCost = surveyer->calculateCostAdjustment(CreatureAttribute::QUICKNESS, 200);

	if (surveyer->getHAM(CreatureAttribute::ACTION) < actionCost) {
		surveyer->setPosture(CreaturePosture::UPRIGHT, true);
		surveyer->sendSystemMessage("@error_message:sample_mind"); //You are exhausted. You nee to clear your head before you can sample again.
		return;
	}

	if(resourceSpawn->getSurveyToolType() != activeSurveyTool->getToolType()) {
		StringIdChatParameter message("@survey:wrong_tool"); // %TO resources cannot be located with this tool
		message.setTO(resourceSpawn->getFinalClass());
		surveyer->sendSystemMessage(message);
		return;
	}

	if(!lastResourceSampleName.isEmpty() && !activeSurveyTool->canSampleRadioactive()) {

		if(resourceSpawn->isType("radioactive") && !activeSurveyTool->canSampleRadioactive()) {
			activeSurveyTool->sendRadioactiveWarning(surveyer);
			return;
		}
	}

	// Player must be kneeling to sample
	if (!surveyer->isKneeling()) {
		surveyer->setPosture(CreaturePosture::CROUCHED, true);
	}

	if(surveyer->getPendingTask("sample") != NULL) {
		return;
	}

	StringIdChatParameter message("survey","start_sampling");
	message.setTO(lastResourceSampleName);
	surveyer->sendSystemMessage(message);

	if (!doGamble && richSampleLocation == NULL && System::random(50) == 7) {

		if (surveyerGhost->hasSuiBoxWindowType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME)) {
			surveyerGhost->removeSuiBoxType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME);
		}

		if (surveyerGhost->hasSuiBoxWindowType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2)) {
			surveyerGhost->removeSuiBoxType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2);
		}

		if(System::random(1) == 1)
			surveyCnodeMinigameSui();
		else
			surveyGnodeMinigameSui();

	} else {

		if (!lastResourceSampleName.isEmpty())
			resourceManager->sendSample(surveyer, lastResourceSampleName,
					activeSurveyTool->getSampleAnimation());
	}
}

void SurveySessionImplementation::surveyCnodeMinigameSui() {
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();

	//int surveyMod = surveyer->getSkillMod("surveying");

	ManagedReference<SuiListBox*> suiConcMinigameBox = new SuiListBox(
			surveyer, SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME, 0);

	suiConcMinigameBox->setPromptTitle("@survey:cnode_t");
	suiConcMinigameBox->setPromptText("@survey:cnode_d");

	suiConcMinigameBox->addMenuItem("@survey:cnode_1", 0);
	suiConcMinigameBox->addMenuItem("@survey:cnode_2", 1);

	suiConcMinigameBox->setCancelButton(true, "Cancel");

	suiConcMinigameBox->setCallback(new SurveyCMinigameSuiCallback(surveyer->getZoneServer()));
	surveyer->getPlayerObject()->addSuiBox(suiConcMinigameBox);
	surveyer->sendMessage(suiConcMinigameBox->generateMessage());
}

void SurveySessionImplementation::surveyCnodeMinigame(int value) {
	ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();
	ManagedReference<ResourceManager*> resourceManager = this->resourceManager.get();
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();
	ManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get();

	if(value == 0) {
		// Add sampletask
		rescheduleSample();

		return;
	}

	richSampleLocation = new Coordinate(surveyer->getPositionX(), surveyer->getPositionZ(), surveyer->getPositionY());
	richSampleLocation->randomizePosition(50);

	ManagedReference<WaypointObject*> newwaypoint = NULL;

	PlayerObject* ghost = surveyer->getPlayerObject();

	// Get previous survey waypoint
	ManagedReference<WaypointObject*> waypoint = ghost->getSurveyWaypoint();

	// Create new waypoint
	if (waypoint == NULL)
		newwaypoint = ( surveyer->getZoneServer()->createObject(0xc456e788, 1)).castTo<WaypointObject*>();
	else {
		ghost->removeWaypoint(waypoint->getObjectID(), true);
		newwaypoint = waypoint.get();
	}

	// Update new waypoint
	newwaypoint->setCustomObjectName(UnicodeString("Resource Survey"), false);
	newwaypoint->setPlanetCRC(surveyer->getZone()->getZoneCRC());
	newwaypoint->setPosition(richSampleLocation->getPositionX(), 0, richSampleLocation->getPositionY());
	newwaypoint->setColor(WaypointObject::COLOR_BLUE);
	newwaypoint->setSpecialTypeID(WaypointObject::SPECIALTYPE_RESOURCE);
	newwaypoint->setActive(true);

	ghost->addWaypoint(newwaypoint, false, true); // Should second argument be true, and waypoints with the same name thus remove their old version?
	surveyer->sendSystemMessage("@survey:node_waypoint");

	// Player must be kneeling to sample
	if (!surveyer->isStanding())
		surveyer->setPosture(CreaturePosture::UPRIGHT, true);
}

void SurveySessionImplementation::surveyGnodeMinigameSui() {
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();

	//int surveyMod = surveyer->getSkillMod("surveying");

	ManagedReference<SuiListBox*> suiConcMinigameBox = new SuiListBox(surveyer, SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2, 0);

	suiConcMinigameBox->setPromptTitle("@survey:gnode_t");
	suiConcMinigameBox->setPromptText("@survey:gnode_d");

	suiConcMinigameBox->addMenuItem("@survey:gnode_1", 0);
	suiConcMinigameBox->addMenuItem("@survey:gnode_2", 1);

	suiConcMinigameBox->setCancelButton(true, "Cancel");

	suiConcMinigameBox->setCallback(new SurveyGMinigameSuiCallback(surveyer->getZoneServer()));
	surveyer->getPlayerObject()->addSuiBox(suiConcMinigameBox);
	surveyer->sendMessage(suiConcMinigameBox->generateMessage());
}

void SurveySessionImplementation::surveyGnodeMinigame(int value) {
	ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();

	if(value == 1) {

		if(surveyer->getHAM(CreatureAttribute::ACTION) < 300) {
			surveyer->sendSystemMessage("@survey:gamble_no_action");
			return;
		}

		surveyer->inflictDamage(surveyer, CreatureAttribute::ACTION, 300, false, true);
		doGamble = true;
	}

	rescheduleSample();
}

void SurveySessionImplementation::rescheduleSurvey(SurveyMessage* surveyMessage, WaypointObject* waypoint, float maxDensity, ResourceSpawn* resourceSpawn) {
	surveyTask = new SurveyTask(surveyer, surveyMessage, waypoint, maxDensity * 100, resourceSpawn);
	surveyer.get()->addPendingTask("survey", surveyTask, 3000);
}

void SurveySessionImplementation::rescheduleSample() {
	// Add sampletask
	if(sampleTask == NULL)
		sampleTask = new SampleTask(surveyer.get(), activeSurveyTool.get());

	if(surveyer.get()->getPendingTask("sample") == NULL)
		surveyer.get()->addPendingTask("sample", sampleTask, 25000);
}

void SurveySessionImplementation::rescheduleSampleResults(ResourceSpawner* resourceSpawner, float density, const String& resname) {
	// Add sampleresultstask
	if(surveyer.get()->getPendingTask("sampleresults") == NULL) {
		sampleResultsTask = new SampleResultsTask(surveyer, resourceSpawner, density, resname);
		surveyer.get()->addPendingTask("sampleresults", sampleResultsTask, 3000);
	}
}

<commit_msg>[added] player may sample resources while riding creatures<commit_after>/*
 * SurveySessionImplementation.cpp
 *
 *  Created on: May 22, 2012
 *      Author: Kyle
 */

#include "server/zone/objects/player/sessions/survey/SurveySession.h"
#include "server/zone/Zone.h"
#include "server/zone/managers/player/PlayerManager.h"
#include "server/zone/managers/resource/ResourceManager.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "server/zone/objects/tangible/tool/SurveyTool.h"
#include "server/zone/packets/scene/PlayClientEffectLocMessage.h"
#include "server/zone/objects/creature/CreatureAttribute.h"
#include "server/zone/objects/player/sessions/survey/sui/SurveyGMinigameSuiCallback.h"
#include "server/zone/objects/player/sessions/survey/sui/SurveyCMinigameSuiCallback.h"
#include "server/zone/managers/resource/resourcespawner/SampleTask.h"
#include "server/zone/managers/resource/resourcespawner/SurveyTask.h"
#include "server/zone/managers/resource/resourcespawner/SampleResultsTask.h"

int SurveySessionImplementation::initializeSession(SurveyTool* tool) {

	activeSurveyTool = tool;
	surveyerGhost = surveyer.get()->getPlayerObject();
	return startSession();
}

int SurveySessionImplementation::startSession() {
	ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();
	ManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get();

	if(surveyer == NULL || activeSurveyTool == NULL || surveyerGhost == NULL) {
		cancelSession();
		return false;
	}

	resourceManager = surveyer->getZoneServer()->getResourceManager();
	if(resourceManager == NULL) {
		cancelSession();
		return false;
	}

	surveyer->addActiveSession(SessionFacadeType::SURVEY, _this.get());

	return true;
}

int SurveySessionImplementation::cancelSession() {
	ManagedReference<CreatureObject*> ref = surveyer.get();

	if(ref != NULL)
		ref->dropActiveSession(SessionFacadeType::SURVEY);

	return clearSession();
}

int SurveySessionImplementation::clearSession() {

	return 0;
}

void SurveySessionImplementation::startSurvey(const String& resname) {
	ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();
	ManagedReference<ResourceManager*> resourceManager = this->resourceManager.get();
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();

	if (activeSurveyTool == NULL) {
		error("surveyTool is NULL");
		return;
	}

	if (resourceManager == NULL) {
		error("ResourceManager is NULL");
		return;
	}

	if (surveyer == NULL) {
		error("surveyer is NULL");
		return;
	}

	if (surveyer->getParent() != NULL && surveyer->getParent().get()->isCellObject()) {
		surveyer->sendSystemMessage("@error_message:survey_in_structure"); //You cannot perform survey-related actions inside a structure.
		return;
	}

	if (surveyer->isSwimming()) {
		surveyer->sendSystemMessage("@error_message:survey_swimming");
		return;
	}

	if (surveyer->isRidingMount()) {
		if(surveyer->isInWater()) {
			surveyer->sendSystemMessage("@error_message:survey_cant");
			return;
		}
	} else {
		if(surveyer->getPosture() != CreaturePosture::UPRIGHT) {
			surveyer->sendSystemMessage("@error_message:survey_standing");
			return;
		}
	}

	//Get actual cost based upon player's Focus
	int mindCost = surveyer->calculateCostAdjustment(CreatureAttribute::FOCUS, 100);

	if (surveyer->getHAM(CreatureAttribute::MIND) < mindCost) {
		surveyer->setPosture(CreaturePosture::UPRIGHT, true);
		surveyer->sendSystemMessage("@error_message:survey_mind"); //You are exhausted. You nee to clear your head before you can survey again.
		return;
	}

	ManagedReference<ResourceSpawn*> spawn = resourceManager->getResourceSpawn(resname);
	if(spawn == NULL) {
		return;
	}

	if(spawn->getSurveyToolType() != activeSurveyTool->getToolType()) {
		StringIdChatParameter message("@survey:wrong_tool"); // %TO resources cannot be located with this tool
		message.setTO(spawn->getFinalClass());
		surveyer->sendSystemMessage(message);
		return;
	}

	PlayClientEffectLoc* effect = new PlayClientEffectLoc(activeSurveyTool->getSurveyAnimation(),
			surveyer->getZone()->getZoneName(),
			surveyer->getPositionX(), surveyer->getPositionZ(),
			surveyer->getPositionY());

	surveyer->broadcastMessage(effect, true);

	resourceManager->sendSurvey(surveyer, resname);
}

void SurveySessionImplementation::startSample(const String& resname) {

	ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();
	ManagedReference<ResourceManager*> resourceManager = this->resourceManager.get();
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();
	ManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get();

	if (activeSurveyTool == NULL) {
		error("surveyTool is NULL");
		return;
	}

	if (resourceManager == NULL) {
		info("ResourceManager is NULL");
		return;
	}

	if (surveyer == NULL) {
		info("surveyer is NULL");
		return;
	}

	if (!resname.isEmpty())
		 lastResourceSampleName = resname;

	ManagedReference<ResourceSpawn* > resourceSpawn = resourceManager->getResourceSpawn(lastResourceSampleName);
	if (resourceSpawn == NULL) {
		return;
	}

	if (surveyer->isInCombat()) {
		surveyer->sendSystemMessage("@survey:sample_cancel_attack"); //You can't take samples while under attack!
		return;
	}

	if (surveyer->getParent() != NULL && surveyer->getParent().get()->isCellObject()) {
		surveyer->sendSystemMessage("@error_message:survey_in_structure"); //You cannot perform survey-related actions inside a structure.
		return;
	}

	if (surveyer->isSwimming()) {
		surveyer->sendSystemMessage("@error_message:survey_swimming");
		return;
	}

	if (surveyer->getParent() != NULL && surveyer->getParent().get()->isVehicleObject() ) {
		surveyer->sendSystemMessage("You cannot perform that action while driving a vehicle.");
		return;
	}

	//Get actual cost based upon player's Quickness
	int actionCost = surveyer->calculateCostAdjustment(CreatureAttribute::QUICKNESS, 200);

	if (surveyer->getHAM(CreatureAttribute::ACTION) < actionCost) {
		surveyer->setPosture(CreaturePosture::UPRIGHT, true);
		surveyer->sendSystemMessage("@error_message:sample_mind"); //You are exhausted. You nee to clear your head before you can sample again.
		return;
	}

	if(resourceSpawn->getSurveyToolType() != activeSurveyTool->getToolType()) {
		StringIdChatParameter message("@survey:wrong_tool"); // %TO resources cannot be located with this tool
		message.setTO(resourceSpawn->getFinalClass());
		surveyer->sendSystemMessage(message);
		return;
	}

	if(!lastResourceSampleName.isEmpty() && !activeSurveyTool->canSampleRadioactive()) {

		if(resourceSpawn->isType("radioactive") && !activeSurveyTool->canSampleRadioactive()) {
			activeSurveyTool->sendRadioactiveWarning(surveyer);
			return;
		}
	}

	// Player must be kneeling to sample (if unmounted)
	if (!surveyer->isKneeling() && !surveyer->isRidingMount() ) {
		surveyer->setPosture(CreaturePosture::CROUCHED, true);
	}

	if(surveyer->getPendingTask("sample") != NULL) {
		return;
	}

	StringIdChatParameter message("survey","start_sampling");
	message.setTO(lastResourceSampleName);
	surveyer->sendSystemMessage(message);

	if (!doGamble && richSampleLocation == NULL && System::random(50) == 7) {

		if (surveyerGhost->hasSuiBoxWindowType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME)) {
			surveyerGhost->removeSuiBoxType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME);
		}

		if (surveyerGhost->hasSuiBoxWindowType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2)) {
			surveyerGhost->removeSuiBoxType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2);
		}

		if(System::random(1) == 1)
			surveyCnodeMinigameSui();
		else
			surveyGnodeMinigameSui();

	} else {

		if (!lastResourceSampleName.isEmpty())
			resourceManager->sendSample(surveyer, lastResourceSampleName,
					activeSurveyTool->getSampleAnimation());
	}
}

void SurveySessionImplementation::surveyCnodeMinigameSui() {
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();

	//int surveyMod = surveyer->getSkillMod("surveying");

	ManagedReference<SuiListBox*> suiConcMinigameBox = new SuiListBox(
			surveyer, SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME, 0);

	suiConcMinigameBox->setPromptTitle("@survey:cnode_t");
	suiConcMinigameBox->setPromptText("@survey:cnode_d");

	suiConcMinigameBox->addMenuItem("@survey:cnode_1", 0);
	suiConcMinigameBox->addMenuItem("@survey:cnode_2", 1);

	suiConcMinigameBox->setCancelButton(true, "Cancel");

	suiConcMinigameBox->setCallback(new SurveyCMinigameSuiCallback(surveyer->getZoneServer()));
	surveyer->getPlayerObject()->addSuiBox(suiConcMinigameBox);
	surveyer->sendMessage(suiConcMinigameBox->generateMessage());
}

void SurveySessionImplementation::surveyCnodeMinigame(int value) {
	ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();
	ManagedReference<ResourceManager*> resourceManager = this->resourceManager.get();
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();
	ManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get();

	if(value == 0) {
		// Add sampletask
		rescheduleSample();

		return;
	}

	richSampleLocation = new Coordinate(surveyer->getPositionX(), surveyer->getPositionZ(), surveyer->getPositionY());
	richSampleLocation->randomizePosition(50);

	ManagedReference<WaypointObject*> newwaypoint = NULL;

	PlayerObject* ghost = surveyer->getPlayerObject();

	// Get previous survey waypoint
	ManagedReference<WaypointObject*> waypoint = ghost->getSurveyWaypoint();

	// Create new waypoint
	if (waypoint == NULL)
		newwaypoint = ( surveyer->getZoneServer()->createObject(0xc456e788, 1)).castTo<WaypointObject*>();
	else {
		ghost->removeWaypoint(waypoint->getObjectID(), true);
		newwaypoint = waypoint.get();
	}

	// Update new waypoint
	newwaypoint->setCustomObjectName(UnicodeString("Resource Survey"), false);
	newwaypoint->setPlanetCRC(surveyer->getZone()->getZoneCRC());
	newwaypoint->setPosition(richSampleLocation->getPositionX(), 0, richSampleLocation->getPositionY());
	newwaypoint->setColor(WaypointObject::COLOR_BLUE);
	newwaypoint->setSpecialTypeID(WaypointObject::SPECIALTYPE_RESOURCE);
	newwaypoint->setActive(true);

	ghost->addWaypoint(newwaypoint, false, true); // Should second argument be true, and waypoints with the same name thus remove their old version?
	surveyer->sendSystemMessage("@survey:node_waypoint");

	// Player must be kneeling to sample
	if (!surveyer->isStanding() && !surveyer->isRidingMount() )
		surveyer->setPosture(CreaturePosture::UPRIGHT, true);
}

void SurveySessionImplementation::surveyGnodeMinigameSui() {
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();

	//int surveyMod = surveyer->getSkillMod("surveying");

	ManagedReference<SuiListBox*> suiConcMinigameBox = new SuiListBox(surveyer, SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2, 0);

	suiConcMinigameBox->setPromptTitle("@survey:gnode_t");
	suiConcMinigameBox->setPromptText("@survey:gnode_d");

	suiConcMinigameBox->addMenuItem("@survey:gnode_1", 0);
	suiConcMinigameBox->addMenuItem("@survey:gnode_2", 1);

	suiConcMinigameBox->setCancelButton(true, "Cancel");

	suiConcMinigameBox->setCallback(new SurveyGMinigameSuiCallback(surveyer->getZoneServer()));
	surveyer->getPlayerObject()->addSuiBox(suiConcMinigameBox);
	surveyer->sendMessage(suiConcMinigameBox->generateMessage());
}

void SurveySessionImplementation::surveyGnodeMinigame(int value) {
	ManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();
	ManagedReference<CreatureObject*> surveyer = this->surveyer.get();

	if(value == 1) {

		if(surveyer->getHAM(CreatureAttribute::ACTION) < 300) {
			surveyer->sendSystemMessage("@survey:gamble_no_action");
			return;
		}

		surveyer->inflictDamage(surveyer, CreatureAttribute::ACTION, 300, false, true);
		doGamble = true;
	}

	rescheduleSample();
}

void SurveySessionImplementation::rescheduleSurvey(SurveyMessage* surveyMessage, WaypointObject* waypoint, float maxDensity, ResourceSpawn* resourceSpawn) {
	surveyTask = new SurveyTask(surveyer, surveyMessage, waypoint, maxDensity * 100, resourceSpawn);
	surveyer.get()->addPendingTask("survey", surveyTask, 3000);
}

void SurveySessionImplementation::rescheduleSample() {
	// Add sampletask
	if(sampleTask == NULL)
		sampleTask = new SampleTask(surveyer.get(), activeSurveyTool.get());

	if(surveyer.get()->getPendingTask("sample") == NULL)
		surveyer.get()->addPendingTask("sample", sampleTask, 25000);
}

void SurveySessionImplementation::rescheduleSampleResults(ResourceSpawner* resourceSpawner, float density, const String& resname) {
	// Add sampleresultstask
	if(surveyer.get()->getPendingTask("sampleresults") == NULL) {
		sampleResultsTask = new SampleResultsTask(surveyer, resourceSpawner, density, resname);
		surveyer.get()->addPendingTask("sampleresults", sampleResultsTask, 3000);
	}
}

<|endoftext|>