#Trouble wrapping my head around `cast discards const qualifier`

1 messages · Page 1 of 1 (latest)

full flower
#

I'm working on implementing a simple physics engine for learning purposes and I'm struggling to wrap my head around how to resolve a compiler error:

const std = @import("std");
const rl = @import("raylib");

pub const Particle = struct {
    position: rl.Vector3,
    velocity: rl.Vector3,
    mass: f32,

    const Self = @This();

    pub fn init(rand: std.Random) Self {
        const position = .{ .x = rand.float(f32) * 10, .y = rand.float(f32) * 10, .z = rand.float(f32) * 10 };
        const velocity = .{ .x = 0, .y = 0, .z = 0 };
        const mass = 1;
        return .{ .position = position, .velocity = velocity, .mass = mass };
    }

    pub fn physics_update(self: *Self) void {
        const force = self.compute_gravity();
        const acceleration: rl.Vector3 = .{ .x = force.x / self.mass, .y = force.y / self.mass, .z = force.z / self.mass };
        self.velocity.x += acceleration.x;
        self.velocity.y += acceleration.y;
        self.velocity.z += acceleration.z;

        self.position.x += self.velocity.x;
        self.position.y += self.velocity.y;
        self.position.z += self.velocity.z;
    }

    pub fn compute_gravity(self: *Self) rl.Vector3 {
        return .{ .x = 0, .y = self.mass * -9.81, .z = 0 };
    }
};

pub fn particle_sim() !void {
    const particle_count: u8 = 1;

    var prng = std.rand.DefaultPrng.init(blk: {
        var seed: u64 = undefined;
        try std.posix.getrandom(std.mem.asBytes(&seed));
        break :blk seed;
    });
    const rand = prng.random();
    const p1 = Particle.init(rand);
    const particles = [particle_count]Particle{p1};

    const sim_time: u8 = 10;
    var current_time: u8 = 0;

    while (current_time < sim_time) {
        std.time.sleep(1_000_000);

        for (&particles) |*p| {
            p.physics_update();
        }
        current_time += 1;
    }
}

brittle void
#

your particles is const

muted radish
#

const particles = [particle_count]Particle{p1};here

#

ya

brittle void
#
var particles: [particle_count]Particle = @splat(p1);
full flower
#

ahhhhh