(******************************************************************************)
(*                                                                            *)
(* SDL Joystick wrapper by Corpsman                                2020.04.21 *)
(*                                                                            *)
(* Version: 0.01                                                              *)
(* History: 0.01 : Initialversion                                             *)
(******************************************************************************)
Unit usdl_joystick;

{$MODE objfpc}{$H+}

Interface

Uses
  Classes, SysUtils, sdl2;

Type

  { TSDL_Joystick }

  TSDL_Joystick = Class
  private
    fAxisCount: integer;
    fButtonCount: integer;
    fInstance: Pointer;
    Function GetAxisValue(index: integer): integer;
  public
    Property AxisCount: integer read fAxisCount;
    Property Axis[index: integer]: integer read GetAxisValue; // ranging from -32768 to 32767

    Constructor Create(Index: integer);
    Destructor Destroy; override;
  End;

Implementation

{ TSDL_Joystick }

Function TSDL_Joystick.GetAxisValue(index: integer): integer;
Begin
  result := SDL_JoystickGetAxis(fInstance, index);
End;

Constructor TSDL_Joystick.Create(Index: integer);
Begin
  Inherited create;
  If (SDL_WasInit(SDL_INIT_JOYSTICK) and SDL_INIT_JOYSTICK) = 0 Then Begin
    Raise Exception.create('Error SDL subsystem for joystick is not initialized.');
  End;
  SDL_JoystickEventState(SDL_ENABLE);
  fInstance := SDL_JoystickOpen(Index);
  If Not assigned(fInstance) Then Begin
    Raise Exception.create('Error could not create joystick instance.');
  End;
  fAxisCount := SDL_JoystickNumAxes(fInstance);
  fButtonCount := SDL_JoystickNumButtons(fInstance);
End;

Destructor TSDL_Joystick.Destroy;
Begin
  If assigned(fInstance) Then Begin
    SDL_JoystickClose(fInstance);
    fInstance := Nil;
  End;
End;

End.

