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