1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 # Simple API for 2D games, built around `Sprite` and `App::update`
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.
21 # This system relies on two cameras `App::world_camera` and `App::ui_camera`.
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`.
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`.
32 # See the sample game at `contrib/asteronits/` and the basic project template
33 # at `lib/gamnit/examples/template/`.
37 intrude import geometry
::points_and_lines
# For _x, _y and _z
39 import matrix
::projection
40 import more_collections
41 import performance_analysis
44 intrude import gamnit
::cameras
45 intrude import gamnit
::cameras_cache
46 import gamnit
::dynamic_resolution
47 import gamnit
::limit_fps
48 import gamnit
::camera_control
50 # Visible 2D entity in the game world or UI
52 # Similar to `gamnit::Actor` which is in 3D.
54 # Each sprite associates a `texture` to the position `center`.
55 # The appearance is modified by `rotation`, `invert_x`,
56 # `scale`, `red`, `green`, `blue` and `alpha`.
57 # These values can be changed at any time and will trigger an update
58 # of the data on the GPU side, having a small performance cost.
60 # For a sprite to be visible, it must be added to either the world `sprites`
61 # or the `ui_sprites`.
62 # However, an instance of `Sprite` can only belong to a single `SpriteSet`
63 # at a time. The final on-screen position depends on the camera associated
67 # # Load texture and create sprite
68 # var texture = new Texture("path/in/assets.png")
69 # var sprite = new Sprite(texture, new Point3d[Float](0.0, 0.0, 0.0))
71 # # Add sprite to the visible game world
72 # app.sprites.add sprite
74 # # Extra configuration of the sprite
75 # sprite.rotation = pi/2.0
78 # # Show only the blue colors
83 # To add a sprite to the UI it can be anchored to screen borders
84 # with `ui_camera.top_left` and the likes.
87 # # Place it a bit off the top left of the screen
88 # var pos = app.ui_camera.top_left.offset(128.0, -128.0, 0)
90 # # Load texture and create sprite
91 # var texture = new Texture("path/in/assets.png")
92 # var sprite = new Sprite(texture, pos)
94 # # Add it to the UI (above world sprites)
95 # app.ui_sprites.add sprite
99 # Texture drawn to screen
100 var texture
: Texture is writable(texture_direct
=)
102 # Texture drawn to screen
103 fun texture
=(value
: Texture)
105 if isset _texture
and value
!= texture
then
107 if value
.root
!= texture
.root
then needs_remap
109 texture_direct
= value
112 # Center position of this sprite in world coordinates
113 var center
: Point3d[Float] is writable(center_direct
=), noautoinit
115 # Center position of this sprite in world coordinates
116 fun center
=(value
: Point3d[Float]) is autoinit
do
117 if isset _center
and value
!= center
then
119 center
.sprites_remove
self
122 value
.sprites_add
self
123 center_direct
= value
126 # Rotation on the Z axis, positive values turn counterclockwise
127 var rotation
= 0.0 is writable(rotation_direct
=)
129 # Rotation on the Z axis, positive values turn counterclockwise
130 fun rotation
=(value
: Float)
132 if isset _rotation
and value
!= rotation
then needs_update
133 rotation_direct
= value
136 # Mirror `texture` horizontally, inverting each pixel on the X axis
137 var invert_x
= false is writable(invert_x_direct
=)
139 # Mirror `texture` horizontally, inverting each pixel on the X axis
140 fun invert_x
=(value
: Bool)
142 if isset _invert_x
and value
!= invert_x
then needs_update
143 invert_x_direct
= value
146 # Scale applied to this sprite
148 # The basic size of `self` depends on the size in pixels of `texture`.
149 var scale
= 1.0 is writable(scale_direct
=)
151 # Scale applied to this sprite
153 # The basic size of `self` depends on the size in pixels of `texture`.
154 fun scale
=(value
: Float)
156 if isset _scale
and value
!= scale
then needs_update
160 # Red tint applied to `texture` on draw
161 fun red
: Float do return tint
[0]
163 # Red tint applied to `texture` on draw
164 fun red
=(value
: Float)
166 if isset _tint
and value
!= red
then needs_update
170 # Green tint applied to `texture` on draw
171 fun green
: Float do return tint
[1]
173 # Green tint applied to `texture` on draw
174 fun green
=(value
: Float)
176 if isset _tint
and value
!= green
then needs_update
180 # Blue tint applied to `texture` on draw
181 fun blue
: Float do return tint
[2]
183 # Blue tint applied to `texture` on draw
184 fun blue
=(value
: Float)
186 if isset _tint
and value
!= blue
then needs_update
190 # Transparency applied to `texture` on draw
191 fun alpha
: Float do return tint
[3]
193 # Transparency applied to `texture` on draw
194 fun alpha
=(value
: Float)
196 if isset _tint
and value
!= alpha
then needs_update
200 # Tint applied to `texture` on draw
202 # Alternative to the accessors `red, green, blue & alpha`.
203 # Changes inside the array do not automatically set `needs_update`.
205 # Require: `tint.length == 4`
206 var tint
: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable(tint_direct
=)
208 # Tint applied to `texture` on draw, see `tint`
209 fun tint
=(value
: Array[Float])
211 if isset _tint
and value
!= tint
then needs_update
215 # Is this sprite static and added in bulk?
217 # Set to `true` to give a hint to the framework that this sprite won't
218 # change often and that it is added in bulk with other static sprites.
219 # This value can be ignored in the prototyping phase of a game and
220 # added only when better performance are needed.
221 var static
= false is writable(static_direct
=)
223 # Is this sprite static and added in bulk? see `static`
224 fun static
=(value
: Bool)
226 if isset _static
and value
!= static
then needs_remap
227 static_direct
= value
230 # Request an update on the CPU
232 # This is called automatically on modification of any value of `Sprite`.
233 # However, it can still be set manually if a modification can't be
234 # detected or by subclasses.
238 if c
!= null then c
.sprites_to_update
.add
self
241 # Request a resorting of this sprite in its sprite list
243 # Resorting is required when `static` or the root of `texture` changes.
244 # This is called automatically when such changes are detected.
245 # However, it can still be set manually if a modification can't be
246 # detected or by subclasses.
250 if l
!= null then l
.sprites_to_remap
.add
self
253 # Current context to which `self` was sorted
254 private var context
: nullable SpriteContext = null
256 # Current context to which `self` belongs
257 private var sprite_set
: nullable SpriteSet = null
261 # Default graphic program to draw `sprites`
262 private var simple_2d_program
= new Simple2dProgram is lazy
264 # Camera for world `sprites` and `depth::actors` with perspective
266 # By default, the camera is configured to a height of 1080 units
267 # of world coordinates at `z == 0.0`.
268 var world_camera
: EulerCamera is lazy
do
269 var camera
= new EulerCamera(app
.display
.as(not null))
271 # Aim for full HD pixel resolution at level 0
272 camera
.reset_height
1080.0
278 # Camera for `ui_sprites` using an orthogonal view
279 var ui_camera
= new UICamera(app
.display
.as(not null)) is lazy
281 # World sprites drawn as seen by `world_camera`
282 var sprites
: Set[Sprite] = new SpriteSet
284 # UI sprites drawn as seen by `ui_camera`, over world `sprites`
285 var ui_sprites
: Set[Sprite] = new SpriteSet
287 # Main method to refine in clients to update game logic and `sprites`
288 fun update
(dt
: Float) do end
290 # Display `texture` as a splash screen
292 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
293 fun show_splash_screen
(texture
: Texture)
297 var splash
= new Sprite(texture
, ui_camera
.center
.offset
(0.0, 0.0, 0.0))
298 ui_sprites
.add splash
300 var display
= display
301 assert display
!= null
302 glClear gl_COLOR_BUFFER_BIT
303 frame_core_ui_sprites display
306 ui_sprites
.remove splash
310 # Support and implementation
312 # Main clock used to count each frame `dt`, lapsed for `update` only
313 private var clock
= new Clock is lazy
315 # Performance clock to for `frame_core_draw` operations
316 private var perf_clock_main
= new Clock
318 # Second performance clock for smaller operations
319 private var perf_clock_sprites
= new Clock is lazy
325 var display
= display
326 assert display
!= null
328 var gl_error
= glGetError
329 assert gl_error
== gl_NO_ERROR
else print_error gl_error
332 var program
= simple_2d_program
333 program
.compile_and_link
335 var gamnit_error
= program
.error
336 assert gamnit_error
== null else print_error gamnit_error
339 gl
.capabilities
.blend
.enable
340 glBlendFunc
(gl_SRC_ALPHA
, gl_ONE_MINUS_SRC_ALPHA
)
343 gl
.capabilities
.depth_test
.enable
344 glDepthFunc gl_LEQUAL
347 # Prepare viewport and background color
348 glViewport
(0, 0, display
.width
, display
.height
)
349 glClearColor
(0.0, 0.0, 0.0, 1.0)
351 gl_error
= glGetError
352 assert gl_error
== gl_NO_ERROR
else print_error gl_error
355 for tex
in all_root_textures
do
357 gamnit_error
= tex
.error
358 if gamnit_error
!= null then print_error gamnit_error
360 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MIN_FILTER
, gl_LINEAR
)
361 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MAG_FILTER
, gl_LINEAR
)
368 simple_2d_program
.delete
371 var display
= display
372 if display
!= null then display
.close
375 redef fun on_resize
(display
)
379 world_camera
.mvp_matrix_cache
= null
380 ui_camera
.mvp_matrix_cache
= null
382 # Update all sprites in the UI
383 for sprite
in ui_sprites
do sprite
.needs_update
386 redef fun frame_core
(display
)
389 var gl_error
= glGetError
390 assert gl_error
== gl_NO_ERROR
else print_error gl_error
392 # Update game logic and set sprites
393 perf_clock_main
.lapse
394 var dt
= clock
.lapse
.to_f
397 sys
.perfs
["gamnit flat update client"].add perf_clock_main
.lapse
399 # Draw and flip screen
400 frame_core_draw display
404 gl_error
= glGetError
405 assert gl_error
== gl_NO_ERROR
else print_error gl_error
408 private var frame_dt
= 0.0
410 # Draw the whole screen, all `glDraw...` calls should be executed here
411 protected fun frame_core_draw
(display
: GamnitDisplay)
413 frame_core_dynamic_resolution_before display
415 perf_clock_main
.lapse
416 frame_core_world_sprites display
417 perfs
["gamnit flat world_sprites"].add perf_clock_main
.lapse
419 frame_core_ui_sprites display
420 perfs
["gamnit flat ui_sprites"].add perf_clock_main
.lapse
422 frame_core_dynamic_resolution_after display
425 private fun frame_core_sprites
(display
: GamnitDisplay, sprite_set
: SpriteSet, camera
: Camera)
427 var simple_2d_program
= app
.simple_2d_program
428 simple_2d_program
.use
429 simple_2d_program
.mvp
.uniform camera
.mvp_matrix
431 sprite_set
.time
+= frame_dt
*sprite_set
.time_mod
432 simple_2d_program
.time
.uniform sprite_set
.time
438 # Draw world sprites from `sprites`
439 protected fun frame_core_world_sprites
(display
: GamnitDisplay)
441 frame_core_sprites
(display
, sprites
.as(SpriteSet), world_camera
)
444 # Draw UI sprites from `ui_sprites`
445 protected fun frame_core_ui_sprites
(display
: GamnitDisplay)
447 # Reset only the depth buffer
448 glClear gl_DEPTH_BUFFER_BIT
450 frame_core_sprites
(display
, ui_sprites
.as(SpriteSet), ui_camera
)
456 # Vertices coordinates of the base geometry
458 # Defines the default width and height of related sprites.
459 private var vertices
: Array[Float] is lazy
do
462 return [-0.5*w
, 0.5*h
, 0.0,
468 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
469 private var texture_coords
: Array[Float] is lazy
do
472 var b
= offset_bottom
480 # Coordinates of this texture on the `root` texture, inverting the X axis
481 private var texture_coords_invert_x
: Array[Float] is lazy
do
484 var b
= offset_bottom
493 # Graphic program to display simple models with a texture, translation, rotation and scale
494 private class Simple2dProgram
495 super GamnitProgramFromSource
497 redef var vertex_shader_source
= """
498 // Vertex coordinates
499 attribute vec4 coord;
502 attribute vec4 color;
504 // Vertex translation
505 attribute vec4 translation;
508 attribute float scale;
510 // Vertex coordinates on textures
511 attribute vec2 tex_coord;
513 // Model view projection matrix
516 // Current world time, in seconds
520 attribute vec4 rotation_row0;
521 attribute vec4 rotation_row1;
522 attribute vec4 rotation_row2;
523 attribute vec4 rotation_row3;
527 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
530 // Output to the fragment shader
531 varying vec4 v_color;
532 varying vec2 v_coord;
536 gl_Position = (vec4(coord.xyz * scale, 1.0) * rotation() + translation)* mvp;
540 """ @ glsl_vertex_shader
542 redef var fragment_shader_source
= """
543 precision mediump float;
545 // Does this object use a texture?
546 uniform bool use_texture;
548 // Texture to apply on this object
549 uniform sampler2D texture0;
551 // Input from the vertex shader
552 varying vec4 v_color;
553 varying vec2 v_coord;
558 gl_FragColor = v_color * texture2D(texture0, v_coord);
559 if (gl_FragColor.a <= 0.01) discard;
561 gl_FragColor = v_color;
564 """ @ glsl_fragment_shader
566 # Vertices coordinates
567 var coord
= attributes
["coord"].as(AttributeVec4) is lazy
569 # Should this program use the texture `texture`?
570 var use_texture
= uniforms
["use_texture"].as(UniformBool) is lazy
572 # Visible texture unit
573 var texture
= uniforms
["texture0"].as(UniformSampler2D) is lazy
575 # Coordinates on the textures, per vertex
576 var tex_coord
= attributes
["tex_coord"].as(AttributeVec2) is lazy
578 # Color tint per vertex
579 var color
= attributes
["color"].as(AttributeVec4) is lazy
581 # Translation applied to each vertex
582 var translation
= attributes
["translation"].as(AttributeVec4) is lazy
584 # Rotation matrix, row 0
585 var rotation_row0
= attributes
["rotation_row0"].as(AttributeVec4) is lazy
587 # Rotation matrix, row 1
588 var rotation_row1
= attributes
["rotation_row1"].as(AttributeVec4) is lazy
590 # Rotation matrix, row 2
591 var rotation_row2
= attributes
["rotation_row2"].as(AttributeVec4) is lazy
593 # Rotation matrix, row 3
594 var rotation_row3
= attributes
["rotation_row3"].as(AttributeVec4) is lazy
597 var scale
= attributes
["scale"].as(AttributeFloat) is lazy
599 # Model view projection matrix
600 var mvp
= uniforms
["mvp"].as(UniformMat4) is lazy
603 redef class Point3d[N
]
605 # Associate each point to its sprites
607 private var sprites
: nullable Array[Sprite] = null
609 private fun sprites_add
(sprite
: Sprite)
611 var sprites
= sprites
612 if sprites
== null then
613 sprites
= new Array[Sprite]
614 self.sprites
= sprites
619 private fun sprites_remove
(sprite
: Sprite)
621 var sprites
= sprites
622 assert sprites
!= null
623 sprites
.remove sprite
627 # Notify `sprites` on attribute modification
629 private fun needs_update
631 var sprites
= sprites
632 if sprites
!= null then for s
in sprites
do s
.needs_update
637 if isset _x
and v
!= x
then needs_update
643 if isset _y
and v
!= y
then needs_update
649 if isset _z
and v
!= z
then needs_update
654 redef class OffsetPoint3d
657 if isset _x
and v
!= x
then needs_update
663 if isset _y
and v
!= y
then needs_update
669 if isset _z
and v
!= z
then needs_update
674 # Set of sprites sorting them into different `SpriteContext`
675 private class SpriteSet
676 super HashSet[Sprite]
678 # Map texture then static vs dynamic to a `SpriteContext`
679 var contexts_map
= new HashMap2[RootTexture, Bool, SpriteContext]
681 # Contexts in `contexts_map`
682 var contexts_items
= new Array[SpriteContext]
684 # Sprites needing resorting in `contexts_map`
685 var sprites_to_remap
= new Array[Sprite]
687 # Animation speed multiplier (0.0 to pause, 1.0 for normal speed, etc.)
688 var time_mod
= 1.0 is writable
690 # Seconds elapsed since the launch of the program, in world time responding to `time_mod`
693 # Add a sprite to the appropriate context
694 fun map_sprite
(sprite
: Sprite)
696 assert sprite
.context
== null else print_error
"Sprite {sprite} belongs to another SpriteSet"
698 var texture
= sprite
.texture
.root
699 var context
= contexts_map
[texture
, sprite
.static
]
701 if context
== null then
702 var usage
= if sprite
.static
then gl_STATIC_DRAW
else gl_DYNAMIC_DRAW
703 context
= new SpriteContext(texture
, usage
)
705 contexts_map
[texture
, sprite
.static
] = context
706 contexts_items
.add context
709 context
.sprites
.add sprite
710 context
.sprites_to_update
.add sprite
712 sprite
.context
= context
713 sprite
.sprite_set
= self
716 # Remove a sprite from its context
717 fun unmap_sprite
(sprite
: Sprite)
719 var context
= sprite
.context
720 assert context
!= null
721 context
.sprites
.remove sprite
723 sprite
.context
= null
724 sprite
.sprite_set
= null
727 # Draw all sprites by all contexts
730 for sprite
in sprites_to_remap
do
734 sprites_to_remap
.clear
736 for context
in contexts_items
do context
.draw
741 if contexts_items
.has
(e
.context
) then return
749 if e
isa Sprite then unmap_sprite e
752 redef fun remove_all
(e
)
754 if not has
(e
) then return
760 for sprite
in self do
761 sprite
.context
= null
762 sprite
.sprite_set
= null
765 for c
in contexts_items
do c
.destroy
771 # Context for calls to `glDrawElements`
773 # Each context has only one `texture` and `usage`, but many sprites.
774 private class SpriteContext
777 # Context config and state
779 # Only root texture drawn by this context
780 var texture
: nullable RootTexture
782 # OpenGL ES usage of `buffer_array` and `buffer_element`
783 var usage
: GLBufferUsage
785 # Sprites drawn by this context
786 var sprites
= new GroupedArray[Sprite]
788 # Sprites to update since last `draw`
789 var sprites_to_update
= new Set[Sprite]
791 # Sprites that have been update and for which `needs_update` can be set to false
792 var updated_sprites
= new Array[Sprite]
794 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
796 # Require: `resize_ratio >= 1.0`
797 var resize_ratio
= 1.2
802 # OpenGL ES buffer name for vertex data
803 var buffer_array
: Int = -1
805 # OpenGL ES buffer name for indices
806 var buffer_element
: Int = -1
808 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
809 var buffer_capacity
= 0
811 # C buffers used to pass the data of a single sprite
812 var local_data_buffer
= new GLfloatArray(float_per_vertex
*4) is lazy
813 var local_indices_buffer
= new CUInt16Array(indices_per_sprite
) is lazy
818 # Number of GL_FLOAT per vertex of `Simple2dProgram`
819 var float_per_vertex
: Int is lazy
do
820 # vec4 translation, vec4 color, vec4 coord,
821 # float scale, vec2 tex_coord, vec4 rotation_row*
826 # Number of bytes per vertex of `Simple2dProgram`
827 var bytes_per_vertex
: Int is lazy
do
828 var fs
= 4 # sizeof(GL_FLOAT)
829 return fs
* float_per_vertex
832 # Number of bytes per sprite
833 var bytes_per_sprite
: Int is lazy
do return bytes_per_vertex
* 4
835 # Number of vertex indices per sprite draw call (2 triangles)
836 var indices_per_sprite
= 6
841 # Allocate `buffer_array` and `buffer_element`
844 var bufs
= glGenBuffers
(2)
845 buffer_array
= bufs
[0]
846 buffer_element
= bufs
[1]
848 var gl_error
= glGetError
849 assert gl_error
== gl_NO_ERROR
else print_error gl_error
852 # Destroy `buffer_array` and `buffer_element`
855 glDeleteBuffers
([buffer_array
, buffer_element
])
856 var gl_error
= glGetError
857 assert gl_error
== gl_NO_ERROR
else print_error gl_error
863 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
866 app
.perf_clock_sprites
.lapse
868 # Allocate a bit more space
869 var capacity
= (sprites
.capacity
.to_f
* resize_ratio
).to_i
871 var array_bytes
= capacity
* bytes_per_sprite
872 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
873 assert glIsBuffer
(buffer_array
)
874 glBufferData
(gl_ARRAY_BUFFER
, array_bytes
, new Pointer.nul
, usage
)
875 var gl_error
= glGetError
876 assert gl_error
== gl_NO_ERROR
else print_error gl_error
878 # GL_TRIANGLES 6 vertices * sprite
879 var n_indices
= capacity
* indices_per_sprite
880 var ius
= 2 # sizeof(GL_UNSIGNED_SHORT)
881 var element_bytes
= n_indices
* ius
882 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
883 assert glIsBuffer
(buffer_element
)
884 glBufferData
(gl_ELEMENT_ARRAY_BUFFER
, element_bytes
, new Pointer.nul
, usage
)
885 gl_error
= glGetError
886 assert gl_error
== gl_NO_ERROR
else print_error gl_error
888 buffer_capacity
= capacity
890 sys
.perfs
["gamnit flat gpu resize"].add app
.perf_clock_sprites
.lapse
893 # Update GPU data of `sprite`
894 fun update_sprite
(sprite
: Sprite)
896 var sprite_index
= sprites
.index_of
(sprite
)
897 if sprite_index
== -1 then return
901 var data
= local_data_buffer
905 data
[o
+ 0] = sprite
.center
.x
906 data
[o
+ 1] = sprite
.center
.y
907 data
[o
+ 2] = sprite
.center
.z
911 data
[o
+ 4] = sprite
.tint
[0]
912 data
[o
+ 5] = sprite
.tint
[1]
913 data
[o
+ 6] = sprite
.tint
[2]
914 data
[o
+ 7] = sprite
.tint
[3]
917 data
[o
+ 8] = sprite
.scale
920 data
[o
+ 9] = sprite
.texture
.vertices
[v
*3+0]
921 data
[o
+10] = sprite
.texture
.vertices
[v
*3+1]
922 data
[o
+11] = sprite
.texture
.vertices
[v
*3+2]
926 var texture
= texture
927 if texture
!= null then
928 var tc
= if sprite
.invert_x
then
929 sprite
.texture
.texture_coords_invert_x
930 else sprite
.texture
.texture_coords
931 data
[o
+13] = tc
[v
*2+0]
932 data
[o
+14] = tc
[v
*2+1]
937 if sprite
.rotation
== 0.0 then
938 # Cache the matrix at no rotation
939 rot
= once
new Matrix.identity
(4)
941 rot
= new Matrix.rotation
(sprite
.rotation
, 0.0, 0.0, 1.0)
943 data
.fill_from_matrix
(rot
, o
+15)
945 o
+= float_per_vertex
948 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
949 glBufferSubData
(gl_ARRAY_BUFFER
, sprite_index
*bytes_per_sprite
, bytes_per_sprite
, data
.native_array
)
951 var gl_error
= glGetError
952 assert gl_error
== gl_NO_ERROR
else print_error gl_error
961 var indices
= local_indices_buffer
962 var io
= sprite_index
*4
970 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
971 glBufferSubData
(gl_ELEMENT_ARRAY_BUFFER
, sprite_index
*6*2, 6*2, indices
.native_array
)
973 gl_error
= glGetError
974 assert gl_error
== gl_NO_ERROR
else print_error gl_error
979 # Call `resize` and `update_sprite` as needed before actual draw operation.
981 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
984 if buffer_array
== -1 then prepare
986 assert buffer_array
> 0 and buffer_element
> 0 else
987 print_error
"Internal error: {self} was destroyed"
991 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
992 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
994 # Resize GPU buffers?
995 if sprites
.capacity
> buffer_capacity
then
996 # Try to defragment first
997 var moved
= sprites
.defragment
999 if sprites
.capacity
> buffer_capacity
then
1000 # Defragmentation wasn't enough, grow
1003 # We must update everything
1004 for s
in sprites
.items
do if s
!= null then sprites_to_update
.add s
1006 # Just update the moved sprites
1007 for s
in moved
do sprites_to_update
.add s
1009 else if sprites
.available
.not_empty
then
1010 # Defragment a bit anyway
1011 # TODO defrag only when there's time left on a frame
1012 var moved
= sprites
.defragment
(1)
1013 for s
in moved
do sprites_to_update
.add s
1016 # Update GPU sprites data
1017 if sprites_to_update
.not_empty
then
1018 app
.perf_clock_sprites
.lapse
1020 for sprite
in sprites_to_update
do update_sprite
(sprite
)
1021 sprites_to_update
.clear
1023 sys
.perfs
["gamnit flat gpu update"].add app
.perf_clock_sprites
.lapse
1026 # Update uniforms specific to this context
1027 var texture
= texture
1028 app
.simple_2d_program
.use_texture
.uniform texture
!= null
1029 if texture
!= null then
1030 glActiveTexture gl_TEXTURE0
1031 glBindTexture
(gl_TEXTURE_2D
, texture
.gl_texture
)
1032 app
.simple_2d_program
.texture
.uniform
0
1034 var gl_error
= glGetError
1035 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1037 # Configure attributes, in order:
1038 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*
1040 var p
= app
.simple_2d_program
1041 var sizeof_gl_float
= 4 # sizeof(GL_FLOAT)
1043 var size
= 4 # Number of floats
1044 glEnableVertexAttribArray p
.translation
.location
1045 glVertexAttribPointeri
(p
.translation
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1046 offset
+= size
* sizeof_gl_float
1047 gl_error
= glGetError
1048 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1051 glEnableVertexAttribArray p
.color
.location
1052 glVertexAttribPointeri
(p
.color
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1053 offset
+= size
* sizeof_gl_float
1054 gl_error
= glGetError
1055 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1058 glEnableVertexAttribArray p
.scale
.location
1059 glVertexAttribPointeri
(p
.scale
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1060 offset
+= size
* sizeof_gl_float
1061 gl_error
= glGetError
1062 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1065 glEnableVertexAttribArray p
.coord
.location
1066 glVertexAttribPointeri
(p
.coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1067 offset
+= size
* sizeof_gl_float
1068 gl_error
= glGetError
1069 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1072 glEnableVertexAttribArray p
.tex_coord
.location
1073 glVertexAttribPointeri
(p
.tex_coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1074 offset
+= size
* sizeof_gl_float
1075 gl_error
= glGetError
1076 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1079 for r
in [p
.rotation_row0
, p
.rotation_row1
, p
.rotation_row2
, p
.rotation_row3
] do
1081 glEnableVertexAttribArray r
.location
1082 glVertexAttribPointeri
(r
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1084 offset
+= size
* sizeof_gl_float
1085 gl_error
= glGetError
1086 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1090 for s
in sprites
.starts
, e
in sprites
.ends
do
1092 glDrawElementsi
(gl_TRIANGLES
, l
*indices_per_sprite
, gl_UNSIGNED_SHORT
, 2*s
*indices_per_sprite
)
1093 gl_error
= glGetError
1094 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1098 for attr
in [p
.translation
, p
.color
, p
.scale
, p
.coord
, p
.tex_coord
,
1099 p
.rotation_row0
, p
.rotation_row1
, p
.rotation_row2
, p
.rotation_row3
: Attribute] do
1100 if not attr
.is_active
then continue
1101 glDisableVertexAttribArray
(attr
.location
)
1102 gl_error
= glGetError
1103 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1106 glBindBuffer
(gl_ARRAY_BUFFER
, 0)
1107 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, 0)
1108 gl_error
= glGetError
1109 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1113 # Representation of sprite data on the GPU
1115 # The main purpose of this class is to optimize the use of contiguous
1116 # space in GPU memory. Each contiguous memory block can be drawn in a
1117 # single call. The starts index of each block is kept by `starts,
1118 # and the end + 1 by `ends`.
1120 # The data can be compressed by a call to `defragment`.
1123 # intrude import gamnit::flat
1125 # var array = new GroupedArray[String]
1126 # assert array.to_s == ""
1134 # assert array.to_s == "[a,b,c,d,e,f]"
1135 # assert array.capacity == 6
1138 # assert array.to_s == "[b,c,d,e,f]"
1141 # assert array.to_s == "[c,d,e,f]"
1144 # assert array.to_s == "[c,d,e]"
1147 # assert array.to_s == "[c][e]"
1150 # assert array.to_s == "[A][c][e]"
1153 # assert array.to_s == "[A,B,c][e]"
1156 # assert array.to_s == "[A,B,c]"
1159 # assert array.to_s == "[A,B,c,D]"
1162 # assert array.to_s == "[A,B,c,D,E]"
1163 # assert array.capacity == 6
1164 # assert array.length == 5
1171 # assert array.to_s == ""
1174 # assert array.to_s == "[a]"
1176 private class GroupedArray[E
]
1178 # Memory with actual objects, and null in empty slots
1179 var items
= new Array[nullable E
]
1181 # Number of items in the array
1184 # Number of item slots in the array
1185 fun capacity
: Int do return items
.length
1188 fun index_of
(item
: E
): Int do return items
.index_of
(item
)
1190 # List of available slots
1191 var available
= new MinHeap[Int].default
1193 # Start index of filled chunks
1194 var starts
= new List[Int]
1196 # Index of the spots after filled chunks
1197 var ends
= new List[Int]
1199 # Add `item` to the first available slot
1204 if available
.not_empty
then
1205 # starts & ends can't be empty
1207 var i
= available
.take
1210 if i
== starts
.first
- 1 then
1211 # slot 0 free, 1 taken
1214 # slot 0 and more free
1217 else if starts
.length
>= 2 and ends
.first
+ 1 == starts
[1] then
1222 # at end of first chunk
1229 if ends
.is_empty
then
1235 # Remove the first instance of `item`
1238 var i
= items
.index_of
(item
)
1244 for s
in starts
, e
in ends
do
1245 if s
<= i
and i
< e
then
1251 if starts
.is_empty
then
1256 else if e-1
== i
then
1257 # last item of chunk
1261 # first item of chunk
1265 ends
.insert
(ends
[ii
], ii
+1)
1267 starts
.insert
(i
+1, ii
+1)
1279 # Defragment and compress everything into a single chunks beginning at 0
1281 # Returns the elements that moved as a list.
1284 # intrude import gamnit::flat
1286 # var array = new GroupedArray[String]
1293 # assert array.to_s == "[b][d]"
1295 # var moved = array.defragment
1296 # assert moved.to_s == "[d]"
1297 # assert array.to_s == "[d,b]"
1298 # assert array.length == 2
1299 # assert array.capacity == 2
1303 # assert array.to_s == "[d,b,e,f]"
1305 fun defragment
(max
: nullable Int): Array[E
]
1307 app
.perf_clock_sprites
.lapse
1308 max
= max
or else length
1310 var moved
= new Array[E
]
1311 while max
> 0 and (starts
.length
> 1 or starts
.first
!= 0) do
1312 var i
= ends
.last
- 1
1320 if starts
.length
== 1 and starts
.first
== 0 then
1321 for i
in [length
..capacity
[ do items
.pop
1325 sys
.perfs
["gamnit flat gpu defrag"].add app
.perf_clock_sprites
.lapse
1331 var ss
= new Array[String]
1332 for s
in starts
, e
in ends
do
1335 var item
: nullable Object = items
[i
]
1336 if item
== null then item
= "null"
1338 if i
!= e-1
then ss
.add
","
1346 redef class GLfloatArray
1347 private fun fill_from_matrix
(matrix
: Matrix, dst_offset
: nullable Int)
1349 dst_offset
= dst_offset
or else 0
1350 var mat_len
= matrix
.width
*matrix
.height
1351 assert length
>= mat_len
+ dst_offset
1352 native_array
.fill_from_matrix_native
(matrix
.items
, dst_offset
, mat_len
)
1356 redef class NativeGLfloatArray
1357 private fun fill_from_matrix_native
(matrix
: matrix
::NativeDoubleArray, dst_offset
, len
: Int) `{
1359 for (i = 0; i < len; i ++)
1360 self[i+dst_offset] = (GLfloat)matrix[i];