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