openMSX
Joystick.cc
Go to the documentation of this file.
1 #include "Joystick.hh"
2 #include "PluggingController.hh"
3 #include "PlugException.hh"
4 #include "MSXEventDistributor.hh"
6 #include "InputEvents.hh"
7 #include "InputEventGenerator.hh"
8 #include "StateChange.hh"
9 #include "TclObject.hh"
10 #include "GlobalSettings.hh"
11 #include "IntegerSetting.hh"
12 #include "CommandController.hh"
13 #include "CommandException.hh"
14 #include "serialize.hh"
15 #include "serialize_meta.hh"
16 #include "xrange.hh"
17 #include <memory>
18 
19 using std::string;
20 using std::shared_ptr;
21 
22 namespace openmsx {
23 
25  StateChangeDistributor& stateChangeDistributor,
26  CommandController& commandController,
27  GlobalSettings& globalSettings,
28  PluggingController& controller)
29 {
30 #ifdef SDL_JOYSTICK_DISABLED
31  (void)eventDistributor;
32  (void)stateChangeDistributor;
33  (void)controller;
34 #else
35  unsigned numJoysticks = SDL_NumJoysticks();
36  ad_printf("#joysticks: %d\n", numJoysticks);
37  for (unsigned i = 0; i < numJoysticks; i++) {
38  SDL_Joystick* joystick = SDL_JoystickOpen(i);
39  if (joystick) {
40  // Avoid devices that have axes but no buttons, like accelerometers.
41  // SDL 1.2.14 in Linux has an issue where it rejects a device from
42  // /dev/input/event* if it has no buttons but does not reject a
43  // device from /dev/input/js* if it has no buttons, while
44  // accelerometers do end up being symlinked as a joystick in
45  // practice.
46  if (InputEventGenerator::joystickNumButtons(joystick) != 0) {
47  controller.registerPluggable(
48  std::make_unique<Joystick>(
49  eventDistributor,
50  stateChangeDistributor,
51  commandController,
52  globalSettings,
53  joystick));
54  }
55  }
56  }
57 #endif
58 }
59 
60 
61 class JoyState final : public StateChange
62 {
63 public:
64  JoyState() = default; // for serialize
65  JoyState(EmuTime::param time_, unsigned joyNum_, byte press_, byte release_)
66  : StateChange(time_)
67  , joyNum(joyNum_), press(press_), release(release_)
68  {
69  assert((press != 0) || (release != 0));
70  assert((press & release) == 0);
71  }
72  unsigned getJoystick() const { return joyNum; }
73  byte getPress() const { return press; }
74  byte getRelease() const { return release; }
75 
76  template<typename Archive> void serialize(Archive& ar, unsigned /*version*/)
77  {
78  ar.template serializeBase<StateChange>(*this);
79  ar.serialize("joyNum", joyNum);
80  ar.serialize("press", press);
81  ar.serialize("release", release);
82  }
83 private:
84  unsigned joyNum;
85  byte press, release;
86 };
88 
89 
90 #ifndef SDL_JOYSTICK_DISABLED
91 static void checkJoystickConfig(Interpreter& interp, TclObject& newValue)
92 {
93  unsigned n = newValue.getListLength(interp);
94  if (n & 1) {
95  throw CommandException("Need an even number of elements");
96  }
97  for (unsigned i = 0; i < n; i += 2) {
98  string_view key = newValue.getListIndex(interp, i + 0).getString();
99  TclObject value = newValue.getListIndex(interp, i + 1);
100  if ((key != "A" ) && (key != "B" ) &&
101  (key != "LEFT") && (key != "RIGHT") &&
102  (key != "UP" ) && (key != "DOWN" )) {
103  throw CommandException(
104  "Invalid MSX joystick action: must be one of "
105  "'A', 'B', 'LEFT', 'RIGHT', 'UP', 'DOWN'.");
106  }
107  for (auto j : xrange(value.getListLength(interp))) {
108  string_view host = value.getListIndex(interp, j).getString();
109  if (!host.starts_with("button") &&
110  !host.starts_with("+axis") &&
111  !host.starts_with("-axis") &&
112  !host.starts_with("L_hat") &&
113  !host.starts_with("R_hat") &&
114  !host.starts_with("U_hat") &&
115  !host.starts_with("D_hat")) {
116  throw CommandException(
117  "Invalid host joystick action: must be "
118  "one of 'button<N>', '+axis<N>', '-axis<N>', "
119  "'L_hat<N>', 'R_hat<N>', 'U_hat<N>', 'D_hat<N>'");
120  }
121  }
122  }
123 }
124 
125 static string getJoystickName(unsigned joyNum)
126 {
127  return strCat("joystick", char('1' + joyNum));
128 }
129 
130 static TclObject getConfigValue(SDL_Joystick* joystick)
131 {
132  TclObject listA, listB;
133  for (auto i : xrange(InputEventGenerator::joystickNumButtons(joystick))) {
134  string button = strCat("button", i);
135  if (i & 1) {
136  listB.addListElement(button);
137  } else {
138  listA.addListElement(button);
139  }
140  }
141  TclObject value;
142  value.addDictKeyValues("LEFT", "-axis0",
143  "RIGHT", "+axis0",
144  "UP", "-axis1",
145  "DOWN", "+axis1",
146  "A", listA,
147  "B", listB);
148  return value;
149 }
150 
151 // Note: It's OK to open/close the same SDL_Joystick multiple times (we open it
152 // once per MSX machine). The SDL documentation doesn't state this, but I
153 // checked the implementation and a SDL_Joystick uses a 'reference count' on
154 // the open/close calls.
156  StateChangeDistributor& stateChangeDistributor_,
157  CommandController& commandController,
158  GlobalSettings& globalSettings,
159  SDL_Joystick* joystick_)
160  : eventDistributor(eventDistributor_)
161  , stateChangeDistributor(stateChangeDistributor_)
162  , joystick(joystick_)
163  , joyNum(SDL_JoystickInstanceID(joystick_))
164  , deadSetting(globalSettings.getJoyDeadzoneSetting(joyNum))
165  , name(getJoystickName(joyNum))
166  , desc(string(SDL_JoystickName(joystick_)))
167  , configSetting(commandController, name + "_config",
168  "joystick configuration", getConfigValue(joystick).getString())
169 {
170  auto& interp = commandController.getInterpreter();
171  configSetting.setChecker([&interp](TclObject& newValue) {
172  checkJoystickConfig(interp, newValue); });
173 
174  pin8 = false; // avoid UMR
175 }
176 
178 {
179  if (isPluggedIn()) {
180  Joystick::unplugHelper(EmuTime::dummy());
181  }
182  if (joystick) {
183  SDL_JoystickClose(joystick);
184  }
185 }
186 
187 // Pluggable
188 const string& Joystick::getName() const
189 {
190  return name;
191 }
192 
194 {
195  return desc;
196 }
197 
198 void Joystick::plugHelper(Connector& /*connector*/, EmuTime::param /*time*/)
199 {
200  if (!joystick) {
201  throw PlugException("Failed to open joystick device");
202  }
203  plugHelper2();
204  status = calcState();
205 }
206 
207 void Joystick::plugHelper2()
208 {
209  eventDistributor.registerEventListener(*this);
210  stateChangeDistributor.registerListener(*this);
211 }
212 
213 void Joystick::unplugHelper(EmuTime::param /*time*/)
214 {
215  stateChangeDistributor.unregisterListener(*this);
216  eventDistributor.unregisterEventListener(*this);
217 }
218 
219 
220 // JoystickDevice
221 byte Joystick::read(EmuTime::param /*time*/)
222 {
223  return pin8 ? 0x3F : status;
224 }
225 
226 void Joystick::write(byte value, EmuTime::param /*time*/)
227 {
228  pin8 = (value & 0x04) != 0;
229 }
230 
231 byte Joystick::calcState()
232 {
233  byte result = JOY_UP | JOY_DOWN | JOY_LEFT | JOY_RIGHT |
235  if (joystick) {
236  int threshold = (deadSetting.getInt() * 32768) / 100;
237  auto& interp = configSetting.getInterpreter();
238  auto& dict = configSetting.getValue();
239  if (getState(interp, dict, "A" , threshold)) result &= ~JOY_BUTTONA;
240  if (getState(interp, dict, "B" , threshold)) result &= ~JOY_BUTTONB;
241  if (getState(interp, dict, "UP" , threshold)) result &= ~JOY_UP;
242  if (getState(interp, dict, "DOWN" , threshold)) result &= ~JOY_DOWN;
243  if (getState(interp, dict, "LEFT" , threshold)) result &= ~JOY_LEFT;
244  if (getState(interp, dict, "RIGHT", threshold)) result &= ~JOY_RIGHT;
245  }
246  return result;
247 }
248 
249 bool Joystick::getState(Interpreter& interp, const TclObject& dict,
250  string_view key, int threshold)
251 {
252  try {
253  const auto& list = dict.getDictValue(interp, key);
254  for (auto i : xrange(list.getListLength(interp))) {
255  const auto& elem = list.getListIndex(interp, i).getString();
256  if (elem.starts_with("button")) {
257  unsigned n = fast_stou(elem.substr(6));
258  if (InputEventGenerator::joystickGetButton(joystick, n)) {
259  return true;
260  }
261  } else if (elem.starts_with("+axis")) {
262  unsigned n = fast_stou(elem.substr(5));
263  if (SDL_JoystickGetAxis(joystick, n) > threshold) {
264  return true;
265  }
266  } else if (elem.starts_with("-axis")) {
267  unsigned n = fast_stou(elem.substr(5));
268  if (SDL_JoystickGetAxis(joystick, n) < -threshold) {
269  return true;
270  }
271  } else if (elem. starts_with("L_hat")) {
272  unsigned n = fast_stou(elem.substr(5));
273  if (SDL_JoystickGetHat(joystick, n) & SDL_HAT_LEFT) {
274  return true;
275  }
276  } else if (elem.starts_with("R_hat")) {
277  unsigned n = fast_stou(elem.substr(5));
278  if (SDL_JoystickGetHat(joystick, n) & SDL_HAT_RIGHT) {
279  return true;
280  }
281  } else if (elem.starts_with("U_hat")) {
282  unsigned n = fast_stou(elem.substr(5));
283  if (SDL_JoystickGetHat(joystick, n) & SDL_HAT_UP) {
284  return true;
285  }
286  } else if (elem.starts_with("D_hat")) {
287  unsigned n = fast_stou(elem.substr(5));
288  if (SDL_JoystickGetHat(joystick, n) & SDL_HAT_DOWN) {
289  return true;
290  }
291  }
292  }
293  } catch (...) {
294  // Error, in getListLength()/getListIndex() or in fast_stou().
295  // In either case we can't do anything about it here, so ignore.
296  }
297  return false;
298 }
299 
300 // MSXEventListener
301 void Joystick::signalMSXEvent(const shared_ptr<const Event>& event,
302  EmuTime::param time)
303 {
304  auto joyEvent = dynamic_cast<const JoystickEvent*>(event.get());
305  if (!joyEvent) return;
306 
307  // TODO: It would be more efficient to make a dispatcher instead of
308  // sending the event to all joysticks.
309  if (joyEvent->getJoystick() != joyNum) return;
310 
311  // TODO: Currently this recalculates the whole joystick state. It might
312  // be possible to implement this more efficiently by using the specific
313  // event information. Though that's not trivial because e.g. multiple
314  // host buttons can map to the same MSX button. Also calcState()
315  // involves some string processing. It might be possible to only parse
316  // the config once (per setting change). Though this solution is likely
317  // good enough.
318  createEvent(time, calcState());
319 }
320 
321 void Joystick::createEvent(EmuTime::param time, byte newStatus)
322 {
323  byte diff = status ^ newStatus;
324  if (!diff) {
325  // event won't actually change the status, so ignore it
326  return;
327  }
328  // make sure we create an event with minimal changes
329  byte press = status & diff;
330  byte release = newStatus & diff;
331  stateChangeDistributor.distributeNew(std::make_shared<JoyState>(
332  time, joyNum, press, release));
333 }
334 
335 // StateChangeListener
336 void Joystick::signalStateChange(const shared_ptr<StateChange>& event)
337 {
338  auto js = dynamic_cast<const JoyState*>(event.get());
339  if (!js) return;
340 
341  // TODO: It would be more efficient to make a dispatcher instead of
342  // sending the event to all joysticks.
343  // TODO an alternative is to log events based on the connector instead
344  // of the joystick. That would make it possible to replay on a
345  // different host without an actual SDL joystick connected.
346  if (js->getJoystick() != joyNum) return;
347 
348  status = (status & ~js->getPress()) | js->getRelease();
349 }
350 
351 void Joystick::stopReplay(EmuTime::param time)
352 {
353  createEvent(time, calcState());
354 }
355 
356 // version 1: Initial version, the variable status was not serialized.
357 // version 2: Also serialize the above variable, this is required for
358 // record/replay, see comment in Keyboard.cc for more details.
359 template<typename Archive>
360 void Joystick::serialize(Archive& ar, unsigned version)
361 {
362  if (ar.versionAtLeast(version, 2)) {
363  ar.serialize("status", status);
364  }
365  if (ar.isLoader()) {
366  if (joystick && isPluggedIn()) {
367  plugHelper2();
368  }
369  }
370  // no need to serialize 'pin8' it's automatically restored via write()
371 }
374 
375 #endif // SDL_JOYSTICK_DISABLED
376 
377 } // namespace openmsx
static const int JOY_LEFT
void setChecker(std::function< void(TclObject &)> checkFunc_)
Set value-check-callback.
Definition: Setting.hh:151
static const int JOY_UP
REGISTER_POLYMORPHIC_INITIALIZER(Pluggable, CassettePlayer, "CassettePlayer")
void serialize(Archive &ar, unsigned)
Definition: Joystick.cc:76
bool starts_with(string_view x) const
Definition: string_view.cc:116
Represents something you can plug devices into.
Definition: Connector.hh:20
static const int JOY_BUTTONB
auto xrange(T e)
Definition: xrange.hh:170
bool isPluggedIn() const
Returns true if this pluggable is currently plugged into a connector.
Definition: Pluggable.hh:49
void unregisterListener(StateChangeListener &listener)
uint8_t byte
8 bit unsigned integer
Definition: openmsx.hh:26
void registerEventListener(MSXEventListener &listener)
Registers a given object to receive certain events.
string_view getString() const
Definition: TclObject.cc:102
unsigned getListLength(Interpreter &interp) const
Definition: TclObject.cc:116
Central administration of Connectors and Pluggables.
void distributeNew(const EventPtr &event)
Deliver the event to all registered listeners MSX input devices should call the distributeNew() versi...
byte read(EmuTime::param time) override
Read from the joystick device.
Definition: Joystick.cc:221
void registerListener(StateChangeListener &listener)
(Un)registers the given object to receive state change events.
void write(byte value, EmuTime::param time) override
Write a value to the joystick device.
Definition: Joystick.cc:226
static int joystickNumButtons(SDL_Joystick *joystick)
Normally the following two functions simply delegate to SDL_JoystickNumButtons() and SDL_JoystickGetB...
Joystick(MSXEventDistributor &eventDistributor, StateChangeDistributor &stateChangeDistributor, CommandController &commandController, GlobalSettings &globalSettings, SDL_Joystick *joystick)
Definition: Joystick.cc:155
const TclObject & getValue() const final override
Gets the current value of this setting as a TclObject.
Definition: Setting.hh:134
Uses an SDL joystick to emulate an MSX joystick.
Definition: Joystick.hh:24
void unregisterEventListener(MSXEventListener &listener)
Unregisters a previously registered event listener.
virtual Interpreter & getInterpreter()=0
~Joystick() override
Definition: Joystick.cc:177
JoyState(EmuTime::param time_, unsigned joyNum_, byte press_, byte release_)
Definition: Joystick.cc:65
string_view getDescription() const override
Description for this pluggable.
Definition: Joystick.cc:193
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:5
TclObject getListIndex(Interpreter &interp, unsigned index) const
Definition: TclObject.cc:134
TclObject getDictValue(Interpreter &interp, const TclObject &key) const
Definition: TclObject.cc:152
void plugHelper(Connector &connector, EmuTime::param time) override
Definition: Joystick.cc:198
static const int JOY_DOWN
const std::string & getName() const override
Name used to identify this pluggable.
Definition: Joystick.cc:188
void registerPluggable(std::unique_ptr< Pluggable > pluggable)
Add a Pluggable to the registry.
This class implements a (close approximation) of the std::string_view class.
Definition: string_view.hh:16
static const int JOY_BUTTONA
void addListElement(T t)
Definition: TclObject.hh:121
#define INSTANTIATE_SERIALIZE_METHODS(CLASS)
Definition: serialize.hh:840
void addDictKeyValues(Args &&... args)
Definition: TclObject.hh:138
Base class for all external MSX state changing events.
Definition: StateChange.hh:13
static bool joystickGetButton(SDL_Joystick *joystick, int button)
byte getPress() const
Definition: Joystick.cc:73
Interpreter & getInterpreter() const
Definition: Setting.cc:161
std::string strCat(Ts &&...ts)
Definition: strCat.hh:577
static void registerAll(MSXEventDistributor &eventDistributor, StateChangeDistributor &stateChangeDistributor, CommandController &commandController, GlobalSettings &globalSettings, PluggingController &controller)
Register all available SDL joysticks.
Definition: Joystick.cc:24
Thrown when a plug action fails.
REGISTER_POLYMORPHIC_CLASS(DiskContainer, NowindRomDisk, "NowindRomDisk")
This class contains settings that are used by several other class (including some singletons)...
byte getRelease() const
Definition: Joystick.cc:74
unsigned fast_stou(string_view s)
Definition: string_view.cc:145
unsigned getJoystick() const
Definition: Joystick.cc:72
void serialize(Archive &ar, unsigned version)
Definition: Joystick.cc:360
#define ad_printf(...)
Definition: openmsx.hh:11
static const int JOY_RIGHT
void unplugHelper(EmuTime::param time) override
Definition: Joystick.cc:213