lib/sdl: add access to texture pixels and alpha mask
[nit.git] / lib / sdl.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2011-2013 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # SDL display support (used in Linux for windows and inputes only)
18 module sdl is
19 c_compiler_option(exec("sdl-config", "--cflags"))
20 c_linker_option(exec("sdl-config", "--libs"), "-lSDL_image -lSDL_ttf")
21 end
22
23 import mnit_display
24 import c
25
26 in "C header" `{
27 #include <unistd.h>
28 #include <SDL/SDL.h>
29 #include <SDL/SDL_syswm.h>
30 #include <SDL/SDL_image.h>
31 #include <SDL/SDL_ttf.h>
32 `}
33
34 # Represent a screen surface
35 extern class SDLDisplay `{SDL_Surface *`}
36 super Display
37
38 redef type I: SDLImage
39
40 # Initialize a surface with width and height
41 new (w, h: Int) import enable_mouse_motion_events `{
42 SDL_Init(SDL_INIT_VIDEO);
43
44 if(TTF_Init()==-1) {
45 printf("TTF_Init: %s\n", TTF_GetError());
46 exit(2);
47 }
48
49 SDL_Surface *self = SDL_SetVideoMode(w, h, 24, SDL_HWSURFACE);
50
51 if (!SDLDisplay_enable_mouse_motion_events(self)) {
52 /* ignores mousemotion for performance reasons */
53 SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
54 }
55
56 return self;
57 `}
58
59 # Indicates wether we want the SDL mouse motion event (or only clicks).
60 # Disabled by defaut for performance reason. To activate, redef this method
61 # andd return true
62 fun enable_mouse_motion_events: Bool do return false
63
64 # Destroy the surface
65 fun destroy `{
66 if (SDL_WasInit(SDL_INIT_VIDEO))
67 SDL_Quit();
68
69 if (TTF_WasInit())
70 TTF_Quit();
71 `}
72
73 redef fun finish `{ SDL_Flip(recv); `}
74
75 # Clear the entire window with given RGB color (integer values)
76 fun clear_int(r, g, b: Int) `{
77 SDL_FillRect(recv, NULL, SDL_MapRGB(recv->format,r,g,b));
78 `}
79
80 redef fun width: Int `{ return recv->w; `}
81 redef fun height: Int `{ return recv->h; `}
82
83 # Fill a rectangle with given color
84 fun fill_rect(rect: SDLRectangle, r, g, b: Int) `{
85 SDL_FillRect(recv, rect, SDL_MapRGB(recv->format,r,g,b));
86 `}
87
88 redef fun clear(r, g, b: Float) `{
89 Uint8 ri, gi, bi;
90 ri = (Uint8)r*255;
91 gi = (Uint8)g*255;
92 bi = (Uint8)b*255;
93 SDL_FillRect(recv, NULL, SDL_MapRGB(recv->format,ri,gi,bi));
94 `}
95
96 # SDL events since the last call to this method
97 fun events: Sequence[SDLInputEvent]
98 do
99 var events = new Array[SDLInputEvent]
100 loop
101 var new_event = poll_event
102 if new_event == null then break
103 events.add new_event
104 end
105 return events
106 end
107
108 private fun poll_event: nullable SDLInputEvent import SDLKeyEvent, SDLMouseButtonEvent, SDLMouseMotionEvent, SDLQuitEvent, NativeString.to_s, SDLMouseButtonEvent.as(nullable SDLInputEvent), SDLMouseMotionEvent.as(nullable SDLInputEvent), SDLKeyEvent.as(nullable SDLInputEvent), SDLQuitEvent.as(nullable SDLInputEvent) `{
109 SDL_Event event;
110
111 SDL_PumpEvents();
112
113 if (SDL_PollEvent(&event))
114 {
115 switch (event.type) {
116 case SDL_KEYDOWN:
117 case SDL_KEYUP:
118 #ifdef DEBUG
119 printf("The \"%s\" key was pressed!\n",
120 SDL_GetKeyName(event.key.keysym.sym));
121 #endif
122
123 return SDLKeyEvent_as_nullable_SDLInputEvent(
124 new_SDLKeyEvent(NativeString_to_s(
125 SDL_GetKeyName(event.key.keysym.sym)),
126 event.type==SDL_KEYDOWN));
127
128 case SDL_MOUSEMOTION:
129 #ifdef DEBUG
130 printf("Mouse moved by %d,%d to (%d,%d)\n",
131 event.motion.xrel, event.motion.yrel,
132 event.motion.x, event.motion.y);
133 #endif
134
135 return SDLMouseMotionEvent_as_nullable_SDLInputEvent(
136 new_SDLMouseMotionEvent(event.motion.x, event.motion.y,
137 event.motion.xrel, event.motion.yrel, SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(1)));
138
139 case SDL_MOUSEBUTTONDOWN:
140 case SDL_MOUSEBUTTONUP:
141 #ifdef DEBUG
142 printf("Mouse button \"%d\" pressed at (%d,%d)\n",
143 event.button.button, event.button.x, event.button.y);
144 #endif
145 return SDLMouseButtonEvent_as_nullable_SDLInputEvent(
146 new_SDLMouseButtonEvent(event.button.x, event.button.y,
147 event.button.button, event.type == SDL_MOUSEBUTTONDOWN));
148
149 case SDL_QUIT:
150 #ifdef DEBUG
151 printf("Quit event\n");
152 #endif
153 return SDLQuitEvent_as_nullable_SDLInputEvent(new_SDLQuitEvent());
154 }
155 }
156
157 return null_SDLInputEvent();
158 `}
159
160 # Set the position of the cursor to x,y
161 fun warp_mouse(x,y: Int) `{ SDL_WarpMouse(x, y); `}
162
163 # Show or hide the cursor
164 fun show_cursor=(val: Bool) `{ SDL_ShowCursor(val? SDL_ENABLE: SDL_DISABLE); `}
165
166 # Is the cursor visible?
167 fun show_cursor: Bool `{ SDL_ShowCursor(SDL_QUERY); `}
168
169 # Grab or release the input
170 fun grab_input=(val: Bool) `{ SDL_WM_GrabInput(val? SDL_GRAB_ON: SDL_GRAB_OFF); `}
171
172 # Is the input grabbed?
173 fun grab_input: Bool `{ SDL_WM_GrabInput(SDL_GRAB_QUERY) == SDL_GRAB_ON; `}
174
175 # Are instances of `SDLMouseMotionEvent` ignored?
176 fun ignore_mouse_motion_events: Bool `{
177 return SDL_EventState(SDL_MOUSEMOTION, SDL_QUERY);
178 `}
179
180 # Do not raise instances of `SDLMouseMotionEvent` if `val`
181 fun ignore_mouse_motion_events=(val: Bool) `{
182 SDL_EventState(SDL_MOUSEMOTION, val? SDL_IGNORE: SDL_ENABLE);
183 `}
184 end
185
186 # Basic Drawing figures
187 extern class SDLDrawable `{SDL_Surface*`}
188 super Drawable
189
190 redef type I: SDLImage
191
192 redef fun blit(img, x, y) do native_blit(img, x.to_i, y.to_i)
193 private fun native_blit(img: I, x, y: Int) `{
194 SDL_Rect dst;
195 dst.x = x;
196 dst.y = y;
197 dst.w = 0;
198 dst.h = 0;
199
200 SDL_BlitSurface(img, NULL, recv, &dst);
201 `}
202
203 redef fun blit_centered(img, x, y)
204 do
205 x = x - img.width / 2
206 y = y - img.height / 2
207 blit(img, x, y)
208 end
209 end
210
211 # A drawable Image
212 extern class SDLImage
213 super DrawableImage
214 super SDLDrawable
215
216 # Import image from a file
217 new from_file(path: String) import String.to_cstring `{
218 SDL_Surface *image = IMG_Load(String_to_cstring(path));
219 return image;
220 `}
221
222 # Copy of an existing SDLImage
223 new copy_of(image: SDLImage) `{
224 SDL_Surface *new_image = SDL_CreateRGBSurface(
225 image->flags, image->w, image->h, 24,
226 0, 0, 0, 0);
227
228 SDL_Rect dst;
229 dst.x = 0;
230 dst.y = 0;
231 dst.w = image->w;
232 dst.h = image->h;
233 SDL_BlitSurface(image, NULL, new_image, &dst);
234
235 return new_image;
236 `}
237
238 # Save the image into the specified file
239 fun save_to_file(path: String) import String.to_cstring `{ `}
240
241 # Destroy the image and free the memory
242 redef fun destroy `{ SDL_FreeSurface(recv); `}
243
244 redef fun width: Int `{ return recv->w; `}
245 redef fun height: Int `{ return recv->h; `}
246
247 fun is_ok: Bool do return not address_is_null
248
249 # Returns a reference to the pixels of the texture
250 fun pixels: NativeCByteArray `{ return recv->pixels; `}
251
252 # Does this texture has an alpha mask?
253 fun amask: Bool `{ return recv->format->Amask; `}
254 end
255
256 # A simple rectangle
257 extern class SDLRectangle `{SDL_Rect*`}
258 # Constructor with x,y positions width and height of the rectangle
259 new (x: Int, y: Int, w: Int, h: Int) `{
260 SDL_Rect *rect = malloc(sizeof(SDL_Rect));
261 rect->x = (Sint16)x;
262 rect->y = (Sint16)y;
263 rect->w = (Uint16)w;
264 rect->h = (Uint16)h;
265 return rect;
266 `}
267
268 fun x=(v: Int) `{ recv->x = (Sint16)v; `}
269 fun x: Int `{ return recv->x; `}
270
271 fun y=(v: Int) `{ recv->y = (Sint16)v; `}
272 fun y: Int `{ return recv->y; `}
273
274 fun w=(v: Int) `{ recv->w = (Uint16)v; `}
275 fun w: Int `{ return recv->w; `}
276
277 fun h=(v: Int) `{ recv->h = (Uint16)v; `}
278 fun h: Int `{ return recv->h; `}
279 end
280
281 interface SDLInputEvent
282 super InputEvent
283 end
284
285 # MouseEvent class containing the cursor position
286 class SDLMouseEvent
287 super PointerEvent
288 super SDLInputEvent
289
290 redef var x: Float
291 redef var y: Float
292
293 private init (x, y: Float)
294 do
295 self.x = x
296 self.y = y
297 end
298 end
299
300 # MouseButtonEvent used to get information when a button is pressed/depressed
301 class SDLMouseButtonEvent
302 super SDLMouseEvent
303
304 var button: Int
305
306 redef var pressed: Bool
307 redef fun depressed: Bool do return not pressed
308
309 # Is this event raised by the left button?
310 fun is_left_button: Bool do return button == 1
311
312 # Is this event raised by the right button?
313 fun is_right_button: Bool do return button == 2
314
315 # Is this event raised by the middle button?
316 fun is_middle_button: Bool do return button == 3
317
318 # Is this event raised by the wheel going down?
319 fun is_down_wheel: Bool do return button == 4
320
321 # Is this event raised by the wheel going up?
322 fun is_up_wheel: Bool do return button == 5
323
324 # Is this event raised by the wheel?
325 fun is_wheel: Bool do return is_down_wheel or is_up_wheel
326
327 init (x, y: Float, button: Int, pressed: Bool)
328 do
329 super(x, y)
330
331 self.button = button
332 self.pressed = pressed
333 end
334
335 redef fun to_s
336 do
337 if pressed then
338 return "MouseButtonEvent button {button} down at {x}, {y}"
339 else
340 return "MouseButtonEvent button {button} up at {x}, {y}"
341 end
342 end
343 end
344
345 # MouseMotionEvent to get the cursor position when the mouse is moved
346 class SDLMouseMotionEvent
347 super SDLMouseEvent
348
349 var rel_x: Float
350 var rel_y: Float
351
352 redef var pressed: Bool
353 redef fun depressed: Bool do return not pressed
354
355 init (x, y, rel_x, rel_y: Float, pressed: Bool)
356 do
357 super(x, y)
358
359 self.rel_x = rel_x
360 self.rel_y = rel_y
361 self.pressed = pressed
362 end
363
364 redef fun to_s do return "MouseMotionEvent at {x}, {y}"
365 end
366
367 # SDLKeyEvent for when a key is pressed
368 class SDLKeyEvent
369 super KeyEvent
370 super SDLInputEvent
371
372 var key_name: String
373 var down: Bool
374
375 init (key_name: String, down: Bool)
376 do
377 self.key_name = key_name
378 self.down = down
379 end
380
381 redef fun to_c: nullable Char
382 do
383 if key_name.length == 1 then return key_name.chars.first
384 return null
385 end
386
387 redef fun to_s
388 do
389 if down then
390 return "KeyboardEvent key {key_name} down"
391 else
392 return "KeyboardEvent key {key_name} up"
393 end
394 end
395
396 # Return true if the key is down, false otherwise
397 redef fun is_down do return down
398
399 # Return true if the key is the up arrow
400 redef fun is_arrow_up do return key_name == "up"
401 # Return true if the key is the left arrow
402 redef fun is_arrow_left do return key_name == "left"
403 # Return true if the key is the down arrow
404 redef fun is_arrow_down do return key_name == "down"
405 # Return true if the key is the right arrow
406 redef fun is_arrow_right do return key_name == "right"
407 end
408
409 class SDLQuitEvent
410 super SDLInputEvent
411 super QuitEvent
412 end
413
414 redef class Int
415 fun delay `{ SDL_Delay(recv); `}
416 end
417
418 # Class to load and use TTF_Font
419 extern class SDLFont `{TTF_Font *`}
420 # Load a font with a specified name and size
421 new (name: String, points: Int) import String.to_cstring `{
422 char * cname = String_to_cstring(name);
423
424 TTF_Font *font = TTF_OpenFont(cname, (int)points);
425 if(!font) {
426 printf("TTF_OpenFont: %s\n", TTF_GetError());
427 exit(1);
428 }
429
430 return font;
431 `}
432
433 fun destroy `{ TTF_CloseFont(recv); `}
434
435 # Create a String with the specified color, return an SDLImage
436 fun render(text: String, r, g, b: Int): SDLImage import String.to_cstring `{
437 SDL_Color color;
438 SDL_Surface *text_surface;
439 char *ctext;
440
441 color.r = r;
442 color.g = g;
443 color.b = b;
444
445 ctext = String_to_cstring(text);
446 if(!(text_surface=TTF_RenderText_Blended(recv, ctext, color)))
447 {
448 fprintf(stderr, "SDL TFF error: %s\n", TTF_GetError());
449 exit(1);
450 }
451 else
452 return text_surface;
453 `}
454
455 # TODO reactivate fun below when updating libsdl_ttf to 2.0.10 or above
456 #fun outline: Int # TODO check to make inline/nitside only
457 #fun outline=(v: Int) is extern
458
459 #fun kerning: Bool is extern
460 #fun kerning=(v: Bool) is extern
461
462 # Maximum pixel height of all glyphs of this font.
463 fun height: Int `{
464 return TTF_FontHeight(recv);
465 `}
466
467 fun ascent: Int `{
468 return TTF_FontAscent(recv);
469 `}
470
471 fun descent: Int `{
472 return TTF_FontDescent(recv);
473 `}
474
475 # Get the recommended pixel height of a rendered line of text of the loaded font. This is usually larger than the Font.height.
476 fun line_skip: Int `{
477 return TTF_FontLineSkip(recv);
478 `}
479
480 # Return true is the font used fixed width for each char
481 fun is_fixed_width: Bool `{
482 return TTF_FontFaceIsFixedWidth(recv);
483 `}
484
485 # Return the family name of the font
486 fun family_name: nullable String import String.to_cstring, String.as nullable `{
487 char *fn = TTF_FontFaceFamilyName(recv);
488
489 if (fn == NULL)
490 return null_String();
491 else
492 return String_as_nullable(NativeString_to_s(fn));
493 `}
494
495 # Return the style name of the font
496 fun style_name: nullable String import String.to_cstring, String.as nullable `{
497 char *sn = TTF_FontFaceStyleName(recv);
498
499 if (sn == NULL)
500 return null_String();
501 else
502 return String_as_nullable(NativeString_to_s(sn));
503 `}
504
505 # Return the estimated width of a String if used with the current font
506 fun width_of(text: String): Int import NativeString.to_s `{
507 char *ctext = String_to_cstring(text);
508 int w;
509 if (TTF_SizeText(recv, ctext, &w, NULL))
510 {
511 fprintf(stderr, "SDL TFF error: %s\n", TTF_GetError());
512 exit(1);
513 }
514 else
515 return w;
516 `}
517 end
518
519 # Information on the SDL window
520 # Used in other modules to get window handle
521 extern class SDLSystemWindowManagerInfo `{SDL_SysWMinfo *`}
522
523 new `{
524 SDL_SysWMinfo *val = malloc(sizeof(SDL_SysWMinfo));
525
526 SDL_VERSION(&val->version);
527
528 if(SDL_GetWMInfo(val) <= 0) {
529 printf("Unable to get window handle");
530 return 0;
531 }
532
533 return val;
534 `}
535
536 # Returns the handle of this window on a X11 window system
537 fun x11_window_handle: Pointer `{
538 return (void*)recv->info.x11.window;
539 `}
540 end