| 1 | // Copyright(C) 2019 Lars Pontoppidan. All rights reserved. |
| 2 | // Use of this source code is governed by an MIT license file distributed with this software package |
| 3 | module particle |
| 4 | |
| 5 | import math.vec |
| 6 | import sokol.sgl |
| 7 | |
| 8 | const default_life_time = 1000 |
| 9 | const default_v_color = Color{93, 136, 193, 255} |
| 10 | |
| 11 | // * Module public |
| 12 | pub fn new(location vec.Vec2[f64]) &Particle { |
| 13 | p := &Particle{ |
| 14 | location: location |
| 15 | velocity: vec.Vec2[f64]{0, 0} |
| 16 | acceleration: vec.Vec2[f64]{0, 0} |
| 17 | color: default_v_color |
| 18 | life_time: default_life_time |
| 19 | life_time_init: default_life_time |
| 20 | } |
| 21 | return p |
| 22 | } |
| 23 | |
| 24 | fn remap(v f64, min f64, max f64, new_min f64, new_max f64) f64 { |
| 25 | return (((v - min) * (new_max - new_min)) / (max - min)) + new_min |
| 26 | } |
| 27 | |
| 28 | // Particle |
| 29 | pub struct Particle { |
| 30 | pub mut: |
| 31 | location vec.Vec2[f64] |
| 32 | velocity vec.Vec2[f64] |
| 33 | acceleration vec.Vec2[f64] |
| 34 | color Color |
| 35 | life_time f64 |
| 36 | life_time_init f64 |
| 37 | } |
| 38 | |
| 39 | pub fn (mut p Particle) update(dt f64) { |
| 40 | mut acc := p.acceleration |
| 41 | acc.multiply_scalar(dt) |
| 42 | p.velocity = p.velocity.add(acc) |
| 43 | p.location = p.location.add(p.velocity) |
| 44 | lt := p.life_time - (1000 * dt) |
| 45 | if lt > 0 { |
| 46 | p.life_time = lt |
| 47 | p.color.r = p.color.r - 1 // u8(remap(p.life_time,0.0,p.life_time_init,0,p.color.r)) |
| 48 | p.color.g = p.color.g - 1 // u8(remap(p.life_time,0.0,p.life_time_init,0,p.color.g)) |
| 49 | p.color.b = p.color.b - 1 // u8(remap(p.life_time,0.0,p.life_time_init,0,p.color.b)) |
| 50 | p.color.a = u8(int(remap(p.life_time, 0.0, p.life_time_init, 0, 255))) - 10 |
| 51 | } else { |
| 52 | p.life_time = 0 |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | pub fn (p Particle) is_dead() bool { |
| 57 | return p.life_time <= 0.0 |
| 58 | } |
| 59 | |
| 60 | pub fn (p Particle) draw() { |
| 61 | l := p.location |
| 62 | sgl.c4b(p.color.r, p.color.g, p.color.b, p.color.a) |
| 63 | lx := f32(l.x) |
| 64 | ly := f32(l.y) |
| 65 | sgl.v2f(lx, ly) |
| 66 | sgl.v2f(lx + 2, ly) |
| 67 | sgl.v2f(lx + 2, ly + 2) |
| 68 | sgl.v2f(lx, ly + 2) |
| 69 | } |
| 70 | |
| 71 | pub fn (mut p Particle) reset() { |
| 72 | p.location.zero() |
| 73 | p.acceleration.zero() |
| 74 | p.velocity.zero() |
| 75 | // p.color = Color{93, 136, 193, 255} |
| 76 | p.color = default_v_color |
| 77 | p.life_time = default_life_time |
| 78 | p.life_time_init = p.life_time |
| 79 | } |
| 80 | |