gamnit: intro `camera_control` an abstraction of `accept_two_fingers_motion`
[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, built 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
25 # zoom in and out. 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
29 # and the like. It can be used to standardize the size of the UI across
30 # devices. It is used to position the sprites in `App::ui_sprites`.
31 #
32 # See the sample game at `contrib/asteronits/` and the basic project template
33 # at `lib/gamnit/examples/template_flat/`.
34 module flat
35
36 import glesv2
37 intrude import geometry::points_and_lines # For _x, _y and _z
38 import matrix::projection
39 import more_collections
40 import performance_analysis
41
42 import gamnit
43 import gamnit::cameras
44 import gamnit::limit_fps
45 import gamnit::camera_control
46
47 # Draw a `texture` at `center`
48 #
49 # An instance of `Sprite` can only belong to a single `SpriteSet` at
50 # a time. The on screen position depends on the camera associated
51 # to the `SpriteSet`.
52 class Sprite
53
54 # Texture drawn to screen
55 var texture: Texture is writable(texture_direct=)
56
57 # Texture drawn to screen
58 fun texture=(value: Texture)
59 do
60 if isset _texture and value != texture then
61 needs_update
62 if value.root != texture.root then needs_remap
63 end
64 texture_direct = value
65 end
66
67 # Center position of this sprite in world coordinates
68 var center: Point3d[Float] is writable(center_direct=), noautoinit
69
70 # Center position of this sprite in world coordinates
71 fun center=(value: Point3d[Float]) is autoinit do
72 if isset _center and value != center then
73 needs_update
74 center.sprites_remove self
75 end
76
77 value.sprites_add self
78 center_direct = value
79 end
80
81 # Rotation on the Z axis, positive values go counterclockwise
82 var rotation = 0.0 is writable(rotation_direct=)
83
84 # Rotation on the Z axis, positive values go counterclockwise
85 fun rotation=(value: Float)
86 do
87 if isset _rotation and value != rotation then needs_update
88 rotation_direct = value
89 end
90
91 # Mirror `texture` horizontally, inverting each pixel on the X axis
92 var invert_x = false is writable(invert_x_direct=)
93
94 # Mirror `texture` horizontally, inverting each pixel on the X axis
95 fun invert_x=(value: Bool)
96 do
97 if isset _invert_x and value != invert_x then needs_update
98 invert_x_direct = value
99 end
100
101 # Scale applied to this sprite
102 #
103 # The default size of `self` depends on the size in pixels of `texture`.
104 var scale = 1.0 is writable(scale_direct=)
105
106 # Scale applied to this sprite, see `scale`
107 fun scale=(value: Float)
108 do
109 if isset _scale and value != scale then needs_update
110 scale_direct = value
111 end
112
113 # Red tint applied to `texture` on draw
114 fun red: Float do return tint[0]
115
116 # Red tint applied to `texture` on draw
117 fun red=(value: Float)
118 do
119 if isset _tint and value != red then needs_update
120 tint[0] = value
121 end
122
123 # Green tint applied to `texture` on draw
124 fun green: Float do return tint[1]
125
126 # Green tint applied to `texture` on draw
127 fun green=(value: Float)
128 do
129 if isset _tint and value != green then needs_update
130 tint[1] = value
131 end
132
133 # Blue tint applied to `texture` on draw
134 fun blue: Float do return tint[2]
135
136 # Blue tint applied to `texture` on draw
137 fun blue=(value: Float)
138 do
139 if isset _tint and value != blue then needs_update
140 tint[2] = value
141 end
142
143 # Transparency applied to `texture` on draw
144 fun alpha: Float do return tint[3]
145
146 # Transparency applied to `texture` on draw
147 fun alpha=(value: Float)
148 do
149 if isset _tint and value != alpha then needs_update
150 tint[3] = value
151 end
152
153 # Tint applied to `texture` on draw
154 #
155 # Alternative to the accessors `red, green, blue & alpha`.
156 # Changes inside the array do not automatically set `needs_update`.
157 #
158 # Require: `tint.length == 4`
159 var tint: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable(tint_direct=)
160
161 # Tint applied to `texture` on draw, see `tint`
162 fun tint=(value: Array[Float])
163 do
164 if isset _tint and value != tint then needs_update
165 tint_direct = value
166 end
167
168 # Is this sprite static and added in bulk?
169 #
170 # Set to `true` to give a hint to the framework that this sprite won't
171 # change often and that it is added in bulk with other static sprites.
172 # This value can be ignored in the prototyping phase of a game and
173 # added only when better performance are needed.
174 var static = false is writable(static_direct=)
175
176 # Is this sprite static and added in bulk? see `static`
177 fun static=(value: Bool)
178 do
179 if isset _static and value != static then needs_remap
180 static_direct = value
181 end
182
183 # Request an update on the CPU
184 #
185 # This is called automatically on modification of any value of `Sprite`.
186 # However, it can still be set manually if a modification can't be
187 # detected or by subclasses.
188 fun needs_update
189 do
190 var c = context
191 if c != null then c.sprites_to_update.add self
192 end
193
194 # Request a resorting of this sprite in its sprite list
195 #
196 # Resorting is required when `static` or the root of `texture` changes.
197 # This is called automatically when such changes are detected.
198 # However, it can still be set manually if a modification can't be
199 # detected or by subclasses.
200 fun needs_remap
201 do
202 var l = sprite_set
203 if l != null then l.sprites_to_remap.add self
204 end
205
206 # Current context to which `self` was sorted
207 private var context: nullable SpriteContext = null
208
209 # Current context to which `self` belongs
210 private var sprite_set: nullable SpriteSet = null
211 end
212
213 redef class App
214 # Default graphic program to draw `sprites`
215 private var simple_2d_program = new Simple2dProgram is lazy
216
217 # Camera for world `sprites` and `depth::actors` with perspective
218 #
219 # By default, the camera is configured to respect the resolution
220 # of the screen in world coordinates at `z == 0.0`.
221 var world_camera: EulerCamera is lazy do
222 var camera = new EulerCamera(app.display.as(not null))
223
224 # Aim for pixel resolution at level 0
225 camera.reset_height
226 camera.near = 100.0
227
228 return camera
229 end
230
231 # Camera for `ui_sprites` using an orthogonal view
232 var ui_camera: UICamera = new UICamera(app.display.as(not null)) is lazy
233
234 # World sprites to draw as seen by `world_camera`
235 var sprites: Set[Sprite] = new SpriteSet
236
237 # UI sprites to draw as seen by `ui_camera`, drawn over world `sprites`
238 var ui_sprites: Set[Sprite] = new SpriteSet
239
240 # Main method to refine in clients to update game logic and `sprites`
241 fun update(dt: Float) do end
242
243 # Display `texture` as a splash screen
244 #
245 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
246 fun show_splash_screen(texture: Texture)
247 do
248 texture.load
249
250 ui_camera.reset_height 1080.0
251
252 var splash = new Sprite(texture, ui_camera.center)
253 ui_sprites.add splash
254
255 var display = display
256 assert display != null
257 glClear gl_COLOR_BUFFER_BIT
258 frame_core_ui_sprites display
259 display.flip
260
261 ui_sprites.remove splash
262 end
263
264 # ---
265 # Support and implementation
266
267 # Main clock used to count each frame `dt`, lapsed for `update` only
268 private var clock = new Clock is lazy
269
270 # Performance clock to for `frame_core_draw` operations
271 private var perf_clock_main = new Clock
272
273 # Second performance clock for smaller operations
274 private var perf_clock_sprites = new Clock is lazy
275
276 redef fun on_create
277 do
278 super
279
280 var display = display
281 assert display != null
282
283 var gl_error = glGetError
284 assert gl_error == gl_NO_ERROR else print_error gl_error
285
286 # Prepare program
287 var program = simple_2d_program
288 program.compile_and_link
289
290 var gamnit_error = program.error
291 assert gamnit_error == null else print_error gamnit_error
292
293 # Enable blending
294 gl.capabilities.blend.enable
295 glBlendFunc(gl_SRC_ALPHA, gl_ONE_MINUS_SRC_ALPHA)
296
297 # Enable depth test
298 gl.capabilities.depth_test.enable
299 glDepthFunc gl_LEQUAL
300 glDepthMask true
301
302 # Prepare viewport and background color
303 glViewport(0, 0, display.width, display.height)
304 glClearColor(0.0, 0.0, 0.0, 1.0)
305
306 gl_error = glGetError
307 assert gl_error == gl_NO_ERROR else print_error gl_error
308
309 # Prepare to draw
310 for tex in all_root_textures do
311 tex.load
312 gamnit_error = tex.error
313 if gamnit_error != null then print_error gamnit_error
314
315 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MIN_FILTER, gl_LINEAR)
316 glTexParameteri(gl_TEXTURE_2D, gl_TEXTURE_MAG_FILTER, gl_LINEAR)
317 end
318 end
319
320 redef fun on_stop
321 do
322 # Clean up
323 simple_2d_program.delete
324
325 # Close gamnit
326 var display = display
327 if display != null then display.close
328 end
329
330 redef fun frame_core(display)
331 do
332 # Prepare to draw, clear buffers
333 glClear(gl_COLOR_BUFFER_BIT | gl_DEPTH_BUFFER_BIT)
334
335 # Check errors
336 var gl_error = glGetError
337 assert gl_error == gl_NO_ERROR else print_error gl_error
338
339 # Update game logic and set sprites
340 perf_clock_main.lapse
341 var dt = clock.lapse.to_f
342 update dt
343 sys.perfs["gamnit flat update client"].add perf_clock_main.lapse
344
345 # Draw and flip screen
346 frame_core_draw display
347 display.flip
348
349 # Check errors
350 gl_error = glGetError
351 assert gl_error == gl_NO_ERROR else print_error gl_error
352 end
353
354 # Draw the whole screen, all `glDraw...` calls should be executed here
355 protected fun frame_core_draw(display: GamnitDisplay)
356 do
357 perf_clock_main.lapse
358
359 frame_core_world_sprites display
360 perfs["gamnit flat world_sprites"].add perf_clock_main.lapse
361
362 frame_core_ui_sprites display
363 perfs["gamnit flat ui_sprites"].add perf_clock_main.lapse
364 end
365
366 private fun frame_core_sprites(display: GamnitDisplay, sprite_set: SpriteSet, camera: Camera)
367 do
368 var simple_2d_program = app.simple_2d_program
369 simple_2d_program.use
370 simple_2d_program.mvp.uniform camera.mvp_matrix
371
372 # draw
373 sprite_set.draw
374 end
375
376 # Draw world sprites from `sprites`
377 protected fun frame_core_world_sprites(display: GamnitDisplay)
378 do
379 frame_core_sprites(display, sprites.as(SpriteSet), world_camera)
380 end
381
382 # Draw UI sprites from `ui_sprites`
383 protected fun frame_core_ui_sprites(display: GamnitDisplay)
384 do
385 # Reset only the depth buffer
386 glClear gl_DEPTH_BUFFER_BIT
387
388 frame_core_sprites(display, ui_sprites.as(SpriteSet), ui_camera)
389 end
390 end
391
392 redef class Texture
393
394 # Vertices coordinates of the base geometry
395 #
396 # Defines the default width and height of related sprites.
397 private var vertices: Array[Float] is lazy do
398 var w = width
399 var h = height
400 return [-0.5*w, 0.5*h, 0.0,
401 0.5*w, 0.5*h, 0.0,
402 -0.5*w, -0.5*h, 0.0,
403 0.5*w, -0.5*h, 0.0]
404 end
405
406 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
407 private var texture_coords: Array[Float] is lazy do
408 var l = offset_left
409 var r = offset_right
410 var b = offset_bottom
411 var t = offset_top
412 return [l, t,
413 r, t,
414 l, b,
415 r, b]
416 end
417
418 # Coordinates of this texture on the `root` texture, inverting the X axis
419 private var texture_coords_invert_x: Array[Float] is lazy do
420 var l = offset_left
421 var r = offset_right
422 var b = offset_bottom
423 var t = offset_top
424 return [r, t,
425 l, t,
426 r, b,
427 l, b]
428 end
429 end
430
431 # Graphic program to display simple models with a texture, translation, rotation and scale
432 private class Simple2dProgram
433 super GamnitProgramFromSource
434
435 redef var vertex_shader_source = """
436 // Vertex coordinates
437 attribute vec4 coord;
438
439 // Vertex color tint
440 attribute vec4 color;
441
442 // Vertex translation
443 attribute vec4 translation;
444
445 // Vertex scaling
446 attribute float scale;
447
448 // Vertex coordinates on textures
449 attribute vec2 tex_coord;
450
451 // Model view projection matrix
452 uniform mat4 mvp;
453
454 // Rotation matrix
455 attribute vec4 rotation_row0;
456 attribute vec4 rotation_row1;
457 attribute vec4 rotation_row2;
458 attribute vec4 rotation_row3;
459
460 mat4 rotation()
461 {
462 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
463 }
464
465 // Output to the fragment shader
466 varying vec4 v_color;
467 varying vec2 v_coord;
468
469 void main()
470 {
471 gl_Position = (vec4(coord.xyz * scale, 1.0) * rotation() + translation)* mvp;
472 v_color = color;
473 v_coord = tex_coord;
474 }
475 """ @ glsl_vertex_shader
476
477 redef var fragment_shader_source = """
478 precision mediump float;
479
480 // Does this object use a texture?
481 uniform bool use_texture;
482
483 // Texture to apply on this object
484 uniform sampler2D texture0;
485
486 // Input from the vertex shader
487 varying vec4 v_color;
488 varying vec2 v_coord;
489
490 void main()
491 {
492 if(use_texture) {
493 gl_FragColor = v_color * texture2D(texture0, v_coord);
494 if (gl_FragColor.a <= 0.1) discard;
495 } else {
496 gl_FragColor = v_color;
497 }
498 }
499 """ @ glsl_fragment_shader
500
501 # Vertices coordinates
502 var coord = attributes["coord"].as(AttributeVec4) is lazy
503
504 # Should this program use the texture `texture`?
505 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
506
507 # Visible texture unit
508 var texture = uniforms["texture0"].as(UniformSampler2D) is lazy
509
510 # Coordinates on the textures, per vertex
511 var tex_coord = attributes["tex_coord"].as(AttributeVec2) is lazy
512
513 # Color tint per vertex
514 var color = attributes["color"].as(AttributeVec4) is lazy
515
516 # Translation applied to each vertex
517 var translation = attributes["translation"].as(AttributeVec4) is lazy
518
519 # Rotation matrix, row 0
520 var rotation_row0 = attributes["rotation_row0"].as(AttributeVec4) is lazy
521
522 # Rotation matrix, row 1
523 var rotation_row1 = attributes["rotation_row1"].as(AttributeVec4) is lazy
524
525 # Rotation matrix, row 2
526 var rotation_row2 = attributes["rotation_row2"].as(AttributeVec4) is lazy
527
528 # Rotation matrix, row 3
529 var rotation_row3 = attributes["rotation_row3"].as(AttributeVec4) is lazy
530
531 # Scaling per vertex
532 var scale = attributes["scale"].as(AttributeFloat) is lazy
533
534 # Model view projection matrix
535 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
536 end
537
538 redef class Point3d[N]
539 # Get a new `Point3d[Float]` with an offset of each axis of `x, y, z`
540 fun offset(x, y, z: Numeric): Point3d[Float]
541 do
542 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)
543 end
544
545 # ---
546 # Associate each point to its sprites
547
548 private var sprites: nullable Array[Sprite] = null
549
550 private fun sprites_add(sprite: Sprite)
551 do
552 var sprites = sprites
553 if sprites == null then
554 sprites = new Array[Sprite]
555 self.sprites = sprites
556 end
557 sprites.add sprite
558 end
559
560 private fun sprites_remove(sprite: Sprite)
561 do
562 var sprites = sprites
563 assert sprites != null
564 sprites.remove sprite
565 end
566
567 # ---
568 # Notify `sprites` on attribute modification
569
570 private fun needs_update
571 do
572 var sprites = sprites
573 if sprites != null then for s in sprites do s.needs_update
574 end
575
576 redef fun x=(v)
577 do
578 if isset _x and v != x then needs_update
579 super
580 end
581
582 redef fun y=(v)
583 do
584 if isset _y and v != y then needs_update
585 super
586 end
587
588 redef fun z=(v)
589 do
590 if isset _z and v != z then needs_update
591 super
592 end
593 end
594
595 # Set of sprites sorting them into different `SpriteContext`
596 private class SpriteSet
597 super HashSet[Sprite]
598
599 # Map texture then static vs dynamic to a `SpriteContext`
600 var contexts_map = new HashMap2[GamnitRootTexture, Bool, SpriteContext]
601
602 # Contexts in `contexts_map`
603 var contexts_items = new Array[SpriteContext]
604
605 # Sprites needing resorting in `contexts_map`
606 var sprites_to_remap = new Array[Sprite]
607
608 # Add a sprite to the appropriate context
609 fun map_sprite(sprite: Sprite)
610 do
611 assert sprite.context == null else print_error "Sprite {sprite} belongs to another SpriteSet"
612
613 var texture = sprite.texture.root
614 var context = contexts_map[texture, sprite.static]
615
616 if context == null then
617 var usage = if sprite.static then gl_STATIC_DRAW else gl_DYNAMIC_DRAW
618 context = new SpriteContext(texture, usage)
619
620 contexts_map[texture, sprite.static] = context
621 contexts_items.add context
622 end
623
624 context.sprites.add sprite
625 context.sprites_to_update.add sprite
626
627 sprite.context = context
628 sprite.sprite_set = self
629 end
630
631 # Remove a sprite from its context
632 fun unmap_sprite(sprite: Sprite)
633 do
634 var context = sprite.context
635 assert context != null
636 context.sprites.remove sprite
637
638 sprite.context = null
639 sprite.sprite_set = null
640 end
641
642 # Draw all sprites by all contexts
643 fun draw
644 do
645 for sprite in sprites_to_remap do
646 unmap_sprite sprite
647 map_sprite sprite
648 end
649 sprites_to_remap.clear
650
651 for context in contexts_items do context.draw
652 end
653
654 redef fun add(e)
655 do
656 if contexts_items.has(e.context) then return
657 map_sprite e
658 super
659 end
660
661 redef fun remove(e)
662 do
663 super
664 if e isa Sprite then unmap_sprite e
665 end
666
667 redef fun remove_all(e)
668 do
669 if not has(e) then return
670 remove e
671 end
672
673 redef fun clear
674 do
675 super
676 for c in contexts_items do c.destroy
677 contexts_map.clear
678 contexts_items.clear
679 end
680 end
681
682 # Context for calls to `glDrawElements`
683 #
684 # Each context has only one `texture` and `usage`, but many sprites.
685 private class SpriteContext
686
687 # ---
688 # Context config and state
689
690 # Only root texture drawn by this context
691 var texture: nullable GamnitRootTexture
692
693 # OpenGL ES usage of `buffer_array` and `buffer_element`
694 var usage: GLBufferUsage
695
696 # Sprites drawn by this context
697 var sprites = new GroupedArray[Sprite]
698
699 # Sprites to update since last `draw`
700 var sprites_to_update = new Set[Sprite]
701
702 # Sprites that have been update and for which `needs_update` can be set to false
703 var updated_sprites = new Array[Sprite]
704
705 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
706 #
707 # Require: `resize_ratio >= 1.0`
708 var resize_ratio = 1.2
709
710 # ---
711 # OpenGL ES data
712
713 # OpenGL ES buffer name for vertex data
714 var buffer_array: Int = -1
715
716 # OpenGL ES buffer name for indices
717 var buffer_element: Int = -1
718
719 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
720 var buffer_capacity = 0
721
722 # C buffers used to pass the data of a single sprite
723 var local_data_buffer = new GLfloatArray(float_per_vertex*4) is lazy
724 var local_indices_buffer = new CUInt16Array(indices_per_sprite) is lazy
725
726 # ---
727 # Constants
728
729 # Number of GL_FLOAT per vertex of `Simple2dProgram`
730 var float_per_vertex: Int is lazy do
731 # vec4 translation, vec4 color, vec4 coord,
732 # float scale, vec2 tex_coord, vec4 rotation_row*
733 return 4 + 4 + 4 +
734 1 + 2 + 4*4
735 end
736
737 # Number of bytes per vertex of `Simple2dProgram`
738 var bytes_per_vertex: Int is lazy do
739 var fs = 4 # sizeof(GL_FLOAT)
740 return fs * float_per_vertex
741 end
742
743 # Number of bytes per sprite
744 var bytes_per_sprite: Int is lazy do return bytes_per_vertex * 4
745
746 # Number of vertex indices per sprite draw call (2 triangles)
747 var indices_per_sprite = 6
748
749 # ---
750 # Main services
751
752 # Allocate `buffer_array` and `buffer_element`
753 fun prepare
754 do
755 var bufs = glGenBuffers(2)
756 buffer_array = bufs[0]
757 buffer_element = bufs[1]
758
759 var gl_error = glGetError
760 assert gl_error == gl_NO_ERROR else print_error gl_error
761 end
762
763 # Destroy `buffer_array` and `buffer_element`
764 fun destroy
765 do
766 glDeleteBuffers([buffer_array, buffer_element])
767 var gl_error = glGetError
768 assert gl_error == gl_NO_ERROR else print_error gl_error
769
770 buffer_array = -1
771 buffer_element = -1
772 end
773
774 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
775 fun resize
776 do
777 app.perf_clock_sprites.lapse
778
779 # Allocate a bit more space
780 var capacity = (sprites.capacity.to_f * resize_ratio).to_i
781
782 var array_bytes = capacity * bytes_per_sprite
783 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
784 assert glIsBuffer(buffer_array)
785 glBufferData(gl_ARRAY_BUFFER, array_bytes, new Pointer.nul, usage)
786 var gl_error = glGetError
787 assert gl_error == gl_NO_ERROR else print_error gl_error
788
789 # GL_TRIANGLES 6 vertices * sprite
790 var n_indices = capacity * indices_per_sprite
791 var ius = 2 # sizeof(GL_UNSIGNED_SHORT)
792 var element_bytes = n_indices * ius
793 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
794 assert glIsBuffer(buffer_element)
795 glBufferData(gl_ELEMENT_ARRAY_BUFFER, element_bytes, new Pointer.nul, usage)
796 gl_error = glGetError
797 assert gl_error == gl_NO_ERROR else print_error gl_error
798
799 buffer_capacity = capacity
800
801 sys.perfs["gamnit flat gpu resize"].add app.perf_clock_sprites.lapse
802 end
803
804 # Update GPU data of `sprite`
805 fun update_sprite(sprite: Sprite)
806 do
807 var sprite_index = sprites.index_of(sprite)
808 if sprite_index == -1 then return
809
810 # Vertices data
811
812 var data = local_data_buffer
813 var o = 0
814 for v in [0..4[ do
815 # vec4 translation
816 data[o+ 0] = sprite.center.x
817 data[o+ 1] = sprite.center.y
818 data[o+ 2] = sprite.center.z
819 data[o+ 3] = 0.0
820
821 # vec4 color
822 data[o+ 4] = sprite.tint[0]
823 data[o+ 5] = sprite.tint[1]
824 data[o+ 6] = sprite.tint[2]
825 data[o+ 7] = sprite.tint[3]
826
827 # float scale
828 data[o+ 8] = sprite.scale
829
830 # vec4 coord
831 data[o+ 9] = sprite.texture.vertices[v*3+0]
832 data[o+10] = sprite.texture.vertices[v*3+1]
833 data[o+11] = sprite.texture.vertices[v*3+2]
834 data[o+12] = 0.0
835
836 # vec2 tex_coord
837 var texture = texture
838 if texture != null then
839 var tc = if sprite.invert_x then
840 sprite.texture.texture_coords_invert_x
841 else sprite.texture.texture_coords
842 data[o+13] = tc[v*2+0]
843 data[o+14] = tc[v*2+1]
844 end
845
846 # mat4 rotation
847 var rot
848 if sprite.rotation == 0.0 then
849 # Cache the matrix at no rotation
850 rot = once new Matrix.identity(4)
851 else
852 rot = new Matrix.rotation(sprite.rotation, 0.0, 0.0, 1.0)
853 end
854 data.fill_from(rot.items, o+15)
855
856 o += float_per_vertex
857 end
858
859 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
860 glBufferSubData(gl_ARRAY_BUFFER, sprite_index*bytes_per_sprite, bytes_per_sprite, data.native_array)
861
862 var gl_error = glGetError
863 assert gl_error == gl_NO_ERROR else print_error gl_error
864
865 # Element / indices
866 #
867 # 0--1
868 # | /|
869 # |/ |
870 # 2--3
871
872 var indices = local_indices_buffer
873 var io = sprite_index*4
874 indices[0] = io+0
875 indices[1] = io+2
876 indices[2] = io+1
877 indices[3] = io+1
878 indices[4] = io+2
879 indices[5] = io+3
880
881 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
882 glBufferSubData(gl_ELEMENT_ARRAY_BUFFER, sprite_index*6*2, 6*2, indices.native_array)
883
884 gl_error = glGetError
885 assert gl_error == gl_NO_ERROR else print_error gl_error
886 end
887
888 # Draw all `sprites`
889 #
890 # Call `resize` and `update_sprite` as needed before actual draw operation.
891 #
892 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
893 fun draw
894 do
895 if buffer_array == -1 then prepare
896
897 assert buffer_array > 0 and buffer_element > 0 else
898 print_error "Internal error: {self} was destroyed"
899 end
900
901 # Setup
902 glBindBuffer(gl_ARRAY_BUFFER, buffer_array)
903 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, buffer_element)
904
905 # Resize GPU buffers?
906 if sprites.capacity > buffer_capacity then
907 # Try to defragment first
908 var moved = sprites.defragment
909
910 if sprites.capacity > buffer_capacity then
911 # Defragmentation wasn't enough, grow
912 resize
913
914 # We must update everything
915 for s in sprites.items do if s != null then sprites_to_update.add s
916 else
917 # Just update the moved sprites
918 for s in moved do sprites_to_update.add s
919 end
920 else if sprites.available.not_empty then
921 # Defragment a bit anyway
922 # TODO defrag only when there's time left on a frame
923 var moved = sprites.defragment(1)
924 for s in moved do sprites_to_update.add s
925 end
926
927 # Update GPU sprites data
928 if sprites_to_update.not_empty then
929 app.perf_clock_sprites.lapse
930
931 for sprite in sprites_to_update do update_sprite(sprite)
932 sprites_to_update.clear
933
934 sys.perfs["gamnit flat gpu update"].add app.perf_clock_sprites.lapse
935 end
936
937 # Update uniforms specific to this context
938 var texture = texture
939 app.simple_2d_program.use_texture.uniform texture != null
940 if texture != null then
941 glActiveTexture gl_TEXTURE0
942 glBindTexture(gl_TEXTURE_2D, texture.gl_texture)
943 app.simple_2d_program.texture.uniform 0
944 end
945 var gl_error = glGetError
946 assert gl_error == gl_NO_ERROR else print_error gl_error
947
948 # Configure attributes, in order:
949 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*
950 var offset = 0
951 var p = app.simple_2d_program
952 var sizeof_gl_float = 4 # sizeof(GL_FLOAT)
953
954 var size = 4 # Number of floats
955 glEnableVertexAttribArray p.translation.location
956 glVertexAttribPointeri(p.translation.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
957 offset += size * sizeof_gl_float
958 gl_error = glGetError
959 assert gl_error == gl_NO_ERROR else print_error gl_error
960
961 size = 4
962 glEnableVertexAttribArray p.color.location
963 glVertexAttribPointeri(p.color.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
964 offset += size * sizeof_gl_float
965 gl_error = glGetError
966 assert gl_error == gl_NO_ERROR else print_error gl_error
967
968 size = 1
969 glEnableVertexAttribArray p.scale.location
970 glVertexAttribPointeri(p.scale.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
971 offset += size * sizeof_gl_float
972 gl_error = glGetError
973 assert gl_error == gl_NO_ERROR else print_error gl_error
974
975 size = 4
976 glEnableVertexAttribArray p.coord.location
977 glVertexAttribPointeri(p.coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
978 offset += size * sizeof_gl_float
979 gl_error = glGetError
980 assert gl_error == gl_NO_ERROR else print_error gl_error
981
982 size = 2
983 glEnableVertexAttribArray p.tex_coord.location
984 glVertexAttribPointeri(p.tex_coord.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
985 offset += size * sizeof_gl_float
986 gl_error = glGetError
987 assert gl_error == gl_NO_ERROR else print_error gl_error
988
989 size = 4
990 for r in [p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3] do
991 if r.is_active then
992 glEnableVertexAttribArray r.location
993 glVertexAttribPointeri(r.location, size, gl_FLOAT, false, bytes_per_vertex, offset)
994 end
995 offset += size * sizeof_gl_float
996 gl_error = glGetError
997 assert gl_error == gl_NO_ERROR else print_error gl_error
998 end
999
1000 # Actual draw
1001 for s in sprites.starts, e in sprites.ends do
1002 var l = e-s
1003 glDrawElementsi(gl_TRIANGLES, l*indices_per_sprite, gl_UNSIGNED_SHORT, 2*s*indices_per_sprite)
1004 gl_error = glGetError
1005 assert gl_error == gl_NO_ERROR else print_error gl_error
1006 end
1007
1008 # Take down
1009 for attr in [p.translation, p.color, p.scale, p.coord, p.tex_coord,
1010 p.rotation_row0, p.rotation_row1, p.rotation_row2, p.rotation_row3: Attribute] do
1011 if not attr.is_active then continue
1012 glDisableVertexAttribArray(attr.location)
1013 gl_error = glGetError
1014 assert gl_error == gl_NO_ERROR else print_error gl_error
1015 end
1016
1017 glBindBuffer(gl_ARRAY_BUFFER, 0)
1018 glBindBuffer(gl_ELEMENT_ARRAY_BUFFER, 0)
1019 gl_error = glGetError
1020 assert gl_error == gl_NO_ERROR else print_error gl_error
1021 end
1022 end
1023
1024 # Representation of sprite data on the GPU
1025 #
1026 # The main purpose of this class is to optimize the use of contiguous
1027 # space in GPU memory. Each contiguous memory block can be drawn in a
1028 # single call. The starts index of each block is kept by `starts,
1029 # and the end + 1 by `ends`.
1030 #
1031 # The data can be compressed by a call to `defragment`.
1032 #
1033 # ~~~
1034 # var array = new GroupedArray[String]
1035 # assert array.to_s == ""
1036 #
1037 # array.add "a"
1038 # array.add "b"
1039 # array.add "c"
1040 # array.add "d"
1041 # array.add "e"
1042 # array.add "f"
1043 # assert array.to_s == "[a,b,c,d,e,f]"
1044 # assert array.capacity == 6
1045 #
1046 # array.remove "a"
1047 # assert array.to_s == "[b,c,d,e,f]"
1048 #
1049 # array.remove "b"
1050 # assert array.to_s == "[c,d,e,f]"
1051 #
1052 # array.remove "f"
1053 # assert array.to_s == "[c,d,e]"
1054 #
1055 # array.remove "d"
1056 # assert array.to_s == "[c][e]"
1057 #
1058 # array.add "A"
1059 # assert array.to_s == "[A][c][e]"
1060 #
1061 # array.add "B"
1062 # assert array.to_s == "[A,B,c][e]"
1063 #
1064 # array.remove "e"
1065 # assert array.to_s == "[A,B,c]"
1066 #
1067 # array.add "D"
1068 # assert array.to_s == "[A,B,c,D]"
1069 #
1070 # array.add "E"
1071 # assert array.to_s == "[A,B,c,D,E]"
1072 # assert array.capacity == 5
1073 # assert array.length == 5
1074 #
1075 # array.remove "A"
1076 # array.remove "B"
1077 # array.remove "c"
1078 # array.remove "D"
1079 # array.remove "E"
1080 # assert array.to_s == ""
1081 #
1082 # array.add "a"
1083 # assert array.to_s == "[a]"
1084 # ~~~
1085 private class GroupedArray[E]
1086
1087 # Memory with actual objects, and null in empty slots
1088 var items = new Array[nullable E]
1089
1090 # Number of items in the array
1091 var length = 0
1092
1093 # Number of item slots in the array
1094 fun capacity: Int do return items.length
1095
1096 # Index of `item`
1097 fun index_of(item: E): Int do return items.index_of(item)
1098
1099 # List of available slots
1100 var available = new MinHeap[Int].default
1101
1102 # Start index of filled chunks
1103 var starts = new List[Int]
1104
1105 # Index of the spots after filled chunks
1106 var ends = new List[Int]
1107
1108 # Add `item` to the first available slot
1109 fun add(item: E)
1110 do
1111 length += 1
1112
1113 if available.not_empty then
1114 # starts & ends can't be empty
1115
1116 var i = available.take
1117 items[i] = item
1118
1119 if i == starts.first - 1 then
1120 # slot 0 free, 1 taken
1121 starts.first -= 1
1122 else if i == 0 then
1123 # slot 0 and more free
1124 starts.unshift 0
1125 ends.unshift 1
1126 else if starts.length >= 2 and ends.first + 1 == starts[1] then
1127 # merge 2 chunks
1128 ends.remove_at 0
1129 starts.remove_at 1
1130 else
1131 # at end of first chunk
1132 ends.first += 1
1133 end
1134 return
1135 end
1136
1137 items.add item
1138 if ends.is_empty then
1139 starts.add 0
1140 ends.add 1
1141 else ends.last += 1
1142 end
1143
1144 # Remove the first instance of `item`
1145 fun remove(item: E)
1146 do
1147 var i = items.index_of(item)
1148 assert i != -1
1149 length -= 1
1150 items[i] = null
1151
1152 var ii = 0
1153 for s in starts, e in ends do
1154 if s <= i and i < e then
1155 if s == e-1 then
1156 # single item chunk
1157 starts.remove_at ii
1158 ends.remove_at ii
1159
1160 if starts.is_empty then
1161 items.clear
1162 available.clear
1163 return
1164 end
1165 else if e-1 == i then
1166 # last item of chunk
1167 ends[ii] -= 1
1168
1169 else if s == i then
1170 # first item of chunk
1171 starts[ii] += 1
1172 else
1173 # break up chunk
1174 ends.insert(ends[ii], ii+1)
1175 ends[ii] = i
1176 starts.insert(i+1, ii+1)
1177 end
1178
1179 available.add i
1180 return
1181 end
1182 ii += 1
1183 end
1184
1185 abort
1186 end
1187
1188 # Defragment and compress everything into a single chunks beginning at 0
1189 #
1190 # Returns the elements that moved as a list.
1191 #
1192 # ~~~
1193 # var array = new GroupedArray[String]
1194 # array.add "a"
1195 # array.add "b"
1196 # array.add "c"
1197 # array.add "d"
1198 # array.remove "c"
1199 # array.remove "a"
1200 # assert array.to_s == "[b][d]"
1201 #
1202 # var moved = array.defragment
1203 # assert moved.to_s == "[d]"
1204 # assert array.to_s == "[d,b]"
1205 # assert array.length == 2
1206 # assert array.capacity == 2
1207 #
1208 # array.add "e"
1209 # array.add "f"
1210 # assert array.to_s == "[d,b,e,f]"
1211 # ~~~
1212 fun defragment(max: nullable Int): Array[E]
1213 do
1214 app.perf_clock_sprites.lapse
1215 max = max or else length
1216
1217 var moved = new Array[E]
1218 while max > 0 and (starts.length > 1 or starts.first != 0) do
1219 var i = ends.last - 1
1220 var e = items[i]
1221 remove e
1222 add e
1223 moved.add e
1224 max -= 1
1225 end
1226
1227 if starts.length == 1 and starts.first == 0 then
1228 for i in [length..capacity[ do items.pop
1229 available.clear
1230 end
1231
1232 sys.perfs["gamnit flat gpu defrag"].add app.perf_clock_sprites.lapse
1233 return moved
1234 end
1235
1236 redef fun to_s
1237 do
1238 var ss = new Array[String]
1239 for s in starts, e in ends do
1240 ss.add "["
1241 for i in [s..e[ do
1242 var item: nullable Object = items[i]
1243 if item == null then item = "null"
1244 ss.add item.to_s
1245 if i != e-1 then ss.add ","
1246 end
1247 ss.add "]"
1248 end
1249 return ss.join
1250 end
1251 end