LinuxForceFeedback.cpp 17 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
The zlib/libpng License

Copyright (c) 2005-2007 Phillip Castaneda (pjcast -- www.wreckedgames.com)

This software is provided 'as-is', without any express or implied warranty. In no event will
the authors be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial
applications, and to alter it and redistribute it freely, subject to the following
restrictions:

    1. The origin of this software must not be misrepresented; you must not claim that
		you wrote the original software. If you use this software in a product,
		an acknowledgment in the product documentation would be appreciated but is
		not required.

    2. Altered source versions must be plainly marked as such, and must not be
		misrepresented as being the original software.

    3. This notice may not be removed or altered from any source distribution.
*/
#include "linux/LinuxForceFeedback.h"
#include "OISException.h"

#include <cstdlib>
#include <errno.h>
#include <memory.h>

using namespace OIS;

// 0 = No trace; 1 = Important traces; 2 = Debug traces
#define OIS_LINUX_JOYFF_DEBUG 1

#ifdef OIS_LINUX_JOYFF_DEBUG
# include <iostream>
  using namespace std;
#endif

//--------------------------------------------------------------//
LinuxForceFeedback::LinuxForceFeedback(int deviceID) :
	ForceFeedback(), mJoyStick(deviceID)
{
}

//--------------------------------------------------------------//
LinuxForceFeedback::~LinuxForceFeedback()
{
	// Unload all effects.
	for(EffectList::iterator i = mEffectList.begin(); i != mEffectList.end(); ++i )
	{
		struct ff_effect *linEffect = i->second;
		if( linEffect )
			_unload(linEffect->id);
	}

	mEffectList.clear();
}

//--------------------------------------------------------------//
unsigned short LinuxForceFeedback::getFFMemoryLoad()
{
	int nEffects = -1;
	if (ioctl(mJoyStick, EVIOCGEFFECTS, &nEffects) == -1)
		OIS_EXCEPT(E_General, "Unknown error reading max number of uploaded effects.");
#if (OIS_LINUX_JOYFF_DEBUG > 1)
Ben Hymers's avatar
Ben Hymers committed
67
	cout << "LinuxForceFeedback("<< mJoyStick
68
69
70
71
72
73
74
75
76
77
78
79
		 << ") : Read device max number of uploaded effects : " << nEffects << endl;
#endif

	return (unsigned short int)(nEffects > 0 ? 100.0*mEffectList.size()/nEffects : 100);
}

//--------------------------------------------------------------//
void LinuxForceFeedback::setMasterGain(float value)
{
	if (!mSetGainSupport)
	{
#if (OIS_LINUX_JOYFF_DEBUG > 0)
Ben Hymers's avatar
Ben Hymers committed
80
		cout << "LinuxForceFeedback("<< mJoyStick << ") : Setting master gain "
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
			 << "is not supported by the device" << endl;
#endif
		return;
	}

	struct input_event event;

	memset(&event, 0, sizeof(event));
	event.type = EV_FF;
	event.code = FF_GAIN;
	if (value < 0.0)
		value = 0.0;
	else if (value > 1.0)
		value = 1.0;
	event.value = (__s32)(value * 0xFFFFUL);

#if (OIS_LINUX_JOYFF_DEBUG > 0)
Ben Hymers's avatar
Ben Hymers committed
98
	cout << "LinuxForceFeedback("<< mJoyStick << ") : Setting master gain to "
99
100
101
102
103
104
105
106
107
108
109
110
111
112
		 << value << " => " << event.value << endl;
#endif

	if (write(mJoyStick, &event, sizeof(event)) != sizeof(event)) {
		OIS_EXCEPT(E_General, "Unknown error changing master gain.");
	}
}

//--------------------------------------------------------------//
void LinuxForceFeedback::setAutoCenterMode(bool enabled)
{
	if (!mSetAutoCenterSupport)
	{
#if (OIS_LINUX_JOYFF_DEBUG > 0)
Ben Hymers's avatar
Ben Hymers committed
113
		cout << "LinuxForceFeedback("<< mJoyStick << ") : Setting auto-center mode "
114
115
116
117
118
119
120
121
122
123
124
125
126
			 << "is not supported by the device" << endl;
#endif
		return;
	}

	struct input_event event;

	memset(&event, 0, sizeof(event));
	event.type = EV_FF;
	event.code = FF_AUTOCENTER;
	event.value = (__s32)(enabled*0xFFFFFFFFUL);

#if (OIS_LINUX_JOYFF_DEBUG > 0)
Ben Hymers's avatar
Ben Hymers committed
127
	cout << "LinuxForceFeedback("<< mJoyStick << ") : Toggling auto-center to "
128
129
130
131
132
133
134
135
136
137
138
139
140
		 << enabled << " => 0x" << hex << event.value << dec << endl;
#endif

	if (write(mJoyStick, &event, sizeof(event)) != sizeof(event)) {
		OIS_EXCEPT(E_General, "Unknown error toggling auto-center.");
	}
}

//--------------------------------------------------------------//
void LinuxForceFeedback::upload( const Effect* effect )
{
	switch( effect->force )
	{
Ben Hymers's avatar
Ben Hymers committed
141
142
		case OIS::Effect::ConstantForce:
			_updateConstantEffect(effect);
143
			break;
Ben Hymers's avatar
Ben Hymers committed
144
		case OIS::Effect::ConditionalForce:
145
146
			_updateConditionalEffect(effect);
			break;
Ben Hymers's avatar
Ben Hymers committed
147
		case OIS::Effect::PeriodicForce:
148
149
			_updatePeriodicEffect(effect);
			break;
Ben Hymers's avatar
Ben Hymers committed
150
151
		case OIS::Effect::RampForce:
			_updateRampEffect(effect);
152
			break;
Ben Hymers's avatar
Ben Hymers committed
153
		case OIS::Effect::CustomForce:
154
155
			//_updateCustomEffect(effect);
			//break;
Ben Hymers's avatar
Ben Hymers committed
156
157
		default:
			OIS_EXCEPT(E_NotImplemented, "Requested force not implemented yet, sorry!");
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
			break;
	}
}

//--------------------------------------------------------------//
void LinuxForceFeedback::modify( const Effect* effect )
{
	upload(effect);
}

//--------------------------------------------------------------//
void LinuxForceFeedback::remove( const Effect* effect )
{
	//Get the effect - if it exists
	EffectList::iterator i = mEffectList.find(effect->_handle);
	if( i != mEffectList.end() )
	{
		struct ff_effect *linEffect = i->second;
		if( linEffect )
		{
			_stop(effect->_handle);

			_unload(effect->_handle);

			free(linEffect);

			mEffectList.erase(i);
		}
		else
			mEffectList.erase(i);
	}
}

//--------------------------------------------------------------//
// To Signed16/Unsigned15 safe conversions
#define MaxUnsigned15Value 0x7FFF
#define toUnsigned15(value) \
	(__u16)((value) < 0 ? 0 : ((value) > MaxUnsigned15Value ? MaxUnsigned15Value : (value)))

#define MaxSigned16Value  0x7FFF
#define MinSigned16Value -0x7FFF
#define toSigned16(value) \
  (__s16)((value) < MinSigned16Value ? MinSigned16Value : ((value) > MaxSigned16Value ? MaxSigned16Value : (value)))

// OIS to Linux duration
#define LinuxInfiniteDuration 0xFFFF
#define OISDurationUnitMS 1000 // OIS duration unit (microseconds), expressed in milliseconds (theLinux duration unit)

// linux/input.h : All duration values are expressed in ms. Values above 32767 ms (0x7fff)
//                 should not be used and have unspecified results.
#define LinuxDuration(oisDuration) ((oisDuration) == Effect::OIS_INFINITE ? LinuxInfiniteDuration \
									: toUnsigned15((oisDuration)/OISDurationUnitMS))


// OIS to Linux levels
#define OISMaxLevel 10000
#define LinuxMaxLevel 0x7FFF

// linux/input.h : Valid range for the attack and fade levels is 0x0000 - 0x7fff
#define LinuxPositiveLevel(oisLevel) toUnsigned15(LinuxMaxLevel*(long)(oisLevel)/OISMaxLevel)

#define LinuxSignedLevel(oisLevel) toSigned16(LinuxMaxLevel*(long)(oisLevel)/OISMaxLevel)


//--------------------------------------------------------------//
Ben Hymers's avatar
Ben Hymers committed
223
224
void LinuxForceFeedback::_setCommonProperties(struct ff_effect *event,
											  struct ff_envelope *ffenvelope,
225
226
227
228
229
230
231
232
233
234
											  const Effect* effect, const Envelope *envelope )
{
	memset(event, 0, sizeof(struct ff_effect));

	if (envelope && ffenvelope && envelope->isUsed()) {
		ffenvelope->attack_length = LinuxDuration(envelope->attackLength);
		ffenvelope->attack_level = LinuxPositiveLevel(envelope->attackLevel);
		ffenvelope->fade_length = LinuxDuration(envelope->fadeLength);
		ffenvelope->fade_level = LinuxPositiveLevel(envelope->fadeLevel);
	}
Ben Hymers's avatar
Ben Hymers committed
235

236
237
238
239
240
241
#if (OIS_LINUX_JOYFF_DEBUG > 1)
	cout << endl;
	if (envelope && ffenvelope)
	{
		cout << "  Enveloppe :" << endl
			 << "    AttackLen : " << envelope->attackLength
Ben Hymers's avatar
Ben Hymers committed
242
			 << " => " << ffenvelope->attack_length << endl
243
			 << "    AttackLvl : " << envelope->attackLevel
Ben Hymers's avatar
Ben Hymers committed
244
			 << " => " << ffenvelope->attack_level << endl
245
246
247
248
249
250
			 << "    FadeLen   : " << envelope->fadeLength
			 << " => " << ffenvelope->fade_length << endl
			 << "    FadeLvl   : " << envelope->fadeLevel
			 << " => " << ffenvelope->fade_level << endl;
	}
#endif
Ben Hymers's avatar
Ben Hymers committed
251

252
253
254
255
256
257
258
259
260
261
262
263
264
	event->direction = (__u16)(1 + (effect->direction*45.0+135.0)*0xFFFFUL/360.0);

#if (OIS_LINUX_JOYFF_DEBUG > 1)
	cout << "  Direction : " << Effect::getDirectionName(effect->direction)
		 << " => 0x" << hex << event->direction << dec << endl;
#endif

	// TODO trigger_button 0 vs. -1
	event->trigger.button = effect->trigger_button; // < 0 ? 0 : effect->trigger_button;
	event->trigger.interval = LinuxDuration(effect->trigger_interval);

#if (OIS_LINUX_JOYFF_DEBUG > 1)
	cout << "  Trigger :" << endl
Ben Hymers's avatar
Ben Hymers committed
265
		 << "    Button   : " << effect->trigger_button
266
		 << " => " << event->trigger.button << endl
Ben Hymers's avatar
Ben Hymers committed
267
		 << "    Interval : " << effect->trigger_interval
268
269
270
271
272
273
274
275
		 << " => " << event->trigger.interval << endl;
#endif

	event->replay.length = LinuxDuration(effect->replay_length);
	event->replay.delay = LinuxDuration(effect->replay_delay);

#if (OIS_LINUX_JOYFF_DEBUG > 1)
	cout << "  Replay :" << endl
Ben Hymers's avatar
Ben Hymers committed
276
		 << "    Length : " << effect->replay_length
277
		 << " => " << event->replay.length << endl
Ben Hymers's avatar
Ben Hymers committed
278
		 << "    Delay  : " << effect->replay_delay
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
		 << " => " << event->replay.delay << endl;
#endif
}

//--------------------------------------------------------------//
void LinuxForceFeedback::_updateConstantEffect( const Effect* eff )
{
	struct ff_effect event;

	ConstantEffect *effect = static_cast<ConstantEffect*>(eff->getForceEffect());

	_setCommonProperties(&event, &event.u.constant.envelope, eff, &effect->envelope);

	event.type = FF_CONSTANT;
	event.id = -1;

	event.u.constant.level = LinuxSignedLevel(effect->level);

#if (OIS_LINUX_JOYFF_DEBUG > 1)
	cout << "  Level : " << effect->level
		 << " => " << event.u.constant.level << endl;
#endif

	_upload(&event, eff);
}

//--------------------------------------------------------------//
void LinuxForceFeedback::_updateRampEffect( const Effect* eff )
{
	struct ff_effect event;

	RampEffect *effect = static_cast<RampEffect*>(eff->getForceEffect());

	_setCommonProperties(&event, &event.u.constant.envelope, eff, &effect->envelope);

	event.type = FF_RAMP;
	event.id = -1;

	event.u.ramp.start_level = LinuxSignedLevel(effect->startLevel);
	event.u.ramp.end_level = LinuxSignedLevel(effect->endLevel);

#if (OIS_LINUX_JOYFF_DEBUG > 1)
	cout << "  StartLevel : " << effect->startLevel
		 << " => " << event.u.ramp.start_level << endl
		 << "  EndLevel   : " << effect->endLevel
		 << " => " << event.u.ramp.end_level << endl;
#endif

	_upload(&event, eff);
}

//--------------------------------------------------------------//
void LinuxForceFeedback::_updatePeriodicEffect( const Effect* eff )
{
	struct ff_effect event;

	PeriodicEffect *effect = static_cast<PeriodicEffect*>(eff->getForceEffect());

	_setCommonProperties(&event, &event.u.periodic.envelope, eff, &effect->envelope);

	event.type = FF_PERIODIC;
	event.id = -1;

	switch( eff->type )
	{
		case OIS::Effect::Square:
			event.u.periodic.waveform = FF_SQUARE;
			break;
		case OIS::Effect::Triangle:
			event.u.periodic.waveform = FF_TRIANGLE;
			break;
		case OIS::Effect::Sine:
			event.u.periodic.waveform = FF_SINE;
			break;
		case OIS::Effect::SawToothUp:
			event.u.periodic.waveform = FF_SAW_UP;
			break;
		case OIS::Effect::SawToothDown:
			event.u.periodic.waveform = FF_SAW_DOWN;
			break;
		// Note: No support for Custom periodic force effect for the moment
		//case OIS::Effect::Custom:
			//event.u.periodic.waveform = FF_CUSTOM;
			//break;
		default:
Ben Hymers's avatar
Ben Hymers committed
364
			OIS_EXCEPT(E_General, "No such available effect for Periodic force!");
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
			break;
	}

	event.u.periodic.period    = LinuxDuration(effect->period);
	event.u.periodic.magnitude = LinuxPositiveLevel(effect->magnitude);
	event.u.periodic.offset    = LinuxPositiveLevel(effect->offset);
	event.u.periodic.phase     = (__u16)(effect->phase*event.u.periodic.period/36000.0); // ?????

	// Note: No support for Custom periodic force effect for the moment
	event.u.periodic.custom_len = 0;
	event.u.periodic.custom_data = 0;

#if (OIS_LINUX_JOYFF_DEBUG > 1)
	cout << "  Magnitude : " << effect->magnitude
		 << " => " << event.u.periodic.magnitude << endl
		 << "  Period    : " << effect->period
		 << " => " << event.u.periodic.period  << endl
		 << "  Offset    : " << effect->offset
		 << " => " << event.u.periodic.offset << endl
		 << "  Phase     : " << effect->phase
		 << " => " << event.u.periodic.phase << endl;
#endif

	_upload(&event, eff);
}

//--------------------------------------------------------------//
void LinuxForceFeedback::_updateConditionalEffect( const Effect* eff )
{
	struct ff_effect event;

	ConditionalEffect *effect = static_cast<ConditionalEffect*>(eff->getForceEffect());

	_setCommonProperties(&event, NULL, eff, NULL);

	switch( eff->type )
	{
		case OIS::Effect::Friction:
Ben Hymers's avatar
Ben Hymers committed
403
			event.type = FF_FRICTION;
404
405
			break;
		case OIS::Effect::Damper:
Ben Hymers's avatar
Ben Hymers committed
406
			event.type = FF_DAMPER;
407
408
			break;
		case OIS::Effect::Inertia:
Ben Hymers's avatar
Ben Hymers committed
409
			event.type = FF_INERTIA;
410
411
412
413
414
			break;
		case OIS::Effect::Spring:
			event.type = FF_SPRING;
			break;
		default:
Ben Hymers's avatar
Ben Hymers committed
415
			OIS_EXCEPT(E_General, "No such available effect for Conditional force!");
416
417
418
419
420
421
422
423
424
			break;
	}

	event.id = -1;

	event.u.condition[0].right_saturation = LinuxSignedLevel(effect->rightSaturation);
	event.u.condition[0].left_saturation  = LinuxSignedLevel(effect->leftSaturation);
	event.u.condition[0].right_coeff      = LinuxSignedLevel(effect->rightCoeff);
	event.u.condition[0].left_coeff       = LinuxSignedLevel(effect->leftCoeff);
Ben Hymers's avatar
Ben Hymers committed
425
	event.u.condition[0].deadband         = LinuxPositiveLevel(effect->deadband);// Unit ??
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
	event.u.condition[0].center           = LinuxSignedLevel(effect->center); // Unit ?? TODO ?

	// TODO support for second condition
	event.u.condition[1] = event.u.condition[0];

#if (OIS_LINUX_JOYFF_DEBUG > 1)
	cout << "  Condition[0] : " << endl
		 << "    RightSaturation  : " << effect->rightSaturation
		 << " => " << event.u.condition[0].right_saturation << endl
		 << "    LeftSaturation   : " << effect->leftSaturation
		 << " => " << event.u.condition[0]. left_saturation << endl
		 << "    RightCoefficient : " << effect->rightCoeff
		 << " => " << event.u.condition[0].right_coeff << endl
		 << "    LeftCoefficient : " << effect->leftCoeff
		 << " => " << event.u.condition[0].left_coeff << endl
		 << "    DeadBand        : " << effect->deadband
		 << " => " << event.u.condition[0].deadband  << endl
		 << "    Center          : " << effect->center
		 << " => " << event.u.condition[0].center << endl;
	cout << "  Condition[1] : Not implemented" << endl;
#endif
	_upload(&event, eff);
}

//--------------------------------------------------------------//
void LinuxForceFeedback::_upload( struct ff_effect* ffeffect, const Effect* effect)
{
	struct ff_effect *linEffect = 0;

	//Get the effect - if it exists
	EffectList::iterator i = mEffectList.find(effect->_handle);
	//It has been created already
	if( i != mEffectList.end() )
		linEffect = i->second;

	if( linEffect == 0 )
	{
#if (OIS_LINUX_JOYFF_DEBUG > 1)
Ben Hymers's avatar
Ben Hymers committed
464
		cout << endl << "LinuxForceFeedback("<< mJoyStick << ") : Adding new effect : "
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
			 << Effect::getEffectTypeName(effect->type) << endl;
#endif

		//This effect has not yet been created, so create it in the device
		if (ioctl(mJoyStick, EVIOCSFF, ffeffect) == -1) {
			// TODO device full check
			// OIS_EXCEPT(E_DeviceFull, "Remove an effect before adding more!");
			OIS_EXCEPT(E_General, "Unknown error creating effect (may be the device is full)->..");
		}

		// Save returned effect handle
		effect->_handle = ffeffect->id;

		// Save a copy of the uploaded effect for later simple modifications
		linEffect = (struct ff_effect *)calloc(1, sizeof(struct ff_effect));
		memcpy(linEffect, ffeffect, sizeof(struct ff_effect));

		mEffectList[effect->_handle] = linEffect;

		// Start playing the effect.
		_start(effect->_handle);
	}
	else
	{
#if (OIS_LINUX_JOYFF_DEBUG > 1)
Ben Hymers's avatar
Ben Hymers committed
490
		cout << endl << "LinuxForceFeedback("<< mJoyStick << ") : Replacing effect : "
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
			 << Effect::getEffectTypeName(effect->type) << endl;
#endif

		// Keep same id/handle, as this is just an update in the device.
		ffeffect->id = effect->_handle;

		// Update effect in the device.
		if (ioctl(mJoyStick, EVIOCSFF, ffeffect) == -1) {
			OIS_EXCEPT(E_General, "Unknown error updating an effect->..");
		}

		// Update local linEffect for next time.
		memcpy(linEffect, ffeffect, sizeof(struct ff_effect));
	}

#if (OIS_LINUX_JOYFF_DEBUG > 1)
Ben Hymers's avatar
Ben Hymers committed
507
	cout << "LinuxForceFeedback("<< mJoyStick
508
509
510
511
512
513
514
515
516
517
518
519
520
		 << ") : Effect handle : " << effect->_handle << endl;
#endif
}

//--------------------------------------------------------------//
void LinuxForceFeedback::_stop( int handle) {
	struct input_event stop;

	stop.type = EV_FF;
	stop.code = handle;
	stop.value = 0;

#if (OIS_LINUX_JOYFF_DEBUG > 1)
Ben Hymers's avatar
Ben Hymers committed
521
	cout << endl << "LinuxForceFeedback("<< mJoyStick
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
		 << ") : Stopping effect with handle " << handle << endl;
#endif

	if (write(mJoyStick, &stop, sizeof(stop)) != sizeof(stop)) {
		OIS_EXCEPT(E_General, "Unknown error stopping effect->..");
	}
}

//--------------------------------------------------------------//
void LinuxForceFeedback::_start( int handle) {
	struct input_event play;

	play.type = EV_FF;
	play.code = handle;
	play.value = 1; // Play once.

#if (OIS_LINUX_JOYFF_DEBUG > 1)
Ben Hymers's avatar
Ben Hymers committed
539
	cout << endl << "LinuxForceFeedback("<< mJoyStick
540
541
542
543
544
545
546
547
548
549
550
551
		 << ") : Starting effect with handle " << handle << endl;
#endif

	if (write(mJoyStick, &play, sizeof(play)) != sizeof(play)) {
		OIS_EXCEPT(E_General, "Unknown error playing effect->..");
	}
}

//--------------------------------------------------------------//
void LinuxForceFeedback::_unload( int handle)
{
#if (OIS_LINUX_JOYFF_DEBUG > 1)
Ben Hymers's avatar
Ben Hymers committed
552
	cout << endl << "LinuxForceFeedback("<< mJoyStick
553
554
555
556
557
558
559
		 << ") : Removing effect with handle " << handle << endl;
#endif

	if (ioctl(mJoyStick, EVIOCRMFF, handle) == -1) {
		OIS_EXCEPT(E_General, "Unknown error removing effect->..");
	}
}