<commit_before># pragma once
# include <Siv3D.hpp>

namespace asc
{
	using namespace s3d;

	/// <summary>
	/// 𑗎M\ TCPClient, TCPServer
	/// </summary>
	/// <remarks>
	/// M UTF-8 ōs܂B
	/// </remarks>
	template<class Socket>
	class TCPString : public Socket
	{
	public:

		/// <summary>
		/// 1 ǂݍ݂܂B
		/// </summary>
		/// <param name="to">
		/// ǂݍݐ
		/// </param>
		/// <returns>
		/// ǂݍ݂ɐ true
		/// </returns>
		/// <remarks>
		/// {Ȃǂ 1 oCgł͂Ȃ͐܂B
		/// </remarks>
		bool readChar(wchar& to)
		{
			std::string buffer;

			if (!lookahead(buffer[0]))
				return false;

			skip(sizeof(std::string::value_type));
			to = FromUTF8(std::move(buffer))[0];

			return true;
		}

		/// <summary>
		/// w肵ĕǂݍ݂܂B
		/// </summary>
		/// <param name="length">
		/// ǂݍޕ
		/// </param>
		/// <param name="to">
		/// ǂݍݐ
		/// </param>
		/// <returns>
		/// ǂݍ݂ɐ true
		/// </returns>
		/// <remarks>
		/// {Ȃǂ 1 oCgł͂Ȃ͐܂B
		/// </remarks>
		bool readString(size_t length, String& to)
		{
			std::string buffer;

			buffer.resize(length);

			if (!lookahead(&buffer[0], buffer.size()))
				return false;

			skip(sizeof(std::string::value_type) * buffer.size());
			to = FromUTF8(std::move(buffer));

			return true;
		}

		/// <summary>
		/// 1 sǂݍ݂܂B
		/// </summary>
		/// <param name="to">
		/// ǂݍݐ
		/// </param>
		/// <returns>
		/// ǂݍ݂ɐ true
		/// </returns>
		/// <remarks>
		/// {Ȃǂ 1 oCgł͂Ȃ܂B
		/// </remarks>
		/// <remarks>
		/// EEEsERE[EhEE LF EEgEpEEE܂�EB
		/// </remarks>
		bool readLine(String& to)
		{
			return readUntil('\n', to);
		}

		/// <summary>
		/// w肵܂œǂݍ݂܂B
		/// </summary>
		/// <param name="end">
		/// w肷镶
		/// </param>
		/// <param name="to">
		/// ǂݍݐ
		/// </param>
		/// <returns>
		/// ǂݍ݂ɐ true
		/// </returns>
		/// <remarks>
		/// {Ȃǂ 1 oCgł͂Ȃ܂B
		/// </remarks>
		bool readUntil(char end, String& to)
		{
			std::string buffer;

			buffer.resize(available());

			if (!lookahead(&buffer[0], buffer.size()))
				return false;

			const auto pos = buffer.find(end);

			if (pos == buffer.npos)
				return false;

			buffer.resize(pos + 1);

			skip(sizeof(std::string::value_type) * buffer.size());
			to = FromUTF8(std::move(buffer));

			return true;
		}

		/// <summary>
		/// w肵񂪗܂œǂݍ݂܂B
		/// </summary>
		/// <param name="end">
		/// w肷镶
		/// </param>
		/// <param name="to">
		/// ǂݍݐ
		/// </param>
		/// <returns>
		/// ǂݍ݂ɐ true
		/// </returns>
		/// <remarks>
		/// {Ȃǂ 1 oCgł͂Ȃ܂B
		/// </remarks>
		bool readUntil(const String& end, String& to)
		{
			const auto str = ToUTF8(end);

			std::string buffer;

			buffer.resize(available());

			if (!lookahead(&buffer[0], buffer.size()))
				return false;

			const auto pos = buffer.find(str);

			if (pos == buffer.npos)
				return false;

			buffer.resize(pos + str.size());

			skip(sizeof(std::string::value_type) * buffer.size());
			to = FromUTF8(std::move(buffer));

			return true;
		}

		/// <summary>
		/// \Ȍǂݍ݂܂B
		/// </summary>
		/// <param name="to">
		/// ǂݍݐ
		/// </param>
		/// <returns>
		/// 1 łǂݍ݂ɐ true
		/// </returns>
		/// <remarks>
		/// {Ȃǂ 1 oCgł͂Ȃ܂B
		/// </remarks>
		bool readAll(String& to)
		{
			if (!available())
				return false;

			std::string buffer;

			buffer.resize(available());

			if (!lookahead(&buffer[0], buffer.size()))
				return false;

			skip(sizeof(std::string::value_type) * buffer.size());
			to = FromUTF8(std::move(buffer));

			return true;
		}

		/// <summary>
		/// 𑗐M܂B
		/// </summary>
		/// <param name="data">
		/// M镶
		/// </param>
		/// <returns>
		/// Mɐ true
		/// </returns>
		/// <remarks>
		/// {Ȃǂ 1 oCgł͂Ȃ܂B
		/// </remarks>
		bool sendString(const String& data)
		{
			const auto str = ToUTF8(data);
			return send(str.data(), sizeof(decltype(str)::value_type) * str.length());
		}
	};

	using TCPStringClient = TCPString<TCPClient>;
	using TCPStringServer = TCPString<TCPServer>;
}
<commit_msg>Fix character encoding.<commit_after># pragma once
# include <Siv3D.hpp>

namespace asc
{
	using namespace s3d;

	/// <summary>
	/// 文字列を送受信可能な TCPClient, TCPServer
	/// </summary>
	/// <remarks>
	/// 送受信は UTF-8 で行います。
	/// </remarks>
	template<class Socket>
	class TCPString : public Socket
	{
	public:

		/// <summary>
		/// 1 文字読み込みます。
		/// </summary>
		/// <param name="to">
		/// 読み込み先
		/// </param>
		/// <returns>
		/// 読み込みに成功すれば true
		/// </returns>
		/// <remarks>
		/// 日本語などの 1 バイトではない文字は正しく扱えません。
		/// </remarks>
		bool readChar(wchar& to)
		{
			std::string buffer;

			if (!lookahead(buffer[0]))
				return false;

			skip(sizeof(std::string::value_type));
			to = FromUTF8(std::move(buffer))[0];

			return true;
		}

		/// <summary>
		/// 文字数を指定して文字列を読み込みます。
		/// </summary>
		/// <param name="length">
		/// 読み込む文字数
		/// </param>
		/// <param name="to">
		/// 読み込み先
		/// </param>
		/// <returns>
		/// 読み込みに成功すれば true
		/// </returns>
		/// <remarks>
		/// 日本語などの 1 バイトではない文字は正しく扱えません。
		/// </remarks>
		bool readString(size_t length, String& to)
		{
			std::string buffer;

			buffer.resize(length);

			if (!lookahead(&buffer[0], buffer.size()))
				return false;

			skip(sizeof(std::string::value_type) * buffer.size());
			to = FromUTF8(std::move(buffer));

			return true;
		}

		/// <summary>
		/// 1 行読み込みます。
		/// </summary>
		/// <param name="to">
		/// 読み込み先
		/// </param>
		/// <returns>
		/// 読み込みに成功すれば true
		/// </returns>
		/// <remarks>
		/// 日本語などの 1 バイトではない文字も扱えます。
		/// </remarks>
		/// <remarks>
		/// 改行コードは LF を使用します。
		/// </remarks>
		bool readLine(String& to)
		{
			return readUntil('\n', to);
		}

		/// <summary>
		/// 指定した文字が来るまで読み込みます。
		/// </summary>
		/// <param name="end">
		/// 指定する文字
		/// </param>
		/// <param name="to">
		/// 読み込み先
		/// </param>
		/// <returns>
		/// 読み込みに成功すれば true
		/// </returns>
		/// <remarks>
		/// 日本語などの 1 バイトではない文字も扱えます。
		/// </remarks>
		bool readUntil(char end, String& to)
		{
			std::string buffer;

			buffer.resize(available());

			if (!lookahead(&buffer[0], buffer.size()))
				return false;

			const auto pos = buffer.find(end);

			if (pos == buffer.npos)
				return false;

			buffer.resize(pos + 1);

			skip(sizeof(std::string::value_type) * buffer.size());
			to = FromUTF8(std::move(buffer));

			return true;
		}

		/// <summary>
		/// 指定した文字列が来るまで読み込みます。
		/// </summary>
		/// <param name="end">
		/// 指定する文字列
		/// </param>
		/// <param name="to">
		/// 読み込み先
		/// </param>
		/// <returns>
		/// 読み込みに成功すれば true
		/// </returns>
		/// <remarks>
		/// 日本語などの 1 バイトではない文字も扱えます。
		/// </remarks>
		bool readUntil(const String& end, String& to)
		{
			const auto str = ToUTF8(end);

			std::string buffer;

			buffer.resize(available());

			if (!lookahead(&buffer[0], buffer.size()))
				return false;

			const auto pos = buffer.find(str);

			if (pos == buffer.npos)
				return false;

			buffer.resize(pos + str.size());

			skip(sizeof(std::string::value_type) * buffer.size());
			to = FromUTF8(std::move(buffer));

			return true;
		}

		/// <summary>
		/// 文字を可能な限り読み込みます。
		/// </summary>
		/// <param name="to">
		/// 読み込み先
		/// </param>
		/// <returns>
		/// 1 文字でも読み込みに成功すれば true
		/// </returns>
		/// <remarks>
		/// 日本語などの 1 バイトではない文字も扱えます。
		/// </remarks>
		bool readAll(String& to)
		{
			if (!available())
				return false;

			std::string buffer;

			buffer.resize(available());

			if (!lookahead(&buffer[0], buffer.size()))
				return false;

			skip(sizeof(std::string::value_type) * buffer.size());
			to = FromUTF8(std::move(buffer));

			return true;
		}

		/// <summary>
		/// 文字列を送信します。
		/// </summary>
		/// <param name="data">
		/// 送信する文字列
		/// </param>
		/// <returns>
		/// 送信に成功すれば true
		/// </returns>
		/// <remarks>
		/// 日本語などの 1 バイトではない文字も扱えます。
		/// </remarks>
		bool sendString(const String& data)
		{
			const auto str = ToUTF8(data);
			return send(str.data(), sizeof(decltype(str)::value_type) * str.length());
		}
	};

	using TCPStringClient = TCPString<TCPClient>;
	using TCPStringServer = TCPString<TCPServer>;
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS aw035 (1.22.44); FILE MERGED 2006/07/12 15:29:52 aw 1.22.44.1: #126320# SdrMark::GetObj() -> SdrMark::GetSdrObjectFromSdrMark() for unique identification<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unnecessary includes<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS oasisbf2 (1.29.238); FILE MERGED 2004/11/04 15:30:30 dvo 1.29.238.1: #i31024# prevent headings with outline num-rules from being written as lists          (plus dependent changes for NO_NUM removal)<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS warnings01 (1.38.8); FILE MERGED 2006/05/23 17:16:56 sb 1.38.8.2: RESYNC: (1.38-1.39); FILE MERGED 2006/05/15 12:30:49 sb 1.38.8.1: #i53898# Made code warning-free and/or compile at all after resync to SRC680m162.<commit_after><|endoftext|>


<commit_before>/**
 *
 *  Graph
 *
 *  Undirected, weighted graph
 *  https://github.com/kdzlvaids/algorithm_and_practice-pknu-2016
 *
 */

#ifndef ALGORITHM_GRAPH_HPP_
#define ALGORITHM_GRAPH_HPP_ 1

/** Includes */
#include <cstddef>      /** size_t definition */
#include <vector>       /** Containers */
#include <map>          /** Containers */

namespace algorithm
{

/** Undirected, weighted graph class

    \note   Vertex deletion is not implemented
    \note   Edge deletion is not implemented
    \note   Cannot use double as WeightType
*/
template<
    class       ValueType,                            /**< Vertex value type; operator== should be defined */
    class       WeightType            = unsigned int, /**< Weight type */
    WeightType  WeightDefaultValue    = 0             /**< Default value of weight */
>
class Graph
{
public:
    typedef size_t                              SizeType;
    typedef std::map<const KeyType, WeightType> EdgeType;   /**< Edges of vertex
                                                                \param  KeyType     key_dest
                                                                \param  WeightType  weight
                                                            */

    /** Test if two keys are equal

        \return     Return true if two keys are equal; otherwise return false
        \param[in]  key_first       First key to compare
        \param[in]  key_second      Second key to compare
    */
    bool
    IsKeyEqual(const KeyType & key_first, const KeyType & key_second)
    const
    { return key_first == key_second; }

    /** Vertex class

        Each vertex has an array for its edges as a member.
    */
    struct VertexNode
    {
        const   KeyType             key;        /**< Key of vertex; same with index in graph_ */
                ValueType           value;      /**< Value of vertex */
                EdgeType            edges;
                //SizeType            edges_size; /**< Count of edges; forward_list not support size() function */

        /** Constructor */
        VertexNode(const KeyType & key, const ValueType & value)
        : key(key)
        , value(value)
        { }

        /** Test if two values are equal

            \return     Return true if two values are equal; otherwise return false
            \param[in]  value       Value to compare
        */
        bool
        IsValueEqual(const ValueType & value)
        const
        { return this->value == value; }
    };

protected:
    std::vector<VertexNode> graph_; /**< Graph */

public:
    /** Test whether there is an edge from the vertices src to dest

        \return     Return true if the edge exists; otherwise return false
        \param[in]  key_src         Key of source (src)
        \param[in]  key_dest        Key of destination (dest)
    */
    bool
    Adjacent(const KeyType & key_src, const KeyType & key_dest)
    {
        for(auto & edge : graph_.at(key_src)->edges)
        {
            if(IsKeyEqual(edge.first, key_dest) == true) /** Found */
                return true;
        }

        return false; /** Not found */
    }

    /** Add a vertex, if a graph not have the vertex with specified value already

        \return     Return the key of vertex if added successfully; otherwise return -1
        \param[in]  value_of_vertex     Value of vertex
    */
    KeyType
    AddVertex(const ValueType & value_of_vertex)
    {
        KeyType key_of_vertex = GetVertexKey(value_of_vertex);

        if(key_of_vertex == GetVertexCount()) /** Not found */
            graph_.push_back(VertexNode(key_of_vertex, value_of_vertex));

        return key_of_vertex;
    }

    /** Add an edge to connect two vertices

        \param[in]  key_src         Key of source (src)
        \param[in]  key_dest        Key of destination (dest)
        \param[in]  weight          Weight of the edge
    */
    void
    AddEdge(const KeyType & key_src, const KeyType & key_dest, const WeightType & weight = WeightDefaultValue)
    {
        graph_.at(key_src).edges.insert(
            std::make_pair<const KeyType, WeightType> (KeyType(key_dest), WeightType(weight))
        );
    }

    /** Get a key of the vertex with specified value from a graph

        If failed to add, return the size of graph which is an invalid key (maximum key + 1).

        \return     Return the key of vertex if added successfully; otherwise return the size of graph
        \param[in]  value_of_vertex     Value of vertex
    */
    KeyType
    GetVertexKey(const ValueType & value_of_vertex)
    {
        for(const VertexNode & vertex : graph_)
        {
            if(vertex.IsValueEqual(value_of_vertex) == true)
                return vertex.key;
        }

        return GetVertexCount();
    }

    /** Get a value of the vertex with specified key from a graph

        \return     Return the value
        \param[in]  key_of_vertex       Key of vertex
    */
    inline
    ValueType
    GetVertexValue(const KeyType & key_of_vertex)
    const
    { return graph_.at(key_of_vertex).value; }

    /** Set a value of the vertex with specified key from a graph

        \param[in]  key_of_vertex       Key of vertex
        \param[in]  value_of_vertex     Value of vertex
    */
    inline
    void
    SetVertexValue(const KeyType & key_of_vertex, const ValueType & value_of_vertex)
    { graph_.at(key_of_vertex).value = value_of_vertex; }

    /** Get a count of vertices

        \return     Count of vertices
    */
    inline
    SizeType
    GetVertexCount(void)
    const
    { return graph_.size(); }

    /** Get a count of edges

        \return     Count of edges
        \param[in]  key_of_vertex       Key of vertex
    */
    inline
    SizeType
    GetVertexEdgeCount(const KeyType & key_of_vertex)
    const
    { return graph_.at(key_of_vertex).edges.size(); }
};

} /** ns: algorithm */

#endif /** ! ALGORITHM_GRAPH_HPP_ */
<commit_msg>Add operation functions for graph<commit_after>/**
 *
 *  Graph
 *
 *  Undirected, weighted graph
 *  https://github.com/kdzlvaids/algorithm_and_practice-pknu-2016
 *
 */

#ifndef ALGORITHM_GRAPH_HPP_
#define ALGORITHM_GRAPH_HPP_ 1

/** Includes */
#include <cstddef>      /** size_t definition */
#include <vector>       /** Containers */
#include <map>          /** Containers */

namespace algorithm
{

/** Undirected, weighted graph class

    \note   Vertex deletion is not implemented
    \note   Edge deletion is not implemented
    \note   Cannot use double as WeightType
*/
template<
    class       ValueType,                                  /**< Vertex value type; operator== should be defined */
    class       WeightType          = unsigned int,         /**< Weight type */
    WeightType  WeightDefaultValue  = 0,                    /**< Default value of weight */
    class       KeyType             = unsigned int,         /**< Key type, used to access an array */
    class       KeyArrayType        = std::vector<KeyType>  /**< Array of Key type */
>
class Graph
{
public:
    typedef size_t                              SizeType;
    typedef std::map<const KeyType, WeightType> EdgeType;   /**< Edges of vertex
                                                                \param  KeyType     key_dest
                                                                \param  WeightType  weight
                                                            */

    /** Test if two keys are equal

        \return     Return true if two keys are equal; otherwise return false
        \param[in]  key_first       First key to compare
        \param[in]  key_second      Second key to compare
    */
    bool
    IsKeyEqual(const KeyType & key_first, const KeyType & key_second)
    const
    { return key_first == key_second; }

    /** Vertex class

        Each vertex has an array for its edges as a member.
    */
    struct VertexNode
    {
        const   KeyType             key;        /**< Key of vertex; same with index in graph_ */
                ValueType           value;      /**< Value of vertex */
                EdgeType            edges;
                //SizeType            edges_size; /**< Count of edges; forward_list not support size() function */

        /** Constructor */
        VertexNode(const KeyType & key, const ValueType & value)
        : key(key)
        , value(value)
        { }

        /** Test if two values are equal

            \return     Return true if two values are equal; otherwise return false
            \param[in]  value       Value to compare
        */
        bool
        IsValueEqual(const ValueType & value)
        const
        { return this->value == value; }
    };

protected:
    std::vector<VertexNode> graph_; /**< Graph */

public:
    /** Add a vertex, if a graph not have the vertex with specific value already

        \return     Return the key of vertex if added successfully; otherwise return -1
        \param[in]  value_of_vertex     Value of vertex
    */
    KeyType
    AddVertex(const ValueType & value_of_vertex)
    {
        KeyType key_of_vertex = GetVertexKey(value_of_vertex);

        if(key_of_vertex == CountOfVertices()) /** Not found */
            graph_.push_back(VertexNode(key_of_vertex, value_of_vertex));

        return key_of_vertex;
    }

    /** Add an edge to connect two vertices

        \param[in]  key_src         Key of source (src)
        \param[in]  key_dest        Key of destination (dest)
        \param[in]  weight          Weight of the edge
    */
    void
    AddEdge(const KeyType & key_src, const KeyType & key_dest, const WeightType & weight = WeightDefaultValue)
    {
        graph_.at(key_src).edges.insert(
            std::make_pair<const KeyType, WeightType> (KeyType(key_dest), WeightType(weight))
        );
    }

    /** Test whether the key of vertex less than its maximum bound

        \return     Return true if the vertex exists; otherwise return false
        \param[in]  key_of_vertex   Key of vertex
    */
    inline
    bool
    IsVertexExist(const KeyType & key_of_vertex)
    const
    {
        try
        { graph_.at(key_of_vertex); } /** .at() throws exception */
        catch(std::out_of_range & e)
        { return false; /** key_of_vertex is over the maximum bound */ }

        return true;
    }

    /** Test whether there is an edge from the vertices src to dest

        \return     Return true if the edge exists; otherwise return false
        \param[in]  key_src         Key of source (src)
        \param[in]  key_dest        Key of destination (dest)
    */
    inline
    bool
    IsEdgeExist(const KeyType & key_src, const KeyType & key_dest)
    const
    { return graph_.at(key_src).edges.find(key_dest) != graph_.at(key_src).edges.end(); }

    /** Get a key of the vertex with specific value

        If failed to add, return the size of graph which is an invalid key (maximum key + 1).

        \return     Return the key of vertex if added successfully; otherwise return the size of graph
        \param[in]  value_of_vertex     Value of vertex
    */
    KeyType
    GetVertexKey(const ValueType & value_of_vertex)
    {
        for(const VertexNode & vertex : graph_)
        {
            if(vertex.IsValueEqual(value_of_vertex) == true)
                return vertex.key;
        }

        return CountOfVertices();
    }

    /** Get a value of the vertex with specific key

        \return     Value of vertex
        \param[in]  key_of_vertex       Key of vertex
    */
    inline
    ValueType
    GetVertexValue(const KeyType & key_of_vertex)
    const
    { return graph_.at(key_of_vertex).value; }

    /** Set a value of the vertex with specific key

        \param[in]  key_of_vertex       Key of vertex
        \param[in]  value_of_vertex     Value of vertex
    */
    inline
    void
    SetVertexValue(const KeyType & key_of_vertex, const ValueType & value_of_vertex)
    { graph_.at(key_of_vertex).value = value_of_vertex; }

    /** Get a weight of the edge

        \return     Weight of edge
        \param[in]  key_src         Key of source (src)
        \param[in]  key_dest        Key of destination (dest)
    */
    inline
    WeightType
    GetEdgeWeight(const KeyType & key_src, const KeyType & key_dest)
    const
    { return graph_.at(key_src).edges.at(key_dest); }

    /** Set a weight of the edge

        \param[in]  key_src         Key of source (src)
        \param[in]  key_dest        Key of destination (dest)
        \param[in]  weight          Weight of edge
    */
    inline
    void
    SetEdgeWeight(const KeyType & key_src, const KeyType & key_dest, const WeightType & weight)
    { graph_.at(key_src).edges.at(key_dest) = weight; }

    /** Get a count of vertices

        \return     Count of vertices
    */
    inline
    SizeType
    CountOfVertices(void)
    const
    { return graph_.size(); }

    /** Get a count of edges

        \return     Count of edges
        \param[in]  key_of_vertex       Key of vertex
    */
    inline
    SizeType
    CountOfEdgeOfVertices(const KeyType & key_of_vertex)
    const
    { return graph_.at(key_of_vertex).edges.size(); }

    /** Get the list of edges

        \return     Size of list
        \param[out] out_edges       List of edges
        \param[in]  key_of_vertex   Key of vertex
    */
    SizeType
    ListOfEdges(KeyArrayType & out_edges, const KeyType & key_of_vertex)
    {
        out_edges.clear();

        for(auto & edge : graph_.at(key_of_vertex).edges)
            out_edges.push_back(edge);

        return out_edges.size();
    }
};

} /** ns: algorithm */

#endif /** ! ALGORITHM_GRAPH_HPP_ */
<|endoftext|>


<commit_before>#include "tests-base.hpp"

#include "utf8rewind.h"

TEST(DecodeUtf16, Character)
{
	const char* i = "\xE0\xA4\x9C";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(2, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0x091C, o[0]);
}

TEST(DecodeUtf16, String)
{
	const char* i = "\xE0\xA4\x9C\xE0\xA4\xA1\xE0\xA4\xA4";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(6, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0x091C, o[0]);
	EXPECT_EQ(0x0921, o[1]);
	EXPECT_EQ(0x0924, o[2]);
}

TEST(DecodeUtf16, SurrogatePair)
{
	const char* i = "\xF0\x9F\x98\xA4";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(4, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0xD83D, o[0]);
	EXPECT_EQ(0xDE24, o[1]);
}<commit_msg>suite-decodeutf16: Added missing tests for different encoding lengths.<commit_after>#include "tests-base.hpp"

#include "utf8rewind.h"

TEST(DecodeUtf16, Character)
{
	const char* i = "\xE0\xA4\x9C";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(2, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0x091C, o[0]);
}

TEST(DecodeUtf16, String)
{
	const char* i = "\xE0\xA4\x9C\xE0\xA4\xA1\xE0\xA4\xA4";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(6, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0x091C, o[0]);
	EXPECT_EQ(0x0921, o[1]);
	EXPECT_EQ(0x0924, o[2]);
}

TEST(DecodeUtf16, Ascii)
{
	const char* i = "k";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(2, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ('k', o[0]);
}

TEST(DecodeUtf16, AsciiFirst)
{
	const char* i = "\0";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(0, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(UTF8_ERR_INVALID_DATA, errors);
	EXPECT_EQ(0x0000, o[0]);
}

TEST(DecodeUtf16, AsciiLast)
{
	const char* i = "\x7F";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(2, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0x007F, o[0]);
}

TEST(DecodeUtf16, AsciiInvalid)
{
	const char* i = "\x97";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(0, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(UTF8_ERR_INVALID_CHARACTER, errors);
	EXPECT_EQ(0x0000, o[0]);
}

TEST(DecodeUtf16, TwoBytes)
{
	const char* i = "\xC5\xA9";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(2, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0x0169, o[0]);
}

TEST(DecodeUtf16, TwoBytesFirst)
{
	const char* i = "\xC2\x80";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(2, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0x0080, o[0]);
}

TEST(DecodeUtf16, TwoBytesLast)
{
	const char* i = "\xDF\xBF";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(2, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0x07FF, o[0]);
}

TEST(DecodeUtf16, TwoBytesNotEnoughData)
{
	const char* i = "\xDA";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(0, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(UTF8_ERR_INVALID_DATA, errors);
	EXPECT_EQ(0x0000, o[0]);
}

TEST(DecodeUtf16, ThreeBytes)
{
	const char* i = "\xE1\x8C\x8A";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(2, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0x130A, o[0]);
}

TEST(DecodeUtf16, ThreeBytesFirst)
{
	const char* i = "\xE0\xA0\x80";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(2, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0x0800, o[0]);
}

TEST(DecodeUtf16, ThreeBytesLast)
{
	const char* i = "\xEF\xBF\xBF";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(2, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0xFFFF, o[0]);
}

TEST(DecodeUtf16, ThreeBytesNotEnoughData)
{
	const char* i = "\xEF\xA9";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(0, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(UTF8_ERR_INVALID_DATA, errors);
	EXPECT_EQ(0x0000, o[0]);
}

TEST(DecodeUtf16, SurrogatePair)
{
	const char* i = "\xF0\x9F\x98\xA4";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(4, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0xD83D, o[0]);
	EXPECT_EQ(0xDE24, o[1]);
}

TEST(DecodeUtf16, SurrogatePairFirst)
{
	const char* i = "\xF0\x90\x80\x80";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(4, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0xD800, o[0]);
	EXPECT_EQ(0xDC00, o[1]);
}

TEST(DecodeUtf16, SurrogatePairLast)
{
	const char* i = "\xF4\x8F\xBF\xBF";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(4, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(0, errors);
	EXPECT_EQ(0xDBFF, o[0]);
	EXPECT_EQ(0xDFFF, o[1]);
}

TEST(DecodeUtf16, SurrogatePairNotEnoughData)
{
	const char* i = "\xF0\x9F\x98";
	const size_t s = 256;
	utf16_t o[s] = { 0 };
	int32_t errors = 0;

	EXPECT_EQ(0, utf8decodeutf16(i, strlen(i), o, s, &errors));
	EXPECT_EQ(UTF8_ERR_INVALID_DATA, errors);
	EXPECT_EQ(0x0000, o[0]);
}<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "RawImage.h"
#include "RawDecoder.h"  // For exceptions
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    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 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

    http://www.klauspost.com
*/
#if defined(__SSE2__)
#include <emmintrin.h>
#endif

namespace RawSpeed {

RawImageData::RawImageData(void):
    dim(0, 0), bpp(0), isCFA(true),
    blackLevel(-1), whitePoint(65536),
    dataRefCount(0), data(0), cpp(1) {
  pthread_mutex_init(&mymutex, NULL);
  subsampling.x = subsampling.y = 1;
}

RawImageData::RawImageData(iPoint2D _dim, uint32 _bpc, uint32 _cpp) :
    dim(_dim), bpp(_bpc),
    blackLevel(-1), whitePoint(65536),
    dataRefCount(0), data(0), cpp(cpp) {
  subsampling.x = subsampling.y = 1;
  createData();
  pthread_mutex_init(&mymutex, NULL);
}

RawImageData::~RawImageData(void) {
  _ASSERTE(dataRefCount == 0);
  if (data)
    _aligned_free(data);
  data = 0;
  mOffset = iPoint2D(0, 0);
  pthread_mutex_destroy(&mymutex);
}

void RawImageData::createData() {
  if (dim.x > 65535 || dim.y > 65535)
    ThrowRDE("RawImageData: Dimensions too large for allocation.");
  if (dim.x <= 0 || dim.y <= 0)
    ThrowRDE("RawImageData: Dimension of one sides is less than 1 - cannot allocate image.");
  if (data)
    ThrowRDE("RawImageData: Duplicate data allocation in createData.");
  pitch = (((dim.x * bpp) + 15) / 16) * 16;
  data = (uchar8*)_aligned_malloc(pitch * dim.y, 16);
  if (!data)
    ThrowRDE("RawImageData::createData: Memory Allocation failed.");
}

void RawImageData::destroyData() {
  if (data)
    _aligned_free(data);
  data = 0;
}

void RawImageData::setCpp(uint32 val) {
  if (data)
    ThrowRDE("RawImageData: Attempted to set Components per pixel after data allocation");
  if (val > 4)
    ThrowRDE("RawImageData: Only up to 4 components per pixel is support - attempted to set: %d", val);
  bpp /= cpp;
  cpp = val;
  bpp *= val;
}

uchar8* RawImageData::getData() {
  if (!data)
    ThrowRDE("RawImageData::getData - Data not yet allocated.");
  return &data[mOffset.y*pitch+mOffset.x*bpp];
}

uchar8* RawImageData::getData(uint32 x, uint32 y) {
  if ((int)x >= dim.x)
    ThrowRDE("RawImageData::getData - X Position outside image requested.");
  if ((int)y >= dim.y) {
    ThrowRDE("RawImageData::getData - Y Position outside image requested.");
  }

  x += mOffset.x;
  y += mOffset.y;

  if (!data)
    ThrowRDE("RawImageData::getData - Data not yet allocated.");

  return &data[y*pitch+x*bpp];
}

void RawImageData::subFrame(iPoint2D offset, iPoint2D new_size) {
  if (!new_size.isThisInside(dim - offset)) {
    printf("WARNING: RawImageData::subFrame - Attempted to create new subframe larger than original size. Crop skipped.\n");
    return;
  }

  mOffset += offset;
  dim = new_size;
}

void RawImageData::scaleBlackWhite() {
  int gw = (dim.x - 20) * cpp;
  if (blackLevel < 0 || whitePoint == 65536) {  // Estimate
    int b = 65536;
    int m = 0;
    for (int row = 10;row < (dim.y - 10);row++) {
      ushort16 *pixel = (ushort16*)getData(10, row);
      for (int col = 10 ; col < gw ; col++) {
        b = MIN(*pixel, b);
        m = MAX(*pixel, m);
        pixel++;
      }
    }
    if (blackLevel < 0)
      blackLevel = b;
    if (whitePoint == 65536)
      whitePoint = m;
    printf("Estimated black:%d, Estimated white: %d\n", blackLevel, whitePoint);
  }
  float f = 65535.0f / (float)(whitePoint - blackLevel);
  scaleValues(f);
}

#if _MSC_VER > 1399 || defined(__SSE2__)

void RawImageData::scaleValues(float f) {
  bool use_sse2;
#ifdef _MSC_VER
  int info[4];
  __cpuid(info, 1);
  use_sse2 = !!(info[3]&(1 << 26));
#else
  use_sse2 = TRUE;
#endif

  // Check SSE2
  if (f >= 0.0f && use_sse2) {

    __m128i ssescale;
    __m128i ssesub;
    __m128i sseround;
    __m128i ssesub2;
    __m128i ssesign;
    uint32 gw = pitch / 16;
    uint32 i = (int)(1024.0f * f);  // 10 bit fraction
    i |= i << 16;
    uint32 b = blackLevel | (blackLevel << 16);

    ssescale = _mm_set_epi32(i, i, i, i);
    ssesub = _mm_set_epi32(b, b, b, b);
    sseround = _mm_set_epi32(512, 512, 512, 512);
    ssesub2 = _mm_set_epi32(32768, 32768, 32768, 32768);
    ssesign = _mm_set_epi32(0x80008000, 0x80008000, 0x80008000, 0x80008000);

    for (int y = 0; y < dim.y; y++) {
      __m128i* pixel = (__m128i*) & data[(mOffset.y+y)*pitch];
      for (uint32 x = 0 ; x < gw; x++) {
        __m128i pix_high;
        __m128i temp;
        __m128i pix_low = _mm_load_si128(pixel);
        // Subtract black
        pix_low = _mm_subs_epu16(pix_low, ssesub);
        // Multiply the two unsigned shorts and combine it to 32 bit result
        pix_high = _mm_mulhi_epu16(pix_low, ssescale);
        temp = _mm_mullo_epi16(pix_low, ssescale);
        pix_low = _mm_unpacklo_epi16(temp, pix_high);
        pix_high = _mm_unpackhi_epi16(temp, pix_high);
        // Add rounder
        pix_low = _mm_add_epi32(pix_low, sseround);
        pix_high = _mm_add_epi32(pix_high, sseround);
        // Shift down
        pix_low = _mm_srai_epi32(pix_low, 10);
        pix_high = _mm_srai_epi32(pix_high, 10);
        // Subtract to avoid clipping
        pix_low = _mm_sub_epi32(pix_low, ssesub2);
        pix_high = _mm_sub_epi32(pix_high, ssesub2);
        // Pack
        pix_low = _mm_packs_epi32(pix_low, pix_high);
        // Shift sign off
        pix_low = _mm_xor_si128(pix_low, ssesign);
        _mm_store_si128(pixel, pix_low);
        pixel++;
      }
    }
  } else {
    // Not SSE2
    int gw = dim.x * cpp;
    int scale = (int)(16384.0f * f);  // 14 bit fraction
    for (int y = 0; y < dim.y; y++) {
      ushort16 *pixel = (ushort16*)getData(0, y);
      for (int x = 0 ; x < gw; x++) {
        pixel[x] = clampbits(((pixel[x] - blackLevel) * scale + 8192) >> 14, 16);
      }
    }
  }
}

#else

void RawImageData::scaleValues(float f) {
  int gw = dim.x * cpp;
  int scale = (int)(16384.0f * f);  // 14 bit fraction
  for (int y = 0; y < dim.y; y++) {
    ushort16 *pixel = (ushort16*)getData(0, y);
    for (int x = 0 ; x < gw; x++) {
      pixel[x] = clampbits(((pixel[x] - blackLevel) * scale + 8192) >> 14, 16);
    }
  }
}

#endif

RawImage::RawImage(RawImageData* p) : p_(p) {
  pthread_mutex_lock(&p_->mymutex);
  ++p_->dataRefCount;
  pthread_mutex_unlock(&p_->mymutex);
}

RawImage::RawImage(const RawImage& p) : p_(p.p_) {
  pthread_mutex_lock(&p_->mymutex);
  ++p_->dataRefCount;
  pthread_mutex_unlock(&p_->mymutex);
}

RawImage::~RawImage() {
  pthread_mutex_lock(&p_->mymutex);
  if (--p_->dataRefCount == 0) {
    pthread_mutex_unlock(&p_->mymutex);
    delete p_;
    return;
  }
  pthread_mutex_unlock(&p_->mymutex);
}

RawImageData* RawImage::operator->() {
  return p_;
}

RawImageData& RawImage::operator*() {
  return *p_;
}

RawImage& RawImage::operator=(const RawImage & p) {
  RawImageData* const old = p_;
  p_ = p.p_;
  ++p_->dataRefCount;
  if (--old->dataRefCount == 0) delete old;
  return *this;
}

} // namespace RawSpeed
<commit_msg>Use larger border when estimating black/white, and check result.<commit_after>#include "StdAfx.h"
#include "RawImage.h"
#include "RawDecoder.h"  // For exceptions
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    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 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

    http://www.klauspost.com
*/
#if defined(__SSE2__)
#include <emmintrin.h>
#endif

namespace RawSpeed {

RawImageData::RawImageData(void):
    dim(0, 0), bpp(0), isCFA(true),
    blackLevel(-1), whitePoint(65536),
    dataRefCount(0), data(0), cpp(1) {
  pthread_mutex_init(&mymutex, NULL);
  subsampling.x = subsampling.y = 1;
}

RawImageData::RawImageData(iPoint2D _dim, uint32 _bpc, uint32 _cpp) :
    dim(_dim), bpp(_bpc),
    blackLevel(-1), whitePoint(65536),
    dataRefCount(0), data(0), cpp(cpp) {
  subsampling.x = subsampling.y = 1;
  createData();
  pthread_mutex_init(&mymutex, NULL);
}

RawImageData::~RawImageData(void) {
  _ASSERTE(dataRefCount == 0);
  if (data)
    _aligned_free(data);
  data = 0;
  mOffset = iPoint2D(0, 0);
  pthread_mutex_destroy(&mymutex);
}

void RawImageData::createData() {
  if (dim.x > 65535 || dim.y > 65535)
    ThrowRDE("RawImageData: Dimensions too large for allocation.");
  if (dim.x <= 0 || dim.y <= 0)
    ThrowRDE("RawImageData: Dimension of one sides is less than 1 - cannot allocate image.");
  if (data)
    ThrowRDE("RawImageData: Duplicate data allocation in createData.");
  pitch = (((dim.x * bpp) + 15) / 16) * 16;
  data = (uchar8*)_aligned_malloc(pitch * dim.y, 16);
  if (!data)
    ThrowRDE("RawImageData::createData: Memory Allocation failed.");
}

void RawImageData::destroyData() {
  if (data)
    _aligned_free(data);
  data = 0;
}

void RawImageData::setCpp(uint32 val) {
  if (data)
    ThrowRDE("RawImageData: Attempted to set Components per pixel after data allocation");
  if (val > 4)
    ThrowRDE("RawImageData: Only up to 4 components per pixel is support - attempted to set: %d", val);
  bpp /= cpp;
  cpp = val;
  bpp *= val;
}

uchar8* RawImageData::getData() {
  if (!data)
    ThrowRDE("RawImageData::getData - Data not yet allocated.");
  return &data[mOffset.y*pitch+mOffset.x*bpp];
}

uchar8* RawImageData::getData(uint32 x, uint32 y) {
  if ((int)x >= dim.x)
    ThrowRDE("RawImageData::getData - X Position outside image requested.");
  if ((int)y >= dim.y) {
    ThrowRDE("RawImageData::getData - Y Position outside image requested.");
  }

  x += mOffset.x;
  y += mOffset.y;

  if (!data)
    ThrowRDE("RawImageData::getData - Data not yet allocated.");

  return &data[y*pitch+x*bpp];
}

void RawImageData::subFrame(iPoint2D offset, iPoint2D new_size) {
  if (!new_size.isThisInside(dim - offset)) {
    printf("WARNING: RawImageData::subFrame - Attempted to create new subframe larger than original size. Crop skipped.\n");
    return;
  }

  mOffset += offset;
  dim = new_size;
}

void RawImageData::scaleBlackWhite() {
  const int skipBorder = 100;
  int gw = (dim.x - skipBorder*2) * cpp;
  if (blackLevel < 0 || whitePoint == 65536) {  // Estimate
    int b = 65536;
    int m = 0;
    for (int row = skipBorder;row < (dim.y - skipBorder);row++) {
      ushort16 *pixel = (ushort16*)getData(skipBorder, row);
      for (int col = skipBorder ; col < gw ; col++) {
        b = MIN(*pixel, b);
        m = MAX(*pixel, m);
        pixel++;
      }
    }
    if (blackLevel < 0)
      blackLevel = b;
    if (whitePoint == 65536)
      whitePoint = m;
    printf("Estimated black:%d, Estimated white: %d\n", blackLevel, whitePoint);
  }

  if (whitePoint <= blackLevel) {
    printf("WARNING: RawImageData::scaleBlackWhite - Unable to estimate Black/White level, skipping scaling.\n");
    return;
  }

  float f = 65535.0f / (float)(whitePoint - blackLevel);
  scaleValues(f);
}

#if _MSC_VER > 1399 || defined(__SSE2__)

void RawImageData::scaleValues(float f) {
  bool use_sse2;
#ifdef _MSC_VER
  int info[4];
  __cpuid(info, 1);
  use_sse2 = !!(info[3]&(1 << 26));
#else
  use_sse2 = TRUE;
#endif

  // Check SSE2
  if (f >= 0.0f && use_sse2) {

    __m128i ssescale;
    __m128i ssesub;
    __m128i sseround;
    __m128i ssesub2;
    __m128i ssesign;
    uint32 gw = pitch / 16;
    uint32 i = (int)(1024.0f * f);  // 10 bit fraction
    i |= i << 16;
    uint32 b = blackLevel | (blackLevel << 16);

    ssescale = _mm_set_epi32(i, i, i, i);
    ssesub = _mm_set_epi32(b, b, b, b);
    sseround = _mm_set_epi32(512, 512, 512, 512);
    ssesub2 = _mm_set_epi32(32768, 32768, 32768, 32768);
    ssesign = _mm_set_epi32(0x80008000, 0x80008000, 0x80008000, 0x80008000);

    for (int y = 0; y < dim.y; y++) {
      __m128i* pixel = (__m128i*) & data[(mOffset.y+y)*pitch];
      for (uint32 x = 0 ; x < gw; x++) {
        __m128i pix_high;
        __m128i temp;
        __m128i pix_low = _mm_load_si128(pixel);
        // Subtract black
        pix_low = _mm_subs_epu16(pix_low, ssesub);
        // Multiply the two unsigned shorts and combine it to 32 bit result
        pix_high = _mm_mulhi_epu16(pix_low, ssescale);
        temp = _mm_mullo_epi16(pix_low, ssescale);
        pix_low = _mm_unpacklo_epi16(temp, pix_high);
        pix_high = _mm_unpackhi_epi16(temp, pix_high);
        // Add rounder
        pix_low = _mm_add_epi32(pix_low, sseround);
        pix_high = _mm_add_epi32(pix_high, sseround);
        // Shift down
        pix_low = _mm_srai_epi32(pix_low, 10);
        pix_high = _mm_srai_epi32(pix_high, 10);
        // Subtract to avoid clipping
        pix_low = _mm_sub_epi32(pix_low, ssesub2);
        pix_high = _mm_sub_epi32(pix_high, ssesub2);
        // Pack
        pix_low = _mm_packs_epi32(pix_low, pix_high);
        // Shift sign off
        pix_low = _mm_xor_si128(pix_low, ssesign);
        _mm_store_si128(pixel, pix_low);
        pixel++;
      }
    }
  } else {
    // Not SSE2
    int gw = dim.x * cpp;
    int scale = (int)(16384.0f * f);  // 14 bit fraction
    for (int y = 0; y < dim.y; y++) {
      ushort16 *pixel = (ushort16*)getData(0, y);
      for (int x = 0 ; x < gw; x++) {
        pixel[x] = clampbits(((pixel[x] - blackLevel) * scale + 8192) >> 14, 16);
      }
    }
  }
}

#else

void RawImageData::scaleValues(float f) {
  int gw = dim.x * cpp;
  int scale = (int)(16384.0f * f);  // 14 bit fraction
  for (int y = 0; y < dim.y; y++) {
    ushort16 *pixel = (ushort16*)getData(0, y);
    for (int x = 0 ; x < gw; x++) {
      pixel[x] = clampbits(((pixel[x] - blackLevel) * scale + 8192) >> 14, 16);
    }
  }
}

#endif

RawImage::RawImage(RawImageData* p) : p_(p) {
  pthread_mutex_lock(&p_->mymutex);
  ++p_->dataRefCount;
  pthread_mutex_unlock(&p_->mymutex);
}

RawImage::RawImage(const RawImage& p) : p_(p.p_) {
  pthread_mutex_lock(&p_->mymutex);
  ++p_->dataRefCount;
  pthread_mutex_unlock(&p_->mymutex);
}

RawImage::~RawImage() {
  pthread_mutex_lock(&p_->mymutex);
  if (--p_->dataRefCount == 0) {
    pthread_mutex_unlock(&p_->mymutex);
    delete p_;
    return;
  }
  pthread_mutex_unlock(&p_->mymutex);
}

RawImageData* RawImage::operator->() {
  return p_;
}

RawImageData& RawImage::operator*() {
  return *p_;
}

RawImage& RawImage::operator=(const RawImage & p) {
  RawImageData* const old = p_;
  p_ = p.p_;
  ++p_->dataRefCount;
  if (--old->dataRefCount == 0) delete old;
  return *this;
}

} // namespace RawSpeed
<|endoftext|>


<commit_before>/**
 *  @file
 *  @copyright defined in eos/LICENSE
 */
#pragma once
// #include <eosio/chain/config.hpp>
#include <eosio/chain/database_utils.hpp>

#include <eosio/chain/transaction.hpp>
#include <fc/uint128.hpp>

#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/mem_fun.hpp>

#include "multi_index_includes.hpp"

namespace eosio { namespace chain {
   using boost::multi_index_container;
   using namespace boost::multi_index;
   /**
    * The purpose of this object is to store transactions generated by processing the
    * transactions included in the chain.  These transactions should be treated like
    * authentic/valid SignedTransactions for the purposes of scheduling transactions
    * in to new blocks
    */
   class generated_transaction_object : public chainbase::object<generated_transaction_object_type, generated_transaction_object>
   {
         OBJECT_CTOR(generated_transaction_object, (packed_trx) )

         id_type                       id;
         transaction_id_type           trx_id;
         account_name                  sender;
         uint128_t                     sender_id = 0; /// ID given this transaction by the sender
         account_name                  payer;
         time_point                    delay_until; /// this generated transaction will not be applied until the specified time
         time_point                    expiration; /// this generated transaction will not be applied after this time
         time_point                    published;
         shared_blob                   packed_trx;

         uint32_t set( const transaction& trx ) {
            auto trxsize = fc::raw::pack_size( trx );
            packed_trx.resize( trxsize );
            fc::datastream<char*> ds( packed_trx.data(), trxsize );
            fc::raw::pack( ds, trx );
            return trxsize;
         }
   };

   struct by_trx_id;
   struct by_expiration;
   struct by_delay;
   struct by_status;
   struct by_sender_id;

   using generated_transaction_multi_index = chainbase::shared_multi_index_container<
      generated_transaction_object,
      indexed_by<
         ordered_unique< tag<by_id>, BOOST_MULTI_INDEX_MEMBER(generated_transaction_object, generated_transaction_object::id_type, id)>,
         ordered_unique< tag<by_trx_id>, BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, transaction_id_type, trx_id)>,
         ordered_unique< tag<by_expiration>,
            composite_key< generated_transaction_object,
               BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, time_point, expiration),
               BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, generated_transaction_object::id_type, id)
            >
         >,
         ordered_unique< tag<by_delay>,
            composite_key< generated_transaction_object,
               BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, time_point, delay_until),
               BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, generated_transaction_object::id_type, id)
            >
         >,
         ordered_unique< tag<by_sender_id>,
            composite_key< generated_transaction_object,
               BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, account_name, sender),
               BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, uint128_t, sender_id)
            >
         >
      >
   >;

   class generated_transaction
   {
      public:
         generated_transaction(const generated_transaction_object& gto)
         :trx_id(gto.trx_id)
         ,sender(gto.sender)
         ,sender_id(gto.sender_id)
         ,payer(gto.payer)
         ,delay_until(gto.delay_until)
         ,expiration(gto.expiration)
         ,published(gto.published)
         ,packed_trx(gto.packed_trx.begin(), gto.packed_trx.end())
         {}

         generated_transaction(const generated_transaction& gt) = default;
         generated_transaction(generated_transaction&& gt) = default;

         transaction_id_type           trx_id;
         account_name                  sender;
         uint128_t                     sender_id;
         account_name                  payer;
         time_point                    delay_until; /// this generated transaction will not be applied until the specified time
         time_point                    expiration; /// this generated transaction will not be applied after this time
         time_point                    published;
         vector<char>                  packed_trx;

   };

   namespace config {
      template<>
      struct billable_size<generated_transaction_object> {
         static const uint64_t overhead = overhead_per_row_per_index_ram_bytes * 5;  ///< overhead for 5x indices internal-key, txid, expiration, delay, sender_id
         static const uint64_t value = 96 + 4 + overhead; ///< 96 bytes for our constant size fields, 4 bytes for a varint for packed_trx size and 96 bytes of implementation overhead
      };
   }
} } // eosio::chain

CHAINBASE_SET_INDEX_TYPE(eosio::chain::generated_transaction_object, eosio::chain::generated_transaction_multi_index)

FC_REFLECT(eosio::chain::generated_transaction_object, (trx_id)(sender)(sender_id)(payer)(delay_until)(expiration)(published)(packed_trx))
<commit_msg>Quick test for buildkite<commit_after>/**
 *  @file
 *  @copyright defined in eos/LICENSE
 */
#pragma once
#include <eosio/chain/config.hpp>
#include <eosio/chain/database_utils.hpp>

#include <eosio/chain/transaction.hpp>
#include <fc/uint128.hpp>

#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/mem_fun.hpp>

#include "multi_index_includes.hpp"

namespace eosio { namespace chain {
   using boost::multi_index_container;
   using namespace boost::multi_index;
   /**
    * The purpose of this object is to store transactions generated by processing the
    * transactions included in the chain.  These transactions should be treated like
    * authentic/valid SignedTransactions for the purposes of scheduling transactions
    * in to new blocks
    */
   class generated_transaction_object : public chainbase::object<generated_transaction_object_type, generated_transaction_object>
   {
         OBJECT_CTOR(generated_transaction_object, (packed_trx) )

         id_type                       id;
         transaction_id_type           trx_id;
         account_name                  sender;
         uint128_t                     sender_id = 0; /// ID given this transaction by the sender
         account_name                  payer;
         time_point                    delay_until; /// this generated transaction will not be applied until the specified time
         time_point                    expiration; /// this generated transaction will not be applied after this time
         time_point                    published;
         shared_blob                   packed_trx;

         uint32_t set( const transaction& trx ) {
            auto trxsize = fc::raw::pack_size( trx );
            packed_trx.resize( trxsize );
            fc::datastream<char*> ds( packed_trx.data(), trxsize );
            fc::raw::pack( ds, trx );
            return trxsize;
         }
   };

   struct by_trx_id;
   struct by_expiration;
   struct by_delay;
   struct by_status;
   struct by_sender_id;

   using generated_transaction_multi_index = chainbase::shared_multi_index_container<
      generated_transaction_object,
      indexed_by<
         ordered_unique< tag<by_id>, BOOST_MULTI_INDEX_MEMBER(generated_transaction_object, generated_transaction_object::id_type, id)>,
         ordered_unique< tag<by_trx_id>, BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, transaction_id_type, trx_id)>,
         ordered_unique< tag<by_expiration>,
            composite_key< generated_transaction_object,
               BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, time_point, expiration),
               BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, generated_transaction_object::id_type, id)
            >
         >,
         ordered_unique< tag<by_delay>,
            composite_key< generated_transaction_object,
               BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, time_point, delay_until),
               BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, generated_transaction_object::id_type, id)
            >
         >,
         ordered_unique< tag<by_sender_id>,
            composite_key< generated_transaction_object,
               BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, account_name, sender),
               BOOST_MULTI_INDEX_MEMBER( generated_transaction_object, uint128_t, sender_id)
            >
         >
      >
   >;

   class generated_transaction
   {
      public:
         generated_transaction(const generated_transaction_object& gto)
         :trx_id(gto.trx_id)
         ,sender(gto.sender)
         ,sender_id(gto.sender_id)
         ,payer(gto.payer)
         ,delay_until(gto.delay_until)
         ,expiration(gto.expiration)
         ,published(gto.published)
         ,packed_trx(gto.packed_trx.begin(), gto.packed_trx.end())
         {}

         generated_transaction(const generated_transaction& gt) = default;
         generated_transaction(generated_transaction&& gt) = default;

         transaction_id_type           trx_id;
         account_name                  sender;
         uint128_t                     sender_id;
         account_name                  payer;
         time_point                    delay_until; /// this generated transaction will not be applied until the specified time
         time_point                    expiration; /// this generated transaction will not be applied after this time
         time_point                    published;
         vector<char>                  packed_trx;

   };

   namespace config {
      template<>
      struct billable_size<generated_transaction_object> {
         static const uint64_t overhead = overhead_per_row_per_index_ram_bytes * 5;  ///< overhead for 5x indices internal-key, txid, expiration, delay, sender_id
         static const uint64_t value = 96 + 4 + overhead; ///< 96 bytes for our constant size fields, 4 bytes for a varint for packed_trx size and 96 bytes of implementation overhead
      };
   }
} } // eosio::chain

CHAINBASE_SET_INDEX_TYPE(eosio::chain::generated_transaction_object, eosio::chain::generated_transaction_multi_index)

FC_REFLECT(eosio::chain::generated_transaction_object, (trx_id)(sender)(sender_id)(payer)(delay_until)(expiration)(published)(packed_trx))
<|endoftext|>


<commit_before>#include <GL/freeglut.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <GL/gl.h>
#include <stdlib.h>
#define PI 3.1415926535898

float w_width=700.0,w_height=700.0;
float x=0.0,y=0.0;
int s;
int r;
float xball=350.0,yball=350.0,a=1.0,b=1.0;

float speed[5]={0.1,0.15,0.18,0.22,0.25};
int level=0;

float xver,yver;
int target[700][700];
int font=0;
int flag=1;
int score=0;
int play=1;

char sc[4];

void init(void)
{
glClearColor(1.0,1.0,1.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(1,700,1,700,-1,1);
}

//::::::::::::::::TEXT FUNCTION:::::::::::::://
void drawBitmapText(const char *string,float x,float y,float z)
{
    const char *c;
    glRasterPos3f(x,y,z);

    for (c=string; *c != '\0'; c++)
    {
      if(font==0)
        glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, *c);
      else if(font==1)
        glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, *c);
      else if(font==2)
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, *c);
      else if(font==3)
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *c);
      else if(font==4)
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
      else if(font==5)
        glutBitmapCharacter(GLUT_BITMAP_8_BY_13, *c);
      else if(font==6)
        glutBitmapCharacter(GLUT_BITMAP_9_BY_15, *c);

    }
}

//::::::::::::::::Display Function::::::::::://
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);

//:::::::::::Ball:::::::::::://
glColor3f(0.0,0.0,1.0);
GLint circle_points=100,i;
GLfloat angle;
glBegin(GL_POLYGON);
for(i=0;i<circle_points;i++)
  {
    angle=2*PI*i/circle_points;
    xver=xball+w_width*cos(angle)/35;
    yver=yball+w_height*sin(angle)/35;
    glVertex2f(xver,yver);
  }
glEnd();

//::::::::::::Separator:::::::::::://
glColor3f(0.0,0.0,0.0);
//glRectf(50.0,70.0,641.0,73.0);
glRectf(50.0,37.0,641.0,40.0);

//::::::::::External Boundary::::::::::://
glColor3f(0.0,0.0,0.0);
glRectf(10.0,10.0,690.0,12.0);
glRectf(10.0,10.0,12.0,690.0);
glRectf(10.0,690.0,690.0,688.0);
glRectf(690.0,690.0,688.0,10.0);

//:::::::::::Internal Gaming Platform Boundary:::::::::::::::://

glColor3f(0.0,0.0,0.0);
glRectf(50.0,594.0,641.0,591.0);
glRectf(50.0,594.0,47.0,37.0);
glRectf(641.0,594.0,644.0,37.0);

//::::::::::Target Blocks::::::::::://
if(flag==1)
{
  for(s=590;s>440;s-=50)
    {
      for(r=50;r<650;r+=50)
        {
          target[r][s]=1;
        }
    }
  flag=0;
}

glBegin(GL_QUADS);
{
  for(s=590;s>440;s-=50)
  {
    for(r=50;r<650;r+=50)
    {
      if(target[r][s]==1)
      {
        glColor3f(0.0,1.0,0.0);
        glVertex3f(r,s,0.0);
        glVertex3f(r+40.0,s,0.0);
        glVertex3f(r+40.0,s-40.0,0.0);
        glVertex3f(r,s-40.0,0.0);
      }
    }
  }
}
glEnd();

//::::::::::::Text:::::::::::://
glColor3f(0.0,0.0,0.0);
font=1;
drawBitmapText("  Tik-i-noids",260,665,0);

font=5;
drawBitmapText("Project: Contributed for Integrated Console Development Project Using openGL",60,650,0);
drawBitmapText("Developer: Jalaz Kumar",60,638,0);

font=2;
drawBitmapText("Instructions:",60,618,0);
drawBitmapText("PRESS:  S-Start   P-Pause   A-Left Shift  D-Right Shift",60,608,0);

font=4;
drawBitmapText("Score:",500,610,0);
drawBitmapText(sc,550,610,0);

glColor3f(1.0,0.0,0.0);
  if(play==2)
    {
      font=1;
      drawBitmapText("!!!!GAME OVER!!!!",230,350,0);

      drawBitmapText("Your Score: ",230,300,0);
      drawBitmapText(sc,360,300,0);
      font=3;
      drawBitmapText("Press R to Restart the game",250,250,0);
    }

//:::::::::::::Block:::::::::::::::://
glColor3f(1.0,0.0,1.0);
glBegin(GL_QUADS);
{
  glVertex3f(310.0+x,40.0,0.0);
  glVertex3f(390.0+x,40.0,0.0);
  glVertex3f(390.0+x,70.0,0.0);
  glVertex3f(310.0+x,70.0,0.0);
}
glEnd();
glFinish();
glutSwapBuffers();

}

//::::::::::::::Reshape Function:::::::::::::::::://
void reshape(int w, int h)
{
	w_height=h;
	w_width=w;
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,0.0,1.0);
}

void againDisplay()
{
  xball=xball+(a*speed[level]);
  yball=yball+(b*speed[level]);

  for(s=590;s>=490;s-=50)
   {
    for(r=50;r<650;r+=50)
     {
      if(target[r][s]==1)
      {
        if((yball<=s-32)&&(yball>=s-58)&&(xball>=r-2)&&(xball<=r+42)&&(b==1))
        {
          b=-b;
          target[r][s]=0;
          score+=10;
        }
      }
    }
  }

  if(((xball<=400.0+x)&&(xball>=300.0+x))&&((yball>=75.0)&&(yball<=90.0)))
  b=-b ;

  if(yball>590.0)
  b=-b;

  if((xball>=620.0)||(xball<=65.0))
  a=-a;

  int s1,s2,s3,s4;
  s1=score/1000;
  s2=(score%1000)/100;
  s3=(score%100)/10;
  s4=score%10;
  sc[0]=s1+48;
  sc[1]=s2+48;
  sc[2]=s3+48;
  sc[3]=s4+48;

  if(yball<=10.0)
  play=2;

  if(yball<=-20.0)
  glutIdleFunc(NULL);

  glutPostRedisplay();

}

//::::::::::::Restart Function::::::::::::::://
void restart(void)
{
  play=1;
  flag=1;
  x=0.0,y=0.0;
  xball=350.0,yball=350.0,a=1.0,b=1.0;
  score=0;
  level=0;

  glutPostRedisplay();
}

//::::::::::::::::::::keyboard function:::::::::::::::::://
void keyboard(unsigned char key, int xm, int ym)
{
  switch (key)
    {

      case 'a':x-=15;if(x<-260)x=-260;
      break;

      case 'd':x+=15; if(x>251)x=251;
      break;

      case 49:level=0;
      break;

      case 50:level=1;
      break;

      case 51:level=2;
      break;

      case 52:level=3;
      break;

      case 53:level=4;
      break;

      case 's':glutIdleFunc(againDisplay);     //Start the game
      break;

      case 'p':glutIdleFunc(NULL);            //Pause the game
      break;

      case 'r':glutIdleFunc(restart);
      default:
      break;
    }
}

int main(int argc,char** argv)
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
  glutInitWindowSize(w_width,w_height);
  glutInitWindowPosition(270,20);
  glutCreateWindow("Tik-i-noids by Jalaz");
  init();
  glutReshapeFunc(reshape);
  glutDisplayFunc(display);
  glutKeyboardFunc(keyboard);
  glutMainLoop();
  return 0;
}
<commit_msg>introducing console environment<commit_after>#include <GL/freeglut.h>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <GL/gl.h>
#include <stdlib.h>
#define PI 3.1415926535898

float w_width=700.0,w_height=700.0;
float x=0.0,y=0.0;
int s;
int r;
float xball=350.0,yball=350.0,a=1.0,b=1.0;

float speed[5]={0.1,0.15,0.18,0.22,0.25};
float speed1=0.08;
int level=0;

float xver,yver;
int target[700][700];
int font=0;
int flag=1;
int score1=0,score2=0;
int play=1;

char sc1[4];
char sc2[4];

int option=0;

void init(void)
{
  glClearColor(0.52,0.80,1.0,0.0);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(1,700,1,700,-1,1);
}

//::::::::::::::::TEXT FUNCTION:::::::::::::://
void drawBitmapText(const char *string,float x,float y,float z)
{
    const char *c;
    glRasterPos3f(x,y,z);

    for (c=string; *c != '\0'; c++)
    {
      if(font==0)
        glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_10, *c);
      else if(font==1)
        glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, *c);
      else if(font==2)
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, *c);
      else if(font==3)
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *c);
      else if(font==4)
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, *c);
      else if(font==5)
        glutBitmapCharacter(GLUT_BITMAP_8_BY_13, *c);
      else if(font==6)
        glutBitmapCharacter(GLUT_BITMAP_9_BY_15, *c);

    }
}

//::::::::::::::::Display Function::::::::::://
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
  if(option==0)
  { glClearColor(0.52,0.80,1.0,0.0);
    glColor3f(0.0,0.0,0.0);
    font=1;
    drawBitmapText("Press L for Level Mode",220,450,0);
    drawBitmapText("Press T for Target Mode",218,400,0);
    drawBitmapText("Press C for Credits",248,350,0);
    drawBitmapText("Press Q for Quit Game",230,300,0);
    glFinish();
    glutSwapBuffers();

  }

  else if(option==3)
  {
    glClear(GL_COLOR_BUFFER_BIT);
    glClearColor(1.0,0.75,0.14,0.0);
    glColor3f(0.0,0.0,0.0);
    font=1;
    drawBitmapText("Graphics Project",250,500,0);
    font=5;
    drawBitmapText("Integrated Gaming Console Development using openGL",140,470,0);
    font=4;
    drawBitmapText("Developer : Jalaz Kumar    NIT Hamirpur",125,400,0);
    font=1;
    drawBitmapText("Special Thanks to:",240,300,0);
    font=4;
    drawBitmapText("Debugger : Sukhbir Singh         NIT Hamirpur",125,250,0);
    drawBitmapText("Tester :   Narendra Dodwaria     NIT Hamirpur",125,200,0);
    glFinish();
    glutSwapBuffers();
  }

  else
  {
      //:::::::::::Ball:::::::::::://
      glColor3f(0.0,0.0,1.0);
      GLint circle_points=100,i;
      GLfloat angle;
      glBegin(GL_POLYGON);
      for(i=0;i<circle_points;i++)
        {
          angle=2*PI*i/circle_points;
          xver=xball+w_width*cos(angle)/35;
          yver=yball+w_height*sin(angle)/35;
          glVertex2f(xver,yver);
        }
      glEnd();

      //::::::::::::Separator:::::::::::://
      glColor3f(1.0,1.0,1.0);
      //glRectf(50.0,70.0,641.0,73.0);
      glRectf(50.0,37.0,641.0,40.0);

      //::::::::::External Boundary::::::::::://
      glColor3f(0.44,0.44,0.77);
      glRectf(10.0,10.0,690.0,12.0);
      glRectf(10.0,10.0,12.0,690.0);
      glRectf(10.0,690.0,690.0,688.0);
      glRectf(690.0,690.0,688.0,10.0);

      //:::::::::::Internal Gaming Platform Boundary:::::::::::::::://

      glColor3f(0.66,0.66,0.66);
      glRectf(50.0,594.0,641.0,591.0);
      glRectf(50.0,594.0,47.0,37.0);
      glRectf(641.0,594.0,644.0,37.0);

  if(option==1)
    {
      //::::::::::Target Blocks::::::::::://
      if(flag==1)
      {
        for(s=590;s>440;s-=50)
          {
            for(r=50;r<650;r+=50)
              {
                target[r][s]=1;
              }
          }
        flag=0;
      }

      glBegin(GL_QUADS);
      {
        for(s=590;s>440;s-=50)
        {
          for(r=50;r<650;r+=50)
          {
            if(target[r][s]==1)
            {
              glColor3f(0.0,1.0,0.0);
              glVertex3f(r,s,0.0);
              glVertex3f(r+40.0,s,0.0);
              glVertex3f(r+40.0,s-40.0,0.0);
              glVertex3f(r,s-40.0,0.0);
            }
          }
        }
      }
      glEnd();
    }

      //::::::::::::Text:::::::::::://
      glColor3f(1.0,1.0,1.0);
      font=1;
      drawBitmapText("  Tik-i-noids",260,665,0);

      font=5;
      drawBitmapText("Project: Contributed for Integrated Console Development Project Using openGL",60,650,0);
      drawBitmapText("Developer: Jalaz Kumar",60,638,0);

      font=2;
      drawBitmapText("Instructions:",60,618,0);
      drawBitmapText("PRESS:  S-Start   P-Pause   A-Left Shift  D-Right Shift",60,608,0);

      font=4;

      if(option==2)
      {
        drawBitmapText("Score:",500,610,0);
        drawBitmapText(sc2,560,610,0);
      }
      else if(option==1)
      {
        drawBitmapText("Score:",500,610,0);
        drawBitmapText(sc1,560,610,0);

      }

      glColor3f(1.0,0.0,0.0);
        if(play==2)
          {
            font=1;
            drawBitmapText("!!!!GAME OVER!!!!",220,350,0);
            if(option==1)
            {
              drawBitmapText("Your Score :- ",230,300,0);
              drawBitmapText(sc1,370,300,0);
            }
            else if(option==2)
            {
              drawBitmapText("Your Score :- ",230,300,0);
              drawBitmapText(sc2,370,300,0);

            }
            font=3;
            drawBitmapText("Press R to Restart the game",250,250,0);
          }

      //:::::::::::::Block:::::::::::::::://
      glColor3f(1.0,0.0,1.0);
      glBegin(GL_QUADS);
      {
        glVertex3f(310.0+x,40.0,0.0);
        glVertex3f(390.0+x,40.0,0.0);
        glVertex3f(390.0+x,70.0,0.0);
        glVertex3f(310.0+x,70.0,0.0);
      }
      glEnd();
      glFinish();
      glutSwapBuffers();

    }
  }

//::::::::::::::Reshape Function:::::::::::::::::://
void reshape(int w, int h)
{
	w_height=h;
	w_width=w;
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0,(GLdouble)w,0.0,(GLdouble)h,0.0,1.0);
}

void againDisplay()
{
  if(option==2)
  {
    xball=xball+(a*speed1);
    yball=yball+(b*speed1);
    speed1+=0.00001;
  }
  else
  {
    xball=xball+(a*speed[level]);
    yball=yball+(b*speed[level]);
  }

  if(option==1)
  {
    for(s=590;s>=490;s-=50)
      {
        for(r=50;r<650;r+=50)
          {
            if(target[r][s]==1)
              {
                if((yball<=s-32)&&(yball>=s-58)&&(xball>=r-2)&&(xball<=r+42)&&(b==1))
                  {
                    b=-b;
                    target[r][s]=0;
                    score1+=10;
                  }
              }
          }
      }
  }

  if(((xball<=400.0+x)&&(xball>=300.0+x))&&((yball>=75.0)&&(yball<=90.0)))
  {
    b=-b ;
    if(option==2)
    score2+=10;
  }

  if(yball>570.0)
  b=-b;

  if((xball>=620.0)||(xball<=65.0))
  a=-a;

  int s11,s12,s13,s14;
  s11=score1/1000;
  s12=(score1%1000)/100;
  s13=(score1%100)/10;
  s14=score1%10;
  sc1[0]=s11+48;
  sc1[1]=s12+48;
  sc1[2]=s13+48;
  sc1[3]=s14+48;

  if(option==2)
    {
      int s21,s22,s23,s24;
      s21=score2/1000;
      s22=(score2%1000)/100;
      s23=(score2%100)/10;
      s24=score2%10;
      sc2[0]=s21+48;
      sc2[1]=s22+48;
      sc2[2]=s23+48;
      sc2[3]=s24+48;
    }

  if(yball<=10.0)
  play=2;

  if(yball<=-20.0)
  glutIdleFunc(NULL);

  glutPostRedisplay();

}

//::::::::::::Restart Function::::::::::::::://
void restart(void)
{
  play=1;
  flag=1;
  x=0.0,y=0.0;
  xball=350.0,yball=350.0,a=1.0,b=1.0;
  score1=0;
  level=0;

  glutPostRedisplay();
}

//::::::::::::::::::::keyboard function:::::::::::::::::://
void keyboard(unsigned char key, int xm, int ym)
{
  if(option==0)
  {
    switch(key)
    {

      case 'l':option=1; glutPostRedisplay();
      break;

      case 't':option=2; glutPostRedisplay();
      break;

      case 'c':option=3; glutPostRedisplay();
      break;

      case 'q':exit(0);
    }
  }
  else
  {
  switch (key)
    {

      case 'a':x-=15;if(x<-260)x=-260;
      break;

      case 'd':x+=15; if(x>251)x=251;
      break;

      case 49:level=0;
      break;

      case 50:level=1;
      break;

      case 51:level=2;
      break;

      case 52:level=3;
      break;

      case 53:level=4;
      break;

      case 's':glutIdleFunc(againDisplay);     //Start the game
      break;

      case 'p':glutIdleFunc(NULL);            //Pause the game
      break;

      case 'r':glutIdleFunc(restart);
      default:
      break;
    }
  }
}

int main(int argc,char** argv)
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
  glutInitWindowSize(w_width,w_height);
  glutInitWindowPosition(270,20);
  glutCreateWindow("Tik-i-noids by Jalaz");
  init();
  glutReshapeFunc(reshape);
  glutDisplayFunc(display);
  glutKeyboardFunc(keyboard);
  glutMainLoop();
  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBlitMask.h"
#include "SkColor.h"
#include "SkColorData.h"
#include "SkOpts.h"

SkBlitMask::BlitLCD16RowProc SkBlitMask::BlitLCD16RowFactory(bool isOpaque) {
    BlitLCD16RowProc proc = PlatformBlitRowProcs16(isOpaque);
    if (proc) {
        return proc;
    }

    if (isOpaque) {
        return  SkBlitLCD16OpaqueRow;
    } else {
        return  SkBlitLCD16Row;
    }
}

static void D32_LCD16_Proc(void* SK_RESTRICT dst, size_t dstRB,
                           const void* SK_RESTRICT mask, size_t maskRB,
                           SkColor color, int width, int height) {

    SkPMColor*        dstRow = (SkPMColor*)dst;
    const uint16_t* srcRow = (const uint16_t*)mask;
    SkPMColor       opaqueDst;

    SkBlitMask::BlitLCD16RowProc proc = nullptr;
    bool isOpaque = (0xFF == SkColorGetA(color));
    proc = SkBlitMask::BlitLCD16RowFactory(isOpaque);
    SkASSERT(proc != nullptr);

    if (isOpaque) {
        opaqueDst = SkPreMultiplyColor(color);
    } else {
        opaqueDst = 0;  // ignored
    }

    do {
        proc(dstRow, srcRow, color, width, opaqueDst);
        dstRow = (SkPMColor*)((char*)dstRow + dstRB);
        srcRow = (const uint16_t*)((const char*)srcRow + maskRB);
    } while (--height != 0);
}

///////////////////////////////////////////////////////////////////////////////

bool SkBlitMask::BlitColor(const SkPixmap& device, const SkMask& mask,
                           const SkIRect& clip, SkColor color) {
    int x = clip.fLeft, y = clip.fTop;

    if (device.colorType() == kN32_SkColorType && mask.fFormat == SkMask::kA8_Format) {
        SkOpts::blit_mask_d32_a8(device.writable_addr32(x,y), device.rowBytes(),
                                 (const SkAlpha*)mask.getAddr(x,y), mask.fRowBytes,
                                 color, clip.width(), clip.height());
        return true;
    }

    if (device.colorType() == kN32_SkColorType && mask.fFormat == SkMask::kLCD16_Format) {
        // TODO: Is this reachable code?  Seems like no.
        D32_LCD16_Proc(device.writable_addr32(x,y), device.rowBytes(),
                       mask.getAddr(x,y), mask.fRowBytes,
                       color, clip.width(), clip.height());
        return true;
    }

    return false;
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

static void BW_RowProc_Blend(
        SkPMColor* SK_RESTRICT dst, const void* maskIn, const SkPMColor* SK_RESTRICT src, int count) {
    const uint8_t* SK_RESTRICT mask = static_cast<const uint8_t*>(maskIn);
    int i, octuple = (count + 7) >> 3;
    for (i = 0; i < octuple; ++i) {
        int m = *mask++;
        if (m & 0x80) { dst[0] = SkPMSrcOver(src[0], dst[0]); }
        if (m & 0x40) { dst[1] = SkPMSrcOver(src[1], dst[1]); }
        if (m & 0x20) { dst[2] = SkPMSrcOver(src[2], dst[2]); }
        if (m & 0x10) { dst[3] = SkPMSrcOver(src[3], dst[3]); }
        if (m & 0x08) { dst[4] = SkPMSrcOver(src[4], dst[4]); }
        if (m & 0x04) { dst[5] = SkPMSrcOver(src[5], dst[5]); }
        if (m & 0x02) { dst[6] = SkPMSrcOver(src[6], dst[6]); }
        if (m & 0x01) { dst[7] = SkPMSrcOver(src[7], dst[7]); }
        src += 8;
        dst += 8;
    }
    count &= 7;
    if (count > 0) {
        int m = *mask;
        do {
            if (m & 0x80) { dst[0] = SkPMSrcOver(src[0], dst[0]); }
            m <<= 1;
            src += 1;
            dst += 1;
        } while (--count > 0);
    }
}

static void BW_RowProc_Opaque(
        SkPMColor* SK_RESTRICT dst, const void* maskIn, const SkPMColor* SK_RESTRICT src, int count) {
    const uint8_t* SK_RESTRICT mask = static_cast<const uint8_t*>(maskIn);
    int i, octuple = (count + 7) >> 3;
    for (i = 0; i < octuple; ++i) {
        int m = *mask++;
        if (m & 0x80) { dst[0] = src[0]; }
        if (m & 0x40) { dst[1] = src[1]; }
        if (m & 0x20) { dst[2] = src[2]; }
        if (m & 0x10) { dst[3] = src[3]; }
        if (m & 0x08) { dst[4] = src[4]; }
        if (m & 0x04) { dst[5] = src[5]; }
        if (m & 0x02) { dst[6] = src[6]; }
        if (m & 0x01) { dst[7] = src[7]; }
        src += 8;
        dst += 8;
    }
    count &= 7;
    if (count > 0) {
        int m = *mask;
        do {
            if (m & 0x80) { dst[0] = SkPMSrcOver(src[0], dst[0]); }
            m <<= 1;
            src += 1;
            dst += 1;
        } while (--count > 0);
    }
}

static void A8_RowProc_Blend(
        SkPMColor* SK_RESTRICT dst, const void* maskIn, const SkPMColor* SK_RESTRICT src, int count) {
    const uint8_t* SK_RESTRICT mask = static_cast<const uint8_t*>(maskIn);
    for (int i = 0; i < count; ++i) {
        if (mask[i]) {
            dst[i] = SkBlendARGB32(src[i], dst[i], mask[i]);
        }
    }
}

// expand the steps that SkAlphaMulQ performs, but this way we can
//  exand.. add.. combine
// instead of
// expand..combine add expand..combine
//
#define EXPAND0(v, m, s)    ((v) & (m)) * (s)
#define EXPAND1(v, m, s)    (((v) >> 8) & (m)) * (s)
#define COMBINE(e0, e1, m)  ((((e0) >> 8) & (m)) | ((e1) & ~(m)))

static void A8_RowProc_Opaque(
        SkPMColor* SK_RESTRICT dst, const void* maskIn, const SkPMColor* SK_RESTRICT src, int count) {
    const uint8_t* SK_RESTRICT mask = static_cast<const uint8_t*>(maskIn);
    for (int i = 0; i < count; ++i) {
        int m = mask[i];
        if (m) {
            m += (m >> 7);
#if 1
            // this is slightly slower than the expand/combine version, but it
            // is much closer to the old results, so we use it for now to reduce
            // rebaselining.
            dst[i] = SkAlphaMulQ(src[i], m) + SkAlphaMulQ(dst[i], 256 - m);
#else
            uint32_t v = src[i];
            uint32_t s0 = EXPAND0(v, rbmask, m);
            uint32_t s1 = EXPAND1(v, rbmask, m);
            v = dst[i];
            uint32_t d0 = EXPAND0(v, rbmask, m);
            uint32_t d1 = EXPAND1(v, rbmask, m);
            dst[i] = COMBINE(s0 + d0, s1 + d1, rbmask);
#endif
        }
    }
}

static int upscale31To255(int value) {
    value = (value << 3) | (value >> 2);
    return value;
}

static int src_alpha_blend(int src, int dst, int srcA, int mask) {

    return dst + SkAlphaMul(src - SkAlphaMul(srcA, dst), mask);
}

static void LCD16_RowProc_Blend(
        SkPMColor* SK_RESTRICT dst, const void* maskIn, const SkPMColor* SK_RESTRICT src, int count) {
    const uint16_t* SK_RESTRICT mask = static_cast<const uint16_t*>(maskIn);
    for (int i = 0; i < count; ++i) {
        uint16_t m = mask[i];
        if (0 == m) {
            continue;
        }

        SkPMColor s = src[i];
        SkPMColor d = dst[i];

        int srcA = SkGetPackedA32(s);
        int srcR = SkGetPackedR32(s);
        int srcG = SkGetPackedG32(s);
        int srcB = SkGetPackedB32(s);

        srcA += srcA >> 7;

        /*  We want all of these in 5bits, hence the shifts in case one of them
         *  (green) is 6bits.
         */
        int maskR = SkGetPackedR16(m) >> (SK_R16_BITS - 5);
        int maskG = SkGetPackedG16(m) >> (SK_G16_BITS - 5);
        int maskB = SkGetPackedB16(m) >> (SK_B16_BITS - 5);

        maskR = upscale31To255(maskR);
        maskG = upscale31To255(maskG);
        maskB = upscale31To255(maskB);

        int dstR = SkGetPackedR32(d);
        int dstG = SkGetPackedG32(d);
        int dstB = SkGetPackedB32(d);

        // LCD blitting is only supported if the dst is known/required
        // to be opaque
        dst[i] = SkPackARGB32(0xFF,
                              src_alpha_blend(srcR, dstR, srcA, maskR),
                              src_alpha_blend(srcG, dstG, srcA, maskG),
                              src_alpha_blend(srcB, dstB, srcA, maskB));
    }
}

static void LCD16_RowProc_Opaque(
        SkPMColor* SK_RESTRICT dst, const void* maskIn, const SkPMColor* SK_RESTRICT src, int count) {
    const uint16_t* SK_RESTRICT mask = static_cast<const uint16_t*>(maskIn);
    for (int i = 0; i < count; ++i) {
        uint16_t m = mask[i];
        if (0 == m) {
            continue;
        }

        SkPMColor s = src[i];
        SkPMColor d = dst[i];

        int srcR = SkGetPackedR32(s);
        int srcG = SkGetPackedG32(s);
        int srcB = SkGetPackedB32(s);

        /*  We want all of these in 5bits, hence the shifts in case one of them
         *  (green) is 6bits.
         */
        int maskR = SkGetPackedR16(m) >> (SK_R16_BITS - 5);
        int maskG = SkGetPackedG16(m) >> (SK_G16_BITS - 5);
        int maskB = SkGetPackedB16(m) >> (SK_B16_BITS - 5);

        // Now upscale them to 0..32, so we can use blend32
        maskR = SkUpscale31To32(maskR);
        maskG = SkUpscale31To32(maskG);
        maskB = SkUpscale31To32(maskB);

        int dstR = SkGetPackedR32(d);
        int dstG = SkGetPackedG32(d);
        int dstB = SkGetPackedB32(d);

        // LCD blitting is only supported if the dst is known/required
        // to be opaque
        dst[i] = SkPackARGB32(0xFF,
                              SkBlend32(srcR, dstR, maskR),
                              SkBlend32(srcG, dstG, maskG),
                              SkBlend32(srcB, dstB, maskB));
    }
}

SkBlitMask::RowProc SkBlitMask::RowFactory(SkColorType ct,
                                           SkMask::Format format,
                                           RowFlags flags) {
// make this opt-in until chrome can rebaseline
    RowProc proc = PlatformRowProcs(ct, format, flags);
    if (proc) {
        return proc;
    }

    static const RowProc gProcs[] = {
        // need X coordinate to handle BW
        false ? (RowProc)BW_RowProc_Blend : nullptr, // suppress unused warning
        false ? (RowProc)BW_RowProc_Opaque : nullptr, // suppress unused warning
        (RowProc)A8_RowProc_Blend,      (RowProc)A8_RowProc_Opaque,
        (RowProc)LCD16_RowProc_Blend,   (RowProc)LCD16_RowProc_Opaque,
    };

    int index;
    switch (ct) {
        case kN32_SkColorType:
            switch (format) {
                case SkMask::kBW_Format:    index = 0; break;
                case SkMask::kA8_Format:    index = 2; break;
                case SkMask::kLCD16_Format: index = 4; break;
                default:
                    return nullptr;
            }
            if (flags & kSrcIsOpaque_RowFlag) {
                index |= 1;
            }
            SkASSERT((size_t)index < SK_ARRAY_COUNT(gProcs));
            return gProcs[index];
        default:
            break;
    }
    return nullptr;
}
<commit_msg>Remove unused BW mask blitters<commit_after>/*
 * Copyright 2014 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBlitMask.h"
#include "SkColor.h"
#include "SkColorData.h"
#include "SkOpts.h"

SkBlitMask::BlitLCD16RowProc SkBlitMask::BlitLCD16RowFactory(bool isOpaque) {
    BlitLCD16RowProc proc = PlatformBlitRowProcs16(isOpaque);
    if (proc) {
        return proc;
    }

    if (isOpaque) {
        return  SkBlitLCD16OpaqueRow;
    } else {
        return  SkBlitLCD16Row;
    }
}

static void D32_LCD16_Proc(void* SK_RESTRICT dst, size_t dstRB,
                           const void* SK_RESTRICT mask, size_t maskRB,
                           SkColor color, int width, int height) {

    SkPMColor*        dstRow = (SkPMColor*)dst;
    const uint16_t* srcRow = (const uint16_t*)mask;
    SkPMColor       opaqueDst;

    SkBlitMask::BlitLCD16RowProc proc = nullptr;
    bool isOpaque = (0xFF == SkColorGetA(color));
    proc = SkBlitMask::BlitLCD16RowFactory(isOpaque);
    SkASSERT(proc != nullptr);

    if (isOpaque) {
        opaqueDst = SkPreMultiplyColor(color);
    } else {
        opaqueDst = 0;  // ignored
    }

    do {
        proc(dstRow, srcRow, color, width, opaqueDst);
        dstRow = (SkPMColor*)((char*)dstRow + dstRB);
        srcRow = (const uint16_t*)((const char*)srcRow + maskRB);
    } while (--height != 0);
}

///////////////////////////////////////////////////////////////////////////////

bool SkBlitMask::BlitColor(const SkPixmap& device, const SkMask& mask,
                           const SkIRect& clip, SkColor color) {
    int x = clip.fLeft, y = clip.fTop;

    if (device.colorType() == kN32_SkColorType && mask.fFormat == SkMask::kA8_Format) {
        SkOpts::blit_mask_d32_a8(device.writable_addr32(x,y), device.rowBytes(),
                                 (const SkAlpha*)mask.getAddr(x,y), mask.fRowBytes,
                                 color, clip.width(), clip.height());
        return true;
    }

    if (device.colorType() == kN32_SkColorType && mask.fFormat == SkMask::kLCD16_Format) {
        // TODO: Is this reachable code?  Seems like no.
        D32_LCD16_Proc(device.writable_addr32(x,y), device.rowBytes(),
                       mask.getAddr(x,y), mask.fRowBytes,
                       color, clip.width(), clip.height());
        return true;
    }

    return false;
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
static void A8_RowProc_Blend(
        SkPMColor* SK_RESTRICT dst, const void* maskIn, const SkPMColor* SK_RESTRICT src, int count) {
    const uint8_t* SK_RESTRICT mask = static_cast<const uint8_t*>(maskIn);
    for (int i = 0; i < count; ++i) {
        if (mask[i]) {
            dst[i] = SkBlendARGB32(src[i], dst[i], mask[i]);
        }
    }
}

// expand the steps that SkAlphaMulQ performs, but this way we can
//  exand.. add.. combine
// instead of
// expand..combine add expand..combine
//
#define EXPAND0(v, m, s)    ((v) & (m)) * (s)
#define EXPAND1(v, m, s)    (((v) >> 8) & (m)) * (s)
#define COMBINE(e0, e1, m)  ((((e0) >> 8) & (m)) | ((e1) & ~(m)))

static void A8_RowProc_Opaque(
        SkPMColor* SK_RESTRICT dst, const void* maskIn, const SkPMColor* SK_RESTRICT src, int count) {
    const uint8_t* SK_RESTRICT mask = static_cast<const uint8_t*>(maskIn);
    for (int i = 0; i < count; ++i) {
        int m = mask[i];
        if (m) {
            m += (m >> 7);
#if 1
            // this is slightly slower than the expand/combine version, but it
            // is much closer to the old results, so we use it for now to reduce
            // rebaselining.
            dst[i] = SkAlphaMulQ(src[i], m) + SkAlphaMulQ(dst[i], 256 - m);
#else
            uint32_t v = src[i];
            uint32_t s0 = EXPAND0(v, rbmask, m);
            uint32_t s1 = EXPAND1(v, rbmask, m);
            v = dst[i];
            uint32_t d0 = EXPAND0(v, rbmask, m);
            uint32_t d1 = EXPAND1(v, rbmask, m);
            dst[i] = COMBINE(s0 + d0, s1 + d1, rbmask);
#endif
        }
    }
}

static int upscale31To255(int value) {
    value = (value << 3) | (value >> 2);
    return value;
}

static int src_alpha_blend(int src, int dst, int srcA, int mask) {

    return dst + SkAlphaMul(src - SkAlphaMul(srcA, dst), mask);
}

static void LCD16_RowProc_Blend(
        SkPMColor* SK_RESTRICT dst, const void* maskIn, const SkPMColor* SK_RESTRICT src, int count) {
    const uint16_t* SK_RESTRICT mask = static_cast<const uint16_t*>(maskIn);
    for (int i = 0; i < count; ++i) {
        uint16_t m = mask[i];
        if (0 == m) {
            continue;
        }

        SkPMColor s = src[i];
        SkPMColor d = dst[i];

        int srcA = SkGetPackedA32(s);
        int srcR = SkGetPackedR32(s);
        int srcG = SkGetPackedG32(s);
        int srcB = SkGetPackedB32(s);

        srcA += srcA >> 7;

        /*  We want all of these in 5bits, hence the shifts in case one of them
         *  (green) is 6bits.
         */
        int maskR = SkGetPackedR16(m) >> (SK_R16_BITS - 5);
        int maskG = SkGetPackedG16(m) >> (SK_G16_BITS - 5);
        int maskB = SkGetPackedB16(m) >> (SK_B16_BITS - 5);

        maskR = upscale31To255(maskR);
        maskG = upscale31To255(maskG);
        maskB = upscale31To255(maskB);

        int dstR = SkGetPackedR32(d);
        int dstG = SkGetPackedG32(d);
        int dstB = SkGetPackedB32(d);

        // LCD blitting is only supported if the dst is known/required
        // to be opaque
        dst[i] = SkPackARGB32(0xFF,
                              src_alpha_blend(srcR, dstR, srcA, maskR),
                              src_alpha_blend(srcG, dstG, srcA, maskG),
                              src_alpha_blend(srcB, dstB, srcA, maskB));
    }
}

static void LCD16_RowProc_Opaque(
        SkPMColor* SK_RESTRICT dst, const void* maskIn, const SkPMColor* SK_RESTRICT src, int count) {
    const uint16_t* SK_RESTRICT mask = static_cast<const uint16_t*>(maskIn);
    for (int i = 0; i < count; ++i) {
        uint16_t m = mask[i];
        if (0 == m) {
            continue;
        }

        SkPMColor s = src[i];
        SkPMColor d = dst[i];

        int srcR = SkGetPackedR32(s);
        int srcG = SkGetPackedG32(s);
        int srcB = SkGetPackedB32(s);

        /*  We want all of these in 5bits, hence the shifts in case one of them
         *  (green) is 6bits.
         */
        int maskR = SkGetPackedR16(m) >> (SK_R16_BITS - 5);
        int maskG = SkGetPackedG16(m) >> (SK_G16_BITS - 5);
        int maskB = SkGetPackedB16(m) >> (SK_B16_BITS - 5);

        // Now upscale them to 0..32, so we can use blend32
        maskR = SkUpscale31To32(maskR);
        maskG = SkUpscale31To32(maskG);
        maskB = SkUpscale31To32(maskB);

        int dstR = SkGetPackedR32(d);
        int dstG = SkGetPackedG32(d);
        int dstB = SkGetPackedB32(d);

        // LCD blitting is only supported if the dst is known/required
        // to be opaque
        dst[i] = SkPackARGB32(0xFF,
                              SkBlend32(srcR, dstR, maskR),
                              SkBlend32(srcG, dstG, maskG),
                              SkBlend32(srcB, dstB, maskB));
    }
}

SkBlitMask::RowProc SkBlitMask::RowFactory(SkColorType ct,
                                           SkMask::Format format,
                                           RowFlags flags) {
// make this opt-in until chrome can rebaseline
    RowProc proc = PlatformRowProcs(ct, format, flags);
    if (proc) {
        return proc;
    }

    static const RowProc gProcs[] = {
        (RowProc)A8_RowProc_Blend,      (RowProc)A8_RowProc_Opaque,
        (RowProc)LCD16_RowProc_Blend,   (RowProc)LCD16_RowProc_Opaque,
    };

    switch (ct) {
        case kN32_SkColorType: {
            size_t index;
            switch (format) {
                case SkMask::kA8_Format:    index = 0; break;
                case SkMask::kLCD16_Format: index = 2; break;
                default:
                    return nullptr;
            }
            if (flags & kSrcIsOpaque_RowFlag) {
                index |= 1;
            }
            SkASSERT(index < SK_ARRAY_COUNT(gProcs));
            return gProcs[index];
        }
        default:
            break;
    }
    return nullptr;
}
<|endoftext|>


<commit_before>#include "ROOMLOAD.H"

#include "GAMEWAD.H"
#include "GPU.H"
#include "LOAD_LEV.H"
#include "SETUP.H"

#include <assert.h>

#include <stdio.h>
#include <string.h>

long AnimFilePos;
long AnimFileLen;
short* floor_data;
unsigned long* SetupPtr;
unsigned short ClutStartY;
struct SVECTOR* RoomBBoxes;
short* mesh_base;
struct PSXSPRITESTRUCT* GLOBAL_default_sprites_ptr;
struct PSXTEXTI* AnimatingWaterfalls[6];
int AnimatingWaterfallsV[6];
unsigned long envmap_data[6];
unsigned long* RelocPtr[128];

//FIXME (Retail)
int dword_800A5F04 = 0;
int dword_800AD724 = 0;
int dword_800A60D8 = 0;

void S_LoadLevelFile(int Name)//60188, 60D54(<)
{
#ifdef INTERNAL
	char buf[80];
	unsigned long* mod;
	FILE* file;

	int a0 = 0;//FIXME
	int s3 = a0;
	a0 = 0;

	//DrawSync();
	init_game_malloc();
	int s0 = 10;
	//LOAD_Start();//loads loading pic right after script file?
	a0 = s3 + 2;
	int v0 = 10;

	char* s00 = "DATA\\SETUP.MOD";

	unsigned long* s1 = db.poly_buffer[0]; //critical unknown var, probably db, db_struct
	///v0 = s1 + 0x1008;
	//	SetupPtr = v0;//&OurSqrt[968]

	int len = FILE_Length("DATA\\SETUP.MOD");

	char* a00 = s00;
	a00 = s00;
	int a1 = 0;
	int a2 = 0;

#ifdef PSX
	PCOpen();
#else
	file = fopen("DATA\\SETUP.MOD", "rb");
#endif

	///s2 = v0;
	///a0 = s1 + 0x1000;
	a1 = 1;
	///	a2 = s2;
	//	s00 = v0;

	//	FILE_Read();
	///a3 = s00;

#ifdef PSX
	PCclose();
#else
	fclose(file);
#endif

	a0 = s0;
	//a0 = SetupPtr;

	///a1 = s1[0x1000];

	//	RelocateModule();

	a1 = a0;
	s3 <<= 1;

	unsigned short* v00 = gfFilenameOffset;
	char* a11 = gfFilenameWad;

	s3 = v0;

	///v1 = *(unsigned short*)s3;
	///a1 += v1;
	strcpy(buf, a11);

	a1 = 10;

	strcat(buf, ".PSX");

	len = FILE_Load(buf, malloc_ptr);//PSX file

	a1 = 0;

#ifdef PSX
	PCopen();
#else
	file = fopen((const char*)file, buf);
	assert(file);
	fclose(file);
#endif

	a2 = 0;

	///v1 = SetupPtr;

	///a1 = v1[0x14];
	//Appears to execute code within SETUP.mod to serialise the level file?

	RelocateLevel();

	a0 = v0;
	LOAD_Stop();
#else

	int a0 = Name;
	int s0 = a0 + 2;//+2 because first entry is setup.mod and second is cutseq.jiz

	//TITLE is the base file entry index for levels, simply as a result, we must add gameflow level id to this.
	GAMEWAD_InitialiseReaderPosition(Name + TITLE);

	a0 = 0;
	//jal sub_6B144 //ResetCallback();

	init_game_malloc();

	a0 = s0;
	LOAD_Start(Name);//FIXME incorRECTTRC ptr returning

	int v0 = 0x000A0000;
	int v1 = 0x000B0000;

	unsigned long* s00 = db.poly_buffer[0];
	int a1 = dword_800AD724;//illegal value
	v0 = s0 + 0x1008;//OurSqrt?
	//SetupPtr = v0;///@FIXME illegal ptr

	//addiu	$a0, $s0, 0x1000 //looks like the ptr?

	//FIXME should switch offset 0x6E5
	GAMEWAD_Read(SETUP_MOD_FILE_SIZE, setupBuff); //jal sub_5E414 //Loads setup.mod to ptr 0xB2940

	//a0 = SetupPtr;
	//lw	$a1, 0x1000($s0)
	a1 += a0;
	//jal	sub_5F430 RelocateModule(); setup.mod?

	//lw	$v0, 0x38C4($gp)
	//lw	$v1, 0x14($v0)
	//jalr	$v1
	RelocateLevel();
	//a0 = s1;

	LOAD_Stop();
#endif
}<commit_msg>Attempt to fix Linux build (3)<commit_after>#include "ROOMLOAD.H"

#include "GAMEWAD.H"
#include "GPU.H"
#include "LOAD_LEV.H"
#include "MALLOC.H"
#include "SETUP.H"

#include <assert.h>

#include <stdio.h>
#include <string.h>

long AnimFilePos;
long AnimFileLen;
short* floor_data;
unsigned long* SetupPtr;
unsigned short ClutStartY;
struct SVECTOR* RoomBBoxes;
short* mesh_base;
struct PSXSPRITESTRUCT* GLOBAL_default_sprites_ptr;
struct PSXTEXTI* AnimatingWaterfalls[6];
int AnimatingWaterfallsV[6];
unsigned long envmap_data[6];
unsigned long* RelocPtr[128];

//FIXME (Retail)
int dword_800A5F04 = 0;
int dword_800AD724 = 0;
int dword_800A60D8 = 0;

void S_LoadLevelFile(int Name)//60188, 60D54(<)
{
#ifdef INTERNAL
	char buf[80];
	unsigned long* mod;
	FILE* file;

	int a0 = 0;//FIXME
	int s3 = a0;
	a0 = 0;

	//DrawSync();
	init_game_malloc();
	int s0 = 10;
	//LOAD_Start();//loads loading pic right after script file?
	a0 = s3 + 2;
	int v0 = 10;

	char* s00 = "DATA\\SETUP.MOD";

	unsigned long* s1 = db.poly_buffer[0]; //critical unknown var, probably db, db_struct
	///v0 = s1 + 0x1008;
	//	SetupPtr = v0;//&OurSqrt[968]

	int len = FILE_Length("DATA\\SETUP.MOD");

	char* a00 = s00;
	a00 = s00;
	int a1 = 0;
	int a2 = 0;

#ifdef PSX
	PCOpen();
#else
	file = fopen("DATA\\SETUP.MOD", "rb");
#endif

	///s2 = v0;
	///a0 = s1 + 0x1000;
	a1 = 1;
	///	a2 = s2;
	//	s00 = v0;

	//	FILE_Read();
	///a3 = s00;

#ifdef PSX
	PCclose();
#else
	fclose(file);
#endif

	a0 = s0;
	//a0 = SetupPtr;

	///a1 = s1[0x1000];

	//	RelocateModule();

	a1 = a0;
	s3 <<= 1;

	unsigned short* v00 = gfFilenameOffset;
	char* a11 = gfFilenameWad;

	s3 = v0;

	///v1 = *(unsigned short*)s3;
	///a1 += v1;
	strcpy(buf, a11);

	a1 = 10;

	strcat(buf, ".PSX");

	len = FILE_Load(buf, malloc_ptr);//PSX file

	a1 = 0;

#ifdef PSX
	PCopen();
#else
	file = fopen((const char*)file, buf);
	assert(file);
	fclose(file);
#endif

	a2 = 0;

	///v1 = SetupPtr;

	///a1 = v1[0x14];
	//Appears to execute code within SETUP.mod to serialise the level file?

	RelocateLevel();

	a0 = v0;
	LOAD_Stop();
#else

	int a0 = Name;
	int s0 = a0 + 2;//+2 because first entry is setup.mod and second is cutseq.jiz

	//TITLE is the base file entry index for levels, simply as a result, we must add gameflow level id to this.
	GAMEWAD_InitialiseReaderPosition(Name + TITLE);

	a0 = 0;
	//jal sub_6B144 //ResetCallback();

	init_game_malloc();

	a0 = s0;
	LOAD_Start(Name);//FIXME incorRECTTRC ptr returning

	int v0 = 0x000A0000;
	int v1 = 0x000B0000;

	unsigned long* s00 = db.poly_buffer[0];
	int a1 = dword_800AD724;//illegal value
	v0 = s0 + 0x1008;//OurSqrt?
	//SetupPtr = v0;///@FIXME illegal ptr

	//addiu	$a0, $s0, 0x1000 //looks like the ptr?

	//FIXME should switch offset 0x6E5
	GAMEWAD_Read(SETUP_MOD_FILE_SIZE, setupBuff); //jal sub_5E414 //Loads setup.mod to ptr 0xB2940

	//a0 = SetupPtr;
	//lw	$a1, 0x1000($s0)
	a1 += a0;
	//jal	sub_5F430 RelocateModule(); setup.mod?

	//lw	$v0, 0x38C4($gp)
	//lw	$v1, 0x14($v0)
	//jalr	$v1
	RelocateLevel();
	//a0 = s1;

	LOAD_Stop();
#endif
}<|endoftext|>