6f9dea47aca13b41c9a6b346538fd2b58606962d
[nit.git] / lib / gamnit / flat.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 `contrib/asteronits/`.
33 module flat
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 fun alpha: Float do return tint[3]
63
64 # Transparency applied to the texture on draw
65 fun alpha=(value: Float) do tint[3] = value
66
67 # Tint applied to the texture on draw
68 #
69 # Require: `tint.length == 4`
70 var tint: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable
71
72 private fun draw
73 do
74 var simple_2d_program = app.simple_2d_program
75
76 glActiveTexture gl_TEXTURE0
77 glBindTexture(gl_TEXTURE_2D, texture.root.gl_texture)
78
79 simple_2d_program.translation.array_enabled = false
80 simple_2d_program.color.array_enabled = false
81 simple_2d_program.scale.array_enabled = false
82
83 simple_2d_program.translation.uniform(center.x, -center.y, center.z, 0.0)
84 simple_2d_program.color.uniform(tint[0], tint[1], tint[2], tint[3])
85 simple_2d_program.scale.uniform scale
86
87 simple_2d_program.use_texture.uniform true
88 simple_2d_program.texture.uniform 0
89 simple_2d_program.tex_coord.array(texture.texture_coords, 2)
90 simple_2d_program.coord.array(texture.vertices, 3)
91
92 simple_2d_program.rotation.uniform new Matrix.rotation(rotation, 0.0, 0.0, 1.0)
93
94 glDrawArrays(gl_TRIANGLE_STRIP, 0, 4)
95 end
96 end
97
98 redef class App
99 # Default graphic program to draw `sprites`
100 var simple_2d_program = new Simple2dProgram is lazy # TODO private
101
102 # Camera for world objects with perspective
103 #
104 # By default, the camera is configured to respect the resolution
105 # of the screen in world coordinates at `z == 0.0`.
106 var world_camera: EulerCamera is lazy do
107 var camera = new EulerCamera(app.display.as(not null))
108
109 # Aim for pixel resolution at level 0
110 camera.reset_height
111 camera.near = 100.0
112
113 return camera
114 end
115
116 # Camera for UI elements using an orthogonal view
117 var ui_camera: UICamera = new UICamera(app.display.as(not null)) is lazy
118
119 # Live sprites to draw in reference to `world_camera`
120 var sprites: Sequence[Sprite] = new List[Sprite]
121
122 # UI sprites to draw in reference to `ui_camera`, over world `sprites`
123 var ui_sprites: Sequence[Sprite] = new List[Sprite]
124
125 private var clock = new Clock
126
127 redef fun on_create
128 do
129 super
130
131 var display = display
132 assert display != null
133
134 var gl_error = glGetError
135 assert gl_error == gl_NO_ERROR else print gl_error
136
137 # Prepare program
138 var program = simple_2d_program
139 program.compile_and_link
140
141 var gamnit_error = program.error
142 assert gamnit_error == null else print_error gamnit_error
143
144 # Enable blending
145 gl.capabilities.blend.enable
146 glBlendFunc(gl_SRC_ALPHA, gl_ONE_MINUS_SRC_ALPHA)
147
148 # Enable depth test
149 gl.capabilities.depth_test.enable
150 glDepthFunc gl_LEQUAL
151 glDepthMask true
152
153 # Prepare viewport and background color
154 glViewport(0, 0, display.width, display.height)
155 glClearColor(0.0, 0.0, 0.0, 1.0)
156
157 gl_error = glGetError
158 assert gl_error == gl_NO_ERROR else print gl_error
159
160 # Prepare to draw
161 for tex in all_root_textures do
162 tex.load
163
164 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
165 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
166
167 gamnit_error = tex.error
168 assert gamnit_error == null else print_error gamnit_error
169 end
170 end
171
172 redef fun frame_core(display)
173 do
174 # Prepare to draw, clear buffers
175 glClear(gl_COLOR_BUFFER_BIT | gl_DEPTH_BUFFER_BIT)
176
177 # Check errors
178 var gl_error = glGetError
179 assert gl_error == gl_NO_ERROR else print gl_error
180
181 # Update game logic and set sprites
182 var dt = clock.lapse.to_f
183 update dt
184
185 # Draw and flip screen
186 frame_core_draw display
187 display.flip
188
189 # Check errors
190 gl_error = glGetError
191 assert gl_error == gl_NO_ERROR else print gl_error
192 end
193
194 # Draw the whole screen, all `glDraw...` calls should be executed here
195 protected fun frame_core_draw(display: GamnitDisplay)
196 do
197 frame_core_world_sprites display
198 frame_core_ui_sprites display
199 end
200
201 # Draw world sprites from `sprites`
202 protected fun frame_core_world_sprites(display: GamnitDisplay)
203 do
204 simple_2d_program.use
205
206 # Set constant configs
207 simple_2d_program.coord.array_enabled = true
208 simple_2d_program.tex_coord.array_enabled = true
209 simple_2d_program.color.array_enabled = false
210
211 # TODO optimize this draw to store constant values on the GPU
212 # World sprites
213 simple_2d_program.mvp.uniform world_camera.mvp_matrix
214 for sprite in sprites do sprite.draw
215 end
216
217 # Draw UI sprites from `ui_sprites`
218 protected fun frame_core_ui_sprites(display: GamnitDisplay)
219 do
220 simple_2d_program.use
221
222 # Set constant configs
223 simple_2d_program.coord.array_enabled = true
224 simple_2d_program.tex_coord.array_enabled = true
225 simple_2d_program.color.array_enabled = false
226
227 # Reset only the depth buffer
228 glClear gl_DEPTH_BUFFER_BIT
229
230 # UI sprites
231 simple_2d_program.mvp.uniform ui_camera.mvp_matrix
232 for sprite in ui_sprites do sprite.draw
233 end
234
235 # Main method to refine in clients to update game logic and `sprites`
236 fun update(dt: Float) do end
237
238 # Display `texture` as a splash screen
239 #
240 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
241 fun show_splash_screen(texture: Texture)
242 do
243 texture.load
244
245 ui_camera.reset_height 1080.0
246
247 var splash = new Sprite(texture, ui_camera.center)
248 ui_sprites.add splash
249
250 var display = display
251 assert display != null
252 glClear gl_COLOR_BUFFER_BIT
253 frame_core_ui_sprites display
254 display.flip
255
256 ui_sprites.remove splash
257 end
258
259 redef fun on_stop
260 do
261 # Clean up
262 simple_2d_program.delete
263
264 # Close gamnit
265 var display = display
266 if display != null then display.close
267 end
268 end
269
270 redef class Texture
271
272 # Vertices coordinates of the base geometry
273 private var vertices: Array[Float] is lazy do
274 var mod = 1.0
275 var w = width * mod
276 var h = height * mod
277 var a = [-0.5*w, -0.5*h, 0.0]
278 var b = [ 0.5*w, -0.5*h, 0.0]
279 var c = [-0.5*w, 0.5*h, 0.0]
280 var d = [ 0.5*w, 0.5*h, 0.0]
281
282 var vertices = new Array[Float]
283 for v in [c, d, a, b] do vertices.add_all v
284 return vertices
285 end
286
287 # Coordinates of this texture on the `root` texture, with `[0..1.0]`
288 private var texture_coords: Array[Float] is lazy do
289 var a = [offset_left, offset_bottom]
290 var b = [offset_right, offset_bottom]
291 var c = [offset_left, offset_top]
292 var d = [offset_right, offset_top]
293
294 var texture_coords = new Array[Float]
295 for v in [c, d, a, b] do texture_coords.add_all v
296 return texture_coords
297 end
298 end
299
300 # Graphic program to display simple models with a texture, translation, rotation and scale
301 class Simple2dProgram
302 super GamnitProgramFromSource
303
304 redef var vertex_shader_source = """
305 // Vertex coordinates
306 attribute vec4 coord;
307
308 // Vertex color tint
309 attribute vec4 color;
310
311 // Vertex translation
312 attribute vec4 translation;
313
314 // Vertex scaling
315 attribute float scale;
316
317 // Vertex coordinates on textures
318 attribute vec2 tex_coord;
319
320 // Model view projection matrix
321 uniform mat4 mvp;
322
323 // Rotation matrix
324 uniform mat4 rotation;
325
326 // Output for the fragment shader
327 varying vec4 v_color;
328 varying vec2 v_coord;
329
330 void main()
331 {
332 v_color = color;
333 gl_Position = (vec4(coord.xyz * scale, 1.0) * rotation + translation) * mvp;
334 v_coord = tex_coord;
335 }
336 """ @ glsl_vertex_shader
337
338 redef var fragment_shader_source = """
339 precision mediump float;
340
341 // Does this object use a texture?
342 uniform bool use_texture;
343
344 // Texture to apply on this object
345 uniform sampler2D texture;
346
347 // Input from the vertex shader
348 varying vec4 v_color;
349 varying vec2 v_coord;
350
351 void main()
352 {
353 if(use_texture) {
354 gl_FragColor = v_color * texture2D(texture, v_coord);
355 if (gl_FragColor.a == 0.0) discard;
356 } else {
357 gl_FragColor = v_color;
358 }
359 }
360 """ @ glsl_fragment_shader
361
362 # Vertices coordinates
363 var coord = attributes["coord"].as(AttributeVec4) is lazy
364
365 # Should this program use the texture `texture`?
366 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
367
368 # Visible texture unit
369 var texture = uniforms["texture"].as(UniformSampler2D) is lazy
370
371 # Coordinates on the textures, per vertex
372 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
373
374 # Color tint per vertex
375 var color = attributes["color"].as(AttributeVec4) is lazy
376
377 # Translation applied to each vertex
378 var translation = attributes["translation"].as(AttributeVec4) is lazy
379
380 # Rotation matrix
381 var rotation = uniforms["rotation"].as(UniformMat4) is lazy
382
383 # Scaling per vertex
384 var scale = attributes["scale"].as(AttributeFloat) is lazy
385
386 # Model view projection matrix
387 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
388 end
389
390 redef class Point3d[N]
391 # Get a new `Point3d[Float]` with an offset of each axis of `x, y, z`
392 fun offset(x, y, z: Numeric): Point3d[Float]
393 do
394 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)
395 end
396 end