e3be7953628ea34d6b8aedbd4b856707479b7176
[nit.git] / lib / gamnit / depth / particles.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 # Particle effects
16 #
17 # Particles are managed by instances of `ParticleSystem` that
18 # are configured for a specific kind of particle.
19 # For instance, a particle system can be created for a max of 100 particles,
20 # with a smoke effect and a precise texture, as in:
21 #
22 # ~~~
23 # var smoke = new ParticleSystem(100, app.smoke_program, new Texture("smoke.png"))
24 # ~~~
25 #
26 # The system must be registered in `app.particle_systems` to be drawn on screen.
27 #
28 # Particles are added to a system with their configuration, as in:
29 #
30 # ~~~
31 # var position = new Point3d[Float](0.0, 0.0, 0.0)
32 # var scale = 2.0
33 # var time_to_live = 1.0 # in seconds
34 # smoke.add(position, scale, time_to_live)
35 # ~~~
36 module particles
37
38 import depth_core
39
40 redef class App
41
42 # Graphics program to display blowing up particles
43 var explosion_program = new ExplosionProgram
44
45 # Graphics program to display particles slowly drifting upwards
46 var smoke_program = new SmokeProgram
47
48 # Enabled particle emitters
49 #
50 # To be populated by the client program.
51 var particle_systems = new Array[ParticleSystem]
52 end
53
54 # Particle system using `program` and `texture` to draw each particles
55 #
56 # Each instance draws a maximum of `n_particles`.
57 # If full, new particles replace the oldest particles.
58 # Expired particle are still sent to the CPU but should be discarded by the vertex shader.
59 class ParticleSystem
60
61 # Maximum number of particles
62 var n_particles: Int
63
64 private var total_particles = 0
65
66 # Program to draw the particles
67 var program: ParticleProgram
68
69 # Texture to apply on particles, if any
70 var texture: nullable Texture
71
72 # Clock used to set `ots` and `program::t`
73 #
74 # TODO control this value from the game logic to allow pausing and slowing time.
75 private var clock = new Clock
76
77 # Coordinates of each particle effects
78 private var centers = new Array[Float]
79
80 # Creation time of each particles
81 private var ots = new Array[Float]
82
83 # Scale of each particles
84 private var scales = new Array[Float]
85
86 # Time-to-live of each particle
87 private var ttls = new Array[Float]
88
89 # Add a particle at `center` with `scale`, living for `ttl` from `time_offset`
90 #
91 # `time_offset` is added to the creation time, it can be used to delay the
92 # apparition of a particle using a positive value.
93 #
94 # See the doc of the precise class of `program`, or the general `ParticleProgram`
95 # for information on the effect of these parameters.
96 fun add(center: Point3d[Float], scale: Float, ttl: Float, time_offset: nullable Float)
97 do
98 var i = total_particles % n_particles
99 total_particles += 1
100
101 centers[i*3 ] = center.x
102 centers[i*3+1] = center.y
103 centers[i*3+2] = center.z
104
105 ttls[i] = ttl
106 scales[i] = scale
107
108 time_offset = time_offset or else 0.0
109 ots[i] = clock.total.to_f + time_offset
110 end
111
112 # Draw all particles of this emitter
113 fun draw
114 do
115 if ots.is_empty then return
116
117 var program = program
118 program.use
119
120 var texture = texture
121 if texture != null then
122 glActiveTexture gl_TEXTURE0
123 glBindTexture(gl_TEXTURE_2D, texture.gl_texture)
124 program.use_texture.uniform true
125 program.texture.uniform 0
126 else
127 program.use_texture.uniform false
128 end
129
130 program.scale.array_enabled = true
131 program.scale.array(scales, 1)
132
133 program.center.array_enabled = true
134 program.center.array(centers, 3)
135
136 program.color.array_enabled = false
137 program.color.uniform(1.0, 1.0, 1.0, 1.0)
138
139 program.ot.array_enabled = true
140 program.ot.array(ots, 1)
141
142 program.ttl.array_enabled = true
143 program.ttl.array(ttls, 1)
144
145 program.t.uniform clock.total.to_f
146 program.mvp.uniform app.world_camera.mvp_matrix
147
148 glDrawArrays(gl_POINTS, 0, ots.length)
149 end
150 end
151
152 # Particle drawing program using `gl_POINTS`
153 #
154 # This program should be subclassed to create custom particle effects.
155 # Either `vertex_shader_source` and `vertex_shader_core` can be refined.
156 abstract class ParticleProgram
157 super GamnitProgramFromSource
158
159 redef var vertex_shader_source = """
160 // Coordinates of particle effects
161 attribute vec4 center;
162
163 // Particles color tint
164 attribute vec4 color;
165 varying vec4 v_color;
166
167 // Per particle scaling
168 attribute float scale;
169
170 // Model view projection matrix
171 uniform mat4 mvp;
172
173 // Time-to-live of each particle
174 attribute float ttl;
175
176 // Creation time of each particle
177 attribute float ot;
178
179 // Current time
180 uniform float t;
181
182 void main()
183 {
184 // Pass varyings to the fragment shader
185 v_color = color;
186
187 float dt = t - ot;
188 float pt = dt/ttl;
189
190 // Discard expired or not yet created particles
191 if (dt > ttl || dt < 0.0) {
192 gl_PointSize = 0.0;
193 return;
194 }
195
196 {{{vertex_shader_core}}}
197 }
198 """
199
200 # Core GLSL code for `vertex_shader_source`
201 #
202 # Refine this function to easily tweak the position, size and color of particles.
203 #
204 # Reminder: Each execution of the vertex shader applies to a single particle.
205 #
206 # ## Input variables:
207 # * `center`: reference coordinates of the particle effect.
208 # This if often the center of the particle itself,
209 # but it can also be reference coordinates for a moving particle.
210 # * `mvp`: model-view-projection matrix.
211 # * `color`: color tint of the particle.
212 #
213 # * `t`: global seconds counter since the creation of this particle emitter.
214 # * `ot`: creation time of the particle, in seconds, in reference to `t`.
215 # * `dt`: seconds since creation of the particle.
216 # * `ttl`: time-to-live of the particle, in seconds.
217 # * `pt`: advancement of this particle in its lifetime, in `[0.0 .. 1.0]`.
218 #
219 # ## Output variables:
220 # * `gl_Position`: position of the particle in camera coordinates.
221 # * `gl_PointSize`: size of the particle in camera coordinates.
222 # Set to `0.0` to discard the particle.
223 # * `v_color`: tint applied to the particle.
224 # Assigned by default to the value of `color`.
225 #
226 # ## Reference implementation
227 #
228 # The default implementation apply the model-view-projection matrix on the position
229 # and scales according to the distance from the camera.
230 # Most particle effects should apply the same base logic as the default implementation.
231 # Here it is for reference:
232 #
233 # ~~~glsl
234 # gl_Position = center * mvp;
235 # gl_PointSize = scale / gl_Position.z;
236 # ~~~
237 fun vertex_shader_core: String do return """
238 gl_Position = center * mvp;
239 gl_PointSize = scale / gl_Position.z;
240 """
241
242 redef var fragment_shader_source = """
243 precision mediump float;
244
245 // Input from the vertex shader
246 varying vec4 v_color;
247
248 // Does this particle use a texture?
249 uniform bool use_texture;
250
251 // Texture to apply on this particle
252 uniform sampler2D texture;
253
254 void main()
255 {
256 if (use_texture) {
257 gl_FragColor = texture2D(texture, gl_PointCoord) * v_color;
258 if (gl_FragColor.a <= 0.01) discard;
259 } else {
260 gl_FragColor = v_color;
261 }
262 }
263 """ @ glsl_fragment_shader
264
265 # Coordinates of particle effects
266 var center = attributes["center"].as(AttributeVec4) is lazy
267
268 # Should this program use the texture `texture`?
269 var use_texture = uniforms["use_texture"].as(UniformBool) is lazy
270
271 # Visible texture unit
272 var texture = uniforms["texture"].as(UniformSampler2D) is lazy
273
274 # Color tint per vertex
275 var color = attributes["color"].as(AttributeVec4) is lazy
276
277 # Scaling per vertex
278 var scale = attributes["scale"].as(AttributeFloat) is lazy
279
280 # Model view projection matrix
281 var mvp = uniforms["mvp"].as(UniformMat4) is lazy
282
283 # Creation time of each particle
284 var ot = attributes["ot"].as(AttributeFloat) is lazy
285
286 # Current time
287 var t = uniforms["t"].as(UniformFloat) is lazy
288
289 # Time-to-live of each particle
290 var ttl = attributes["ttl"].as(AttributeFloat) is lazy
291 end
292
293 # Graphics program to display blowing up particles
294 class ExplosionProgram
295 super ParticleProgram
296
297 redef fun vertex_shader_core do return """
298 gl_Position = center * mvp;
299 gl_PointSize = scale / gl_Position.z * pt;
300
301 if (pt > 0.8) v_color.a = (1.0-pt)/0.2;
302 """
303 end
304
305 # Graphics program to display particles slowly drifting upwards
306 class SmokeProgram
307 super ParticleProgram
308
309 redef fun vertex_shader_core do return """
310 vec4 c = center;
311 c.y += dt * 1.0;
312 c.x += dt * 0.1;
313
314 gl_Position = c * mvp;
315 gl_PointSize = scale / gl_Position.z * (pt+0.1);
316
317 if (pt < 0.1)
318 v_color.a = pt / 0.1;
319 else
320 v_color.a = 1.0 - pt*0.9;
321 """
322 end