Update zig

This one was annoying.
This commit is contained in:
IntegratedQuantum 2024-04-03 13:57:25 +02:00
parent 2dfbe98844
commit 0acb0e2c80
24 changed files with 166 additions and 165 deletions

View File

@ -1 +1 @@
0.12.0-dev.3142+9d500bda2
0.12.0-dev.3518+d2be725e4

View File

@ -212,7 +212,7 @@ var curIndex: u16 = 0;
var curEndIndex: std.atomic.Value(u16) = .{.value = sampleRate/60 & ~@as(u16, 1)};
fn addMusic(buffer: []f32) void {
const musicId = if(main.game.world) |world| world.playerBiome.load(.Monotonic).preferredMusic else "cubyz";
const musicId = if(main.game.world) |world| world.playerBiome.load(.monotonic).preferredMusic else "cubyz";
if(!std.mem.eql(u8, musicId, activeMusicId)) {
if(activeMusicId.len == 0) {
if(findMusic(musicId)) |musicBuffer| {

View File

@ -113,7 +113,7 @@ pub const ClientEntityManager = struct {
fn update() void {
std.debug.assert(!mutex.tryLock()); // The mutex should be locked when calling this function.
var time: i16 = @truncate(std.time.milliTimestamp());
time -%= timeDifference.difference.load(.Monotonic);
time -%= timeDifference.difference.load(.monotonic);
for(entities.items) |*ent| {
ent.update(time, lastTime);
}

View File

@ -177,14 +177,14 @@ pub const World = struct {
const newTime: i64 = std.time.milliTimestamp();
while(self.milliTime +% 100 -% newTime < 0) {
self.milliTime +%= 100;
var curTime = self.gameTime.load(.Monotonic);
while(self.gameTime.cmpxchgWeak(curTime, curTime +% 1, .Monotonic, .Monotonic)) |actualTime| {
var curTime = self.gameTime.load(.monotonic);
while(self.gameTime.cmpxchgWeak(curTime, curTime +% 1, .monotonic, .monotonic)) |actualTime| {
curTime = actualTime;
}
}
// Ambient light:
{
var dayTime = @abs(@mod(self.gameTime.load(.Monotonic), dayCycle) -% dayCycle/2);
var dayTime = @abs(@mod(self.gameTime.load(.monotonic), dayCycle) -% dayCycle/2);
if(dayTime < dayCycle/4 - dayCycle/16) {
self.ambientLight = 0.1;
self.clearColor[0] = 0;
@ -238,7 +238,7 @@ pub fn update(deltaTime: f64) void {
if(main.Window.grabbed) {
if(KeyBoard.key("forward").pressed) {
if(KeyBoard.key("sprint").pressed) {
if(Player.isFlying.load(.Monotonic)) {
if(Player.isFlying.load(.monotonic)) {
movement += forward*@as(Vec3d, @splat(128));
} else {
movement += forward*@as(Vec3d, @splat(8));
@ -257,7 +257,7 @@ pub fn update(deltaTime: f64) void {
movement += right*@as(Vec3d, @splat(-4));
}
if(KeyBoard.key("jump").pressed) {
if(Player.isFlying.load(.Monotonic)) {
if(Player.isFlying.load(.monotonic)) {
if(KeyBoard.key("sprint").pressed) {
movement[2] = 59.45;
} else {
@ -268,7 +268,7 @@ pub fn update(deltaTime: f64) void {
}
}
if(KeyBoard.key("fall").pressed) {
if(Player.isFlying.load(.Monotonic)) {
if(Player.isFlying.load(.monotonic)) {
if(KeyBoard.key("sprint").pressed) {
movement[2] = -59.45;
} else {

View File

@ -25,16 +25,16 @@ pub var window = GuiWindow {
pub fn render() void {
draw.setColor(0xffffffff);
var y: f32 = 0;
draw.print(" fps: {d:.0} Hz{s}", .{1.0/main.lastFrameTime.load(.Monotonic), if(main.settings.vsync) @as([]const u8, " (vsync)") else ""}, 0, y, 8, .left);
draw.print(" fps: {d:.0} Hz{s}", .{1.0/main.lastFrameTime.load(.monotonic), if(main.settings.vsync) @as([]const u8, " (vsync)") else ""}, 0, y, 8, .left);
y += 8;
draw.print(" frameTime: {d:.1} ms", .{main.lastFrameTime.load(.Monotonic)*1000.0}, 0, y, 8, .left);
draw.print(" frameTime: {d:.1} ms", .{main.lastFrameTime.load(.monotonic)*1000.0}, 0, y, 8, .left);
y += 8;
draw.print("window size: {}×{}", .{main.Window.width, main.Window.height}, 0, y, 8, .left);
y += 8;
if (main.game.world != null) {
draw.print("Pos: {d:.1}", .{main.game.Player.getPosBlocking()}, 0, y, 8, .left);
y += 8;
draw.print("Game Time: {}", .{main.game.world.?.gameTime.load(.Monotonic)}, 0, y, 8, .left);
draw.print("Game Time: {}", .{main.game.world.?.gameTime.load(.monotonic)}, 0, y, 8, .left);
y += 8;
draw.print("Queue size: {}", .{main.threadPool.queueSize()}, 0, y, 8, .left);
y += 8;
@ -52,7 +52,7 @@ pub fn render() void {
draw.print("ChunkMesh memory: {} MiB / {} MiB (fragmentation: {} MiB)", .{used >> 20, size >> 20, fragmentation >> 20}, 0, y, 8, .left);
y += 8;
}
draw.print("Biome: {s}", .{main.game.world.?.playerBiome.load(.Monotonic).id}, 0, y, 8, .left);
draw.print("Biome: {s}", .{main.game.world.?.playerBiome.load(.monotonic).id}, 0, y, 8, .left);
y += 8;
draw.print("Opaque faces: {}, Transparent faces: {}", .{main.renderer.chunk_meshing.quadsDrawn, main.renderer.chunk_meshing.transparentQuadsDrawn}, 0, y, 8, .left);
y += 8;

View File

@ -31,15 +31,15 @@ pub fn render() void {
draw.print("Players Connected: {}", .{main.server.users.items.len}, 0, y, 8, .left);
y += 8;
}
const sent = network.Connection.packetsSent.load(.Monotonic);
const resent = network.Connection.packetsResent.load(.Monotonic);
const sent = network.Connection.packetsSent.load(.monotonic);
const resent = network.Connection.packetsResent.load(.monotonic);
const loss = @as(f64, @floatFromInt(resent))/@as(f64, @floatFromInt(sent))*100;
draw.print("Packet loss: {d:.1}% ({}/{})", .{loss, resent, sent}, 0, y, 8, .left);
y += 8;
inline for(@typeInfo(network.Protocols).Struct.decls) |decl| {
if(@TypeOf(@field(network.Protocols, decl.name)) == type) {
const id = @field(network.Protocols, decl.name).id;
draw.print("{s}: {}kiB in {} packets", .{decl.name, network.bytesReceived[id].load(.Monotonic) >> 10, network.packetsReceived[id].load(.Monotonic)}, 0, y, 8, .left);
draw.print("{s}: {}kiB in {} packets", .{decl.name, network.bytesReceived[id].load(.monotonic) >> 10, network.packetsReceived[id].load(.monotonic)}, 0, y, 8, .left);
y += 8;
}
}

View File

@ -34,7 +34,7 @@ fn discoverIpAddress() void {
return;
}; // TODO: default port
ipAddress = std.fmt.allocPrint(main.globalAllocator.allocator, "{}", .{connection.?.externalAddress}) catch unreachable;
gotIpAddress.store(true, .Release);
gotIpAddress.store(true, .release);
}
fn discoverIpAddressFromNewThread() void {
@ -115,8 +115,8 @@ pub fn onClose() void {
}
pub fn update() void {
if(gotIpAddress.load(.Acquire)) {
gotIpAddress.store(false, .Monotonic);
if(gotIpAddress.load(.acquire)) {
gotIpAddress.store(false, .monotonic);
ipAddressLabel.updateText(ipAddress);
}
}

View File

@ -49,7 +49,7 @@ pub fn deinit() void {
}
pub fn render() void {
lastFrameTime[index] = @floatCast(main.lastFrameTime.load(.Monotonic)*1000.0);
lastFrameTime[index] = @floatCast(main.lastFrameTime.load(.monotonic)*1000.0);
index = (index + 1)%@as(u31, @intCast(lastFrameTime.len));
draw.setColor(0xffffffff);
draw.text("32 ms", 0, 16, 8, .left);

View File

@ -506,7 +506,7 @@ pub const ClientItemDropManager = struct {
pub fn updateInterpolationData(self: *ClientItemDropManager) void {
var time = @as(i16, @truncate(std.time.milliTimestamp())) -% settings.entityLookback;
time -%= self.timeDifference.difference.load(.Monotonic);
time -%= self.timeDifference.difference.load(.monotonic);
{
self.super.mutex.lock();
defer self.super.mutex.unlock();

View File

@ -243,7 +243,8 @@ pub const JsonElement = union(JsonType) {
std.fmt.formatInt(value, 10, .lower, .{}, list.writer()) catch unreachable;
},
.JsonFloat => |value| {
std.fmt.formatFloatScientific(value, .{}, list.writer()) catch unreachable;
var buf: [std.fmt.format_float.bufferSize(.scientific, @TypeOf(value))]u8 = undefined;
list.appendSlice(std.fmt.format_float.formatFloat(&buf, value, .{.mode = .scientific}) catch unreachable);
},
.JsonBool => |value| {
if(value) {

View File

@ -780,9 +780,9 @@ pub fn main() void {
const deltaTime = @as(f64, @floatFromInt(newTime -% lastTime))/1e9;
if(@import("builtin").os.tag == .linux and deltaTime > 5) { // On linux a process that runs 10 seconds or longer on the GPU will get stopped. This allows detecting an infinite loop on the GPU.
std.log.err("Frame got too long with {} seconds. Infinite loop on GPU?", .{deltaTime});
std.os.exit(1);
std.posix.exit(1);
}
lastFrameTime.store(deltaTime, .Monotonic);
lastFrameTime.store(deltaTime, .monotonic);
lastTime = newTime;
if(game.world != null) { // Update the game
game.update(deltaTime);

View File

@ -23,12 +23,12 @@ const NeverFailingAllocator = main.utils.NeverFailingAllocator;
//TODO: Might want to use SSL or something similar to encode the message
const Socket = struct {
const os = std.os;
socketID: os.socket_t,
const posix = std.posix;
socketID: posix.socket_t,
fn startup() void {
if(builtin.os.tag == .windows) {
_ = os.windows.WSAStartup(2, 2) catch |err| {
_ = std.os.windows.WSAStartup(2, 2) catch |err| {
std.log.err("Could not initialize the Windows Socket API: {s}", .{@errorName(err)});
@panic("Could not init networking.");
};
@ -37,27 +37,27 @@ const Socket = struct {
fn init(localPort: u16) !Socket {
const self = Socket {
.socketID = try os.socket(os.AF.INET, os.SOCK.DGRAM, os.IPPROTO.UDP),
.socketID = try posix.socket(posix.AF.INET, posix.SOCK.DGRAM, posix.IPPROTO.UDP),
};
errdefer self.deinit();
const bindingAddr = os.sockaddr.in {
const bindingAddr = posix.sockaddr.in {
.port = @byteSwap(localPort),
.addr = 0,
};
try os.bind(self.socketID, @ptrCast(&bindingAddr), @sizeOf(os.sockaddr.in));
try posix.bind(self.socketID, @ptrCast(&bindingAddr), @sizeOf(posix.sockaddr.in));
return self;
}
fn deinit(self: Socket) void {
os.close(self.socketID);
posix.close(self.socketID);
}
fn send(self: Socket, data: []const u8, destination: Address) void {
const addr = os.sockaddr.in {
const addr = posix.sockaddr.in {
.port = @byteSwap(destination.port),
.addr = destination.ip,
};
std.debug.assert(data.len == os.sendto(self.socketID, data, 0, @ptrCast(&addr), @sizeOf(os.sockaddr.in)) catch |err| {
std.debug.assert(data.len == posix.sendto(self.socketID, data, 0, @ptrCast(&addr), @sizeOf(posix.sockaddr.in)) catch |err| {
std.log.info("Got error while sending to {}: {s}", .{destination, @errorName(err)});
return;
});
@ -65,32 +65,32 @@ const Socket = struct {
fn receive(self: Socket, buffer: []u8, timeout: i32, resultAddress: *Address) ![]u8 {
if(builtin.os.tag == .windows) { // Of course Windows always has it's own special thing.
var pfd = [1]os.pollfd {
var pfd = [1]posix.pollfd {
.{.fd = self.socketID, .events = std.c.POLL.RDNORM | std.c.POLL.RDBAND, .revents = undefined},
};
const length = os.windows.ws2_32.WSAPoll(&pfd, pfd.len, 0); // The timeout is set to zero. Otherwise sendto operations from other threads will block on this.
if (length == os.windows.ws2_32.SOCKET_ERROR) {
switch (os.windows.ws2_32.WSAGetLastError()) {
const length = std.os.windows.ws2_32.WSAPoll(&pfd, pfd.len, 0); // The timeout is set to zero. Otherwise sendto operations from other threads will block on this.
if (length == std.os.windows.ws2_32.SOCKET_ERROR) {
switch (std.os.windows.ws2_32.WSAGetLastError()) {
.WSANOTINITIALISED => unreachable,
.WSAENETDOWN => return error.NetworkSubsystemFailed,
.WSAENOBUFS => return error.SystemResources,
// TODO: handle more errors
else => |err| return os.windows.unexpectedWSAError(err),
else => |err| return std.os.windows.unexpectedWSAError(err),
}
} else if(length == 0) {
std.time.sleep(1000000); // Manually sleep, since WSAPoll is blocking.
return error.Timeout;
}
} else {
var pfd = [1]os.pollfd {
.{.fd = self.socketID, .events = os.POLL.IN, .revents = undefined},
var pfd = [1]posix.pollfd {
.{.fd = self.socketID, .events = posix.POLL.IN, .revents = undefined},
};
const length = try os.poll(&pfd, timeout);
const length = try posix.poll(&pfd, timeout);
if(length == 0) return error.Timeout;
}
var addr: os.sockaddr.in = undefined;
var addrLen: os.socklen_t = @sizeOf(os.sockaddr.in);
const length = try os.recvfrom(self.socketID, buffer, 0, @ptrCast(&addr), &addrLen);
var addr: posix.sockaddr.in = undefined;
var addrLen: posix.socklen_t = @sizeOf(posix.sockaddr.in);
const length = try posix.recvfrom(self.socketID, buffer, 0, @ptrCast(&addr), &addrLen);
resultAddress.ip = addr.addr;
resultAddress.port = @byteSwap(addr.port);
return buffer[0..length];
@ -417,7 +417,7 @@ pub const ConnectionManager = struct {
conn.disconnect();
}
self.running.store(false, .Monotonic);
self.running.store(false, .monotonic);
self.thread.join();
Socket.deinit(self.socket);
self.connections.deinit();
@ -430,9 +430,9 @@ pub const ConnectionManager = struct {
}
pub fn makeOnline(self: *ConnectionManager) void {
if(!self.online.load(.Acquire)) {
if(!self.online.load(.acquire)) {
self.externalAddress = STUN.requestAddress(self);
self.online.store(true, .Release);
self.online.store(true, .release);
}
}
@ -523,7 +523,7 @@ pub const ConnectionManager = struct {
return;
}
}
if(self.online.load(.Acquire) and source.ip == self.externalAddress.ip and source.port == self.externalAddress.port) return;
if(self.online.load(.acquire) and source.ip == self.externalAddress.ip and source.port == self.externalAddress.port) return;
// TODO: Reduce the number of false alarms in the short period after a disconnect.
std.log.warn("Unknown connection from address: {}", .{source});
std.log.debug("Message: {any}", .{data});
@ -536,7 +536,7 @@ pub const ConnectionManager = struct {
main.stackAllocator = sta.allocator();
var lastTime = std.time.milliTimestamp();
while(self.running.load(.Monotonic)) {
while(self.running.load(.monotonic)) {
self.waitingToFinishReceive.broadcast();
var source: Address = undefined;
if(self.socket.receive(&self.receiveBuffer, 100, &source)) |data| {
@ -569,7 +569,7 @@ pub const ConnectionManager = struct {
i += 1;
}
}
if(self.connections.items.len == 0 and self.online.load(.Acquire)) {
if(self.connections.items.len == 0 and self.online.load(.acquire)) {
// Send a message to external ip, to keep the port open:
const data = [1]u8{0};
self.send(&data, self.externalAddress);
@ -601,8 +601,8 @@ pub const Protocols = struct {
const stepComplete: u8 = 255;
fn receive(conn: *Connection, data: []const u8) !void {
if(conn.handShakeState.load(.Monotonic) < data[0]) {
conn.handShakeState.store(data[0], .Monotonic);
if(conn.handShakeState.load(.monotonic) < data[0]) {
conn.handShakeState.store(data[0], .monotonic);
switch(data[0]) {
stepUserData => {
const json = JsonElement.parseFromString(main.stackAllocator, data[1..]);
@ -642,8 +642,8 @@ pub const Protocols = struct {
const outData = jsonObject.toStringEfficient(main.stackAllocator, &[1]u8{stepServerData});
defer main.stackAllocator.free(outData);
conn.sendImportant(id, outData);
conn.handShakeState.store(stepServerData, .Monotonic);
conn.handShakeState.store(stepComplete, .Monotonic);
conn.handShakeState.store(stepServerData, .monotonic);
conn.handShakeState.store(stepComplete, .monotonic);
// TODO:
// synchronized(conn) { // Notify the waiting server thread.
// conn.notifyAll();
@ -660,7 +660,7 @@ pub const Protocols = struct {
const json = JsonElement.parseFromString(main.stackAllocator, data[1..]);
defer json.free(main.stackAllocator);
try conn.manager.world.?.finishHandshake(json);
conn.handShakeState.store(stepComplete, .Monotonic);
conn.handShakeState.store(stepComplete, .monotonic);
conn.handShakeWaiting.broadcast(); // Notify the waiting client thread.
},
stepComplete => {
@ -676,7 +676,7 @@ pub const Protocols = struct {
}
pub fn serverSide(conn: *Connection) void {
conn.handShakeState.store(stepStart, .Monotonic);
conn.handShakeState.store(stepStart, .monotonic);
}
pub fn clientSide(conn: *Connection, name: []const u8) void {
@ -1086,19 +1086,19 @@ pub const Protocols = struct {
const json = JsonElement.parseFromString(main.stackAllocator, data[1..]);
defer json.free(main.stackAllocator);
const expectedTime = json.get(i64, "time", 0);
var curTime = world.gameTime.load(.Monotonic);
var curTime = world.gameTime.load(.monotonic);
if(@abs(curTime -% expectedTime) >= 1000) {
world.gameTime.store(expectedTime, .Monotonic);
world.gameTime.store(expectedTime, .monotonic);
} else if(curTime < expectedTime) { // world.gameTime++
while(world.gameTime.cmpxchgWeak(curTime, curTime +% 1, .Monotonic, .Monotonic)) |actualTime| {
while(world.gameTime.cmpxchgWeak(curTime, curTime +% 1, .monotonic, .monotonic)) |actualTime| {
curTime = actualTime;
}
} else { // world.gameTime--
while(world.gameTime.cmpxchgWeak(curTime, curTime -% 1, .Monotonic, .Monotonic)) |actualTime| {
while(world.gameTime.cmpxchgWeak(curTime, curTime -% 1, .monotonic, .monotonic)) |actualTime| {
curTime = actualTime;
}
}
world.playerBiome.store(main.server.terrain.biomes.getById(json.get([]const u8, "biome", "")), .Monotonic);
world.playerBiome.store(main.server.terrain.biomes.getById(json.get([]const u8, "biome", "")), .monotonic);
}
},
else => |unrecognizedType| {
@ -1275,7 +1275,7 @@ pub const Protocols = struct {
data = _inflatedData;
const map = main.globalAllocator.create(main.server.terrain.LightMap.LightMapFragment);
map.init(pos.wx, pos.wy, pos.voxelSize);
_ = map.refCount.fetchAdd(1, .Monotonic);
_ = map.refCount.fetchAdd(1, .monotonic);
for(&map.startHeight) |*val| {
val.* = std.mem.readInt(i16, data[0..2], .big);
data = data[2..];
@ -1402,7 +1402,7 @@ pub const Connection = struct {
.id = id,
};
self.unconfirmedPackets.append(packet);
_ = packetsSent.fetchAdd(1, .Monotonic);
_ = packetsSent.fetchAdd(1, .monotonic);
self.manager.send(packet.data, self.remoteAddress);
self.streamPosition = importantHeaderSize;
}
@ -1546,8 +1546,8 @@ pub const Connection = struct {
// Resend packets that didn't receive confirmation within the last 2 keep-alive signals.
for(self.unconfirmedPackets.items) |*packet| {
if(self.lastKeepAliveReceived -% @as(i33, packet.lastKeepAliveSentBefore) >= 2) {
_ = packetsSent.fetchAdd(1, .Monotonic);
_ = packetsResent.fetchAdd(1, .Monotonic);
_ = packetsSent.fetchAdd(1, .monotonic);
_ = packetsResent.fetchAdd(1, .monotonic);
self.manager.send(packet.data, self.remoteAddress);
packet.lastKeepAliveSentBefore = self.lastKeepAliveSent;
}
@ -1631,7 +1631,7 @@ pub const Connection = struct {
self.lastReceivedPackets[self.lastIncompletePacket & 65535] = null;
}
self.lastIndex = newIndex;
_ = bytesReceived[protocol].fetchAdd(data.len + 1 + (7 + std.math.log2_int(usize, 1 + data.len))/7, .Monotonic);
_ = bytesReceived[protocol].fetchAdd(data.len + 1 + (7 + std.math.log2_int(usize, 1 + data.len))/7, .monotonic);
if(Protocols.list[protocol]) |prot| {
try prot(self, data);
} else {
@ -1650,15 +1650,15 @@ pub const Connection = struct {
pub fn flawedReceive(self: *Connection, data: []const u8) !void {
std.debug.assert(self.manager.threadId == std.Thread.getCurrentId());
const protocol = data[0];
if(self.handShakeState.load(.Monotonic) != Protocols.handShake.stepComplete and protocol != Protocols.handShake.id and protocol != Protocols.keepAlive and protocol != Protocols.important) {
if(self.handShakeState.load(.monotonic) != Protocols.handShake.stepComplete and protocol != Protocols.handShake.id and protocol != Protocols.keepAlive and protocol != Protocols.important) {
return; // Reject all non-handshake packets until the handshake is done.
}
self.lastConnection = std.time.milliTimestamp();
_ = bytesReceived[protocol].fetchAdd(data.len + 20 + 8, .Monotonic); // Including IP header and udp header;
_ = packetsReceived[protocol].fetchAdd(1, .Monotonic);
_ = bytesReceived[protocol].fetchAdd(data.len + 20 + 8, .monotonic); // Including IP header and udp header;
_ = packetsReceived[protocol].fetchAdd(1, .monotonic);
if(protocol == Protocols.important) {
const id = std.mem.readInt(u32, data[1..5], .big);
if(self.handShakeState.load(.Monotonic) == Protocols.handShake.stepComplete and id == 0) { // Got a new "first" packet from client. So the client tries to reconnect, but we still think it's connected.
if(self.handShakeState.load(.monotonic) == Protocols.handShake.stepComplete and id == 0) { // Got a new "first" packet from client. So the client tries to reconnect, but we still think it's connected.
// TODO:
// if(this instanceof User) {
// Server.disconnect((User)this);

View File

@ -115,7 +115,7 @@ pub fn updateViewport(width: u31, height: u31, fov: f32) void {
lastHeight = height;
lastFov = fov;
c.glViewport(0, 0, width, height);
game.projectionMatrix = Mat4f.perspective(std.math.degreesToRadians(f32, fov), @as(f32, @floatFromInt(width))/@as(f32, @floatFromInt(height)), zNear, zFar);
game.projectionMatrix = Mat4f.perspective(std.math.degreesToRadians(fov), @as(f32, @floatFromInt(width))/@as(f32, @floatFromInt(height)), zNear, zFar);
worldFrameBuffer.updateSize(width, height, c.GL_RGB16F);
worldFrameBuffer.unbind();
}
@ -594,7 +594,7 @@ pub const MenuBackGround = struct {
c.glDisable(c.GL_DEPTH_TEST);
c.glBindFramebuffer(c.GL_FRAMEBUFFER, 0);
const fileName = std.fmt.allocPrint(main.stackAllocator.allocator, "assets/backgrounds/{s}_{}.png", .{game.world.?.name, game.world.?.gameTime.load(.Monotonic)}) catch unreachable;
const fileName = std.fmt.allocPrint(main.stackAllocator.allocator, "assets/backgrounds/{s}_{}.png", .{game.world.?.name, game.world.?.gameTime.load(.monotonic)}) catch unreachable;
defer main.stackAllocator.free(fileName);
image.exportToFile(fileName) catch |err| {
std.log.err("Cannot write file {s} due to {s}", .{fileName, @errorName(err)});
@ -616,7 +616,7 @@ pub const Frustum = struct {
const cameraUp = vec.xyz(invRotationMatrix.mulVec(Vec4f{0, 1, 0, 1}));
const cameraRight = vec.xyz(invRotationMatrix.mulVec(Vec4f{1, 0, 0, 1}));
const halfVSide = std.math.tan(std.math.degreesToRadians(f32, fovY)*0.5);
const halfVSide = std.math.tan(std.math.degreesToRadians(fovY)*0.5);
const halfHSide = halfVSide*@as(f32, @floatFromInt(width))/@as(f32, @floatFromInt(height));
var self: Frustum = undefined;

View File

@ -467,7 +467,7 @@ pub const ChunkMesh = struct {
}
pub fn deinit(self: *ChunkMesh) void {
std.debug.assert(self.refCount.load(.Monotonic) == 0);
std.debug.assert(self.refCount.load(.monotonic) == 0);
self.opaqueMesh.deinit();
self.transparentMesh.deinit();
self.chunk.deinit();
@ -479,21 +479,21 @@ pub const ChunkMesh = struct {
}
pub fn increaseRefCount(self: *ChunkMesh) void {
const prevVal = self.refCount.fetchAdd(1, .Monotonic);
const prevVal = self.refCount.fetchAdd(1, .monotonic);
std.debug.assert(prevVal != 0);
}
/// In cases where it's not certain whether the thing was cleared already.
pub fn tryIncreaseRefCount(self: *ChunkMesh) bool {
var prevVal = self.refCount.load(.Monotonic);
var prevVal = self.refCount.load(.monotonic);
while(prevVal != 0) {
prevVal = self.refCount.cmpxchgWeak(prevVal, prevVal + 1, .Monotonic, .Monotonic) orelse return true;
prevVal = self.refCount.cmpxchgWeak(prevVal, prevVal + 1, .monotonic, .monotonic) orelse return true;
}
return false;
}
pub fn decreaseRefCount(self: *ChunkMesh) void {
const prevVal = self.refCount.fetchSub(1, .Monotonic);
const prevVal = self.refCount.fetchSub(1, .monotonic);
std.debug.assert(prevVal != 0);
if(prevVal == 1) {
mesh_storage.addMeshToClearListAndDecreaseRefCount(self);
@ -501,7 +501,7 @@ pub const ChunkMesh = struct {
}
pub fn scheduleLightRefreshAndDecreaseRefCount(self: *ChunkMesh) void {
if(!self.needsLightRefresh.swap(true, .AcqRel)) {
if(!self.needsLightRefresh.swap(true, .acq_rel)) {
LightRefreshTask.scheduleAndDecreaseRefCount(self);
} else {
self.decreaseRefCount();
@ -534,7 +534,7 @@ pub const ChunkMesh = struct {
}
pub fn run(self: *LightRefreshTask) void {
if(self.mesh.needsLightRefresh.swap(false, .AcqRel)) {
if(self.mesh.needsLightRefresh.swap(false, .acq_rel)) {
self.mesh.mutex.lock();
self.mesh.finishData();
self.mesh.mutex.unlock();
@ -633,13 +633,13 @@ pub const ChunkMesh = struct {
const shiftSelf: u5 = @intCast(((dx + 1)*3 + dy + 1)*3 + dz + 1);
const shiftOther: u5 = @intCast(((-dx + 1)*3 + -dy + 1)*3 + -dz + 1);
if(neighborMesh.litNeighbors.fetchOr(@as(u27, 1) << shiftOther, .Monotonic) ^ @as(u27, 1) << shiftOther == ~@as(u27, 0)) { // Trigger mesh creation for neighbor
if(neighborMesh.litNeighbors.fetchOr(@as(u27, 1) << shiftOther, .monotonic) ^ @as(u27, 1) << shiftOther == ~@as(u27, 0)) { // Trigger mesh creation for neighbor
neighborMesh.generateMesh();
}
neighborMesh.mutex.lock();
const neighborFinishedLighting = neighborMesh.finishedLighting;
neighborMesh.mutex.unlock();
if(neighborFinishedLighting and self.litNeighbors.fetchOr(@as(u27, 1) << shiftSelf, .Monotonic) ^ @as(u27, 1) << shiftSelf == ~@as(u27, 0)) {
if(neighborFinishedLighting and self.litNeighbors.fetchOr(@as(u27, 1) << shiftSelf, .monotonic) ^ @as(u27, 1) << shiftSelf == ~@as(u27, 0)) {
self.generateMesh();
}
}
@ -886,7 +886,7 @@ pub const ChunkMesh = struct {
}
}
}
_ = neighborMesh.needsLightRefresh.swap(false, .AcqRel);
_ = neighborMesh.needsLightRefresh.swap(false, .acq_rel);
neighborMesh.finishData();
neighborMesh.increaseRefCount();
mesh_storage.addToUpdateListAndDecreaseRefCount(neighborMesh);
@ -962,7 +962,7 @@ pub const ChunkMesh = struct {
}
self.mutex.lock();
defer self.mutex.unlock();
_ = self.needsLightRefresh.swap(false, .AcqRel);
_ = self.needsLightRefresh.swap(false, .acq_rel);
self.finishData();
mesh_storage.finishMesh(self);
}

View File

@ -71,7 +71,7 @@ pub const ChannelChunk = struct {
pub fn getValue(self: *const ChannelChunk, x: i32, y: i32, z: i32) [3]u8 {
const index = chunk.getIndex(x, y, z);
return .{self.data[index][0].load(.Unordered), self.data[index][1].load(.Unordered), self.data[index][2].load(.Unordered)};
return .{self.data[index][0].load(.unordered), self.data[index][1].load(.unordered), self.data[index][2].load(.unordered)};
}
fn calculateIncomingOcclusion(result: *[3]u8, block: blocks.Block, voxelSize: u31, neighbor: usize) void {
@ -113,9 +113,9 @@ pub const ChannelChunk = struct {
while(lightQueue.dequeue()) |entry| {
const index = chunk.getIndex(entry.x, entry.y, entry.z);
const oldValue: [3]u8 = .{
self.data[index][0].load(.Unordered),
self.data[index][1].load(.Unordered),
self.data[index][2].load(.Unordered),
self.data[index][0].load(.unordered),
self.data[index][1].load(.unordered),
self.data[index][2].load(.unordered),
};
const newValue: [3]u8 = .{
@max(entry.value[0], oldValue[0]),
@ -123,9 +123,9 @@ pub const ChannelChunk = struct {
@max(entry.value[2], oldValue[2]),
};
if(newValue[0] == oldValue[0] and newValue[1] == oldValue[1] and newValue[2] == oldValue[2]) continue;
self.data[index][0].store(newValue[0], .Unordered);
self.data[index][1].store(newValue[1], .Unordered);
self.data[index][2].store(newValue[2], .Unordered);
self.data[index][0].store(newValue[0], .unordered);
self.data[index][1].store(newValue[1], .unordered);
self.data[index][2].store(newValue[2], .unordered);
for(chunk.Neighbors.iterable) |neighbor| {
if(neighbor == entry.sourceDir) continue;
const nx = entry.x + chunk.Neighbors.relX[neighbor];
@ -175,9 +175,9 @@ pub const ChannelChunk = struct {
while(lightQueue.dequeue()) |entry| {
const index = chunk.getIndex(entry.x, entry.y, entry.z);
const oldValue: [3]u8 = .{
self.data[index][0].load(.Unordered),
self.data[index][1].load(.Unordered),
self.data[index][2].load(.Unordered),
self.data[index][0].load(.unordered),
self.data[index][1].load(.unordered),
self.data[index][2].load(.unordered),
};
var activeValue: @Vector(3, bool) = @bitCast(entry.activeValue);
var append: bool = false;
@ -204,9 +204,9 @@ pub const ChannelChunk = struct {
continue;
}
isFirstIteration = false;
if(activeValue[0]) self.data[index][0].store(0, .Unordered);
if(activeValue[1]) self.data[index][1].store(0, .Unordered);
if(activeValue[2]) self.data[index][2].store(0, .Unordered);
if(activeValue[0]) self.data[index][0].store(0, .unordered);
if(activeValue[1]) self.data[index][1].store(0, .unordered);
if(activeValue[2]) self.data[index][2].store(0, .unordered);
for(chunk.Neighbors.iterable) |neighbor| {
if(neighbor == entry.sourceDir) continue;
const nx = entry.x + chunk.Neighbors.relX[neighbor];
@ -309,7 +309,7 @@ pub const ChannelChunk = struct {
const neighborLightChunk = neighborMesh.lightingData[@intFromBool(self.isSun)];
const index = chunk.getIndex(x, y, z);
const neighborIndex = chunk.getIndex(otherX, otherY, otherZ);
var value: [3]u8 = .{neighborLightChunk.data[neighborIndex][0].load(.Unordered), neighborLightChunk.data[neighborIndex][1].load(.Unordered), neighborLightChunk.data[neighborIndex][2].load(.Unordered)};
var value: [3]u8 = .{neighborLightChunk.data[neighborIndex][0].load(.unordered), neighborLightChunk.data[neighborIndex][1].load(.unordered), neighborLightChunk.data[neighborIndex][2].load(.unordered)};
if(!self.isSun or neighbor != chunk.Neighbors.dirUp or value[0] != 255 or value[1] != 255 or value[2] != 255) {
value[0] -|= 8*|@as(u8, @intCast(self.ch.pos.voxelSize));
@ -332,7 +332,7 @@ pub const ChannelChunk = struct {
defer lightQueue.deinit();
for(lights) |pos| {
const index = chunk.getIndex(pos[0], pos[1], pos[2]);
lightQueue.enqueue(.{.x = @intCast(pos[0]), .y = @intCast(pos[1]), .z = @intCast(pos[2]), .value = .{self.data[index][0].load(.Unordered), self.data[index][1].load(.Unordered), self.data[index][2].load(.Unordered)}, .sourceDir = 6, .activeValue = 0b111});
lightQueue.enqueue(.{.x = @intCast(pos[0]), .y = @intCast(pos[1]), .z = @intCast(pos[2]), .value = .{self.data[index][0].load(.unordered), self.data[index][1].load(.unordered), self.data[index][2].load(.unordered)}, .sourceDir = 6, .activeValue = 0b111});
}
var constructiveEntries: main.ListUnmanaged(ChunkEntries) = .{};
defer constructiveEntries.deinit(main.stackAllocator);
@ -348,11 +348,11 @@ pub const ChannelChunk = struct {
const channelChunk = if(mesh) |_mesh| _mesh.lightingData[@intFromBool(self.isSun)] else self;
for(entryList.items) |entry| {
const index = chunk.getIndex(entry.x, entry.y, entry.z);
const value = .{channelChunk.data[index][0].load(.Unordered), channelChunk.data[index][1].load(.Unordered), channelChunk.data[index][2].load(.Unordered)};
const value = .{channelChunk.data[index][0].load(.unordered), channelChunk.data[index][1].load(.unordered), channelChunk.data[index][2].load(.unordered)};
if(value[0] == 0 and value[1] == 0 and value[2] == 0) continue;
channelChunk.data[index][0].store(0, .Unordered);
channelChunk.data[index][1].store(0, .Unordered);
channelChunk.data[index][2].store(0, .Unordered);
channelChunk.data[index][0].store(0, .unordered);
channelChunk.data[index][1].store(0, .unordered);
channelChunk.data[index][2].store(0, .unordered);
lightQueue.enqueue(.{.x = entry.x, .y = entry.y, .z = entry.z, .value = value, .sourceDir = 6, .activeValue = 0b111});
}
channelChunk.propagateDirect(&lightQueue);

View File

@ -129,9 +129,9 @@ fn getMapPieceLocation(x: i32, y: i32, voxelSize: u31) *Atomic(?*LightMap.LightM
}
pub fn getLightMapPieceAndIncreaseRefCount(x: i32, y: i32, voxelSize: u31) ?*LightMap.LightMapFragment {
const result: *LightMap.LightMapFragment = getMapPieceLocation(x, y, voxelSize).load(.Acquire) orelse return null;
const result: *LightMap.LightMapFragment = getMapPieceLocation(x, y, voxelSize).load(.acquire) orelse return null;
var refCount: u16 = 1;
while(result.refCount.cmpxchgWeak(refCount, refCount+1, .Monotonic, .Monotonic)) |otherVal| {
while(result.refCount.cmpxchgWeak(refCount, refCount+1, .monotonic, .monotonic)) |otherVal| {
if(otherVal == 0) return null;
refCount = otherVal;
}
@ -140,7 +140,7 @@ pub fn getLightMapPieceAndIncreaseRefCount(x: i32, y: i32, voxelSize: u31) ?*Lig
pub fn getBlockFromRenderThread(x: i32, y: i32, z: i32) ?blocks.Block {
const node = getNodeFromRenderThread(.{.wx = x, .wy = y, .wz = z, .voxelSize=1});
const mesh = node.mesh.load(.Acquire) orelse return null;
const mesh = node.mesh.load(.acquire) orelse return null;
const block = mesh.chunk.getBlock(x & chunk.chunkMask, y & chunk.chunkMask, z & chunk.chunkMask);
return block;
}
@ -149,7 +149,7 @@ pub fn getBlockFromAnyLodFromRenderThread(x: i32, y: i32, z: i32) blocks.Block {
var lod: u5 = 0;
while(lod < settings.highestLOD) : (lod += 1) {
const node = getNodeFromRenderThread(.{.wx = x, .wy = y, .wz = z, .voxelSize=@as(u31, 1) << lod});
const mesh = node.mesh.load(.Acquire) orelse continue;
const mesh = node.mesh.load(.acquire) orelse continue;
const block = mesh.chunk.getBlock(x & chunk.chunkMask<<lod, y & chunk.chunkMask<<lod, z & chunk.chunkMask<<lod);
return block;
}
@ -160,7 +160,7 @@ pub fn getMeshFromAnyLodFromRenderThread(wx: i32, wy: i32, wz: i32, voxelSize: u
var lod: u5 = @ctz(voxelSize);
while(lod < settings.highestLOD) : (lod += 1) {
const node = getNodeFromRenderThread(.{.wx = wx & ~chunk.chunkMask<<lod, .wy = wy & ~chunk.chunkMask<<lod, .wz = wz & ~chunk.chunkMask<<lod, .voxelSize=@as(u31, 1) << lod});
return node.mesh.load(.Acquire) orelse continue;
return node.mesh.load(.acquire) orelse continue;
}
return null;
}
@ -172,12 +172,12 @@ pub fn getNeighborFromRenderThread(_pos: chunk.ChunkPosition, resolution: u31, n
pos.wz += pos.voxelSize*chunk.chunkSize*chunk.Neighbors.relZ[neighbor];
pos.voxelSize = resolution;
const node = getNodeFromRenderThread(pos);
return node.mesh.load(.Acquire);
return node.mesh.load(.acquire);
}
pub fn getMeshAndIncreaseRefCount(pos: chunk.ChunkPosition) ?*chunk_meshing.ChunkMesh {
const node = getNodeFromRenderThread(pos);
const mesh = node.mesh.load(.Acquire) orelse return null;
const mesh = node.mesh.load(.acquire) orelse return null;
const lod = std.math.log2_int(u31, pos.voxelSize);
const mask = ~((@as(i32, 1) << lod+chunk.chunkShift) - 1);
if(pos.wx & mask != mesh.pos.wx or pos.wy & mask != mesh.pos.wy or pos.wz & mask != mesh.pos.wz) return null;
@ -327,9 +327,9 @@ fn freeOldMeshes(olderPx: i32, olderPy: i32, olderPz: i32, olderRD: i32) void {
const index = (xIndex*storageSize + yIndex)*storageSize + zIndex;
const node = &storageLists[_lod][@intCast(index)];
if(node.mesh.load(.Acquire)) |mesh| {
if(node.mesh.load(.acquire)) |mesh| {
mesh.decreaseRefCount();
node.mesh.store(null, .Release);
node.mesh.store(null, .release);
}
}
}
@ -386,8 +386,8 @@ fn freeOldMeshes(olderPx: i32, olderPy: i32, olderPz: i32, olderRD: i32) void {
const index = xIndex*storageSize + yIndex;
const mapAtomic = &mapStorageLists[_lod][@intCast(index)];
if(mapAtomic.load(.Acquire)) |map| {
mapAtomic.store(null, .Release);
if(mapAtomic.load(.acquire)) |map| {
mapAtomic.store(null, .release);
map.decreaseRefCount();
}
}
@ -460,7 +460,7 @@ fn createNewMeshes(olderPx: i32, olderPy: i32, olderPz: i32, olderRD: i32, meshR
const pos = chunk.ChunkPosition{.wx=x, .wy=y, .wz=z, .voxelSize=@as(u31, 1)<<lod};
const node = &storageLists[_lod][@intCast(index)];
std.debug.assert(node.mesh.load(.Acquire) == null);
std.debug.assert(node.mesh.load(.acquire) == null);
meshRequests.append(pos);
}
}
@ -518,7 +518,7 @@ fn createNewMeshes(olderPx: i32, olderPy: i32, olderPz: i32, olderRD: i32, meshR
const pos = LightMap.MapFragmentPosition{.wx=x, .wy=y, .voxelSize=@as(u31, 1)<<lod, .voxelSizeShift = lod};
const node = &mapStorageLists[_lod][@intCast(index)];
std.debug.assert(node.load(.Acquire) == null);
std.debug.assert(node.load(.acquire) == null);
mapRequests.append(pos);
}
}
@ -583,7 +583,7 @@ pub noinline fn updateAndGetRenderChunks(conn: *network.Connection, playerPos: V
var lod: u3 = 0;
while(lod <= settings.highestLOD) : (lod += 1) {
const node = getNodeFromRenderThread(firstPos);
if(node.mesh.load(.Acquire) != null and node.mesh.load(.Acquire).?.finishedMeshing) {
if(node.mesh.load(.acquire) != null and node.mesh.load(.acquire).?.finishedMeshing) {
node.lod = lod;
node.min = @splat(-1);
node.max = @splat(1);
@ -607,7 +607,7 @@ pub noinline fn updateAndGetRenderChunks(conn: *network.Connection, playerPos: V
while(searchList.removeOrNull()) |data| {
nodeList.append(data.node);
data.node.active = false;
const mesh = data.node.mesh.load(.Acquire).?;
const mesh = data.node.mesh.load(.acquire).?;
std.debug.assert(mesh.finishedMeshing);
mesh.visibilityMask = 0xff;
const relPos: Vec3d = @as(Vec3d, @floatFromInt(Vec3i{mesh.pos.wx, mesh.pos.wy, mesh.pos.wz})) - playerPos;
@ -765,7 +765,7 @@ pub noinline fn updateAndGetRenderChunks(conn: *network.Connection, playerPos: V
neighborPos.voxelSize *= 2;
}
const node = getNodeFromRenderThread(neighborPos);
if(node.mesh.load(.Acquire)) |neighborMesh| {
if(node.mesh.load(.acquire)) |neighborMesh| {
if(!neighborMesh.finishedMeshing) continue;
// Ensure that there are no high-to-low lod transitions, which would produce cracks.
if(lod == data.node.lod and lod != settings.highestLOD and !node.rendered) {
@ -831,10 +831,10 @@ pub noinline fn updateAndGetRenderChunks(conn: *network.Connection, playerPos: V
}
for(nodeList.items) |node| {
node.rendered = false;
const mesh = node.mesh.load(.Acquire).?;
const mesh = node.mesh.load(.acquire).?;
if(mesh.pos.voxelSize != @as(u31, 1) << settings.highestLOD) {
const parent = getNodeFromRenderThread(.{.wx=mesh.pos.wx, .wy=mesh.pos.wy, .wz=mesh.pos.wz, .voxelSize=mesh.pos.voxelSize << 1});
if(parent.mesh.load(.Acquire)) |parentMesh| {
if(parent.mesh.load(.acquire)) |parentMesh| {
const sizeShift = chunk.chunkShift + @ctz(mesh.pos.voxelSize);
const octantIndex: u3 = @intCast((mesh.pos.wx>>sizeShift & 1) | (mesh.pos.wy>>sizeShift & 1)<<1 | (mesh.pos.wz>>sizeShift & 1)<<2);
parentMesh.visibilityMask &= ~(@as(u8, 1) << octantIndex);
@ -862,7 +862,7 @@ pub fn updateMeshes(targetTime: i64) void {
for(blockUpdateList.items) |blockUpdate| {
const pos = chunk.ChunkPosition{.wx=blockUpdate.x, .wy=blockUpdate.y, .wz=blockUpdate.z, .voxelSize=1};
const node = getNodeFromRenderThread(pos);
if(node.mesh.load(.Acquire)) |mesh| {
if(node.mesh.load(.acquire)) |mesh| {
mesh.updateBlock(blockUpdate.x, blockUpdate.y, blockUpdate.z, blockUpdate.newBlock);
} // TODO: It seems like we simply ignore the block update if we don't have the mesh yet.
}
@ -887,7 +887,7 @@ pub fn updateMeshes(targetTime: i64) void {
mutex.unlock();
defer mutex.lock();
mesh.decreaseRefCount();
if(getNodeFromRenderThread(mesh.pos).mesh.load(.Acquire) != mesh) continue; // This mesh isn't used for rendering anymore.
if(getNodeFromRenderThread(mesh.pos).mesh.load(.acquire) != mesh) continue; // This mesh isn't used for rendering anymore.
mesh.uploadData();
if(std.time.milliTimestamp() >= targetTime) break; // Update at least one mesh.
}
@ -895,7 +895,7 @@ pub fn updateMeshes(targetTime: i64) void {
if(!isMapInRenderDistance(map.pos)) {
map.decreaseRefCount();
} else {
if(getMapPieceLocation(map.pos.wx, map.pos.wy, map.pos.voxelSize).swap(map, .AcqRel)) |old| {
if(getMapPieceLocation(map.pos.wx, map.pos.wy, map.pos.voxelSize).swap(map, .acq_rel)) |old| {
old.decreaseRefCount();
}
}
@ -932,7 +932,7 @@ pub fn updateMeshes(targetTime: i64) void {
const node = getNodeFromRenderThread(mesh.pos);
mesh.finishedMeshing = true;
mesh.uploadData();
if(node.mesh.swap(mesh, .AcqRel)) |oldMesh| {
if(node.mesh.swap(mesh, .acq_rel)) |oldMesh| {
oldMesh.decreaseRefCount();
}
} else {
@ -943,14 +943,14 @@ pub fn updateMeshes(targetTime: i64) void {
}
pub fn addMeshToClearListAndDecreaseRefCount(mesh: *chunk_meshing.ChunkMesh) void {
std.debug.assert(mesh.refCount.load(.Monotonic) == 0);
std.debug.assert(mesh.refCount.load(.monotonic) == 0);
mutex.lock();
defer mutex.unlock();
clearList.append(mesh);
}
pub fn addToUpdateListAndDecreaseRefCount(mesh: *chunk_meshing.ChunkMesh) void {
std.debug.assert(mesh.refCount.load(.Monotonic) != 0);
std.debug.assert(mesh.refCount.load(.monotonic) != 0);
mutex.lock();
defer mutex.unlock();
if(mesh.finishedMeshing) {
@ -968,7 +968,7 @@ pub fn addMeshToStorage(mesh: *chunk_meshing.ChunkMesh) error{AlreadyStored}!voi
defer mutex.unlock();
if(isInRenderDistance(mesh.pos)) {
const node = getNodeFromRenderThread(mesh.pos);
if(node.mesh.cmpxchgStrong(null, mesh, .AcqRel, .Monotonic) != null) {
if(node.mesh.cmpxchgStrong(null, mesh, .acq_rel, .monotonic) != null) {
return error.AlreadyStored;
} else {
mesh.increaseRefCount();

View File

@ -63,7 +63,7 @@ pub const User = struct {
pub fn update(self: *User) void {
std.debug.assert(!mutex.tryLock()); // The mutex should be locked when calling this function.
var time = @as(i16, @truncate(std.time.milliTimestamp())) -% main.settings.entityLookback;
time -%= self.timeDifference.difference.load(.Monotonic);
time -%= self.timeDifference.difference.load(.monotonic);
self.interpolation.update(time, self.lastTime);
self.lastTime = time;
}
@ -168,11 +168,11 @@ pub fn start(name: []const u8) void {
var sta = utils.StackAllocator.init(main.globalAllocator, 1 << 23);
defer sta.deinit();
main.stackAllocator = sta.allocator();
std.debug.assert(!running.load(.Monotonic)); // There can only be one server.
std.debug.assert(!running.load(.monotonic)); // There can only be one server.
init(name);
defer deinit();
running.store(true, .Monotonic);
while(running.load(.Monotonic)) {
running.store(true, .monotonic);
while(running.load(.monotonic)) {
const newTime = std.time.nanoTimestamp();
if(newTime -% lastTime < updateNanoTime) {
std.time.sleep(@intCast(lastTime +% updateNanoTime -% newTime));
@ -187,7 +187,7 @@ pub fn start(name: []const u8) void {
}
pub fn stop() void {
running.store(false, .Monotonic);
running.store(false, .monotonic);
}
pub fn disconnect(user: *User) void {

View File

@ -458,7 +458,7 @@ pub fn deinit() void {
}
fn mapFragmentDeinit(mapFragment: *CaveBiomeMapFragment) void {
if(@atomicRmw(u16, &mapFragment.refCount.raw, .Sub, 1, .Monotonic) == 1) {
if(@atomicRmw(u16, &mapFragment.refCount.raw, .Sub, 1, .monotonic) == 1) {
main.globalAllocator.destroy(mapFragment);
}
}
@ -469,7 +469,7 @@ fn cacheInit(pos: ChunkPosition) *CaveBiomeMapFragment {
for(profile.caveBiomeGenerators) |generator| {
generator.generate(mapFragment, profile.seed ^ generator.generatorSeed);
}
_= @atomicRmw(u16, &mapFragment.refCount.raw, .Add, 1, .Monotonic);
_= @atomicRmw(u16, &mapFragment.refCount.raw, .Add, 1, .monotonic);
return mapFragment;
}
@ -482,6 +482,6 @@ fn getOrGenerateFragment(_wx: i32, _wy: i32, _wz: i32) *CaveBiomeMapFragment {
.voxelSize = CaveBiomeMapFragment.caveBiomeSize,
};
const result = cache.findOrCreate(compare, cacheInit);
std.debug.assert(@atomicRmw(u16, &result.refCount.raw, .Add, 1, .Monotonic) != 0);
std.debug.assert(@atomicRmw(u16, &result.refCount.raw, .Add, 1, .monotonic) != 0);
return result;
}

View File

@ -289,7 +289,7 @@ var cache: Cache(CaveMapFragment, cacheSize, associativity, mapFragmentDeinit) =
var profile: TerrainGenerationProfile = undefined;
fn mapFragmentDeinit(mapFragment: *CaveMapFragment) void {
if(@atomicRmw(u16, &mapFragment.refCount.raw, .Sub, 1, .Monotonic) == 1) {
if(@atomicRmw(u16, &mapFragment.refCount.raw, .Sub, 1, .monotonic) == 1) {
main.globalAllocator.destroy(mapFragment);
}
}
@ -300,7 +300,7 @@ fn cacheInit(pos: ChunkPosition) *CaveMapFragment {
for(profile.caveGenerators) |generator| {
generator.generate(mapFragment, profile.seed ^ generator.generatorSeed);
}
_ = @atomicRmw(u16, &mapFragment.refCount.raw, .Add, 1, .Monotonic);
_ = @atomicRmw(u16, &mapFragment.refCount.raw, .Add, 1, .monotonic);
return mapFragment;
}
@ -331,6 +331,6 @@ fn getOrGenerateFragment(wx: i32, wy: i32, wz: i32, voxelSize: u31) *CaveMapFrag
.voxelSize = voxelSize,
};
const result = cache.findOrCreate(compare, cacheInit);
std.debug.assert(@atomicRmw(u16, &result.refCount.raw, .Add, 1, .Monotonic) != 0);
std.debug.assert(@atomicRmw(u16, &result.refCount.raw, .Add, 1, .monotonic) != 0);
return result;
}

View File

@ -106,7 +106,7 @@ pub fn deinitGenerators() void {
}
fn mapFragmentDeinit(mapFragment: *ClimateMapFragment) void {
if(@atomicRmw(u16, &mapFragment.refCount.raw, .Sub, 1, .Monotonic) == 1) {
if(@atomicRmw(u16, &mapFragment.refCount.raw, .Sub, 1, .monotonic) == 1) {
main.globalAllocator.destroy(mapFragment);
}
}
@ -115,7 +115,7 @@ fn cacheInit(pos: ClimateMapFragmentPosition) *ClimateMapFragment {
const mapFragment = main.globalAllocator.create(ClimateMapFragment);
mapFragment.init(pos.wx, pos.wy);
profile.climateGenerator.generateMapFragment(mapFragment, profile.seed);
_ = @atomicRmw(u16, &mapFragment.refCount.raw, .Add, 1, .Monotonic);
_ = @atomicRmw(u16, &mapFragment.refCount.raw, .Add, 1, .monotonic);
return mapFragment;
}
@ -131,7 +131,7 @@ pub fn deinit() void {
fn getOrGenerateFragment(wx: i32, wy: i32) *ClimateMapFragment {
const compare = ClimateMapFragmentPosition{.wx = wx, .wy = wy};
const result = cache.findOrCreate(compare, cacheInit);
std.debug.assert(@atomicRmw(u16, &result.refCount.raw, .Add, 1, .Monotonic) != 0);
std.debug.assert(@atomicRmw(u16, &result.refCount.raw, .Add, 1, .monotonic) != 0);
return result;
}

View File

@ -30,7 +30,7 @@ pub const LightMapFragment = struct {
}
pub fn decreaseRefCount(self: *LightMapFragment) void {
if(@atomicRmw(u16, &self.refCount.raw, .Sub, 1, .Monotonic) == 1) {
if(@atomicRmw(u16, &self.refCount.raw, .Sub, 1, .monotonic) == 1) {
main.globalAllocator.destroy(self);
}
}
@ -60,7 +60,7 @@ fn cacheInit(pos: MapFragmentPosition) *LightMapFragment {
mapFragment.startHeight[x << LightMapFragment.mapShift | y] = @max(0, baseHeight +| 16); // Simple heuristic. TODO: Update this value once chunks get generated in the region.
}
}
_ = @atomicRmw(u16, &mapFragment.refCount.raw, .Add, 1, .Monotonic);
_ = @atomicRmw(u16, &mapFragment.refCount.raw, .Add, 1, .monotonic);
return mapFragment;
}
@ -76,6 +76,6 @@ pub fn getOrGenerateFragment(wx: i32, wy: i32, voxelSize: u31) *LightMapFragment
voxelSize
);
const result = cache.findOrCreate(compare, cacheInit);
std.debug.assert(@atomicRmw(u16, &result.refCount.raw, .Add, 1, .Monotonic) != 0);
std.debug.assert(@atomicRmw(u16, &result.refCount.raw, .Add, 1, .monotonic) != 0);
return result;
}

View File

@ -138,7 +138,7 @@ pub fn deinitGenerators() void {
}
fn mapFragmentDeinit(mapFragment: *MapFragment) void {
if(@atomicRmw(u16, &mapFragment.refCount.raw, .Sub, 1, .Monotonic) == 1) {
if(@atomicRmw(u16, &mapFragment.refCount.raw, .Sub, 1, .monotonic) == 1) {
main.globalAllocator.destroy(mapFragment);
}
}
@ -147,7 +147,7 @@ fn cacheInit(pos: MapFragmentPosition) *MapFragment {
const mapFragment = main.globalAllocator.create(MapFragment);
mapFragment.init(pos.wx, pos.wy, pos.voxelSize);
profile.mapFragmentGenerator.generateMapFragment(mapFragment, profile.seed);
_ = @atomicRmw(u16, &mapFragment.refCount.raw, .Add, 1, .Monotonic);
_ = @atomicRmw(u16, &mapFragment.refCount.raw, .Add, 1, .monotonic);
return mapFragment;
}
@ -167,6 +167,6 @@ pub fn getOrGenerateFragment(wx: i32, wy: i32, voxelSize: u31) *MapFragment {
voxelSize
);
const result = cache.findOrCreate(compare, cacheInit);
std.debug.assert(@atomicRmw(u16, &result.refCount.raw, .Add, 1, .Monotonic) != 0);
std.debug.assert(@atomicRmw(u16, &result.refCount.raw, .Add, 1, .monotonic) != 0);
return result;
}

View File

@ -1051,7 +1051,7 @@ pub const ThreadPool = struct {
}
// Wait for active tasks:
for(self.currentTasks) |*task| {
while(task.load(.Monotonic) == vtable) {
while(task.load(.monotonic) == vtable) {
std.time.sleep(1e6);
}
}
@ -1067,9 +1067,9 @@ pub const ThreadPool = struct {
while(true) {
{
const task = self.loadList.extractMax() catch break;
self.currentTasks[id].store(task.vtable, .Monotonic);
self.currentTasks[id].store(task.vtable, .monotonic);
task.vtable.run(task.self);
self.currentTasks[id].store(null, .Monotonic);
self.currentTasks[id].store(null, .monotonic);
}
if(id == 0 and std.time.milliTimestamp() -% lastUpdate > refreshTime) {
@ -1204,13 +1204,13 @@ pub fn Cache(comptime T: type, comptime numberOfBuckets: u32, comptime bucketSiz
/// Tries to find the entry that fits to the supplied hashable.
pub fn find(self: *@This(), compareAndHash: anytype) ?*T {
const index: u32 = compareAndHash.hashCode() & hashMask;
_ = @atomicRmw(usize, &self.cacheRequests.raw, .Add, 1, .Monotonic);
_ = @atomicRmw(usize, &self.cacheRequests.raw, .Add, 1, .monotonic);
self.buckets[index].mutex.lock();
defer self.buckets[index].mutex.unlock();
if(self.buckets[index].find(compareAndHash)) |item| {
return item;
}
_ = @atomicRmw(usize, &self.cacheMisses.raw, .Add, 1, .Monotonic);
_ = @atomicRmw(usize, &self.cacheMisses.raw, .Add, 1, .monotonic);
return null;
}
@ -1400,13 +1400,13 @@ pub const TimeDifference = struct {
const currentTime: i16 = @truncate(std.time.milliTimestamp());
const timeDifference = currentTime -% time;
if(self.firstValue) {
self.difference.store(timeDifference, .Monotonic);
self.difference.store(timeDifference, .monotonic);
self.firstValue = false;
}
if(timeDifference -% self.difference.load(.Monotonic) > 0) {
_ = @atomicRmw(i16, &self.difference.raw, .Add, 1, .Monotonic);
} else if(timeDifference -% self.difference.load(.Monotonic) < 0) {
_ = @atomicRmw(i16, &self.difference.raw, .Add, -1, .Monotonic);
if(timeDifference -% self.difference.load(.monotonic) > 0) {
_ = @atomicRmw(i16, &self.difference.raw, .Add, 1, .monotonic);
} else if(timeDifference -% self.difference.load(.monotonic) < 0) {
_ = @atomicRmw(i16, &self.difference.raw, .Add, -1, .monotonic);
}
}
};

View File

@ -63,7 +63,7 @@ const LinuxImpl = struct {
fn init() void {
fd = c.inotify_init();
if(fd == -1) {
std.log.err("Error while initializing inotifiy: {}", .{std.os.errno(fd)});
std.log.err("Error while initializing inotifiy: {}", .{std.posix.errno(fd)});
}
watchDescriptors = std.StringHashMap(*DirectoryInfo).init(main.globalAllocator.allocator);
callbacks = std.AutoHashMap(c_int, *DirectoryInfo).init(main.globalAllocator.allocator);
@ -72,7 +72,7 @@ const LinuxImpl = struct {
fn deinit() void {
const result = c.close(fd);
if(result == -1) {
std.log.err("Error while closing file descriptor: {}", .{std.os.errno(result)});
std.log.err("Error while closing file descriptor: {}", .{std.posix.errno(result)});
}
var iterator = watchDescriptors.iterator();
while(iterator.next()) |entry| {
@ -120,14 +120,14 @@ const LinuxImpl = struct {
var available: c_uint = 0;
const result = c.ioctl(fd, c.FIONREAD, &available);
if(result == -1) {
std.log.err("Error while checking the number of available bytes for the inotify file descriptor: {}", .{std.os.errno(result)});
std.log.err("Error while checking the number of available bytes for the inotify file descriptor: {}", .{std.posix.errno(result)});
}
if(available == 0) return;
const events: []u8 = main.stackAllocator.alloc(u8, available);
defer main.stackAllocator.free(events);
const readBytes = c.read(fd, events.ptr, available);
if(readBytes == -1) {
std.log.err("Error while reading inotify event: {}", .{std.os.errno(readBytes)});
std.log.err("Error while reading inotify event: {}", .{std.posix.errno(readBytes)});
return;
}
var triggeredCallbacks = std.AutoHashMap(*DirectoryInfo, void).init(main.stackAllocator.allocator); // Avoid duplicate calls
@ -157,7 +157,7 @@ const LinuxImpl = struct {
std.debug.assert(!mutex.tryLock());
const watchDescriptor = c.inotify_add_watch(fd, path.ptr, c.IN_CLOSE_WRITE | c.IN_DELETE | c.IN_CREATE | c.IN_MOVE | c.IN_ONLYDIR);
if(watchDescriptor == -1) {
std.log.err("Error while adding watch descriptor for path {s}: {}", .{path, std.os.errno(watchDescriptor)});
std.log.err("Error while adding watch descriptor for path {s}: {}", .{path, std.posix.errno(watchDescriptor)});
}
callbacks.put(watchDescriptor, info) catch unreachable;
info.watchDescriptors.append(main.globalAllocator, watchDescriptor);
@ -168,8 +168,8 @@ const LinuxImpl = struct {
_ = callbacks.remove(watchDescriptor);
const result = c.inotify_rm_watch(fd, watchDescriptor);
if(result == -1) {
const err = std.os.errno(result);
if(err != .INVAL) std.log.err("Error while removing watch descriptors for path {s}: {}", .{path, std.os.errno(result)});
const err = std.posix.errno(result);
if(err != .INVAL) std.log.err("Error while removing watch descriptors for path {s}: {}", .{path, err});
}
}