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 # Last animation set with `animate`
127 var animation
: nullable Animation = null
129 # Animation on the shader, if this changes it `needs_remap`
130 private var shader_animation
: nullable Animation = null
132 # Animation start time, relative to `sprite_set.time`
134 # At -1.0 if animation started before being assigned a `sprite_set`.
135 private var animation_start
= 0.0
137 # Number of loops to show `animation`
138 private var animation_loops
= 0.0
140 # Start the `animation` for `n_loops`, replacing the static `texture`
142 # By default, if `n_loops` is not set, the animation plays once.
143 # If `n_loops == -1.0` then the animation loops infinitely.
144 # Otherwise, the animation repeats, e.g. it repeats twice and a half
145 # if `n_loops == 2.5`.
147 # The animation can be stopped using `animate_stop`.
148 fun animate
(animation
: Animation, n_loops
: nullable Float)
150 if not animation
.valid
then print_error
"{class_name}::animate: invalid animation {animation}"
152 var shader_animation
= shader_animation
153 if shader_animation
== null or animation
.frames
.first
.root
!= shader_animation
.frames
.first
.root
then
154 # Resort with the new animation texture
160 var sprite_set
= sprite_set
161 animation_start
= if sprite_set
!= null then sprite_set
.time
else -1.0
162 animation_loops
= n_loops
or else 1.0
163 self.shader_animation
= animation
164 self.animation
= animation
167 # Stop any active `animation` to display the static `texture`
170 if animation
== null then return
175 # Rotation on the Z axis, positive values turn counterclockwise
176 var rotation
= 0.0 is writable(rotation_direct
=)
178 # Rotation on the Z axis, positive values turn counterclockwise
179 fun rotation
=(value
: Float)
181 if isset _rotation
and value
!= rotation
then needs_update
182 rotation_direct
= value
185 # Mirror `texture` horizontally, inverting each pixel on the X axis
186 var invert_x
= false is writable(invert_x_direct
=)
188 # Mirror `texture` horizontally, inverting each pixel on the X axis
189 fun invert_x
=(value
: Bool)
191 if isset _invert_x
and value
!= invert_x
then needs_update
192 invert_x_direct
= value
195 # Scale applied to this sprite
197 # The basic size of `self` depends on the size in pixels of `texture`.
198 var scale
= 1.0 is writable(scale_direct
=)
200 # Scale applied to this sprite
202 # The basic size of `self` depends on the size in pixels of `texture`.
203 fun scale
=(value
: Float)
205 if isset _scale
and value
!= scale
then needs_update
209 # Red tint applied to `texture` on draw
210 fun red
: Float do return tint
[0]
212 # Red tint applied to `texture` on draw
213 fun red
=(value
: Float)
215 if isset _tint
and value
!= red
then needs_update
219 # Green tint applied to `texture` on draw
220 fun green
: Float do return tint
[1]
222 # Green tint applied to `texture` on draw
223 fun green
=(value
: Float)
225 if isset _tint
and value
!= green
then needs_update
229 # Blue tint applied to `texture` on draw
230 fun blue
: Float do return tint
[2]
232 # Blue tint applied to `texture` on draw
233 fun blue
=(value
: Float)
235 if isset _tint
and value
!= blue
then needs_update
239 # Transparency applied to `texture` on draw
240 fun alpha
: Float do return tint
[3]
242 # Transparency applied to `texture` on draw
243 fun alpha
=(value
: Float)
245 if isset _tint
and value
!= alpha
then needs_update
249 # Tint applied to `texture` on draw
251 # Alternative to the accessors `red, green, blue & alpha`.
252 # Changes inside the array do not automatically set `needs_update`.
254 # Require: `tint.length == 4`
255 var tint
: Array[Float] = [1.0, 1.0, 1.0, 1.0] is writable(tint_direct
=)
257 # Tint applied to `texture` on draw, see `tint`
258 fun tint
=(value
: Array[Float])
260 if isset _tint
and value
!= tint
then needs_update
264 # Is this sprite static and added in bulk?
266 # Set to `true` to give a hint to the framework that this sprite won't
267 # change often and that it is added in bulk with other static sprites.
268 # This value can be ignored in the prototyping phase of a game and
269 # added only when better performance are needed.
270 var static
= false is writable(static_direct
=)
272 # Is this sprite static and added in bulk? see `static`
273 fun static
=(value
: Bool)
275 if isset _static
and value
!= static
then needs_remap
276 static_direct
= value
279 # Request an update on the CPU
281 # This is called automatically on modification of any value of `Sprite`.
282 # However, it can still be set manually if a modification can't be
283 # detected or by subclasses.
287 if c
!= null then c
.sprites_to_update
.add
self
290 # Request a resorting of this sprite in its sprite list
292 # Resorting is required when `static` or the root of `texture` changes.
293 # This is called automatically when such changes are detected.
294 # However, it can still be set manually if a modification can't be
295 # detected or by subclasses.
299 if l
!= null then l
.sprites_to_remap
.add
self
302 # Current context to which `self` was sorted
303 private var context
: nullable SpriteContext = null
305 # Current context to which `self` belongs
306 private var sprite_set
: nullable SpriteSet = null
309 # Animation for sprites, set with `Sprite.animate`
311 # Two main services create animations:
312 # * The constructors accepts an array of textures and the number of frames per
313 # seconds: `new Animation(array_of_subtextures, 10.0)`
314 # * The method `Texture::to_animation` uses the whole texture
315 # dividing it in frames either on X or Y:
316 # `new Texture("path/in/assets.png").to_animation(30.0, 0, 12)`
319 # Frames composing this animation
321 # All frames must share the same `Texture::root`, be on a vertical or
322 # horizontal line, be spaced equally and share the same dimensions.
323 var frames
: SequenceRead[Texture]
325 # Frames per seconds, a higher value makes this animation faster
327 # The animation speed is also affected by `SpriteSet::time_mod`.
330 # Are the `frames` valid for an animation? (see the requirements in `frames`)
331 var valid
: Bool is lazy
do
332 var r
: nullable RootTexture = null
337 if r
!= f
.root
then return false
341 # TODO check for line, constant distance, and same aspect ratio.
348 # Default graphic program to draw `sprites`
349 private var simple_2d_program
= new Simple2dProgram is lazy
351 # Camera for world `sprites` and `depth::actors` with perspective
353 # By default, the camera is configured to a height of 1080 units
354 # of world coordinates at `z == 0.0`.
355 var world_camera
: EulerCamera is lazy
do
356 var camera
= new EulerCamera(app
.display
.as(not null))
358 # Aim for full HD pixel resolution at level 0
359 camera
.reset_height
1080.0
365 # Camera for `ui_sprites` using an orthogonal view
366 var ui_camera
= new UICamera(app
.display
.as(not null)) is lazy
368 # World sprites drawn as seen by `world_camera`
369 var sprites
: Set[Sprite] = new SpriteSet
371 # UI sprites drawn as seen by `ui_camera`, over world `sprites`
372 var ui_sprites
: Set[Sprite] = new SpriteSet
374 # Main method to refine in clients to update game logic and `sprites`
375 fun update
(dt
: Float) do end
377 # Display `texture` as a splash screen
379 # Load `texture` if needed and resets `ui_camera` to 1080 units on the Y axis.
380 fun show_splash_screen
(texture
: Texture)
384 var splash
= new Sprite(texture
, ui_camera
.center
.offset
(0.0, 0.0, 0.0))
385 ui_sprites
.add splash
387 var display
= display
388 assert display
!= null
389 glClear gl_COLOR_BUFFER_BIT
390 frame_core_ui_sprites display
393 ui_sprites
.remove splash
397 # Support and implementation
399 # Main clock used to count each frame `dt`, lapsed for `update` only
400 private var clock
= new Clock is lazy
402 # Performance clock to for `frame_core_draw` operations
403 private var perf_clock_main
= new Clock
405 # Second performance clock for smaller operations
406 private var perf_clock_sprites
= new Clock is lazy
412 var display
= display
413 assert display
!= null
415 var gl_error
= glGetError
416 assert gl_error
== gl_NO_ERROR
else print_error gl_error
419 var program
= simple_2d_program
420 program
.compile_and_link
422 var gamnit_error
= program
.error
423 assert gamnit_error
== null else print_error gamnit_error
426 gl
.capabilities
.blend
.enable
427 glBlendFunc
(gl_SRC_ALPHA
, gl_ONE_MINUS_SRC_ALPHA
)
430 gl
.capabilities
.depth_test
.enable
431 glDepthFunc gl_LEQUAL
434 # Prepare viewport and background color
435 glViewport
(0, 0, display
.width
, display
.height
)
436 glClearColor
(0.0, 0.0, 0.0, 1.0)
438 gl_error
= glGetError
439 assert gl_error
== gl_NO_ERROR
else print_error gl_error
442 for tex
in all_root_textures
do
444 gamnit_error
= tex
.error
445 if gamnit_error
!= null then print_error gamnit_error
447 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MIN_FILTER
, gl_LINEAR
)
448 glTexParameteri
(gl_TEXTURE_2D
, gl_TEXTURE_MAG_FILTER
, gl_LINEAR
)
455 simple_2d_program
.delete
458 var display
= display
459 if display
!= null then display
.close
462 redef fun on_resize
(display
)
466 world_camera
.mvp_matrix_cache
= null
467 ui_camera
.mvp_matrix_cache
= null
469 # Update all sprites in the UI
470 for sprite
in ui_sprites
do sprite
.needs_update
473 redef fun frame_core
(display
)
476 var gl_error
= glGetError
477 assert gl_error
== gl_NO_ERROR
else print_error gl_error
479 # Update game logic and set sprites
480 perf_clock_main
.lapse
481 var dt
= clock
.lapse
.to_f
484 sys
.perfs
["gamnit flat update client"].add perf_clock_main
.lapse
486 # Draw and flip screen
487 frame_core_draw display
491 gl_error
= glGetError
492 assert gl_error
== gl_NO_ERROR
else print_error gl_error
495 private var frame_dt
= 0.0
497 # Draw the whole screen, all `glDraw...` calls should be executed here
498 protected fun frame_core_draw
(display
: GamnitDisplay)
500 frame_core_dynamic_resolution_before display
502 perf_clock_main
.lapse
503 frame_core_world_sprites display
504 perfs
["gamnit flat world_sprites"].add perf_clock_main
.lapse
506 frame_core_ui_sprites display
507 perfs
["gamnit flat ui_sprites"].add perf_clock_main
.lapse
509 frame_core_dynamic_resolution_after display
512 private fun frame_core_sprites
(display
: GamnitDisplay, sprite_set
: SpriteSet, camera
: Camera)
514 var simple_2d_program
= app
.simple_2d_program
515 simple_2d_program
.use
516 simple_2d_program
.mvp
.uniform camera
.mvp_matrix
518 sprite_set
.time
+= frame_dt
*sprite_set
.time_mod
519 simple_2d_program
.time
.uniform sprite_set
.time
525 # Draw world sprites from `sprites`
526 protected fun frame_core_world_sprites
(display
: GamnitDisplay)
528 frame_core_sprites
(display
, sprites
.as(SpriteSet), world_camera
)
531 # Draw UI sprites from `ui_sprites`
532 protected fun frame_core_ui_sprites
(display
: GamnitDisplay)
534 # Reset only the depth buffer
535 glClear gl_DEPTH_BUFFER_BIT
537 frame_core_sprites
(display
, ui_sprites
.as(SpriteSet), ui_camera
)
543 # Vertices coordinates of the base geometry
545 # Defines the default width and height of related sprites.
546 private var vertices
: Array[Float] is lazy
do
549 return [-0.5*w
, 0.5*h
, 0.0,
555 # Coordinates of this texture on the `root` texture, in `[0..1.0]`
556 private var texture_coords
: Array[Float] is lazy
do
559 var b
= offset_bottom
567 # Coordinates of this texture on the `root` texture, inverting the X axis
568 private var texture_coords_invert_x
: Array[Float] is lazy
do
571 var b
= offset_bottom
579 # Convert to a sprite animation at `fps` speed with `x` or `y` frames
581 # The arguments `x` and `y` set the number of frames in the texture.
582 # Use `x` for an horizontal arrangement or `y` for vertical.
583 # One and only one of the arguments must be different than 0,
584 # as an animation can only be on a line and cannot wrap.
585 fun to_animation
(fps
: Float, x
, y
: Int): Animation
587 assert (x
== 0) != (y
== 0)
589 var n_frames
= x
.max
(y
)
590 var frames
= new Array[Texture]
592 var dx
= (x
/n_frames
).to_f
/n_frames
.to_f
593 var dy
= (y
/n_frames
).to_f
/n_frames
.to_f
594 var w
= if x
== 0 then 1.0 else dx
595 var h
= if y
== 0 then 1.0 else dy
598 for i
in n_frames
.times
do
599 frames
.add
new RelativeSubtexture(root
, left
, top
, left
+w
, top
+h
)
604 return new Animation(frames
, fps
)
608 # Graphic program to display simple models with a texture, translation, rotation and scale
609 private class Simple2dProgram
610 super GamnitProgramFromSource
612 redef var vertex_shader_source
= """
613 // Vertex coordinates
614 attribute vec4 coord;
617 attribute vec4 color;
619 // Vertex translation
620 attribute vec4 translation;
623 attribute float scale;
625 // Vertex coordinates on textures
626 attribute vec2 tex_coord;
628 // Model view projection matrix
631 // Current world time, in seconds
635 attribute vec4 rotation_row0;
636 attribute vec4 rotation_row1;
637 attribute vec4 rotation_row2;
638 attribute vec4 rotation_row3;
640 // Animation speed, frames per seconds
641 attribute float a_fps;
643 // Number of frames in the animation
644 attribute float a_n_frames;
646 // World coordinate of the animation (for aspect ratio)
647 attribute vec2 a_coord;
649 // Animation texture coordinates of the first frame
650 attribute vec2 a_tex_coord;
652 // Animation texture coordinates difference between frames
653 attribute vec2 a_tex_diff;
655 // Animation start time, in reference to `time`
656 attribute float a_start;
658 // Number of loops to play of the animation
659 attribute float a_loops;
663 return mat4(rotation_row0, rotation_row1, rotation_row2, rotation_row3);
666 // Output to the fragment shader
667 varying vec4 v_color;
668 varying vec2 v_coord;
670 // Is there an active animation?
671 varying float v_animated;
677 float end = a_start + a_loops/a_fps*a_n_frames;
678 if (a_loops == -1.0 || time < end) {
680 float frame = mod(floor((time-a_start)*a_fps), a_n_frames);
681 v_coord = a_tex_coord + a_tex_diff*frame;
682 c = vec3(a_coord, coord.z);
691 gl_Position = (vec4(c * scale, 1.0) * rotation() + translation)* mvp;
694 """ @ glsl_vertex_shader
696 redef var fragment_shader_source
= """
697 precision mediump float;
699 // Does this object use a texture?
700 uniform bool use_texture;
702 // Texture to apply on this object
703 uniform sampler2D texture0;
705 // Texture to apply on this object
706 uniform sampler2D animation;
708 // Input from the vertex shader
709 varying vec4 v_color;
710 varying vec2 v_coord;
711 varying float v_animated;
715 if (v_animated > 0.5) {
716 gl_FragColor = v_color * texture2D(animation, v_coord);
717 if (gl_FragColor.a <= 0.01) discard;
718 } else if (use_texture) {
719 gl_FragColor = v_color * texture2D(texture0, v_coord);
720 if (gl_FragColor.a <= 0.01) discard;
722 gl_FragColor = v_color;
725 """ @ glsl_fragment_shader
727 # Vertices coordinates
728 var coord
= attributes
["coord"].as(AttributeVec4) is lazy
730 # Should this program use the texture `texture`?
731 var use_texture
= uniforms
["use_texture"].as(UniformBool) is lazy
733 # Visible texture unit
734 var texture
= uniforms
["texture0"].as(UniformSampler2D) is lazy
736 # Coordinates on the textures, per vertex
737 var tex_coord
= attributes
["tex_coord"].as(AttributeVec2) is lazy
739 # Color tint per vertex
740 var color
= attributes
["color"].as(AttributeVec4) is lazy
742 # Translation applied to each vertex
743 var translation
= attributes
["translation"].as(AttributeVec4) is lazy
745 # Rotation matrix, row 0
746 var rotation_row0
= attributes
["rotation_row0"].as(AttributeVec4) is lazy
748 # Rotation matrix, row 1
749 var rotation_row1
= attributes
["rotation_row1"].as(AttributeVec4) is lazy
751 # Rotation matrix, row 2
752 var rotation_row2
= attributes
["rotation_row2"].as(AttributeVec4) is lazy
754 # Rotation matrix, row 3
755 var rotation_row3
= attributes
["rotation_row3"].as(AttributeVec4) is lazy
758 var scale
= attributes
["scale"].as(AttributeFloat) is lazy
760 # Model view projection matrix
761 var mvp
= uniforms
["mvp"].as(UniformMat4) is lazy
763 # World time, in seconds
764 var time
= uniforms
["time"].as(UniformFloat) is lazy
769 # Texture of all the frames of the animation
770 var animation_texture
= uniforms
["animation"].as(UniformSampler2D) is lazy
772 # Frame per second of the animation
773 var animation_fps
= attributes
["a_fps"].as(AttributeFloat) is lazy
775 # Number of frames in the animation
776 var animation_n_frames
= attributes
["a_n_frames"].as(AttributeFloat) is lazy
778 # Coordinates of each frame (mush be shared by all frames)
779 var animation_coord
= attributes
["a_coord"].as(AttributeVec2) is lazy
781 # Texture coordinates of the first frame
782 var animation_tex_coord
= attributes
["a_tex_coord"].as(AttributeVec2) is lazy
784 # Coordinate difference between each frame
785 var animation_tex_diff
= attributes
["a_tex_diff"].as(AttributeVec2) is lazy
787 # Animation start time, in seconds and in reference to `dt`
788 var animation_start
= attributes
["a_start"].as(AttributeFloat) is lazy
790 # Number of loops of the animation, -1 for infinite
791 var animation_loops
= attributes
["a_loops"].as(AttributeFloat) is lazy
794 redef class Point3d[N
]
796 # Associate each point to its sprites
798 private var sprites
: nullable Array[Sprite] = null
800 private fun sprites_add
(sprite
: Sprite)
802 var sprites
= sprites
803 if sprites
== null then
804 sprites
= new Array[Sprite]
805 self.sprites
= sprites
810 private fun sprites_remove
(sprite
: Sprite)
812 var sprites
= sprites
813 assert sprites
!= null
814 sprites
.remove sprite
818 # Notify `sprites` on attribute modification
820 private fun needs_update
822 var sprites
= sprites
823 if sprites
!= null then for s
in sprites
do s
.needs_update
828 if isset _x
and v
!= x
then needs_update
834 if isset _y
and v
!= y
then needs_update
840 if isset _z
and v
!= z
then needs_update
845 redef class OffsetPoint3d
848 if isset _x
and v
!= x
then needs_update
854 if isset _y
and v
!= y
then needs_update
860 if isset _z
and v
!= z
then needs_update
865 # Set of sprites sorting them into different `SpriteContext`
866 private class SpriteSet
867 super HashSet[Sprite]
869 # Map texture then static vs dynamic to a `SpriteContext`
870 var contexts_map
= new HashMap3[RootTexture, nullable RootTexture, Bool, SpriteContext]
872 # Contexts in `contexts_map`
873 var contexts_items
= new Array[SpriteContext]
875 # Sprites needing resorting in `contexts_map`
876 var sprites_to_remap
= new Array[Sprite]
878 # Animation speed multiplier (0.0 to pause, 1.0 for normal speed, etc.)
879 var time_mod
= 1.0 is writable
881 # Seconds elapsed since the launch of the program, in world time responding to `time_mod`
884 # Add a sprite to the appropriate context
885 fun map_sprite
(sprite
: Sprite)
887 assert sprite
.context
== null else print_error
"Sprite {sprite} belongs to another SpriteSet"
889 # Sort by texture and animation texture
890 var texture
= sprite
.texture
.root
891 var animation
= sprite
.animation
892 var animation_texture
= if animation
!= null then
893 animation
.frames
.first
.root
else null
894 var context
= contexts_map
[texture
, animation_texture
, sprite
.static
]
896 if context
== null then
897 var usage
= if sprite
.static
then gl_STATIC_DRAW
else gl_DYNAMIC_DRAW
898 context
= new SpriteContext(texture
, animation_texture
, usage
)
900 contexts_map
[texture
, animation_texture
, sprite
.static
] = context
901 contexts_items
.add context
904 context
.sprites
.add sprite
905 context
.sprites_to_update
.add sprite
907 sprite
.context
= context
908 sprite
.sprite_set
= self
910 if animation
!= null and sprite
.animation_start
== -1.0 then
912 sprite
.animation_start
= time
916 # Remove a sprite from its context
917 fun unmap_sprite
(sprite
: Sprite)
919 var context
= sprite
.context
920 assert context
!= null
921 context
.sprites
.remove sprite
923 sprite
.context
= null
924 sprite
.sprite_set
= null
927 # Draw all sprites by all contexts
930 for sprite
in sprites_to_remap
do
934 sprites_to_remap
.clear
936 for context
in contexts_items
do context
.draw
941 if contexts_items
.has
(e
.context
) then return
949 if e
isa Sprite then unmap_sprite e
952 redef fun remove_all
(e
)
954 if not has
(e
) then return
960 for sprite
in self do
961 sprite
.context
= null
962 sprite
.sprite_set
= null
965 for c
in contexts_items
do c
.destroy
971 # Context for calls to `glDrawElements`
973 # Each context has only one `texture` and `usage`, but many sprites.
974 private class SpriteContext
977 # Context config and state
979 # Only root texture drawn by this context
980 var texture
: nullable RootTexture
982 # Only animation texture drawn by this context
983 var animation_texture
: nullable RootTexture
985 # OpenGL ES usage of `buffer_array` and `buffer_element`
986 var usage
: GLBufferUsage
988 # Sprites drawn by this context
989 var sprites
= new GroupedArray[Sprite]
991 # Sprites to update since last `draw`
992 var sprites_to_update
= new Set[Sprite]
994 # Sprites that have been update and for which `needs_update` can be set to false
995 var updated_sprites
= new Array[Sprite]
997 # Buffer size to preallocate at `resize`, multiplied by `sprites.length`
999 # Require: `resize_ratio >= 1.0`
1000 var resize_ratio
= 1.2
1005 # OpenGL ES buffer name for vertex data
1006 var buffer_array
: Int = -1
1008 # OpenGL ES buffer name for indices
1009 var buffer_element
: Int = -1
1011 # Current capacity, in sprites, of `buffer_array` and `buffer_element`
1012 var buffer_capacity
= 0
1014 # C buffers used to pass the data of a single sprite
1015 var local_data_buffer
= new GLfloatArray(float_per_vertex
*4) is lazy
1016 var local_indices_buffer
= new CUInt16Array(indices_per_sprite
) is lazy
1021 # Number of GL_FLOAT per vertex of `Simple2dProgram`
1022 var float_per_vertex
: Int is lazy
do
1023 return 4 + 4 + 4 + # vec4 translation, vec4 color, vec4 coord,
1024 1 + 2 + 4*4 + # float scale, vec2 tex_coord, vec4 rotation_row*,
1025 1 + 1 + # float a_fps, float a_n_frames,
1026 2 + 2 + 2 + # vec2 a_coord, vec2 a_tex_coord, vec2 a_tex_diff,
1027 1 + 1 # float a_start, float a_loops
1030 # Number of bytes per vertex of `Simple2dProgram`
1031 var bytes_per_vertex
: Int is lazy
do
1032 var fs
= 4 # sizeof(GL_FLOAT)
1033 return fs
* float_per_vertex
1036 # Number of bytes per sprite
1037 var bytes_per_sprite
: Int is lazy
do return bytes_per_vertex
* 4
1039 # Number of vertex indices per sprite draw call (2 triangles)
1040 var indices_per_sprite
= 6
1045 # Allocate `buffer_array` and `buffer_element`
1048 var bufs
= glGenBuffers
(2)
1049 buffer_array
= bufs
[0]
1050 buffer_element
= bufs
[1]
1052 var gl_error
= glGetError
1053 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1056 # Destroy `buffer_array` and `buffer_element`
1059 glDeleteBuffers
([buffer_array
, buffer_element
])
1060 var gl_error
= glGetError
1061 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1067 # Resize `buffer_array` and `buffer_element` to fit all `sprites` (and more)
1070 app
.perf_clock_sprites
.lapse
1072 # Allocate a bit more space
1073 var capacity
= (sprites
.capacity
.to_f
* resize_ratio
).to_i
1075 var array_bytes
= capacity
* bytes_per_sprite
1076 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
1077 assert glIsBuffer
(buffer_array
)
1078 glBufferData
(gl_ARRAY_BUFFER
, array_bytes
, new Pointer.nul
, usage
)
1079 var gl_error
= glGetError
1080 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1082 # GL_TRIANGLES 6 vertices * sprite
1083 var n_indices
= capacity
* indices_per_sprite
1084 var ius
= 2 # sizeof(GL_UNSIGNED_SHORT)
1085 var element_bytes
= n_indices
* ius
1086 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
1087 assert glIsBuffer
(buffer_element
)
1088 glBufferData
(gl_ELEMENT_ARRAY_BUFFER
, element_bytes
, new Pointer.nul
, usage
)
1089 gl_error
= glGetError
1090 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1092 buffer_capacity
= capacity
1094 sys
.perfs
["gamnit flat gpu resize"].add app
.perf_clock_sprites
.lapse
1097 # Update GPU data of `sprite`
1098 fun update_sprite
(sprite
: Sprite)
1100 var sprite_index
= sprites
.index_of
(sprite
)
1101 if sprite_index
== -1 then return
1105 var data
= local_data_buffer
1109 data
[o
+ 0] = sprite
.center
.x
1110 data
[o
+ 1] = sprite
.center
.y
1111 data
[o
+ 2] = sprite
.center
.z
1115 data
[o
+ 4] = sprite
.tint
[0]
1116 data
[o
+ 5] = sprite
.tint
[1]
1117 data
[o
+ 6] = sprite
.tint
[2]
1118 data
[o
+ 7] = sprite
.tint
[3]
1121 data
[o
+ 8] = sprite
.scale
1124 data
[o
+ 9] = sprite
.texture
.vertices
[v
*3+0]
1125 data
[o
+10] = sprite
.texture
.vertices
[v
*3+1]
1126 data
[o
+11] = sprite
.texture
.vertices
[v
*3+2]
1130 var texture
= texture
1131 if texture
!= null then
1132 var tc
= if sprite
.invert_x
then
1133 sprite
.texture
.texture_coords_invert_x
1134 else sprite
.texture
.texture_coords
1135 data
[o
+13] = tc
[v
*2+0]
1136 data
[o
+14] = tc
[v
*2+1]
1141 if sprite
.rotation
== 0.0 then
1142 # Cache the matrix at no rotation
1143 rot
= once
new Matrix.identity
(4)
1145 rot
= new Matrix.rotation
(sprite
.rotation
, 0.0, 0.0, 1.0)
1147 data
.fill_from_matrix
(rot
, o
+15)
1149 var animation
= sprite
.animation
1150 if animation
== null then
1151 for i
in [31..40] do data
[o
+i
] = 0.0
1154 data
[o
+31] = animation
.fps
1157 data
[o
+32] = animation
.frames
.length
.to_f
1160 data
[o
+33] = animation
.frames
.first
.vertices
[v
*3+0]
1161 data
[o
+34] = animation
.frames
.first
.vertices
[v
*3+1]
1164 var tc
= if sprite
.invert_x
then
1165 animation
.frames
.first
.texture_coords_invert_x
1166 else animation
.frames
.first
.texture_coords
1167 data
[o
+35] = tc
[v
*2]
1168 data
[o
+36] = tc
[v
*2+1]
1171 var dx
= animation
.frames
[1].texture_coords
[0] - animation
.frames
[0].texture_coords
[0]
1172 var dy
= animation
.frames
[1].texture_coords
[1] - animation
.frames
[0].texture_coords
[1]
1177 data
[o
+39] = sprite
.animation_start
1180 data
[o
+40] = sprite
.animation_loops
1183 o
+= float_per_vertex
1186 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
1187 glBufferSubData
(gl_ARRAY_BUFFER
, sprite_index
*bytes_per_sprite
, bytes_per_sprite
, data
.native_array
)
1189 var gl_error
= glGetError
1190 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1199 var indices
= local_indices_buffer
1200 var io
= sprite_index
*4
1208 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
1209 glBufferSubData
(gl_ELEMENT_ARRAY_BUFFER
, sprite_index
*6*2, 6*2, indices
.native_array
)
1211 gl_error
= glGetError
1212 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1215 # Draw all `sprites`
1217 # Call `resize` and `update_sprite` as needed before actual draw operation.
1219 # Require: `app.simple_2d_program` and `mvp` must be bound on the GPU
1222 if buffer_array
== -1 then prepare
1224 assert buffer_array
> 0 and buffer_element
> 0 else
1225 print_error
"Internal error: {self} was destroyed"
1229 glBindBuffer
(gl_ARRAY_BUFFER
, buffer_array
)
1230 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, buffer_element
)
1232 # Resize GPU buffers?
1233 if sprites
.capacity
> buffer_capacity
then
1234 # Try to defragment first
1235 var moved
= sprites
.defragment
1237 if sprites
.capacity
> buffer_capacity
then
1238 # Defragmentation wasn't enough, grow
1241 # We must update everything
1242 for s
in sprites
.items
do if s
!= null then sprites_to_update
.add s
1244 # Just update the moved sprites
1245 for s
in moved
do sprites_to_update
.add s
1247 else if sprites
.available
.not_empty
then
1248 # Defragment a bit anyway
1249 # TODO defrag only when there's time left on a frame
1250 var moved
= sprites
.defragment
(1)
1251 for s
in moved
do sprites_to_update
.add s
1254 # Update GPU sprites data
1255 if sprites_to_update
.not_empty
then
1256 app
.perf_clock_sprites
.lapse
1258 for sprite
in sprites_to_update
do update_sprite
(sprite
)
1259 sprites_to_update
.clear
1261 sys
.perfs
["gamnit flat gpu update"].add app
.perf_clock_sprites
.lapse
1264 # Update uniforms specific to this context
1265 var texture
= texture
1266 app
.simple_2d_program
.use_texture
.uniform texture
!= null
1267 if texture
!= null then
1268 glActiveTexture gl_TEXTURE0
1269 glBindTexture
(gl_TEXTURE_2D
, texture
.gl_texture
)
1270 app
.simple_2d_program
.texture
.uniform
0
1272 var gl_error
= glGetError
1273 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1275 var animation
= animation_texture
1276 if animation
!= null then
1277 glActiveTexture gl_TEXTURE1
1278 glBindTexture
(gl_TEXTURE_2D
, animation
.gl_texture
)
1279 app
.simple_2d_program
.animation_texture
.uniform
1
1281 gl_error
= glGetError
1282 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1284 # Configure attributes, in order:
1285 # vec4 translation, vec4 color, float scale, vec4 coord, vec2 tex_coord, vec4 rotation_row*,
1286 # a_fps, a_n_frames, a_coord, a_tex_coord, a_tex_diff, a_start, a_loops
1289 var p
= app
.simple_2d_program
1290 var sizeof_gl_float
= 4 # sizeof(GL_FLOAT)
1292 var size
= 4 # Number of floats
1293 glEnableVertexAttribArray p
.translation
.location
1294 glVertexAttribPointeri
(p
.translation
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1295 offset
+= size
* sizeof_gl_float
1296 gl_error
= glGetError
1297 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1300 glEnableVertexAttribArray p
.color
.location
1301 glVertexAttribPointeri
(p
.color
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1302 offset
+= size
* sizeof_gl_float
1303 gl_error
= glGetError
1304 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1307 glEnableVertexAttribArray p
.scale
.location
1308 glVertexAttribPointeri
(p
.scale
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1309 offset
+= size
* sizeof_gl_float
1310 gl_error
= glGetError
1311 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1314 glEnableVertexAttribArray p
.coord
.location
1315 glVertexAttribPointeri
(p
.coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1316 offset
+= size
* sizeof_gl_float
1317 gl_error
= glGetError
1318 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1321 glEnableVertexAttribArray p
.tex_coord
.location
1322 glVertexAttribPointeri
(p
.tex_coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1323 offset
+= size
* sizeof_gl_float
1324 gl_error
= glGetError
1325 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1328 for r
in [p
.rotation_row0
, p
.rotation_row1
, p
.rotation_row2
, p
.rotation_row3
] do
1330 glEnableVertexAttribArray r
.location
1331 glVertexAttribPointeri
(r
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1333 offset
+= size
* sizeof_gl_float
1334 gl_error
= glGetError
1335 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1339 glEnableVertexAttribArray p
.animation_fps
.location
1340 glVertexAttribPointeri
(p
.animation_fps
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1341 offset
+= size
* sizeof_gl_float
1342 gl_error
= glGetError
1343 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1346 glEnableVertexAttribArray p
.animation_n_frames
.location
1347 glVertexAttribPointeri
(p
.animation_n_frames
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1348 offset
+= size
* sizeof_gl_float
1349 gl_error
= glGetError
1350 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1353 glEnableVertexAttribArray p
.animation_coord
.location
1354 glVertexAttribPointeri
(p
.animation_coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1355 offset
+= size
* sizeof_gl_float
1356 gl_error
= glGetError
1357 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1360 glEnableVertexAttribArray p
.animation_tex_coord
.location
1361 glVertexAttribPointeri
(p
.animation_tex_coord
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1362 offset
+= size
* sizeof_gl_float
1363 gl_error
= glGetError
1364 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1367 glEnableVertexAttribArray p
.animation_tex_diff
.location
1368 glVertexAttribPointeri
(p
.animation_tex_diff
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1369 offset
+= size
* sizeof_gl_float
1370 gl_error
= glGetError
1371 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1374 glEnableVertexAttribArray p
.animation_start
.location
1375 glVertexAttribPointeri
(p
.animation_start
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1376 offset
+= size
* sizeof_gl_float
1377 gl_error
= glGetError
1378 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1381 glEnableVertexAttribArray p
.animation_loops
.location
1382 glVertexAttribPointeri
(p
.animation_loops
.location
, size
, gl_FLOAT
, false, bytes_per_vertex
, offset
)
1383 offset
+= size
* sizeof_gl_float
1384 gl_error
= glGetError
1385 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1388 for s
in sprites
.starts
, e
in sprites
.ends
do
1390 glDrawElementsi
(gl_TRIANGLES
, l
*indices_per_sprite
, gl_UNSIGNED_SHORT
, 2*s
*indices_per_sprite
)
1391 gl_error
= glGetError
1392 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1396 for attr
in [p
.translation
, p
.color
, p
.scale
, p
.coord
, p
.tex_coord
,
1397 p
.rotation_row0
, p
.rotation_row1
, p
.rotation_row2
, p
.rotation_row3
: Attribute] do
1398 if not attr
.is_active
then continue
1399 glDisableVertexAttribArray
(attr
.location
)
1400 gl_error
= glGetError
1401 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1404 glBindBuffer
(gl_ARRAY_BUFFER
, 0)
1405 glBindBuffer
(gl_ELEMENT_ARRAY_BUFFER
, 0)
1406 gl_error
= glGetError
1407 assert gl_error
== gl_NO_ERROR
else print_error gl_error
1411 # Representation of sprite data on the GPU
1413 # The main purpose of this class is to optimize the use of contiguous
1414 # space in GPU memory. Each contiguous memory block can be drawn in a
1415 # single call. The starts index of each block is kept by `starts,
1416 # and the end + 1 by `ends`.
1418 # The data can be compressed by a call to `defragment`.
1421 # intrude import gamnit::flat
1423 # var array = new GroupedArray[String]
1424 # assert array.to_s == ""
1432 # assert array.to_s == "[a,b,c,d,e,f]"
1433 # assert array.capacity == 6
1436 # assert array.to_s == "[b,c,d,e,f]"
1439 # assert array.to_s == "[c,d,e,f]"
1442 # assert array.to_s == "[c,d,e]"
1445 # assert array.to_s == "[c][e]"
1448 # assert array.to_s == "[A][c][e]"
1451 # assert array.to_s == "[A,B,c][e]"
1454 # assert array.to_s == "[A,B,c]"
1457 # assert array.to_s == "[A,B,c,D]"
1460 # assert array.to_s == "[A,B,c,D,E]"
1461 # assert array.capacity == 6
1462 # assert array.length == 5
1469 # assert array.to_s == ""
1472 # assert array.to_s == "[a]"
1474 private class GroupedArray[E
]
1476 # Memory with actual objects, and null in empty slots
1477 var items
= new Array[nullable E
]
1479 # Number of items in the array
1482 # Number of item slots in the array
1483 fun capacity
: Int do return items
.length
1486 fun index_of
(item
: E
): Int do return items
.index_of
(item
)
1488 # List of available slots
1489 var available
= new MinHeap[Int].default
1491 # Start index of filled chunks
1492 var starts
= new List[Int]
1494 # Index of the spots after filled chunks
1495 var ends
= new List[Int]
1497 # Add `item` to the first available slot
1502 if available
.not_empty
then
1503 # starts & ends can't be empty
1505 var i
= available
.take
1508 if i
== starts
.first
- 1 then
1509 # slot 0 free, 1 taken
1512 # slot 0 and more free
1515 else if starts
.length
>= 2 and ends
.first
+ 1 == starts
[1] then
1520 # at end of first chunk
1527 if ends
.is_empty
then
1533 # Remove the first instance of `item`
1536 var i
= items
.index_of
(item
)
1542 for s
in starts
, e
in ends
do
1543 if s
<= i
and i
< e
then
1549 if starts
.is_empty
then
1554 else if e-1
== i
then
1555 # last item of chunk
1559 # first item of chunk
1563 ends
.insert
(ends
[ii
], ii
+1)
1565 starts
.insert
(i
+1, ii
+1)
1577 # Defragment and compress everything into a single chunks beginning at 0
1579 # Returns the elements that moved as a list.
1582 # intrude import gamnit::flat
1584 # var array = new GroupedArray[String]
1591 # assert array.to_s == "[b][d]"
1593 # var moved = array.defragment
1594 # assert moved.to_s == "[d]"
1595 # assert array.to_s == "[d,b]"
1596 # assert array.length == 2
1597 # assert array.capacity == 2
1601 # assert array.to_s == "[d,b,e,f]"
1603 fun defragment
(max
: nullable Int): Array[E
]
1605 app
.perf_clock_sprites
.lapse
1606 max
= max
or else length
1608 var moved
= new Array[E
]
1609 while max
> 0 and (starts
.length
> 1 or starts
.first
!= 0) do
1610 var i
= ends
.last
- 1
1618 if starts
.length
== 1 and starts
.first
== 0 then
1619 for i
in [length
..capacity
[ do items
.pop
1623 sys
.perfs
["gamnit flat gpu defrag"].add app
.perf_clock_sprites
.lapse
1629 var ss
= new Array[String]
1630 for s
in starts
, e
in ends
do
1633 var item
: nullable Object = items
[i
]
1634 if item
== null then item
= "null"
1636 if i
!= e-1
then ss
.add
","
1644 redef class GLfloatArray
1645 private fun fill_from_matrix
(matrix
: Matrix, dst_offset
: nullable Int)
1647 dst_offset
= dst_offset
or else 0
1648 var mat_len
= matrix
.width
*matrix
.height
1649 assert length
>= mat_len
+ dst_offset
1650 native_array
.fill_from_matrix_native
(matrix
.items
, dst_offset
, mat_len
)
1654 redef class NativeGLfloatArray
1655 private fun fill_from_matrix_native
(matrix
: matrix
::NativeDoubleArray, dst_offset
, len
: Int) `{
1657 for (i = 0; i < len; i ++)
1658 self[i+dst_offset] = (GLfloat)matrix[i];