Exemplo n.º 1
0
result_t console_base::clickMouse(exlib::string button, bool dbclick)
{
	result_t hr;

	hr = mouseDown(button);
	if (hr < 0)
		return hr;

	hr = mouseUp(button);
	if (hr < 0)
		return hr;

	if (dbclick)
	{
		hr = mouseDown(button);
		if (hr < 0)
			return hr;

		hr = mouseUp(button);
		if (hr < 0)
			return hr;
	}

	return 0;
}
Exemplo n.º 2
0
	void PretzelSlider::mouseUp(const vec2 &pos){
        for( auto it=mSliderListi.begin(); it!=mSliderListi.end(); ++it){
            it->mouseUp( pos - mOffset );
        }
        for( auto it=mSliderListf.begin(); it!=mSliderListf.end(); ++it){
            it->mouseUp( pos - mOffset );
        }
	}
Exemplo n.º 3
0
//! Connects to mouseDown, mouseDrag, mouseWheel and resize signals of \a window, with optional priority \a signalPriority
void CameraUi::connect( const app::WindowRef &window, int signalPriority )
{
	mWindow = window;
	mSignalPriority = signalPriority;
	if( window ) {
		mMouseDownConnection = window->getSignalMouseDown().connect( signalPriority,
			[this]( app::MouseEvent &event ) { mouseDown( event ); } );
		mMouseUpConnection = window->getSignalMouseUp().connect( signalPriority,
			[this]( app::MouseEvent &event ) { mouseUp( event ); } );
		mMouseDragConnection = window->getSignalMouseDrag().connect( signalPriority,
			[this]( app::MouseEvent &event ) { mouseDrag( event ); } );
		mMouseWheelConnection = window->getSignalMouseWheel().connect( signalPriority,
			[this]( app::MouseEvent &event ) { mouseWheel( event ); } );
		mWindowResizeConnection = window->getSignalResize().connect( signalPriority,
			[this]() {
				setWindowSize( mWindow->getSize() );
				if( mCamera )
					mCamera->setAspectRatio( mWindow->getAspectRatio() );
			}
		);
	}
	else
		disconnect();
		
	mLastAction = ACTION_NONE;
}
Exemplo n.º 4
0
void GUI::handleEvent(const SDL_Event &event)
{
    auto k = event.key.keysym.sym;

    switch (event.type)
    {
    case SDL_MOUSEBUTTONDOWN:
        mouseDown(event.button.button);
        break;
    case SDL_MOUSEBUTTONUP:
        mouseUp(event.button.button);
        break;
    case SDL_MOUSEMOTION:
        mouseMovement(event.motion.x, event.motion.y);
        break;
    case SDL_KEYDOWN:
        context->injectKeyDown(key(event.key.keysym.sym));
        if (key(event.key.keysym.sym) < 95) // REALLY UGLY FIX, 95 IS A RANDOM NUMBER NO GUARANTY IT WILL ALWAYS WORK
            context->injectChar(key(event.key.keysym.sym));
        break;
    case SDL_KEYUP:
        context->injectKeyUp(key(event.key.keysym.sym));
        break;
    }
}
Exemplo n.º 5
0
/**
* Click and drag absolute: move to a relative coordinate within the window
* windowname, clamped.
*/
bool clickAndDragAbsolute(std::string window_name, nlohmann::json action){
   //populate the window variables. 
  int x_start, x_end, y_start, y_end, mouse_button;
  bool no_clamp = false; 
  bool success = populateClickAndDragValues(action, window_name, x_start,
                       x_end, y_start, y_end, mouse_button, no_clamp);
  
  //if we couldn't populate the values, do nothing (window doesn't exist)
  if(!success){ 
    std::cout << "Click and drag unsuccessful due to failure to populate click and drag values." << std::endl;
    return false;
  }


  int start_x_position = action.value("start_x", -1);
  int start_y_position = action.value("start_y", -1);

  int end_x_position = action.value("end_x", -1);
  int end_y_position = action.value("end_y", -1);

  if (start_x_position == end_x_position && start_y_position == end_y_position){
    std::cout << "Error, the click and drag action did not specify movement." << std::endl;
    return false;
  }

  if(end_x_position == -1 || end_y_position == -1){
    std::cout << "ERROR: the click and drag action must include an ending position" << std::endl;
    return false;
  }
  


  //get the mouse into starting position if they are specified.
  if(start_x_position != -1 && start_y_position != -1){ 
    start_x_position = start_x_position + x_start;
    start_y_position = start_y_position + y_start;

    //don't move out of the window.
    clamp(start_x_position, x_start, x_end); 
    clamp(start_y_position, y_start, y_end);
    mouse_move(window_name, start_x_position, start_y_position,x_start, x_end, 
                                                        y_start, y_end, false); 
  }
  
  end_x_position = end_x_position + x_start;
  end_y_position = end_y_position + y_start;
  
  //clamp the end position so we don't exit the window. 
  clamp(end_x_position, x_start, x_end); 
  clamp(end_y_position, y_start, y_end);

  //These functions won't do anything if the window doesn't exist. 
  mouseDown(window_name,mouse_button); 
  mouse_move(window_name, end_x_position, end_y_position,x_start, x_end, 
                                                  y_start, y_end, false);
  mouseUp(window_name,mouse_button);  

  return true;
}
Exemplo n.º 6
0
/**
* This function mousedowns then mouseups to simulate a click. 
*/
bool click(std::string window_name, int button){
  bool success = mouseDown(window_name, button);
  if(!success){
    return false;
  }
  success = mouseUp(window_name, button);
  return success;
}
Exemplo n.º 7
0
void MouseThread::threadedFunction() {
  Action action;
  
  while (true) {
    action.type = NO_ACTION;

    lock();
    if (next.type != NO_ACTION) {
      action = next;
      next.type = NO_ACTION;
    }
    unlock();

    switch (action.type) {
      case NO_ACTION: {
        sleep(100);
        break;
      }
      case MOVE: {
        mouseMove(action.x1, action.y1);
        sleep(100);
        break;
      }
      case CLICK: {
        mouseDown(action.x1, action.y1);
        sleep(10);
        mouseUp(action.x1, action.y1);
        sleep(100);
        break;
      }
      case DRAG: {
        mouseDown(action.x1, action.y1);
        for (int i = 0; i < 10; ++i) {
          sleep(10);
          mouseDrag(action.x1 + (action.x2 - action.x1) * i / 10, action.y1 + (action.y2 - action.y1) * i / 10);
        }
        sleep(10);
        mouseUp(action.x2, action.y2);
        sleep(400);
        break;
      }
    }
  }
}
Exemplo n.º 8
0
//--------------------------------------------------------------
// mouse clicked
void mgUglyButton::mouseClick(
  void* source,
  int x,
  int y,
  int modifiers,
  int button,
  int clickCount)
{
  mouseDown(source, x, y, modifiers, button);
  mouseUp(source, x, y, modifiers, button);
}
Exemplo n.º 9
0
void gameController::handleEvents() 
{
    static SDL_Event event;
    
    while(SDL_PollEvent(&event)) 
    {
        fsPoint2f p = m_oMouseLocWorld.loc;
        
        switch(event.type) 
        {
                
            case SDL_MOUSEMOTION:
                mouseMove(event.button.x,event.button.y, 0);
                break;
            case SDL_MOUSEBUTTONDOWN:
                mouseDown(p.x,p.y ,0);
                
                break;           
            case SDL_MOUSEBUTTONUP:
                mouseUp(p.x,p.y ,0);
                break;
                /*
                 //case SDL_ACTIVEEVENT:
                 //Something's happend with our focus
                 //If we lost focus or we are iconified, we
                 //shouldn't draw the screen
                 
                 if (event.active.gain == 0)
                 isActive = false;
                 else
                 isActive = true;
                 */
                break;
            case SDL_VIDEORESIZE:
                resizeWindow(event.resize.w, event.resize.h);
                break;
            case SDL_KEYDOWN:
                // handle key presses
                keyPress(&event.key.keysym);
                break;
            case SDL_QUIT:
                // handle quit requests
                done = true;
                break;
            default:
                break;
        }
    }
}
Exemplo n.º 10
0
bool Node::treeMouseUp( MouseEvent event )
{
    if(!mIsVisible) return false;

    // test children first, from top to bottom
    NodeList nodes(mChildren);
    NodeList::reverse_iterator itr;
    bool handled = false;
    for(itr=nodes.rbegin(); itr!=nodes.rend()&&!handled; ++itr)
        (*itr)->treeMouseUp(event); // don't care about 'handled' for now

    // if not handled, test this node
    if(!handled) handled = mouseUp(event);

    return handled;
}
Exemplo n.º 11
0
bool TreentNode::deepMouseUp( ci::app::MouseEvent &event )
{
  bool captured = false;
  auto gui_component = component<GuiComponent>();
  if( gui_component )
    captured = gui_component->mouseUp( event, getWorldTransform() );

  for( TreentNodeRef &child : mChildren )
  { // stop evaluation if event was captured by self or a child
    if( captured )
      break;

    captured = child->deepMouseUp( event );
  }
  return captured;
}
Exemplo n.º 12
0
void GUI::mouseUp(const Events::Event &event) {
	if (event.button.button != SDL_BUTTON_LMASK)
		// We only care about left mouse button presses
		return;

	Widget *widget = getWidgetAt(event.button.x, event.button.y);
	if (widget != _currentWidget) {
		changedWidget(widget);
		return;
	}

	mouseUp(_currentWidget, event);

	checkWidgetActive(_currentWidget);

	updateMouse();
}
Exemplo n.º 13
0
int GUI::processEventQueue() {
	bool hasMove = false;

	for (std::list<Events::Event>::const_iterator e = _eventQueue.begin();
	     e != _eventQueue.end(); ++e) {

		if      (e->type == Events::kEventMouseMove)
			hasMove = true;
		else if (e->type == Events::kEventMouseDown)
			mouseDown(*e);
		else if (e->type == Events::kEventMouseUp)
			mouseUp(*e);
	}

	_eventQueue.clear();

	if (hasMove)
		updateMouse();

	return _returnCode;
}
Exemplo n.º 14
0
        //---------------------------------------------------------------------
        //! @brief Constructor
        //---------------------------------------------------------------------
        Image::Image( Evas* _win
                    , bool  _use_rh )
            : image__()
            , image_pressed__()
            , visibility__( Visibility::INVISIBLE )
            , use_rh__( _use_rh )
            , path__()
            , path_pressed__()
            , rh__( Factory< IResourceHandler >::get( "EFL" ) )
            , signal__( new Events::Signal() )
        {
            image__ = evas_object_image_filled_add( _win );
            image_pressed__ = evas_object_image_filled_add( _win );

            CCallbackHandler::evasEventCallback( image__
                                               , CALLBACK_MOUSE_DOWN
                                               , [=](){ mouseDown();
                                                        Factory< Timer >::get( "Timer" )->touchEvent(); } );
            CCallbackHandler::evasEventCallback( image__
                                               , CALLBACK_MOUSE_UP
                                               , [=](){ mouseUp(); } );
        }
Exemplo n.º 15
0
Arquivo: win.c Projeto: jacereda/glcv
static int onRBUTTONUP(HWND win, int x, int y, UINT flacv) {
        return mouseUp(CVK_MOUSERIGHT);
}
Exemplo n.º 16
0
Arquivo: win.c Projeto: jacereda/glcv
static int onMBUTTONUP(HWND win, int x, int y, UINT flacv) {
        return mouseUp(CVK_MOUSEMIDDLE);
}
Exemplo n.º 17
0
Arquivo: win.c Projeto: jacereda/glcv
static int onLBUTTONUP(HWND win, int x, int y, UINT flacv) {
        return mouseUp(CVK_MOUSELEFT);
}
Exemplo n.º 18
0
void xlGridCanvasPictures::mouseRightUp(wxMouseEvent& event)
{
    mouseUp();
}
Exemplo n.º 19
0
int main(int argc, char **argv) {

    //////////////////////////////////////////////////////////////////////
    // check joystick
    //////////////////////////////////////////////////////////////////////

    std::string commandNoJoystick = std::string(argv[0]) +  " --no-joystick ";
    Herve::utilInfo("to disable joystick, use : ", commandNoJoystick.c_str() , __FILE__, __LINE__);
    if (argc == 2 and std::string(argv[1]) == "--no-joystick")
        gEnableJoystick = false;

    //////////////////////////////////////////////////////////////////////
    // init
    //////////////////////////////////////////////////////////////////////

    // display device
    gUptrDisplayDevice.reset(new HerveOvr::DisplayDeviceStereoOvr(1024, 1024));
    if (not gUptrDisplayDevice->initDevice()) {
        gUptrDisplayDevice.reset(new Herve::DisplayDeviceMono());
        //gUptrDisplayDevice.reset(new Herve::DisplayDeviceStereoFake(1024, 1024));
        gUptrDisplayDevice->initDevice();
    }

    // SDL
    if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
        Herve::utilError("SDL_Init", "", __FILE__, __LINE__);
    const SDL_VideoInfo* info = SDL_GetVideoInfo();
    int maxWidth = info->current_w;
    int maxHeight = info->current_h;
    SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
    gPtrSurface = SDL_SetVideoMode( gUptrDisplayDevice->getWidth(), gUptrDisplayDevice->getHeight(), 24, SDL_OPENGL|SDL_RESIZABLE );
    if( gPtrSurface == NULL )
        Herve::utilError("SDL_SetVideoMode", "", __FILE__, __LINE__);
    atexit(SDL_Quit);
    SDL_EnableUNICODE( SDL_TRUE );
    SDL_WM_SetCaption( "DemoSdl1", NULL );

    // joysticks
    int nbJoysticks = SDL_NumJoysticks();
    for(int i=0; i<nbJoysticks; i++) {
        SDL_Joystick * stick = SDL_JoystickOpen( i );
        if( stick ) {
            Herve::utilInfo("joystick = ", SDL_JoystickName(i), __FILE__, __LINE__);
        }
    }

    // scene data
    gUptrDisplayDevice->initDisplay(maxWidth, maxHeight);
    gScene.init(gUptrDisplayDevice.get());
    gFpsCounter.start();

    Herve::utilInfo("width = ", std::to_string(gUptrDisplayDevice->getWidth()).c_str(), __FILE__, __LINE__);
    Herve::utilInfo("height = ", std::to_string(gUptrDisplayDevice->getHeight()).c_str(), __FILE__, __LINE__);
    Herve::utilInfo("maxWidth = ", std::to_string(gUptrDisplayDevice->getMaxWidth()).c_str(), __FILE__, __LINE__);
    Herve::utilInfo("maxHeight = ", std::to_string(gUptrDisplayDevice->getMaxHeight()).c_str(), __FILE__, __LINE__);


    //////////////////////////////////////////////////////////////////////
    // main loop
    //////////////////////////////////////////////////////////////////////

    SDL_Event event;
    while (true)	{
        // handle events
        while( SDL_PollEvent( &event ) ) {
            switch(event.type) {
            case SDL_QUIT:
                exit(0);
                break;
            case SDL_KEYDOWN:
                keyDown(event.key);
                break;
            case SDL_KEYUP:
                keyUp(event.key);
                break;
            case SDL_MOUSEBUTTONUP :
                mouseUp(event.button);
                break;
            case SDL_MOUSEBUTTONDOWN :
                mouseDown(event.button);
                break;
            case SDL_MOUSEMOTION :
                mouseMotion(event.motion);
                break;
            case SDL_VIDEORESIZE :
                resize(event.resize);
                break;
            case SDL_JOYAXISMOTION :
                joyMotion(event.jaxis);
                break;
            }
        }

        updateCamera();
        render();
    }

    return 0;
}
Exemplo n.º 20
0
void CameraUi::mouseUp( app::MouseEvent &event )
{
	mouseUp( event.getPos() );
	event.setHandled();
}
Exemplo n.º 21
0
hkDefaultDemo::~hkDefaultDemo()
{

#if HK_CONFIG_THREAD == HK_CONFIG_MULTI_THREADED

	if (m_jobThreadPool)
	{
		m_jobThreadPool->removeReferenceLockUnchecked();
	}

	delete m_jobQueue;

	if (m_spuUtil)
	{

		#if defined (HK_PLATFORM_PS3_PPU)
			// free resources if necessary
			int ret = cellSpursFinalize ( hkGetSpursInstance() );
			if (ret)
			{
				HK_ERROR(0x73e432b3, "cellSpursFinalize failed :" << ret);
			}
			void* spurs = hkGetSpursInstance();

			hkAlignedDeallocate<char>( (char*)spurs );
		#endif
	}
#endif

	for ( int i = 0; i < m_steppers.getSize(); ++i )
	{
		m_steppers[i]->removeReference();
	}

	if(m_mouseActive)
	{
		mouseUp();
	}
	if ( m_lastProgress )
	{
		delete m_lastProgress;
	}

	cleanupGraphics();

	for( int i = 0; i < m_delayedCleanup.getSize(); ++i )
	{
		m_delayedCleanup[i]->removeReference();
	}

	if (m_forcedShadowsOn)
	{
		m_env->m_options->m_enableShadows = false; // reset
	}
	else if (m_forcedShadowsOff)
	{
		m_env->m_options->m_enableShadows = true;// reset
	}
	
#if defined (HK_USE_CHARACTER_FACTORY)
 	if (m_characterFactory)
 	{
 		delete m_characterFactory;
 	}
#endif
}
Exemplo n.º 22
0
void Gdc2005Demo::handleUserInput(struct GdcStateInput& stateInput)
{
	const hkgKeyboard& keys = m_env->m_window->getKeyboard();

	// Show help on the keys if the user asks for it
	if ( keys.getKeyState('H') ||
		keys.getKeyState(HKG_VKEY_F1) ||
		( m_env->m_gamePad->isButtonPressed(HKG_PAD_BUTTON_L1)
		&& m_env->m_gamePad->isButtonPressed(HKG_PAD_BUTTON_R1)
		&& m_env->m_gamePad->isButtonPressed(HKG_PAD_BUTTON_0) )
		)
	{
		showKeys();
	}

	// For reference, on PC keyboard:
	//  HKG_VKEY_DELETE == HKG_PAD_BUTTON_L1
	//  HKG_VKEY_END == HKG_PAD_BUTTON_R1
	//  HKG_VKEY_INSERT == HKG_PAD_BUTTON_L2
	//  HKG_VKEY_HOME == HKG_PAD_BUTTON_R2

	// See if we want to chuck anything into the scene
	if ( m_env->m_gamePad->wasButtonPressed(HKG_PAD_BUTTON_2) )
	{
		hkVector4 startPos;
		m_env->m_window->getCurrentViewport()->getCamera()->getFrom( (float*)&startPos );

		hkVector4 velocity;
		m_env->m_window->getCurrentViewport()->getCamera()->getDir( (float*)&velocity );
		velocity.mul4( m_options.m_Physics.m_launchVelocity );

		chuckSomething( startPos, velocity );
	}

	// See if we want to shot the guy (right click or L2)
	if ( m_env->m_gamePad->isButtonPressed(HKG_PAD_BUTTON_L2) ||
		(m_env->m_window->getMouse().getButtonState() & HKG_MOUSE_RIGHT_BUTTON) )
	{
		hkVector4 rayStart;
		hkVector4 rayEnd;

		// unproject current 'mouse' pos.
		hkgCamera* cam = m_env->m_window->getViewport(0)->getCamera();
		int xPos = m_env->m_window->getMouse().getPosX();
		int yPos = m_env->m_window->getMouse().getPosY();
		cam->unProject( xPos, yPos, 0, m_env->m_window->getWidth(), m_env->m_window->getHeight(), (float*)&rayStart);
		cam->unProject( xPos, yPos, 1, m_env->m_window->getWidth(), m_env->m_window->getHeight(), (float*)&rayEnd);

		fireShot( rayStart, rayEnd, m_options.m_Physics.m_shotStrength ); // num == strength
	}

	// See if we want to drag objects around
	if( !m_mouseActive && ( m_env->m_gamePad->wasButtonPressed(HKG_PAD_BUTTON_R1) ||
		keys.getKeyState(HKG_VKEY_SPACE)) ) // Space == Button0 on PC == jump
	{
    	mouseDown(); // pick object under cursor
	}
	else if ( m_mouseActive )
	{
		if( !m_env->m_gamePad->isButtonPressed(HKG_PAD_BUTTON_R1) &&
			!m_env->m_window->getKeyboard().getKeyState(HKG_VKEY_SPACE) )
		{
			mouseUp(); // default physics game impl : delete mouse spring
		}
		else
		{
			mouseDrag(); // default physics game impl : unproject mouse and move spring.
		}
	}

	// Desired direction
	// If we are on a console we are using a stick and want that to dictate
	// the desired direction. Otherwise we will use the dpad ( keyboard dir keys )
	updateUserControl();

	// Die ? Get up? Jump?
	{
		const hkUint32 currentAnimationState = m_animationStateMachine->getCurrentState();
		const bool usingGamepad = m_env->m_window->hasGamePads() && !m_env->m_options->m_forceKeyboardGamepad;

		// DIE?
		if (m_env->m_gamePad->wasButtonPressed(HKG_PAD_BUTTON_1) && currentAnimationState != GDC_DYING_STATE && currentAnimationState != GDC_DEAD_STATE && currentAnimationState != GDC_GETTING_UP_STATE)
		{
			stateInput.m_shouldDie = true;
		}
		else
		{
			stateInput.m_shouldDie = false;
		}

		// DIVE?
		if (m_env->m_gamePad->wasButtonPressed(HKG_PAD_BUTTON_3) && currentAnimationState != GDC_DYING_STATE && currentAnimationState != GDC_DEAD_STATE && currentAnimationState != GDC_GETTING_UP_STATE)
		{
			stateInput.m_shouldDive = true;
		}
		else
		{
			stateInput.m_shouldDive = false;
		}

		// GET UP?
		if (m_env->m_gamePad->wasButtonPressed(HKG_PAD_BUTTON_1) && currentAnimationState == GDC_DEAD_STATE)
		{
			stateInput.m_shouldGetUp = true;
		}
		else
		{
			stateInput.m_shouldGetUp = false;
		}

		// JUMP?
		bool jumpPressed;
		if (usingGamepad)
		{
			jumpPressed = m_env->m_gamePad->wasButtonPressed(HKG_PAD_BUTTON_0);
		}
		else
		{
			jumpPressed = keys.wasKeyPressed('4');
		}
		if (jumpPressed && currentAnimationState!=GDC_DYING_STATE && currentAnimationState!=GDC_IN_AIR_STATE && currentAnimationState!=GDC_DEAD_STATE && currentAnimationState!=GDC_JUMP_STATE)
		{
			stateInput.m_shouldJump = true;
		}
		else
		{
			stateInput.m_shouldJump = false;
		}

	}
}
Exemplo n.º 23
0
/**
* The 'delta' version of the click and drag command. This function moves an xy
* distance from a startpoint. This distance is 'wrapping', so if it is outside 
* of the window, we mouseup, return to the start position, mousedown, and then
* move again. We give a one pixel border at each side of the window and clamp 
* using that value to avoid accidental resizing.
*/
bool clickAndDragDelta(std::string window_name, nlohmann::json action){
  //get the values of the student's window.
  int x_start, x_end, y_start, y_end, mouse_button; 
  bool no_clamp = false; 
  bool success = populateClickAndDragValues(action, window_name, x_start, 
                      x_end, y_start, y_end, mouse_button, no_clamp);
  
  //if we can't populate the click and drag values, do nothing.
  if(!success){ 
    std::cout << "Could not populate the click and drag values."<< std::endl;
    return false;
  }
  
  //Define the corners of our window. (We use vectors as 2d points.)
  std::vector<int> upper_left, upper_right, lower_left, lower_right; 
  upper_left.push_back(x_start); upper_left.push_back(y_start);
  upper_right.push_back(x_end); upper_right.push_back(y_start);
  lower_left.push_back(x_start); lower_left.push_back(y_end);
  lower_right.push_back(x_end); lower_right.push_back(y_end);

  
  //delta version, 2 values movement x and movement y.
  int amt_x_movement_remaining = action.value("x_distance", 0);
  int amt_y_movement_remaining = action.value("y_distance", 0);
  std::string start_location   = action.value("start_location", "center");

  //This shouldn't fail unless there isn't a mouse.
  std::string mouse_location_string = output_of_system_command("xdotool getmouselocation"); 
  std::vector<int> xy = extractIntsFromString(mouse_location_string);                      
  
  //if the mouse isn't detected, fail.
  if(xy.size() < 2){ 
    std::cout << "Mouse coordinates couldn't be found. Mouse undetected." 
                << std::endl;
    return false;
  }
  //get the current mouse location
  int start_mouse_x = xy[0];
  int start_mouse_y = xy[1];
  //clamp the mouse within the screen (and move in by a pixel).
  clamp(start_mouse_x, x_start+1, x_end-1); 
  clamp(start_mouse_y, y_start+1, y_end-1);

  //get the center of the window
  int width  = x_end - x_start;
  int height = y_end - y_start;
  int x_middle = x_start + (width/2);
  int y_middle = y_start+(height/2);

  //NOTE: check my arithmetic. 
  /**
  * The process that this algorithm goes through is as follows:
  * 1) Determine the slope of the dragged line and its distance.
  * 2) while we have not traversed the necessary distance
  * 3) project a line from the current mouse position towards the end 
  *      position with length equal to the remaining distance. 
  * 4) Now that we have a line segment defined, find where/if it intersects
  *      any of the window's edges
  * 5) if it does intersect, cut it off at the point of intersection, and only
  *      drag that far. Else, if it doesn't intersect, we can assume we are 
  *      inside of the window, due to the clamp, and can drag.
  * 6) update remaining distance and continue to loop.
  */

  //rise / run
  float slope=(float)amt_y_movement_remaining/(float)amt_x_movement_remaining;
  float total_distance_needed = sqrt(pow(amt_x_movement_remaining, 2) 
                                    + pow (amt_y_movement_remaining, 2)); 

  //remaining distance needed.
  float remaining_distance_needed = total_distance_needed; 

  int action_start_x = (start_location == "current") ? start_mouse_x : x_middle;
  int action_start_y = (start_location == "current") ? start_mouse_y : y_middle;

  std::cout << "start x " << start_mouse_x << " our x " << action_start_x;
  std::cout << "start y " << start_mouse_y << " our y " << action_start_y;

  //The functions called within this loop will not fire if the window doesn't 
  // exist. This check just short circuits to avoid additional printing.
  while(remaining_distance_needed >= 1 && windowExists(window_name)){ 
    int curr_x = action_start_x;                                             
    int curr_y = action_start_y;                                              
    int moved_mouse_x, moved_mouse_y;
    //reset the mouse to the start location.
    mouse_move(window_name, action_start_x, action_start_y, x_start, x_end, y_start, y_end,
                                                                        false); 
    //determine how far we've come.
    float fraction_of_distance_remaining = remaining_distance_needed 
                                            / total_distance_needed; 
    //project in the direction of the move to find the end of our line segment.
    float projected_x = action_start_x + (amt_x_movement_remaining * fraction_of_distance_remaining); 
    float projected_y = action_start_y + (amt_y_movement_remaining * fraction_of_distance_remaining);  

    //we are using vectors as 2d points.
    std::vector<int> current_point, projected_point;  
    current_point.push_back(curr_x); current_point.push_back(curr_y);
    projected_point.push_back(projected_x); 
    projected_point.push_back(projected_y);

    std::vector<float> intersection_point; 
    intersection_point=getLineIntersectionPoint(current_point,projected_point,
                                                      upper_left, upper_right);
    

    /**
    * TODO make this block smaller. 
    * These if statements just test all edges of the window against our 
    * projected line.
    */

    //found is just a quick short-circuit to keep the code from ballooning.
    bool found = false; 
    if(intersection_point.size() != 0){ //TOP
      std::cout << "intersected top" << std::endl;
      moved_mouse_x = (int)intersection_point[0]; 
      moved_mouse_y = (int)intersection_point[1];
      found = true;
    }

    if(!found) //RIGHT
    {
      intersection_point = getLineIntersectionPoint(current_point, 
                            projected_point, upper_right, lower_right);
      if(intersection_point.size() != 0){ 
        std::cout << "intersected right" << std::endl;
        moved_mouse_x = (int)intersection_point[0]; 
        moved_mouse_y = (int)intersection_point[1];
        found = true;
      }
    }

    if(!found) //BOTTOM
    {
      intersection_point = getLineIntersectionPoint(current_point, 
                              projected_point, lower_right, lower_left);
      if(intersection_point.size() != 0){
        std::cout << "intersected bottom" << std::endl;
        moved_mouse_x = (int)intersection_point[0]; 
        moved_mouse_y = (int)intersection_point[1];
        found = true;
      }
    }

    if(!found) //LEFT
    {
      intersection_point = getLineIntersectionPoint(current_point,
                             projected_point, lower_left, upper_left);
      if(intersection_point.size() != 0){
        std::cout << "intersected left" << std::endl;
        moved_mouse_x = (int)intersection_point[0]; 
        moved_mouse_y = (int)intersection_point[1];
        found = true;
      }
    }

    //if we didn't intersect, we are inside of the box (guaranteed by clamp)
    // so we can move freely.
    if(!found) 
    {
      std::cout << "No intersection at all"<< std::endl;
      moved_mouse_x = projected_x;
      moved_mouse_y = projected_y;
    }

    //the distance we can move
    float distance_of_move = sqrt(pow(moved_mouse_x - action_start_x, 2) 
                                    + pow (moved_mouse_y - action_start_y, 2)); 
    //we are moving distance_of_move
    remaining_distance_needed -= distance_of_move; 
    std::cout << "after the move, we had " << remaining_distance_needed 
                                          << " distance left " << std::endl;
    mouseDown(window_name,mouse_button); //click
    mouse_move(window_name, moved_mouse_x, moved_mouse_y,x_start, x_end, //drag
                                                        y_start, y_end, false); 
    mouseUp(window_name,mouse_button); //release
  } //end loop.

  //to preserve backwards compatibility.
  if(start_location != "current"){
    //put the mouse back where we found it.
    mouse_move(window_name, start_mouse_x, start_mouse_y, x_start, x_end, y_start, y_end,false);
  }

  return true;
}
Exemplo n.º 24
0
void FboMaskManager::mouseReleased(ofMouseEventArgs &e){
	mouseUp(e.x, e.y);
};
Exemplo n.º 25
0
int main()
{
  initializeCrap();
  install_int_ex(increment_speed_counter,BPS_TO_TIMER(120));
  int screenMode = 0; //0 for windowed, 1 for fullscreen
  srand((unsigned)time(NULL));

  BITMAP *buffer = create_bitmap(800,600);
  BITMAP *titleimg = load_bitmap("quiximgTitle.bmp",NULL);
  BITMAP *imgPlayers = load_bitmap("quiximgPlayerSet.bmp",NULL);
  MIDI *song = load_midi("quixsong.mid");
  PlayerObject poPlayer[4];
  LaserObject loLaser[4];
  LevelObject Level;
  MenuObject Menu;
  float scrollerX = -150.0, scrollerY = 5.0;
  int winner;

  poPlayer[0].setControlScheme(0);
  poPlayer[1].setControlScheme(1);
  poPlayer[2].setControlScheme(2);
  poPlayer[3].setControlScheme(3);
  poPlayer[0].samSound = load_sample("quixp1Death.wav");
  poPlayer[1].samSound = load_sample("quixp2Death.wav");
  poPlayer[2].samSound = load_sample("quixp3Death.wav");
  poPlayer[3].samSound = load_sample("quixp4Death.wav");
  poPlayer[0].setX(32);
  poPlayer[0].setY(32);
  poPlayer[0].setDir('l');
  poPlayer[1].setX(32);
  poPlayer[1].setY(544);
  poPlayer[1].setDir('l');
  poPlayer[2].setX(736);
  poPlayer[2].setY(544);
  poPlayer[2].setDir('r');
  poPlayer[3].setX(736);
  poPlayer[3].setY(32);
  poPlayer[3].setDir('r');

  int mouseDown[21];    //Kind of a crappy array --- Each button is a #
                        //and it's set to true if that button was clicked.
  for (int i = 0; i < 20; i++) { mouseDown[i] = false; }

  while ( !Menu.isDone() )
  {
    while (speed_counter > 0)
    {
      /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
      /* ~~~~~~~~~~~~~~~~~~~~~ MENU SCREEN ~~~~~~~~~~~~~~~~~~~~~ */
      /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
      if ( Menu.getEnabled() == true ) {
        if (key[KEY_Z]) {
          if (Menu.getFullscreen() == true) { Menu.changeScreenSize(0); Menu.setFullscreen(false); }
          else { Menu.changeScreenSize(1); Menu.setFullscreen(true); }
        }

        if (mouse_b & 1)
        {
          mouseDownClick(&Menu, mouseDown);
        }
        else {
          mouseUp(&Menu, mouseDown, poPlayer, &Level, song);
        }
      }
      /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
      /* ~~~~~~~~~~~~~~~~~~~~~~~ IN-GAME ~~~~~~~~~~~~~~~~~~~~~~~ */
      /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
      else {

        //Player Input1
        if (key[KEY_ESC]) {
            play_midi(NULL, false);
          if (Menu.fragLimitHit == true) {
            Menu.fragLimitHit == false;

            for (int i=0; i<4; i++) {
              poPlayer[i].resetScore();
              poPlayer[i].resetDeaths();
            }

            poPlayer[0].setX(32);
            poPlayer[0].setY(32);
            poPlayer[0].setDir('l');
            poPlayer[1].setX(32);
            poPlayer[1].setY(544);
            poPlayer[1].setDir('l');
            poPlayer[2].setX(736);
            poPlayer[2].setY(544);
            poPlayer[2].setDir('r');
            poPlayer[3].setX(736);
            poPlayer[3].setY(32);
            poPlayer[3].setDir('r');

            Menu.fragLimitHit = false;

            Menu.resetPressed = false;
            mouseDown[19] = false;

          }
          Level.setEnabled(false); Menu.setEnabled(true);
        }
        for (int i=0; i<4; i++) {
          if (poPlayer[i].getControlScheme() == 0) {
            if (key[KEY_W]) { moveCharacter(Level, &poPlayer[i], i, 'u'); }
            if (key[KEY_A]) { moveCharacter(Level, &poPlayer[i], i, 'l'); }
            if (key[KEY_S]) { moveCharacter(Level, &poPlayer[i], i, 'd'); }
            if (key[KEY_D]) { moveCharacter(Level, &poPlayer[i], i, 'r'); }
            if (key[KEY_F]) {
              if ( loLaser[i].getEnabled() == false ) { shootLaser( &loLaser[i], poPlayer[i]); }
            }
          }
          else if (poPlayer[i].getControlScheme() == 1) {
            if (key[KEY_I]) { moveCharacter(Level, &poPlayer[i], i, 'u'); }
            if (key[KEY_J]) { moveCharacter(Level, &poPlayer[i], i, 'l'); }
            if (key[KEY_K]) { moveCharacter(Level, &poPlayer[i], i, 'd'); }
            if (key[KEY_L]) { moveCharacter(Level, &poPlayer[i], i, 'r'); }
            if (key[KEY_H]) { if ( loLaser[i].getEnabled() == false ) { shootLaser( &loLaser[i], poPlayer[i]); } }
          }
          else if (poPlayer[i].getControlScheme() == 2) {
            if (key[KEY_UP]) { moveCharacter(Level, &poPlayer[i], i, 'u'); }
            if (key[KEY_LEFT]) { moveCharacter(Level, &poPlayer[i], i, 'l'); }
            if (key[KEY_DOWN]) { moveCharacter(Level, &poPlayer[i], i, 'd'); }
            if (key[KEY_RIGHT]) { moveCharacter(Level, &poPlayer[i], i, 'r'); }
            if (key[KEY_RCONTROL]) { if ( loLaser[i].getEnabled() == false ) { shootLaser( &loLaser[i], poPlayer[i]); } }
          }
          else if (poPlayer[i].getControlScheme() == 3) {
            if (key[KEY_8_PAD]) { moveCharacter(Level, &poPlayer[i], i, 'u'); }
            if (key[KEY_4_PAD]) { moveCharacter(Level, &poPlayer[i], i, 'l'); }
            if (key[KEY_2_PAD]) { moveCharacter(Level, &poPlayer[i], i, 'd'); }
            if (key[KEY_6_PAD]) { moveCharacter(Level, &poPlayer[i], i, 'r'); }
            if (key[KEY_PLUS_PAD]) { if ( loLaser[i].getEnabled() == false ) { shootLaser( &loLaser[i], poPlayer[i]); } }
          }
          else if(poPlayer[i].getControlScheme() == 4) {
            //Joystick #1
            poll_joystick();
            if (joy[0].stick[0].axis[1].d1) { moveCharacter(Level, &poPlayer[i], i, 'u'); } //Up
            if (joy[0].stick[0].axis[0].d1) { moveCharacter(Level, &poPlayer[i], i, 'l'); } //Left
            if (joy[0].stick[0].axis[1].d2) { moveCharacter(Level, &poPlayer[i], i, 'd'); } //Down
            if (joy[0].stick[0].axis[0].d2) { moveCharacter(Level, &poPlayer[i], i, 'r'); } //Right
            if (joy[0].button[0].b || joy[0].button[1].b || joy[0].button[2].b) { if ( loLaser[i].getEnabled() == false ) { shootLaser( &loLaser[i], poPlayer[i]); } }
          }
          else if(poPlayer[i].getControlScheme() == 5) {
            //Joystick #2
            poll_joystick();
            if (joy[1].stick[0].axis[1].d1) { moveCharacter(Level, &poPlayer[i], i, 'u'); } //Up
            if (joy[1].stick[0].axis[0].d1) { moveCharacter(Level, &poPlayer[i], i, 'l'); } //Left
            if (joy[1].stick[0].axis[1].d2) { moveCharacter(Level, &poPlayer[i], i, 'd'); } //Down
            if (joy[1].stick[0].axis[0].d2) {moveCharacter(Level, &poPlayer[i], i, 'r'); } //Right
            if (joy[1].button[0].b || joy[0].button[1].b || joy[0].button[2].b) { if ( loLaser[i].getEnabled() == false ) { shootLaser( &loLaser[i], poPlayer[i]); } }
          }
          else if(poPlayer[i].getControlScheme() == 6) {
            //Joystick #3
            poll_joystick();
            if (joy[2].stick[0].axis[1].d1) { moveCharacter(Level, &poPlayer[i], i, 'u'); } //Up
            if (joy[2].stick[0].axis[0].d1) { moveCharacter(Level, &poPlayer[i], i, 'l'); } //Left
            if (joy[2].stick[0].axis[1].d2) {moveCharacter(Level, &poPlayer[i], i, 'd'); } //Down
            if (joy[2].stick[0].axis[0].d2) { moveCharacter(Level, &poPlayer[i], i, 'r'); } //Right
            if (joy[2].button[0].b || joy[0].button[1].b || joy[0].button[2].b) { if ( loLaser[i].getEnabled() == false ) { shootLaser( &loLaser[i], poPlayer[i]); } }
          }
          else if(poPlayer[i].getControlScheme() == 7) {
            //Joystick #4
            poll_joystick();
            if (joy[3].stick[0].axis[1].d1) { moveCharacter(Level, &poPlayer[i], i, 'u'); } //Up
            if (joy[3].stick[0].axis[0].d1) { moveCharacter(Level, &poPlayer[i], i, 'l'); } //Left
            if (joy[3].stick[0].axis[1].d2) { moveCharacter(Level, &poPlayer[i], i, 'd'); } //Down
            if (joy[3].stick[0].axis[0].d2) { moveCharacter(Level, &poPlayer[i], i, 'r'); } //Right
            if (joy[3].button[0].b || joy[0].button[1].b || joy[0].button[2].b) { if ( loLaser[i].getEnabled() == false ) { shootLaser( &loLaser[i], poPlayer[i]); } }
          }
        }
        if (Level.timeForAPowerupTimer >= 60) { Level.timeForAPowerupTimer = 0; }
        else { Level.timeForAPowerupTimer++; }
      }
      if ( Level.getFrame() < 32 ) { Level.setFrame( Level.getFrame() + 1 ); }
      else { Level.setFrame(0); }

    //Score Bar
      if (Level.getFragLimit() != 0 && Level.getEnabled() == true) {
        scrollerX += 0.5;
        if (scrollerX >= 1200.0) { scrollerX = -150.0; }
      }
      for (int i=0; i<4; i++) {
        //Res circle
        if (poPlayer[i].getRespawnCounter() >= 0) {
          poPlayer[i].setRespawnCounter( poPlayer[i].getRespawnCounter() + 1);
        }
        //"Laser" movement
        if (loLaser[i].getEnabled() == true) {
          if (loLaser[i].getDir() == 'u') { loLaser[i].moveUp('l'); }
          else if (loLaser[i].getDir() == 'd') { loLaser[i].moveDown('l'); }
          else if (loLaser[i].getDir() == 'l') { loLaser[i].moveLeft('l'); }
          else if (loLaser[i].getDir() == 'r') { loLaser[i].moveRight('l'); }
          checkCollision(&loLaser[i], poPlayer, i, Level);
        }
        if ((poPlayer[i].returnScore() == Level.getFragLimit()) && (Level.getFragLimit() > 0)) {
          //Frag Limit hit
          Menu.fragLimitHit = true;
          winner = i;
        }
      }

      speed_counter--;
    }//while (speed_counter > 0)

    if ( Menu.getEnabled() == true ) {
      drawMenuStuff(buffer, Menu, titleimg, imgPlayers, Level);
    }
    else if (Menu.fragLimitHit == true) {
      //Show win window!
      floodfill  (buffer, 0, 0, makecol(0,0,0));
      textprintf(buffer,font,348,203,makecol(100,0,0), "Player %i Wins!", winner+1 );
      textprintf(buffer,font,347,202,makecol(150,0,0), "Player %i Wins!", winner+1 );
      textprintf(buffer,font,346,201,makecol(200,0,0), "Player %i Wins!", winner+1 );
      textprintf(buffer,font,345,200,makecol(255,0,0), "Player %i Wins!", winner+1 );

      textprintf(buffer,font,330,250,makecol(255,0,0), "Player 1 score: %i", poPlayer[0].returnScore() );
      textprintf(buffer,font,330,260,makecol(255,0,0), "Player 2 score: %i", poPlayer[1].returnScore() );
      textprintf(buffer,font,330,270,makecol(255,0,0), "Player 3 score: %i", poPlayer[2].returnScore() );
      textprintf(buffer,font,330,280,makecol(255,0,0), "Player 4 score: %i", poPlayer[3].returnScore() );

      textprintf(buffer,font,330,249,makecol(255,255,255), "Player 1 score: %i", poPlayer[0].returnScore() );
      textprintf(buffer,font,330,259,makecol(255,255,255), "Player 2 score: %i", poPlayer[1].returnScore() );
      textprintf(buffer,font,330,269,makecol(255,255,255), "Player 3 score: %i", poPlayer[2].returnScore() );
      textprintf(buffer,font,330,279,makecol(255,255,255), "Player 4 score: %i", poPlayer[3].returnScore() );

      textout_centre(buffer, font, "Hit esc to continue", 400, 300, makecol(255,255,255));
    }
    else {
      generateBackground(buffer, Level);
      drawCharacters(poPlayer, Level, buffer);
      drawScoreBar(buffer, poPlayer, scrollerX, scrollerY, Level);
      if (loLaser[0].getEnabled() == true) { drawLaser(loLaser[0], buffer, Level, 0); }
      if (loLaser[1].getEnabled() == true) { drawLaser(loLaser[1], buffer, Level, 1); }
      if (loLaser[2].getEnabled() == true) { drawLaser(loLaser[2], buffer, Level, 2); }
      if (loLaser[3].getEnabled() == true) { drawLaser(loLaser[3], buffer, Level, 3); }
    }


    acquire_screen();
    blit(buffer, screen, 0, 0, 0, 0, 800, 600);
    clear_bitmap(buffer);
    release_screen();
  }//while ( !Menu.isDone() )

    return 0;

  return 0;
}
Exemplo n.º 26
0
StaticFrameGui::StaticFrameGui(QWidget* parent): FrameGui(parent)
{

    setTitle("Static Frame");

    group = new QButtonGroup (this);
    grid = new QGridLayout (this);

    dewellSwitch = new QRadioButton (this);
    dewellSwitch->setText("Dewell (ms)");
    dewellSwitch->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
    repeatSwitch = new QRadioButton (this);
    repeatSwitch->setText("Repeat (frames)");
    repeatSwitch->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);

    group->addButton(dewellSwitch,1);
    group->addButton(repeatSwitch,2);

    grid->addWidget(dewellSwitch,2,0,1,1);
    grid->addWidget(repeatSwitch,3,0,1,1);

    QLabel * pointsLabel = new QLabel ("Points",this);
    pointsLabel->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
    pointsDisplay = new QLabel ("0",this);
    pointsDisplay->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
    grid->addWidget(pointsLabel,1,0,1,1);
    grid->addWidget(pointsDisplay,1,1,1,1);

    dewellEntry = new QSpinBox (this);
    dewellEntry->setMinimum (40);
    dewellEntry->setMaximum (600000);

    repeatEntry = new QSpinBox (this);
    repeatEntry->setMinimum (1);
    repeatEntry->setMaximum (1000);

    grid->addWidget(dewellEntry,2,1,1,1);
    grid->addWidget(repeatEntry,3,1,1,1);
    QLabel *l = new QLabel (this);
    l->setText("ArcBall");
    l->setFrameShape(QFrame::Panel);
    l->setFrameShadow(QFrame::Raised);
    l->setAlignment(Qt::AlignHCenter);
    arcball = new ArcBall(this);
    connect (arcball,SIGNAL(angleChanged(QQuaternion)),this,SLOT(angleChangedData(QQuaternion)));
    connect (arcball,SIGNAL(mouseDown()),this,SLOT(arcballDown()));
    connect (arcball,SIGNAL(mouseUp()),this,SLOT(arcballUp()));
    grid->addWidget(l,4,0);
    grid->addWidget(arcball,5,0);
    l = new QLabel (this);
    l->setText ("Size");
    l->setFrameShape(QFrame::Panel);
    l->setFrameShadow(QFrame::Raised);
    l->setAlignment(Qt::AlignHCenter);
    grid->addWidget(l,4,1);
    size = new QSlider(Qt::Vertical,this);
    size->setRange(-200,100);
    size->setSliderPosition(0);
    grid->addWidget(size,5,1);
    setLayout(grid);
}
Exemplo n.º 27
0
ServerProxy::EResult
ServerProxy::parseMessage(const UInt8* code)
{
	if (memcmp(code, kMsgDMouseMove, 4) == 0) {
		mouseMove();
	}

	else if (memcmp(code, kMsgDMouseRelMove, 4) == 0) {
		mouseRelativeMove();
	}

	else if (memcmp(code, kMsgDMouseWheel, 4) == 0) {
		mouseWheel();
	}

	else if (memcmp(code, kMsgDKeyDown, 4) == 0) {
		keyDown();
	}

	else if (memcmp(code, kMsgDKeyUp, 4) == 0) {
		keyUp();
	}

	else if (memcmp(code, kMsgDMouseDown, 4) == 0) {
		mouseDown();
	}

	else if (memcmp(code, kMsgDMouseUp, 4) == 0) {
		mouseUp();
	}

	else if (memcmp(code, kMsgDKeyRepeat, 4) == 0) {
		keyRepeat();
	}

	else if (memcmp(code, kMsgCKeepAlive, 4) == 0) {
		// echo keep alives and reset alarm
		ProtocolUtil::writef(m_stream, kMsgCKeepAlive);
		resetKeepAliveAlarm();
	}

	else if (memcmp(code, kMsgCNoop, 4) == 0) {
		// accept and discard no-op
	}

	else if (memcmp(code, kMsgCEnter, 4) == 0) {
		enter();
	}

	else if (memcmp(code, kMsgCLeave, 4) == 0) {
		leave();
	}

	else if (memcmp(code, kMsgCClipboard, 4) == 0) {
		grabClipboard();
	}

	else if (memcmp(code, kMsgCScreenSaver, 4) == 0) {
		screensaver();
	}

	else if (memcmp(code, kMsgQInfo, 4) == 0) {
		queryInfo();
	}

	else if (memcmp(code, kMsgCInfoAck, 4) == 0) {
		infoAcknowledgment();
	}

	else if (memcmp(code, kMsgDClipboard, 4) == 0) {
		setClipboard();
	}

	else if (memcmp(code, kMsgCResetOptions, 4) == 0) {
		resetOptions();
	}

	else if (memcmp(code, kMsgDSetOptions, 4) == 0) {
		setOptions();
	}

	else if (memcmp(code, kMsgDFileTransfer, 4) == 0) {
		fileChunkReceived();
	}
	else if (memcmp(code, kMsgDDragInfo, 4) == 0) {
		dragInfoReceived();
	}

	else if (memcmp(code, kMsgCClose, 4) == 0) {
		// server wants us to hangup
		LOG((CLOG_DEBUG1 "recv close"));
		m_client->disconnect(NULL);
		return kDisconnect;
	}
	else if (memcmp(code, kMsgEBad, 4) == 0) {
		LOG((CLOG_ERR "server disconnected due to a protocol error"));
		m_client->disconnect("server reported a protocol error");
		return kDisconnect;
	}
	else {
		return kUnknown;
	}

	// send a reply.  this is intended to work around a delay when
	// running a linux server and an OS X (any BSD?) client.  the
	// client waits to send an ACK (if the system control flag
	// net.inet.tcp.delayed_ack is 1) in hopes of piggybacking it
	// on a data packet.  we provide that packet here.  i don't
	// know why a delayed ACK should cause the server to wait since
	// TCP_NODELAY is enabled.
	ProtocolUtil::writef(m_stream, kMsgCNoop);

	return kOkay;
}
void MediaPluginGStreamer010::receiveMessage(const char *message_string)
{
	//std::cerr << "MediaPluginGStreamer010::receiveMessage: received message: \"" << message_string << "\"" << std::endl;

	LLPluginMessage message_in;

	if(message_in.parse(message_string) >= 0)
	{
		std::string message_class = message_in.getClass();
		std::string message_name = message_in.getName();
		if(message_class == LLPLUGIN_MESSAGE_CLASS_BASE)
		{
			if(message_name == "init")
			{
				LLPluginMessage message("base", "init_response");
				LLSD versions = LLSD::emptyMap();
				versions[LLPLUGIN_MESSAGE_CLASS_BASE] = LLPLUGIN_MESSAGE_CLASS_BASE_VERSION;
				versions[LLPLUGIN_MESSAGE_CLASS_MEDIA] = LLPLUGIN_MESSAGE_CLASS_MEDIA_VERSION;
				versions[LLPLUGIN_MESSAGE_CLASS_MEDIA_TIME] = LLPLUGIN_MESSAGE_CLASS_MEDIA_TIME_VERSION;
				message.setValueLLSD("versions", versions);

				if ( load() )
				{
					DEBUGMSG("GStreamer010 media instance set up");
				}
				else
				{
					WARNMSG("GStreamer010 media instance failed to set up");
				}

				message.setValue("plugin_version", getVersion());
				sendMessage(message);
			}
			else if(message_name == "idle")
			{
				// no response is necessary here.
				double time = message_in.getValueReal("time");
				
				// Convert time to milliseconds for update()
				update((int)(time * 1000.0f));
			}
			else if(message_name == "cleanup")
			{
				unload();
				closedown();
			}
			else if(message_name == "shm_added")
			{
				SharedSegmentInfo info;
				info.mAddress = message_in.getValuePointer("address");
				info.mSize = (size_t)message_in.getValueS32("size");
				std::string name = message_in.getValue("name");

				std::ostringstream str;
				INFOMSG("MediaPluginGStreamer010::receiveMessage: shared memory added, name: %s, size: %d, address: %p", name.c_str(), int(info.mSize), info.mAddress);

				mSharedSegments.insert(SharedSegmentMap::value_type(name, info));
			}
			else if(message_name == "shm_remove")
			{
				std::string name = message_in.getValue("name");

				DEBUGMSG("MediaPluginGStreamer010::receiveMessage: shared memory remove, name = %s", name.c_str());
				
				SharedSegmentMap::iterator iter = mSharedSegments.find(name);
				if(iter != mSharedSegments.end())
				{
					if(mPixels == iter->second.mAddress)
					{
						// This is the currently active pixel buffer.  Make sure we stop drawing to it.
						mPixels = NULL;
						mTextureSegmentName.clear();
						
						// Make sure the movie decoder is no longer pointed at the shared segment.
						sizeChanged();						
					}
					mSharedSegments.erase(iter);
				}
				else
				{
					WARNMSG("MediaPluginGStreamer010::receiveMessage: unknown shared memory region!");
				}

				// Send the response so it can be cleaned up.
				LLPluginMessage message("base", "shm_remove_response");
				message.setValue("name", name);
				sendMessage(message);
			}
			else
			{
				std::ostringstream str;
				INFOMSG("MediaPluginGStreamer010::receiveMessage: unknown base message: %s", message_name.c_str());
			}
		}
		else if(message_class == LLPLUGIN_MESSAGE_CLASS_MEDIA)
		{
			if(message_name == "init")
			{
				// Plugin gets to decide the texture parameters to use.
				LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_MEDIA, "texture_params");
				// lame to have to decide this now, it depends on the movie.  Oh well.
				mDepth = 4;

				mCurrentWidth = 1;
				mCurrentHeight = 1;
				mPreviousWidth = 1;
				mPreviousHeight = 1;
				mNaturalWidth = 1;
				mNaturalHeight = 1;
				mWidth = 1;
				mHeight = 1;
				mTextureWidth = 1;
				mTextureHeight = 1;

				message.setValueU32("format", GL_RGBA);
				message.setValueU32("type", GL_UNSIGNED_INT_8_8_8_8_REV);

				message.setValueS32("depth", mDepth);
				message.setValueS32("default_width", mWidth);
				message.setValueS32("default_height", mHeight);
				message.setValueU32("internalformat", GL_RGBA8);
				message.setValueBoolean("coords_opengl", true);	// true == use OpenGL-style coordinates, false == (0,0) is upper left.
				message.setValueBoolean("allow_downsample", true); // we respond with grace and performance if asked to downscale
				sendMessage(message);
			}
			else if(message_name == "size_change")
			{
				std::string name = message_in.getValue("name");
				S32 width = message_in.getValueS32("width");
				S32 height = message_in.getValueS32("height");
				S32 texture_width = message_in.getValueS32("texture_width");
				S32 texture_height = message_in.getValueS32("texture_height");

				std::ostringstream str;
				INFOMSG("---->Got size change instruction from application with shm name: %s - size is %d x %d", name.c_str(), width, height);

				LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_MEDIA, "size_change_response");
				message.setValue("name", name);
				message.setValueS32("width", width);
				message.setValueS32("height", height);
				message.setValueS32("texture_width", texture_width);
				message.setValueS32("texture_height", texture_height);
				sendMessage(message);

				if(!name.empty())
				{
					// Find the shared memory region with this name
					SharedSegmentMap::iterator iter = mSharedSegments.find(name);
					if(iter != mSharedSegments.end())
					{
						INFOMSG("*** Got size change with matching shm, new size is %d x %d", width, height);
						INFOMSG("*** Got size change with matching shm, texture size size is %d x %d", texture_width, texture_height);

						mPixels = (unsigned char*)iter->second.mAddress;
						mTextureSegmentName = name;
						mWidth = width;
						mHeight = height;

						if (texture_width > 1 ||
						    texture_height > 1) // not a dummy size from the app, a real explicit forced size
						{
							INFOMSG("**** = REAL RESIZE REQUEST FROM APP");
							
							GST_OBJECT_LOCK(mVideoSink);
							mVideoSink->resize_forced_always = true;
							mVideoSink->resize_try_width = texture_width;
							mVideoSink->resize_try_height = texture_height;
							GST_OBJECT_UNLOCK(mVideoSink);
 						}

						mTextureWidth = texture_width;
						mTextureHeight = texture_height;
					}
				}
			}
			else if(message_name == "load_uri")
			{
				std::string uri = message_in.getValue("uri");
				navigateTo( uri );
				sendStatus();		
			}
			else if(message_name == "mouse_event")
			{
				std::string event = message_in.getValue("event");
				S32 x = message_in.getValueS32("x");
				S32 y = message_in.getValueS32("y");
				
				if(event == "down")
				{
					mouseDown(x, y);
				}
				else if(event == "up")
				{
					mouseUp(x, y);
				}
				else if(event == "move")
				{
					mouseMove(x, y);
				};
			};
		}
		else if(message_class == LLPLUGIN_MESSAGE_CLASS_MEDIA_TIME)
		{
			if(message_name == "stop")
			{
				stop();
			}
			else if(message_name == "start")
			{
				double rate = 0.0;
				if(message_in.hasValue("rate"))
				{
					rate = message_in.getValueReal("rate");
				}
				// NOTE: we don't actually support rate.
				play(rate);
			}
			else if(message_name == "pause")
			{
				pause();
			}
			else if(message_name == "seek")
			{
				double time = message_in.getValueReal("time");
				// defer the actual seek in case we haven't
				// really truly started yet in which case there
				// is nothing to seek upon
				mSeekWanted = true;
				mSeekDestination = time;
			}
			else if(message_name == "set_loop")
			{
				bool loop = message_in.getValueBoolean("loop");
				mIsLooping = loop;
			}
			else if(message_name == "set_volume")
			{
				double volume = message_in.getValueReal("volume");
				setVolume(volume);
			}
		}
		else
		{
			INFOMSG("MediaPluginGStreamer010::receiveMessage: unknown message class: %s", message_class.c_str());
		}
	}
}
Exemplo n.º 29
0
 void mouseReleaseEvent(QMouseEvent*)
 {
     mouseUp();
 }
Exemplo n.º 30
0
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_CREATE:
		break;
	case WM_PAINT:

		hdc = BeginPaint(hWnd, &ps);

		{
			RECT cr;
			GetClientRect(hWnd, &cr);

			int width = cr.right - cr.left;
			int height = cr.bottom - cr.top;

			HDC bufDC;
			HBITMAP bufBMP;

			bufDC = CreateCompatibleDC(hdc);
			bufBMP = CreateCompatibleBitmap(hdc, width, height);
			SelectObject(bufDC, bufBMP);

			setPaintDC(bufDC);

			RECT r = {0};
			r.right = width;
			r.bottom = height;

			FillRect(bufDC, &r, GetStockBrush(WHITE_BRUSH));

			paint();

			setPaintDC(NULL);

			BitBlt(hdc, 0, 0, width, height, bufDC, 0, 0, SRCCOPY);

			DeleteObject(bufBMP);
			DeleteDC(bufDC);
		}

		EndPaint(hWnd, &ps);
		break;
	
	case WM_MOUSEMOVE:
		{
			int x = GET_X_LPARAM(lParam); 
			int y = GET_Y_LPARAM(lParam);

			mouseMove(x, y);
		}
	break;
	
	case WM_LBUTTONDOWN:
		SetCapture(hWnd);
		mouseDown();
	break;

	case WM_LBUTTONUP:
		ReleaseCapture();
		mouseUp();
	break;

	case WM_KEYDOWN:
		{
			int vk = wParam;
			char ch = MapVirtualKey(vk, MAPVK_VK_TO_CHAR);

			keyDown(ch, vk);
		}

		break;
	
	case WM_KEYUP:
		{
			int vk = wParam;
			char ch = MapVirtualKey(vk, MAPVK_VK_TO_CHAR);

			keyUp(ch, vk);
		}

		break;

	case WM_TIMER:
		switch(wParam)
		{
		case IDT_TIMER0:
			timerTick();
			break;
		}
		
		break;

	case WM_DESTROY:
		finalize();

		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}