lib/gamnit: intro `simple_2d` and API for easy 2D games programming
[nit.git] / lib / gamnit / simple_2d.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Simple API for 2D games, based around `Sprite` and `App::update`
16 #
17 # Client programs should implement `App::update` to execute game logic and
18 # add instances of `Sprite` to `App::sprites` and `App::ui_sprites`.
19 # At each frame, all sprites are drawn to the screen.
20 #
21 # This system relies on two cameras `App::world_camera` and `App::ui_camera`.
22 #
23 # * `App::world_camera` applies a perspective effect to draw the game world.
24 # This camera is designed to be moved around to see the world as well as to zoom in and out.
25 # It is used to position the sprites in `App::sprites`.
26 #
27 # * `App::ui_camera` is a simple orthogonal camera to display UI objects.
28 # This camera should mostly be still, it can still move for chock effects and the like.
29 # It can be used to standardize the size of the UI across devices.
30 # It is used to position the sprites in `App::ui_sprites`.
31 #
32 # See the sample game at `examples/asteronits/`.
33 module simple_2d
34
35 import glesv2
36
37 import geometry::points_and_lines
38 import matrix::projection
39 import more_collections
40 import realtime
41
42 import gamnit
43 import gamnit::cameras
44 import gamnit::limit_fps
45
46 # Image to draw on screen
47 class Sprite
48
49 # Texture drawn to screen
50 var texture: Texture is writable
51
52 # Position of this sprite in world coordinates
53 var center: Point3d[Float] is writable
54
55 # Rotation on the Z axis
56 var rotation = 0.0 is writable
57
58 # Scale applied to this sprite
59 var scale = 1.0 is writable
60
61 # Transparency applied to the texture on draw
62 var alpha = 1.0 is writable
63
64 private fun draw
65 do
66 var simple_2d_program = app.simple_2d_program
67
68 glActiveTexture gl_TEXTURE0
69 glBindTexture(gl_TEXTURE_2D, texture.root.gl_texture)
70
71 simple_2d_program.translation.uniform(center.x, -center.y, center.z, 0.0)
72 simple_2d_program.color.uniform(1.0, 1.0, 1.0, alpha)
73 simple_2d_program.scale.uniform scale
74
75 simple_2d_program.use_texture.uniform true
76 simple_2d_program.texture.uniform 0
77 simple_2d_program.tex_coord.array(texture.texture_coords, 2)
78 simple_2d_program.coord.array(texture.vertices, 3)
79
80 simple_2d_program.rotation.uniform new Matrix.rotation(rotation, 0.0, 0.0, 1.0)
81
82 glDrawArrays(gl_TRIANGLE_STRIP, 0, 4)
83 end
84 end
85
86 redef class App
87 # Default graphic program to draw `sprites`
88 var simple_2d_program = new Simple2dProgram is lazy # TODO private
89
90 # Camera for world objects with perspective
91 #
92 # By default, the camera is configured to respect the resolution
93 # of the screen in world coordinates at `z == 0.0`.
94 var world_camera: EulerCamera is lazy do
95 var camera = new EulerCamera(app.display.as(not null))
96
97 # Aim for pixel resolution at level 0
98 camera.reset_height
99
100 return camera
101 end
102
103 # Camera for UI elements using an orthogonal view
104 var ui_camera: UICamera = new UICamera(app.display.as(not null)) is lazy
105
106 # Live sprites to draw in reference to `world_camera`
107 var sprites: Sequence[Sprite] = new List[Sprite]
108
109 # UI sprites to draw in reference to `ui_camera`, over world `sprites`
110 var ui_sprites: Sequence[Sprite] = new List[Sprite]
111
112 private var clock = new Clock
113
114 redef fun on_create
115 do
116 super
117
118 var display = display
119 assert display != null
120
121 var gl_error = glGetError
122 assert gl_error == gl_NO_ERROR else print gl_error
123
124 # Prepare program
125 var program = simple_2d_program
126 program.compile_and_link
127
128 var gamnit_error = program.error
129 assert gamnit_error == null else print_error gamnit_error
130
131 # Enable blending
132 gl.capabilities.blend.enable
133 glBlendFunc(gl_SRC_ALPHA, gl_ONE_MINUS_SRC_ALPHA)
134
135 # Enable depth test
136 gl.capabilities.depth_test.enable
137 glDepthFunc gl_LEQUAL
138 glDepthMask true
139
140 # Prepare viewport and background color
141 glViewport(0, 0, display.width, display.height)
142 glClearColor(0.0, 0.0, 0.0, 1.0)
143
144 gl_error = glGetError
145 assert gl_error == gl_NO_ERROR else print gl_error
146
147 # Prepare to draw
148 for tex in all_root_textures do
149 tex.load
150
151 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
152 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
153
154 gamnit_error = tex.error
155 assert gamnit_error == null else print_error gamnit_error
156 end
157
158 # Constant program values
159 program.use
160 program.coord.array_enabled = true
161 program.tex_coord.array_enabled = true
162
163 gl_error = glGetError
164 assert gl_error == gl_NO_ERROR else print gl_error
165 end
166
167 redef fun frame_core(display)
168 do
169 # Prepare to draw, clear buffers
170 glClear(gl_COLOR_BUFFER_BIT | gl_DEPTH_BUFFER_BIT)
171
172 # Check errors
173 var gl_error = glGetError
174 assert gl_error == gl_NO_ERROR else print gl_error
175
176 # Update game logic and set sprites
177 var dt = clock.lapse.to_f
178 update dt
179
180 # Draw and flip screen
181 # TODO optimize this draw to store constant values on the GPU
182
183 ## World sprites
184 simple_2d_program.use
185 simple_2d_program.mvp.uniform world_camera.mvp_matrix
186 for sprite in sprites do sprite.draw
187
188 ## Reset only the depth buffer
189 glClear gl_DEPTH_BUFFER_BIT
190
191 ## UI sprites
192 simple_2d_program.mvp.uniform ui_camera.mvp_matrix
193 for sprite in ui_sprites do sprite.draw
194 display.flip
195
196 # Check errors
197 gl_error = glGetError
198 assert gl_error == gl_NO_ERROR else print gl_error
199 end
200
201 # Main method to refine in clients to update game logic and `sprites`
202 fun update(dt: Float) do end
203
204 redef fun on_stop
205 do
206 # Clean up
207 simple_2d_program.delete
208
209 # Close gamnit
210 var display = display
211 if display != null then display.close
212 end
213 end
214
215 redef class Texture
216
217 # Vertices coordinates of the base geometry
218 private var vertices: Array[Float] is lazy do
219 var mod = 1.0
220 var w = width * mod
221 var h = height * mod
222 var a = [-0.5*w, -0.5*h, 0.0]
223 var b = [ 0.5*w, -0.5*h, 0.0]
224 var c = [-0.5*w, 0.5*h, 0.0]
225 var d = [ 0.5*w, 0.5*h, 0.0]
226
227 var vertices = new Array[Float]
228 for v in [c, d, a, b] do vertices.add_all v
229 return vertices
230 end
231
232 # Coordinates of this texture on the `root` texture, with `[0..1.0]`
233 private var texture_coords: Array[Float] is lazy do
234 var a = [offset_left, offset_bottom]
235 var b = [offset_right, offset_bottom]
236 var c = [offset_left, offset_top]
237 var d = [offset_right, offset_top]
238
239 var texture_coords = new Array[Float]
240 for v in [c, d, a, b] do texture_coords.add_all v
241 return texture_coords
242 end
243 end
244
245 # Graphic program to display simple models with a texture, translation, rotation and scale
246 class Simple2dProgram
247 super GamnitProgramFromSource
248
249 redef var vertex_shader_source = """
250 // Vertex coordinates
251 attribute vec4 coord;
252
253 // Vertex color tint
254 attribute vec4 color;
255
256 // Vertex translation
257 attribute vec4 translation;
258
259 // Vertex scaling
260 attribute float scale;
261
262 // Vertex coordinates on textures
263 attribute vec2 tex_coord;
264
265 // Model view projection matrix
266 uniform mat4 mvp;
267
268 // Rotation matrix
269 uniform mat4 rotation;
270
271 // Output for the fragment shader
272 varying vec4 v_color;
273 varying vec2 v_coord;
274
275 void main()
276 {
277 v_color = color;
278 gl_Position = (vec4(coord.xyz * scale, 1.0) * rotation + translation) * mvp;
279 v_coord = tex_coord;
280 }
281 """ @ glsl_vertex_shader
282
283 redef var fragment_shader_source = """
284 precision mediump float;
285
286 // Does this object use a texture?
287 uniform bool use_texture;
288
289 // Texture to apply on this object
290 uniform sampler2D texture;
291
292 // Input from the vertex shader
293 varying vec4 v_color;
294 varying vec2 v_coord;
295
296 void main()
297 {
298 if(use_texture) {
299 gl_FragColor = v_color * texture2D(texture, v_coord);
300 if (gl_FragColor.a == 0.0) discard;
301 } else {
302 gl_FragColor = v_color;
303 }
304 }
305 """ @ glsl_fragment_shader
306
307 # Vertices coordinates
308 var coord = attributes["coord"].as(AttributeVec4) is lazy
309
310 # Should this program use the texture `texture`?
311 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
312
313 # Visible texture unit
314 var texture = uniforms["texture"].as(UniformSampler2D) is lazy
315
316 # Coordinates on the textures, per vertex
317 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
318
319 # Color tint per vertex
320 var color = attributes["color"].as(AttributeVec4) is lazy
321
322 # Translation applied to each vertex
323 var translation = attributes["translation"].as(AttributeVec4) is lazy
324
325 # Rotation matrix
326 var rotation = uniforms["rotation"].as(UniformMat4) is lazy
327
328 # Scaling per vertex
329 var scale = attributes["scale"].as(AttributeFloat) is lazy
330
331 # Model view projection matrix
332 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
333 end
334
335 redef class Point3d[N]
336 # Get a new `Point3d[Float]` with an offset of each axis of `x, y, z`
337 fun offset(x, y, z: Numeric): Point3d[Float]
338 do
339 return new Point3d[Float](self.x.to_f+x.to_f, self.y.to_f+y.to_f, self.z.to_f+z.to_f)
340 end
341 end