<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id: graphics.hpp 39 2005-04-10 20:39:53Z pavlenko $

#ifndef GRAPHICS_HPP
#define GRAPHICS_HPP
// mapnik
#include <mapnik/color.hpp>
#include <mapnik/gamma.hpp>
#include <mapnik/image_data.hpp>
#include <mapnik/envelope.hpp>
#include <mapnik/image_view.hpp>
// stl
#include <cmath>
#include <string>
#include <cassert>

namespace mapnik
{
    class MAPNIK_DECL Image32
    {
    private:
        unsigned width_;
        unsigned height_;
        Color background_;
        ImageData32 data_;
    public:
        Image32(int width,int height);
        Image32(Image32 const& rhs);
        ~Image32();
        void setBackground(Color const& background);
        const Color& getBackground() const;
        const ImageData32& data() const;

        inline ImageData32& data()
        {
            return data_;
        }

        inline const unsigned char* raw_data() const
        {
            return data_.getBytes();
        }

        inline unsigned char* raw_data()
        {
            return data_.getBytes();
        }

        inline image_view<ImageData32> get_view(unsigned x,unsigned y, unsigned w,unsigned h)
        {
            return image_view<ImageData32>(x,y,w,h,data_);
        }

        void saveToFile(const std::string& file,const std::string& format="auto");

    private:

        inline bool checkBounds(unsigned x, unsigned y) const
        {
            return (x < width_ && y < height_);
        }

    public:
        inline void setPixel(int x,int y,unsigned int rgba)
        {
            if (checkBounds(x,y))
            {
                data_(x,y)=rgba;
            }
        }
        inline void blendPixel(int x,int y,unsigned int rgba1,int t)
        {
            if (checkBounds(x,y))
            {
                unsigned rgba0 = data_(x,y);
                unsigned a1 = t;//(rgba1 >> 24) & 0xff;
                if (a1 == 0) return;
                unsigned r1 = rgba1 & 0xff;
                unsigned g1 = (rgba1 >> 8 ) & 0xff;
                unsigned b1 = (rgba1 >> 16) & 0xff;

                unsigned a0 = (rgba0 >> 24) & 0xff;
                unsigned r0 = (rgba0 & 0xff) * a0;
                unsigned g0 = ((rgba0 >> 8 ) & 0xff) * a0;
                unsigned b0 = ((rgba0 >> 16) & 0xff) * a0;

                a0 = ((a1 + a0) << 8) - a0*a1;

                r0 = ((((r1 << 8) - r0) * a1 + (r0 << 8)) / a0);
                g0 = ((((g1 << 8) - g0) * a1 + (g0 << 8)) / a0);
                b0 = ((((b1 << 8) - b0) * a1 + (b0 << 8)) / a0);
                a0 = a0 >> 8;
                data_(x,y)= (a0 << 24)| (b0 << 16) |  (g0 << 8) | (r0) ;
            }
        }

        inline unsigned width() const
        {
            return width_;
        }

        inline unsigned height() const
        {
            return height_;
        }

        inline void set_rectangle(int x0,int y0,ImageData32 const& data)
        {
            Envelope<int> ext0(0,0,width_,height_);
            Envelope<int> ext1(x0,y0,x0+data.width(),y0+data.height());

            if (ext0.intersects(ext1))
            {
               Envelope<int> box = ext0.intersect(ext1);
               for (int y = box.miny(); y < box.maxy(); ++y)
               {
                  unsigned int* row_to =  data_.getRow(y);
                  unsigned int const * row_from = data.getRow(y-y0);

                  for (int x = box.minx(); x < box.maxx(); ++x)
                  {
                     if (row_from[x-x0] & 0xff000000)
                     {
                        row_to[x] = row_from[x-x0];
                     }
                  }
               }
            }
        }

        inline void set_rectangle_alpha(int x0,int y0,const ImageData32& data)
        {
            Envelope<int> ext0(0,0,width_,height_);
            Envelope<int> ext1(x0,y0,x0 + data.width(),y0 + data.height());

            if (ext0.intersects(ext1))
            {
                Envelope<int> box = ext0.intersect(ext1);
                for (int y = box.miny(); y < box.maxy(); ++y)
                {
                   unsigned int* row_to =  data_.getRow(y);
                   unsigned int const * row_from = data.getRow(y-y0);
                   for (int x = box.minx(); x < box.maxx(); ++x)
                   {
                      unsigned rgba0 = row_to[x];
                      unsigned rgba1 = row_from[x-x0];

                      unsigned a1 = (rgba1 >> 24) & 0xff;
                      if (a1 == 0) continue;
                      unsigned r1 = rgba1 & 0xff;
                      unsigned g1 = (rgba1 >> 8 ) & 0xff;
                      unsigned b1 = (rgba1 >> 16) & 0xff;

                      unsigned a0 = (rgba0 >> 24) & 0xff;
                      unsigned r0 = (rgba0 & 0xff) * a0;
                      unsigned g0 = ((rgba0 >> 8 ) & 0xff) * a0;
                      unsigned b0 = ((rgba0 >> 16) & 0xff) * a0;

                      a0 = ((a1 + a0) << 8) - a0*a1;

                      r0 = ((((r1 << 8) - r0) * a1 + (r0 << 8)) / a0);
                      g0 = ((((g1 << 8) - g0) * a1 + (g0 << 8)) / a0);
                      b0 = ((((b1 << 8) - b0) * a1 + (b0 << 8)) / a0);
                      a0 = a0 >> 8;
                      row_to[x] = (a0 << 24)| (b0 << 16) |  (g0 << 8) | (r0) ;
                   }
                }
            }
        }

        inline void set_rectangle_alpha2(ImageData32 const& data, unsigned x0, unsigned y0, float opacity)
        {
            Envelope<int> ext0(0,0,width_,height_);
            Envelope<int> ext1(x0,y0,x0 + data.width(),y0 + data.height());
            unsigned a1 = int(opacity * 255);

            if (ext0.intersects(ext1))
            {
                Envelope<int> box = ext0.intersect(ext1);
                for (int y = box.miny(); y < box.maxy(); ++y)
                {
                   unsigned int* row_to =  data_.getRow(y);
                   unsigned int const * row_from = data.getRow(y-y0);
                   for (int x = box.minx(); x < box.maxx(); ++x)
                   {
                      unsigned rgba0 = row_to[x];
                      unsigned rgba1 = row_from[x-x0];
                      if (((rgba1 >> 24) & 255)== 0) continue;
                      unsigned r1 = rgba1 & 0xff;
                      unsigned g1 = (rgba1 >> 8 ) & 0xff;
                      unsigned b1 = (rgba1 >> 16) & 0xff;

                      unsigned a0 = (rgba0 >> 24) & 0xff;
                      unsigned r0 = rgba0 & 0xff ;
                      unsigned g0 = (rgba0 >> 8 ) & 0xff;
                      unsigned b0 = (rgba0 >> 16) & 0xff;

                      unsigned a = (a1 * 255 + (255 - a1) * a0 + 127)/255;

                      r0 = (r1*a1 + (((255 - a1) * a0 + 127)/255) * r0 + 127)/a;
                      g0 = (g1*a1 + (((255 - a1) * a0 + 127)/255) * g0 + 127)/a;
                      b0 = (b1*a1 + (((255 - a1) * a0 + 127)/255) * b0 + 127)/a;

                      row_to[x] = (a << 24)| (b0 << 16) |  (g0 << 8) | (r0) ;
                    }
                }
            }
        }
    };
}
#endif //GRAPHICS_HPP
<commit_msg>applied patch from gravitystorm (see ticket:64)<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id: graphics.hpp 39 2005-04-10 20:39:53Z pavlenko $

#ifndef GRAPHICS_HPP
#define GRAPHICS_HPP
// mapnik
#include <mapnik/color.hpp>
#include <mapnik/gamma.hpp>
#include <mapnik/image_data.hpp>
#include <mapnik/envelope.hpp>
#include <mapnik/image_view.hpp>
// stl
#include <cmath>
#include <string>
#include <cassert>

namespace mapnik
{
    class MAPNIK_DECL Image32
    {
    private:
        unsigned width_;
        unsigned height_;
        Color background_;
        ImageData32 data_;
    public:
        Image32(int width,int height);
        Image32(Image32 const& rhs);
        ~Image32();
        void setBackground(Color const& background);
        const Color& getBackground() const;
        const ImageData32& data() const;

        inline ImageData32& data()
        {
            return data_;
        }

        inline const unsigned char* raw_data() const
        {
            return data_.getBytes();
        }

        inline unsigned char* raw_data()
        {
            return data_.getBytes();
        }

        inline image_view<ImageData32> get_view(unsigned x,unsigned y, unsigned w,unsigned h)
        {
            return image_view<ImageData32>(x,y,w,h,data_);
        }

        void saveToFile(const std::string& file,const std::string& format="auto");

    private:

        inline bool checkBounds(unsigned x, unsigned y) const
        {
            return (x < width_ && y < height_);
        }

    public:
        inline void setPixel(int x,int y,unsigned int rgba)
        {
            if (checkBounds(x,y))
            {
                data_(x,y)=rgba;
            }
        }
        inline void blendPixel(int x,int y,unsigned int rgba1,int t)
        {
            if (checkBounds(x,y))
            {
                unsigned rgba0 = data_(x,y);
                unsigned a1 = (rgba1 >> 24) & 0xff; //t;
                a1 = (t*a1) / 255;
                if (a1 == 0) return;
                unsigned r1 = rgba1 & 0xff;
                unsigned g1 = (rgba1 >> 8 ) & 0xff;
                unsigned b1 = (rgba1 >> 16) & 0xff;

                unsigned a0 = (rgba0 >> 24) & 0xff;
                unsigned r0 = (rgba0 & 0xff) * a0;
                unsigned g0 = ((rgba0 >> 8 ) & 0xff) * a0;
                unsigned b0 = ((rgba0 >> 16) & 0xff) * a0;

                a0 = ((a1 + a0) << 8) - a0*a1;

                r0 = ((((r1 << 8) - r0) * a1 + (r0 << 8)) / a0);
                g0 = ((((g1 << 8) - g0) * a1 + (g0 << 8)) / a0);
                b0 = ((((b1 << 8) - b0) * a1 + (b0 << 8)) / a0);
                a0 = a0 >> 8;
                data_(x,y)= (a0 << 24)| (b0 << 16) |  (g0 << 8) | (r0) ;
            }
        }

        inline unsigned width() const
        {
            return width_;
        }

        inline unsigned height() const
        {
            return height_;
        }

        inline void set_rectangle(int x0,int y0,ImageData32 const& data)
        {
            Envelope<int> ext0(0,0,width_,height_);
            Envelope<int> ext1(x0,y0,x0+data.width(),y0+data.height());

            if (ext0.intersects(ext1))
            {
               Envelope<int> box = ext0.intersect(ext1);
               for (int y = box.miny(); y < box.maxy(); ++y)
               {
                  unsigned int* row_to =  data_.getRow(y);
                  unsigned int const * row_from = data.getRow(y-y0);

                  for (int x = box.minx(); x < box.maxx(); ++x)
                  {
                     if (row_from[x-x0] & 0xff000000)
                     {
                        row_to[x] = row_from[x-x0];
                     }
                  }
               }
            }
        }

        inline void set_rectangle_alpha(int x0,int y0,const ImageData32& data)
        {
            Envelope<int> ext0(0,0,width_,height_);
            Envelope<int> ext1(x0,y0,x0 + data.width(),y0 + data.height());

            if (ext0.intersects(ext1))
            {
                Envelope<int> box = ext0.intersect(ext1);
                for (int y = box.miny(); y < box.maxy(); ++y)
                {
                   unsigned int* row_to =  data_.getRow(y);
                   unsigned int const * row_from = data.getRow(y-y0);
                   for (int x = box.minx(); x < box.maxx(); ++x)
                   {
                      unsigned rgba0 = row_to[x];
                      unsigned rgba1 = row_from[x-x0];

                      unsigned a1 = (rgba1 >> 24) & 0xff;
                      if (a1 == 0) continue;
                      unsigned r1 = rgba1 & 0xff;
                      unsigned g1 = (rgba1 >> 8 ) & 0xff;
                      unsigned b1 = (rgba1 >> 16) & 0xff;

                      unsigned a0 = (rgba0 >> 24) & 0xff;
                      unsigned r0 = (rgba0 & 0xff) * a0;
                      unsigned g0 = ((rgba0 >> 8 ) & 0xff) * a0;
                      unsigned b0 = ((rgba0 >> 16) & 0xff) * a0;

                      a0 = ((a1 + a0) << 8) - a0*a1;

                      r0 = ((((r1 << 8) - r0) * a1 + (r0 << 8)) / a0);
                      g0 = ((((g1 << 8) - g0) * a1 + (g0 << 8)) / a0);
                      b0 = ((((b1 << 8) - b0) * a1 + (b0 << 8)) / a0);
                      a0 = a0 >> 8;
                      row_to[x] = (a0 << 24)| (b0 << 16) |  (g0 << 8) | (r0) ;
                   }
                }
            }
        }

        inline void set_rectangle_alpha2(ImageData32 const& data, unsigned x0, unsigned y0, float opacity)
        {
            Envelope<int> ext0(0,0,width_,height_);
            Envelope<int> ext1(x0,y0,x0 + data.width(),y0 + data.height());

            if (ext0.intersects(ext1))
            {
                Envelope<int> box = ext0.intersect(ext1);
                for (int y = box.miny(); y < box.maxy(); ++y)
                {
                   unsigned int* row_to =  data_.getRow(y);
                   unsigned int const * row_from = data.getRow(y-y0);
                   for (int x = box.minx(); x < box.maxx(); ++x)
                   {
                      unsigned rgba0 = row_to[x];
                      unsigned rgba1 = row_from[x-x0];
                      unsigned a1 = int( ((rgba1 >> 24) & 0xff) * opacity );
                      if (a1 == 0) continue;
                      unsigned r1 = rgba1 & 0xff;
                      unsigned g1 = (rgba1 >> 8 ) & 0xff;
                      unsigned b1 = (rgba1 >> 16) & 0xff;

                      unsigned a0 = (rgba0 >> 24) & 0xff;
                      unsigned r0 = rgba0 & 0xff ;
                      unsigned g0 = (rgba0 >> 8 ) & 0xff;
                      unsigned b0 = (rgba0 >> 16) & 0xff;

                      unsigned a = (a1 * 255 + (255 - a1) * a0 + 127)/255;

                      r0 = (r1*a1 + (((255 - a1) * a0 + 127)/255) * r0 + 127)/a;
                      g0 = (g1*a1 + (((255 - a1) * a0 + 127)/255) * g0 + 127)/a;
                      b0 = (b1*a1 + (((255 - a1) * a0 + 127)/255) * b0 + 127)/a;

                      row_to[x] = (a << 24)| (b0 << 16) |  (g0 << 8) | (r0) ;
                    }
                }
            }
        }
    };
}
#endif //GRAPHICS_HPP
<|endoftext|>


<commit_before>#ifndef INCLUDE_AL_MATRIX4_HPP
#define INCLUDE_AL_MATRIX4_HPP

#include "math/al_Constants.hpp"
#include "math/al_Quat.hpp"
#include "math/al_Vec.hpp"

namespace al {

template<class T> class Matrix4;

/// 4x4 Matrix (Homogenous Transform)
template<typename T=double>
class Matrix4 : public Mat<4, T> {
public:
	typedef Mat<4, T> Base;

	Matrix4()
	: Base(
		1, 0, 0, 0,
		0, 1, 0, 0,
		0, 0, 1, 0,
		0, 0, 0, 1
	)
	{}

	Matrix4(
		const T& v11, const T& v21, const T& v31, const T& v41,
		const T& v12, const T& v22, const T& v32, const T& v42,
		const T& v13, const T& v23, const T& v33, const T& v43,
		const T& v14, const T& v24, const T& v34, const T& v44
	)
	:	Base(
			v11, v21, v31, v41,
			v12, v22, v32, v42,
			v13, v23, v33, v43,
			v14, v24, v34, v44
		)
	{}

	Matrix4(
		const Vec3<T>& xaxis,
		const Vec3<T>& yaxis,
		const Vec3<T>& zaxis,
		const Vec3<T>& position
	)
	:	Base(
			xaxis[0], xaxis[1], xaxis[2], 0,
			yaxis[0], yaxis[1], yaxis[2], 0,
			zaxis[0], zaxis[1], zaxis[2], 0,
			position[0], position[1], position[2], 1
		)
	{}

	Matrix4(const T * src)
	:	Base(src)
	{}

	Matrix4(const Base & src)
	:	Base(src)
	{}

	Matrix4& set(const Base & src) { Base::set(src.elems); return *this; }

	Quat<T>& toQuat() {
		Quat<T> q;
		q.fromMatrix(Base::elems);
		return q;
	}
	void fromQuat(Quat<T>& q) { q.toMatrix(Base::elems); }

	static const Matrix4 identity() {
		return Matrix4(
			1,	0,	0,	0,
			0,	1,	0,	0,
			0,	0,	1,	0,
			0,	0,	0,	1
		);
	}

	static const Matrix4 translate(T x, T y, T z) {
		return Matrix4(
			1, 0, 0, x,
			0, 1, 0, y,
			0, 0, 1, z,
			0, 0, 0, 1
		);
	}

	static const Matrix4 scale(T x, T y, T z) {
		return Matrix4(
			x,	0,	0,	0,
			0,	y,	0,	0,
			0,	0,	z,	0,
			0,	0,	0,	1
		);
	}

	static const Matrix4 rotateYZ(T theta) {
		const T C = cos(theta);
		const T S = sin(theta);
		return Matrix4(	1,	0,	0,	0,
						0,	C,	S,	0,
						0,	-S,	C,	0,
						0,	0,	0,	1	);
	}
	static const Matrix4 rotateZX(T theta) {
		const T C = cos(theta);
		const T S = sin(theta);
		return Matrix4(	C,	0,	-S,	0,
						0,	1,	0,	0,
						S,	0,	C,	0,
						0,	0,	0,	1 );
	}
	static const Matrix4 rotateXY(T theta) {
		const T C = cos(theta);
		const T S = sin(theta);
		return Matrix4(	C,	S,	0,	0,
						-S,	C,	0,	0,
						0,	0,	1,	0,
						0,	0,	0,	1	);
	}

	static const Matrix4 rotate(float angle, const Vec<3, T> &v) {
		Vec<3, T> axis(v);
		axis.normalize();

		float c = cos(angle*M_DEG2RAD);
		float s = sin(angle*M_DEG2RAD);

		Matrix4 m(
			axis[0]*axis[0]*(1-c)+c,
			axis[1]*axis[0]*(1-c)+axis[2]*s,
			axis[0]*axis[2]*(1-c)-axis[1]*s,
			0,

			axis[0]*axis[1]*(1-c)-axis[2]*s,
			axis[1]*axis[1]*(1-c)+c,
			axis[1]*axis[2]*(1-c)+axis[0]*s,
			0,

			axis[0]*axis[2]*(1-c)+axis[1]*s,
			axis[1]*axis[2]*(1-c)-axis[0]*s,
			axis[2]*axis[2]*(1-c)+c,
			0,

			0, 0, 0, 1
		);

		return m;
	}

	static const Matrix4 shearYZ(T y, T z) {
		return Matrix4(	1,	y,	z,	0,
						0,	1,	0,	0,
						0,	0,	1,	0,
						0,	0,	0,	1	);
	}
	static const Matrix4 shearZX(T z, T x) {
		return Matrix4(	1,	0,	0,	0,
						x,	1,	z,	0,
						0,	0,	1,	0,
						0,	0,	0,	1	);
	}
	static const Matrix4 shearXY(T x, T y) {
		return Matrix4(	1,	0,	0,	0,
						0,	1,	0,	0,
						x,	y,	1,	0,
						0,	0,	0,	1	);
	}

	static const Matrix4 perspective(T l, T r, T b, T t, T n, T f) {
		const T W = r-l;	const T W2 = r+l;
		const T H = t-b;	const T H2 = t+b;
		const T D = f-n;	const T D2 = f+n;
		const T n2 = n*2;
		const T fn2 = f*n2;
		return Matrix4(	n2/W,	0,		0,		0,
						0,		n2/H,	0,		0,
						W2/W,	H2/H,	-D2/D,	-1,
						0,		0,		-fn2/D,	0 );
	}

	static const Matrix4 perspective(T fovy, T aspect, T near, T far) {
		float f = 1/tan(fovy*M_DEG2RAD/2.);
		return Matrix4(
			f/aspect, 0, 0, 0,
			0, f, 0, 0,
			0, 0, (far+near)/(near-far), -1,
			0, 0, (2*far*near)/(near-far), 0
		);
	}

	// for stereographics:
	static const Matrix4 perspectiveLeft(T fovy, T aspect, T near, T far, T eyeSep, T focal) {
		T shift = 0.5*eyeSep*near/focal;				// stereo eye separation adjustment
		T top = near * tan(fovy*M_DEG2RAD*0.5);	// height of view at distance = near
		T bottom = -top;
		T left = -aspect*top + shift;
		T right = aspect*top + shift;
		return perspective(left, right, bottom, top, near, far);
	}

	// for stereographics:
	static const Matrix4 perspectiveRight(T fovy, T aspect, T near, T far, T eyeSep, T focal) {
		T shift = -0.5*eyeSep*near/focal;				// stereo eye separation adjustment
		T top = near * tan(fovy*M_DEG2RAD*0.5);	// height of view at distance = near
		T bottom = -top;
		T left = -aspect*top + shift;
		T right = aspect*top + shift;
		return perspective(left, right, bottom, top, near, far);
	}

	static const Matrix4 unPerspective(T l, T r, T b, T t, T n, T f) {
		const T W = r-l;	const T W2 = r+l;
		const T H = t-b;	const T H2 = t+b;
		const T D = f-n;	const T D2 = f+n;
		const T n2 = n*2;
		const T fn2 = f*n2;
		return Matrix4(	W/n2,	0,		0,		0,
						0,		H/n2,	0,		0,
						0,		0,		0,		-D/fn2,
						W2/n2,	H2/n2,	-1,		D2/fn2	);
	}

	static const Matrix4 ortho(T l, T r, T b, T t, T n, T f) {
		const T W = r-l;	const T W2 = r+l;
		const T H = t-b;	const T H2 = t+b;
		const T D = f-n;	const T D2 = f+n;
		return Matrix4(	2/W,	0,		0,		0,
						0,		2/H,	0,		0,
						0,		0,		-2/D,	0,
						-W2/W,	-H2/H,	-D2/D,	1	);
	}

	static const Matrix4 unOrtho(T l, T r, T b, T t, T n, T f) {
		const T W = r-l;	const T W2 = r+l;
		const T H = t-b;	const T H2 = t+b;
		const T D = f-n;	const T D2 = f+n;
		return Matrix4(	W/2,	0,		0,		0,
						0,		H/2,	0,		0,
						0,		0,		D/-2,	0,
						W2/2,	H2/2,	D2/2,	1	);
	}

	static const Matrix4 lookAt(const Vec3<T>& ux, const Vec3<T>& uz, const Vec3<T>& uy, const Vec3<T>& pos) {
		return Matrix4(
			ux[0], uy[0], -uz[0], 0,
			ux[1], uy[1], -uz[1], 0,
			ux[2], uy[2], -uz[2], 0,
			-(ux.dot(pos)), -(uy.dot(pos)), (uz.dot(pos)), 1
		);
	}

	// for stereographics:
	static const Matrix4 lookAtLeft(const Vec3<T>& ux, const Vec3<T>& uz, const Vec3<T>& uy, const Vec3<T>& pos, double eyeSep) {
		Vec3<T> eyePos = pos - (ux * eyeSep);

		return Matrix4(
			ux[0], uy[0], -uz[0], 0,
			ux[1], uy[1], -uz[1], 0,
			ux[2], uy[2], -uz[2], 0,
			-(ux.dot(eyePos)), -(uy.dot(eyePos)), (uz.dot(eyePos)), 1
		);
	}
	static const Matrix4 lookAtRight(const Vec3<T>& ux, const Vec3<T>& uz, const Vec3<T>& uy, const Vec3<T>& pos, double eyeSep) {
		Vec3<T> eyePos = pos + (ux * eyeSep);

		return Matrix4(
			ux[0], uy[0], -uz[0], 0,
			ux[1], uy[1], -uz[1], 0,
			ux[2], uy[2], -uz[2], 0,
			-(ux.dot(eyePos)), -(uy.dot(eyePos)), (uz.dot(eyePos)), 1
		);
	}

};

typedef Matrix4<double>	Matrix4d;	///< Double-precision quaternion
typedef Matrix4<float>	Matrix4f;	///< Single-precision quaternion

} // al::

#endif /* include guard */
<commit_msg>applied suggestions by lance to matrix4<commit_after>#ifndef INCLUDE_AL_MATRIX4_HPP
#define INCLUDE_AL_MATRIX4_HPP

#include "math/al_Constants.hpp"
#include "math/al_Quat.hpp"
#include "math/al_Vec.hpp"

namespace al {

template<class T> class Matrix4;

/// 4x4 Matrix (Homogenous Transform)
template<typename T=double>
class Matrix4 : public Mat<4, T> {
public:
	typedef Mat<4, T> Base;

	Matrix4()
	: Base(
		1, 0, 0, 0,
		0, 1, 0, 0,
		0, 0, 1, 0,
		0, 0, 0, 1
	)
	{}

	Matrix4(
		const T& v11, const T& v21, const T& v31, const T& v41,
		const T& v12, const T& v22, const T& v32, const T& v42,
		const T& v13, const T& v23, const T& v33, const T& v43,
		const T& v14, const T& v24, const T& v34, const T& v44
	)
	:	Base(
			v11, v21, v31, v41,
			v12, v22, v32, v42,
			v13, v23, v33, v43,
			v14, v24, v34, v44
		)
	{}

	Matrix4(
		const Vec3<T>& xaxis,
		const Vec3<T>& yaxis,
		const Vec3<T>& zaxis,
		const Vec3<T>& position
	)
	:	Base(
			xaxis[0], xaxis[1], xaxis[2], 0,
			yaxis[0], yaxis[1], yaxis[2], 0,
			zaxis[0], zaxis[1], zaxis[2], 0,
			position[0], position[1], position[2], 1
		)
	{}

	Matrix4(const T * src)
	:	Base(src)
	{}

	Matrix4(const Base & src)
	:	Base(src)
	{}

	Matrix4& set(const Base & src) { Base::set(src.elems); return *this; }

	Quat<T>& toQuat() {
		Quat<T> q;
		q.fromMatrix(Base::elems);
		return q;
	}
	void fromQuat(Quat<T>& q) { q.toMatrix(Base::elems); }

	static const Matrix4 identity() {
		return Matrix4(
			1,	0,	0,	0,
			0,	1,	0,	0,
			0,	0,	1,	0,
			0,	0,	0,	1
		);
	}

	static const Matrix4 translate(T x, T y, T z) {
		return Matrix4(
			1, 0, 0, x,
			0, 1, 0, y,
			0, 0, 1, z,
			0, 0, 0, 1
		);
	}

	static const Matrix4 scale(T x, T y, T z) {
		return Matrix4(
			x,	0,	0,	0,
			0,	y,	0,	0,
			0,	0,	z,	0,
			0,	0,	0,	1
		);
	}

	static const Matrix4 rotateYZ(T theta) {
		const T C = cos(theta);
		const T S = sin(theta);
		return Matrix4(	1,	0,	0,	0,
						0,	C,	S,	0,
						0,	-S,	C,	0,
						0,	0,	0,	1	);
	}
	static const Matrix4 rotateZX(T theta) {
		const T C = cos(theta);
		const T S = sin(theta);
		return Matrix4(	C,	0,	-S,	0,
						0,	1,	0,	0,
						S,	0,	C,	0,
						0,	0,	0,	1 );
	}
	static const Matrix4 rotateXY(T theta) {
		const T C = cos(theta);
		const T S = sin(theta);
		return Matrix4(	C,	S,	0,	0,
						-S,	C,	0,	0,
						0,	0,	1,	0,
						0,	0,	0,	1	);
	}

	static const Matrix4 rotate(float angle, const Vec<3, T> &v) {
		Vec<3, T> axis(v);
		axis.normalize();

		float c = cos(angle*M_DEG2RAD);
		float s = sin(angle*M_DEG2RAD);

		Matrix4 m(
			axis[0]*axis[0]*(1-c)+c,
			axis[1]*axis[0]*(1-c)+axis[2]*s,
			axis[0]*axis[2]*(1-c)-axis[1]*s,
			0,

			axis[0]*axis[1]*(1-c)-axis[2]*s,
			axis[1]*axis[1]*(1-c)+c,
			axis[1]*axis[2]*(1-c)+axis[0]*s,
			0,

			axis[0]*axis[2]*(1-c)+axis[1]*s,
			axis[1]*axis[2]*(1-c)-axis[0]*s,
			axis[2]*axis[2]*(1-c)+c,
			0,

			0, 0, 0, 1
		);

		return m;
	}

	static const Matrix4 shearYZ(T y, T z) {
		return Matrix4(	1,	y,	z,	0,
						0,	1,	0,	0,
						0,	0,	1,	0,
						0,	0,	0,	1	);
	}
	static const Matrix4 shearZX(T z, T x) {
		return Matrix4(	1,	0,	0,	0,
						x,	1,	z,	0,
						0,	0,	1,	0,
						0,	0,	0,	1	);
	}
	static const Matrix4 shearXY(T x, T y) {
		return Matrix4(	1,	0,	0,	0,
						0,	1,	0,	0,
						x,	y,	1,	0,
						0,	0,	0,	1	);
	}

	static const Matrix4 perspective(T l, T r, T b, T t, T n, T f) {
		const T W = r-l;	const T W2 = r+l;
		const T H = t-b;	const T H2 = t+b;
		const T D = f-n;	const T D2 = f+n;
		const T n2 = n*2;
		const T fn2 = f*n2;
		return Matrix4(	n2/W,	0,		0,		0,
						0,		n2/H,	0,		0,
						W2/W,	H2/H,	-D2/D,	-1,
						0,		0,		-fn2/D,	0 );
	}

	static const Matrix4 perspective(T fovy, T aspect, T near, T far) {
		float f = 1/tan(fovy*M_DEG2RAD/2.);
		return Matrix4(
			f/aspect, 0, 0, 0,
			0, f, 0, 0,
			0, 0, (far+near)/(near-far), -1,
			0, 0, (2*far*near)/(near-far), 0
		);
	}

	// for stereographics:
	static const Matrix4 perspectiveLeft(T fovy, T aspect, T near, T far, T eyeSep, T focal) {
		return perspectiveOffAxis(fovy, aspect, near, far,-eyeSep, focal);
	}
	static const Matrix4 perspectiveRight(T fovy, T aspect, T near, T far, T eyeSep, T focal) {
		return perspectiveOffAxis(fovy, aspect, near, far, eyeSep, focal);
	}
	static const Matrix4 perspectiveOffAxis(T fovy, T aspect, T near, T far, T eyeShift, T focal) {
		T shift = -0.5*eyeShift*near/focal;
		T top = near * tan(fovy*M_DEG2RAD*0.5);	// height of view at distance = near
		T bottom = -top;
		T left = -aspect*top + shift;
		T right = aspect*top + shift;
		return perspective(left, right, bottom, top, near, far);
	}

	static const Matrix4 unPerspective(T l, T r, T b, T t, T n, T f) {
		const T W = r-l;	const T W2 = r+l;
		const T H = t-b;	const T H2 = t+b;
		const T D = f-n;	const T D2 = f+n;
		const T n2 = n*2;
		const T fn2 = f*n2;
		return Matrix4(	W/n2,	0,		0,		0,
						0,		H/n2,	0,		0,
						0,		0,		0,		-D/fn2,
						W2/n2,	H2/n2,	-1,		D2/fn2	);
	}

	static const Matrix4 ortho(T l, T r, T b, T t, T n, T f) {
		const T W = r-l;	const T W2 = r+l;
		const T H = t-b;	const T H2 = t+b;
		const T D = f-n;	const T D2 = f+n;
		return Matrix4(	2/W,	0,		0,		0,
						0,		2/H,	0,		0,
						0,		0,		-2/D,	0,
						-W2/W,	-H2/H,	-D2/D,	1	);
	}

	static const Matrix4 unOrtho(T l, T r, T b, T t, T n, T f) {
		const T W = r-l;	const T W2 = r+l;
		const T H = t-b;	const T H2 = t+b;
		const T D = f-n;	const T D2 = f+n;
		return Matrix4(	W/2,	0,		0,		0,
						0,		H/2,	0,		0,
						0,		0,		D/-2,	0,
						W2/2,	H2/2,	D2/2,	1	);
	}

	static const Matrix4 lookAt(const Vec3<T>& ux, const Vec3<T>& uz, const Vec3<T>& uy, const Vec3<T>& pos) {
		return Matrix4(
			ux[0], uy[0], -uz[0], 0,
			ux[1], uy[1], -uz[1], 0,
			ux[2], uy[2], -uz[2], 0,
			-(ux.dot(pos)), -(uy.dot(pos)), (uz.dot(pos)), 1
		);
	}

	// for stereographics:
	static const Matrix4 lookAtLeft(const Vec3<T>& ux, const Vec3<T>& uz, const Vec3<T>& uy, const Vec3<T>& pos, double eyeSep) {
		return lookAtOffAxis(ux,uz,uy, pos,-eyeSep);
	}
	static const Matrix4 lookAtRight(const Vec3<T>& ux, const Vec3<T>& uz, const Vec3<T>& uy, const Vec3<T>& pos, double eyeSep) {
		return lookAtOffAxis(ux,uz,uy, pos, eyeSep);
	}
	static const Matrix4 lookAtOffAxis(const Vec3<T>& ux, const Vec3<T>& uz, const Vec3<T>& uy, const Vec3<T>& pos, double eyeShift){
		Vec3<T> eyePos = pos + (ux * eyeShift);

		return Matrix4(
			ux[0], uy[0], -uz[0], 0,
			ux[1], uy[1], -uz[1], 0,
			ux[2], uy[2], -uz[2], 0,
			-(ux.dot(eyePos)), -(uy.dot(eyePos)), (uz.dot(eyePos)), 1
		);
	}

};

typedef Matrix4<double>	Matrix4d;	///< Double-precision quaternion
typedef Matrix4<float>	Matrix4f;	///< Single-precision quaternion

} // al::

#endif /* include guard */
<|endoftext|>


<commit_before>#pragma once

#include <iterator>

namespace helene
{

template <class IteratorCategory, class IteratorToStruct>
class member_iterator_base;

template <class IteratorToStruct>
class member_iterator_base<std::input_iterator_tag, IteratorToStruct>
{
public:
    member_iterator_base(IteratorToStruct it) : current_(it)
    {
    }

    bool
    operator!=(const member_iterator_base& other) const
    {
        return current_ != other.current_;
    }

protected:
    IteratorToStruct current_;
};

template <class IteratorToStruct>
class member_iterator_base<std::forward_iterator_tag, IteratorToStruct>
    : public member_iterator_base<std::input_iterator_tag, IteratorToStruct>
{
public:
    using member_iterator_base<std::input_iterator_tag,
                               IteratorToStruct>::member_iterator_base;
};

/*
template <class IteratorToStruct>
class member_iterator_base<std::random_access_iterator_tag, IteratorToStruct>
{
public:
    member_iterator_base(IteratorToStruct it) : current_(it)
    {
    }

protected:
    IteratorToStruct current_;
};
*/

template <class MemberType,
          class StructType,
          class IteratorToStruct,
          MemberType StructType::*PtrValue>
class member_iterator
    : public member_iterator_base<
          typename std::iterator_traits<IteratorToStruct>::iterator_category,
          IteratorToStruct>
{
public:
    // using base class constructor directly
    using member_iterator_base<
        typename std::iterator_traits<IteratorToStruct>::iterator_category,
        IteratorToStruct>::member_iterator_base;
};
}
<commit_msg>Add additional template parameter to member_iterator_base. 	modified:   include/member_iterator.hpp<commit_after>#pragma once

#include <iterator>

namespace helene
{

template <class IteratorCategory, class IteratorToStruct, class MemberType>
class member_iterator_base;

template <class IteratorToStruct, class MemberType>
class member_iterator_base<std::input_iterator_tag,
                           IteratorToStruct,
                           MemberType>
{
public:
    member_iterator_base(IteratorToStruct it) : current_(it)
    {
    }

    bool
    operator!=(const member_iterator_base& other) const
    {
        return current_ != other.current_;
    }

protected:
    IteratorToStruct current_;
};

template <class IteratorToStruct, class MemberType>
class member_iterator_base<std::forward_iterator_tag,
                           IteratorToStruct,
                           MemberType>
    : public member_iterator_base<std::input_iterator_tag,
                                  IteratorToStruct,
                                  MemberType>
{
public:
    using member_iterator_base<std::input_iterator_tag,
                               IteratorToStruct,
                               MemberType>::member_iterator_base;
};

/*
template <class IteratorToStruct>
class member_iterator_base<std::random_access_iterator_tag, IteratorToStruct>
{
public:
    member_iterator_base(IteratorToStruct it) : current_(it)
    {
    }

protected:
    IteratorToStruct current_;
};
*/

template <class MemberType,
          class StructType,
          class IteratorToStruct,
          MemberType StructType::*PtrValue>
class member_iterator
    : public member_iterator_base<
          typename std::iterator_traits<IteratorToStruct>::iterator_category,
          IteratorToStruct,
          MemberType>
{
public:
    // using base class constructor directly
    using member_iterator_base<
        typename std::iterator_traits<IteratorToStruct>::iterator_category,
        IteratorToStruct,
        MemberType>::member_iterator_base;

};
}
<|endoftext|>


<commit_before>#pragma once

#include "adapters/net.hpp"
#include "drawtypes/animation.hpp"
#include "drawtypes/label.hpp"
#include "drawtypes/ramp.hpp"
#include "modules/meta.hpp"

#define DEFAULT_FORMAT_CONNECTED TAG_LABEL_CONNECTED
#define DEFAULT_FORMAT_DISCONNECTED TAG_LABEL_DISCONNECTED
#define DEFAULT_FORMAT_PACKETLOSS TAG_LABEL_CONNECTED

#define DEFAULT_LABEL_CONNECTED "%ifname% %local_ip%"
#define DEFAULT_LABEL_DISCONNECTED ""
#define DEFAULT_LABEL_PACKETLOSS ""

LEMONBUDDY_NS

namespace modules {

  class network_module : public timer_module<network_module> {
   public:
    using timer_module::timer_module;

    void setup() {
      // Load configuration values
      m_interface = m_conf.get<string>(name(), "interface");
      m_interval = chrono::duration<double>(m_conf.get<float>(name(), "interval", 1));
      m_ping_nth_update = m_conf.get<int>(name(), "ping-interval", 0);
      m_udspeed_minwidth = m_conf.get<int>(name(), "udspeed-minwidth", m_udspeed_minwidth);

      // Add formats
      m_formatter->add(
          FORMAT_CONNECTED, DEFAULT_FORMAT_CONNECTED, {TAG_RAMP_SIGNAL, TAG_LABEL_CONNECTED});
      m_formatter->add(FORMAT_DISCONNECTED, DEFAULT_FORMAT_DISCONNECTED, {TAG_LABEL_DISCONNECTED});

      // Create elements for format-connected
      if (m_formatter->has(TAG_RAMP_SIGNAL, FORMAT_CONNECTED))
        m_ramp_signal = get_config_ramp(m_conf, name(), TAG_RAMP_SIGNAL);
      if (m_formatter->has(TAG_LABEL_CONNECTED, FORMAT_CONNECTED)) {
        m_label_connected =
            get_optional_config_label(m_conf, name(), TAG_LABEL_CONNECTED, DEFAULT_LABEL_CONNECTED);
        m_label_connected_tokenized = m_label_connected->clone();
      }

      // Create elements for format-disconnected
      if (m_formatter->has(TAG_LABEL_DISCONNECTED, FORMAT_DISCONNECTED)) {
        m_label_disconnected = get_optional_config_label(
            m_conf, name(), TAG_LABEL_DISCONNECTED, DEFAULT_LABEL_DISCONNECTED);
        m_label_disconnected->replace_token("%ifname%", m_interface);
      }

      // Create elements for format-packetloss if we are told to test connectivity
      if (m_ping_nth_update > 0) {
        m_formatter->add(FORMAT_PACKETLOSS, DEFAULT_FORMAT_PACKETLOSS,
            {TAG_ANIMATION_PACKETLOSS, TAG_LABEL_PACKETLOSS, TAG_LABEL_CONNECTED});

        if (m_formatter->has(TAG_LABEL_PACKETLOSS, FORMAT_PACKETLOSS)) {
          m_label_packetloss = get_optional_config_label(
              m_conf, name(), TAG_LABEL_PACKETLOSS, DEFAULT_LABEL_PACKETLOSS);
          m_label_packetloss_tokenized = m_label_packetloss->clone();
        }
        if (m_formatter->has(TAG_ANIMATION_PACKETLOSS, FORMAT_PACKETLOSS))
          m_animation_packetloss = get_config_animation(m_conf, name(), TAG_ANIMATION_PACKETLOSS);
      }

      // Get an intstance of the network interface
      try {
        if (net::is_wireless_interface(m_interface)) {
          m_wireless_network = make_unique<net::wireless_network>(m_interface);
        } else {
          m_wired_network = make_unique<net::wired_network>(m_interface);
        }
      } catch (net::network_error& e) {
        m_log.err("%s: %s", name(), e.what());
        std::exit(EXIT_FAILURE);
      }
    }

    void start() {
      timer_module::start();

      // We only need to start the subthread if the packetloss animation is used
      if (m_animation_packetloss)
        m_threads.emplace_back(thread(&network_module::subthread_routine, this));
    }
    bool update() {
      string ip, essid, linkspeed;
      int signal_quality = 0;

      net::network* network = nullptr;

      // Process data for wireless network interfaces
      if (m_wireless_network) {
        network = m_wireless_network.get();

        try {
          essid = m_wireless_network->essid();
          signal_quality = m_wireless_network->signal_quality();
        } catch (net::wireless_network_error& e) {
          m_log.trace("%s: %s", name(), e.what());
        }

        m_signal_quality = signal_quality;

        // Process data for wired network interfaces
      } else if (m_wired_network) {
        network = m_wired_network.get();
        linkspeed = m_wired_network->link_speed();
      }

      if (network != nullptr) {
        try {
          ip = network->ip();
        } catch (net::network_error& e) {
          m_log.trace("%s: %s", name(), e.what());
        }

        m_connected = network->connected();

        // Ignore the first run
        if (m_counter == -1) {
          m_counter = 0;
        } else if (m_ping_nth_update > 0 && m_connected && (++m_counter % m_ping_nth_update) == 0) {
          m_conseq_packetloss = !network->test();
          m_counter = 0;
        }
      }

      // Update label contents
      if (m_label_connected || m_label_packetloss) {
        auto replace_tokens = [&](label_t label) {
          label->replace_token("%ifname%", m_interface);
          label->replace_token("%local_ip%", !ip.empty() ? ip : "x.x.x.x");

          if (m_wired_network) {
            label->replace_token("%linkspeed%", linkspeed);
          } else if (m_wireless_network) {
            label->replace_token("%essid%", !essid.empty() ? essid : "UNKNOWN");
            label->replace_token("%signal%", to_string(signal_quality) + "%");
          }

          auto upspeed = network->upspeed(m_udspeed_minwidth);
          auto downspeed = network->downspeed(m_udspeed_minwidth);

          label->replace_token("%upspeed%", upspeed);
          label->replace_token("%downspeed%", downspeed);
        };

        if (m_label_connected) {
          m_label_connected_tokenized->m_text = m_label_connected->m_text;
          replace_tokens(m_label_connected_tokenized);
        }

        if (m_label_packetloss) {
          m_label_packetloss_tokenized->m_text = m_label_packetloss->m_text;
          replace_tokens(m_label_packetloss_tokenized);
        }
      }

      return true;
    }

    string get_format() {
      if (!m_connected)
        return FORMAT_DISCONNECTED;
      else if (m_conseq_packetloss && m_ping_nth_update > 0)
        return FORMAT_PACKETLOSS;
      else
        return FORMAT_CONNECTED;
    }

    bool build(builder* builder, string tag) {
      if (tag == TAG_LABEL_CONNECTED)
        builder->node(m_label_connected_tokenized);
      else if (tag == TAG_LABEL_DISCONNECTED)
        builder->node(m_label_disconnected);
      else if (tag == TAG_LABEL_PACKETLOSS)
        builder->node(m_label_packetloss_tokenized);
      else if (tag == TAG_ANIMATION_PACKETLOSS)
        builder->node(m_animation_packetloss->get());
      else if (tag == TAG_RAMP_SIGNAL)
        builder->node(m_ramp_signal->get_by_percentage(m_signal_quality));
      else
        return false;
      return true;
    }

   protected:
    void subthread_routine() {
      this_thread::yield();

      const auto dur =
          chrono::duration<double>(float(m_animation_packetloss->framerate()) / 1000.0f);

      while (enabled()) {
        if (m_connected && m_conseq_packetloss)
          broadcast();

        sleep(dur);
      }

      m_log.trace("%s: Reached end of network subthread", name());
    }

   private:
    static constexpr auto FORMAT_CONNECTED = "format-connected";
    static constexpr auto FORMAT_PACKETLOSS = "format-packetloss";
    static constexpr auto FORMAT_DISCONNECTED = "format-disconnected";

    static constexpr auto TAG_RAMP_SIGNAL = "<ramp-signal>";
    static constexpr auto TAG_LABEL_CONNECTED = "<label-connected>";
    static constexpr auto TAG_LABEL_DISCONNECTED = "<label-disconnected>";
    static constexpr auto TAG_LABEL_PACKETLOSS = "<label-packetloss>";
    static constexpr auto TAG_ANIMATION_PACKETLOSS = "<animation-packetloss>";

    unique_ptr<net::wired_network> m_wired_network;
    unique_ptr<net::wireless_network> m_wireless_network;

    ramp_t m_ramp_signal;
    animation_t m_animation_packetloss;
    label_t m_label_connected;
    label_t m_label_connected_tokenized;
    label_t m_label_disconnected;
    label_t m_label_packetloss;
    label_t m_label_packetloss_tokenized;

    stateflag m_connected{false};
    stateflag m_conseq_packetloss{false};

    string m_interface;
    int m_signal_quality;
    int m_ping_nth_update;
    int m_counter = -1;  // -1 to ignore the first run
    int m_udspeed_minwidth = 3;
  };
}

LEMONBUDDY_NS_END
<commit_msg>fix(network): Let module fail silently<commit_after>#pragma once

#include "adapters/net.hpp"
#include "drawtypes/animation.hpp"
#include "drawtypes/label.hpp"
#include "drawtypes/ramp.hpp"
#include "modules/meta.hpp"

#define DEFAULT_FORMAT_CONNECTED TAG_LABEL_CONNECTED
#define DEFAULT_FORMAT_DISCONNECTED TAG_LABEL_DISCONNECTED
#define DEFAULT_FORMAT_PACKETLOSS TAG_LABEL_CONNECTED

#define DEFAULT_LABEL_CONNECTED "%ifname% %local_ip%"
#define DEFAULT_LABEL_DISCONNECTED ""
#define DEFAULT_LABEL_PACKETLOSS ""

LEMONBUDDY_NS

namespace modules {

  class network_module : public timer_module<network_module> {
   public:
    using timer_module::timer_module;

    void setup() {
      // Load configuration values
      m_interface = m_conf.get<string>(name(), "interface");
      m_interval = chrono::duration<double>(m_conf.get<float>(name(), "interval", 1));
      m_ping_nth_update = m_conf.get<int>(name(), "ping-interval", 0);
      m_udspeed_minwidth = m_conf.get<int>(name(), "udspeed-minwidth", m_udspeed_minwidth);

      // Add formats
      m_formatter->add(
          FORMAT_CONNECTED, DEFAULT_FORMAT_CONNECTED, {TAG_RAMP_SIGNAL, TAG_LABEL_CONNECTED});
      m_formatter->add(FORMAT_DISCONNECTED, DEFAULT_FORMAT_DISCONNECTED, {TAG_LABEL_DISCONNECTED});

      // Create elements for format-connected
      if (m_formatter->has(TAG_RAMP_SIGNAL, FORMAT_CONNECTED))
        m_ramp_signal = get_config_ramp(m_conf, name(), TAG_RAMP_SIGNAL);
      if (m_formatter->has(TAG_LABEL_CONNECTED, FORMAT_CONNECTED)) {
        m_label_connected =
            get_optional_config_label(m_conf, name(), TAG_LABEL_CONNECTED, DEFAULT_LABEL_CONNECTED);
        m_label_connected_tokenized = m_label_connected->clone();
      }

      // Create elements for format-disconnected
      if (m_formatter->has(TAG_LABEL_DISCONNECTED, FORMAT_DISCONNECTED)) {
        m_label_disconnected = get_optional_config_label(
            m_conf, name(), TAG_LABEL_DISCONNECTED, DEFAULT_LABEL_DISCONNECTED);
        m_label_disconnected->replace_token("%ifname%", m_interface);
      }

      // Create elements for format-packetloss if we are told to test connectivity
      if (m_ping_nth_update > 0) {
        m_formatter->add(FORMAT_PACKETLOSS, DEFAULT_FORMAT_PACKETLOSS,
            {TAG_ANIMATION_PACKETLOSS, TAG_LABEL_PACKETLOSS, TAG_LABEL_CONNECTED});

        if (m_formatter->has(TAG_LABEL_PACKETLOSS, FORMAT_PACKETLOSS)) {
          m_label_packetloss = get_optional_config_label(
              m_conf, name(), TAG_LABEL_PACKETLOSS, DEFAULT_LABEL_PACKETLOSS);
          m_label_packetloss_tokenized = m_label_packetloss->clone();
        }
        if (m_formatter->has(TAG_ANIMATION_PACKETLOSS, FORMAT_PACKETLOSS))
          m_animation_packetloss = get_config_animation(m_conf, name(), TAG_ANIMATION_PACKETLOSS);
      }

      // Get an intstance of the network interface
      if (net::is_wireless_interface(m_interface)) {
        m_wireless_network = make_unique<net::wireless_network>(m_interface);
      } else {
        m_wired_network = make_unique<net::wired_network>(m_interface);
      }
    }

    void start() {
      timer_module::start();

      // We only need to start the subthread if the packetloss animation is used
      if (m_animation_packetloss)
        m_threads.emplace_back(thread(&network_module::subthread_routine, this));
    }
    bool update() {
      string ip, essid, linkspeed;
      int signal_quality = 0;

      net::network* network = nullptr;

      // Process data for wireless network interfaces
      if (m_wireless_network) {
        network = m_wireless_network.get();

        try {
          essid = m_wireless_network->essid();
          signal_quality = m_wireless_network->signal_quality();
        } catch (net::wireless_network_error& e) {
          m_log.trace("%s: %s", name(), e.what());
        }

        m_signal_quality = signal_quality;

        // Process data for wired network interfaces
      } else if (m_wired_network) {
        network = m_wired_network.get();
        linkspeed = m_wired_network->link_speed();
      }

      if (network != nullptr) {
        try {
          ip = network->ip();
        } catch (net::network_error& e) {
          m_log.trace("%s: %s", name(), e.what());
        }

        m_connected = network->connected();

        // Ignore the first run
        if (m_counter == -1) {
          m_counter = 0;
        } else if (m_ping_nth_update > 0 && m_connected && (++m_counter % m_ping_nth_update) == 0) {
          m_conseq_packetloss = !network->test();
          m_counter = 0;
        }
      }

      // Update label contents
      if (m_label_connected || m_label_packetloss) {
        auto replace_tokens = [&](label_t label) {
          label->replace_token("%ifname%", m_interface);
          label->replace_token("%local_ip%", !ip.empty() ? ip : "x.x.x.x");

          if (m_wired_network) {
            label->replace_token("%linkspeed%", linkspeed);
          } else if (m_wireless_network) {
            label->replace_token("%essid%", !essid.empty() ? essid : "UNKNOWN");
            label->replace_token("%signal%", to_string(signal_quality) + "%");
          }

          auto upspeed = network->upspeed(m_udspeed_minwidth);
          auto downspeed = network->downspeed(m_udspeed_minwidth);

          label->replace_token("%upspeed%", upspeed);
          label->replace_token("%downspeed%", downspeed);
        };

        if (m_label_connected) {
          m_label_connected_tokenized->m_text = m_label_connected->m_text;
          replace_tokens(m_label_connected_tokenized);
        }

        if (m_label_packetloss) {
          m_label_packetloss_tokenized->m_text = m_label_packetloss->m_text;
          replace_tokens(m_label_packetloss_tokenized);
        }
      }

      return true;
    }

    string get_format() {
      if (!m_connected)
        return FORMAT_DISCONNECTED;
      else if (m_conseq_packetloss && m_ping_nth_update > 0)
        return FORMAT_PACKETLOSS;
      else
        return FORMAT_CONNECTED;
    }

    bool build(builder* builder, string tag) {
      if (tag == TAG_LABEL_CONNECTED)
        builder->node(m_label_connected_tokenized);
      else if (tag == TAG_LABEL_DISCONNECTED)
        builder->node(m_label_disconnected);
      else if (tag == TAG_LABEL_PACKETLOSS)
        builder->node(m_label_packetloss_tokenized);
      else if (tag == TAG_ANIMATION_PACKETLOSS)
        builder->node(m_animation_packetloss->get());
      else if (tag == TAG_RAMP_SIGNAL)
        builder->node(m_ramp_signal->get_by_percentage(m_signal_quality));
      else
        return false;
      return true;
    }

   protected:
    void subthread_routine() {
      this_thread::yield();

      const auto dur =
          chrono::duration<double>(float(m_animation_packetloss->framerate()) / 1000.0f);

      while (enabled()) {
        if (m_connected && m_conseq_packetloss)
          broadcast();

        sleep(dur);
      }

      m_log.trace("%s: Reached end of network subthread", name());
    }

   private:
    static constexpr auto FORMAT_CONNECTED = "format-connected";
    static constexpr auto FORMAT_PACKETLOSS = "format-packetloss";
    static constexpr auto FORMAT_DISCONNECTED = "format-disconnected";

    static constexpr auto TAG_RAMP_SIGNAL = "<ramp-signal>";
    static constexpr auto TAG_LABEL_CONNECTED = "<label-connected>";
    static constexpr auto TAG_LABEL_DISCONNECTED = "<label-disconnected>";
    static constexpr auto TAG_LABEL_PACKETLOSS = "<label-packetloss>";
    static constexpr auto TAG_ANIMATION_PACKETLOSS = "<animation-packetloss>";

    unique_ptr<net::wired_network> m_wired_network;
    unique_ptr<net::wireless_network> m_wireless_network;

    ramp_t m_ramp_signal;
    animation_t m_animation_packetloss;
    label_t m_label_connected;
    label_t m_label_connected_tokenized;
    label_t m_label_disconnected;
    label_t m_label_packetloss;
    label_t m_label_packetloss_tokenized;

    stateflag m_connected{false};
    stateflag m_conseq_packetloss{false};

    string m_interface;
    int m_signal_quality;
    int m_ping_nth_update;
    int m_counter = -1;  // -1 to ignore the first run
    int m_udspeed_minwidth = 3;
  };
}

LEMONBUDDY_NS_END
<|endoftext|>


<commit_before>#include <cstddef>
#include <optional>
#include <string>
#include <tabulate/color.hpp>
#include <tabulate/font_align.hpp>
#include <tabulate/font_style.hpp>
#include <vector>

namespace tabulate {

class Format {
public:
  Format &width(size_t value) {
    width_ = value;
    return *this;
  }

  Format &height(size_t value) {
    height_ = value;
    return *this;
  }

  Format &margin(size_t value) {
    margin_left_ = value;
    margin_right_ = value;
    margin_top_ = value;
    margin_bottom_ = value;
    return *this;
  }

  Format &margin_left(size_t value) {
    margin_left_ = value;
    return *this;
  }

  Format &margin_right(size_t value) {
    margin_right_ = value;
    return *this;
  }

  Format &margin_top(size_t value) {
    margin_top_ = value;
    return *this;
  }

  Format &margin_bottom(size_t value) {
    margin_bottom_ = value;
    return *this;
  }

  Format &padding(size_t value) {
    padding_left_ = value;
    padding_right_ = value;
    padding_top_ = value;
    padding_bottom_ = value;
    return *this;
  }

  Format &padding_left(size_t value) {
    padding_left_ = value;
    return *this;
  }

  Format &padding_right(size_t value) {
    padding_right_ = value;
    return *this;
  }

  Format &padding_top(size_t value) {
    padding_top_ = value;
    return *this;
  }

  Format &padding_bottom(size_t value) {
    padding_bottom_ = value;
    return *this;
  }

  Format &border(const std::string &value) {
    border_left_ = value;
    border_right_ = value;
    border_top_ = value;
    border_bottom_ = value;
    return *this;
  }

  Format &border_left(const std::string &value) {
    border_left_ = value;
    return *this;
  }

  Format &border_right(const std::string &value) {
    border_right_ = value;
    return *this;
  }

  Format &border_top(const std::string &value) {
    border_top_ = value;
    return *this;
  }

  Format &border_bottom(const std::string &value) {
    border_bottom_ = value;
    return *this;
  }

  Format &corner(const std::string &value) {
    corner_ = value;
    return *this;
  }

  Format &column_separator(const std::string &value) {
    column_separator_ = value;
    return *this;
  }

  Format &font_align(FontAlign value) {
    font_align_ = value;
    return *this;
  }

  Format &font_style(const std::vector<FontStyle> &style) {
    for (auto &s : style)
      font_style_.push_back(s);
    return *this;
  }

  Format &color(Color value) {
    color_ = value;
    return *this;
  }

  Format &background_color(Color value) {
    background_color_ = value;
    return *this;
  }

  Format &word_wrap(bool value) {
    word_wrap_ = value;
    return *this;
  }

private:
  friend class Cell;
  friend class Row;
  friend class Table;
  std::optional<size_t> width_{};
  std::optional<size_t> height_{};

  FontAlign font_align_{FontAlign::left};
  std::vector<FontStyle> font_style_{};

  std::optional<Color> color_;
  std::optional<Color> background_color_;

  size_t margin_left_{1};
  size_t margin_top_{1};
  size_t margin_right_{1};
  size_t margin_bottom_{1};

  size_t padding_left_{1};
  size_t padding_top_{1};
  size_t padding_right_{1};
  size_t padding_bottom_{1};

  std::string border_top_{"-"};
  std::string border_bottom_{"-"};
  std::string border_left_{"|"};
  std::string border_right_{"|"};

  std::string corner_{"+"};
  std::string column_separator_{"|"};

  bool word_wrap_{false};
};

}; // namespace tabulate
<commit_msg>Minor update<commit_after>#include <cstddef>
#include <optional>
#include <string>
#include <tabulate/color.hpp>
#include <tabulate/font_align.hpp>
#include <tabulate/font_style.hpp>
#include <vector>

namespace tabulate {

class Format {
public:
  Format &width(size_t value) {
    width_ = value;
    return *this;
  }

  Format &height(size_t value) {
    height_ = value;
    return *this;
  }

  Format &margin(size_t value) {
    margin_left_ = value;
    margin_right_ = value;
    margin_top_ = value;
    margin_bottom_ = value;
    return *this;
  }

  Format &margin_left(size_t value) {
    margin_left_ = value;
    return *this;
  }

  Format &margin_right(size_t value) {
    margin_right_ = value;
    return *this;
  }

  Format &margin_top(size_t value) {
    margin_top_ = value;
    return *this;
  }

  Format &margin_bottom(size_t value) {
    margin_bottom_ = value;
    return *this;
  }

  Format &padding(size_t value) {
    padding_left_ = value;
    padding_right_ = value;
    padding_top_ = value;
    padding_bottom_ = value;
    return *this;
  }

  Format &padding_left(size_t value) {
    padding_left_ = value;
    return *this;
  }

  Format &padding_right(size_t value) {
    padding_right_ = value;
    return *this;
  }

  Format &padding_top(size_t value) {
    padding_top_ = value;
    return *this;
  }

  Format &padding_bottom(size_t value) {
    padding_bottom_ = value;
    return *this;
  }

  Format &border(const std::string &value) {
    border_left_ = value;
    border_right_ = value;
    border_top_ = value;
    border_bottom_ = value;
    return *this;
  }

  Format &border_left(const std::string &value) {
    border_left_ = value;
    return *this;
  }

  Format &border_right(const std::string &value) {
    border_right_ = value;
    return *this;
  }

  Format &border_top(const std::string &value) {
    border_top_ = value;
    return *this;
  }

  Format &border_bottom(const std::string &value) {
    border_bottom_ = value;
    return *this;
  }

  Format &corner(const std::string &value) {
    corner_ = value;
    return *this;
  }

  Format &column_separator(const std::string &value) {
    column_separator_ = value;
    return *this;
  }

  Format &font_align(FontAlign value) {
    font_align_ = value;
    return *this;
  }

  Format &font_style(const std::vector<FontStyle> &style) {
    for (auto &s : style)
      font_style_.push_back(s);
    return *this;
  }

  Format &color(Color value) {
    color_ = value;
    return *this;
  }

  Format &background_color(Color value) {
    background_color_ = value;
    return *this;
  }

  Format &word_wrap(bool value) {
    word_wrap_ = value;
    return *this;
  }

private:
  friend class Cell;
  friend class Row;
  friend class Table;
  std::optional<size_t> width_{};
  std::optional<size_t> height_{};

  FontAlign font_align_{FontAlign::left};
  std::vector<FontStyle> font_style_{};

  std::optional<Color> color_;
  std::optional<Color> background_color_;

  size_t margin_left_{1};
  size_t margin_top_{1};
  size_t margin_right_{1};
  size_t margin_bottom_{1};

  size_t padding_left_{1};
  size_t padding_top_{1};
  size_t padding_right_{1};
  size_t padding_bottom_{1};

  std::string border_top_{"-"};
  std::string border_bottom_{"-"};
  std::string border_left_{"|"};
  std::string border_right_{"|"};

  std::string corner_{"+"};
  std::string column_separator_{"|"};

  bool word_wrap_{false};
};

}; // namespace tabulate
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: vclxaccessiblecomponent.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: pb $ $Date: 2002-03-22 08:24:32 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#define _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_

#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <drafts/com/sun/star/accessibility/XAccessible.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleContext.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleExtendedComponent.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif

#ifndef _CPPUHELPER_COMPBASE4_HXX_
#include <cppuhelper/compbase4.hxx>
#endif

#include <tools/gen.hxx>    // Size
#include <tools/link.hxx>   // Size

class Window;
class VCLXWindow;
class VclSimpleEvent;
class VclWindowEvent;

namespace utl {
class AccessibleStateSetHelper;
}

class MutexHelper_Impl
{
protected:
    ::osl::Mutex    maMutex;
};

typedef cppu::WeakComponentImplHelper4<
    ::drafts::com::sun::star::accessibility::XAccessible,
    ::drafts::com::sun::star::accessibility::XAccessibleContext,
    ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent,
    ::drafts::com::sun::star::accessibility::XAccessibleEventBroadcaster
    > VCLXAccessibleComponentBase;

//  ----------------------------------------------------
//  class VCLXAccessibleComponent
//  ----------------------------------------------------

class VCLXAccessibleComponent : public MutexHelper_Impl, public VCLXAccessibleComponentBase
{
private:
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> mxWindow;
    VCLXWindow*                         mpVCLXindow;

    ::cppu::OInterfaceContainerHelper   maEventListeners;

    ULONG                           nDummy1;
    ULONG                           nDummy2;
    void*                           pDummy1;
    void*                           pDummy2;

protected:
    ::osl::Mutex&   GetMutex() { return maMutex; }
     DECL_LINK( WindowEventListener, VclSimpleEvent* );

    virtual void    ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent );
    virtual void    FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet );

    void            NotifyAccessibleEvent( sal_Int16 nEventId, const ::com::sun::star::uno::Any& rOldValue, const ::com::sun::star::uno::Any& rNewValue );

public:
    VCLXAccessibleComponent( VCLXWindow* pVCLXindow );
    ~VCLXAccessibleComponent();

    VCLXWindow*    GetVCLXWindow() const { return mpVCLXindow; }
    Window*        GetWindow() const;

    virtual void SAL_CALL disposing();

    // ::drafts::com::sun::star::accessibility::XAccessible
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext(  ) throw (::com::sun::star::uno::RuntimeException);

    // ::drafts::com::sun::star::accessibility::XAccessibleEventBroadcaster
    void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);

    // ::drafts::com::sun::star::accessibility::XAccessibleContext
    sal_Int32 SAL_CALL getAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleParent(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Int32 SAL_CALL getAccessibleIndexInParent(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Int16 SAL_CALL getAccessibleRole(  ) throw (::com::sun::star::uno::RuntimeException);
    ::rtl::OUString SAL_CALL getAccessibleDescription(  ) throw (::com::sun::star::uno::RuntimeException);
    ::rtl::OUString SAL_CALL getAccessibleName(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::lang::Locale SAL_CALL getLocale(  ) throw (::drafts::com::sun::star::accessibility::IllegalAccessibleComponentStateException, ::com::sun::star::uno::RuntimeException);

    // ::drafts::com::sun::star::accessibility::XAccessibleComponent
    sal_Bool SAL_CALL contains( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAt( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::awt::Rectangle SAL_CALL getBounds(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::awt::Size SAL_CALL getSize(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::awt::Point SAL_CALL getLocation(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Bool SAL_CALL isShowing(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Bool SAL_CALL isVisible(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Bool SAL_CALL isFocusTraversable(  ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL addFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL removeFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL grabFocus(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Any SAL_CALL getAccessibleKeyBinding(  ) throw (::com::sun::star::uno::RuntimeException);

    // ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent
    virtual sal_Int32 SAL_CALL getForeground(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL getBackground(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL getFont(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::awt::FontDescriptor SAL_CALL getFontMetrics( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont >& xFont ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL isEnabled(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getTitledBorderText(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getToolTipText(  ) throw (::com::sun::star::uno::RuntimeException);
};

/* ----------------------------------------------------------
  Accessibility only for the Window hierarchy!
  Maybe derived classes must overwrite these Accessibility interfaces:

    // XAccessibleContext:
    sal_Int16 getAccessibleRole() => VCL Window::GetAccessibleRole()
    OUString getAccessibleDescription() => VCL Window::GetAccessibleDescription
    OUString getAccessibleName() => VCL Window::GetAccessibleText() => Most windows return Window::GetText()
    Reference< XAccessibleRelationSet > getAccessibleRelationSet()
    Reference< XAccessibleStateSet > getAccessibleStateSet() => overload FillAccessibleStateSet( ... )

// ::drafts::com::sun::star::accessibility::XAccessibleComponent
    sal_Bool isFocusTraversable()
    Any getAccessibleKeyBinding()

---------------------------------------------------------- */

#endif // _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_

<commit_msg>#98750# - derive from OAccessibleImplementationAccess - derive from OAccessibleExtendedComponentHelper for not duplicating code<commit_after>/*************************************************************************
 *
 *  $RCSfile: vclxaccessiblecomponent.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: fs $ $Date: 2002-04-25 11:21:20 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#define _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_

#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <drafts/com/sun/star/accessibility/XAccessible.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleContext.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleExtendedComponent.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif

#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef COMPHELPER_ACCIMPLACCESS_HXX
#include <comphelper/accimplaccess.hxx>
#endif
#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX
#include <comphelper/accessiblecomponenthelper.hxx>
#endif

#include <tools/gen.hxx>    // Size
#include <tools/link.hxx>   // Size

class Window;
class VCLXWindow;
class VclSimpleEvent;
class VclWindowEvent;

namespace utl {
class AccessibleStateSetHelper;
}

//class MutexHelper_Impl
//{
//protected:
//  ::osl::Mutex    maMutex;
//};

//typedef cppu::WeakComponentImplHelper3<
//    ::drafts::com::sun::star::accessibility::XAccessibleContext,
//  ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent,
//    ::drafts::com::sun::star::accessibility::XAccessibleEventBroadcaster
//    > VCLXAccessibleComponentBase;

typedef ::comphelper::OAccessibleExtendedComponentHelper    VCLXAccessibleComponentBase;

//  ----------------------------------------------------
//  class VCLXAccessibleComponent
//  ----------------------------------------------------

class VCLXAccessibleComponent
        :public VCLXAccessibleComponentBase
        ,public ::comphelper::OAccessibleImplementationAccess
{
private:
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> mxWindow;
    VCLXWindow*                         mpVCLXindow;

    ULONG                           nDummy1;
    ULONG                           nDummy2;
    void*                           pDummy1;
    void*                           pDummy2;

protected:
//  ::osl::Mutex&   GetMutex() { return maMutex; }
     DECL_LINK( WindowEventListener, VclSimpleEvent* );

    virtual void    ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent );
    virtual void    FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet );

public:
    VCLXAccessibleComponent( VCLXWindow* pVCLXindow );
    ~VCLXAccessibleComponent();

    VCLXWindow*    GetVCLXWindow() const { return mpVCLXindow; }
    Window*        GetWindow() const;

    virtual void SAL_CALL disposing();

    // ::com::sun::star::uno::XInterface
    DECLARE_XINTERFACE()
    // ::com::sun::star::lang::XTypeProvider
    DECLARE_XTYPEPROVIDER()

    // ::drafts::com::sun::star::accessibility::XAccessibleContext
    sal_Int32 SAL_CALL getAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleParent(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Int32 SAL_CALL getAccessibleIndexInParent(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Int16 SAL_CALL getAccessibleRole(  ) throw (::com::sun::star::uno::RuntimeException);
    ::rtl::OUString SAL_CALL getAccessibleDescription(  ) throw (::com::sun::star::uno::RuntimeException);
    ::rtl::OUString SAL_CALL getAccessibleName(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::lang::Locale SAL_CALL getLocale(  ) throw (::drafts::com::sun::star::accessibility::IllegalAccessibleComponentStateException, ::com::sun::star::uno::RuntimeException);

    // ::drafts::com::sun::star::accessibility::XAccessibleComponent
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAt( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Bool SAL_CALL isShowing(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Bool SAL_CALL isVisible(  ) throw (::com::sun::star::uno::RuntimeException);
    sal_Bool SAL_CALL isFocusTraversable(  ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL addFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL removeFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    void SAL_CALL grabFocus(  ) throw (::com::sun::star::uno::RuntimeException);
    ::com::sun::star::uno::Any SAL_CALL getAccessibleKeyBinding(  ) throw (::com::sun::star::uno::RuntimeException);

    // ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent
    virtual sal_Int32 SAL_CALL getForeground(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL getBackground(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL getFont(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::awt::FontDescriptor SAL_CALL getFontMetrics( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont >& xFont ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL isEnabled(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getTitledBorderText(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getToolTipText(  ) throw (::com::sun::star::uno::RuntimeException);

protected:
    // base class overridables
    ::com::sun::star::awt::Rectangle SAL_CALL implGetBounds(  ) throw (::com::sun::star::uno::RuntimeException);

private:
    /** we may be reparented (if external components use OAccessibleImplementationAccess base class),
        so this method here returns the parent in the VCL world, in opposite to the parent
        an external component gave us
    @precond
        the caller must ensure thread safety, i.e. our mutex must be locked
    */
    ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible >
            getVclParent() const;
};

/* ----------------------------------------------------------
  Accessibility only for the Window hierarchy!
  Maybe derived classes must overwrite these Accessibility interfaces:

    // XAccessibleContext:
    sal_Int16 getAccessibleRole() => VCL Window::GetAccessibleRole()
    OUString getAccessibleDescription() => VCL Window::GetAccessibleDescription
    OUString getAccessibleName() => VCL Window::GetAccessibleText() => Most windows return Window::GetText()
    Reference< XAccessibleRelationSet > getAccessibleRelationSet()
    Reference< XAccessibleStateSet > getAccessibleStateSet() => overload FillAccessibleStateSet( ... )

// ::drafts::com::sun::star::accessibility::XAccessibleComponent
    sal_Bool isFocusTraversable()
    Any getAccessibleKeyBinding()

---------------------------------------------------------- */

#endif // _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_

<|endoftext|>


<commit_before>#include "SliceRenderer.hpp"
#include "Exception.hpp"
#include "DeviceManager.hpp"
#include "HelperFunctions.hpp"
#include "Image.hpp"
#include "DynamicImage.hpp"
#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl_gl.h>
#include <OpenGL/OpenGL.h>
#else
#if _WIN32
#include <GL/gl.h>
#include <CL/cl_gl.h>
#else
#include <GL/glx.h>
#include <CL/cl_gl.h>
#endif
#endif

#ifndef GL_RGBA32F
#define GL_RGBA32F 34838
#endif

using namespace fast;

#if defined(__APPLE__) || defined(__MACOSX)
#else
#if _WIN32
#else
static Display * mXDisplay;
#endif
#endif

void SliceRenderer::execute() {
    if(!mInput.isValid())
        throw Exception("No input was given to SliceRenderer");

    Image::pointer input;
    if(mInput->isDynamicData()) {
        input = DynamicImage::pointer(mInput)->getNextFrame();
    } else {
        input = mInput;
    }

    // Determine level and window
    float window = mWindow;
    float level = mLevel;
    // If mWindow/mLevel is equal to -1 use default level/window values
    if(window == -1) {
        window = getDefaultIntensityWindow(input->getDataType());
    }
    if(level == -1) {
        level = getDefaultIntensityLevel(input->getDataType());
    }

#if defined(__APPLE__) || defined(__MACOSX)
    // Returns 0 on success
    bool success = CGLSetCurrentContext((CGLContextObj)mDevice->getGLContext()) == 0;
#else
#if _WIN32
    bool success = wglMakeCurrent(wglGetCurrentDC(), (HGLRC)mDevice->getGLContext());
#else
    bool success = glXMakeCurrent(mXDisplay,glXGetCurrentDrawable(),(GLXContext)mDevice->getGLContext());
#endif
#endif
    if(!success)
        throw Exception("failed to switch to window");

    OpenCLImageAccess3D access = input->getOpenCLImageAccess3D(ACCESS_READ, mDevice);
    cl::Image3D* clImage = access.get();

    glEnable(GL_TEXTURE_2D);
    if(mTextureIsCreated) {
        // Delete old texture
        glDeleteTextures(1, &mTexture);
    }

    // Create OpenGL texture
    glGenTextures(1, &mTexture);
    glBindTexture(GL_TEXTURE_2D, mTexture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, clImage->getImageInfo<CL_IMAGE_WIDTH>(), clImage->getImageInfo<CL_IMAGE_HEIGHT>(), 0, GL_RGBA, GL_FLOAT, 0);
    glBindTexture(GL_TEXTURE_2D, 0);
    glFinish();

    // Create CL-GL image
#if defined(CL_VERSION_1_2)
    mImageGL = cl::ImageGL(
            mDevice->getContext(),
            CL_MEM_READ_WRITE,
            GL_TEXTURE_2D,
            0,
            mTexture
    );
#else
    mImageGL = cl::Image2DGL(
            mDevice->getContext(),
            CL_MEM_READ_WRITE,
            GL_TEXTURE_2D,
            0,
            mTexture
    );
#endif

    // Run kernel to fill the texture
    cl::CommandQueue queue = mDevice->getCommandQueue();
    std::vector<cl::Memory> v;
    v.push_back(mImageGL);
    queue.enqueueAcquireGLObjects(&v);

    cl::Kernel kernel(mProgram, "renderToTexture");
    kernel.setArg(0, *clImage);
    kernel.setArg(1, mImageGL);
    kernel.setArg(2, (int)(clImage->getImageInfo<CL_IMAGE_DEPTH>()/2));
    kernel.setArg(3, level);
    kernel.setArg(4, window);
    queue.enqueueNDRangeKernel(
            kernel,
            cl::NullRange,
            cl::NDRange(clImage->getImageInfo<CL_IMAGE_WIDTH>(), clImage->getImageInfo<CL_IMAGE_HEIGHT>()),
            cl::NullRange
    );

    queue.enqueueReleaseGLObjects(&v);
    queue.finish();

    mTextureIsCreated = true;
}

void SliceRenderer::setInput(ImageData::pointer image) {
    mInput = image;
    addParent(mInput);
    mIsModified = true;
    /*
    if(image->getNrOfDimensions() != 3)
        throw Exception("The SliceRenderer only supports 3D images");
        */
}

SliceRenderer::SliceRenderer() {
    mDevice = boost::static_pointer_cast<OpenCLDevice>(DeviceManager::getInstance().getDefaultVisualizationDevice());
    int i = mDevice->createProgramFromSource(std::string(FAST_ROOT_DIR) + "/Visualization/SliceRenderer.cl");
    mProgram = mDevice->getProgram(i);
    mTextureIsCreated = false;
    mIsModified = true;
#if defined(__APPLE__) || defined(__MACOSX)
#else
#if _WIN32
#else
    // Open the display here to avoid getting maximum number of clients error
    mXDisplay = XOpenDisplay(NULL);
#endif
#endif
}

void SliceRenderer::draw() {
    std::cout << "calling draw()" << std::endl;

    if(!mTextureIsCreated)
        return;

#if defined(__APPLE__) || defined(__MACOSX)
    // Returns 0 on success
    bool success = CGLSetCurrentContext((CGLContextObj)mDevice->getGLContext()) == 0;
#else
#if _WIN32
    bool success = wglMakeCurrent(wglGetCurrentDC(), (HGLRC)mDevice->getGLContext());
#else
    bool success = glXMakeCurrent(mXDisplay,glXGetCurrentDrawable(),(GLXContext)mDevice->getGLContext());
#endif
#endif
    if(!success)
        throw Exception("failed to switch to window");

    glBindTexture(GL_TEXTURE_2D, mTexture);

    glBegin(GL_QUADS);
        glTexCoord2i(0, 1);
        glVertex3f(-1.0f, 1.0f, 0.0f);
        glTexCoord2i(1, 1);
        glVertex3f( 1.0f, 1.0f, 0.0f);
        glTexCoord2i(1, 0);
        glVertex3f( 1.0f,-1.0f, 0.0f);
        glTexCoord2i(0, 0);
        glVertex3f(-1.0f,-1.0f, 0.0f);
    glEnd();

    glBindTexture(GL_TEXTURE_2D, 0);
}
<commit_msg>added a check that the input image is 3D in the SliceRenderer<commit_after>#include "SliceRenderer.hpp"
#include "Exception.hpp"
#include "DeviceManager.hpp"
#include "HelperFunctions.hpp"
#include "Image.hpp"
#include "DynamicImage.hpp"
#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl_gl.h>
#include <OpenGL/OpenGL.h>
#else
#if _WIN32
#include <GL/gl.h>
#include <CL/cl_gl.h>
#else
#include <GL/glx.h>
#include <CL/cl_gl.h>
#endif
#endif

#ifndef GL_RGBA32F
#define GL_RGBA32F 34838
#endif

using namespace fast;

#if defined(__APPLE__) || defined(__MACOSX)
#else
#if _WIN32
#else
static Display * mXDisplay;
#endif
#endif

void SliceRenderer::execute() {
    if(!mInput.isValid())
        throw Exception("No input was given to SliceRenderer");

    Image::pointer input;
    if(mInput->isDynamicData()) {
        input = DynamicImage::pointer(mInput)->getNextFrame();
    } else {
        input = mInput;
    }

    if(input->getDimensions() != 3)
        throw Exception("The SliceRenderer only supports 3D images");

    // Determine level and window
    float window = mWindow;
    float level = mLevel;
    // If mWindow/mLevel is equal to -1 use default level/window values
    if(window == -1) {
        window = getDefaultIntensityWindow(input->getDataType());
    }
    if(level == -1) {
        level = getDefaultIntensityLevel(input->getDataType());
    }

#if defined(__APPLE__) || defined(__MACOSX)
    // Returns 0 on success
    bool success = CGLSetCurrentContext((CGLContextObj)mDevice->getGLContext()) == 0;
#else
#if _WIN32
    bool success = wglMakeCurrent(wglGetCurrentDC(), (HGLRC)mDevice->getGLContext());
#else
    bool success = glXMakeCurrent(mXDisplay,glXGetCurrentDrawable(),(GLXContext)mDevice->getGLContext());
#endif
#endif
    if(!success)
        throw Exception("failed to switch to window");

    OpenCLImageAccess3D access = input->getOpenCLImageAccess3D(ACCESS_READ, mDevice);
    cl::Image3D* clImage = access.get();

    glEnable(GL_TEXTURE_2D);
    if(mTextureIsCreated) {
        // Delete old texture
        glDeleteTextures(1, &mTexture);
    }

    // Create OpenGL texture
    glGenTextures(1, &mTexture);
    glBindTexture(GL_TEXTURE_2D, mTexture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, clImage->getImageInfo<CL_IMAGE_WIDTH>(), clImage->getImageInfo<CL_IMAGE_HEIGHT>(), 0, GL_RGBA, GL_FLOAT, 0);
    glBindTexture(GL_TEXTURE_2D, 0);
    glFinish();

    // Create CL-GL image
#if defined(CL_VERSION_1_2)
    mImageGL = cl::ImageGL(
            mDevice->getContext(),
            CL_MEM_READ_WRITE,
            GL_TEXTURE_2D,
            0,
            mTexture
    );
#else
    mImageGL = cl::Image2DGL(
            mDevice->getContext(),
            CL_MEM_READ_WRITE,
            GL_TEXTURE_2D,
            0,
            mTexture
    );
#endif

    // Run kernel to fill the texture
    cl::CommandQueue queue = mDevice->getCommandQueue();
    std::vector<cl::Memory> v;
    v.push_back(mImageGL);
    queue.enqueueAcquireGLObjects(&v);

    cl::Kernel kernel(mProgram, "renderToTexture");
    kernel.setArg(0, *clImage);
    kernel.setArg(1, mImageGL);
    kernel.setArg(2, (int)(clImage->getImageInfo<CL_IMAGE_DEPTH>()/2));
    kernel.setArg(3, level);
    kernel.setArg(4, window);
    queue.enqueueNDRangeKernel(
            kernel,
            cl::NullRange,
            cl::NDRange(clImage->getImageInfo<CL_IMAGE_WIDTH>(), clImage->getImageInfo<CL_IMAGE_HEIGHT>()),
            cl::NullRange
    );

    queue.enqueueReleaseGLObjects(&v);
    queue.finish();

    mTextureIsCreated = true;
}

void SliceRenderer::setInput(ImageData::pointer image) {
    mInput = image;
    addParent(mInput);
    mIsModified = true;
    /*
    if(image->getNrOfDimensions() != 3)
        throw Exception("The SliceRenderer only supports 3D images");
        */
}

SliceRenderer::SliceRenderer() {
    mDevice = boost::static_pointer_cast<OpenCLDevice>(DeviceManager::getInstance().getDefaultVisualizationDevice());
    int i = mDevice->createProgramFromSource(std::string(FAST_ROOT_DIR) + "/Visualization/SliceRenderer.cl");
    mProgram = mDevice->getProgram(i);
    mTextureIsCreated = false;
    mIsModified = true;
#if defined(__APPLE__) || defined(__MACOSX)
#else
#if _WIN32
#else
    // Open the display here to avoid getting maximum number of clients error
    mXDisplay = XOpenDisplay(NULL);
#endif
#endif
}

void SliceRenderer::draw() {
    std::cout << "calling draw()" << std::endl;

    if(!mTextureIsCreated)
        return;

#if defined(__APPLE__) || defined(__MACOSX)
    // Returns 0 on success
    bool success = CGLSetCurrentContext((CGLContextObj)mDevice->getGLContext()) == 0;
#else
#if _WIN32
    bool success = wglMakeCurrent(wglGetCurrentDC(), (HGLRC)mDevice->getGLContext());
#else
    bool success = glXMakeCurrent(mXDisplay,glXGetCurrentDrawable(),(GLXContext)mDevice->getGLContext());
#endif
#endif
    if(!success)
        throw Exception("failed to switch to window");

    glBindTexture(GL_TEXTURE_2D, mTexture);

    glBegin(GL_QUADS);
        glTexCoord2i(0, 1);
        glVertex3f(-1.0f, 1.0f, 0.0f);
        glTexCoord2i(1, 1);
        glVertex3f( 1.0f, 1.0f, 0.0f);
        glTexCoord2i(1, 0);
        glVertex3f( 1.0f,-1.0f, 0.0f);
        glTexCoord2i(0, 0);
        glVertex3f(-1.0f,-1.0f, 0.0f);
    glEnd();

    glBindTexture(GL_TEXTURE_2D, 0);
}
<|endoftext|>