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