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