1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # An example to test and demonstrate the `sdl2` lib with `image` and `events`
22 # Check for an error, then print and clear it
24 # Some errors are not fatal, so we ignore them at this level.
25 fun check_error
(loc
: String)
27 var error
= sys
.sdl
.error
.to_s
28 if not error
.is_empty
then
29 print
"at {loc}: {error}"
34 # Init `sdl2`, including video and events
35 sys
.sdl
.initialize
((new SDLInitFlags).video
)
39 sdl
.img
.initialize
((new SDLImgInitFlags).png
)
40 check_error
"img_init"
43 var window
= new SDLWindow("Window title!".to_cstring
, 800, 600, (new SDLWindowFlags).opengl
)
46 # Create a render, the suffested one
47 var renderer
= new SDLRenderer(window
, -1, (new SDLRendererFlags).accelerated
)
48 check_error
"renderer"
51 var surface
= new SDLSurface.load
("assets/fighter.png".to_cstring
)
53 assert not surface
.address_is_null
55 # Alternative code to load a BMP image without `sdl2::image`
57 # var surface = new SDLSurface.load_bmp("assets/fighter.bmp".to_cstring)
63 # Get a texture out of that surface
64 var texture
= new SDLTexture.from_surface
(renderer
, surface
)
67 # Allocate memory for reusable objects
68 var event
= new SDLEventBuffer.malloc
69 var src
= new SDLRect.nil
70 var dst
= new SDLRect(0, 0, 128, 128)
72 # Set the colors we will be using
73 var white
= new SDLColor(255, 255, 255, 255)
74 var green
= new SDLColor( 0, 255, 0, 255)
75 var spacy
= new SDLColor( 25, 25, 50, 255)
78 # Loop over events until we get a quit event
79 while event
.poll_event
do
80 var higher_event
= event
.to_event
81 if higher_event
isa SDLQuitEvent then
83 else if higher_event
isa SDLMouseButtonDownEvent then
84 # Update `dst` to be centered on the latest click
85 dst
.x
= higher_event
.x
- dst
.w
/2
86 dst
.y
= higher_event
.y
- dst
.h
/2
90 # Clear the screen with a spacy color
91 renderer
.draw_color
= spacy
94 # Draw the target box for the following `copy`
95 renderer
.draw_color
= green
96 renderer
.draw_rect dst
98 # Copy a texture to the screen
99 renderer
.draw_color
= white
100 renderer
.copy
(texture
, src
, dst
)
102 # Copy the back buffer to the screen
105 check_error
"present"