This repository has been archived by the owner on Mar 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GLFW.hx
629 lines (443 loc) · 20.8 KB
/
GLFW.hx
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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
364
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
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
464
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
package glfw;
import cpp.NativeString;
import cpp.Pointer;
import glfw.errors.*;
import glfw.mouse.*;
import haxe.ds.ReadOnlyArray;
/**
Main entry point to the GLFW library
You must only instance it once at a time.
Calling `GLFW.destroy` will invalidate the instance and all the resources associated.
Using the object, or objects created thought it, after the destruction will throw a `UseAfterDestroyException` exception.
**/
@:allow(glfw)
@:build(glfw.GLFWBuilder.build())
@:cppNamespaceCode('
static bool had_init = false;
static GLFW_obj *singleton = nullptr;
static void error_callback(int code, const char *message) {
glfw::GLFW_obj::errorCallback(code, message);
}
static void gamepad_callback(int id, int event) {
singleton->_onGamepadChange(id, event == GLFW_CONNECTED);
}
static void monitor_callback(GLFWmonitor *monitor, int status) {
singleton->updateMonitor(monitor, status == GLFW_CONNECTED);
}
')
@:headerInclude('./glfw.h')
class GLFW {
/**
Called from `glfwSetErrorCallback`.
**/
static function errorCallback(code:Int, message:String):Void {
switch (code) {
case 0x0001000B: // GLFW_CURSOR_UNAVAILABLE
throw new CursorUnavailableException(message);
case 0x00010009: // GLFW_FORMAT_UNAVAILABLE
throw new FormatUnavailableException(message);
case 0x00010003, 0x00010004: // GLFW_INVALID_ENUM & GLFW_INVALID_VALUE
throw new InternalException(message);
case 0x00010001: // GLFW_NOT_INITIALIZED
throw new NotInitializedException(message);
case 0x00010005: // GLFW_OUT_OF_MEMORY
throw new OutOfMemoryException(message);
case 0x00010008: // GLFW_PLATFORM_ERROR
throw new PlatformErrorException(message);
default: // Basic error type
throw new Exception(message);
}
}
static function validate():Void {
if (untyped __cpp__('singleton == nullptr')) {
if (untyped __cpp__('had_init')) {
throw new UseAfterDestroyException();
} else {
throw new NotInitializedException("GLFW has not been initialized");
}
}
}
/**
<p>The version of the native GLFW library used. Can be called without having a `GLFW` instance.</p><p><b>Thread safety:</b> This function may be called from any thread.</p>
**/
public static var version(get, never):{major:Int, minor:Int, patch:Int};
static function get_version():{major:Int, minor:Int, patch:Int} {
var major = 0;
var minor = 0;
var patch = 0;
untyped __cpp__('glfwGetVersion(&major, &minor, &patch)');
return {
major: major,
minor: minor,
patch: patch,
};
}
/**
The contents of the clipboard as a string.
This is the contents of the system clipboard, if it contains or is convertible to a UTF-8 encoded string.
If the clipboard is empty or if its contents cannot be converted, the result is an empty string.
**Thread safety:** This function must only be called from the main thread.
@throws PlatformErrorException
@throws UseAfterDestroyException
**/
public var clipboardString(get, set):String;
/**
Array of possible gamepads.
This is a set of 15 preallocated `Gamepad` instances, the gamepads are not necessarily connected, check with `Gamepad.connected` or use `GLFW.getConnectedGamepads` to only get the gamepads that are connected.
Use `GLFW.onGamepadChange` or `Gamepad.onStatusChange` to be notified of gamepad connections and disconnections.
**/
public var gamepads(default, null):ReadOnlyArray<Gamepad>;
var _monitors:Array<Monitor>;
/**
The currently connected monitors.
The primary monitor is always first in the array.
The `Monitor` instances are only valid until the instance is destroyed or the monitor gets disconnected.
@throws UseAfterDestroyException
**/
public var monitors(get, never):ReadOnlyArray<Monitor>;
/**
The callbacks to be called when a gamepad is connected or disconnected from the system.
Disconnecting then reconnecting the same physical gamepad is not guaranteed to map to the same `Gamepad` object.
Arguments:
* `gamepad` The gamepad that was connected or disconnected.
* `connected` True if the gamepad was connected, false if disconnected.
To add a callback push a function to this array.
**/
public var onGamepadChange:Array<(gamepad:Gamepad, connected:Bool) -> Void>;
/**
The callbacks to be called when a monitor is connected to or disconnected from the system.
Arguments:
* `monitor` The monitor that was connected or disconnected.
* `connected` True if the monitor was connected, false if disconnected.
If the monitor was disconnected the `Monitor` instance is valid until the callback returns.
Disconnecting then connecting back a monitor will not reuse the old `Monitor` object.
To add a callback push a function to this array.
**/
public var onMonitorChange:Array<(monitor:Monitor, connected:Bool) -> Void>;
/**
The primary monitor, usually the monitor where elements like the task bar or global menu bar are located.
This is equalivalent to `monitors[0]`.
If no monitor is available then accessing this will throw a `NoMonitorException` exception.
@throws NoMonitorException
@throws UseAfterDestroyException
**/
public var primaryMonitor(get, never):Monitor;
function get_clipboardString():String {
validate();
return NativeString.fromPointer(untyped __cpp__('glfwGetClipboardString(nullptr)'));
}
function set_clipboardString(value:String):String {
validate();
untyped __cpp__('glfwSetClipboardString(nullptr, value)');
return value;
}
inline function get_monitors():ReadOnlyArray<Monitor> {
validate();
return _monitors;
}
inline function get_primaryMonitor():Monitor {
validate();
if (_monitors.length == 0) {
throw new NoMonitorException();
}
return _monitors[0];
}
/**
Create a new instance of GLFW.
Only one instance must be valid at a time.
Trying to create a second one will throw a `AlreadyInitializedException` exception.
**Thread safety:** This function must only be called from the main thread.
@throws AlreadyInitializedException
@throws PlatformErrorException
**/
public function new() {
if (untyped __cpp__('singleton != nullptr')) {
throw new AlreadyInitializedException();
}
untyped __cpp__('
glfwSetErrorCallback(error_callback);
glfwInitHint(GLFW_JOYSTICK_HAT_BUTTONS, GLFW_FALSE);
glfwInit();
singleton = this;
');
this._monitors = [];
this.onGamepadChange = [];
this.onMonitorChange = [];
this.gamepads = [for (i in 0...16) new Gamepad(i)];
untyped __cpp__('
int count;
GLFWmonitor **raw_monitors = glfwGetMonitors(&count);
for (unsigned int i = 0; i < count; ++i) {
glfw::Monitor monitor = glfw::Monitor_obj::__alloc(HX_CTX);
monitor->native = raw_monitors[i];
_monitors->push(monitor);
}
glfwSetJoystickCallback(gamepad_callback);
glfwSetMonitorCallback(monitor_callback);
');
}
/**
Creates a new custom cursor image that can be set for a window with `Window.cursor`.
The cursor can be destroyed `Cursor.destroy`, any remaining cursors are destroyed by `GLFW.destroy`.
The cursor hotspot is specified in pixels, relative to the upper-left corner of the cursor image. Like all other coordinate systems in GLFW, the X-axis points to the right and the Y-axis points down.
**Thread safety:** This function must only be called from the main thread.
@param image The desired cursor image.
@param x The desired x-coordinate, in pixels, of the cursor hotspot.
@param y The desired y-coordinate, in pixels, of the cursor hotspot.
@return The created cursor.
@throws PlatformErrorException
@throws UseAfterDestroyException
**/
public function createCursor(image:Image, x:Int, y:Int):Cursor {
validate();
var cursor = new Cursor();
untyped __cpp__('
unsigned char *pixels = (unsigned char*)malloc(sizeof(*pixels) * image->pixels->length);
for (unsigned int i = 0; i < image->pixels->length; ++i) {
pixels[i] = image->pixels->__get(i);
}
GLFWimage native_image = {
width: image->width,
height: image->height,
pixels: pixels,
};
cursor->native = glfwCreateCursor(&native_image, x, y);
free(pixels);
');
return cursor;
}
/**
Creates a cursor with a standard shape, that can be set for a window with `Window.cursor`.
The images for these cursors come from the system cursor theme and their exact appearance will vary between platforms.
Most of these shapes are guaranteed to exist on every supported platform but a few may not be present. See the table below for details.
Cursor shape | Windows | macOS | X11 | Wayland
------------------------------ | ------- | ------- | --------- | -------
`CursorMode.Arrow` | Yes | Yes | Yes | Yes
`CursorMode.IBeam` | Yes | Yes | Yes | Yes
`CursorMode.Crosshair` | Yes | Yes | Yes | Yes
`CursorMode.PointingHand` | Yes | Yes | Yes | Yes
`CursorMode.ResizeEW` | Yes | Yes | Yes | Yes
`CursorMode.ResizeNS` | Yes | Yes | Yes | Yes
`CursorMode.ResizeNWSE` | Yes | Yes (1) | Maybe (2) | Maybe (2)
`CursorMode.ResizeNESW` | Yes | Yes (1) | Maybe (2) | Maybe (2)
`CursorMode.ResizeAll` | Yes | Yes | Yes | Yes
`CursorMode.NotAllowed` | Yes | Yes | Maybe (2) | Maybe (2)
(1) This uses a private system API and may fail in the future.
(2) This uses a newer standard that not all cursor themes support.
**Thread safety:** This function must only be called from the main thread.
@param shape One of the standard shapes in `CursorShape`.
@return The created cursor.
@throws CursorUnavailableException
@throws PlatformErrorException
@throws UseAfterDestroyException
**/
public function createStandardCursor(shape:CursorShape):Cursor {
validate();
var cursor = new Cursor();
untyped __cpp__('cursor->native = glfwCreateStandardCursor(shape)');
return cursor;
}
/**
Create a window with the options `options`.
To create a fullscreen window, you need to specify the monitor the window will cover in `WindowOptions.monitor`. If no monitor is specified, the window will be windowed mode.
Unless you have a way for the user to choose a specific monitor, it is recommended that you pick the primary monitor using `primaryMonitor`.
You can get information on the available monitors in the `monitors` array.
For fullscreen windows, the specified size becomes the resolution of the window's _desired video mode_. As long as a fullscreen window is not iconified, the supported video mode most closely matching the desired video mode is set for the specified monitor.
Once you have created the window, you can switch it between windowed and fullscreen mode with `Window.setFullscreenMonitor`.
By default, newly created windows use the placement recommended by the window system.
To create the window at a specific position, make it initially invisible using `WindowOptions.visible`, set its position with `Window.setPosition` and then show it with `Window.show`.
As long as at least one fullscreen window is not iconified, the screensaver is prohibited from starting.
Window systems put limits on window sizes.
Very large or very small window dimensions may be overridden by the window system on creation. Check the actual size with `Window.getSize` after creation.
Window creation will fail if the Microsoft GDI software OpenGL implementation is the only one available.
On MacOS the window has no icon, as it is not a document window, but the dock icon will be the same as the application bundle's icon.
For more information on bundles, see the [Bundle Programming Guide](https://developer.apple.com/library/mac/documentation/CoreFoundation/Conceptual/CFBundles/) in the Mac Developer Library.
On X11 some window managers will not respect the placement of initially hidden windows.
On X11 due to the asynchronous nature of X11, it may take a moment for a window to reach its requested state. This means you may not be able to query the final size, position or other attributes directly after window creation.
On wayland a fullscreen window will not attempt to change the mode, no matter what the requested size or refresh rate.
On wayland screensaver inhibition requires the idle-inhibit protocol to be implemented in the user's compositor.
**Thread safety:** This function must only be called from the main thread.
@param options The options used to create the window.
@return The created window.
@throws FormatUnavailableException
@throws PlatformErrorException
@throws UseAfterDestroyException
**/
public function createWindow(options:WindowOptions):Window {
validate();
return new Window(this, options);
}
/**
Destroy this instance.
This function destroys all remaining windows and cursors and frees any other allocated resources.
Once this function is called, you must again create a new instance of `GLFW`.
This function should be called before the application exits.
Using the object, or objects created thought it, after the destruction will throw a `UseAfterDestroyException` exception.
**Reentrancy:** This function must not be called from a callback.
**Thread safety:** This function must only be called from the main thread.
@throws UseAfterDestroyException
@throws PlatformErrorException
@throws UseAfterDestroyException
**/
public function destroy():Void {
validate();
untyped __cpp__('
glfwTerminate();
singleton = nullptr;
');
}
function findMonitor(ptr:Pointer<cpp.Void>):Null<Monitor> {
for (m in _monitors) {
if (untyped __cpp__('m->native == (GLFWmonitor*)((void*)ptr)')) {
return m;
}
}
return null;
}
/**
Get the connected gamepads.
This is a subset from `GLFW.gamepads` implemented with:
```haxe
return gamepads.filter(g -> g.connected);
```
@throws UseAfterDestroyException
**/
public function getConnectedGamepads():Array<Gamepad> {
validate();
return gamepads.filter(g -> g.connected);
}
function _onGamepadChange(id:Int, connected:Bool):Void {
if (id > 15) {
return;
}
final gamepad = gamepads[id];
for (fn in onGamepadChange) {
fn(gamepad, connected);
}
for (fn in gamepad.onStatusChange) {
fn(connected);
}
}
/**
Processes all pending events.
This function processes only those events that are already in the event queue and then returns immediately. Processing events will cause the window and input callbacks associated with those events to be called.
On some platforms, a window move, resize or menu operation will cause event processing to block. This is due to how event processing is designed on those platforms.
You can use the `Window.onRefresh` callback to redraw the contents of your window when necessary during such operations.
Do not assume that callbacks you set will _only_ be called in response to event processing functions like this one. While it is necessary to poll for events, window systems that require GLFW to register callbacks of its own can pass events to GLFW in response to many window system function calls. GLFW will pass those events on to the application callbacks before returning.
**Reentrancy:** This function must not be called from a callback.
**Thread safety:** This function must only be called from the main thread.
@throws PlatformErrorException
@throws UseAfterDestroyException
**/
public function pollEvents():Void {
validate();
untyped __cpp__('glfwPollEvents();');
for (gamepad in gamepads) {
gamepad.update();
}
}
/**
Posts an empty event to the event queue.
This is causing `GLFW.waitEvents` or `GLFW.waitEventsTimeout` to return.
**Thread safety:** This function may be called from any thread.
@throws PlatformErrorException
@throws UseAfterDestroyException
**/
public function postEmptyEvent():Void {
validate();
untyped __cpp__('glfwPostEmptyEvent()');
}
/**
Adds the specified SDL_GameControllerDB gamepad mappings.
This parses the specified ASCII encoded string and updates the internal list with any gamepad mappings it finds.
This string may contain either a single gamepad mapping or many mappings separated by newlines.
The parser supports the full format of the `gamecontrollerdb.txt` source file including empty lines and comments.
If there is already a gamepad mapping for a given GUID in the internal list, it will be replaced by the one passed to this function.
If the library is terminated and re-initialized the internal list will revert to the built-in default.
**Thread safety:** This function must only be called from the main thread.
@param patch The string containing the gamepad mappings patch.
@throws UseAfterDestroyException
**/
public function updateGamepadMappings(patch:String):Void {
validate();
untyped __cpp__('glfwUpdateGamepadMappings(patch)');
}
/**
Called from `glfwSetMonitorCallback`.
**/
function updateMonitor(raw:Pointer<cpp.Void>, connected:Bool):Void {
var monitor = findMonitor(raw);
if (monitor == null) {
monitor = new Monitor();
untyped __cpp__('monitor->native = (GLFWmonitor*)((void*)raw)');
}
if (connected) {
_monitors.push(monitor);
} else {
_monitors.remove(monitor);
}
for (fn in onMonitorChange) {
fn(monitor, connected);
}
if (!connected) {
untyped __cpp__('monitor->native = nullptr');
}
// Move the primary monitor to the start of the array.
var primary = switch (findMonitor(untyped __cpp__('glfwGetPrimaryMonitor()'))) {
case null: throw "assert false";
case value: (value : Monitor);
}
_monitors.remove(primary);
_monitors.unshift(primary);
}
/**
Waits until events are queued and processes them.
This function puts the calling thread to sleep until at least one event is available in the event queue.
Once one or more events are available, it behaves exactly like `GLFW.pollEvents`, i.e. the events in the queue are processed and the function then returns immediately.
Processing events will cause the window and input callbacks associated with those events to be called.
Since not all events are associated with callbacks, this function may return without a callback having been called even if you are monitoring all callbacks.
On some platforms, a window move, resize or menu operation will cause event processing to block.
This is due to how event processing is designed on those platforms.
You can use the `Window.onRefresh` callback to redraw the contents of your window when necessary during such operations.
Do not assume that callbacks you set will _only_ be called in response to event processing functions like this one.
While it is necessary to poll for events, window systems that require GLFW to register callbacks of its own can pass events to GLFW in response to many window system function calls.
GLFW will pass those events on to the application callbacks before returning.
**Reentrancy:** This function must not be called from a callback.
**Thead safety:** This function must only be called from the main thread.
@throws PlatformErrorException
@throws UseAfterDestroyException
**/
public function waitEvents():Void {
validate();
untyped __cpp__('glfwWaitEvents()');
for (gamepad in gamepads) {
gamepad.update();
}
}
/**
Waits with timeout until events are queued and processes them.
This function puts the calling thread to sleep until at least one event is available in the event queue, or until the specified timeout is reached.
If one or more events are available, it behaves exactly like `GLFW.pollEvents`, i.e. the events in the queue are processed and the function then returns immediately.
Processing events will cause the window and input callbacks associated with those events to be called.
The timeout value must be a positive finite number.
Since not all events are associated with callbacks, this function may return without a callback having been called even if you are monitoring all callbacks.
On some platforms, a window move, resize or menu operation will cause event processing to block.
This is due to how event processing is designed on those platforms.
You can use the `Window.onRefresh` callback to redraw the contents of your window when necessary during such operations.
Do not assume that callbacks you set will _only_ be called in response to event processing functions like this one.
While it is necessary to poll for events, window systems that require GLFW to register callbacks of its own can pass events to GLFW in response to many window system function calls.
GLFW will pass those events on to the application callbacks before returning.
**Reentrancy:** This function must not be called from a callback.
**Thread safety:** This function must only be called from the main thread.
@param timeout The maximum amount of time, in seconds, to wait.
@throws PlatformErrorException
@throws UseAfterDestroyException
**/
public function waitEventsTimeout(timeout:Float):Void {
validate();
untyped __cpp__('glfwWaitEventsTimeout(timeout >= 0 ? timeout : 0)');
for (gamepad in gamepads) {
gamepad.update();
}
}
}