<commit_before>#include <queue>
#include <vector>
using namespace std;
struct Node {
    int point; //點
    int dis; // 距離源點的距離
    Node(int _point = 0, int _dis = 0)
    {
        point = _point, dis = _dis;
    }
    bool operator<(const Node& e) const
    {
        return dis > e.dis; // for the priority queue 定義小於 且顛倒 讓priority queue 由 小到大
    }
};
struct Edge {
    int v;
    int cost;
    Edge(int _v = 0, int _cost = 0)
    {
        v = _v, cost = _cost;
    }
};
int dis[10000];
vector<Edge> e[10000];
void init(int n) // initialize
{
    for (int i = 0; i < n; i++) {
        dis[n] = 1e9;
        e[i].clear();
    }
}
void Dijkstra(int s) // 起點
{

    priority_queue<Node> pq;
    pq.push(Node(s, 0));
    dis[s] = 0;
    while (!pq.empty()) {
        Node top = pq.top();
        pq.pop();
        int u = top.point;
        int val = top.dis;
        if (val != dis[u])
            continue; // 加速
        for (int i = 0; i < e[u].size(); i++) {
            int v = e[u][i].v;
            int cost = e[u][i].cost;
            if (dis[u] + cost < dis[v]) {
                dis[v] = dis[u] + cost;
                pq.push(Node(v, dis[v]));
            }
        }
    }
}
<commit_msg>debug<commit_after>#include <queue>
#include <vector>
using namespace std;
struct Node {
    int point; //點
    int dis; // 距離源點的距離
    Node(int _point = 0, int _dis = 0)
    {
        point = _point, dis = _dis;
    }
    bool operator<(const Node& e) const
    {
        return dis > e.dis; // for the priority queue 定義小於 且顛倒 讓priority queue 由 小到大
    }
};
struct Edge {
    int v;
    int cost;
    Edge(int _v = 0, int _cost = 0)
    {
        v = _v, cost = _cost;
    }
};
int dis[10000];
vector<Edge> e[10000];
void init(int n) // initialize
{
    for (int i = 0; i < n; i++) {
        dis[i] = 1e9;
        e[i].clear();
    }
}
void Dijkstra(int s) // 起點
{

    priority_queue<Node> pq;
    pq.push(Node(s, 0));
    dis[s] = 0;
    while (!pq.empty()) {
        Node top = pq.top();
        pq.pop();
        int u = top.point;
        int val = top.dis;
        if (val != dis[u])
            continue; // 加速
        for (int i = 0; i < e[u].size(); i++) {
            int v = e[u][i].v;
            int cost = e[u][i].cost;
            if (dis[u] + cost < dis[v]) {
                dis[v] = dis[u] + cost;
                pq.push(Node(v, dis[v]));
            }
        }
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 J-P Nurmi
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
*/

#include "statusbar_p.h"

#include <QtAndroid>

// WindowManager.LayoutParams
#define FLAG_TRANSLUCENT_STATUS 0x04000000
#define FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 0x80000000
// View
#define SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 0x00002000

static QAndroidJniObject getAndroidWindow()
{
    QAndroidJniObject window = QtAndroid::androidActivity().callObjectMethod("getWindow", "()Landroid/view/Window;");
    window.callMethod<void>("addFlags", "(I)V", FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.callMethod<void>("clearFlags", "(I)V", FLAG_TRANSLUCENT_STATUS);
    return window;
}

bool StatusBarPrivate::isAvailable_sys()
{
    return QtAndroid::androidSdkVersion() >= 21;
}

void StatusBarPrivate::setColor_sys(const QColor &color)
{
    if (QtAndroid::androidSdkVersion() < 21)
        return;

    QtAndroid::runOnAndroidThread([=]() {
        QAndroidJniObject window = getAndroidWindow();
        window.callMethod<void>("setStatusBarColor", "(I)V", color.rgba());
    });
}

void StatusBarPrivate::setTheme_sys(StatusBar::Theme theme)
{
    if (QtAndroid::androidSdkVersion() < 23)
        return;

    QtAndroid::runOnAndroidThread([=]() {
        QAndroidJniObject window = getAndroidWindow();
        QAndroidJniObject view = window.callObjectMethod("getDecorView", "()Landroid/view/View;");
        int visibility = view.callMethod<int>("getSystemUiVisibility", "()I");
        if (theme == Light)
            visibility |= SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        else
            visibility &= ~SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        view.callMethod<void>("setSystemUiVisibility", "(I)V", visibility);
    });
}
<commit_msg>Fix Compilation, due to the Theme Enum not getting recognized<commit_after>/*
 * Copyright (c) 2016 J-P Nurmi
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
*/

#include "statusbar_p.h"

#include <QtAndroid>

// WindowManager.LayoutParams
#define FLAG_TRANSLUCENT_STATUS 0x04000000
#define FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 0x80000000
// View
#define SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 0x00002000

static QAndroidJniObject getAndroidWindow()
{
    QAndroidJniObject window = QtAndroid::androidActivity().callObjectMethod("getWindow", "()Landroid/view/Window;");
    window.callMethod<void>("addFlags", "(I)V", FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.callMethod<void>("clearFlags", "(I)V", FLAG_TRANSLUCENT_STATUS);
    return window;
}

bool StatusBarPrivate::isAvailable_sys()
{
    return QtAndroid::androidSdkVersion() >= 21;
}

void StatusBarPrivate::setColor_sys(const QColor &color)
{
    if (QtAndroid::androidSdkVersion() < 21)
        return;

    QtAndroid::runOnAndroidThread([=]() {
        QAndroidJniObject window = getAndroidWindow();
        window.callMethod<void>("setStatusBarColor", "(I)V", color.rgba());
    });
}

void StatusBarPrivate::setTheme_sys(StatusBar::Theme theme)
{
    if (QtAndroid::androidSdkVersion() < 23)
        return;

    QtAndroid::runOnAndroidThread([=]() {
        QAndroidJniObject window = getAndroidWindow();
        QAndroidJniObject view = window.callObjectMethod("getDecorView", "()Landroid/view/View;");
        int visibility = view.callMethod<int>("getSystemUiVisibility", "()I");
        if (theme == StatusBar::Theme::Light)
            visibility |= SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        else
            visibility &= ~SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        view.callMethod<void>("setSystemUiVisibility", "(I)V", visibility);
    });
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013-2016 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
 *
 * This file is part of vanillacoin.
 *
 * vanillacoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef COIN_DB_ENV_HPP
#define COIN_DB_ENV_HPP

#include <db_cxx.h>

#include <cstdint>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

#include <coin/filesystem.hpp>

namespace coin {

    /**
     * Implements a berkley database DbEnv object wrapper.
     */
    class db_env
    {
        public:

            /**
             * The default cache size.
             */
            enum { default_cache_size = 128 };

            /**
             * Constructor
             */
            db_env();

            /**
             * Destructor
             */
            ~db_env();

            /**
             * Opens the database environment.
             * @param cache_size The cache size.
             */
            bool open(
                const std::uint32_t & cache_size = default_cache_size
            );

            /**
             * Closes the DbEnv object.
             */
            void close_DbEnv();

            /**
             * Closes a Db object.
             * @param file_name The file name.
             */
            void close_Db(const std::string & file_name);

            /**
             * Removes a Db object.
             * @param file_name The file name.
             */
            bool remove_Db(const std::string & file_name);

            /**
             * Verifies that the database file is OK.
             * @param file_name The file name.
             */
            bool verify(const std::string & file_name);

            /**
             * Attempts to salvage data from a file.
             * @param file_name The file name.
             * @param aggressive If true the DB_AGGRESSIVE will be used.
             * @param result The result.
             */
            bool salvage(
                const std::string & file_name, const bool & aggressive,
                std::vector< std::pair< std::vector<std::uint8_t>,
                std::vector<std::uint8_t> > > & result
            );

            /**
             * checkpoint_lsn
             * @param file_name The file name.
             */
            void checkpoint_lsn(const std::string & file_name);

            /**
             * Flushes.
             */
            void flush();

            /**
             * The DbEnv.
             */
            DbEnv & get_DbEnv();

            /**
             * The file use counts.
             */
            std::map<std::string, std::uint32_t> & file_use_counts();

            /**
             * The Db objects.
             */
            std::map<std::string, Db *> & Dbs();

            /**
             * The std::mutex.
             */
            std::recursive_mutex & mutex_DbEnv();

            /**
             * txn_begin
             * @param flags The flags.
             */
            DbTxn * txn_begin(int flags = DB_TXN_WRITE_NOSYNC);

        private:

            /**
             * The DbEnv.
             */
            DbEnv m_DbEnv;

            /**
             * The file use counts.
             */
            std::map<std::string, std::uint32_t> m_file_use_counts;

            /**
             * The Db objects.
             */
            std::map<std::string, Db *> m_Dbs;

            /**
             * The m_DbEnv std::recursive_mutex.
             */
            std::recursive_mutex m_mutex_DbEnv;

        protected:

            /**
             * The state.
             */
            enum
            {
                state_opened,
                state_closed,
            } state_;

            /**
             * m_file_use_counts std::recursive_mutex.
             */
            std::recursive_mutex mutex_file_use_counts_;

            /**
             * m_Dbs std::recursive_mutex.
             */
            std::recursive_mutex mutex_m_Dbs_;
    };

} // namespace coin

#endif // COIN_DB_ENV_HPP
<commit_msg>0.4.5 RC2 partial merge (database mempool cache size reduction)<commit_after>/*
 * Copyright (c) 2013-2016 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
 *
 * This file is part of vanillacoin.
 *
 * vanillacoin is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef COIN_DB_ENV_HPP
#define COIN_DB_ENV_HPP

#include <db_cxx.h>

#include <cstdint>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

#include <coin/filesystem.hpp>

namespace coin {

    /**
     * Implements a berkley database DbEnv object wrapper.
     */
    class db_env
    {
        public:

            /**
             * The default cache size.
             */
            enum { default_cache_size = 100 };

            /**
             * Constructor
             */
            db_env();

            /**
             * Destructor
             */
            ~db_env();

            /**
             * Opens the database environment.
             * @param cache_size The cache size.
             */
            bool open(
                const std::uint32_t & cache_size = default_cache_size
            );

            /**
             * Closes the DbEnv object.
             */
            void close_DbEnv();

            /**
             * Closes a Db object.
             * @param file_name The file name.
             */
            void close_Db(const std::string & file_name);

            /**
             * Removes a Db object.
             * @param file_name The file name.
             */
            bool remove_Db(const std::string & file_name);

            /**
             * Verifies that the database file is OK.
             * @param file_name The file name.
             */
            bool verify(const std::string & file_name);

            /**
             * Attempts to salvage data from a file.
             * @param file_name The file name.
             * @param aggressive If true the DB_AGGRESSIVE will be used.
             * @param result The result.
             */
            bool salvage(
                const std::string & file_name, const bool & aggressive,
                std::vector< std::pair< std::vector<std::uint8_t>,
                std::vector<std::uint8_t> > > & result
            );

            /**
             * checkpoint_lsn
             * @param file_name The file name.
             */
            void checkpoint_lsn(const std::string & file_name);

            /**
             * Flushes.
             */
            void flush();

            /**
             * The DbEnv.
             */
            DbEnv & get_DbEnv();

            /**
             * The file use counts.
             */
            std::map<std::string, std::uint32_t> & file_use_counts();

            /**
             * The Db objects.
             */
            std::map<std::string, Db *> & Dbs();

            /**
             * The std::mutex.
             */
            std::recursive_mutex & mutex_DbEnv();

            /**
             * txn_begin
             * @param flags The flags.
             */
            DbTxn * txn_begin(int flags = DB_TXN_WRITE_NOSYNC);

        private:

            /**
             * The DbEnv.
             */
            DbEnv m_DbEnv;

            /**
             * The file use counts.
             */
            std::map<std::string, std::uint32_t> m_file_use_counts;

            /**
             * The Db objects.
             */
            std::map<std::string, Db *> m_Dbs;

            /**
             * The m_DbEnv std::recursive_mutex.
             */
            std::recursive_mutex m_mutex_DbEnv;

        protected:

            /**
             * The state.
             */
            enum
            {
                state_opened,
                state_closed,
            } state_;

            /**
             * m_file_use_counts std::recursive_mutex.
             */
            std::recursive_mutex mutex_file_use_counts_;

            /**
             * m_Dbs std::recursive_mutex.
             */
            std::recursive_mutex mutex_m_Dbs_;
    };

} // namespace coin

#endif // COIN_DB_ENV_HPP
<|endoftext|>


<commit_before>#pragma once
/**
	@file
	@brief tiny time class

	Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved.
*/
#include <ctime>
#include <cybozu/exception.hpp>
#include <cybozu/atoi.hpp>
#include <cybozu/itoa.hpp>
#ifdef _WIN32
	#include <sys/timeb.h>
#else
	#include <sys/time.h>
#endif

namespace cybozu {

/**
	time struct with time_t and msec
	@note time MUST be latesr than 1970/1/1
*/
class Time {
	static const uint64_t epochBias = 116444736000000000ull;
	std::time_t time_;
	int msec_;
public:
	Time() {}
	explicit Time(std::time_t time, int msec = 0)
		: time_(time)
		, msec_(msec)
	{
	}
	explicit Time(bool doSet)
	{
		if (doSet) setCurrentTime();
	}
	Time& setTime(std::time_t time, int msec = 0)
	{
		time_ = time;
		msec_ = msec;
		return *this;
	}
	/*
		Windows FILETIME is defined as
		struct FILETILME {
			DWORD dwLowDateTime;
			DWORD dwHighDateTime;
		};
		the value represents the number of 100-nanosecond intervals since January 1, 1601 (UTC).
	*/
	void setByFILETIME(uint32_t low, uint32_t high)
	{
		const uint64_t fileTime = (((uint64_t(high) << 32) | low) - epochBias) / 10000;
		time_ = fileTime / 1000;
		msec_ = fileTime % 1000;
	}
	/*
		DWORD is defined as unsigned long in windows
	*/
	template<class dword>
	void getFILETIME(dword& low, dword& high) const
	{
		const uint64_t fileTime = (time_ * 1000 + msec_) * 10000 + epochBias;
		low = dword(fileTime);
		high = dword(fileTime >> 32);
	}
	explicit Time(const std::string& in)
	{
		fromString(in);
	}
	explicit Time(const char *in)
	{
		fromString(in, in + strlen(in));
	}
	const std::time_t& getTime() const { return time_; }
	int getMsec() const { return msec_; }
	double getTimeSec() const { return time_ + msec_ * 1e-3; }
	void addSec(int sec) { time_ += sec; }
	bool operator<(const Time& rhs) const { return (time_ < rhs.time_) || (time_ == rhs.time_ && msec_ < rhs.msec_); }
//	bool operator<=(const Time& rhs) const { return (*this < rhs) || (*this == rhs); }
//	bool operator>(const Time& rhs) const { return rhs < *this; }
	bool operator==(const Time& rhs) const { return (time_ == rhs.time_) && (msec_ == rhs.msec_); }
	bool operator!=(const Time& rhs) const { return !(*this == rhs); }
	/**
		set time from string such as
		2009-Jan-23T02:53:44Z
		2009-Jan-23T02:53:44.078Z
		2009-01-23T02:53:44Z
		2009-01-23T02:53:44.078Z
		@note 'T' may be ' '. '-' may be '/'. last char 'Z' is omissible
	*/
	void fromString(const std::string& in) { fromString(&in[0], &in[0] + in.size()); }

	void fromString(const char *begin, const char *end)
	{
		const size_t len = end - begin;
		if (len >= 19) {
			const char *p = begin;
			struct tm tm;
			int num;
			bool b;
			tm.tm_year = getNum(&b, p, 4, 1970, 3000) - 1900;
			if (!b) goto ERR;
			p += 4;
			char sep = *p++;
			if (sep != '-' && sep != '/') goto ERR;

			p = getMonth(&num, p);
			if (p == 0) goto ERR;
			tm.tm_mon = num;
			if (*p++ != sep) goto ERR;

			tm.tm_mday = getNum(&b, p, 2, 1, 31);
			if (!b) goto ERR;
			p += 2;
			if (*p != ' ' && *p != 'T') goto ERR;
			p++;

			tm.tm_hour = getNum(&b, p, 2, 0, 23);
			if (!b) goto ERR;
			p += 2;
			if (*p++ != ':') goto ERR;

			tm.tm_min = getNum(&b, p, 2, 0, 59);
			if (!b) goto ERR;
			p += 2;
			if (*p++ != ':') goto ERR;

			tm.tm_sec = getNum(&b, p, 2, 0, 59);
			if (!b) goto ERR;
			p += 2;

			if (p == end) {
				msec_ = 0;
			} else if (p + 1 == end && *p == 'Z') {
				msec_ = 0;
				p++;
			} else if (*p == '.' && (p + 4 == end || (p + 5 == end && *(p + 4) == 'Z'))) {
				msec_ = getNum(&b, p + 1, 3, 0, 999);
				if (!b) goto ERR;
				p += 4;
			} else {
				goto ERR;
			}
#ifdef _WIN32
			time_ = _mkgmtime64(&tm);
			if (time_ == -1) goto ERR;
#else
			time_ = timegm(&tm);
#endif
			return;
		}
	ERR:
		throw cybozu::Exception("time::fromString") << std::string(begin, 24);
	}

	/**
		get current time with format
		@param out [out] output string
		@param format [in] foramt for strftime and append three digits for msec
		@param appendMsec [in] appemd <mmm>
		@param doClear (append to out if false)
		@note ex. "%Y-%b-%d %H:%M:%S." to get 2009-Jan-23 02:53:44.078
	*/
	void toString(std::string& out, const char *format, bool appendMsec = true, bool doClear = true) const
	{
		if (doClear) out.clear();
		char buf[128];
		struct tm tm;
#ifdef _WIN32
		bool isOK = _gmtime64_s(&tm, &time_) == 0;
#else
		bool isOK = gmtime_r(&time_, &tm) != 0;
#endif
		if (!isOK) throw cybozu::Exception("time::toString") << time_;
		if (std::strftime(buf, sizeof(buf), format, &tm) == 0) {
			throw cybozu::Exception("time::toString::too long") << format << time_;
		}
		out += buf;
		if (appendMsec) {
			out += cybozu::itoaWithZero(msec_, 3);
		}
	}

	/**
		get current time such as 2009-01-23 02:53:44.078
		@param out [out] sink string
	*/
	void toString(std::string& out, bool appendMsec = true, bool doClear = true) const
	{
		const char *format = appendMsec ? "%Y-%m-%d %H:%M:%S." : "%Y-%m-%d %H:%M:%S";
		toString(out, format, appendMsec, doClear);
	}
	std::string toString() const { std::string out; toString(out); return out; }
	/**
		get current time
	*/
	Time& setCurrentTime()
	{
#ifdef _WIN32
		struct _timeb timeb;
		_ftime_s(&timeb);
		time_ = timeb.time;
		msec_ = timeb.millitm;
#else
		struct timeval tv;
		gettimeofday(&tv, 0);
		time_ = tv.tv_sec;
		msec_ = tv.tv_usec / 1000;
#endif
		return *this;
	}
private:

	int getNum(bool *b, const char *in, size_t len, int min, int max) const
	{
		int ret = cybozu::atoi(b, in, len);
		if (min <= ret && ret <= max) {
			return ret;
		} else {
			*b = false;
			return 0;
		}
	}

	/*
		convert month-str to [0, 11]
		@param ret [out] return idx
		@param p [in] month-str
		@retval next pointer or null
	*/
	const char *getMonth(int *ret, const char *p) const
	{
		static const char monthTbl[12][4] = {
			"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
		};

		for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(monthTbl); i++) {
			if (memcmp(p, monthTbl[i], 3) == 0) {
				*ret = (int)i;
				return p + 3;
			}
		}
		bool b;
		*ret = getNum(&b, p, 2, 1, 12) - 1;
		if (b) {
			return p + 2;
		} else {
			return 0;
		}
	}
};

inline std::ostream& operator<<(std::ostream& os, const cybozu::Time& time)
{
	return os << time.toString();
}

inline double GetCurrentTimeSec()
{
	return cybozu::Time(true).getTimeSec();
}

} // cybozu
<commit_msg>add appendMsec option to toString<commit_after>#pragma once
/**
	@file
	@brief tiny time class

	Copyright (C) 2008 Cybozu Labs, Inc., all rights reserved.
*/
#include <ctime>
#include <cybozu/exception.hpp>
#include <cybozu/atoi.hpp>
#include <cybozu/itoa.hpp>
#ifdef _WIN32
	#include <sys/timeb.h>
#else
	#include <sys/time.h>
#endif

namespace cybozu {

/**
	time struct with time_t and msec
	@note time MUST be latesr than 1970/1/1
*/
class Time {
	static const uint64_t epochBias = 116444736000000000ull;
	std::time_t time_;
	int msec_;
public:
	Time() {}
	explicit Time(std::time_t time, int msec = 0)
		: time_(time)
		, msec_(msec)
	{
	}
	explicit Time(bool doSet)
	{
		if (doSet) setCurrentTime();
	}
	Time& setTime(std::time_t time, int msec = 0)
	{
		time_ = time;
		msec_ = msec;
		return *this;
	}
	/*
		Windows FILETIME is defined as
		struct FILETILME {
			DWORD dwLowDateTime;
			DWORD dwHighDateTime;
		};
		the value represents the number of 100-nanosecond intervals since January 1, 1601 (UTC).
	*/
	void setByFILETIME(uint32_t low, uint32_t high)
	{
		const uint64_t fileTime = (((uint64_t(high) << 32) | low) - epochBias) / 10000;
		time_ = fileTime / 1000;
		msec_ = fileTime % 1000;
	}
	/*
		DWORD is defined as unsigned long in windows
	*/
	template<class dword>
	void getFILETIME(dword& low, dword& high) const
	{
		const uint64_t fileTime = (time_ * 1000 + msec_) * 10000 + epochBias;
		low = dword(fileTime);
		high = dword(fileTime >> 32);
	}
	explicit Time(const std::string& in)
	{
		fromString(in);
	}
	explicit Time(const char *in)
	{
		fromString(in, in + strlen(in));
	}
	const std::time_t& getTime() const { return time_; }
	int getMsec() const { return msec_; }
	double getTimeSec() const { return time_ + msec_ * 1e-3; }
	void addSec(int sec) { time_ += sec; }
	bool operator<(const Time& rhs) const { return (time_ < rhs.time_) || (time_ == rhs.time_ && msec_ < rhs.msec_); }
//	bool operator<=(const Time& rhs) const { return (*this < rhs) || (*this == rhs); }
//	bool operator>(const Time& rhs) const { return rhs < *this; }
	bool operator==(const Time& rhs) const { return (time_ == rhs.time_) && (msec_ == rhs.msec_); }
	bool operator!=(const Time& rhs) const { return !(*this == rhs); }
	/**
		set time from string such as
		2009-Jan-23T02:53:44Z
		2009-Jan-23T02:53:44.078Z
		2009-01-23T02:53:44Z
		2009-01-23T02:53:44.078Z
		@note 'T' may be ' '. '-' may be '/'. last char 'Z' is omissible
	*/
	void fromString(const std::string& in) { fromString(&in[0], &in[0] + in.size()); }

	void fromString(const char *begin, const char *end)
	{
		const size_t len = end - begin;
		if (len >= 19) {
			const char *p = begin;
			struct tm tm;
			int num;
			bool b;
			tm.tm_year = getNum(&b, p, 4, 1970, 3000) - 1900;
			if (!b) goto ERR;
			p += 4;
			char sep = *p++;
			if (sep != '-' && sep != '/') goto ERR;

			p = getMonth(&num, p);
			if (p == 0) goto ERR;
			tm.tm_mon = num;
			if (*p++ != sep) goto ERR;

			tm.tm_mday = getNum(&b, p, 2, 1, 31);
			if (!b) goto ERR;
			p += 2;
			if (*p != ' ' && *p != 'T') goto ERR;
			p++;

			tm.tm_hour = getNum(&b, p, 2, 0, 23);
			if (!b) goto ERR;
			p += 2;
			if (*p++ != ':') goto ERR;

			tm.tm_min = getNum(&b, p, 2, 0, 59);
			if (!b) goto ERR;
			p += 2;
			if (*p++ != ':') goto ERR;

			tm.tm_sec = getNum(&b, p, 2, 0, 59);
			if (!b) goto ERR;
			p += 2;

			if (p == end) {
				msec_ = 0;
			} else if (p + 1 == end && *p == 'Z') {
				msec_ = 0;
				p++;
			} else if (*p == '.' && (p + 4 == end || (p + 5 == end && *(p + 4) == 'Z'))) {
				msec_ = getNum(&b, p + 1, 3, 0, 999);
				if (!b) goto ERR;
				p += 4;
			} else {
				goto ERR;
			}
#ifdef _WIN32
			time_ = _mkgmtime64(&tm);
			if (time_ == -1) goto ERR;
#else
			time_ = timegm(&tm);
#endif
			return;
		}
	ERR:
		throw cybozu::Exception("time::fromString") << std::string(begin, 24);
	}

	/**
		get current time with format
		@param out [out] output string
		@param format [in] foramt for strftime and append three digits for msec
		@param appendMsec [in] appemd <mmm>
		@param doClear (append to out if false)
		@note ex. "%Y-%b-%d %H:%M:%S." to get 2009-Jan-23 02:53:44.078
	*/
	void toString(std::string& out, const char *format, bool appendMsec = true, bool doClear = true) const
	{
		if (doClear) out.clear();
		char buf[128];
		struct tm tm;
#ifdef _WIN32
		bool isOK = _gmtime64_s(&tm, &time_) == 0;
#else
		bool isOK = gmtime_r(&time_, &tm) != 0;
#endif
		if (!isOK) throw cybozu::Exception("time::toString") << time_;
		if (std::strftime(buf, sizeof(buf), format, &tm) == 0) {
			throw cybozu::Exception("time::toString::too long") << format << time_;
		}
		out += buf;
		if (appendMsec) {
			out += cybozu::itoaWithZero(msec_, 3);
		}
	}

	/**
		get current time such as 2009-01-23 02:53:44.078
		@param out [out] sink string
	*/
	void toString(std::string& out, bool appendMsec = true, bool doClear = true) const
	{
		const char *format = appendMsec ? "%Y-%m-%d %H:%M:%S." : "%Y-%m-%d %H:%M:%S";
		toString(out, format, appendMsec, doClear);
	}
	std::string toString(bool appendMsec = true) const { std::string out; toString(out, appendMsec); return out; }
	/**
		get current time
	*/
	Time& setCurrentTime()
	{
#ifdef _WIN32
		struct _timeb timeb;
		_ftime_s(&timeb);
		time_ = timeb.time;
		msec_ = timeb.millitm;
#else
		struct timeval tv;
		gettimeofday(&tv, 0);
		time_ = tv.tv_sec;
		msec_ = tv.tv_usec / 1000;
#endif
		return *this;
	}
private:

	int getNum(bool *b, const char *in, size_t len, int min, int max) const
	{
		int ret = cybozu::atoi(b, in, len);
		if (min <= ret && ret <= max) {
			return ret;
		} else {
			*b = false;
			return 0;
		}
	}

	/*
		convert month-str to [0, 11]
		@param ret [out] return idx
		@param p [in] month-str
		@retval next pointer or null
	*/
	const char *getMonth(int *ret, const char *p) const
	{
		static const char monthTbl[12][4] = {
			"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
		};

		for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(monthTbl); i++) {
			if (memcmp(p, monthTbl[i], 3) == 0) {
				*ret = (int)i;
				return p + 3;
			}
		}
		bool b;
		*ret = getNum(&b, p, 2, 1, 12) - 1;
		if (b) {
			return p + 2;
		} else {
			return 0;
		}
	}
};

inline std::ostream& operator<<(std::ostream& os, const cybozu::Time& time)
{
	return os << time.toString();
}

inline double GetCurrentTimeSec()
{
	return cybozu::Time(true).getTimeSec();
}

} // cybozu
<|endoftext|>


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

#include "mesh_resource_marker.h"

#include "marker_selection_handler.h"
#include "rviz/default_plugin/marker_display.h"
#include "rviz/selection/selection_manager.h"

#include "rviz/display_context.h"
#include "rviz/mesh_loader.h"
#include "marker_display.h"

#include <OgreSceneNode.h>
#include <OgreSceneManager.h>
#include <OgreEntity.h>
#include <OgreSubEntity.h>
#include <OgreMaterialManager.h>
#include <OgreTextureManager.h>
#include <OgreSharedPtr.h>
#include <OgreTechnique.h>

namespace rviz
{

MeshResourceMarker::MeshResourceMarker(MarkerDisplay* owner, DisplayContext* context, Ogre::SceneNode* parent_node)
: MarkerBase(owner, context, parent_node)
, entity_(0)
{
}

MeshResourceMarker::~MeshResourceMarker()
{
  reset();
}

void MeshResourceMarker::reset()
{
  //destroy entity
  if (entity_)
  {
    context_->getSceneManager()->destroyEntity(entity_);
    entity_ = 0;
  }

  // destroy all the materials we've created
  S_MaterialPtr::iterator it;
  for (it = materials_.begin(); it != materials_.end(); it++)
  {
    Ogre::MaterialPtr material = *it;
    if (!material.isNull())
    {
      material->unload();
      Ogre::MaterialManager::getSingleton().remove(material->getName());
    }
  }
  materials_.clear();

}

void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)
{
  ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE);

  // flag indicating if the mesh material color needs to be updated
  bool update_color = false;

  scene_node_->setVisible(false);

  // Get the color information from the message
  float r = new_message->color.r;
  float g = new_message->color.g;
  float b = new_message->color.b;
  float a = new_message->color.a;

  Ogre::SceneBlendType blending;
  bool depth_write;

  if (a < 0.9998)
  {
    blending = Ogre::SBT_TRANSPARENT_ALPHA;
    depth_write = false;
  }
  else
  {
    blending = Ogre::SBT_REPLACE;
    depth_write = true;
  }

  if (!entity_ ||
      old_message->mesh_resource != new_message->mesh_resource ||
      old_message->mesh_use_embedded_materials != new_message->mesh_use_embedded_materials)
  {
    reset();

    if (new_message->mesh_resource.empty())
    {
      return;
    }

    if (loadMeshFromResource(new_message->mesh_resource).isNull())
    {
      std::stringstream ss;
      ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]";
      if (owner_)
      {
        owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str());
      }
      ROS_DEBUG("%s", ss.str().c_str());
      return;
    }

    static uint32_t count = 0;
    std::stringstream ss;
    ss << "mesh_resource_marker_" << count++;
    std::string id = ss.str();
    entity_ = context_->getSceneManager()->createEntity(id, new_message->mesh_resource);
    scene_node_->attachObject(entity_);

    // create a default material for any sub-entities which don't have their own.
    ss << "Material";
    Ogre::MaterialPtr default_material = Ogre::MaterialManager::getSingleton().create(ss.str(), ROS_PACKAGE_NAME);
    default_material->setReceiveShadows(false);
    default_material->getTechnique(0)->setLightingEnabled(true);
    default_material->getTechnique(0)->setAmbient(0.5, 0.5, 0.5);

    materials_.insert(default_material);

    if (new_message->mesh_use_embedded_materials)
    {
      // make clones of all embedded materials so selection works correctly
      S_MaterialPtr materials = getMaterials();

      S_MaterialPtr::iterator it;
      for (it = materials.begin(); it != materials.end(); it++)
      {
        if ((*it)->getName() != "BaseWhiteNoLighting")
        {
          Ogre::MaterialPtr new_material = (*it)->clone(id + (*it)->getName());
          materials_.insert(new_material);
        }
      }

      // make sub-entities use cloned materials
      for (uint32_t i = 0; i < entity_->getNumSubEntities(); ++i)
      {
        std::string mat_name = entity_->getSubEntity(i)->getMaterialName();
        if (mat_name != "BaseWhiteNoLighting")
        {
          entity_->getSubEntity(i)->setMaterialName(id + mat_name);
        }
        else
        {
          // BaseWhiteNoLighting is the default material Ogre uses
          // when it sees a mesh with no material.  Here we replace
          // that with our default_material which gets colored with
          // new_message->color.
          entity_->getSubEntity(i)->setMaterial(default_material);
        }
      }
    }
    else
    {
      entity_->setMaterial(default_material);
    }

    // always update color on resource change
    update_color = true;

    handler_.reset(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id), context_));
    handler_->addTrackedObject(entity_);
  }
  else
  {
    // underlying mesh resource has not changed but if the color has
    //  then we need to update the materials color
    if (!old_message
        || old_message->color.r != new_message->color.r
        || old_message->color.g != new_message->color.g
        || old_message->color.b != new_message->color.b
        || old_message->color.a != new_message->color.a)
    {
      update_color = true;
    }
  }

  // update material color
  //  if the mesh_use_embedded_materials is true and color is non-zero
  //  then the color will be used to tint the embedded materials
  if (update_color)
  {
    if( new_message->mesh_use_embedded_materials && r == 0 && g == 0 && b == 0 && a == 0 )
    {
      r = 1; g = 1; b = 1; a = 1;
    }
    S_MaterialPtr::iterator material_it;
    for (material_it = materials_.begin(); material_it != materials_.end(); material_it++)
    {
      Ogre::Technique* technique = (*material_it)->getTechnique(0);
      technique->setAmbient( r*0.5, g*0.5, b*0.5 );
      technique->setDiffuse( r, g, b, a );
      technique->setSceneBlending( blending );
      technique->setDepthWriteEnabled( depth_write );
      technique->setLightingEnabled( true );
    }

  }

  Ogre::Vector3 pos, scale;
  Ogre::Quaternion orient;
  transform(new_message, pos, orient, scale);

  scene_node_->setVisible(true);
  setPosition(pos);
  setOrientation(orient);

  scene_node_->setScale(scale);
}

S_MaterialPtr MeshResourceMarker::getMaterials()
{
  S_MaterialPtr materials;
  if (entity_)
  {
    extractMaterials(entity_, materials);
  }
  return materials;
}

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

#include "mesh_resource_marker.h"

#include "marker_selection_handler.h"
#include "rviz/default_plugin/marker_display.h"
#include "rviz/selection/selection_manager.h"

#include "rviz/display_context.h"
#include "rviz/mesh_loader.h"
#include "marker_display.h"

#include <OgreSceneNode.h>
#include <OgreSceneManager.h>
#include <OgreEntity.h>
#include <OgreSubEntity.h>
#include <OgreMaterialManager.h>
#include <OgreTextureManager.h>
#include <OgreSharedPtr.h>
#include <OgreTechnique.h>

namespace rviz
{

MeshResourceMarker::MeshResourceMarker(MarkerDisplay* owner, DisplayContext* context, Ogre::SceneNode* parent_node)
: MarkerBase(owner, context, parent_node)
, entity_(0)
{
}

MeshResourceMarker::~MeshResourceMarker()
{
  reset();
}

void MeshResourceMarker::reset()
{
  //destroy entity
  if (entity_)
  {
    context_->getSceneManager()->destroyEntity(entity_);
    entity_ = 0;
  }

  // destroy all the materials we've created
  S_MaterialPtr::iterator it;
  for (it = materials_.begin(); it != materials_.end(); it++)
  {
    Ogre::MaterialPtr material = *it;
    if (!material.isNull())
    {
      material->unload();
      Ogre::MaterialManager::getSingleton().remove(material->getName());
    }
  }
  materials_.clear();

}

void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)
{
  ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE);

  // flag indicating if the mesh material color needs to be updated
  bool update_color = false;

  scene_node_->setVisible(false);

  // Get the color information from the message
  float r = new_message->color.r;
  float g = new_message->color.g;
  float b = new_message->color.b;
  float a = new_message->color.a;

  Ogre::SceneBlendType blending;
  bool depth_write;

  if (a < 0.9998)
  {
    blending = Ogre::SBT_TRANSPARENT_ALPHA;
    depth_write = false;
  }
  else
  {
    blending = Ogre::SBT_REPLACE;
    depth_write = true;
  }

  if (!entity_ ||
      old_message->mesh_resource != new_message->mesh_resource ||
      old_message->mesh_use_embedded_materials != new_message->mesh_use_embedded_materials)
  {
    reset();

    if (new_message->mesh_resource.empty())
    {
      return;
    }

    if (loadMeshFromResource(new_message->mesh_resource).isNull())
    {
      std::stringstream ss;
      ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]";
      if (owner_)
      {
        owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str());
      }
      ROS_DEBUG("%s", ss.str().c_str());
      return;
    }

    static uint32_t count = 0;
    std::stringstream ss;
    ss << "mesh_resource_marker_" << count++;
    std::string id = ss.str();
    entity_ = context_->getSceneManager()->createEntity(id, new_message->mesh_resource);
    scene_node_->attachObject(entity_);

    // create a default material for any sub-entities which don't have their own.
    ss << "Material";
    Ogre::MaterialPtr default_material = Ogre::MaterialManager::getSingleton().create(ss.str(), ROS_PACKAGE_NAME);
    default_material->setReceiveShadows(false);
    default_material->getTechnique(0)->setLightingEnabled(true);
    default_material->getTechnique(0)->setAmbient(0.5, 0.5, 0.5);

    materials_.insert(default_material);

    if (new_message->mesh_use_embedded_materials)
    {
      // make clones of all embedded materials so selection works correctly
      S_MaterialPtr materials = getMaterials();

      S_MaterialPtr::iterator it;
      for (it = materials.begin(); it != materials.end(); it++)
      {
        if ((*it)->getName() != "BaseWhiteNoLighting")
        {
          Ogre::MaterialPtr new_material = (*it)->clone(id + (*it)->getName());
          materials_.insert(new_material);
        }
      }

      // make sub-entities use cloned materials
      for (uint32_t i = 0; i < entity_->getNumSubEntities(); ++i)
      {
        std::string mat_name = entity_->getSubEntity(i)->getMaterialName();
        if (mat_name != "BaseWhiteNoLighting")
        {
          entity_->getSubEntity(i)->setMaterialName(id + mat_name);
        }
        else
        {
          // BaseWhiteNoLighting is the default material Ogre uses
          // when it sees a mesh with no material.  Here we replace
          // that with our default_material which gets colored with
          // new_message->color.
          entity_->getSubEntity(i)->setMaterial(default_material);
        }
      }
    }
    else
    {
      entity_->setMaterial(default_material);
    }

    // always update color on resource change
    update_color = true;

    handler_.reset(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id), context_));
    handler_->addTrackedObject(entity_);
  }
  else
  {
    // underlying mesh resource has not changed but if the color has
    //  then we need to update the materials color
    if (!old_message
        || old_message->color.r != new_message->color.r
        || old_message->color.g != new_message->color.g
        || old_message->color.b != new_message->color.b
        || old_message->color.a != new_message->color.a)
    {
      update_color = true;
    }
  }

  // update material color
  //  if the mesh_use_embedded_materials is true and color is non-zero
  //  then the color will be used to tint the embedded materials
  if (update_color)
  {
    if( new_message->mesh_use_embedded_materials && r == 0 && g == 0 && b == 0 && a == 0 )
    {
    blending = Ogre::SBT_REPLACE;
    depth_write = true;
    r = 1; g = 1; b = 1; a = 1;
    }
    S_MaterialPtr::iterator material_it;
    for (material_it = materials_.begin(); material_it != materials_.end(); material_it++)
    {
      Ogre::Technique* technique = (*material_it)->getTechnique(0);
      technique->setAmbient( r*0.5, g*0.5, b*0.5 );
      technique->setDiffuse( r, g, b, a );
      technique->setSceneBlending( blending );
      technique->setDepthWriteEnabled( depth_write );
      technique->setLightingEnabled( true );
    }

  }

  Ogre::Vector3 pos, scale;
  Ogre::Quaternion orient;
  transform(new_message, pos, orient, scale);

  scene_node_->setVisible(true);
  setPosition(pos);
  setOrientation(orient);

  scene_node_->setScale(scale);
}

S_MaterialPtr MeshResourceMarker::getMaterials()
{
  S_MaterialPtr materials;
  if (entity_)
  {
    extractMaterials(entity_, materials);
  }
  return materials;
}

}
<|endoftext|>


<commit_before>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (C) 2008 Sacha Schutz <istdasklar@free.fr>
 * Copyright (C) 2008 Olivier Gueudelot <gueudelotolive@gmail.com>
 * Copyright (C) 2008 Charles Huet <packadal@gmail.com>
 * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "mesh.h"
#include "materialinstance.h"
#include "vertexbuffer.h"
#include "vertexattribute.h"

#include <QtGui/QMatrix4x4>
#include <QtGui/QColor>

#include "math.h"

using namespace GluonGraphics;

class Mesh::MeshPrivate
{
    public:
        MeshPrivate()
        {
        }

        VertexBuffer* buffer;
        MaterialInstance* material;
};

Mesh::Mesh( QObject* parent )
    : QObject( parent ),
      d( new MeshPrivate )
{
    d->buffer = new VertexBuffer( this );
}

Mesh::~Mesh()
{
    delete d;
}

void
Mesh::load( const QString& filename )
{
    if( isLoaded() )
        return;

    VertexAttribute vertices( "vertex", 3);
    vertices << -1.f << -1.f << 0.f;
    vertices << -1.f <<  1.f << 0.f;
    vertices <<  1.f <<  1.f << 0.f;
    vertices <<  1.f << -1.f << 0.f;
    d->buffer->addAttribute( vertices );

    VertexAttribute colors("color", 4 );
    colors << 1.f << 1.f << 1.f << 1.f;
    colors << 1.f << 1.f << 1.f << 1.f;
    colors << 1.f << 1.f << 1.f << 1.f;
    colors << 1.f << 1.f << 1.f << 1.f;
    d->buffer->addAttribute( colors );

    VertexAttribute uvs( "uv0", 2 );
    uvs << 0.f << 0.f;
    uvs << 0.f << 1.f;
    uvs << 1.f << 1.f;
    uvs << 1.f << 0.f;
    d->buffer->addAttribute( uvs );

    QVector<uint> indices;
    indices << 0 << 1 << 2
            << 0 << 2 << 3;

    d->buffer->setIndices( indices );

    d->buffer->initialize();
}

void
Mesh::setVertexBuffer( VertexBuffer* buffer )
{
    if( d->buffer )
    {
        delete d->buffer;
    }

    d->buffer = buffer;

    if( buffer && !buffer->isInitialized() )
    {
        buffer->initialize();
    }
}

void
Mesh::render( MaterialInstance* material, VertexBuffer::RenderMode mode )
{
    d->buffer->render( mode, material );
}

bool
Mesh::isLoaded() const
{
    return d->buffer->isInitialized();
}

VertexBuffer*
Mesh::vertexBuffer() const
{
    return d->buffer;
}

#include "mesh.moc"
<commit_msg>Set the mesh as the parent of the vertex buffer.<commit_after>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (C) 2008 Sacha Schutz <istdasklar@free.fr>
 * Copyright (C) 2008 Olivier Gueudelot <gueudelotolive@gmail.com>
 * Copyright (C) 2008 Charles Huet <packadal@gmail.com>
 * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "mesh.h"
#include "materialinstance.h"
#include "vertexbuffer.h"
#include "vertexattribute.h"

#include <QtGui/QMatrix4x4>
#include <QtGui/QColor>

#include "math.h"

using namespace GluonGraphics;

class Mesh::MeshPrivate
{
    public:
        MeshPrivate()
        {
        }

        VertexBuffer* buffer;
        MaterialInstance* material;
};

Mesh::Mesh( QObject* parent )
    : QObject( parent ),
      d( new MeshPrivate )
{
    d->buffer = new VertexBuffer( this );
}

Mesh::~Mesh()
{
    delete d;
}

void
Mesh::load( const QString& filename )
{
    if( isLoaded() )
        return;

    VertexAttribute vertices( "vertex", 3);
    vertices << -1.f << -1.f << 0.f;
    vertices << -1.f <<  1.f << 0.f;
    vertices <<  1.f <<  1.f << 0.f;
    vertices <<  1.f << -1.f << 0.f;
    d->buffer->addAttribute( vertices );

    VertexAttribute colors("color", 4 );
    colors << 1.f << 1.f << 1.f << 1.f;
    colors << 1.f << 1.f << 1.f << 1.f;
    colors << 1.f << 1.f << 1.f << 1.f;
    colors << 1.f << 1.f << 1.f << 1.f;
    d->buffer->addAttribute( colors );

    VertexAttribute uvs( "uv0", 2 );
    uvs << 0.f << 0.f;
    uvs << 0.f << 1.f;
    uvs << 1.f << 1.f;
    uvs << 1.f << 0.f;
    d->buffer->addAttribute( uvs );

    QVector<uint> indices;
    indices << 0 << 1 << 2
            << 0 << 2 << 3;

    d->buffer->setIndices( indices );

    d->buffer->initialize();
}

void
Mesh::setVertexBuffer( VertexBuffer* buffer )
{
    if( d->buffer )
    {
        delete d->buffer;
    }

    d->buffer = buffer;

    if( buffer )
    {
        buffer->setParent( this );
        if( !buffer->isInitialized() )
        {
            buffer->initialize();
        }
    }
}

void
Mesh::render( MaterialInstance* material, VertexBuffer::RenderMode mode )
{
    d->buffer->render( mode, material );
}

bool
Mesh::isLoaded() const
{
    return d->buffer->isInitialized();
}

VertexBuffer*
Mesh::vertexBuffer() const
{
    return d->buffer;
}

#include "mesh.moc"
<|endoftext|>


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

/**
 * @date 05/04/2014
 * @author Jan Issac (jan.issac@gmail.com)
 * Max-Planck-Institute for Intelligent Systems, University of Southern California (USC),
 *   Karlsruhe Institute of Technology (KIT)
 */

#include <sensor_msgs/PointCloud2.h>
#include <stereo_msgs/DisparityImage.h>
#include <sensor_msgs/image_encodings.h>
#include <string>
#include <yaml-cpp/yaml.h>

#include "oni_vicon_player/oni_player.hpp"

using namespace oni_vicon_player;

OniPlayer::OniPlayer():
    image_width_(KINECT_IMAGE_COLS),
    image_height_(KINECT_IMAGE_ROWS),
    depth_width_(KINECT_IMAGE_COLS),
    depth_height_(KINECT_IMAGE_ROWS)
{
    node_handle_ = ros::NodeHandle("~");

    node_handle_.param ("rgb_frame_id", rgb_frame_id_, std::string (""));
    if (rgb_frame_id_.empty ())
    {
        rgb_frame_id_ = "/camera_rgb_optical_frame";
        ROS_INFO ("'rgb_frame_id' not set. using default: '%s'", rgb_frame_id_.c_str());
    }
    else
    {
        ROS_INFO ("rgb_frame_id = '%s' ", rgb_frame_id_.c_str());
    }

    node_handle_.param ("depth_frame_id", depth_frame_id_, std::string (""));
    if (depth_frame_id_.empty ())
    {
        depth_frame_id_ = "/camera_depth_optical_frame";
        ROS_INFO ("'depth_frame_id' not set. using default: '%s'", depth_frame_id_.c_str());
    }
    else
    {
        ROS_INFO ("depth_frame_id = '%s' ", depth_frame_id_.c_str());
    }

    // Init all publishers
    it_ = new image_transport::ImageTransport(node_handle_);
    pub_depth_image_ = it_->advertise ("depth/image", 5);

    pub_depth_info_ = node_handle_.advertise<sensor_msgs::CameraInfo> ("depth/camera_info", 5);
    pub_point_cloud_ = node_handle_.advertise<sensor_msgs::PointCloud2> ("depth/points", 5);
}

OniPlayer::~OniPlayer()
{

}

bool OniPlayer::process()
{
    boost::mutex::scoped_lock lock (capture_mutex_);

    if(kinect_capture(device_)!=0)
    {
        ROS_ERROR("Error during capture!\n");
        return false;
    }

    ros::Time time = ros::Time::now ();

    if(device_->depth_dirty)
    {
        if (pub_depth_info_.getNumSubscribers () > 0)
        {
            pub_depth_info_.publish (fillCameraInfo (time, false));
        }

        if (pub_depth_image_.getNumSubscribers () > 0)
        {
            publishDepthImage(time);
        }

        if (pub_point_cloud_.getNumSubscribers () > 0)
        {
            publishXYZPointCloud(time);
        }
    }

    ros::spinOnce();

    return true;
}

void OniPlayer::publishDepthImage(ros::Time time)
{
    sensor_msgs::ImagePtr depth_msg = boost::make_shared<sensor_msgs::Image> ();
    depth_msg->header.stamp         = time;
    // all depth data is relative to the rgb frame since we take registered data by default
    depth_msg->header.frame_id      = rgb_frame_id_;
    depth_msg->encoding             = sensor_msgs::image_encodings::TYPE_32FC1;
    depth_msg->height               = depth_height_;
    depth_msg->width                = depth_width_;
    depth_msg->step                 = depth_msg->width * sizeof (float);
    depth_msg->data.resize (depth_msg->height * depth_msg->step);

    kinect_get_f_depth_buffer(device_,
                              reinterpret_cast<float*>(&depth_msg->data[0]),
                               depth_msg->width * depth_msg->height *sizeof(float));

    if (pub_depth_image_.getNumSubscribers () > 0)
    {
        pub_depth_image_.publish (depth_msg);
    }
}

void OniPlayer::publishXYZPointCloud(ros::Time time)
{

  sensor_msgs::ImagePtr depth_msg = boost::make_shared<sensor_msgs::Image > ();
  depth_msg->header.stamp         = time;
  // all depth data is relative to the rgb frame since we take registered data by default
  depth_msg->header.frame_id      = rgb_frame_id_;
  depth_msg->encoding             = sensor_msgs::image_encodings::TYPE_32FC1;
  depth_msg->height               = depth_height_;
  depth_msg->width                = depth_width_;
  depth_msg->step                 = depth_msg->width * sizeof (float);
  depth_msg->data.resize (depth_msg->height * depth_msg->step);

  kinect_get_f_depth_buffer(device_,
                reinterpret_cast<float*>(&depth_msg->data[0]),
                depth_msg->width * depth_msg->height *sizeof(float));

  float *point_buffer = (float*)calloc(1,KINECT_IMAGE_COLS*KINECT_IMAGE_ROWS*sizeof(float)*3);
  kinect_f_depth_to_xyz_buffer(device_,
                   reinterpret_cast<float*>(&depth_msg->data[0]), depth_msg->width * depth_msg->height *sizeof(float),
                   NULL, 0,
                   point_buffer, KINECT_IMAGE_COLS*KINECT_IMAGE_ROWS*sizeof(float),
                   NULL, 0);

  sensor_msgs::PointCloud2Ptr points = boost::make_shared<sensor_msgs::PointCloud2 > ();
  // all depth data is relative to the rgb frame since we take registered data by default
  points->header.frame_id = rgb_frame_id_;
  points->header.stamp = time;
  points->width        = KINECT_IMAGE_COLS;
  points->height       = KINECT_IMAGE_ROWS;
  points->is_dense     = false;
  points->is_bigendian = false;
  points->fields.resize( 3 );
  points->fields[0].name = "x";
  points->fields[1].name = "y";
  points->fields[2].name = "z";
  int offset = 0;
  for (size_t d = 0;
       d < points->fields.size ();
       ++d, offset += sizeof(float)) {
    points->fields[d].offset = offset;
    points->fields[d].datatype =
      sensor_msgs::PointField::FLOAT32;
    points->fields[d].count  = 1;
  }

  points->point_step = offset;
  points->row_step   =
    points->point_step * points->width;

  points->data.resize (points->width *
              points->height *
              points->point_step);

  for(int i=0; i<KINECT_IMAGE_ROWS; i++)
    {
      for(int j=0; j<KINECT_IMAGE_COLS; j++)
    {

      memcpy (&points->data[i * points->row_step + j * points->point_step + points->fields[0].offset],
          &point_buffer[i*KINECT_IMAGE_COLS*3 + j*3 + 0], sizeof (float));
      memcpy (&points->data[i * points->row_step + j * points->point_step + points->fields[1].offset],
          &point_buffer[i*KINECT_IMAGE_COLS*3 + j*3 + 1], sizeof (float));
      memcpy (&points->data[i * points->row_step + j * points->point_step + points->fields[2].offset],
          &point_buffer[i*KINECT_IMAGE_COLS*3 + j*3 + 2], sizeof (float));

      /*
      std::cout << "x y z " << point_buffer[i*KINECT_IMAGE_COLS*3 + j*3 + 0] << " "
            << point_buffer[i*KINECT_IMAGE_COLS*3 + j*3 + 1] << " "
                << point_buffer[i*KINECT_IMAGE_COLS*3 + j*3 + 2] << " " << std::endl;
      */
    }
    }

  if (  pub_point_cloud_.getNumSubscribers () > 0)
    pub_point_cloud_.publish (points);

  free(point_buffer);
}

sensor_msgs::CameraInfoPtr OniPlayer::fillCameraInfo (ros::Time time, bool is_rgb)
{
  sensor_msgs::CameraInfoPtr info_msg = boost::make_shared<sensor_msgs::CameraInfo > ();
  info_msg->header.stamp    = time;
  info_msg->header.frame_id = is_rgb ? rgb_frame_id_ : depth_frame_id_;
  info_msg->width           = is_rgb ? image_width_ : depth_width_;
  info_msg->height          = is_rgb ? image_height_ : depth_height_;

#if ROS_VERSION_MINIMUM(1, 3, 0)
  info_msg->D = std::vector<double>(5, 0.0);
  info_msg->distortion_model = sensor_msgs::distortion_models::PLUMB_BOB;
#else
  info_msg->D.assign (0.0);
#endif
  info_msg->K.assign (0.0);
  info_msg->R.assign (0.0);
  info_msg->P.assign (0.0);
  // Simple camera matrix: square pixels, principal point at center
  double f = is_rgb ? device_->params.rgb_focal_length : device_->params.ir_focal_length;
  info_msg->K[0] = info_msg->K[4] = f;
  info_msg->K[2] = is_rgb ?  device_->params.rgb_camera_center.x : device_->params.ir_camera_center.x;
  info_msg->K[5] = is_rgb ?  device_->params.rgb_camera_center.y : device_->params.ir_camera_center.y;
  info_msg->K[8] = 1.0;
  // no rotation: identity
  info_msg->R[0] = info_msg->R[4] = info_msg->R[8] = 1.0;
  // no rotation, no translation => P=K(I|0)=(K|0)
  info_msg->P[0] = info_msg->P[5] = info_msg->K[0];
  info_msg->P[2] = info_msg->K[2];
  info_msg->P[6] = info_msg->K[5];
  info_msg->P[10] = 1.0;

  return info_msg;
}
<commit_msg>Some Depth generator example<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2014 Max-Planck-Institute for Intelligent Systems,
 *                     University of Southern California,
 *                     Karlsruhe Institute of Technology
 *    Jan Issac (jan.issac@gmail.com)
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

/**
 * @date 05/04/2014
 * @author Jan Issac (jan.issac@gmail.com)
 * Max-Planck-Institute for Intelligent Systems, University of Southern California (USC),
 *   Karlsruhe Institute of Technology (KIT)
 */

#include <sensor_msgs/PointCloud2.h>
#include <stereo_msgs/DisparityImage.h>
#include <sensor_msgs/image_encodings.h>
#include <string>
#include <yaml-cpp/yaml.h>

#include "oni_vicon_player/oni_player.hpp"

using namespace oni_vicon_player;

OniPlayer::OniPlayer():
    image_width_(KINECT_IMAGE_COLS),
    image_height_(KINECT_IMAGE_ROWS),
    depth_width_(KINECT_IMAGE_COLS),
    depth_height_(KINECT_IMAGE_ROWS)
{
    node_handle_ = ros::NodeHandle("~");

    node_handle_.param ("rgb_frame_id", rgb_frame_id_, std::string (""));
    if (rgb_frame_id_.empty ())
    {
        rgb_frame_id_ = "/camera_rgb_optical_frame";
        ROS_INFO ("'rgb_frame_id' not set. using default: '%s'", rgb_frame_id_.c_str());
    }
    else
    {
        ROS_INFO ("rgb_frame_id = '%s' ", rgb_frame_id_.c_str());
    }

    node_handle_.param ("depth_frame_id", depth_frame_id_, std::string (""));
    if (depth_frame_id_.empty ())
    {
        depth_frame_id_ = "/camera_depth_optical_frame";
        ROS_INFO ("'depth_frame_id' not set. using default: '%s'", depth_frame_id_.c_str());
    }
    else
    {
        ROS_INFO ("depth_frame_id = '%s' ", depth_frame_id_.c_str());
    }

    // Init all publishers
    it_ = new image_transport::ImageTransport(node_handle_);
    pub_depth_image_ = it_->advertise ("depth/image", 5);

    pub_depth_info_ = node_handle_.advertise<sensor_msgs::CameraInfo> ("depth/camera_info", 5);
    pub_point_cloud_ = node_handle_.advertise<sensor_msgs::PointCloud2> ("depth/points", 5);
}

OniPlayer::~OniPlayer()
{

}

bool OniPlayer::process()
{
    boost::mutex::scoped_lock lock (capture_mutex_);

    if(kinect_capture(device_)!=0)
    {
        ROS_ERROR("Error during capture!\n");
        return false;
    }

    ros::Time time = ros::Time::now ();

    if(device_->depth_dirty)
    {
        if (pub_depth_info_.getNumSubscribers () > 0)
        {
            pub_depth_info_.publish (fillCameraInfo (time, false));
        }

        if (pub_depth_image_.getNumSubscribers () > 0)
        {
            publishDepthImage(time);
        }

        if (pub_point_cloud_.getNumSubscribers () > 0)
        {
            publishXYZPointCloud(time);
        }
    }

    ros::spinOnce();

    return true;
}

void OniPlayer::publishDepthImage(ros::Time time)
{
    sensor_msgs::ImagePtr depth_msg = boost::make_shared<sensor_msgs::Image> ();
    depth_msg->header.stamp         = time;
    // all depth data is relative to the rgb frame since we take registered data by default
    depth_msg->header.frame_id      = rgb_frame_id_;
    depth_msg->encoding             = sensor_msgs::image_encodings::TYPE_32FC1;
    depth_msg->height               = depth_height_;
    depth_msg->width                = depth_width_;
    depth_msg->step                 = depth_msg->width * sizeof (float);
    depth_msg->data.resize (depth_msg->height * depth_msg->step);

    kinect_get_f_depth_buffer(device_,
                              reinterpret_cast<float*>(&depth_msg->data[0]),
                               depth_msg->width * depth_msg->height *sizeof(float));

    if (pub_depth_image_.getNumSubscribers () > 0)
    {
        pub_depth_image_.publish (depth_msg);
    }
}

void OniPlayer::publishXYZPointCloud(ros::Time time)
{

  sensor_msgs::ImagePtr depth_msg = boost::make_shared<sensor_msgs::Image > ();
  depth_msg->header.stamp         = time;
  // all depth data is relative to the rgb frame since we take registered data by default
  depth_msg->header.frame_id      = rgb_frame_id_;
  depth_msg->encoding             = sensor_msgs::image_encodings::TYPE_32FC1;
  depth_msg->height               = depth_height_;
  depth_msg->width                = depth_width_;
  depth_msg->step                 = depth_msg->width * sizeof (float);
  depth_msg->data.resize (depth_msg->height * depth_msg->step);

  kinect_get_f_depth_buffer(device_,
                reinterpret_cast<float*>(&depth_msg->data[0]),
                depth_msg->width * depth_msg->height *sizeof(float));

  float *point_buffer = (float*)calloc(1,KINECT_IMAGE_COLS*KINECT_IMAGE_ROWS*sizeof(float)*3);
  kinect_f_depth_to_xyz_buffer(device_,
                   reinterpret_cast<float*>(&depth_msg->data[0]), depth_msg->width * depth_msg->height *sizeof(float),
                   NULL, 0,
                   point_buffer, KINECT_IMAGE_COLS*KINECT_IMAGE_ROWS*sizeof(float),
                   NULL, 0);

  sensor_msgs::PointCloud2Ptr points = boost::make_shared<sensor_msgs::PointCloud2 > ();
  // all depth data is relative to the rgb frame since we take registered data by default
  points->header.frame_id = rgb_frame_id_;
  points->header.stamp = time;
  points->width        = KINECT_IMAGE_COLS;
  points->height       = KINECT_IMAGE_ROWS;
  points->is_dense     = false;
  points->is_bigendian = false;
  points->fields.resize( 3 );
  points->fields[0].name = "x";
  points->fields[1].name = "y";
  points->fields[2].name = "z";
  int offset = 0;
  for (size_t d = 0; d < points->fields.size (); ++d, offset += sizeof(float)) {
    points->fields[d].offset = offset;
    points->fields[d].datatype = sensor_msgs::PointField::FLOAT32;
    points->fields[d].count  = 1;
  }

  points->point_step = offset;
  points->row_step   =
    points->point_step * points->width;

  points->data.resize (points->width *
              points->height *
              points->point_step);

  for(int i=0; i<KINECT_IMAGE_ROWS; i++)
    {
      for(int j=0; j<KINECT_IMAGE_COLS; j++)
    {

      memcpy (&points->data[i * points->row_step + j * points->point_step + points->fields[0].offset],
          &point_buffer[i*KINECT_IMAGE_COLS*3 + j*3 + 0], sizeof (float));
      memcpy (&points->data[i * points->row_step + j * points->point_step + points->fields[1].offset],
          &point_buffer[i*KINECT_IMAGE_COLS*3 + j*3 + 1], sizeof (float));
      memcpy (&points->data[i * points->row_step + j * points->point_step + points->fields[2].offset],
          &point_buffer[i*KINECT_IMAGE_COLS*3 + j*3 + 2], sizeof (float));

      /*
      std::cout << "x y z " << point_buffer[i*KINECT_IMAGE_COLS*3 + j*3 + 0] << " "
            << point_buffer[i*KINECT_IMAGE_COLS*3 + j*3 + 1] << " "
                << point_buffer[i*KINECT_IMAGE_COLS*3 + j*3 + 2] << " " << std::endl;
      */
    }
    }

  if (  pub_point_cloud_.getNumSubscribers () > 0)
    pub_point_cloud_.publish (points);

  free(point_buffer);
}

sensor_msgs::CameraInfoPtr OniPlayer::fillCameraInfo (ros::Time time, bool is_rgb)
{
  sensor_msgs::CameraInfoPtr info_msg = boost::make_shared<sensor_msgs::CameraInfo > ();
  info_msg->header.stamp    = time;
  info_msg->header.frame_id = is_rgb ? rgb_frame_id_ : depth_frame_id_;
  info_msg->width           = is_rgb ? image_width_ : depth_width_;
  info_msg->height          = is_rgb ? image_height_ : depth_height_;

#if ROS_VERSION_MINIMUM(1, 3, 0)
  info_msg->D = std::vector<double>(5, 0.0);
  info_msg->distortion_model = sensor_msgs::distortion_models::PLUMB_BOB;
#else
  info_msg->D.assign (0.0);
#endif
  info_msg->K.assign (0.0);
  info_msg->R.assign (0.0);
  info_msg->P.assign (0.0);
  // Simple camera matrix: square pixels, principal point at center
  double f = is_rgb ? device_->params.rgb_focal_length : device_->params.ir_focal_length;
  info_msg->K[0] = info_msg->K[4] = f;
  info_msg->K[2] = is_rgb ?  device_->params.rgb_camera_center.x : device_->params.ir_camera_center.x;
  info_msg->K[5] = is_rgb ?  device_->params.rgb_camera_center.y : device_->params.ir_camera_center.y;
  info_msg->K[8] = 1.0;
  // no rotation: identity
  info_msg->R[0] = info_msg->R[4] = info_msg->R[8] = 1.0;
  // no rotation, no translation => P=K(I|0)=(K|0)
  info_msg->P[0] = info_msg->P[5] = info_msg->K[0];
  info_msg->P[2] = info_msg->K[2];
  info_msg->P[6] = info_msg->K[5];
  info_msg->P[10] = 1.0;

  return info_msg;
}

/*
 *
 *
int main(int argc, char* argv[])
{
    if(argc < 2 )
    {
        std::cout << ">> Error: missing file argument!" << std::endl;
        return -1;
    }

    // initialize rainbow coloring
    rainbow_init();

    Context context;
    int nRetVal = context.Init();
    CHECK_RC(nRetVal, "Init");

    std::string sourceFile = argv[1];

    Player player;
    context.OpenFileRecording( sourceFile.c_str(), player );

    DepthGenerator depthGenerator;
    depthGenerator.Create(context);

    XnUInt32 uFrames;
    player.GetNumFrames( depthGenerator.GetName(), uFrames );
    std::cout << "Total " << uFrames << " frames" << std::endl;

    // create window / gui
    std::string windowName = "Kinect Display";
    cv::namedWindow(windowName, 1);
    int tbPos;
    cv::createTrackbar("MyTrackbar", windowName, &tbPos, uFrames);
    cv::createButton("button6", callbackButton2, NULL, cv::QT_PUSH_BUTTON, 1);
    cv::createButton("button6", callbackButton2, NULL, cv::QT_RADIOBOX, 1);
    cv::createButton("button6", callbackButton2, NULL, cv::QT_CHECKBOX, 1);
    cv::createButton("button6", callbackButton2, NULL, cv::QT_CHECKBOX, 1);
    cv::displayOverlay(windowName, "some stuff to display overlayed");

    // create the test images
    cv::Mat depth_image(KINECT_IMAGE_ROWS, KINECT_IMAGE_COLS, CV_8UC3);
    cv::Mat display(KINECT_IMAGE_ROWS, KINECT_IMAGE_COLS, CV_8UC3);
    uint16_t *depth_buffer = (uint16_t*)calloc(1,KINECT_IMAGE_COLS*KINECT_IMAGE_ROWS*sizeof(uint16_t));
    cv::Rect rect;

    context.StartGeneratingAll();

    const int ESC=27;
    char pressed_key = 0;
    uint8_t *dst;
    uint16_t val, min_val, max_val;
    DepthMetaData xDepthMap;

    player.SetPlaybackSpeed(1.0);

    //for( unsigned int i = 0; i < uFrames; ++ i )
    while(true)
    {
        player.SeekToFrame(depthGenerator.GetName(), tbPos, XN_PLAYER_SEEK_SET);

        depthGenerator.WaitAndUpdateData();

        // get value
        depthGenerator.GetMetaData( xDepthMap );
        //cout << "Frame " << uFrames << ", frameID " << xDepthMap.FrameID() << ", timestamp " << xDepthMap.Timestamp() << endl;

        memcpy(depth_buffer, (char*)xDepthMap.Data(), sizeof(uint16_t) * KINECT_IMAGE_COLS * KINECT_IMAGE_ROWS);

        min_val = 65535;
        max_val = 0;
        for(int i=0; i<KINECT_IMAGE_ROWS; i++)
        {
            for(int j=0; j<KINECT_IMAGE_COLS; j++)
            {
                val = depth_buffer[i*KINECT_IMAGE_COLS + j];
                if(val < min_val)
                    min_val = val;
                if(val > max_val)
                    max_val = val;
            }
        }

        for(int i=0; i<KINECT_IMAGE_ROWS; i++)
        {
            for(int j=0; j<KINECT_IMAGE_COLS; j++)
            {
                dst = (uint8_t*)(&depth_image.data[i*KINECT_IMAGE_COLS*3 + j*3]);
                val = depth_buffer[i*KINECT_IMAGE_COLS + j];
                rainbow_set(dst, (max_val - val)*1.0, min_val*1.0, max_val*1.0);
            }
        }

        // form the display image
        display = cv::Scalar(0);
        rect.x = 0;
        rect.y = 0;
        rect.width = KINECT_IMAGE_COLS;
        rect.height = KINECT_IMAGE_ROWS;
        cv::Mat roi_depth(display, rect);
        depth_image.convertTo(roi_depth, roi_depth.type(), 1, 0);

        pressed_key = cv::waitKey(2);
        if(pressed_key == ESC)
        {
            break;
        }
        cv::imshow(windowName, display);
    }

    context.StopGeneratingAll();
    context.Release();

    return 0;
}
*/
<|endoftext|>


<commit_before>#ifndef HTOOL_HTOOL_HPP
#define HTOOL_HTOOL_HPP

#ifndef HTOOL_MKL
# ifdef INTEL_MKL_VERSION
#  define HTOOL_MKL           1
# else
#  define HTOOL_MKL           0
# endif
#endif

#include "clustering/cluster.hpp"
#include "clustering/geometric_splitting.hpp"
#include "clustering/regular_splitting.hpp"

#include "input_output/geometry.hpp"
#include "input_output/output.hpp"

#include "lrmat/lrmat.hpp"
#include "lrmat/SVD.hpp"
#include "lrmat/fullACA.hpp"
#include "lrmat/partialACA.hpp"
#include "lrmat/sympartialACA.hpp"

#include "multilrmat/multilrmat.hpp"
#include "multilrmat/multipartialACA.hpp"

#include "misc/infos.hpp"
#include "misc/parametres.hpp"
#include "misc/user.hpp"

#include "types/hmatrix.hpp"
#include "types/matrix.hpp"
#include "types/multihmatrix.hpp"
#include "types/multimatrix.hpp"
#include "types/point.hpp"
#include "types/vector.hpp"

#ifdef WITH_HPDDM
    // #include "wrappers/wrapper_hpddm.hpp"
#endif
#include "wrappers/wrapper_blas.hpp"
#include "wrappers/wrapper_mpi.hpp"

#ifdef WITH_HPDDM
    // #include "solvers/ddm.hpp"
    // #include "solvers/proto_ddm.hpp"
#endif

#endif
<commit_msg>cleaning htool.hpp<commit_after>#ifndef HTOOL_HTOOL_HPP
#define HTOOL_HTOOL_HPP

#ifndef HTOOL_MKL
# ifdef INTEL_MKL_VERSION
#  define HTOOL_MKL           1
# else
#  define HTOOL_MKL           0
# endif
#endif

#include "clustering/cluster.hpp"
#include "clustering/geometric_splitting.hpp"
#include "clustering/regular_splitting.hpp"

#include "input_output/geometry.hpp"
#include "input_output/output.hpp"

#include "lrmat/lrmat.hpp"
#include "lrmat/SVD.hpp"
#include "lrmat/fullACA.hpp"
#include "lrmat/partialACA.hpp"
#include "lrmat/sympartialACA.hpp"

#include "multilrmat/multilrmat.hpp"
#include "multilrmat/multipartialACA.hpp"

#include "misc/infos.hpp"
#include "misc/parametres.hpp"
#include "misc/user.hpp"

#include "types/hmatrix.hpp"
#include "types/matrix.hpp"
#include "types/multihmatrix.hpp"
#include "types/multimatrix.hpp"
#include "types/point.hpp"
#include "types/vector.hpp"

#ifdef WITH_HPDDM
    #include "wrappers/wrapper_hpddm.hpp"
#endif
#include "wrappers/wrapper_blas.hpp"
#include "wrappers/wrapper_mpi.hpp"

#ifdef WITH_HPDDM
    #include "solvers/ddm.hpp"
    #include "solvers/proto_ddm.hpp"
#endif

#endif
<|endoftext|>


<commit_before>//
//  inpal_prime.hpp
//  Inverse Palindrome Library
//
//  Created by Bryan Triana
//  Copyright © 2016 Inverse Palindrome. All rights reserved.
//

#ifndef inpal_prime_hpp
#define inpal_prime_hpp

#include <vector>
#include <string>
#include <cmath>
#include <algorithm>

namespace inpal
{
    namespace prime
    {
        //general purpose functions
        std::vector<std::size_t> prime_list(std::size_t range);
        std::vector<bool> prime_sieve(std::size_t range);
        std::vector<std::size_t> factor_list(std::size_t num);
        //special purpose functions
        std::size_t prime_locate(std::size_t pos);
        std::size_t max_prime(std::size_t range);
        std::size_t prime_count(std::size_t range);
        double prime_density(double range);
        bool prime_test(std::size_t num);
        bool twin_test(std::size_t num);
        bool cousin_test(std::size_t num);
        bool sexy_test(std::size_t num);
        std::size_t max_palprime(std::size_t range);
        std::size_t max_factor(std::size_t num);
        std::size_t factor_count(std::size_t num);
    }
}

#endif /* inpal_prime_hpp */
<commit_msg>function name change<commit_after>//
//  inpal_prime.hpp
//  Inverse Palindrome Library
//
//  Created by Bryan Triana
//  Copyright © 2016 Inverse Palindrome. All rights reserved.
//

#ifndef inpal_prime_hpp
#define inpal_prime_hpp

#include <vector>
#include <string>
#include <cmath>
#include <algorithm>

namespace inpal
{
    namespace prime
    {
        //general purpose functions
        std::vector<std::size_t> prime_list(std::size_t range);
        std::vector<bool> prime_sieve(std::size_t range);
        std::vector<std::size_t> factor_list(std::size_t num);

        //special purpose functions
        std::size_t prime_locate(std::size_t pos);
        std::size_t max_prime(std::size_t range);
        std::size_t prime_count(std::size_t range);
        bool prime_test(std::size_t num);
        bool twin_prime_test(std::size_t num);
        bool cousin_prime_test(std::size_t num);
        bool sexy_prime_test(std::size_t num);
        std::size_t max_palindromic_prime(std::size_t range);
        std::size_t max_factor(std::size_t num);
        std::size_t factor_count(std::size_t num);
    }
}

#endif /* inpal_prime_hpp */
<|endoftext|>


<commit_before>#include <build-bot/worker.h>

#include <boost/filesystem.hpp>
#include <boost/random/random_device.hpp>
#include <boost/random/uniform_int_distribution.hpp>

#include <boost/process.hpp>

namespace fs = boost::filesystem;

namespace dsn {
namespace build_bot {
    namespace priv {
        class Worker : public dsn::log::Base<Worker> {
        private:
            std::string m_url;
            std::string m_branch;
            std::string m_revision;
            std::string m_configFile;
            std::string m_profileName;
            std::string m_buildDir;
            std::string m_repoName;

            std::string generateBuildId()
            {
                std::string res;
                boost::random::random_device rng;
                boost::random::uniform_int_distribution<> dist(0, BUILD_ID_CHARS.size() - 1);

                for (size_t i = 0; i < BUILD_ID_LENGTH; i++)
                    res += BUILD_ID_CHARS[dist(rng)];

                return res;
            }

            std::string m_buildId;

            static const std::string BUILD_ID_CHARS;
            static const size_t BUILD_ID_LENGTH;

            std::string m_toplevelDirectory;

            bool initToplevelDirectory()
            {
                std::stringstream ss;
                ss << m_buildDir << "/" << m_profileName << "/" << m_repoName << "/" << m_buildId;
                m_toplevelDirectory = ss.str();
                fs::path path(m_toplevelDirectory);

                BOOST_LOG_SEV(log, severity::info) << "Toplevel build directory is " << m_toplevelDirectory;

                if (!fs::exists(path)) {
                    try {
                        fs::create_directories(path);
                    }

                    catch (boost::system::system_error& ex) {
                        BOOST_LOG_SEV(log, severity::error) << "Failed to create toplevel directory " << m_toplevelDirectory << ": " << ex.what();
                        return false;
                    }
                }

                return true;
            }

            std::string m_gitExecutable;
            bool findGitExecutable()
            {
                try {
                    m_gitExecutable = boost::process::search_path("git");
                }
                catch (std::runtime_error& ex) {
                    BOOST_LOG_SEV(log, severity::error) << "Failed to locate git executable in PATH: " << ex.what();
                    return false;
                }

                if (m_gitExecutable.size() == 0) {
                    BOOST_LOG_SEV(log, severity::error) << "No git executable found in PATH!";
                    return false;
                }

                BOOST_LOG_SEV(log, severity::debug) << "Using git executable from " << m_gitExecutable;
                return true;
            }

            std::string m_sourceDirectory;
            bool checkoutSources()
            {
                m_sourceDirectory = m_toplevelDirectory + "/repo";
                BOOST_LOG_SEV(log, severity::info) << "Checking out sources from " << m_url << " to " << m_sourceDirectory;

                return true;
            }

        public:
            Worker(const std::string& build_directory,
                   const std::string& repo_name,
                   const std::string& url, const std::string& branch, const std::string& revision,
                   const std::string& config_file, const std::string& profile_name)
                : m_buildDir(build_directory)
                , m_url(url)
                , m_branch(branch)
                , m_revision(revision)
                , m_configFile(config_file)
                , m_profileName(profile_name)
                , m_repoName(repo_name)
            {
            }

            void run()
            {
                if (!findGitExecutable()) {
                    BOOST_LOG_SEV(log, severity::error) << "Failed to find git; build FAILED!";
                    return;
                }

                m_buildId = generateBuildId();
                BOOST_LOG_SEV(log, severity::info) << "Worker started for repo " << m_repoName
                                                   << " (profile: " << m_profileName << ", config: " << m_configFile << ") - Build ID: " << m_buildId;
                if (!initToplevelDirectory()) {
                    BOOST_LOG_SEV(log, severity::error) << "Unable to create build directory; build FAILED!";
                    return;
                }

                if (!checkoutSources()) {
                    BOOST_LOG_SEV(log, severity::error) << "Failed to checkout sources from " << m_url << "; build FAILED!";
                    return;
                }
            }
        };

        const std::string Worker::BUILD_ID_CHARS{ "0123456789abcdef" };
        const size_t Worker::BUILD_ID_LENGTH{ 8 };
    }
}
}

using namespace dsn::build_bot;

Worker::Worker(const std::string& build_directory,
               const std::string& repo_name,
               const std::string& url, const std::string& branch, const std::string& revision,
               const std::string& config_file, const std::string& profile_name)
    : m_impl(new priv::Worker(build_directory, repo_name, url, branch, revision, config_file, profile_name))
{
}

Worker::~Worker()
{
}

void Worker::run()
{
    return m_impl->run();
}
<commit_msg>Call git to checkout sources<commit_after>#include <build-bot/worker.h>

#include <boost/filesystem.hpp>
#include <boost/random/random_device.hpp>
#include <boost/random/uniform_int_distribution.hpp>

#include <boost/process.hpp>

namespace fs = boost::filesystem;

namespace dsn {
namespace build_bot {
    namespace priv {
        class Worker : public dsn::log::Base<Worker> {
        private:
            std::string m_url;
            std::string m_branch;
            std::string m_revision;
            std::string m_configFile;
            std::string m_profileName;
            std::string m_buildDir;
            std::string m_repoName;

            std::string generateBuildId()
            {
                std::string res;
                boost::random::random_device rng;
                boost::random::uniform_int_distribution<> dist(0, BUILD_ID_CHARS.size() - 1);

                for (size_t i = 0; i < BUILD_ID_LENGTH; i++)
                    res += BUILD_ID_CHARS[dist(rng)];

                return res;
            }

            std::string m_buildId;

            static const std::string BUILD_ID_CHARS;
            static const size_t BUILD_ID_LENGTH;

            std::string m_toplevelDirectory;

            bool initToplevelDirectory()
            {
                std::stringstream ss;
                ss << m_buildDir << "/" << m_profileName << "/" << m_repoName << "/" << m_buildId;
                m_toplevelDirectory = ss.str();
                fs::path path(m_toplevelDirectory);

                BOOST_LOG_SEV(log, severity::info) << "Toplevel build directory is " << m_toplevelDirectory;

                if (!fs::exists(path)) {
                    try {
                        fs::create_directories(path);
                    }

                    catch (boost::system::system_error& ex) {
                        BOOST_LOG_SEV(log, severity::error) << "Failed to create toplevel directory " << m_toplevelDirectory << ": " << ex.what();
                        return false;
                    }
                }

                return true;
            }

            std::string m_gitExecutable;
            bool findGitExecutable()
            {
                try {
                    m_gitExecutable = boost::process::search_path("git");
                }
                catch (std::runtime_error& ex) {
                    BOOST_LOG_SEV(log, severity::error) << "Failed to locate git executable in PATH: " << ex.what();
                    return false;
                }

                if (m_gitExecutable.size() == 0) {
                    BOOST_LOG_SEV(log, severity::error) << "No git executable found in PATH!";
                    return false;
                }

                BOOST_LOG_SEV(log, severity::debug) << "Using git executable from " << m_gitExecutable;
                return true;
            }

            std::string m_sourceDirectory;
            bool checkoutSources()
            {
                m_sourceDirectory = m_toplevelDirectory + "/repo";
                BOOST_LOG_SEV(log, severity::info) << "Checking out sources from " << m_url << " to " << m_sourceDirectory;

                try {
                    std::stringstream ssArgs;
                    ssArgs << m_gitExecutable << " clone -q --recursive -b " << m_branch << " " << m_url << " " << m_sourceDirectory;
                    std::string args = ssArgs.str();
                    BOOST_LOG_SEV(log, severity::debug) << "Git command line is " << args;

                    boost::process::child child = boost::process::execute(boost::process::initializers::run_exe(m_gitExecutable),
                                                                          boost::process::initializers::set_cmd_line(args));
                    auto exit_code = boost::process::wait_for_exit(child);

                    if (exit_code != 0) {
                        BOOST_LOG_SEV(log, severity::error) << "Got non-zero exit status from '" << args << "': " << exit_code;
                        return false;
                    }
                }

                catch (boost::system::system_error& ex) {
                    BOOST_LOG_SEV(log, severity::error) << "Failed to run git to check out sources: " << ex.what();
                    return false;
                }

                return true;
            }

        public:
            Worker(const std::string& build_directory,
                   const std::string& repo_name,
                   const std::string& url, const std::string& branch, const std::string& revision,
                   const std::string& config_file, const std::string& profile_name)
                : m_buildDir(build_directory)
                , m_url(url)
                , m_branch(branch)
                , m_revision(revision)
                , m_configFile(config_file)
                , m_profileName(profile_name)
                , m_repoName(repo_name)
            {
            }

            void run()
            {
                if (!findGitExecutable()) {
                    BOOST_LOG_SEV(log, severity::error) << "Failed to find git; build FAILED!";
                    return;
                }

                m_buildId = generateBuildId();
                BOOST_LOG_SEV(log, severity::info) << "Worker started for repo " << m_repoName
                                                   << " (profile: " << m_profileName << ", config: " << m_configFile << ") - Build ID: " << m_buildId;
                if (!initToplevelDirectory()) {
                    BOOST_LOG_SEV(log, severity::error) << "Unable to create build directory; build FAILED!";
                    return;
                }

                if (!checkoutSources()) {
                    BOOST_LOG_SEV(log, severity::error) << "Failed to checkout sources from " << m_url << "; build FAILED!";
                    return;
                }
            }
        };

        const std::string Worker::BUILD_ID_CHARS{ "0123456789abcdef" };
        const size_t Worker::BUILD_ID_LENGTH{ 8 };
    }
}
}

using namespace dsn::build_bot;

Worker::Worker(const std::string& build_directory,
               const std::string& repo_name,
               const std::string& url, const std::string& branch, const std::string& revision,
               const std::string& config_file, const std::string& profile_name)
    : m_impl(new priv::Worker(build_directory, repo_name, url, branch, revision, config_file, profile_name))
{
}

Worker::~Worker()
{
}

void Worker::run()
{
    return m_impl->run();
}
<|endoftext|>