<commit_before>#include <algorithm>
#include <map>
#include <iostream>

#include "google/protobuf/descriptor.h"

#include "vtrc-rpc-lowlevel.pb.h"
#include "vtrc-rpc-options.pb.h"

#include "vtrc-rpc-channel.h"
#include "vtrc-protocol-layer.h"
#include "vtrc-exception.h"

#include "vtrc-bind.h"

namespace vtrc { namespace common  {

    namespace gpb = google::protobuf;

    namespace {

        void default_error_cb( const rpc_channel::lowlevel_unit_type &llu )
        {
            throw vtrc::common::exception( llu.error( ).code( ),
                                           llu.error( ).category( ),
                                           llu.error( ).additional( ) );
        }

        void default_chan_error_cb( const char *message )
        {
            throw vtrc::common::exception( rpc::errors::ERR_CHANNEL,
                                           message );
        }

        rpc_channel::proto_error_cb_type get_default_error_cb( )
        {
            return vtrc::bind( default_error_cb, vtrc::placeholders::_1 );
        }

        rpc_channel::channel_error_cb_type get_default_chan_error_cb( )
        {
            return vtrc::bind( default_chan_error_cb, vtrc::placeholders::_1 );
        }
    }

    struct rpc_channel::impl {

        unsigned direct_type_;
        unsigned callback_type_;
        std::string data_;

        rpc_channel::proto_error_cb_type    error_cb_;
        rpc_channel::channel_error_cb_type  chan_error_cb_;

        impl( unsigned direct_call_type, unsigned callback_type )
            :direct_type_(direct_call_type)
            ,callback_type_(callback_type)
            ,error_cb_(get_default_error_cb( ))
            ,chan_error_cb_(get_default_chan_error_cb( ))
        { }
    };

    rpc_channel::rpc_channel(unsigned direct_call_type, unsigned callback_type)
        :impl_(new impl(direct_call_type, callback_type))
    { }

    rpc_channel::~rpc_channel( )
    {
        delete impl_;
    }

    rpc_channel::lowlevel_unit_sptr rpc_channel::create_lowlevel(
                                        const gpb::MethodDescriptor *method,
                                        const gpb::Message *request,
                                              gpb::Message *response)
    {
        lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>( ));

        const std::string &serv_name(method->service( )->full_name( ));
        const std::string &meth_name(method->name( ));

        llu->mutable_call( )->set_service_id( serv_name );
        llu->mutable_call( )->set_method_id( meth_name );

        if( request ) {
            llu->set_request( request->SerializeAsString( ) );
        }

        if( !response ) {
            llu->mutable_opt( )->set_accept_response( false );
        }

        return llu;
    }

    rpc_channel::lowlevel_unit_sptr rpc_channel::make_lowlevel(
                        const google::protobuf::MethodDescriptor* method,
                        const google::protobuf::Message* request,
                              google::protobuf::Message* response )
    {
        rpc_channel::lowlevel_unit_sptr res =
                create_lowlevel( method, request, response );
        return res;
    }

    rpc_channel::lowlevel_unit_sptr rpc_channel::raw_call(
                                rpc_channel::lowlevel_unit_sptr /*llu*/,
                                lowlevel_closure_type /*callbacks*/ )
    {
        ;;; /// nothing to do here
        return rpc_channel::lowlevel_unit_sptr( );
    }

    void rpc_channel::set_channel_data( const std::string &data )
    {
        impl_->data_ = data;
    }

    const std::string &rpc_channel::channel_data( )
    {
        return impl_->data_;
    }

    bool can_accept_callbacks( const common::call_context *cc )
    {
#if 1   /// yeap. we always set it up
        rpc::lowlevel_unit const *llu  = cc->get_lowlevel_message( );
        return llu->opt( ).wait( ) && llu->opt( ).accept_callbacks( );
#else
        rpc::options       const *opts = cc->get_call_options( );
        rpc::lowlevel_unit const *llu  = cc->get_lowlevel_message( );

        bool accept_callbacks = llu->opt( ).has_accept_callbacks( )
                                ? llu->opt( ).accept_callbacks( )
                                : opts->accept_callbacks( );

        bool wait = llu->opt( ).has_wait( )
                    ? llu->opt( ).wait( )
                    : opts->wait( );

        return  wait && accept_callbacks;
#endif
    }

    void rpc_channel::configure_message( common::connection_iface_sptr c,
                                         unsigned mess_type,
                                         lowlevel_unit_type &llu ) const
    {
        const common::call_context *cc(common::call_context::get(c));

        llu.set_id(c->get_protocol( ).next_index( ));

        if( mess_type == impl_->callback_type_ ) {

            if( cc && can_accept_callbacks( cc ) ) {

                llu.mutable_info( )->set_message_type( mess_type );
                llu.set_target_id( cc->get_lowlevel_message( )->id( ) );

            } else {

                llu.mutable_info( )->set_message_type( impl_->direct_type_ );

            }
        } else {
            llu.mutable_info( )->set_message_type( mess_type );
        }
    }

    rpc_channel::lowlevel_unit_sptr rpc_channel::call_and_wait_raw (
                        google::protobuf::uint64 call_id,
                        lowlevel_unit_type &llu,
                        common::connection_iface_sptr &cl,
                        lowlevel_closure_type events,
                        const rpc::options *call_opt ) const
    {
        cl->get_protocol( ).call_rpc_method( call_id, llu );

        const unsigned mess_type( llu.info( ).message_type( ) );

        bool wait = true;

        lowlevel_unit_sptr top (vtrc::make_shared<lowlevel_unit_type>( ));

        if( !events ) {
            llu.mutable_opt( )->set_accept_callbacks( false );
        }

        while( wait ) {

            top->Clear( );

            cl->get_protocol( ).read_slot_for( call_id, top,
                                               call_opt->timeout( ) );

            if( top->error( ).code( ) != rpc::errors::ERR_NO_ERROR ) {
                wait = false;
            } else if( top->info( ).message_type( ) != mess_type ) {
                if( events ) {
                    events( *top );
                }
            } else {
                wait = false;
            }
        }
        cl->get_protocol( ).erase_slot( call_id );
        return top;
    }

    const rpc_channel::proto_error_cb_type &
          rpc_channel::get_proto_error_callback( ) const
    {
        return impl_->error_cb_;
    }

    void rpc_channel::set_proto_error_callback(
            const rpc_channel::proto_error_cb_type &value )
    {
        if( value ) {
            impl_->error_cb_ = value;
        } else {
            impl_->error_cb_ = get_default_error_cb( );
        }
    }

    const rpc_channel::channel_error_cb_type &
          rpc_channel::get_channel_error_callback( ) const
    {
        return impl_->chan_error_cb_;
    }

    void rpc_channel::set_channel_error_callback(
            const rpc_channel::channel_error_cb_type &value )
    {
        if( value ) {
            impl_->chan_error_cb_ = value;
        } else {
            impl_->chan_error_cb_ = get_default_chan_error_cb( );
        }
    }

    bool rpc_channel::call_and_wait(
                            google::protobuf::uint64 call_id,
                            const lowlevel_unit_type &llu,
                            google::protobuf::Message *response,
                            connection_iface_sptr &cl,
                            const rpc::options *call_opt ) const
    {
        cl->get_protocol( ).call_rpc_method( call_id, llu );

        const unsigned mess_type(llu.info( ).message_type( ));

        bool wait = true;

        lowlevel_unit_sptr top (vtrc::make_shared<lowlevel_unit_type>( ));

        while( wait ) {

            top->Clear( );

            cl->get_protocol( ).read_slot_for( call_id, top,
                                               call_opt->timeout( ) );

            if( top->error( ).code( ) != rpc::errors::ERR_NO_ERROR ) {
                cl->get_protocol( ).erase_slot( call_id );
                impl_->error_cb_( *top );
//                throw vtrc::common::exception( top->error( ).code( ),
//                                         top->error( ).category( ),
//                                         top->error( ).additional( ) );
                return false;
            }

            /// from client: call, insertion_call
            /// from server: event, callback
            if( top->info( ).message_type( ) != mess_type ) {
                cl->get_protocol( ).make_local_call( top );
            } else {
                if( response ) {
                    response->ParseFromString( top->response( ) );
                }
                wait = false;
            }
        }
        cl->get_protocol( ).erase_slot( call_id );
        return true;
    }

    protocol_layer &rpc_channel::get_protocol(connection_iface &cl)
    {
        return cl.get_protocol( );
    }

    void rpc_channel::CallMethod( const gpb::MethodDescriptor *method,
                                        gpb::RpcController *controller,
                                  const gpb::Message *request,
                                        gpb::Message *response,
                                        gpb::Closure *done)
    {
        lowlevel_unit_sptr llu( create_lowlevel( method, request, response ) );
        if( !impl_->data_.empty( ) ) {
            llu->set_channel_data( impl_->data_ );
        }
        send_message( *llu, method, controller, request, response, done );
    }

}}

<commit_msg>errors<commit_after>#include <algorithm>
#include <map>
#include <iostream>

#include "google/protobuf/descriptor.h"

#include "vtrc-rpc-lowlevel.pb.h"
#include "vtrc-rpc-options.pb.h"

#include "vtrc-rpc-channel.h"
#include "vtrc-protocol-layer.h"
#include "vtrc-exception.h"

#include "vtrc-bind.h"

namespace vtrc { namespace common  {

    namespace gpb = google::protobuf;
    namespace ph  = vtrc::placeholders;

    namespace {

        void default_error_cb( const rpc_channel::lowlevel_unit_type &llu )
        {
            throw vtrc::common::exception( llu.error( ).code( ),
                                           llu.error( ).category( ),
                                           llu.error( ).additional( ) );
        }

        void default_chan_error_cb( const char *message )
        {
            throw vtrc::common::exception( rpc::errors::ERR_CHANNEL,
                                           message );
        }

        rpc_channel::proto_error_cb_type get_default_error_cb( )
        {
            return vtrc::bind( default_error_cb, ph::_1 );
        }

        rpc_channel::channel_error_cb_type get_default_chan_error_cb( )
        {
            return vtrc::bind( default_chan_error_cb, ph::_1 );
        }
    }

    struct rpc_channel::impl {

        unsigned direct_type_;
        unsigned callback_type_;
        std::string data_;

        rpc_channel::proto_error_cb_type    error_cb_;
        rpc_channel::channel_error_cb_type  chan_error_cb_;

        impl( unsigned direct_call_type, unsigned callback_type )
            :direct_type_(direct_call_type)
            ,callback_type_(callback_type)
            ,error_cb_(get_default_error_cb( ))
            ,chan_error_cb_(get_default_chan_error_cb( ))
        { }
    };

    rpc_channel::rpc_channel(unsigned direct_call_type, unsigned callback_type)
        :impl_(new impl(direct_call_type, callback_type))
    { }

    rpc_channel::~rpc_channel( )
    {
        delete impl_;
    }

    rpc_channel::lowlevel_unit_sptr rpc_channel::create_lowlevel(
                                        const gpb::MethodDescriptor *method,
                                        const gpb::Message *request,
                                              gpb::Message *response)
    {
        lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>( ));

        const std::string &serv_name(method->service( )->full_name( ));
        const std::string &meth_name(method->name( ));

        llu->mutable_call( )->set_service_id( serv_name );
        llu->mutable_call( )->set_method_id( meth_name );

        if( request ) {
            llu->set_request( request->SerializeAsString( ) );
        }

        if( !response ) {
            llu->mutable_opt( )->set_accept_response( false );
        }

        return llu;
    }

    rpc_channel::lowlevel_unit_sptr rpc_channel::make_lowlevel(
                        const google::protobuf::MethodDescriptor* method,
                        const google::protobuf::Message* request,
                              google::protobuf::Message* response )
    {
        rpc_channel::lowlevel_unit_sptr res =
                create_lowlevel( method, request, response );
        return res;
    }

    rpc_channel::lowlevel_unit_sptr rpc_channel::raw_call(
                                rpc_channel::lowlevel_unit_sptr /*llu*/,
                                lowlevel_closure_type /*callbacks*/ )
    {
        ;;; /// nothing to do here
        return rpc_channel::lowlevel_unit_sptr( );
    }

    void rpc_channel::set_channel_data( const std::string &data )
    {
        impl_->data_ = data;
    }

    const std::string &rpc_channel::channel_data( )
    {
        return impl_->data_;
    }

    bool can_accept_callbacks( const common::call_context *cc )
    {
#if 1   /// yeap. we always set it up
        rpc::lowlevel_unit const *llu  = cc->get_lowlevel_message( );
        return llu->opt( ).wait( ) && llu->opt( ).accept_callbacks( );
#else
        rpc::options       const *opts = cc->get_call_options( );
        rpc::lowlevel_unit const *llu  = cc->get_lowlevel_message( );

        bool accept_callbacks = llu->opt( ).has_accept_callbacks( )
                                ? llu->opt( ).accept_callbacks( )
                                : opts->accept_callbacks( );

        bool wait = llu->opt( ).has_wait( )
                    ? llu->opt( ).wait( )
                    : opts->wait( );

        return  wait && accept_callbacks;
#endif
    }

    void rpc_channel::configure_message( common::connection_iface_sptr c,
                                         unsigned mess_type,
                                         lowlevel_unit_type &llu ) const
    {
        const common::call_context *cc(common::call_context::get(c));

        llu.set_id(c->get_protocol( ).next_index( ));

        if( mess_type == impl_->callback_type_ ) {

            if( cc && can_accept_callbacks( cc ) ) {

                llu.mutable_info( )->set_message_type( mess_type );
                llu.set_target_id( cc->get_lowlevel_message( )->id( ) );

            } else {

                llu.mutable_info( )->set_message_type( impl_->direct_type_ );

            }
        } else {
            llu.mutable_info( )->set_message_type( mess_type );
        }
    }

    rpc_channel::lowlevel_unit_sptr rpc_channel::call_and_wait_raw (
                        google::protobuf::uint64 call_id,
                        lowlevel_unit_type &llu,
                        common::connection_iface_sptr &cl,
                        lowlevel_closure_type events,
                        const rpc::options *call_opt ) const
    {
        cl->get_protocol( ).call_rpc_method( call_id, llu );

        const unsigned mess_type( llu.info( ).message_type( ) );

        bool wait = true;

        lowlevel_unit_sptr top (vtrc::make_shared<lowlevel_unit_type>( ));

        if( !events ) {
            llu.mutable_opt( )->set_accept_callbacks( false );
        }

        while( wait ) {

            top->Clear( );

            cl->get_protocol( ).read_slot_for( call_id, top,
                                               call_opt->timeout( ) );

            if( top->error( ).code( ) != rpc::errors::ERR_NO_ERROR ) {
                wait = false;
            } else if( top->info( ).message_type( ) != mess_type ) {
                if( events ) {
                    events( *top );
                }
            } else {
                wait = false;
            }
        }
        cl->get_protocol( ).erase_slot( call_id );
        return top;
    }

    const rpc_channel::proto_error_cb_type &
          rpc_channel::get_proto_error_callback( ) const
    {
        return impl_->error_cb_;
    }

    void rpc_channel::set_proto_error_callback(
            const rpc_channel::proto_error_cb_type &value )
    {
        if( value ) {
            impl_->error_cb_ = value;
        } else {
            impl_->error_cb_ = get_default_error_cb( );
        }
    }

    const rpc_channel::channel_error_cb_type &
          rpc_channel::get_channel_error_callback( ) const
    {
        return impl_->chan_error_cb_;
    }

    void rpc_channel::set_channel_error_callback(
            const rpc_channel::channel_error_cb_type &value )
    {
        if( value ) {
            impl_->chan_error_cb_ = value;
        } else {
            impl_->chan_error_cb_ = get_default_chan_error_cb( );
        }
    }

    bool rpc_channel::call_and_wait(
                            google::protobuf::uint64 call_id,
                            const lowlevel_unit_type &llu,
                            google::protobuf::Message *response,
                            connection_iface_sptr &cl,
                            const rpc::options *call_opt ) const
    {
        cl->get_protocol( ).call_rpc_method( call_id, llu );

        const unsigned mess_type(llu.info( ).message_type( ));

        bool wait = true;

        lowlevel_unit_sptr top (vtrc::make_shared<lowlevel_unit_type>( ));

        while( wait ) {

            top->Clear( );

            cl->get_protocol( ).read_slot_for( call_id, top,
                                               call_opt->timeout( ) );

            if( top->error( ).code( ) != rpc::errors::ERR_NO_ERROR ) {
                cl->get_protocol( ).erase_slot( call_id );
                impl_->error_cb_( *top );
//                throw vtrc::common::exception( top->error( ).code( ),
//                                         top->error( ).category( ),
//                                         top->error( ).additional( ) );
                return false;
            }

            /// from client: call, insertion_call
            /// from server: event, callback
            if( top->info( ).message_type( ) != mess_type ) {
                cl->get_protocol( ).make_local_call( top );
            } else {
                if( response ) {
                    response->ParseFromString( top->response( ) );
                }
                wait = false;
            }
        }
        cl->get_protocol( ).erase_slot( call_id );
        return true;
    }

    protocol_layer &rpc_channel::get_protocol(connection_iface &cl)
    {
        return cl.get_protocol( );
    }

    void rpc_channel::CallMethod( const gpb::MethodDescriptor *method,
                                        gpb::RpcController *controller,
                                  const gpb::Message *request,
                                        gpb::Message *response,
                                        gpb::Closure *done)
    {
        lowlevel_unit_sptr llu( create_lowlevel( method, request, response ) );
        if( !impl_->data_.empty( ) ) {
            llu->set_channel_data( impl_->data_ );
        }
        send_message( *llu, method, controller, request, response, done );
    }

}}

<|endoftext|>


<commit_before>#include "Globals.h"
#include "App.h"
#include "ModuleInput.h"
#include "ModuleCamera3D.h"
#include "EditorUI.h"
#include "Game.h"
#include "ModuleWindow.h"
#include "Cursor.h"
#include "imgui.h"

ModuleCamera3D::ModuleCamera3D(bool start_enabled) : Module(start_enabled)
{
	SetName("Camera3D");

	CalculateViewMatrix();

	// Normalized vectors that define the direction of X, Y and Z
	X = vec3(1.0f, 0.0f, 0.0f);
	Y = vec3(0.0f, 1.0f, 0.0f);
	Z = vec3(0.0f, 0.0f, 1.0f);

	// Position of the camera X, Y and Z
	Position = vec3(0.0f, 0.0f, 0.0f);

	// Reference point in which is rotating from
	Reference = vec3(0.0f, 0.0f, 0.0f);
}

ModuleCamera3D::~ModuleCamera3D()
{}

bool ModuleCamera3D::Awake()
{
	bool ret = true;

	LOG_OUTPUT("Loading Camera3D");

	return ret;
}

// -----------------------------------------------------------------
bool ModuleCamera3D::Start()
{
	bool ret = true;

	LOG_OUTPUT("Setting up the camera");

	camera_speed = 20.0f;
	wheel_speed = 5.0f;
	mouse_sensitivity = 0.25f;

	return ret;
}

// -----------------------------------------------------------------
bool ModuleCamera3D::CleanUp()
{
	LOG_OUTPUT("Cleaning camera");

	return true;
}

// -----------------------------------------------------------------
bool ModuleCamera3D::Update()
{
	bool ret = true;

	float speed = camera_speed * App->GetDT();

	if (App->input->GetKeyRepeat(SDL_SCANCODE_LSHIFT))
		speed = camera_speed/2 * App->GetDT();

	if (App->input->GetKeyRepeat(SDL_SCANCODE_R))
		MoveUp(speed);

	if (App->input->GetKeyRepeat(SDL_SCANCODE_F))
		MoveDown(speed);

	if (IsMouseInsideWindow())
	{
		mouse_movement = true;
	}

	// Mouse motion ----------------
	if (mouse_movement)
	{
		if (App->input->GetMouseWheel() == 1)
		{
			MoveFront(wheel_speed);
		}
		else if (App->input->GetMouseWheel() == -1)
		{
			MoveBack(wheel_speed);
		}
		else if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT)
		{
			App->window->GetCursor()->Hand();

			if (App->input->GetKeyRepeat(SDL_SCANCODE_W))
				MoveFront(speed);

			if (App->input->GetKeyRepeat(SDL_SCANCODE_S))
				MoveBack(speed);

			if (App->input->GetKeyRepeat(SDL_SCANCODE_A))
				MoveLeft(speed);

			if (App->input->GetKeyRepeat(SDL_SCANCODE_D))
				MoveRight(speed);

			if (App->input->GetKeyRepeat(SDL_SCANCODE_LALT) || App->input->GetKeyRepeat(SDL_SCANCODE_RALT))
			{
				Orbit(vec3(0, 0, 0), App->input->GetMouseXMotion(), App->input->GetMouseYMotion());

				App->window->GetCursor()->SizeAll();
			}
			else
			{
				Rotate(App->input->GetMouseXMotion(), App->input->GetMouseYMotion());
			}
		}
		else
		{
			mouse_movement = false;
		}
	}

	// Recalculate matrix -------------
	//LOG_OUTPUT("X:%f, %f, %f  Y:%f, %f, %f   Z:%f, %f, %f ", X.x, X.y, X.z, Y.x, Y.y, Y.z, Z.x, Z.y, Z.z);

	LOG_OUTPUT("5. %f %f %f", X.x, X.y, X.z);
	CalculateViewMatrix();
	LOG_OUTPUT("6. %f %f %f", X.x, X.y, X.z);

	return ret;
}

// -----------------------------------------------------------------
void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference)
{
	this->Position = Position;
	this->Reference = Reference;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	if (!RotateAroundReference)
	{
		this->Reference = this->Position;
		this->Position += Z * 0.05f;
	}

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::LookAt(const vec3 &Spot)
{
	Reference = Spot;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::Move(const vec3 &Movement)
{
	Position += Movement;
	Reference += Movement;

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
float* ModuleCamera3D::GetViewMatrix()
{
	return &ViewMatrix;
}

// -----------------------------------------------------------------
void ModuleCamera3D::CalculateViewMatrix()
{
	ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
	ViewMatrixInverse = inverse(ViewMatrix);
}

void ModuleCamera3D::MoveFront(float speed)
{
	vec3 newPos(0, 0, 0);
	newPos -= Z * speed;
	Position += newPos;
	Reference += newPos;
}

void ModuleCamera3D::MoveBack(float speed)
{
	vec3 newPos(0, 0, 0);
	newPos += Z * speed;
	Position += newPos;
	Reference += newPos;
}

void ModuleCamera3D::MoveLeft(float speed)
{
	vec3 newPos(0, 0, 0);
	newPos -= X * speed;
	Position += newPos;
	Reference += newPos;
}

void ModuleCamera3D::MoveRight(float speed)
{
	vec3 newPos(0, 0, 0);
	newPos += X * speed;
	Position += newPos;
	Reference += newPos;
}

void ModuleCamera3D::MoveUp(float speed)
{
	vec3 newPos(0, 0, 0);
	newPos.y += speed;
	Position += newPos;
	Reference += newPos;
}

void ModuleCamera3D::MoveDown(float speed)
{
	vec3 newPos(0, 0, 0);
	newPos.y -= speed;
	Position += newPos;
	Reference += newPos;
}

void ModuleCamera3D::Orbit(vec3 orbit_center, float motion_x, float motion_y)
{
	Reference = orbit_center;

	int dx = -motion_x;
	int dy = -motion_y;

	Position -= Reference;

	if (dx != 0)
	{
		float DeltaX = (float)dx * mouse_sensitivity;

		// Rotate arround the y axis
		X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
		Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
		Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
	}

	if (dy != 0)
	{
		float DeltaY = (float)dy * mouse_sensitivity;

		// Rotate arround the X direction
		Y = rotate(Y, DeltaY, X);
		Z = rotate(Z, DeltaY, X);
	}

	Position = Reference + Z * length(Position);
}

void ModuleCamera3D::Rotate(float motion_x, float motion_y)
{
	Reference = Position;

	int dx = -motion_x;
	int dy = -motion_y;

	Position -= Reference;

	if (dx != 0)
	{
		float DeltaX = (float)dx * mouse_sensitivity;

		X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
		Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
		Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
	}

	if (dy != 0)
	{
		float DeltaY = (float)dy * mouse_sensitivity;

		Y = rotate(Y, DeltaY, X);
		Z = rotate(Z, DeltaY, X);
	}

	Position = Reference + Z * length(Position);
}

bool ModuleCamera3D::IsMouseInsideWindow() const
{
	return PointInRect(float2(App->input->GetMouseX(), App->input->GetMouseY()), App->editorUI->GameRect());
}
<commit_msg>Cleaned log<commit_after>#include "Globals.h"
#include "App.h"
#include "ModuleInput.h"
#include "ModuleCamera3D.h"
#include "EditorUI.h"
#include "Game.h"
#include "ModuleWindow.h"
#include "Cursor.h"
#include "imgui.h"

ModuleCamera3D::ModuleCamera3D(bool start_enabled) : Module(start_enabled)
{
	SetName("Camera3D");

	CalculateViewMatrix();

	// Normalized vectors that define the direction of X, Y and Z
	X = vec3(1.0f, 0.0f, 0.0f);
	Y = vec3(0.0f, 1.0f, 0.0f);
	Z = vec3(0.0f, 0.0f, 1.0f);

	// Position of the camera X, Y and Z
	Position = vec3(0.0f, 0.0f, 0.0f);

	// Reference point in which is rotating from
	Reference = vec3(0.0f, 0.0f, 0.0f);
}

ModuleCamera3D::~ModuleCamera3D()
{}

bool ModuleCamera3D::Awake()
{
	bool ret = true;

	LOG_OUTPUT("Loading Camera3D");

	return ret;
}

// -----------------------------------------------------------------
bool ModuleCamera3D::Start()
{
	bool ret = true;

	LOG_OUTPUT("Setting up the camera");

	camera_speed = 20.0f;
	wheel_speed = 5.0f;
	mouse_sensitivity = 0.25f;

	return ret;
}

// -----------------------------------------------------------------
bool ModuleCamera3D::CleanUp()
{
	LOG_OUTPUT("Cleaning camera");

	return true;
}

// -----------------------------------------------------------------
bool ModuleCamera3D::Update()
{
	bool ret = true;

	float speed = camera_speed * App->GetDT();

	if (App->input->GetKeyRepeat(SDL_SCANCODE_LSHIFT))
		speed = camera_speed/2 * App->GetDT();

	if (App->input->GetKeyRepeat(SDL_SCANCODE_R))
		MoveUp(speed);

	if (App->input->GetKeyRepeat(SDL_SCANCODE_F))
		MoveDown(speed);

	if (IsMouseInsideWindow())
	{
		mouse_movement = true;
	}

	// Mouse motion ----------------
	if (mouse_movement)
	{
		if (App->input->GetMouseWheel() == 1)
		{
			MoveFront(wheel_speed);
		}
		else if (App->input->GetMouseWheel() == -1)
		{
			MoveBack(wheel_speed);
		}
		else if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT)
		{
			App->window->GetCursor()->Hand();

			if (App->input->GetKeyRepeat(SDL_SCANCODE_W))
				MoveFront(speed);

			if (App->input->GetKeyRepeat(SDL_SCANCODE_S))
				MoveBack(speed);

			if (App->input->GetKeyRepeat(SDL_SCANCODE_A))
				MoveLeft(speed);

			if (App->input->GetKeyRepeat(SDL_SCANCODE_D))
				MoveRight(speed);

			if (App->input->GetKeyRepeat(SDL_SCANCODE_LALT) || App->input->GetKeyRepeat(SDL_SCANCODE_RALT))
			{
				Orbit(vec3(0, 0, 0), App->input->GetMouseXMotion(), App->input->GetMouseYMotion());

				App->window->GetCursor()->SizeAll();
			}
			else
			{
				Rotate(App->input->GetMouseXMotion(), App->input->GetMouseYMotion());
			}
		}
		else
		{
			mouse_movement = false;
		}
	}

	// Recalculate matrix -------------
	CalculateViewMatrix();

	return ret;
}

// -----------------------------------------------------------------
void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference)
{
	this->Position = Position;
	this->Reference = Reference;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	if (!RotateAroundReference)
	{
		this->Reference = this->Position;
		this->Position += Z * 0.05f;
	}

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::LookAt(const vec3 &Spot)
{
	Reference = Spot;

	Z = normalize(Position - Reference);
	X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z));
	Y = cross(Z, X);

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
void ModuleCamera3D::Move(const vec3 &Movement)
{
	Position += Movement;
	Reference += Movement;

	CalculateViewMatrix();
}

// -----------------------------------------------------------------
float* ModuleCamera3D::GetViewMatrix()
{
	return &ViewMatrix;
}

// -----------------------------------------------------------------
void ModuleCamera3D::CalculateViewMatrix()
{
	ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
	ViewMatrixInverse = inverse(ViewMatrix);
}

void ModuleCamera3D::MoveFront(float speed)
{
	vec3 newPos(0, 0, 0);
	newPos -= Z * speed;
	Position += newPos;
	Reference += newPos;
}

void ModuleCamera3D::MoveBack(float speed)
{
	vec3 newPos(0, 0, 0);
	newPos += Z * speed;
	Position += newPos;
	Reference += newPos;
}

void ModuleCamera3D::MoveLeft(float speed)
{
	vec3 newPos(0, 0, 0);
	newPos -= X * speed;
	Position += newPos;
	Reference += newPos;
}

void ModuleCamera3D::MoveRight(float speed)
{
	vec3 newPos(0, 0, 0);
	newPos += X * speed;
	Position += newPos;
	Reference += newPos;
}

void ModuleCamera3D::MoveUp(float speed)
{
	vec3 newPos(0, 0, 0);
	newPos.y += speed;
	Position += newPos;
	Reference += newPos;
}

void ModuleCamera3D::MoveDown(float speed)
{
	vec3 newPos(0, 0, 0);
	newPos.y -= speed;
	Position += newPos;
	Reference += newPos;
}

void ModuleCamera3D::Orbit(vec3 orbit_center, float motion_x, float motion_y)
{
	Reference = orbit_center;

	int dx = -motion_x;
	int dy = -motion_y;

	Position -= Reference;

	if (dx != 0)
	{
		float DeltaX = (float)dx * mouse_sensitivity;

		// Rotate arround the y axis
		X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
		Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
		Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
	}

	if (dy != 0)
	{
		float DeltaY = (float)dy * mouse_sensitivity;

		// Rotate arround the X direction
		Y = rotate(Y, DeltaY, X);
		Z = rotate(Z, DeltaY, X);
	}

	Position = Reference + Z * length(Position);
}

void ModuleCamera3D::Rotate(float motion_x, float motion_y)
{
	Reference = Position;

	int dx = -motion_x;
	int dy = -motion_y;

	Position -= Reference;

	if (dx != 0)
	{
		float DeltaX = (float)dx * mouse_sensitivity;

		X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f));
		Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f));
		Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f));
	}

	if (dy != 0)
	{
		float DeltaY = (float)dy * mouse_sensitivity;

		Y = rotate(Y, DeltaY, X);
		Z = rotate(Z, DeltaY, X);
	}

	Position = Reference + Z * length(Position);
}

bool ModuleCamera3D::IsMouseInsideWindow() const
{
	return PointInRect(float2(App->input->GetMouseX(), App->input->GetMouseY()), App->editorUI->GameRect());
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include <cassert>
#include <fstream>
#include <iostream>
#include <strstream>

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

//These came from the debug test.
#include <cstdio>
#include <ctime>
#include <string>
#include <string.h>
#include <vector>

#include <util/PlatformUtils.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanFileOutputStream.hpp>
#include <PlatformSupport/XalanOutputStreamPrintWriter.hpp>
#include <XercesParserLiaison/XercesDOMSupport.hpp>

#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathSupportDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>

#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/StylesheetRoot.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInit.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>

#include <XercesParserLiaison/XercesParserLiaison.hpp>

#include <XMLFileReporter.hpp>

//This is here for the threads.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winbase.h>
#define THREADFUNCTIONRETURN DWORD WINAPI

#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::cout;
	using std::cin;
	using std::endl;
	using std::ifstream;
	using std::ios_base;
	using std::ostrstream;
	using std::string;
#endif

// This is here for memory leak testing.
#if defined(_DEBUG)
#include <crtdbg.h>
#endif

const char* 	xslStylesheets[] =
{
	"v:\\xsl-test\\perf\\basic\\basic-all_well",
	"v:\\xsl-test\\perf\\basic\\basic-datetranscode",
	"v:\\xsl-test\\perf\\basic\\basic-dict2",
	"v:\\xsl-test\\perf\\basic\\basic-Fischer-Euwe",
	//"v:\\xsl-test\\perf\\basic\\basic-queens",
	"v:\\xsl-test\\perf\\large\\large-all_well",
	//"v:\\xsl-test\\perf\\large\\large-evans_large",
	"v:\\xsl-test\\perf\\nodes\\nodes-fancy_xml_tree_viewer_34",
	"v:\\xsl-test\\perf\\nodes\\nodes-showtree-19991008",
	"v:\\xsl-test\\perf\\sort\\sort-big",
	"v:\\xsl-test\\perf\\xpath\\xpath-evans_small",
	"v:\\xsl-test\\perf\\xpath\\xpath-evans_tiny",
	0
};
const char* 	outputDir = "d:\\xslt-results\\perf\\test\\";

// Used to hold compiled stylesheet, and source document.
XalanNode*		glbSourceXML[sizeof(xslStylesheets) / sizeof(const char*)];
StylesheetRoot*	glbStylesheetRoot[sizeof(xslStylesheets) / sizeof(const char*)];

void outputMessage(int iter)
{
	cout << "\n" << "Starting Iteration: " << iter << '\0';
}

int main( int argc,	const char* argv [])
{
	XMLFileReporter theXMLFileReporter;

	theXMLFileReporter.setFileName("testfile.txt");
	theXMLFileReporter.initialize();
	theXMLFileReporter.logTestFileInit("CConformanceTest - Iterates over all conf test dirs and validates outputs USING Xalan-C");
	theXMLFileReporter.logTestFileClose("xxx", "pass");
	theXMLFileReporter.close();

	assert(sizeof(glbStylesheetRoot) == sizeof(glbSourceXML));

#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

	if (argc > 2)
	{
		cerr << "Usage: perf" << endl  << endl;
	}
	else
	{
		int	iterCount = 1;
		if (argc == 2)
		{
			iterCount = atoi(argv[1]);
		}

		try
		{
			// Call the static initializers...
			XMLPlatformUtils::Initialize();

			{
				XSLTInit	theInit;

				const XalanDOMString  XSLSuffix(".xsl");
				const XalanDOMString  XMLSuffix(".xml");
				const XalanDOMString  outputSuffix(".out");

				// Create the necessary support objects to instantiate a processor.
				XercesDOMSupport			    csDOMSupport;
				XercesParserLiaison				csParserLiaison(csDOMSupport);
				XPathSupportDefault				csXPathSupport(csDOMSupport);
				XSLTProcessorEnvSupportDefault	csXSLTProcessorEnvSupport;
				XObjectFactoryDefault			csXObjectFactory;
				XPathFactoryDefault				csXPathFactory;

				// Create a processor for stylesheet compilation and connect to
				// ProcessorEnvSupport object
				XSLTEngineImpl	csProcessor(
						csParserLiaison,
						csXPathSupport,
						csXSLTProcessorEnvSupport,
						csDOMSupport,
						csXObjectFactory,
						csXPathFactory);
				csXSLTProcessorEnvSupport.setProcessor(&csProcessor);

				// Create separate factory support object, so the stylesheet's
				// factory-created XPath instance are independent from processor's.
				XPathFactoryDefault			ssXPathFactory;

				// Create a stylesheet construction context, using the
				// stylesheet's factory support objects.
				StylesheetConstructionContextDefault	csConstructionContext(
														csProcessor,
														csXSLTProcessorEnvSupport,
														ssXPathFactory);

				for(int i = 0; xslStylesheets[i] != 0; i++)
				{
					const XalanDOMString  theXSLfile(XalanDOMString(xslStylesheets[i]) + XSLSuffix);
					const XalanDOMString  theXMLfile(XalanDOMString(xslStylesheets[i]) + XMLSuffix);

					cout << "Now compiling Stylesheet: " << xslStylesheets[i] << endl;

					//Generate the XML and XSL input objects.
					XSLTInputSource		csStylesheetSourceXSL(c_wstr(theXSLfile));
					XSLTInputSource		csSourceXML(c_wstr(theXMLfile));

					// Ask the processor to create a compiled stylesheet (StylesheetRoot) for the
					// specified input XSL. We don't have to delete it, since it is owned by the
					// StylesheetConstructionContext instance.

					{const double startTime = clock();
					//cout << "Clock before Compliation: " << startTime << endl;

					glbStylesheetRoot[i] = csProcessor.processStylesheet(csStylesheetSourceXSL,
														   csConstructionContext);
					const double endTime = clock();
					//cout << "Clock after Compliation: " << endTime << endl;
					cout << "Compliation took: " << endTime - startTime << endl;
					}

					assert(glbStylesheetRoot[i] != 0);

					// Have the processor create a compiled SourceDocument for the specified
					// input XML.
					glbSourceXML[i] = csProcessor.getSourceTreeFromInput(csSourceXML);
					assert(glbSourceXML[i] != 0);
				}

				for(int ii = 0; xslStylesheets[ii] != 0; ii++)
				{
					cout << endl << "Testing: " << xslStylesheets[ii] << endl;

					// The execution context uses the same factory support objects as
					// the processor, since those objects have the same lifetime as
					// other objects created as a result of the execution.
					StylesheetExecutionContextDefault	psExecutionContext(
							csProcessor,
							csXSLTProcessorEnvSupport,
							csXPathSupport,
							csXObjectFactory);

					const XalanDOMString  outputfile(//XalanDOMString(outputDir) +
						                             XalanDOMString(xslStylesheets[ii]) +
													                outputSuffix);

					//Generate the XML input and output objects.
					XSLTInputSource		csSourceXML(glbSourceXML[ii]);
					XSLTResultTarget	theResultTarget(outputfile);

					// Set the stylesheet to be the compiled stylesheet. Then do the transform.
					const double singleStart = clock();
					//cout << "Clock before single transform: " << singleStart << endl;
						csProcessor.setStylesheetRoot(glbStylesheetRoot[ii]);
						csProcessor.process(csSourceXML, theResultTarget,psExecutionContext);
						psExecutionContext.reset();
					const double singleEnd = clock();
					//cout << "Clock after single transform: " << singleEnd << endl;
					cout << "Single Transform time: " << singleEnd - singleStart << endl;

					const double startTime = clock();
					//cout << endl << "Clock before transforms: " << startTime << endl;
					for(int j = 0; j < iterCount; ++j)
					{
						csProcessor.setStylesheetRoot(glbStylesheetRoot[ii]);
						csProcessor.process(csSourceXML, theResultTarget,psExecutionContext);
						psExecutionContext.reset();
					}
					const double endTime = clock();
					//cout << "Clock after transforms: " << endTime << endl;
					//cout << "Total clock ticks: " << endTime - startTime << endl;
					const double	millis = ((endTime - startTime) / CLOCKS_PER_SEC) * 1000.0;
					//cout << "Milliseconds: " << millis << endl;
					cout << "Averaged: " << millis / iterCount << " for " << iterCount << " iterations" << endl;
				}

			}

			XMLPlatformUtils::Terminate();
		}
		catch(...)
		{
			cerr << "Exception caught!!!"
				 << endl
				 << endl;
		}
	}

	return 0;
}
<commit_msg>Major overhaul.  Don't compile all the stylesheets beforehand. Now just do one at a time.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include <cassert>
#include <fstream>
#include <iostream>
#include <strstream>

#if !defined(NDEBUG) && defined(_MSC_VER)
#include <crtdbg.h>
#endif

//These came from the debug test.
#include <cstdio>
#include <ctime>
#include <string>
#include <string.h>
#include <vector>

#include <util/PlatformUtils.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/XalanFileOutputStream.hpp>
#include <PlatformSupport/XalanOutputStreamPrintWriter.hpp>

#include <XercesParserLiaison/XercesDOMSupport.hpp>
#include <XercesParserLiaison/XercesParserLiaison.hpp>

#include <XPath/XObjectFactoryDefault.hpp>
#include <XPath/XPathSupportDefault.hpp>
#include <XPath/XPathFactoryDefault.hpp>

#include <XSLT/StylesheetConstructionContextDefault.hpp>
#include <XSLT/StylesheetExecutionContextDefault.hpp>
#include <XSLT/StylesheetRoot.hpp>
#include <XSLT/XSLTEngineImpl.hpp>
#include <XSLT/XSLTInit.hpp>
#include <XSLT/XSLTInputSource.hpp>
#include <XSLT/XSLTProcessorEnvSupportDefault.hpp>
#include <XSLT/XSLTResultTarget.hpp>

#include <XMLFileReporter.hpp>

//This is here for the threads.
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winbase.h>
#define THREADFUNCTIONRETURN DWORD WINAPI

#if !defined(XALAN_NO_NAMESPACES)
	using std::cerr;
	using std::cout;
	using std::cin;
	using std::endl;
	using std::ifstream;
	using std::ios_base;
	using std::ostrstream;
	using std::string;
#endif

// This is here for memory leak testing.
#if defined(_DEBUG)
#include <crtdbg.h>
#endif

const char* 	xslStylesheets[] =
{
	"v:\\xsl-test\\perf\\basic\\basic-all_well",
	//"v:\\xsl-test\\perf\\basic\\basic-datetranscode",
	//"v:\\xsl-test\\perf\\basic\\basic-dict2",
	//"v:\\xsl-test\\perf\\basic\\basic-Fischer-Euwe",
	//"v:\\xsl-test\\perf\\basic\\basic-queens",
	"v:\\xsl-test\\perf\\large\\large-all_well",
	//"v:\\xsl-test\\perf\\large\\large-evans_large",
	//"v:\\xsl-test\\perf\\nodes\\nodes-fancy_xml_tree_viewer_34",
	//"v:\\xsl-test\\perf\\nodes\\nodes-showtree-19991008",
	//"v:\\xsl-test\\perf\\sort\\sort-big",
	//"v:\\xsl-test\\perf\\xpath\\xpath-evans_small",
	//"v:\\xsl-test\\perf\\xpath\\xpath-evans_tiny",
	0
};
const char* 	outputDir = "d:\\xslt-results\\perf\\test\\";

// Used to hold compiled stylesheet, and source document.
XalanNode*		glbSourceXML;
StylesheetRoot*	glbStylesheetRoot;

void outputMessage(int iter)
{
	cout << "\n" << "Starting Iteration: " << iter << '\0';
}

int main( int argc,	const char* argv [])
{
	XMLFileReporter theXMLFileReporter;

	theXMLFileReporter.setFileName("testfile.txt");
	theXMLFileReporter.initialize();
	theXMLFileReporter.logTestFileInit("CConformanceTest - Iterates over all conf test dirs and validates outputs USING Xalan-C");
	theXMLFileReporter.logTestFileClose("xxx", "pass");
	theXMLFileReporter.close();

#if !defined(NDEBUG) && defined(_MSC_VER)
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);

	_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
	_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
#endif

	if (argc > 2)
	{
		cerr << "Usage: perf" << endl  << endl;
	}
	else
	{
		int	iterCount = 1;
		if (argc == 2)
		{
			iterCount = atoi(argv[1]);
		}

		try
		{
			// Call the static initializers... and define file suffixes
			XMLPlatformUtils::Initialize();
			const XalanDOMString  XSLSuffix(".xsl");
			const XalanDOMString  XMLSuffix(".xml");
			const XalanDOMString  outputSuffix(".out");

			{
			  XSLTInit	theInit;

			  for(int i = 0; xslStylesheets[i] != 0; i++)
			  {
				// Create the necessary support objects to instantiate a processor.
				XercesDOMSupport			    csDOMSupport;
				XercesParserLiaison				csParserLiaison(csDOMSupport);
				XPathSupportDefault				csXPathSupport(csDOMSupport);
				XSLTProcessorEnvSupportDefault	csXSLTProcessorEnvSupport;
				XObjectFactoryDefault			csXObjectFactory;
				XPathFactoryDefault				csXPathFactory;

				// Create a processor for stylesheet compilation and connect to
				// ProcessorEnvSupport object
				XSLTEngineImpl	csProcessor(
						csParserLiaison,
						csXPathSupport,
						csXSLTProcessorEnvSupport,
						csDOMSupport,
						csXObjectFactory,
						csXPathFactory);
				csXSLTProcessorEnvSupport.setProcessor(&csProcessor);

				// Create separate factory support object, so the stylesheet's
				// factory-created XPath instance are independent from processor's.
				XPathFactoryDefault			ssXPathFactory;

				// Create a stylesheet construction context, using the
				// stylesheet's factory support objects.
				StylesheetConstructionContextDefault	csConstructionContext(
														csProcessor,
														csXSLTProcessorEnvSupport,
														ssXPathFactory);

				const XalanDOMString  theXSLfile(XalanDOMString(xslStylesheets[i]) + XSLSuffix);
				const XalanDOMString  theXMLfile(XalanDOMString(xslStylesheets[i]) + XMLSuffix);

				cout << endl << "Compiling: " << xslStylesheets[i] << endl;

				//Generate the XML and XSL input objects.
				XSLTInputSource		csStylesheetSourceXSL(c_wstr(theXSLfile));
				XSLTInputSource		csSourceXML(c_wstr(theXMLfile));

				// Ask the processor to create a compiled stylesheet (StylesheetRoot) for the
				// specified input XSL. We don't have to delete it, since it is owned by the
				// StylesheetConstructionContext instance.

				const double startTime = clock();
					glbStylesheetRoot= csProcessor.processStylesheet(csStylesheetSourceXSL,
												   csConstructionContext);
				const double endTime = clock();
				cout << "Compliation took: " << endTime - startTime << endl;

				assert(glbStylesheetRoot != 0);

				// Have the processor create a compiled SourceDocument for the specified
				// input XML.
				glbSourceXML = csProcessor.getSourceTreeFromInput(csSourceXML);
				assert(glbSourceXML != 0);

				//cout << endl << "Testing: " << xslStylesheets[i] << endl;

				// The execution context uses the same factory support objects as
				// the processor, since those objects have the same lifetime as
				// other objects created as a result of the execution.
				StylesheetExecutionContextDefault	psExecutionContext(
							csProcessor,
							csXSLTProcessorEnvSupport,
							csXPathSupport,
							csXObjectFactory);

				const XalanDOMString  outputfile(//XalanDOMString(outputDir) +
						                             XalanDOMString(xslStylesheets[i]) +
													                outputSuffix);

				//Generate the XML input and output objects.
				//XSLTInputSource		csSourceXML(glbSourceXML);
				XSLTResultTarget	theResultTarget(outputfile);

				// Set the stylesheet to be the compiled stylesheet. Then do the transform.
				csProcessor.setStylesheetRoot(glbStylesheetRoot);

				const double singleStart = clock();
					csProcessor.process(csSourceXML, theResultTarget,psExecutionContext);
				const double singleEnd = clock();

				psExecutionContext.reset();
				cout << "Single Transform time: " << singleEnd - singleStart << endl;

/*
				const double startTime = clock();
				//cout << endl << "Clock before transforms: " << startTime << endl;
				for(int j = 0; j < iterCount; ++j)
				{
					csProcessor.setStylesheetRoot(glbStylesheetRoot);
					csProcessor.process(csSourceXML, theResultTarget,psExecutionContext);
					psExecutionContext.reset();
				}
				const double endTime = clock();
				//cout << "Clock after transforms: " << endTime << endl;
				//cout << "Total clock ticks: " << endTime - startTime << endl;
				const double	millis = ((endTime - startTime) / CLOCKS_PER_SEC) * 1000.0;
				//cout << "Milliseconds: " << millis << endl;
				cout << "Averaged: " << millis / iterCount << " for " << iterCount << " iterations" << endl;
*/
  }

		}

			XMLPlatformUtils::Terminate();
		}
		catch(...)
		{
			cerr << "Exception caught!!!"
				 << endl
				 << endl;
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * c7a/api/size.hpp
 *
 * Part of Project c7a.
 *
 * Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef C7A_API_SIZE_HEADER
#define C7A_API_SIZE_HEADER

#include <c7a/api/action_node.hpp>
#include <c7a/core/stage_builder.hpp>
#include <c7a/net/collective_communication.hpp>
#include <c7a/net/flow_control_channel.hpp>
#include <c7a/net/flow_control_manager.hpp>
#include <c7a/net/group.hpp>

#include <string>

namespace c7a {
namespace api {

//! \addtogroup api Interface
//! \{

template <typename ValueType, typename ParentStack>
class SizeNode : public ActionNode
{
    static const bool debug = false;

    using Super = ActionNode;
    using Super::context_;
    using Super::parents;
    using Super::result_file_;

    using ParentInput = typename ParentStack::Input;

public:
    SizeNode(Context& ctx,
             const std::shared_ptr<DIANode<ParentInput> >& parent,
             const ParentStack& parent_stack)
        : ActionNode(ctx, { parent }, "Size"),
          parent_(parent)
    {
        // Hook PreOp(s)
        auto pre_op_fn = [=](const ValueType&) { ++local_size_; };

        lop_chain_ = parent_stack.push(pre_op_fn).emit();
        parent_->RegisterChild(lop_chain_);
    }

    virtual ~SizeNode() {
        parent_->UnregisterChild(lop_chain_);
    }

    //! Executes the size operation.
    void Execute() override {
        this->StartExecutionTimer();
        MainOp();
        this->StopExecutionTimer();
    }

    /*!
     * Returns result of global size.
     * \return result
     */
    auto result() {
        return global_size_;
    }

    /*!
     * Returns "[SizeNode]" as a string.
     * \return "[SizeNode]"
     */
    std::string ToString() override {
        return "[SizeNode] Id:" + result_file_.ToString();
    }

private:
    // Local size to be used.
    size_t local_size_ = 0;
    // Global size resulting from all reduce.
    size_t global_size_ = 0;

    std::shared_ptr<DIANode<ParentInput> > parent_;
    common::delegate<void(ParentInput)> lop_chain_;

    void PreOp() { }

    void MainOp() {
        // get the number of elements that are stored on this worker
        LOG1 << "MainOp processing, sum: " << local_size_;
        net::FlowControlChannel& channel = context_.flow_control_channel();

        // process the reduce, default argument is SumOp.
        global_size_ = channel.AllReduce(local_size_);
    }

    void PostOp() { }
};

template <typename ValueType, typename Stack>
size_t DIARef<ValueType, Stack>::Size() const {

    using SizeResultNode = SizeNode<ValueType, Stack>;

    auto shared_node
        = std::make_shared<SizeResultNode>(node_->context(), node_, stack_);

    core::StageBuilder().RunScope(shared_node.get());
    return shared_node.get()->result();
}

//! \}

} // namespace api
} // namespace c7a

#endif // !C7A_API_SIZE_HEADER

/******************************************************************************/
<commit_msg>remove LOG1 in size.hpp .. please do not commit LOG1 :c<commit_after>/*******************************************************************************
 * c7a/api/size.hpp
 *
 * Part of Project c7a.
 *
 * Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef C7A_API_SIZE_HEADER
#define C7A_API_SIZE_HEADER

#include <c7a/api/action_node.hpp>
#include <c7a/core/stage_builder.hpp>
#include <c7a/net/collective_communication.hpp>
#include <c7a/net/flow_control_channel.hpp>
#include <c7a/net/flow_control_manager.hpp>
#include <c7a/net/group.hpp>

#include <string>

namespace c7a {
namespace api {

//! \addtogroup api Interface
//! \{

template <typename ValueType, typename ParentStack>
class SizeNode : public ActionNode
{
    static const bool debug = false;

    using Super = ActionNode;
    using Super::context_;
    using Super::parents;
    using Super::result_file_;

    using ParentInput = typename ParentStack::Input;

public:
    SizeNode(Context& ctx,
             const std::shared_ptr<DIANode<ParentInput> >& parent,
             const ParentStack& parent_stack)
        : ActionNode(ctx, { parent }, "Size"),
          parent_(parent)
    {
        // Hook PreOp(s)
        auto pre_op_fn = [=](const ValueType&) { ++local_size_; };

        lop_chain_ = parent_stack.push(pre_op_fn).emit();
        parent_->RegisterChild(lop_chain_);
    }

    virtual ~SizeNode() {
        parent_->UnregisterChild(lop_chain_);
    }

    //! Executes the size operation.
    void Execute() override {
        this->StartExecutionTimer();
        MainOp();
        this->StopExecutionTimer();
    }

    /*!
     * Returns result of global size.
     * \return result
     */
    auto result() {
        return global_size_;
    }

    /*!
     * Returns "[SizeNode]" as a string.
     * \return "[SizeNode]"
     */
    std::string ToString() override {
        return "[SizeNode] Id:" + result_file_.ToString();
    }

private:
    // Local size to be used.
    size_t local_size_ = 0;
    // Global size resulting from all reduce.
    size_t global_size_ = 0;

    std::shared_ptr<DIANode<ParentInput> > parent_;
    common::delegate<void(ParentInput)> lop_chain_;

    void PreOp() { }

    void MainOp() {
        // get the number of elements that are stored on this worker
        LOG << "MainOp processing, sum: " << local_size_;
        net::FlowControlChannel& channel = context_.flow_control_channel();

        // process the reduce, default argument is SumOp.
        global_size_ = channel.AllReduce(local_size_);
    }

    void PostOp() { }
};

template <typename ValueType, typename Stack>
size_t DIARef<ValueType, Stack>::Size() const {

    using SizeResultNode = SizeNode<ValueType, Stack>;

    auto shared_node
        = std::make_shared<SizeResultNode>(node_->context(), node_, stack_);

    core::StageBuilder().RunScope(shared_node.get());
    return shared_node.get()->result();
}

//! \}

} // namespace api
} // namespace c7a

#endif // !C7A_API_SIZE_HEADER

/******************************************************************************/
<|endoftext|>


<commit_before>#include "timeentryeditorwidget.h"
#include "ui_timeentryeditorwidget.h"

#include <QMessageBox>

#include "toggl_api.h"

TimeEntryEditorWidget::TimeEntryEditorWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TimeEntryEditorWidget),
    guid(""),
    timeEntryAutocompleteNeedsUpdate(false),
    projectAutocompleteNeedsUpdate(false),
    workspaceSelectNeedsUpdate(false),
    clientSelectNeedsUpdate(false)
{
    ui->setupUi(this);

    setVisible(false);

    ui->addNewProject->setText("Add new project");

    connect(TogglApi::instance, SIGNAL(displayLogin(bool,uint64_t)),
            this, SLOT(displayLogin(bool,uint64_t)));

    connect(TogglApi::instance, SIGNAL(displayTimeEntryList(bool,QVector<TimeEntryView*>)),
            this, SLOT(displayTimeEntryList(bool,QVector<TimeEntryView*>)));

    connect(TogglApi::instance, SIGNAL(displayTimeEntryEditor(bool,TimeEntryView*,QString)),
            this, SLOT(displayTimeEntryEditor(bool,TimeEntryView*,QString)));

    connect(TogglApi::instance, SIGNAL(displayTags(QVector<GenericView*>)),
            this, SLOT(displayTags(QVector<GenericView*>)));

    connect(TogglApi::instance, SIGNAL(displayWorkspaceSelect(QVector<GenericView*>)),
            this, SLOT(displayWorkspaceSelect(QVector<GenericView*>)));

    connect(TogglApi::instance, SIGNAL(displayProjectAutocomplete(QVector<AutocompleteView*>)),
            this, SLOT(displayProjectAutocomplete(QVector<AutocompleteView*>)));

    connect(TogglApi::instance, SIGNAL(displayTimeEntryAutocomplete(QVector<AutocompleteView*>)),
            this, SLOT(displayTimeEntryAutocomplete(QVector<AutocompleteView*>)));

    connect(TogglApi::instance, SIGNAL(displayClientSelect(QVector<GenericView*>)),
            this, SLOT(displayClientSelect(QVector<GenericView*>)));
}

TimeEntryEditorWidget::~TimeEntryEditorWidget()
{
    delete ui;
}

void TimeEntryEditorWidget::displayTags(
    QVector<GenericView*> tags)
{

}

void TimeEntryEditorWidget::displayClientSelect(
    QVector<GenericView *> list)
{
    clientSelectUpdate = list;
    clientSelectNeedsUpdate = true;
    if (ui->newProjectClient->hasFocus())
    {
        return;
    }

    u_int64_t workspaceID = 0;
    QVariant data = ui->newProjectWorkspace->currentData();
    if (data.canConvert<GenericView *>())
    {
        GenericView *view = data.value<GenericView *>();
        workspaceID = view->ID;
    }
    ui->newProjectClient->clear();
    ui->newProjectClient->addItem("");
    foreach(GenericView *view, clientSelectUpdate)
    {
        if (workspaceID && workspaceID != view->WID)
        {
            continue;
        }
        ui->newProjectClient->addItem(view->Name, QVariant::fromValue(view));
    }
    clientSelectNeedsUpdate = false;
}

void TimeEntryEditorWidget::displayTimeEntryAutocomplete(
    QVector<AutocompleteView *> list)
{
    timeEntryAutocompleteUpdate = list;
    timeEntryAutocompleteNeedsUpdate = true;
    if (ui->description->hasFocus())
    {
        return;
    }
    ui->description->clear();
    ui->description->addItem("");
    foreach(AutocompleteView *view, timeEntryAutocompleteUpdate)
    {
        ui->description->addItem(view->Text, QVariant::fromValue(view));
    }
    timeEntryAutocompleteNeedsUpdate = false;
}

void TimeEntryEditorWidget::displayProjectAutocomplete(
    QVector<AutocompleteView *> list)
{
    projectAutocompleteUpdate = list;
    projectAutocompleteNeedsUpdate = true;
    if (ui->project->hasFocus())
    {
        return;
    }
    ui->project->clear();
    ui->project->addItem("");
    foreach(AutocompleteView *view, projectAutocompleteUpdate)
    {
        ui->project->addItem(view->Text, QVariant::fromValue(view));
    }
    projectAutocompleteNeedsUpdate = false;
}

void TimeEntryEditorWidget::displayWorkspaceSelect(
    QVector<GenericView *> list)
{
    workspaceSelectUpdate = list;
    workspaceSelectNeedsUpdate = true;
    if (ui->newProjectWorkspace->hasFocus())
    {
        return;
    }
    ui->newProjectWorkspace->clear();
    foreach(GenericView *view, workspaceSelectUpdate)
    {
        ui->newProjectWorkspace->addItem(view->Name, QVariant::fromValue(view));
    }
    workspaceSelectNeedsUpdate = false;
}

void TimeEntryEditorWidget::displayLogin(
    const bool open,
    const uint64_t user_id)
{
    if (open || !user_id)
    {
        setVisible(false);
    }
}

void TimeEntryEditorWidget::displayTimeEntryList(
    const bool open,
    QVector<TimeEntryView *> list)
{
    if (open)
    {
        setVisible(false);
    }
}

void TimeEntryEditorWidget::displayTimeEntryEditor(
    const bool open,
    TimeEntryView *view,
    const QString focused_field_name)
{
    if (open)
    {
        ui->timeDetails->setVisible(false);
        ui->timeOverview->setVisible(true);

        ui->newProject->setVisible(false);
        ui->addNewProject->setVisible(true);

        setVisible(true);
    }

    guid = view->GUID;

    ui->description->setEditText(view->Description);
    ui->project->setEditText(view->ProjectAndTaskLabel);
    ui->start->setText(view->StartTimeString);
    ui->stop->setText(view->EndTimeString);
    ui->duration->setText(view->Duration);
    ui->billable->setChecked(view->Billable);
    ui->timeOverview->setText("" + view->timeOverview() + "");

    ui->lastUpdate->setVisible(view->UpdatedAt);
    ui->lastUpdate->setText(view->lastUpdate());
}

void TimeEntryEditorWidget::on_doneButton_clicked()
{
    TogglApi::instance->viewTimeEntryList();
}

void TimeEntryEditorWidget::on_deleteButton_clicked()
{
    if (QMessageBox::Ok == QMessageBox(QMessageBox::Question,
                                        "Delete this time entry?",
                                        "Deleted time entries cannot be restored.",
                                        QMessageBox::Ok|QMessageBox::Cancel).exec())
    {
        TogglApi::instance->deleteTimeEntry(guid);
    }
}

void TimeEntryEditorWidget::on_addNewProject_linkActivated(const QString &link)
{
    ui->addNewProject->setVisible(false);
    ui->newProject->setVisible(true);
    ui->newProjectName->setFocus();
}

void TimeEntryEditorWidget::on_timeOverview_linkActivated(const QString &link)
{
    ui->timeOverview->setVisible(false);
    ui->timeDetails->setVisible(true);
}

void TimeEntryEditorWidget::on_newProjectWorkspace_currentIndexChanged(int index)
{
    displayClientSelect(clientSelectUpdate);
}
<commit_msg>Edit form improvemenets (linux)<commit_after>#include "timeentryeditorwidget.h"
#include "ui_timeentryeditorwidget.h"

#include <QMessageBox>

#include "toggl_api.h"

TimeEntryEditorWidget::TimeEntryEditorWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TimeEntryEditorWidget),
    guid(""),
    timeEntryAutocompleteNeedsUpdate(false),
    projectAutocompleteNeedsUpdate(false),
    workspaceSelectNeedsUpdate(false),
    clientSelectNeedsUpdate(false)
{
    ui->setupUi(this);

    setVisible(false);

    ui->addNewProject->setText("Add new project");

    connect(TogglApi::instance, SIGNAL(displayLogin(bool,uint64_t)),
            this, SLOT(displayLogin(bool,uint64_t)));

    connect(TogglApi::instance, SIGNAL(displayTimeEntryList(bool,QVector<TimeEntryView*>)),
            this, SLOT(displayTimeEntryList(bool,QVector<TimeEntryView*>)));

    connect(TogglApi::instance, SIGNAL(displayTimeEntryEditor(bool,TimeEntryView*,QString)),
            this, SLOT(displayTimeEntryEditor(bool,TimeEntryView*,QString)));

    connect(TogglApi::instance, SIGNAL(displayTags(QVector<GenericView*>)),
            this, SLOT(displayTags(QVector<GenericView*>)));

    connect(TogglApi::instance, SIGNAL(displayWorkspaceSelect(QVector<GenericView*>)),
            this, SLOT(displayWorkspaceSelect(QVector<GenericView*>)));

    connect(TogglApi::instance, SIGNAL(displayProjectAutocomplete(QVector<AutocompleteView*>)),
            this, SLOT(displayProjectAutocomplete(QVector<AutocompleteView*>)));

    connect(TogglApi::instance, SIGNAL(displayTimeEntryAutocomplete(QVector<AutocompleteView*>)),
            this, SLOT(displayTimeEntryAutocomplete(QVector<AutocompleteView*>)));

    connect(TogglApi::instance, SIGNAL(displayClientSelect(QVector<GenericView*>)),
            this, SLOT(displayClientSelect(QVector<GenericView*>)));
}

TimeEntryEditorWidget::~TimeEntryEditorWidget()
{
    delete ui;
}

void TimeEntryEditorWidget::displayTags(
    QVector<GenericView*> tags)
{

}

void TimeEntryEditorWidget::displayClientSelect(
    QVector<GenericView *> list)
{
    clientSelectUpdate = list;
    clientSelectNeedsUpdate = true;
    if (ui->newProjectClient->hasFocus())
    {
        return;
    }

    u_int64_t workspaceID = 0;
    QVariant data = ui->newProjectWorkspace->currentData();
    if (data.canConvert<GenericView *>())
    {
        GenericView *view = data.value<GenericView *>();
        workspaceID = view->ID;
    }
    ui->newProjectClient->clear();
    ui->newProjectClient->addItem("");
    foreach(GenericView *view, clientSelectUpdate)
    {
        if (workspaceID && workspaceID != view->WID)
        {
            continue;
        }
        ui->newProjectClient->addItem(view->Name, QVariant::fromValue(view));
    }
    clientSelectNeedsUpdate = false;
}

void TimeEntryEditorWidget::displayTimeEntryAutocomplete(
    QVector<AutocompleteView *> list)
{
    timeEntryAutocompleteUpdate = list;
    timeEntryAutocompleteNeedsUpdate = true;
    if (ui->description->hasFocus())
    {
        return;
    }
    ui->description->clear();
    ui->description->addItem("");
    foreach(AutocompleteView *view, timeEntryAutocompleteUpdate)
    {
        ui->description->addItem(view->Text, QVariant::fromValue(view));
    }
    timeEntryAutocompleteNeedsUpdate = false;
}

void TimeEntryEditorWidget::displayProjectAutocomplete(
    QVector<AutocompleteView *> list)
{
    projectAutocompleteUpdate = list;
    projectAutocompleteNeedsUpdate = true;
    if (ui->project->hasFocus())
    {
        return;
    }
    ui->project->clear();
    ui->project->addItem("");
    foreach(AutocompleteView *view, projectAutocompleteUpdate)
    {
        ui->project->addItem(view->Text, QVariant::fromValue(view));
    }
    projectAutocompleteNeedsUpdate = false;
}

void TimeEntryEditorWidget::displayWorkspaceSelect(
    QVector<GenericView *> list)
{
    workspaceSelectUpdate = list;
    workspaceSelectNeedsUpdate = true;
    if (ui->newProjectWorkspace->hasFocus())
    {
        return;
    }
    ui->newProjectWorkspace->clear();
    foreach(GenericView *view, workspaceSelectUpdate)
    {
        ui->newProjectWorkspace->addItem(view->Name, QVariant::fromValue(view));
    }
    workspaceSelectNeedsUpdate = false;
}

void TimeEntryEditorWidget::displayLogin(
    const bool open,
    const uint64_t user_id)
{
    if (open || !user_id)
    {
        setVisible(false);
    }
}

void TimeEntryEditorWidget::displayTimeEntryList(
    const bool open,
    QVector<TimeEntryView *> list)
{
    if (open)
    {
        setVisible(false);
    }
}

void TimeEntryEditorWidget::displayTimeEntryEditor(
    const bool open,
    TimeEntryView *view,
    const QString focused_field_name)
{
    if (open)
    {
        ui->timeDetails->setVisible(false);
        ui->timeOverview->setVisible(true);

        ui->newProject->setVisible(false);
        ui->addNewProject->setVisible(true);

        setVisible(true);
    }

    guid = view->GUID;

    ui->description->setEditText(view->Description);
    ui->project->setEditText(view->ProjectAndTaskLabel);
    ui->start->setText(view->StartTimeString);
    ui->stop->setText(view->EndTimeString);
    ui->dateEdit->setDateTime(QDateTime::fromTime_t(view->Started));
    ui->duration->setText(view->Duration);
    ui->billable->setChecked(view->Billable);
    ui->timeOverview->setText("" + view->timeOverview() + "");

    ui->lastUpdate->setVisible(view->UpdatedAt);
    ui->lastUpdate->setText(view->lastUpdate());
}

void TimeEntryEditorWidget::on_doneButton_clicked()
{
    TogglApi::instance->viewTimeEntryList();
}

void TimeEntryEditorWidget::on_deleteButton_clicked()
{
    if (QMessageBox::Ok == QMessageBox(QMessageBox::Question,
                                        "Delete this time entry?",
                                        "Deleted time entries cannot be restored.",
                                        QMessageBox::Ok|QMessageBox::Cancel).exec())
    {
        TogglApi::instance->deleteTimeEntry(guid);
    }
}

void TimeEntryEditorWidget::on_addNewProject_linkActivated(const QString &link)
{
    ui->addNewProject->setVisible(false);
    ui->newProject->setVisible(true);
    ui->newProjectName->setFocus();
}

void TimeEntryEditorWidget::on_timeOverview_linkActivated(const QString &link)
{
    ui->timeOverview->setVisible(false);
    ui->timeDetails->setVisible(true);
    ui->duration->setFocus();
}

void TimeEntryEditorWidget::on_newProjectWorkspace_currentIndexChanged(int index)
{
    displayClientSelect(clientSelectUpdate);
}
<|endoftext|>


<commit_before>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

ControlMovements lineFollowingControl() {

  line_main();

  return ControlMovements();
}

void line_main() {
//  printf("Hello, this is Caleb\n");

  VideoCapture cap("../../tests/videos/top_down_4.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

  namedWindow("edges", CV_WINDOW_NORMAL);
//  Mat edges;
  for (; ;) {
    Mat mask;
    Mat frame, hsv;
    cap >> frame; // get a new frame from camera

    cvtColor(frame, hsv, CV_BGR2HSV);

    double minH = 30;
    double minS = 0;
    double minV = 240;
    double maxH = 80;
    double maxS = 70;
    double maxV = 255;

    cv::Scalar lower(minH, minS, minV);
    cv::Scalar upper(maxH, maxS, maxV);
    cv::inRange(hsv, lower, upper, mask);

//    bitwise_and(frame, frame, frame, mask);

    erode(mask, mask, Mat(), Point(-1, -1), 5);
    medianBlur(mask, mask, 5);
    medianBlur(mask, mask, 5);
    medianBlur(mask, mask, 5);

    vector<Vec4i> lines;
    HoughLines(mask, lines, 1, CV_PI / 180.0, 10);

    printf("Adding in %d lines\n", (int) lines.size());
    for (size_t i = 0; i < lines.size(); i++) {
      float rho = lines[i][0], theta = lines[i][1];
      Point pt1, pt2;
      double a = cos(theta), b = sin(theta);
      double x0 = a * rho, y0 = b * rho;
      pt1.x = cvRound(x0 + 1000 * (-b));
      pt1.y = cvRound(y0 + 1000 * (a));
      pt2.x = cvRound(x0 - 1000 * (-b));
      pt2.y = cvRound(y0 - 1000 * (a));
      line(frame, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
    }
//    if (lines.size() < 1) continue;

    imshow("edges", mask);
    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor
  return;
}
<commit_msg>messing with erode<commit_after>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

ControlMovements lineFollowingControl() {

  line_main();

  return ControlMovements();
}

void line_main() {
//  printf("Hello, this is Caleb\n");

  VideoCapture cap("../../tests/videos/top_down_4.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

  namedWindow("edges", CV_WINDOW_NORMAL);
//  Mat edges;
  for (; ;) {
    Mat mask;
    Mat frame, hsv;
    cap >> frame; // get a new frame from camera

    cvtColor(frame, hsv, CV_BGR2HSV);

    double minH = 30;
    double minS = 0;
    double minV = 240;
    double maxH = 80;
    double maxS = 70;
    double maxV = 255;

    cv::Scalar lower(minH, minS, minV);
    cv::Scalar upper(maxH, maxS, maxV);
    cv::inRange(hsv, lower, upper, mask);

//    bitwise_and(frame, frame, frame, mask);

//    erode(mask, mask, Mat(), Point(-1, -1), 5);
//    medianBlur(mask, mask, 5);
//    medianBlur(mask, mask, 5);
//    medianBlur(mask, mask, 5);

    vector<Vec2f> lines;
    HoughLines(mask, lines, 1, CV_PI/180, 100, 0, 0 );

    printf("Adding in %d lines\n", (int) lines.size());
    for (size_t i = 0; i < lines.size(); i++) {
      float rho = lines[i][0], theta = lines[i][1];
      Point pt1, pt2;
      double a = cos(theta), b = sin(theta);
      double x0 = a * rho, y0 = b * rho;
      pt1.x = cvRound(x0 + 1000 * (-b));
      pt1.y = cvRound(y0 + 1000 * (a));
      pt2.x = cvRound(x0 - 1000 * (-b));
      pt2.y = cvRound(y0 - 1000 * (a));
      line(frame, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
    }
//    if (lines.size() < 1) continue;

    imshow("edges", mask);
    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor
  return;
}
<|endoftext|>


<commit_before>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

ControlMovements lineFollowingControl() {

  line_main();

  return ControlMovements();
}

void line_main() {
//  printf("Hello, this is Caleb\n");

  VideoCapture cap("../../tests/videos/top_down_4.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

  namedWindow("edges", CV_WINDOW_NORMAL);
//  Mat edges;
  for (; ;) {
    Mat mask;
    Mat frame, hsv;
    cap >> frame; // get a new frame from camera

    cvtColor(frame, hsv, CV_BGR2HSV);

    double minH = 30;
    double minS = 0;
    double minV = 240;
    double maxH = 80;
    double maxS = 70;
    double maxV = 255;

    cv::Scalar lower(minH, minS, minV);
    cv::Scalar upper(maxH, maxS, maxV);
    cv::inRange(hsv, lower, upper, mask);

//    bitwise_and(frame, frame, frame, mask);

    resize(mask, mask, Size(), .2, .2);

    vector <Vec4i> lines;
    HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 100, 10);

    printf("Adding in %d lines\n", (int) lines.size());
    for (size_t i = 0; i < lines.size(); i++) {
      Vec4i l = lines[i];
      line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
      // break;
    }
//    if (lines.size() < 1) continue;

    imshow("edges", frame);
    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor
  return;
}
<commit_msg>size changes<commit_after>/*

*/

#include "lineFollowing.h"

using namespace std;
using namespace cv;

ControlMovements lineFollowingControl() {

  line_main();

  return ControlMovements();
}

void line_main() {
//  printf("Hello, this is Caleb\n");

  VideoCapture cap("../../tests/videos/top_down_4.m4v");
  if (!cap.isOpened())  // check if we succeeded
    return;

  namedWindow("edges", CV_WINDOW_NORMAL);
//  Mat edges;
  for (; ;) {
    Mat mask;
    Mat frame, hsv;
    cap >> frame; // get a new frame from camera

    resize(frame, frame, Size(), .2, .2);
    cvtColor(frame, hsv, CV_BGR2HSV);

    double minH = 30;
    double minS = 0;
    double minV = 240;
    double maxH = 80;
    double maxS = 70;
    double maxV = 255;

    cv::Scalar lower(minH, minS, minV);
    cv::Scalar upper(maxH, maxS, maxV);
    cv::inRange(hsv, lower, upper, mask);

//    bitwise_and(frame, frame, frame, mask);

    vector <Vec4i> lines;
    HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 100, 10);

    printf("Adding in %d lines\n", (int) lines.size());
    for (size_t i = 0; i < lines.size(); i++) {
      Vec4i l = lines[i];
      line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
      // break;
    }
//    if (lines.size() < 1) continue;

    imshow("edges", frame);
    if (waitKey(30) >= 0) break;

  }
  // the camera will be deinitialized automatically in VideoCapture destructor
  return;
}
<|endoftext|>