mirror of
https://github.com/PixelGuys/Cubyz.git
synced 2025-08-03 03:06:55 -04:00
Refactoring: Use const instead of var where possible.
When I started to use zig, I mostly used `var`. But over time I adapted to using `const` where possible which is more readable and the compiler is currently optimizing it better.
This commit is contained in:
parent
c2a955f86c
commit
e398824cab
@ -29,7 +29,7 @@ pub fn readAllJsonFilesInAddons(externalAllocator: Allocator, addons: std.ArrayL
|
||||
while(try walker.next()) |entry| {
|
||||
if(entry.kind == .file and std.ascii.endsWithIgnoreCase(entry.basename, ".json")) {
|
||||
const folderName = addonName;
|
||||
var id: []u8 = try externalAllocator.alloc(u8, folderName.len + 1 + entry.path.len - 5);
|
||||
const id: []u8 = try externalAllocator.alloc(u8, folderName.len + 1 + entry.path.len - 5);
|
||||
@memcpy(id[0..folderName.len], folderName);
|
||||
id[folderName.len] = ':';
|
||||
for(0..entry.path.len-5) |i| {
|
||||
@ -40,7 +40,7 @@ pub fn readAllJsonFilesInAddons(externalAllocator: Allocator, addons: std.ArrayL
|
||||
}
|
||||
}
|
||||
|
||||
var file = try dir.dir.openFile(entry.path, .{});
|
||||
const file = try dir.dir.openFile(entry.path, .{});
|
||||
defer file.close();
|
||||
const string = try file.readToEndAlloc(main.threadAllocator, std.math.maxInt(usize));
|
||||
defer main.threadAllocator.free(string);
|
||||
@ -63,7 +63,7 @@ pub fn readAllFilesInAddons(externalAllocator: Allocator, addons: std.ArrayList(
|
||||
|
||||
while(try walker.next()) |entry| {
|
||||
if(entry.kind == .file) {
|
||||
var file = try dir.dir.openFile(entry.path, .{});
|
||||
const file = try dir.dir.openFile(entry.path, .{});
|
||||
defer file.close();
|
||||
const string = try file.readToEndAlloc(externalAllocator, std.math.maxInt(usize));
|
||||
try output.append(string);
|
||||
@ -144,7 +144,7 @@ fn registerRecipesFromFile(file: []const u8) !void {
|
||||
pub const BlockPalette = struct {
|
||||
palette: std.ArrayList([]const u8),
|
||||
pub fn init(allocator: Allocator, json: JsonElement) !*BlockPalette {
|
||||
var self = try allocator.create(BlockPalette);
|
||||
const self = try allocator.create(BlockPalette);
|
||||
self.* = BlockPalette {
|
||||
.palette = std.ArrayList([]const u8).init(allocator),
|
||||
};
|
||||
@ -152,7 +152,7 @@ pub const BlockPalette = struct {
|
||||
if(json != .JsonObject or json.JsonObject.count() == 0) {
|
||||
try self.palette.append(try allocator.dupe(u8, "cubyz:air"));
|
||||
} else {
|
||||
var palette = try main.threadAllocator.alloc(?[]const u8, json.JsonObject.count());
|
||||
const palette = try main.threadAllocator.alloc(?[]const u8, json.JsonObject.count());
|
||||
defer main.threadAllocator.free(palette);
|
||||
for(palette) |*val| {
|
||||
val.* = null;
|
||||
@ -174,7 +174,7 @@ pub const BlockPalette = struct {
|
||||
for(self.palette.items) |item| {
|
||||
self.palette.allocator.free(item);
|
||||
}
|
||||
var allocator = self.palette.allocator;
|
||||
const allocator = self.palette.allocator;
|
||||
self.palette.deinit();
|
||||
allocator.destroy(self);
|
||||
}
|
||||
@ -213,7 +213,7 @@ pub fn loadWorldAssets(assetFolder: []const u8, palette: *BlockPalette) !void {
|
||||
// blocks:
|
||||
var block: u32 = 0;
|
||||
for(palette.palette.items) |id| {
|
||||
var nullValue = blocks.get(id);
|
||||
const nullValue = blocks.get(id);
|
||||
var json: JsonElement = undefined;
|
||||
if(nullValue) |value| {
|
||||
json = value;
|
||||
|
@ -97,7 +97,7 @@ const MusicLoadTask = struct {
|
||||
};
|
||||
|
||||
pub fn schedule(musicId: []const u8) !void {
|
||||
var task = try main.globalAllocator.create(MusicLoadTask);
|
||||
const task = try main.globalAllocator.create(MusicLoadTask);
|
||||
task.* = MusicLoadTask {
|
||||
.musicId = musicId,
|
||||
};
|
||||
|
@ -117,14 +117,14 @@ pub fn register(_: []const u8, id: []const u8, json: JsonElement) !u16 {
|
||||
_gui[size] = try allocator.dupe(u8, json.get([]const u8, "GUI", ""));
|
||||
_transparent[size] = json.get(bool, "transparent", false);
|
||||
_viewThrough[size] = json.get(bool, "viewThrough", false) or _transparent[size];
|
||||
var hasFog: bool = json.get(f32, "fogDensity", 0.0) != 0.0;
|
||||
const hasFog: bool = json.get(f32, "fogDensity", 0.0) != 0.0;
|
||||
_hasBackFace[size] = hasFog and _transparent[size];
|
||||
|
||||
const oreProperties = json.getChild("ore");
|
||||
if (oreProperties != .JsonNull) {
|
||||
// Extract the ids:
|
||||
const sourceBlocks = oreProperties.getChild("sources").toSlice();
|
||||
var oreIds = try main.globalAllocator.alloc([]const u8, sourceBlocks.len);
|
||||
const oreIds = try main.globalAllocator.alloc([]const u8, sourceBlocks.len);
|
||||
for(sourceBlocks, oreIds) |source, *oreId| {
|
||||
oreId.* = try main.globalAllocator.dupe(u8, source.as([]const u8, ""));
|
||||
}
|
||||
@ -167,7 +167,7 @@ fn registerBlockDrop(typ: u16, json: JsonElement) !void {
|
||||
name = _id[typ];
|
||||
}
|
||||
|
||||
var item = items.getByID(name) orelse continue;
|
||||
const item = items.getByID(name) orelse continue;
|
||||
result.len += 1;
|
||||
result[result.len - 1] = BlockDrop{.item = items.Item{.baseItem = item}, .amount = amount};
|
||||
}
|
||||
@ -436,7 +436,7 @@ pub const meshes = struct {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
var file = std.fs.cwd().openFile(path, .{}) catch |err| blk: {
|
||||
const file = std.fs.cwd().openFile(path, .{}) catch |err| blk: {
|
||||
if(err == error.FileNotFound) {
|
||||
path = try std.fmt.bufPrint(&buffer, "assets/{s}/blocks/textures/{s}.png", .{mod, id}); // Default to global assets.
|
||||
break :blk std.fs.cwd().openFile(path, .{}) catch |err2| {
|
||||
@ -462,7 +462,7 @@ pub const meshes = struct {
|
||||
try textureIDs.append(try arenaForWorld.allocator().dupe(u8, path));
|
||||
try animation.append(.{.frames = 1, .time = 1});
|
||||
} else if(textureInfo == .JsonObject) {
|
||||
var animationTime = textureInfo.get(i32, "time", 500);
|
||||
const animationTime = textureInfo.get(i32, "time", 500);
|
||||
const textures = textureInfo.getChild("textures");
|
||||
if(textures != .JsonArray) return result;
|
||||
// Add the new textures into the list. Since this is an animation all textures that weren't found need to be replaced with undefined.
|
||||
@ -478,7 +478,7 @@ pub const meshes = struct {
|
||||
const id = splitter.rest();
|
||||
var buffer: [1024]u8 = undefined;
|
||||
var path = try std.fmt.bufPrint(&buffer, "{s}/{s}/blocks/textures/{s}.png", .{assetFolder, mod, id});
|
||||
var file = std.fs.cwd().openFile(path, .{}) catch |err| blk: {
|
||||
const file = std.fs.cwd().openFile(path, .{}) catch |err| blk: {
|
||||
if(err == error.FileNotFound) {
|
||||
path = try std.fmt.bufPrint(&buffer, "assets/{s}/blocks/textures/{s}.png", .{mod, id}); // Default to global assets.
|
||||
break :blk std.fs.cwd().openFile(path, .{}) catch |err2| {
|
||||
@ -506,7 +506,7 @@ pub const meshes = struct {
|
||||
}
|
||||
|
||||
pub fn getTextureIndices(json: JsonElement, assetFolder: []const u8, textureIndicesRef: []u32) !void {
|
||||
var defaultIndex = try readTexture(json.getChild("texture"), assetFolder) orelse 0;
|
||||
const defaultIndex = try readTexture(json.getChild("texture"), assetFolder) orelse 0;
|
||||
for(textureIndicesRef, sideNames) |*ref, name| {
|
||||
ref.* = defaultIndex;
|
||||
const textureInfo = json.getChild(name);
|
||||
|
@ -116,7 +116,7 @@ pub const ChunkPosition = struct {
|
||||
}
|
||||
|
||||
pub fn getMinDistanceSquared(self: ChunkPosition, playerPosition: Vec3d) f64 {
|
||||
var halfWidth: f64 = @floatFromInt(self.voxelSize*@divExact(chunkSize, 2));
|
||||
const halfWidth: f64 = @floatFromInt(self.voxelSize*@divExact(chunkSize, 2));
|
||||
var dx = @abs(@as(f64, @floatFromInt(self.wx)) + halfWidth - playerPosition[0]);
|
||||
var dy = @abs(@as(f64, @floatFromInt(self.wy)) + halfWidth - playerPosition[1]);
|
||||
var dz = @abs(@as(f64, @floatFromInt(self.wz)) + halfWidth - playerPosition[2]);
|
||||
@ -127,7 +127,7 @@ pub const ChunkPosition = struct {
|
||||
}
|
||||
|
||||
pub fn getMaxDistanceSquared(self: ChunkPosition, playerPosition: Vec3d) f64 {
|
||||
var halfWidth: f64 = @floatFromInt(self.voxelSize*@divExact(chunkSize, 2));
|
||||
const halfWidth: f64 = @floatFromInt(self.voxelSize*@divExact(chunkSize, 2));
|
||||
var dx = @abs(@as(f64, @floatFromInt(self.wx)) + halfWidth - playerPosition[0]);
|
||||
var dy = @abs(@as(f64, @floatFromInt(self.wy)) + halfWidth - playerPosition[1]);
|
||||
var dz = @abs(@as(f64, @floatFromInt(self.wz)) + halfWidth - playerPosition[2]);
|
||||
@ -138,7 +138,7 @@ pub const ChunkPosition = struct {
|
||||
}
|
||||
|
||||
pub fn getCenterDistanceSquared(self: ChunkPosition, playerPosition: Vec3d) f64 {
|
||||
var halfWidth: f64 = @floatFromInt(self.voxelSize*@divExact(chunkSize, 2));
|
||||
const halfWidth: f64 = @floatFromInt(self.voxelSize*@divExact(chunkSize, 2));
|
||||
var dx = @as(f64, @floatFromInt(self.wx)) + halfWidth - playerPosition[0];
|
||||
var dy = @as(f64, @floatFromInt(self.wy)) + halfWidth - playerPosition[1];
|
||||
var dz = @as(f64, @floatFromInt(self.wz)) + halfWidth - playerPosition[2];
|
||||
@ -230,7 +230,7 @@ pub const Chunk = struct {
|
||||
const x = _x >> self.voxelSizeShift;
|
||||
const y = _y >> self.voxelSizeShift;
|
||||
const z = _z >> self.voxelSizeShift;
|
||||
var index = getIndex(x, y, z);
|
||||
const index = getIndex(x, y, z);
|
||||
if (self.blocks[index].typ == 0 or self.blocks[index].degradable()) {
|
||||
self.blocks[index] = newBlock;
|
||||
}
|
||||
@ -242,7 +242,7 @@ pub const Chunk = struct {
|
||||
const x = _x >> self.voxelSizeShift;
|
||||
const y = _y >> self.voxelSizeShift;
|
||||
const z = _z >> self.voxelSizeShift;
|
||||
var index = getIndex(x, y, z);
|
||||
const index = getIndex(x, y, z);
|
||||
self.blocks[index] = newBlock;
|
||||
}
|
||||
|
||||
@ -252,7 +252,7 @@ pub const Chunk = struct {
|
||||
const x = _x >> self.voxelSizeShift;
|
||||
const y = _y >> self.voxelSizeShift;
|
||||
const z = _z >> self.voxelSizeShift;
|
||||
var index = getIndex(x, y, z);
|
||||
const index = getIndex(x, y, z);
|
||||
self.blocks[index] = newBlock;
|
||||
}
|
||||
|
||||
@ -262,7 +262,7 @@ pub const Chunk = struct {
|
||||
const x = _x >> self.voxelSizeShift;
|
||||
const y = _y >> self.voxelSizeShift;
|
||||
const z = _z >> self.voxelSizeShift;
|
||||
var index = getIndex(x, y, z);
|
||||
const index = getIndex(x, y, z);
|
||||
return self.blocks[index];
|
||||
}
|
||||
|
||||
@ -272,9 +272,9 @@ pub const Chunk = struct {
|
||||
y &= chunkMask;
|
||||
z &= chunkMask;
|
||||
for(Neighbors.relX, 0..) |_, i| {
|
||||
var xi = x + Neighbors.relX[i];
|
||||
var yi = y + Neighbors.relY[i];
|
||||
var zi = z + Neighbors.relZ[i];
|
||||
const xi = x + Neighbors.relX[i];
|
||||
const yi = y + Neighbors.relY[i];
|
||||
const zi = z + Neighbors.relZ[i];
|
||||
if (xi == (xi & chunkMask) and yi == (yi & chunkMask) and zi == (zi & chunkMask)) { // Simple double-bound test for coordinates.
|
||||
neighborsArray[i] = self.getBlock(xi, yi, zi);
|
||||
} else {
|
||||
@ -519,8 +519,8 @@ pub const meshing = struct {
|
||||
}
|
||||
|
||||
fn replaceNeighbors(self: *PrimitiveMesh, neighbor: usize, additionalNeighborFaces: []FaceData) !void {
|
||||
var rangeStart = self.neighborStart[neighbor ^ 1];
|
||||
var rangeEnd = self.neighborStart[(neighbor ^ 1)+1];
|
||||
const rangeStart = self.neighborStart[neighbor ^ 1];
|
||||
const rangeEnd = self.neighborStart[(neighbor ^ 1)+1];
|
||||
try self.faces.replaceRange(rangeStart, rangeEnd - rangeStart, additionalNeighborFaces);
|
||||
for(self.neighborStart[1+(neighbor ^ 1)..]) |*neighborStart| {
|
||||
neighborStart.* = neighborStart.* - (rangeEnd - rangeStart) + @as(u31, @intCast(additionalNeighborFaces.len));
|
||||
@ -920,7 +920,7 @@ pub const meshing = struct {
|
||||
self.opaqueMesh.startNeighbor(neighbor);
|
||||
self.voxelMesh.startNeighbor(neighbor);
|
||||
self.transparentMesh.startNeighbor(neighbor);
|
||||
var nullNeighborMesh = renderer.RenderStructure.getNeighbor(self.pos, self.pos.voxelSize, neighbor);
|
||||
const nullNeighborMesh = renderer.RenderStructure.getNeighbor(self.pos, self.pos.voxelSize, neighbor);
|
||||
if(nullNeighborMesh) |neighborMesh| {
|
||||
std.debug.assert(neighborMesh != self);
|
||||
neighborMesh.mutex.lock();
|
||||
@ -932,7 +932,7 @@ pub const meshing = struct {
|
||||
defer additionalNeighborFacesVoxel.deinit();
|
||||
var additionalNeighborFacesTransparent = std.ArrayList(FaceData).init(main.threadAllocator);
|
||||
defer additionalNeighborFacesTransparent.deinit();
|
||||
var x3: u8 = if(neighbor & 1 == 0) @intCast(chunkMask) else 0;
|
||||
const x3: u8 = if(neighbor & 1 == 0) @intCast(chunkMask) else 0;
|
||||
var x1: u8 = 0;
|
||||
while(x1 < chunkSize): (x1 += 1) {
|
||||
var x2: u8 = 0;
|
||||
@ -953,11 +953,11 @@ pub const meshing = struct {
|
||||
y = x1;
|
||||
z = x3;
|
||||
}
|
||||
var otherX: u8 = @intCast(x+%Neighbors.relX[neighbor] & chunkMask);
|
||||
var otherY: u8 = @intCast(y+%Neighbors.relY[neighbor] & chunkMask);
|
||||
var otherZ: u8 = @intCast(z+%Neighbors.relZ[neighbor] & chunkMask);
|
||||
var block = (&chunk.blocks)[getIndex(x, y, z)]; // ← a temporary fix to a compiler performance bug. TODO: check if this was fixed.
|
||||
var otherBlock = (&neighborMesh.chunk.load(.Monotonic).?.blocks)[getIndex(otherX, otherY, otherZ)]; // ← a temporary fix to a compiler performance bug. TODO: check if this was fixed.
|
||||
const otherX: u8 = @intCast(x+%Neighbors.relX[neighbor] & chunkMask);
|
||||
const otherY: u8 = @intCast(y+%Neighbors.relY[neighbor] & chunkMask);
|
||||
const otherZ: u8 = @intCast(z+%Neighbors.relZ[neighbor] & chunkMask);
|
||||
const block = (&chunk.blocks)[getIndex(x, y, z)]; // ← a temporary fix to a compiler performance bug. TODO: check if this was fixed.
|
||||
const otherBlock = (&neighborMesh.chunk.load(.Monotonic).?.blocks)[getIndex(otherX, otherY, otherZ)]; // ← a temporary fix to a compiler performance bug. TODO: check if this was fixed.
|
||||
if(canBeSeenThroughOtherBlock(block, otherBlock, neighbor)) {
|
||||
if(block.transparent()) {
|
||||
if(block.hasBackFace()) {
|
||||
@ -996,7 +996,7 @@ pub const meshing = struct {
|
||||
}
|
||||
// lod border:
|
||||
if(self.pos.voxelSize == 1 << settings.highestLOD) continue;
|
||||
var neighborMesh = renderer.RenderStructure.getNeighbor(self.pos, 2*self.pos.voxelSize, neighbor) orelse return error.LODMissing;
|
||||
const neighborMesh = renderer.RenderStructure.getNeighbor(self.pos, 2*self.pos.voxelSize, neighbor) orelse return error.LODMissing;
|
||||
neighborMesh.mutex.lock();
|
||||
defer neighborMesh.mutex.unlock();
|
||||
if(neighborMesh.generated) {
|
||||
@ -1024,11 +1024,11 @@ pub const meshing = struct {
|
||||
y = x1;
|
||||
z = x3;
|
||||
}
|
||||
var otherX: u8 = @intCast((x+%Neighbors.relX[neighbor]+%offsetX >> 1) & chunkMask);
|
||||
var otherY: u8 = @intCast((y+%Neighbors.relY[neighbor]+%offsetY >> 1) & chunkMask);
|
||||
var otherZ: u8 = @intCast((z+%Neighbors.relZ[neighbor]+%offsetZ >> 1) & chunkMask);
|
||||
var block = (&chunk.blocks)[getIndex(x, y, z)]; // ← a temporary fix to a compiler performance bug. TODO: check if this was fixed.
|
||||
var otherBlock = (&neighborMesh.chunk.load(.Monotonic).?.blocks)[getIndex(otherX, otherY, otherZ)]; // ← a temporary fix to a compiler performance bug. TODO: check if this was fixed.
|
||||
const otherX: u8 = @intCast((x+%Neighbors.relX[neighbor]+%offsetX >> 1) & chunkMask);
|
||||
const otherY: u8 = @intCast((y+%Neighbors.relY[neighbor]+%offsetY >> 1) & chunkMask);
|
||||
const otherZ: u8 = @intCast((z+%Neighbors.relZ[neighbor]+%offsetZ >> 1) & chunkMask);
|
||||
const block = (&chunk.blocks)[getIndex(x, y, z)]; // ← a temporary fix to a compiler performance bug. TODO: check if this was fixed.
|
||||
const otherBlock = (&neighborMesh.chunk.load(.Monotonic).?.blocks)[getIndex(otherX, otherY, otherZ)]; // ← a temporary fix to a compiler performance bug. TODO: check if this was fixed.
|
||||
if(canBeSeenThroughOtherBlock(otherBlock, block, neighbor ^ 1)) {
|
||||
if(otherBlock.transparent()) {
|
||||
try self.transparentMesh.append(constructFaceData(otherBlock, neighbor ^ 1, x, y, z, false));
|
||||
@ -1116,7 +1116,7 @@ pub const meshing = struct {
|
||||
}/@as(Vec3d, @splat(@as(f64, @floatFromInt(self.pos.voxelSize))));
|
||||
relativePos = @min(relativePos, @as(Vec3d, @splat(0)));
|
||||
relativePos = @max(relativePos, @as(Vec3d, @splat(-32)));
|
||||
var updatePos: Vec3i = @intFromFloat(relativePos);
|
||||
const updatePos: Vec3i = @intFromFloat(relativePos);
|
||||
if(@reduce(.Or, updatePos != self.lastTransparentUpdatePos)) {
|
||||
self.lastTransparentUpdatePos = updatePos;
|
||||
needsUpdate = true;
|
||||
|
@ -21,9 +21,8 @@ pub fn writeJson(path: []const u8, json: JsonElement) !void {
|
||||
}
|
||||
|
||||
pub fn openDir(path: []const u8) !Dir {
|
||||
var dir = try std.fs.cwd().makeOpenPath(path, .{});
|
||||
return Dir {
|
||||
.dir = dir,
|
||||
.dir = try std.fs.cwd().makeOpenPath(path, .{}),
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -141,7 +141,7 @@ pub const World = struct {
|
||||
pub fn finishHandshake(self: *World, json: JsonElement) !void {
|
||||
// TODO: Consider using a per-world allocator.
|
||||
self.blockPalette = try assets.BlockPalette.init(main.globalAllocator, json.getChild("blockPalette"));
|
||||
var jsonSpawn = json.getChild("spawn");
|
||||
const jsonSpawn = json.getChild("spawn");
|
||||
self.spawn[0] = jsonSpawn.get(f32, "x", 0);
|
||||
self.spawn[1] = jsonSpawn.get(f32, "y", 0);
|
||||
self.spawn[2] = jsonSpawn.get(f32, "z", 0);
|
||||
@ -162,7 +162,7 @@ pub const World = struct {
|
||||
}
|
||||
|
||||
pub fn update(self: *World) !void {
|
||||
var newTime: i64 = std.time.milliTimestamp();
|
||||
const newTime: i64 = std.time.milliTimestamp();
|
||||
while(self.milliTime +% 100 -% newTime < 0) {
|
||||
self.milliTime +%= 100;
|
||||
var curTime = self.gameTime.load(.Monotonic);
|
||||
@ -303,8 +303,8 @@ pub var fog = Fog{.color=.{0, 1, 0.5}, .density=1.0/15.0/128.0}; // TODO: Make t
|
||||
|
||||
pub fn update(deltaTime: f64) !void {
|
||||
var movement = Vec3d{0, 0, 0};
|
||||
var forward = vec.rotateY(Vec3d{0, 0, -1}, -camera.rotation[1]);
|
||||
var right = Vec3d{forward[2], 0, -forward[0]};
|
||||
const forward = vec.rotateY(Vec3d{0, 0, -1}, -camera.rotation[1]);
|
||||
const right = Vec3d{forward[2], 0, -forward[0]};
|
||||
if(main.Window.grabbed) {
|
||||
if(KeyBoard.key("forward").pressed) {
|
||||
if(KeyBoard.key("sprint").pressed) {
|
||||
|
@ -131,7 +131,7 @@ pub const draw = struct {
|
||||
|
||||
fn initRect() void {
|
||||
rectShader = Shader.initAndGetUniforms("assets/cubyz/shaders/graphics/Rect.vs", "assets/cubyz/shaders/graphics/Rect.fs", &rectUniforms) catch Shader{.id = 0};
|
||||
var rawData = [_]f32 {
|
||||
const rawData = [_]f32 {
|
||||
0, 0,
|
||||
0, 1,
|
||||
1, 0,
|
||||
@ -185,7 +185,7 @@ pub const draw = struct {
|
||||
|
||||
fn initLine() void {
|
||||
lineShader = Shader.initAndGetUniforms("assets/cubyz/shaders/graphics/Line.vs", "assets/cubyz/shaders/graphics/Line.fs", &lineUniforms) catch Shader{.id = 0};
|
||||
var rawData = [_]f32 {
|
||||
const rawData = [_]f32 {
|
||||
0, 0,
|
||||
1, 1,
|
||||
};
|
||||
@ -231,7 +231,7 @@ pub const draw = struct {
|
||||
var drawRectVBO: c_uint = undefined;
|
||||
|
||||
fn initDrawRect() void {
|
||||
var rawData = [_]f32 {
|
||||
const rawData = [_]f32 {
|
||||
0, 0,
|
||||
0, 1,
|
||||
1, 1,
|
||||
@ -284,7 +284,7 @@ pub const draw = struct {
|
||||
|
||||
fn initCircle() void {
|
||||
circleShader = Shader.initAndGetUniforms("assets/cubyz/shaders/graphics/Circle.vs", "assets/cubyz/shaders/graphics/Circle.fs", &circleUniforms) catch Shader{.id = 0};
|
||||
var rawData = [_]f32 {
|
||||
const rawData = [_]f32 {
|
||||
-1, -1,
|
||||
-1, 1,
|
||||
1, -1,
|
||||
@ -583,7 +583,7 @@ pub const TextBuffer = struct {
|
||||
}
|
||||
|
||||
// Let harfbuzz do its thing:
|
||||
var buffer = hbft.hb_buffer_create() orelse return error.OutOfMemory;
|
||||
const buffer = hbft.hb_buffer_create() orelse return error.OutOfMemory;
|
||||
defer hbft.hb_buffer_destroy(buffer);
|
||||
hbft.hb_buffer_add_utf32(buffer, parser.parsedText.items.ptr, @intCast(parser.parsedText.items.len), 0, @intCast(parser.parsedText.items.len));
|
||||
hbft.hb_buffer_set_direction(buffer, hbft.HB_DIRECTION_LTR);
|
||||
@ -601,7 +601,7 @@ pub const TextBuffer = struct {
|
||||
}
|
||||
|
||||
// Guess the text index from the given cluster indices. Only works if the number of glyphs and the number of characters in a cluster is the same.
|
||||
var textIndexGuess = try stackFallbackAllocator.alloc(u32, glyphInfos.len);
|
||||
const textIndexGuess = try stackFallbackAllocator.alloc(u32, glyphInfos.len);
|
||||
defer stackFallbackAllocator.free(textIndexGuess);
|
||||
for(textIndexGuess, 0..) |*index, i| {
|
||||
if(i == 0 or glyphInfos[i-1].cluster != glyphInfos[i].cluster) {
|
||||
@ -698,7 +698,7 @@ pub const TextBuffer = struct {
|
||||
self.lineBreaks.clearRetainingCapacity();
|
||||
const spaceCharacterWidth = 8;
|
||||
try self.lineBreaks.append(.{.index = 0, .width = 0});
|
||||
var scaledMaxWidth = maxLineWidth/fontSize*16.0;
|
||||
const scaledMaxWidth = maxLineWidth/fontSize*16.0;
|
||||
var lineWidth: f32 = 0;
|
||||
var lastSpaceWidth: f32 = 0;
|
||||
var lastSpaceIndex: u32 = 0;
|
||||
@ -811,7 +811,7 @@ pub const TextBuffer = struct {
|
||||
const lineStart = @max(0, line.start);
|
||||
const lineEnd = @min(lineWrap, line.end);
|
||||
if(lineStart < lineEnd) {
|
||||
var start = Vec2f{lineStart + self.getLineOffset(j), y};
|
||||
const start = Vec2f{lineStart + self.getLineOffset(j), y};
|
||||
const dim = Vec2f{lineEnd - lineStart, 1};
|
||||
draw.rect(start, dim);
|
||||
}
|
||||
@ -880,7 +880,7 @@ pub const TextBuffer = struct {
|
||||
const lineStart = @max(0, line.start);
|
||||
const lineEnd = @min(lineWrap, line.end);
|
||||
if(lineStart < lineEnd) {
|
||||
var start = Vec2f{lineStart + self.getLineOffset(j), y};
|
||||
const start = Vec2f{lineStart + self.getLineOffset(j), y};
|
||||
const dim = Vec2f{lineEnd - lineStart, 1};
|
||||
draw.rect(start, dim);
|
||||
}
|
||||
@ -1119,7 +1119,7 @@ pub const Shader = struct {
|
||||
}
|
||||
|
||||
pub fn init(vertex: []const u8, fragment: []const u8) !Shader {
|
||||
var shader = Shader{.id = c.glCreateProgram()};
|
||||
const shader = Shader{.id = c.glCreateProgram()};
|
||||
try shader.addShader(vertex, c.GL_VERTEX_SHADER);
|
||||
try shader.addShader(fragment, c.GL_FRAGMENT_SHADER);
|
||||
try shader.link();
|
||||
@ -1137,7 +1137,7 @@ pub const Shader = struct {
|
||||
}
|
||||
|
||||
pub fn initCompute(compute: []const u8) !Shader {
|
||||
var shader = Shader{.id = c.glCreateProgram()};
|
||||
const shader = Shader{.id = c.glCreateProgram()};
|
||||
try shader.addShader(compute, c.GL_COMPUTE_SHADER);
|
||||
try shader.link();
|
||||
return shader;
|
||||
@ -1473,7 +1473,7 @@ pub const TextureArray = struct {
|
||||
c.glTexStorage3D(c.GL_TEXTURE_2D_ARRAY, maxLOD, c.GL_RGBA8, maxWidth, maxHeight, @intCast(images.len));
|
||||
var arena = std.heap.ArenaAllocator.init(main.threadAllocator);
|
||||
defer arena.deinit();
|
||||
var lodBuffer: [][]Color = try arena.allocator().alloc([]Color, maxLOD);
|
||||
const lodBuffer: [][]Color = try arena.allocator().alloc([]Color, maxLOD);
|
||||
for(lodBuffer, 0..) |*buffer, i| {
|
||||
buffer.* = try arena.allocator().alloc(Color, (maxWidth >> @intCast(i))*(maxHeight >> @intCast(i)));
|
||||
}
|
||||
@ -1822,7 +1822,7 @@ pub fn generateBlockTexture(blockType: u16) !Texture {
|
||||
finalFrameBuffer.init(false, c.GL_NEAREST, c.GL_REPEAT);
|
||||
finalFrameBuffer.updateSize(textureSize, textureSize, c.GL_RGBA8);
|
||||
finalFrameBuffer.bind();
|
||||
var texture = Texture{.textureID = finalFrameBuffer.texture};
|
||||
const texture = Texture{.textureID = finalFrameBuffer.texture};
|
||||
defer c.glDeleteFramebuffers(1, &finalFrameBuffer.frameBuffer);
|
||||
block_texture.shader.bind();
|
||||
c.glUniform1i(block_texture.uniforms.transparent, if(block.transparent()) c.GL_TRUE else c.GL_FALSE);
|
||||
|
@ -43,7 +43,7 @@ pub fn __deinit() void {
|
||||
}
|
||||
|
||||
pub fn init(pos: Vec2f, width: f32, text: []const u8, comptime fmt: []const u8, valueList: anytype, initialValue: u16, callback: *const fn(u16) void) Allocator.Error!*DiscreteSlider {
|
||||
var values = try main.globalAllocator.alloc([]const u8, valueList.len);
|
||||
const values = try main.globalAllocator.alloc([]const u8, valueList.len);
|
||||
var maxLen: usize = 0;
|
||||
for(valueList, 0..) |value, i| {
|
||||
values[i] = try std.fmt.allocPrint(main.globalAllocator, fmt, .{value});
|
||||
|
@ -384,7 +384,7 @@ pub fn inputCharacter(self: *TextInput, character: u21) !void {
|
||||
if(self.cursor) |*cursor| {
|
||||
self.deleteSelection();
|
||||
var buf: [4]u8 = undefined;
|
||||
var utf8 = buf[0..try std.unicode.utf8Encode(character, &buf)];
|
||||
const utf8 = buf[0..try std.unicode.utf8Encode(character, &buf)];
|
||||
try self.currentString.insertSlice(cursor.*, utf8);
|
||||
try self.reloadText();
|
||||
cursor.* += @intCast(utf8.len);
|
||||
@ -448,7 +448,7 @@ fn ensureCursorVisibility(self: *TextInput) void {
|
||||
const diff = self.textSize[1] - (self.maxHeight - 2*border);
|
||||
y -= diff*self.scrollBar.currentState;
|
||||
if(self.cursor) |cursor| {
|
||||
var cursorPos = y + self.textBuffer.indexToCursorPos(cursor)[1];
|
||||
const cursorPos = y + self.textBuffer.indexToCursorPos(cursor)[1];
|
||||
if(cursorPos < 0) {
|
||||
self.scrollBar.currentState += cursorPos/diff;
|
||||
} else if(cursorPos + 16 >= self.maxHeight - 2*border) {
|
||||
@ -480,7 +480,7 @@ pub fn render(self: *TextInput, mousePosition: Vec2f) !void {
|
||||
self.cursor = self.textBuffer.mousePosToIndex(mousePosition - textPos - self.pos, self.currentString.items.len);
|
||||
}
|
||||
if(self.cursor) |cursor| {
|
||||
var cursorPos = textPos + self.textBuffer.indexToCursorPos(cursor);
|
||||
const cursorPos = textPos + self.textBuffer.indexToCursorPos(cursor);
|
||||
if(self.selectionStart) |selectionStart| {
|
||||
draw.setColor(0x440000ff);
|
||||
try self.textBuffer.drawSelection(textPos, @min(selectionStart, cursor), @max(selectionStart, cursor));
|
||||
|
@ -42,7 +42,7 @@ fn apply(_: usize) void {
|
||||
}
|
||||
|
||||
pub fn onOpen() Allocator.Error!void {
|
||||
var list = try VerticalList.init(.{padding, 16 + padding}, 300, 16);
|
||||
const list = try VerticalList.init(.{padding, 16 + padding}, 300, 16);
|
||||
const width = 420;
|
||||
if(settings.playerName.len == 0) {
|
||||
try list.add(try Label.init(.{0, 0}, width, "Please enter your name!", .center));
|
||||
|
@ -45,7 +45,7 @@ fn refresh() Allocator.Error!void {
|
||||
old.mutexComponent.child.verticalList.children.clearRetainingCapacity();
|
||||
old.deinit();
|
||||
}
|
||||
var list = try VerticalList.init(.{padding, 16 + padding}, 300, 0);
|
||||
const list = try VerticalList.init(.{padding, 16 + padding}, 300, 0);
|
||||
for(history.items[if(hideInput) historyStart else 0 ..]) |msg| {
|
||||
msg.pos = .{0, 0};
|
||||
try list.add(msg);
|
||||
|
@ -36,15 +36,15 @@ fn keypressListener(key: c_int, mouseButton: c_int, scancode: c_int) void {
|
||||
}
|
||||
|
||||
pub fn onOpen() Allocator.Error!void {
|
||||
var list = try VerticalList.init(.{padding, 16 + padding}, 300, 8);
|
||||
const list = try VerticalList.init(.{padding, 16 + padding}, 300, 8);
|
||||
for(&main.KeyBoard.keys) |*key| {
|
||||
var label = try Label.init(.{0, 0}, 128, key.name, .left);
|
||||
var button = if(key == selectedKey) (
|
||||
const label = try Label.init(.{0, 0}, 128, key.name, .left);
|
||||
const button = if(key == selectedKey) (
|
||||
try Button.initText(.{16, 0}, 128, "...", .{})
|
||||
) else (
|
||||
try Button.initText(.{16, 0}, 128, key.getName(), .{.callback = &function, .arg = @intFromPtr(key)})
|
||||
);
|
||||
var row = try HorizontalList.init();
|
||||
const row = try HorizontalList.init();
|
||||
try row.add(label);
|
||||
try row.add(button);
|
||||
row.finish(.{0, 0}, .center);
|
||||
@ -65,7 +65,7 @@ pub fn onClose() void {
|
||||
pub fn render() Allocator.Error!void {
|
||||
if(needsUpdate) {
|
||||
needsUpdate = false;
|
||||
var oldScroll = window.rootComponent.?.verticalList.scrollBar.currentState;
|
||||
const oldScroll = window.rootComponent.?.verticalList.scrollBar.currentState;
|
||||
onClose();
|
||||
onOpen() catch {
|
||||
std.log.err("Received out of memory error while rebuilding the controls GUI. This behavior is not handled.", .{});
|
||||
|
@ -53,10 +53,10 @@ pub fn onOpen() Allocator.Error!void {
|
||||
try items.append(Item{.baseItem = item.*});
|
||||
}
|
||||
|
||||
var list = try VerticalList.init(.{padding, padding + 16}, 140, 0);
|
||||
const list = try VerticalList.init(.{padding, padding + 16}, 140, 0);
|
||||
var i: u32 = 0;
|
||||
while(i < items.items.len) {
|
||||
var row = try HorizontalList.init();
|
||||
const row = try HorizontalList.init();
|
||||
for(0..8) |_| {
|
||||
if(i >= items.items.len) break;
|
||||
const item = items.items[i];
|
||||
|
@ -38,7 +38,7 @@ fn vsyncCallback(newValue: bool) void {
|
||||
}
|
||||
|
||||
pub fn onOpen() Allocator.Error!void {
|
||||
var list = try VerticalList.init(.{padding, 16 + padding}, 300, 16);
|
||||
const list = try VerticalList.init(.{padding, 16 + padding}, 300, 16);
|
||||
const renderDistances = [_]u32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
|
||||
try list.add(try DiscreteSlider.init(.{0, 0}, 128, "#ffffffRender Distance: ", "{}", &renderDistances, settings.renderDistance - 1, &renderDistanceCallback));
|
||||
const LODFactors = [_]f32{0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8};
|
||||
|
@ -79,7 +79,7 @@ const vtable = ItemSlot.VTable {
|
||||
};
|
||||
|
||||
pub fn onOpen() Allocator.Error!void {
|
||||
var list = try HorizontalList.init();
|
||||
const list = try HorizontalList.init();
|
||||
for(0..8) |i| {
|
||||
itemSlots[i] = try ItemSlot.init(.{0, 0}, Player.inventory__SEND_CHANGES_TO_SERVER.items[i], &vtable, i);
|
||||
try list.add(itemSlots[i]);
|
||||
|
@ -90,19 +90,19 @@ const vtable = ItemSlot.VTable {
|
||||
};
|
||||
|
||||
pub fn onOpen() Allocator.Error!void {
|
||||
var list = try VerticalList.init(.{padding, padding + 16}, 300, 0);
|
||||
const list = try VerticalList.init(.{padding, padding + 16}, 300, 0);
|
||||
// Some miscellanious slots and buttons:
|
||||
// TODO: armor slots, backpack slot + stack-based backpack inventory, other items maybe?
|
||||
{
|
||||
var row = try HorizontalList.init();
|
||||
const row = try HorizontalList.init();
|
||||
try row.add(try Button.initIcon(.{0, 0}, .{24, 24}, craftingIcon, true, gui.openWindowCallback("inventory_crafting")));
|
||||
try list.add(row);
|
||||
}
|
||||
// Inventory:
|
||||
for(1..4) |y| {
|
||||
var row = try HorizontalList.init();
|
||||
const row = try HorizontalList.init();
|
||||
for(0..8) |x| {
|
||||
var index: usize = y*8 + x;
|
||||
const index: usize = y*8 + x;
|
||||
const slot = try ItemSlot.init(.{0, 0}, Player.inventory__SEND_CHANGES_TO_SERVER.items[index], &vtable, index);
|
||||
itemSlots[index - 8] = slot;
|
||||
try row.add(slot);
|
||||
|
@ -117,7 +117,7 @@ fn findAvailableRecipes(list: *VerticalList) Allocator.Error!bool {
|
||||
continue :outer; // Ingredient not found.
|
||||
}
|
||||
// All ingredients found: Add it to the list.
|
||||
var rowList = try HorizontalList.init();
|
||||
const rowList = try HorizontalList.init();
|
||||
const maxColumns: u32 = 4;
|
||||
const itemsPerColumn = recipe.sourceItems.len/maxColumns;
|
||||
const remainder = recipe.sourceItems.len%maxColumns;
|
||||
@ -125,7 +125,7 @@ fn findAvailableRecipes(list: *VerticalList) Allocator.Error!bool {
|
||||
for(0..maxColumns) |col| {
|
||||
var itemsThisColumn = itemsPerColumn;
|
||||
if(col < remainder) itemsThisColumn += 1;
|
||||
var columnList = try VerticalList.init(.{0, 0}, std.math.inf(f32), 0);
|
||||
const columnList = try VerticalList.init(.{0, 0}, std.math.inf(f32), 0);
|
||||
for(0..itemsThisColumn) |_| {
|
||||
try columnList.add(try ImmutableItemSlot.init(.{0, 0}, recipe.sourceItems[i], recipe.sourceAmounts[i]));
|
||||
i += 1;
|
||||
@ -143,7 +143,7 @@ fn findAvailableRecipes(list: *VerticalList) Allocator.Error!bool {
|
||||
}
|
||||
|
||||
fn refresh() Allocator.Error!void {
|
||||
var list = try VerticalList.init(.{padding, padding + 16}, 300, 8);
|
||||
const list = try VerticalList.init(.{padding, padding + 16}, 300, 8);
|
||||
if(!try findAvailableRecipes(list)) {
|
||||
list.deinit();
|
||||
return;
|
||||
|
@ -18,7 +18,7 @@ pub var window = GuiWindow {
|
||||
const padding: f32 = 8;
|
||||
|
||||
pub fn onOpen() Allocator.Error!void {
|
||||
var list = try VerticalList.init(.{padding, 16 + padding}, 300, 16);
|
||||
const list = try VerticalList.init(.{padding, 16 + padding}, 300, 16);
|
||||
try list.add(try Button.initText(.{0, 0}, 128, "Singleplayer", gui.openWindowCallback("save_selection")));
|
||||
try list.add(try Button.initText(.{0, 0}, 128, "Multiplayer", gui.openWindowCallback("multiplayer")));
|
||||
try list.add(try Button.initText(.{0, 0}, 128, "Settings", gui.openWindowCallback("settings")));
|
||||
|
@ -85,7 +85,7 @@ fn copyIp(_: usize) void {
|
||||
}
|
||||
|
||||
pub fn onOpen() Allocator.Error!void {
|
||||
var list = try VerticalList.init(.{padding, 16 + padding}, 300, 16);
|
||||
const list = try VerticalList.init(.{padding, 16 + padding}, 300, 16);
|
||||
try list.add(try Label.init(.{0, 0}, width, "Please send your IP to the host of the game and enter the host's IP below.", .center));
|
||||
// 255.255.255.255:?65536 (longest possible ip address)
|
||||
ipAddressLabel = try Label.init(.{0, 0}, width, " ", .center);
|
||||
|
@ -110,7 +110,7 @@ fn parseEscapedFolderName(name: []const u8) ![]const u8 {
|
||||
|
||||
pub fn onOpen() Allocator.Error!void {
|
||||
buttonNameArena = std.heap.ArenaAllocator.init(main.globalAllocator);
|
||||
var list = try VerticalList.init(.{padding, 16 + padding}, 300, 8);
|
||||
const list = try VerticalList.init(.{padding, 16 + padding}, 300, 8);
|
||||
// TODO: try list.add(try Button.initText(.{0, 0}, 128, "Create World", gui.openWindowCallback("save_creation")));
|
||||
|
||||
var dir: std.fs.IterableDir = std.fs.cwd().makeOpenPathIterable("saves", .{}) catch |err| {
|
||||
@ -125,7 +125,7 @@ pub fn onOpen() Allocator.Error!void {
|
||||
return;
|
||||
}) |entry| {
|
||||
if(entry.kind == .directory) {
|
||||
var row = try HorizontalList.init();
|
||||
const row = try HorizontalList.init();
|
||||
|
||||
const decodedName = try parseEscapedFolderName(entry.name);
|
||||
defer main.threadAllocator.free(decodedName);
|
||||
|
@ -18,7 +18,7 @@ pub var window: GuiWindow = GuiWindow {
|
||||
const padding: f32 = 8;
|
||||
|
||||
pub fn onOpen() Allocator.Error!void {
|
||||
var list = try VerticalList.init(.{padding, 16 + padding}, 300, 16);
|
||||
const list = try VerticalList.init(.{padding, 16 + padding}, 300, 16);
|
||||
try list.add(try Button.initText(.{0, 0}, 128, "Graphics", gui.openWindowCallback("graphics")));
|
||||
try list.add(try Button.initText(.{0, 0}, 128, "Sound", gui.openWindowCallback("sound")));
|
||||
try list.add(try Button.initText(.{0, 0}, 128, "Controls", gui.openWindowCallback("controls")));
|
||||
|
@ -41,7 +41,7 @@ fn musicFormatter(allocator: Allocator, value: f32) Allocator.Error![]const u8 {
|
||||
const padding: f32 = 8;
|
||||
|
||||
pub fn onOpen() Allocator.Error!void {
|
||||
var list = try VerticalList.init(.{padding, 16 + padding}, 300, 16);
|
||||
const list = try VerticalList.init(.{padding, 16 + padding}, 300, 16);
|
||||
try list.add(try ContinuousSlider.init(.{0, 0}, 128, -60, 0, linearToDezibel(settings.musicVolume), &musicCallback, &musicFormatter));
|
||||
list.finish(.center);
|
||||
window.rootComponent = list.toComponent();
|
||||
|
@ -129,12 +129,12 @@ pub fn onOpen() Allocator.Error!void {
|
||||
seed = @truncate(@as(u128, @bitCast(std.time.nanoTimestamp())));
|
||||
@memset(&availableItems, null);
|
||||
@memset(&craftingGrid, .{});
|
||||
var list = try HorizontalList.init();
|
||||
const list = try HorizontalList.init();
|
||||
{ // crafting grid
|
||||
var grid = try VerticalList.init(.{0, 0}, 300, 0);
|
||||
const grid = try VerticalList.init(.{0, 0}, 300, 0);
|
||||
// Inventory:
|
||||
for(0..5) |y| {
|
||||
var row = try HorizontalList.init();
|
||||
const row = try HorizontalList.init();
|
||||
for(0..5) |x| {
|
||||
const index = x + y*5;
|
||||
const slot = try ItemSlot.init(.{0, 0}, craftingGrid[index], &vtable, index);
|
||||
|
@ -139,7 +139,7 @@ pub const ItemDropManager = struct {
|
||||
|
||||
fn storeSingle(self: *ItemDropManager, allocator: Allocator, i: u16) !JsonElement {
|
||||
std.debug.assert(!self.mutex.tryLock()); // Mutex must be locked!
|
||||
var obj = try JsonElement.initObject(allocator);
|
||||
const obj = try JsonElement.initObject(allocator);
|
||||
const itemDrop = self.list.get(i);
|
||||
try obj.put("i", i);
|
||||
try obj.put("x", itemDrop.pos.x);
|
||||
@ -731,7 +731,7 @@ pub const ItemDropRenderer = struct {
|
||||
c.glUniform3fv(itemUniforms.ambientLight, 1, @ptrCast(&ambientLight));
|
||||
c.glUniformMatrix4fv(itemUniforms.viewMatrix, 1, c.GL_FALSE, @ptrCast(&game.camera.viewMatrix));
|
||||
c.glUniform1f(itemUniforms.sizeScale, @floatCast(ItemDropManager.diameter/4.0));
|
||||
var itemDrops = &game.world.?.itemDrops.super;
|
||||
const itemDrops = &game.world.?.itemDrops.super;
|
||||
itemDrops.mutex.lock();
|
||||
defer itemDrops.mutex.unlock();
|
||||
for(itemDrops.indices[0..itemDrops.size]) |i| {
|
||||
|
@ -928,7 +928,7 @@ pub const Tool = struct {
|
||||
inertiaCenterOfMass: f32,
|
||||
|
||||
pub fn init() !*Tool {
|
||||
var self = try main.globalAllocator.create(Tool);
|
||||
const self = try main.globalAllocator.create(Tool);
|
||||
self.image = try graphics.Image.init(main.globalAllocator, 16, 16);
|
||||
self.texture = null;
|
||||
self.tooltip = null;
|
||||
@ -945,7 +945,7 @@ pub const Tool = struct {
|
||||
}
|
||||
|
||||
pub fn initFromCraftingGrid(craftingGrid: [25]?*const BaseItem, seed: u32) !*Tool {
|
||||
var self = try init();
|
||||
const self = try init();
|
||||
self.seed = seed;
|
||||
self.craftingGrid = craftingGrid;
|
||||
// Produce the tool and its textures:
|
||||
@ -956,7 +956,7 @@ pub const Tool = struct {
|
||||
}
|
||||
|
||||
pub fn initFromJson(json: JsonElement) !*Tool {
|
||||
var self = try initFromCraftingGrid(extractItemsFromJson(json.getChild("grid")), json.get(u32, "seed", 0));
|
||||
const self = try initFromCraftingGrid(extractItemsFromJson(json.getChild("grid")), json.get(u32, "seed", 0));
|
||||
self.durability = json.get(u32, "durability", self.maxDurability);
|
||||
return self;
|
||||
}
|
||||
@ -970,8 +970,8 @@ pub const Tool = struct {
|
||||
}
|
||||
|
||||
pub fn save(self: *const Tool, allocator: Allocator) !JsonElement {
|
||||
var jsonObject = try JsonElement.initObject(allocator);
|
||||
var jsonArray = try JsonElement.initArray(allocator);
|
||||
const jsonObject = try JsonElement.initObject(allocator);
|
||||
const jsonArray = try JsonElement.initArray(allocator);
|
||||
for(self.craftingGrid) |nullItem| {
|
||||
if(nullItem) |item| {
|
||||
try jsonArray.JsonArray.append(JsonElement{.JsonString=item.id});
|
||||
@ -1049,7 +1049,7 @@ pub const Item = union(enum) {
|
||||
if(reverseIndices.get(json.get([]const u8, "item", "null"))) |baseItem| {
|
||||
return Item{.baseItem = baseItem};
|
||||
} else {
|
||||
var toolJson = json.getChild("tool");
|
||||
const toolJson = json.getChild("tool");
|
||||
if(toolJson != .JsonObject) return error.ItemNotFound;
|
||||
return Item{.tool = try Tool.initFromJson(toolJson)};
|
||||
}
|
||||
@ -1194,7 +1194,7 @@ pub const ItemStack = struct {
|
||||
}
|
||||
|
||||
pub fn store(self: *const ItemStack, allocator: Allocator) !JsonElement {
|
||||
var result = try JsonElement.initObject(allocator);
|
||||
const result = try JsonElement.initObject(allocator);
|
||||
try self.storeToJson(result);
|
||||
return result;
|
||||
}
|
||||
@ -1262,7 +1262,7 @@ pub const Inventory = struct {
|
||||
}
|
||||
|
||||
pub fn save(self: Inventory, allocator: Allocator) !JsonElement {
|
||||
var jsonObject = try JsonElement.initObject(allocator);
|
||||
const jsonObject = try JsonElement.initObject(allocator);
|
||||
try jsonObject.put("capacity", self.items.len);
|
||||
for(self.items, 0..) |stack, i| {
|
||||
if(!stack.empty()) {
|
||||
@ -1277,7 +1277,7 @@ pub const Inventory = struct {
|
||||
for(self.items, 0..) |*stack, i| {
|
||||
stack.clear();
|
||||
var buf: [1024]u8 = undefined;
|
||||
var stackJson = json.getChild(buf[0..std.fmt.formatIntBuf(&buf, i, 10, .lower, .{})]);
|
||||
const stackJson = json.getChild(buf[0..std.fmt.formatIntBuf(&buf, i, 10, .lower, .{})]);
|
||||
if(stackJson == .JsonObject) {
|
||||
stack.item = try Item.init(stackJson);
|
||||
stack.amount = stackJson.get(u16, "amount", 0);
|
||||
@ -1319,7 +1319,7 @@ pub fn register(_: []const u8, texturePath: []const u8, replacementTexturePath:
|
||||
if(reverseIndices.contains(id)) {
|
||||
std.log.warn("Registered item with id {s} twice!", .{id});
|
||||
}
|
||||
var newItem = &itemList[itemListSize];
|
||||
const newItem = &itemList[itemListSize];
|
||||
try newItem.init(arena.allocator(), texturePath, replacementTexturePath, id, json);
|
||||
try reverseIndices.put(newItem.id, newItem);
|
||||
itemListSize += 1;
|
||||
|
@ -26,7 +26,7 @@ pub const JsonElement = union(JsonType) {
|
||||
JsonObject: *std.StringHashMap(JsonElement),
|
||||
|
||||
pub fn initObject(allocator: Allocator) !JsonElement {
|
||||
var map: *std.StringHashMap(JsonElement) = try allocator.create(std.StringHashMap(JsonElement));
|
||||
const map: *std.StringHashMap(JsonElement) = try allocator.create(std.StringHashMap(JsonElement));
|
||||
map.* = std.StringHashMap(JsonElement).init(allocator);
|
||||
return JsonElement{.JsonObject=map};
|
||||
}
|
||||
@ -208,7 +208,7 @@ pub const JsonElement = union(JsonType) {
|
||||
.JsonObject => {
|
||||
var iterator = self.JsonObject.iterator();
|
||||
while(true) {
|
||||
var elem = iterator.next() orelse break;
|
||||
const elem = iterator.next() orelse break;
|
||||
allocator.free(elem.key_ptr.*);
|
||||
elem.value_ptr.free(allocator);
|
||||
}
|
||||
@ -284,7 +284,7 @@ pub const JsonElement = union(JsonType) {
|
||||
var iterator = obj.iterator();
|
||||
var first: bool = true;
|
||||
while(true) {
|
||||
var elem = iterator.next() orelse break;
|
||||
const elem = iterator.next() orelse break;
|
||||
if(!first) {
|
||||
try writer.writeByte(',');
|
||||
}
|
||||
@ -490,7 +490,7 @@ const Parser = struct {
|
||||
}
|
||||
|
||||
fn parseObject(allocator: Allocator, chars: []const u8, index: *u32) OutOfMemory!JsonElement {
|
||||
var map: *std.StringHashMap(JsonElement) = try allocator.create(std.StringHashMap(JsonElement));
|
||||
const map: *std.StringHashMap(JsonElement) = try allocator.create(std.StringHashMap(JsonElement));
|
||||
map.* = std.StringHashMap(JsonElement).init(allocator);
|
||||
while(index.* < chars.len) {
|
||||
skipWhitespaces(chars, index);
|
||||
|
@ -744,8 +744,8 @@ pub fn main() !void {
|
||||
c.glClear(c.GL_DEPTH_BUFFER_BIT | c.GL_STENCIL_BUFFER_BIT | c.GL_COLOR_BUFFER_BIT);
|
||||
}
|
||||
gui.windowlist.gpu_performance_measuring.stopQuery();
|
||||
var newTime = std.time.nanoTimestamp();
|
||||
var deltaTime = @as(f64, @floatFromInt(newTime -% lastTime))/1e9;
|
||||
const newTime = std.time.nanoTimestamp();
|
||||
const deltaTime = @as(f64, @floatFromInt(newTime -% lastTime))/1e9;
|
||||
lastFrameTime.store(deltaTime, .Monotonic);
|
||||
lastTime = newTime;
|
||||
if(game.world != null) { // Update the game
|
||||
|
@ -32,7 +32,7 @@ const Socket = struct {
|
||||
}
|
||||
|
||||
fn init(localPort: u16) !Socket {
|
||||
var self = Socket {
|
||||
const self = Socket {
|
||||
.socketID = try os.socket(os.AF.INET, os.SOCK.DGRAM, os.IPPROTO.UDP),
|
||||
};
|
||||
errdefer self.deinit();
|
||||
@ -281,7 +281,7 @@ const STUN = struct {
|
||||
|
||||
var splitter = std.mem.split(u8, server, ":");
|
||||
const ip = splitter.first();
|
||||
var serverAddress = Address {
|
||||
const serverAddress = Address {
|
||||
.ip=Socket.resolveIP(ip) catch |err| {
|
||||
std.log.err("Cannot resolve stun server address: {s}, error: {s}", .{ip, @errorName(err)});
|
||||
continue;
|
||||
@ -389,7 +389,7 @@ pub const ConnectionManager = struct {
|
||||
world: ?*game.World = null,
|
||||
|
||||
pub fn init(localPort: u16, online: bool) !*ConnectionManager {
|
||||
var result: *ConnectionManager = try main.globalAllocator.create(ConnectionManager);
|
||||
const result: *ConnectionManager = try main.globalAllocator.create(ConnectionManager);
|
||||
result.* = .{};
|
||||
result.connections = std.ArrayList(*Connection).init(main.globalAllocator);
|
||||
result.requests = std.ArrayList(*Request).init(main.globalAllocator);
|
||||
@ -462,7 +462,7 @@ pub const ConnectionManager = struct {
|
||||
if(allocator.ptr == main.globalAllocator.ptr) {
|
||||
return request.data;
|
||||
} else {
|
||||
var result = try allocator.dupe(u8, request.data);
|
||||
const result = try allocator.dupe(u8, request.data);
|
||||
main.globalAllocator.free(request.data);
|
||||
return result;
|
||||
}
|
||||
@ -569,7 +569,7 @@ pub const ConnectionManager = struct {
|
||||
}
|
||||
if(self.connections.items.len == 0 and self.online.load(.Acquire)) {
|
||||
// Send a message to external ip, to keep the port open:
|
||||
var data = [1]u8{0};
|
||||
const data = [1]u8{0};
|
||||
try self.send(&data, self.externalAddress);
|
||||
}
|
||||
}
|
||||
@ -611,7 +611,7 @@ pub const Protocols = struct {
|
||||
|
||||
{
|
||||
// TODO: Send the world data.
|
||||
var path = try std.fmt.allocPrint(main.threadAllocator, "saves/{s}/assets/", .{"Development"}); // TODO: Use world name.
|
||||
const path = try std.fmt.allocPrint(main.threadAllocator, "saves/{s}/assets/", .{"Development"}); // TODO: Use world name.
|
||||
defer main.threadAllocator.free(path);
|
||||
var dir = try std.fs.cwd().openIterableDir(path, .{});
|
||||
defer dir.close();
|
||||
@ -654,7 +654,7 @@ pub const Protocols = struct {
|
||||
try utils.Compression.unpack(try std.fs.cwd().openDir("serverAssets", .{}), data[1..]);
|
||||
},
|
||||
stepServerData => {
|
||||
var json = JsonElement.parseFromString(main.threadAllocator, data[1..]);
|
||||
const json = JsonElement.parseFromString(main.threadAllocator, data[1..]);
|
||||
defer json.free(main.threadAllocator);
|
||||
try conn.manager.world.?.finishHandshake(json);
|
||||
conn.handShakeState = stepComplete;
|
||||
@ -677,13 +677,13 @@ pub const Protocols = struct {
|
||||
}
|
||||
|
||||
pub fn clientSide(conn: *Connection, name: []const u8) !void {
|
||||
var jsonObject = JsonElement{.JsonObject=try main.threadAllocator.create(std.StringHashMap(JsonElement))};
|
||||
const jsonObject = JsonElement{.JsonObject=try main.threadAllocator.create(std.StringHashMap(JsonElement))};
|
||||
defer jsonObject.free(main.threadAllocator);
|
||||
jsonObject.JsonObject.* = std.StringHashMap(JsonElement).init(main.threadAllocator);
|
||||
try jsonObject.putOwnedString("version", settings.version);
|
||||
try jsonObject.putOwnedString("name", name);
|
||||
var prefix = [1]u8 {stepUserData};
|
||||
var data = try jsonObject.toStringEfficient(main.threadAllocator, &prefix);
|
||||
const prefix = [1]u8 {stepUserData};
|
||||
const data = try jsonObject.toStringEfficient(main.threadAllocator, &prefix);
|
||||
defer main.threadAllocator.free(data);
|
||||
try conn.sendImportant(id, data);
|
||||
|
||||
@ -711,7 +711,7 @@ pub const Protocols = struct {
|
||||
}
|
||||
pub fn sendRequest(conn: *Connection, requests: []chunk.ChunkPosition) !void {
|
||||
if(requests.len == 0) return;
|
||||
var data = try main.threadAllocator.alloc(u8, 16*requests.len);
|
||||
const data = try main.threadAllocator.alloc(u8, 16*requests.len);
|
||||
defer main.threadAllocator.free(data);
|
||||
var remaining = data;
|
||||
for(requests) |req| {
|
||||
@ -728,7 +728,7 @@ pub const Protocols = struct {
|
||||
const id: u8 = 3;
|
||||
fn receive(_: *Connection, _data: []const u8) !void {
|
||||
var data = _data;
|
||||
var pos = chunk.ChunkPosition{
|
||||
const pos = chunk.ChunkPosition{
|
||||
.wx = std.mem.readIntBig(i32, data[0..4]),
|
||||
.wy = std.mem.readIntBig(i32, data[4..8]),
|
||||
.wz = std.mem.readIntBig(i32, data[8..12]),
|
||||
@ -741,7 +741,7 @@ pub const Protocols = struct {
|
||||
std.log.err("Transmission of chunk has invalid size: {}. Input data: {any}, After inflate: {any}", .{_inflatedLen, data, _inflatedData[0.._inflatedLen]});
|
||||
}
|
||||
data = _inflatedData;
|
||||
var ch = try main.globalAllocator.create(chunk.Chunk);
|
||||
const ch = try main.globalAllocator.create(chunk.Chunk);
|
||||
ch.init(pos);
|
||||
for(&ch.blocks) |*block| {
|
||||
block.* = Block.fromInt(std.mem.readIntBig(u32, data[0..4]));
|
||||
@ -834,10 +834,10 @@ pub const Protocols = struct {
|
||||
pub const blockUpdate = struct {
|
||||
const id: u8 = 7;
|
||||
fn receive(_: *Connection, data: []const u8) !void {
|
||||
var x = std.mem.readIntBig(i32, data[0..4]);
|
||||
var y = std.mem.readIntBig(i32, data[4..8]);
|
||||
var z = std.mem.readIntBig(i32, data[8..12]);
|
||||
var newBlock = Block.fromInt(std.mem.readIntBig(u32, data[12..16]));
|
||||
const x = std.mem.readIntBig(i32, data[0..4]);
|
||||
const y = std.mem.readIntBig(i32, data[4..8]);
|
||||
const z = std.mem.readIntBig(i32, data[8..12]);
|
||||
const newBlock = Block.fromInt(std.mem.readIntBig(u32, data[12..16]));
|
||||
try renderer.RenderStructure.updateBlock(x, y, z, newBlock);
|
||||
// TODO:
|
||||
// if(conn instanceof User) {
|
||||
@ -1076,7 +1076,7 @@ pub const Protocols = struct {
|
||||
if(conn.manager.world) |world| {
|
||||
const json = JsonElement.parseFromString(main.threadAllocator, data[1..]);
|
||||
defer json.free(main.threadAllocator);
|
||||
var expectedTime = json.get(i64, "time", 0);
|
||||
const expectedTime = json.get(i64, "time", 0);
|
||||
var curTime = world.gameTime.load(.Monotonic);
|
||||
if(@abs(curTime -% expectedTime) >= 1000) {
|
||||
world.gameTime.store(expectedTime, .Monotonic);
|
||||
@ -1161,7 +1161,7 @@ pub const Protocols = struct {
|
||||
}
|
||||
|
||||
pub fn itemStackDrop(conn: *Connection, stack: ItemStack, pos: Vec3d, dir: Vec3f, vel: f32) !void {
|
||||
var jsonObject = try stack.store(main.threadAllocator);
|
||||
const jsonObject = try stack.store(main.threadAllocator);
|
||||
defer jsonObject.free(main.threadAllocator);
|
||||
try jsonObject.put("x", pos[0]);
|
||||
try jsonObject.put("y", pos[1]);
|
||||
@ -1176,7 +1176,7 @@ pub const Protocols = struct {
|
||||
}
|
||||
|
||||
pub fn itemStackCollect(conn: *Connection, stack: ItemStack) !void {
|
||||
var json = try stack.store(main.threadAllocator);
|
||||
const json = try stack.store(main.threadAllocator);
|
||||
defer json.free(main.threadAllocator);
|
||||
const string = try json.toString(main.threadAllocator);
|
||||
defer main.threadAllocator.free(string);
|
||||
@ -1184,7 +1184,7 @@ pub const Protocols = struct {
|
||||
}
|
||||
|
||||
pub fn sendTimeAndBiome(conn: *Connection, world: *const main.server.ServerWorld) !void {
|
||||
var json = try JsonElement.initObject(main.threadAllocator);
|
||||
const json = try JsonElement.initObject(main.threadAllocator);
|
||||
defer json.free(main.threadAllocator);
|
||||
try json.put("time", world.gameTime);
|
||||
const pos = conn.user.?.player.pos;
|
||||
@ -1259,7 +1259,7 @@ pub const Connection = struct {
|
||||
mutex: std.Thread.Mutex = std.Thread.Mutex{},
|
||||
|
||||
pub fn init(manager: *ConnectionManager, ipPort: []const u8) !*Connection {
|
||||
var result: *Connection = try main.globalAllocator.create(Connection);
|
||||
const result: *Connection = try main.globalAllocator.create(Connection);
|
||||
result.* = Connection {
|
||||
.manager = manager,
|
||||
.remoteAddress = undefined,
|
||||
@ -1312,11 +1312,11 @@ pub const Connection = struct {
|
||||
if(self.streamPosition == importantHeaderSize) return; // Don't send empty packets.
|
||||
// Fill the header:
|
||||
self.streamBuffer[0] = Protocols.important;
|
||||
var id = self.messageID;
|
||||
const id = self.messageID;
|
||||
self.messageID += 1;
|
||||
std.mem.writeIntBig(u32, self.streamBuffer[1..5], id); // TODO: Use little endian for better hardware support. Currently the aim is interoperability with the java version which uses big endian.
|
||||
|
||||
var packet = UnconfirmedPacket{
|
||||
const packet = UnconfirmedPacket{
|
||||
.data = try main.globalAllocator.dupe(u8, self.streamBuffer[0..self.streamPosition]),
|
||||
.lastKeepAliveSentBefore = self.lastKeepAliveSent,
|
||||
.id = id,
|
||||
@ -1350,7 +1350,7 @@ pub const Connection = struct {
|
||||
|
||||
var remaining: []const u8 = data;
|
||||
while(remaining.len != 0) {
|
||||
var copyableSize = @min(remaining.len, self.streamBuffer.len - self.streamPosition);
|
||||
const copyableSize = @min(remaining.len, self.streamBuffer.len - self.streamPosition);
|
||||
@memcpy(self.streamBuffer[self.streamPosition..][0..copyableSize], remaining[0..copyableSize]);
|
||||
remaining = remaining[copyableSize..];
|
||||
self.streamPosition += @intCast(copyableSize);
|
||||
@ -1366,7 +1366,7 @@ pub const Connection = struct {
|
||||
|
||||
if(self.disconnected) return;
|
||||
std.debug.assert(data.len + 1 < maxPacketSize);
|
||||
var fullData = try main.threadAllocator.alloc(u8, data.len + 1);
|
||||
const fullData = try main.threadAllocator.alloc(u8, data.len + 1);
|
||||
defer main.threadAllocator.free(fullData);
|
||||
fullData[0] = id;
|
||||
@memcpy(fullData[1..], data);
|
||||
@ -1382,8 +1382,8 @@ pub const Connection = struct {
|
||||
self.lastKeepAliveReceived = std.mem.readIntBig(u32, data[4..8]);
|
||||
var remaining: []const u8 = data[8..];
|
||||
while(remaining.len >= 8) {
|
||||
var start = std.mem.readIntBig(u32, remaining[0..4]);
|
||||
var len = std.mem.readIntBig(u32, remaining[4..8]);
|
||||
const start = std.mem.readIntBig(u32, remaining[0..4]);
|
||||
const len = std.mem.readIntBig(u32, remaining[4..8]);
|
||||
remaining = remaining[8..];
|
||||
var j: usize = 0;
|
||||
while(j < self.unconfirmedPackets.items.len) {
|
||||
@ -1413,7 +1413,7 @@ pub const Connection = struct {
|
||||
var leftRegion: ?u32 = null;
|
||||
var rightRegion: ?u32 = null;
|
||||
for(runLengthEncodingStarts.items, runLengthEncodingLengths.items, 0..) |start, length, reg| {
|
||||
var diff = packetID -% start;
|
||||
const diff = packetID -% start;
|
||||
if(diff < length) continue;
|
||||
if(diff == length) {
|
||||
leftRegion = @intCast(reg);
|
||||
@ -1449,7 +1449,7 @@ pub const Connection = struct {
|
||||
self.receivedPackets[0] = putBackToFront;
|
||||
self.receivedPackets[0].clearRetainingCapacity();
|
||||
}
|
||||
var output = try main.threadAllocator.alloc(u8, runLengthEncodingStarts.items.len*8 + 9);
|
||||
const output = try main.threadAllocator.alloc(u8, runLengthEncodingStarts.items.len*8 + 9);
|
||||
defer main.threadAllocator.free(output);
|
||||
output[0] = Protocols.keepAlive;
|
||||
std.mem.writeIntBig(u32, output[1..5], self.lastKeepAliveSent);
|
||||
@ -1476,7 +1476,7 @@ pub const Connection = struct {
|
||||
if(self.bruteforcingPort) {
|
||||
// This is called every 100 ms, so if I send 10 requests it shouldn't be too bad.
|
||||
for(0..5) |_| {
|
||||
var data = [1]u8{0};
|
||||
const data = [1]u8{0};
|
||||
if(self.remoteAddress.port +% self.bruteForcedPortRange != 0) {
|
||||
try self.manager.send(&data, Address{.ip = self.remoteAddress.ip, .port = self.remoteAddress.port +% self.bruteForcedPortRange});
|
||||
}
|
||||
@ -1501,7 +1501,7 @@ pub const Connection = struct {
|
||||
var id = self.lastIncompletePacket;
|
||||
var receivedPacket = self.lastReceivedPackets[id & 65535] orelse return;
|
||||
var newIndex = self.lastIndex;
|
||||
var protocol = receivedPacket[newIndex];
|
||||
const protocol = receivedPacket[newIndex];
|
||||
newIndex += 1;
|
||||
if(self.manager.world == null and self.user == null and protocol != Protocols.handShake.id)
|
||||
return;
|
||||
@ -1529,12 +1529,12 @@ pub const Connection = struct {
|
||||
var dataAvailable = receivedPacket.len - newIndex;
|
||||
var idd = id + 1;
|
||||
while(dataAvailable < len): (idd += 1) {
|
||||
var otherPacket = self.lastReceivedPackets[idd & 65535] orelse return;
|
||||
const otherPacket = self.lastReceivedPackets[idd & 65535] orelse return;
|
||||
dataAvailable += otherPacket.len;
|
||||
}
|
||||
|
||||
// Copy the data to an array:
|
||||
var data = try main.threadAllocator.alloc(u8, len);
|
||||
const data = try main.threadAllocator.alloc(u8, len);
|
||||
defer main.threadAllocator.free(data);
|
||||
var remaining = data[0..];
|
||||
while(remaining.len != 0) {
|
||||
@ -1571,7 +1571,7 @@ pub const Connection = struct {
|
||||
bytesReceived[protocol] += data.len + 20 + 8; // Including IP header and udp header;
|
||||
packetsReceived[protocol] += 1;
|
||||
if(protocol == Protocols.important) {
|
||||
var id = std.mem.readIntBig(u32, data[1..5]);
|
||||
const id = std.mem.readIntBig(u32, data[1..5]);
|
||||
if(self.handShakeState == 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) {
|
||||
|
@ -37,7 +37,7 @@ pub fn nextInt(comptime T: type, seed: *u64) T {
|
||||
pub fn nextIntBounded(comptime T: type, seed: *u64, bound: T) T {
|
||||
if(@typeInfo(T) != .Int) @compileError("Type must be integer.");
|
||||
if(@typeInfo(T).Int.signedness == .signed) @compileError("Type must be unsigned.");
|
||||
var bitSize = std.math.log2_int_ceil(T, bound);
|
||||
const bitSize = std.math.log2_int_ceil(T, bound);
|
||||
var result = nextWithBitSize(T, seed, bitSize);
|
||||
while(result >= bound) {
|
||||
result = nextWithBitSize(T, seed, bitSize);
|
||||
@ -67,8 +67,8 @@ pub fn nextDoubleSigned(seed: *u64) f64 {
|
||||
|
||||
pub fn nextPointInUnitCircle(seed: *u64) Vec2f {
|
||||
while(true) {
|
||||
var x: f32 = nextFloatSigned(seed);
|
||||
var y: f32 = nextFloatSigned(seed);
|
||||
const x: f32 = nextFloatSigned(seed);
|
||||
const y: f32 = nextFloatSigned(seed);
|
||||
if(x*x + y*y < 1) {
|
||||
return Vec2f{x, y};
|
||||
}
|
||||
|
@ -114,7 +114,7 @@ pub fn updateViewport(width: u31, height: u31, fov: f32) void {
|
||||
}
|
||||
|
||||
pub fn render(playerPosition: Vec3d) !void {
|
||||
var startTime = std.time.milliTimestamp();
|
||||
const startTime = std.time.milliTimestamp();
|
||||
// TODO:
|
||||
// if (Cubyz.player != null) {
|
||||
// if (Cubyz.playerInc.x != 0 || Cubyz.playerInc.z != 0) { // while walking
|
||||
@ -144,7 +144,7 @@ pub fn render(playerPosition: Vec3d) !void {
|
||||
ambient[0] = @max(0.1, world.ambientLight);
|
||||
ambient[1] = @max(0.1, world.ambientLight);
|
||||
ambient[2] = @max(0.1, world.ambientLight);
|
||||
var skyColor = vec.xyz(world.clearColor);
|
||||
const skyColor = vec.xyz(world.clearColor);
|
||||
game.fog.color = skyColor;
|
||||
|
||||
try renderWorld(world, ambient, skyColor, playerPosition);
|
||||
@ -532,7 +532,7 @@ pub const MenuBackGround = struct {
|
||||
const newTime = std.time.nanoTimestamp();
|
||||
angle += @as(f32, @floatFromInt(newTime - lastTime))/2e10;
|
||||
lastTime = newTime;
|
||||
var viewMatrix = Mat4f.rotationY(angle);
|
||||
const viewMatrix = Mat4f.rotationY(angle);
|
||||
shader.bind();
|
||||
|
||||
c.glUniformMatrix4fv(uniforms.viewMatrix, 1, c.GL_FALSE, @ptrCast(&viewMatrix));
|
||||
@ -546,7 +546,7 @@ pub const MenuBackGround = struct {
|
||||
|
||||
pub fn takeBackgroundImage() !void {
|
||||
const size: usize = 1024; // Use a power of 2 here, to reduce video memory waste.
|
||||
var pixels: []u32 = try main.threadAllocator.alloc(u32, size*size);
|
||||
const pixels: []u32 = try main.threadAllocator.alloc(u32, size*size);
|
||||
defer main.threadAllocator.free(pixels);
|
||||
|
||||
// Change the viewport and the matrices to render 4 cube faces:
|
||||
@ -568,7 +568,7 @@ pub const MenuBackGround = struct {
|
||||
const angles = [_]f32 {std.math.pi/2.0, std.math.pi, std.math.pi*3/2.0, std.math.pi*2};
|
||||
|
||||
// All 4 sides are stored in a single image.
|
||||
var image = try graphics.Image.init(main.threadAllocator, 4*size, size);
|
||||
const image = try graphics.Image.init(main.threadAllocator, 4*size, size);
|
||||
defer image.deinit(main.threadAllocator);
|
||||
|
||||
for(0..4) |i| {
|
||||
@ -610,10 +610,10 @@ pub const Frustum = struct {
|
||||
planes: [4]Plane, // Who cares about the near/far plane anyways?
|
||||
|
||||
pub fn init(cameraPos: Vec3f, rotationMatrix: Mat4f, fovY: f32, width: u31, height: u31) Frustum {
|
||||
var invRotationMatrix = rotationMatrix.transpose();
|
||||
var cameraDir = vec.xyz(invRotationMatrix.mulVec(Vec4f{0, 0, 1, 1}));
|
||||
var cameraUp = vec.xyz(invRotationMatrix.mulVec(Vec4f{0, 1, 0, 1}));
|
||||
var cameraRight = vec.xyz(invRotationMatrix.mulVec(Vec4f{1, 0, 0, 1}));
|
||||
const invRotationMatrix = rotationMatrix.transpose();
|
||||
const cameraDir = vec.xyz(invRotationMatrix.mulVec(Vec4f{0, 0, 1, 1}));
|
||||
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 halfHSide = halfVSide*@as(f32, @floatFromInt(width))/@as(f32, @floatFromInt(height));
|
||||
@ -656,7 +656,7 @@ pub const MeshSelection = struct {
|
||||
pub fn init() !void {
|
||||
shader = try Shader.initAndGetUniforms("assets/cubyz/shaders/block_selection_vertex.vs", "assets/cubyz/shaders/block_selection_fragment.fs", &uniforms);
|
||||
|
||||
var rawData = [_]f32 {
|
||||
const rawData = [_]f32 {
|
||||
0, 0, 0,
|
||||
0, 0, 1,
|
||||
0, 1, 0,
|
||||
@ -666,7 +666,7 @@ pub const MeshSelection = struct {
|
||||
1, 1, 0,
|
||||
1, 1, 1,
|
||||
};
|
||||
var indices = [_]u8 {
|
||||
const indices = [_]u8 {
|
||||
0, 1,
|
||||
0, 2,
|
||||
0, 4,
|
||||
@ -733,8 +733,8 @@ pub const MeshSelection = struct {
|
||||
// Check the true bounding box (using this algorithm here: https://tavianator.com/2011/ray_box.html):
|
||||
const model = blocks.meshes.model(block);
|
||||
const voxelModel = &models.voxelModels.items[model.modelIndex];
|
||||
var transformedMin = model.permutation.transform(voxelModel.min - @as(Vec3i, @splat(8))) + @as(Vec3i, @splat(8));
|
||||
var transformedMax = model.permutation.transform(voxelModel.max - @as(Vec3i, @splat(8))) + @as(Vec3i, @splat(8));
|
||||
const transformedMin = model.permutation.transform(voxelModel.min - @as(Vec3i, @splat(8))) + @as(Vec3i, @splat(8));
|
||||
const transformedMax = model.permutation.transform(voxelModel.max - @as(Vec3i, @splat(8))) + @as(Vec3i, @splat(8));
|
||||
const min: Vec3d = @floatFromInt(@min(transformedMin, transformedMax));
|
||||
const max: Vec3d = @floatFromInt(@max(transformedMin ,transformedMax));
|
||||
const voxelPosFloat: Vec3d = @floatFromInt(voxelPos);
|
||||
@ -859,11 +859,11 @@ pub const MeshSelection = struct {
|
||||
c.glEnable(c.GL_POLYGON_OFFSET_LINE);
|
||||
defer c.glDisable(c.GL_POLYGON_OFFSET_LINE);
|
||||
c.glPolygonOffset(-2, 0);
|
||||
var block = RenderStructure.getBlock(_selectedBlockPos[0], _selectedBlockPos[1], _selectedBlockPos[2]) orelse return;
|
||||
const block = RenderStructure.getBlock(_selectedBlockPos[0], _selectedBlockPos[1], _selectedBlockPos[2]) orelse return;
|
||||
const model = blocks.meshes.model(block);
|
||||
const voxelModel = &models.voxelModels.items[model.modelIndex];
|
||||
var transformedMin = model.permutation.transform(voxelModel.min - @as(Vec3i, @splat(8))) + @as(Vec3i, @splat(8));
|
||||
var transformedMax = model.permutation.transform(voxelModel.max - @as(Vec3i, @splat(8))) + @as(Vec3i, @splat(8));
|
||||
const transformedMin = model.permutation.transform(voxelModel.min - @as(Vec3i, @splat(8))) + @as(Vec3i, @splat(8));
|
||||
const transformedMax = model.permutation.transform(voxelModel.max - @as(Vec3i, @splat(8))) + @as(Vec3i, @splat(8));
|
||||
const min: Vec3f = @floatFromInt(@min(transformedMin, transformedMax));
|
||||
const max: Vec3f = @floatFromInt(@max(transformedMin ,transformedMax));
|
||||
drawCube(projectionMatrix, viewMatrix, @as(Vec3d, @floatFromInt(_selectedBlockPos)) - playerPos, min/@as(Vec3f, @splat(16.0)), max/@as(Vec3f, @splat(16.0)));
|
||||
@ -939,28 +939,28 @@ pub const RenderStructure = struct {
|
||||
}
|
||||
|
||||
fn getNodeFromRenderThread(pos: chunk.ChunkPosition) ?*ChunkMeshNode {
|
||||
var lod = std.math.log2_int(u31, pos.voxelSize);
|
||||
var xIndex = pos.wx-%(&lastX[lod]).* >> lod+chunk.chunkShift;
|
||||
var yIndex = pos.wy-%(&lastY[lod]).* >> lod+chunk.chunkShift;
|
||||
var zIndex = pos.wz-%(&lastZ[lod]).* >> lod+chunk.chunkShift;
|
||||
const lod = std.math.log2_int(u31, pos.voxelSize);
|
||||
const xIndex = pos.wx-%(&lastX[lod]).* >> lod+chunk.chunkShift;
|
||||
const yIndex = pos.wy-%(&lastY[lod]).* >> lod+chunk.chunkShift;
|
||||
const zIndex = pos.wz-%(&lastZ[lod]).* >> lod+chunk.chunkShift;
|
||||
if(xIndex < 0 or xIndex >= (&lastSize[lod]).*) return null;
|
||||
if(yIndex < 0 or yIndex >= (&lastSize[lod]).*) return null;
|
||||
if(zIndex < 0 or zIndex >= (&lastSize[lod]).*) return null;
|
||||
var index = (xIndex*(&lastSize[lod]).* + yIndex)*(&lastSize[lod]).* + zIndex;
|
||||
const index = (xIndex*(&lastSize[lod]).* + yIndex)*(&lastSize[lod]).* + zIndex;
|
||||
return storageLists[lod][@intCast(index)];
|
||||
}
|
||||
|
||||
fn _getNode(pos: chunk.ChunkPosition) ?*ChunkMeshNode {
|
||||
var lod = std.math.log2_int(u31, pos.voxelSize);
|
||||
const lod = std.math.log2_int(u31, pos.voxelSize);
|
||||
lodMutex[lod].lock();
|
||||
defer lodMutex[lod].unlock();
|
||||
var xIndex = pos.wx-%(&lastX[lod]).* >> lod+chunk.chunkShift;
|
||||
var yIndex = pos.wy-%(&lastY[lod]).* >> lod+chunk.chunkShift;
|
||||
var zIndex = pos.wz-%(&lastZ[lod]).* >> lod+chunk.chunkShift;
|
||||
const xIndex = pos.wx-%(&lastX[lod]).* >> lod+chunk.chunkShift;
|
||||
const yIndex = pos.wy-%(&lastY[lod]).* >> lod+chunk.chunkShift;
|
||||
const zIndex = pos.wz-%(&lastZ[lod]).* >> lod+chunk.chunkShift;
|
||||
if(xIndex < 0 or xIndex >= (&lastSize[lod]).*) return null;
|
||||
if(yIndex < 0 or yIndex >= (&lastSize[lod]).*) return null;
|
||||
if(zIndex < 0 or zIndex >= (&lastSize[lod]).*) return null;
|
||||
var index = (xIndex*(&lastSize[lod]).* + yIndex)*(&lastSize[lod]).* + zIndex;
|
||||
const index = (xIndex*(&lastSize[lod]).* + yIndex)*(&lastSize[lod]).* + zIndex;
|
||||
return storageLists[lod][@intCast(index)];
|
||||
}
|
||||
|
||||
@ -991,7 +991,7 @@ pub const RenderStructure = struct {
|
||||
pos.wy += pos.voxelSize*chunk.chunkSize*chunk.Neighbors.relY[neighbor];
|
||||
pos.wz += pos.voxelSize*chunk.chunkSize*chunk.Neighbors.relZ[neighbor];
|
||||
pos.voxelSize = resolution;
|
||||
var node = _getNode(pos) orelse return null;
|
||||
const node = _getNode(pos) orelse return null;
|
||||
return &node.mesh;
|
||||
}
|
||||
|
||||
@ -1072,7 +1072,7 @@ pub const RenderStructure = struct {
|
||||
}
|
||||
}
|
||||
|
||||
var oldList = storageLists[lod];
|
||||
const oldList = storageLists[lod];
|
||||
{
|
||||
lodMutex[lod].lock();
|
||||
defer lodMutex[lod].unlock();
|
||||
@ -1421,7 +1421,7 @@ pub const RenderStructure = struct {
|
||||
};
|
||||
|
||||
pub fn schedule(mesh: *chunk.Chunk) !void {
|
||||
var task = try main.globalAllocator.create(MeshGenerationTask);
|
||||
const task = try main.globalAllocator.create(MeshGenerationTask);
|
||||
task.* = MeshGenerationTask {
|
||||
.mesh = mesh,
|
||||
};
|
||||
@ -1433,7 +1433,7 @@ pub const RenderStructure = struct {
|
||||
}
|
||||
|
||||
pub fn isStillNeeded(self: *MeshGenerationTask) bool {
|
||||
var distanceSqr = self.mesh.pos.getMinDistanceSquared(game.Player.getPosBlocking()); // TODO: This is called in loop, find a way to do this without calling the mutex every time.
|
||||
const distanceSqr = self.mesh.pos.getMinDistanceSquared(game.Player.getPosBlocking()); // TODO: This is called in loop, find a way to do this without calling the mutex every time.
|
||||
var maxRenderDistance = settings.renderDistance*chunk.chunkSize*self.mesh.pos.voxelSize;
|
||||
if(self.mesh.pos.voxelSize != 1) maxRenderDistance = @intFromFloat(@ceil(@as(f32, @floatFromInt(maxRenderDistance))*settings.LODFactor));
|
||||
maxRenderDistance += 2*self.mesh.pos.voxelSize*chunk.chunkSize;
|
||||
|
@ -66,7 +66,7 @@ pub const CaveBiomeGenerator = struct {
|
||||
var generatorRegistry: std.StringHashMapUnmanaged(CaveBiomeGenerator) = .{};
|
||||
|
||||
pub fn registerGenerator(comptime Generator: type) !void {
|
||||
var self = CaveBiomeGenerator {
|
||||
const self = CaveBiomeGenerator {
|
||||
.init = &Generator.init,
|
||||
.deinit = &Generator.deinit,
|
||||
.generate = &Generator.generate,
|
||||
|
@ -98,7 +98,7 @@ pub const CaveGenerator = struct {
|
||||
var generatorRegistry: std.StringHashMapUnmanaged(CaveGenerator) = .{};
|
||||
|
||||
pub fn registerGenerator(comptime Generator: type) !void {
|
||||
var self = CaveGenerator {
|
||||
const self = CaveGenerator {
|
||||
.init = &Generator.init,
|
||||
.deinit = &Generator.deinit,
|
||||
.generate = &Generator.generate,
|
||||
|
@ -71,7 +71,7 @@ pub const ClimateMapGenerator = struct {
|
||||
var generatorRegistry: std.StringHashMapUnmanaged(ClimateMapGenerator) = .{};
|
||||
|
||||
pub fn registerGenerator(comptime Generator: type) !void {
|
||||
var self = ClimateMapGenerator {
|
||||
const self = ClimateMapGenerator {
|
||||
.init = &Generator.init,
|
||||
.deinit = &Generator.deinit,
|
||||
.generateMapFragment = &Generator.generateMapFragment,
|
||||
|
@ -92,7 +92,7 @@ pub const MapGenerator = struct {
|
||||
var generatorRegistry: std.StringHashMapUnmanaged(MapGenerator) = .{};
|
||||
|
||||
fn registerGenerator(comptime Generator: type) !void {
|
||||
var self = MapGenerator {
|
||||
const self = MapGenerator {
|
||||
.init = &Generator.init,
|
||||
.deinit = &Generator.deinit,
|
||||
.generateMapFragment = &Generator.generateMapFragment,
|
||||
|
@ -43,7 +43,7 @@ pub fn generate(map: *CaveMapFragment, worldSeed: u64) Allocator.Error!void {
|
||||
const outerSize = @max(map.pos.voxelSize, interpolatedPart);
|
||||
const outerSizeShift = std.math.log2_int(u31, outerSize);
|
||||
const outerSizeFloat: f32 = @floatFromInt(outerSize);
|
||||
var noise = try FractalNoise3D.generateAligned(main.threadAllocator, map.pos.wx, map.pos.wy, map.pos.wz, outerSize, CaveMapFragment.width*map.pos.voxelSize/outerSize + 1, CaveMapFragment.height*map.pos.voxelSize/outerSize + 1, CaveMapFragment.width*map.pos.voxelSize/outerSize + 1, worldSeed, scale);//try Cached3DFractalNoise.init(map.pos.wx, map.pos.wy & ~@as(i32, CaveMapFragment.width*map.pos.voxelSize - 1), map.pos.wz, outerSize, map.pos.voxelSize*CaveMapFragment.width, worldSeed, scale);
|
||||
const noise = try FractalNoise3D.generateAligned(main.threadAllocator, map.pos.wx, map.pos.wy, map.pos.wz, outerSize, CaveMapFragment.width*map.pos.voxelSize/outerSize + 1, CaveMapFragment.height*map.pos.voxelSize/outerSize + 1, CaveMapFragment.width*map.pos.voxelSize/outerSize + 1, worldSeed, scale);//try Cached3DFractalNoise.init(map.pos.wx, map.pos.wy & ~@as(i32, CaveMapFragment.width*map.pos.voxelSize - 1), map.pos.wz, outerSize, map.pos.voxelSize*CaveMapFragment.width, worldSeed, scale);
|
||||
defer noise.deinit(main.threadAllocator);
|
||||
biomeMap.bulkInterpolateValue("caves", map.pos.wx, map.pos.wy, map.pos.wz, outerSize, noise, .addToMap, scale);
|
||||
var x: u31 = 0;
|
||||
|
@ -121,7 +121,7 @@ fn considerCrystal(x: i32, y: i32, z: i32, chunk: *main.chunk.Chunk, seed: *u64,
|
||||
}
|
||||
|
||||
fn considerCoordinates(x: i32, y: i32, z: i32, chunk: *main.chunk.Chunk, caveMap: CaveMap.CaveMapView, biomeMap: CaveBiomeMap.CaveBiomeMapView, seed: *u64) void {
|
||||
var oldSeed = seed.*;
|
||||
const oldSeed = seed.*;
|
||||
const crystalSpawns = biomeMap.getBiomeAndSeed(x + main.chunk.chunkSize/2 - chunk.pos.wx, y + main.chunk.chunkSize/2 - chunk.pos.wy, z + main.chunk.chunkSize/2 - chunk.pos.wz, true, seed).crystals;
|
||||
random.scrambleSeed(seed);
|
||||
var differendColors: u32 = 1;
|
||||
|
@ -52,7 +52,7 @@ pub fn generate(worldSeed: u64, chunk: *main.chunk.Chunk, caveMap: CaveMap.CaveM
|
||||
if(relY < py or relY >= py + 32) continue;
|
||||
const biome = biomeMap.getBiome(px, relY, pz);
|
||||
var randomValue = random.nextFloat(&seed);
|
||||
for(biome.vegetationModels) |model| {
|
||||
for(biome.vegetationModels) |model| { // TODO: Could probably use an alias table here.
|
||||
const adaptedChance = model.chance*16;
|
||||
if(randomValue < adaptedChance) {
|
||||
try model.generate(px, relY, pz, chunk, caveMap, &seed);
|
||||
@ -78,7 +78,7 @@ pub fn generate(worldSeed: u64, chunk: *main.chunk.Chunk, caveMap: CaveMap.CaveM
|
||||
var seed = random.initSeed3D(worldSeed, .{wpx, relY, wpz});
|
||||
var randomValue = random.nextFloat(&seed);
|
||||
const biome = biomeMap.getBiome(px, relY, pz);
|
||||
for(biome.vegetationModels) |model| {
|
||||
for(biome.vegetationModels) |model| { // TODO: Could probably use an alias table here.
|
||||
var adaptedChance = model.chance;
|
||||
// Increase chance if there are less spawn points considered. Messes up positions, but at that distance density matters more.
|
||||
adaptedChance = 1 - std.math.pow(f32, 1 - adaptedChance, @as(f32, @floatFromInt(chunk.pos.voxelSize*chunk.pos.voxelSize)));
|
||||
|
@ -29,13 +29,13 @@ pub fn deinit() void {
|
||||
pub fn generateMapFragment(map: *ClimateMapFragment, worldSeed: u64) Allocator.Error!void {
|
||||
var seed: u64 = worldSeed;
|
||||
|
||||
var generator = try GenerationStructure.init(main.threadAllocator, map.pos.wx, map.pos.wz, ClimateMapFragment.mapSize, ClimateMapFragment.mapSize, terrain.biomes.byTypeBiomes, seed);
|
||||
const generator = try GenerationStructure.init(main.threadAllocator, map.pos.wx, map.pos.wz, ClimateMapFragment.mapSize, ClimateMapFragment.mapSize, terrain.biomes.byTypeBiomes, seed);
|
||||
defer generator.deinit(main.threadAllocator);
|
||||
|
||||
try generator.toMap(map, ClimateMapFragment.mapSize, ClimateMapFragment.mapSize, worldSeed);
|
||||
|
||||
// TODO: Remove debug image:
|
||||
var image = try main.graphics.Image.init(main.threadAllocator, @intCast(map.map.len), @intCast(map.map[0].len));
|
||||
const image = try main.graphics.Image.init(main.threadAllocator, @intCast(map.map.len), @intCast(map.map[0].len));
|
||||
defer image.deinit(main.threadAllocator);
|
||||
var x: u31 = 0;
|
||||
while(x < map.map.len) : (x += 1) {
|
||||
@ -57,7 +57,7 @@ const BiomePoint = struct {
|
||||
|
||||
fn voronoiDistanceFunction(self: @This(), pos: Vec2f) f32 {
|
||||
const len = vec.lengthSquare(self.pos - pos);
|
||||
var result = len*self.weight;
|
||||
const result = len*self.weight;
|
||||
if(result > 1.0) {
|
||||
return result + (result - 1.0)/8192.0*len;
|
||||
}
|
||||
@ -97,7 +97,7 @@ const Chunk = struct {
|
||||
fn checkIfBiomeIsValid(x: f32, y: f32, biomeRadius: f32, biomesSortedByX: []BiomePoint, chunkLocalMaxBiomeRadius: f32) bool {
|
||||
const minX = x - biomeRadius - chunkLocalMaxBiomeRadius;
|
||||
const maxX = x + biomeRadius + chunkLocalMaxBiomeRadius;
|
||||
var i: usize = getStartCoordinate(minX, biomesSortedByX);
|
||||
const i: usize = getStartCoordinate(minX, biomesSortedByX);
|
||||
for(biomesSortedByX[i..]) |other| {
|
||||
if(other.pos[0] >= maxX) break;
|
||||
const minDistance = (biomeRadius + other.biome.radius)*0.85;
|
||||
@ -140,7 +140,7 @@ const Chunk = struct {
|
||||
const x = random.nextFloat(&seed)*chunkSize + @as(f32, @floatFromInt(wx));
|
||||
const y = random.nextFloat(&seed)*chunkSize + @as(f32, @floatFromInt(wz));
|
||||
var biomeSeed: u64 = 562478564;
|
||||
var drawnBiome = tree.getBiome(&biomeSeed, x, y);
|
||||
const drawnBiome = tree.getBiome(&biomeSeed, x, y);
|
||||
if(!checkIfBiomeIsValid(x, y, drawnBiome.radius, selectedBiomes.items(), chunkLocalMaxBiomeRadius)) {
|
||||
rejections += 1;
|
||||
continue :outer;
|
||||
|
@ -94,9 +94,9 @@ pub fn generateMapFragment(map: *MapFragment, worldSeed: u64) Allocator.Error!vo
|
||||
var updatedZ = wz + (zOffsetMap.get(x, z) - 0.5)*biomeSize*4;
|
||||
var xBiome: i32 = @intFromFloat(@floor((updatedX - @as(f32, @floatFromInt(map.pos.wx)))/biomeSize));
|
||||
var zBiome: i32 = @intFromFloat(@floor((updatedZ - @as(f32, @floatFromInt(map.pos.wz)))/biomeSize));
|
||||
var relXBiome = (0.5 + updatedX - @as(f32, @floatFromInt(map.pos.wx +% xBiome*biomeSize)))/biomeSize;
|
||||
const relXBiome = (0.5 + updatedX - @as(f32, @floatFromInt(map.pos.wx +% xBiome*biomeSize)))/biomeSize;
|
||||
xBiome += offset;
|
||||
var relZBiome = (0.5 + updatedZ - @as(f32, @floatFromInt(map.pos.wz +% zBiome*biomeSize)))/biomeSize;
|
||||
const relZBiome = (0.5 + updatedZ - @as(f32, @floatFromInt(map.pos.wz +% zBiome*biomeSize)))/biomeSize;
|
||||
zBiome += offset;
|
||||
var closestBiome: *const terrain.biomes.Biome = undefined;
|
||||
if(relXBiome < 0.5) {
|
||||
|
@ -4,13 +4,11 @@ const main = @import("root");
|
||||
const random = main.random;
|
||||
|
||||
fn getSeedX(x: f32, worldSeed: u64) u64 {
|
||||
var seed: u64 = worldSeed ^ @as(u64, 54275629861)*%@as(u32, @bitCast(@as(i32, @intFromFloat(x))));
|
||||
return seed;
|
||||
return worldSeed ^ @as(u64, 54275629861)*%@as(u32, @bitCast(@as(i32, @intFromFloat(x))));
|
||||
}
|
||||
|
||||
fn getSeedY(x: f32, worldSeed: u64) u64 {
|
||||
var seed: u64 = worldSeed ^ @as(u64, 5478938690717)*%@as(u32, @bitCast(@as(i32, @intFromFloat(x))));
|
||||
return seed;
|
||||
return worldSeed ^ @as(u64, 5478938690717)*%@as(u32, @bitCast(@as(i32, @intFromFloat(x))));
|
||||
}
|
||||
|
||||
fn getGridValue1D(x: f32, worldSeed: u64) f32 {
|
||||
|
@ -30,7 +30,7 @@ pub const BlockGenerator = struct {
|
||||
var generatorRegistry: std.StringHashMapUnmanaged(BlockGenerator) = .{};
|
||||
|
||||
pub fn registerGenerator(comptime GeneratorType: type) !void {
|
||||
var self = BlockGenerator {
|
||||
const self = BlockGenerator {
|
||||
.init = &GeneratorType.init,
|
||||
.deinit = &GeneratorType.deinit,
|
||||
.generate = &GeneratorType.generate,
|
||||
|
@ -43,7 +43,7 @@ const ChunkManager = struct {
|
||||
};
|
||||
|
||||
pub fn schedule(pos: ChunkPosition, source: ?*User) !void {
|
||||
var task = try main.globalAllocator.create(ChunkLoadTask);
|
||||
const task = try main.globalAllocator.create(ChunkLoadTask);
|
||||
task.* = ChunkLoadTask {
|
||||
.pos = pos,
|
||||
.creationTime = std.time.milliTimestamp(),
|
||||
|
@ -43,9 +43,9 @@ pub const Compression = struct {
|
||||
_ = try comp.write(&len);
|
||||
_ = try comp.write(relPath);
|
||||
|
||||
var file = try sourceDir.dir.openFile(relPath, .{});
|
||||
const file = try sourceDir.dir.openFile(relPath, .{});
|
||||
defer file.close();
|
||||
var fileData = try file.readToEndAlloc(main.threadAllocator, std.math.maxInt(u32));
|
||||
const fileData = try file.readToEndAlloc(main.threadAllocator, std.math.maxInt(u32));
|
||||
defer main.threadAllocator.free(fileData);
|
||||
|
||||
std.mem.writeIntBig(u32, &len, @as(u32, @intCast(fileData.len)));
|
||||
@ -60,24 +60,24 @@ pub const Compression = struct {
|
||||
var stream = std.io.fixedBufferStream(input);
|
||||
var decomp = try std.compress.deflate.decompressor(main.threadAllocator, stream.reader(), null);
|
||||
defer decomp.deinit();
|
||||
var reader = decomp.reader();
|
||||
const reader = decomp.reader();
|
||||
const _data = try reader.readAllAlloc(main.threadAllocator, std.math.maxInt(usize));
|
||||
defer main.threadAllocator.free(_data);
|
||||
var data = _data;
|
||||
while(data.len != 0) {
|
||||
var len = std.mem.readIntBig(u32, data[0..4]);
|
||||
data = data[4..];
|
||||
var path = data[0..len];
|
||||
const path = data[0..len];
|
||||
data = data[len..];
|
||||
len = std.mem.readIntBig(u32, data[0..4]);
|
||||
data = data[4..];
|
||||
var fileData = data[0..len];
|
||||
const fileData = data[0..len];
|
||||
data = data[len..];
|
||||
|
||||
var splitter = std.mem.splitBackwards(u8, path, "/");
|
||||
_ = splitter.first();
|
||||
try outDir.makePath(splitter.rest());
|
||||
var file = try outDir.createFile(path, .{});
|
||||
const file = try outDir.createFile(path, .{});
|
||||
defer file.close();
|
||||
try file.writeAll(fileData);
|
||||
}
|
||||
@ -145,7 +145,7 @@ pub fn AliasTable(comptime T: type) type {
|
||||
}
|
||||
|
||||
pub fn initFromContext(allocator: Allocator, slice: anytype) !@This() {
|
||||
var items = try allocator.alloc(T, slice.len);
|
||||
const items = try allocator.alloc(T, slice.len);
|
||||
for(slice, items) |context, *result| {
|
||||
result.* = context.getItem();
|
||||
}
|
||||
@ -329,7 +329,7 @@ pub fn BlockingMaxHeap(comptime T: type) type {
|
||||
closed: bool = false,
|
||||
|
||||
pub fn init(allocator: Allocator) !*@This() {
|
||||
var self = try allocator.create(@This());
|
||||
const self = try allocator.create(@This());
|
||||
self.* = @This() {
|
||||
.size = 0,
|
||||
.array = try allocator.alloc(T, initialSize),
|
||||
@ -360,11 +360,11 @@ pub fn BlockingMaxHeap(comptime T: type) type {
|
||||
std.debug.assert(!self.mutex.tryLock()); // The mutex should be locked when calling this function.
|
||||
var i = _i;
|
||||
while(2*i + 1 < self.size) {
|
||||
var biggest = if(2*i + 2 < self.size and self.array[2*i + 2].biggerThan(self.array[2*i + 1])) 2*i + 2 else 2*i + 1;
|
||||
const biggest = if(2*i + 2 < self.size and self.array[2*i + 2].biggerThan(self.array[2*i + 1])) 2*i + 2 else 2*i + 1;
|
||||
// Break if all childs are smaller.
|
||||
if(self.array[i].biggerThan(self.array[biggest])) return;
|
||||
// Swap it:
|
||||
var local = self.array[biggest];
|
||||
const local = self.array[biggest];
|
||||
self.array[biggest] = self.array[i];
|
||||
self.array[i] = local;
|
||||
// goto the next node:
|
||||
@ -377,9 +377,9 @@ pub fn BlockingMaxHeap(comptime T: type) type {
|
||||
std.debug.assert(!self.mutex.tryLock()); // The mutex should be locked when calling this function.
|
||||
var i = _i;
|
||||
while(i > 0) {
|
||||
var parentIndex = (i - 1)/2;
|
||||
const parentIndex = (i - 1)/2;
|
||||
if(!self.array[i].biggerThan(self.array[parentIndex])) break;
|
||||
var local = self.array[parentIndex];
|
||||
const local = self.array[parentIndex];
|
||||
self.array[parentIndex] = self.array[i];
|
||||
self.array[i] = local;
|
||||
i = parentIndex;
|
||||
@ -436,7 +436,7 @@ pub fn BlockingMaxHeap(comptime T: type) type {
|
||||
self.waitingThreads.wait(&self.mutex);
|
||||
self.waitingThreadCount -= 1;
|
||||
} else {
|
||||
var ret = self.array[0];
|
||||
const ret = self.array[0];
|
||||
self.removeIndex(0);
|
||||
return ret;
|
||||
}
|
||||
@ -538,7 +538,7 @@ pub const ThreadPool = struct {
|
||||
var lastUpdate = std.time.milliTimestamp();
|
||||
while(true) {
|
||||
{
|
||||
var task = self.loadList.extractMax() catch break;
|
||||
const task = self.loadList.extractMax() catch break;
|
||||
self.currentTasks[id].store(task.vtable, .Monotonic);
|
||||
try task.vtable.run(task.self);
|
||||
self.currentTasks[id].store(null, .Monotonic);
|
||||
@ -843,8 +843,7 @@ pub fn GenericInterpolation(comptime elements: comptime_int) type {
|
||||
const drag = std.math.pow(f64, 0.5, deltaTime);
|
||||
for(indices) |i| {
|
||||
const index = @as(usize, i)*coordinatesPerIndex;
|
||||
var j: u32 = 0;
|
||||
while(j < coordinatesPerIndex): (j += 1) {
|
||||
for(0..coordinatesPerIndex) |j| {
|
||||
// Just move on with the current velocity.
|
||||
self.outPos[index + j] += self.outVel[index + j]*deltaTime;
|
||||
// Add some drag to prevent moving far away on short connection loss.
|
||||
@ -856,8 +855,7 @@ pub fn GenericInterpolation(comptime elements: comptime_int) type {
|
||||
const t = deltaTime;
|
||||
for(indices) |i| {
|
||||
const index = @as(usize, i)*coordinatesPerIndex;
|
||||
var j: u32 = 0;
|
||||
while(j < coordinatesPerIndex): (j += 1) {
|
||||
for(0..coordinatesPerIndex) |j| {
|
||||
self.interpolateCoordinate(index + j, t, tScale);
|
||||
}
|
||||
}
|
||||
|
16
src/vec.zig
16
src/vec.zig
@ -168,7 +168,7 @@ pub const Mat4f = struct {
|
||||
}
|
||||
|
||||
pub fn mul(self: Mat4f, other: Mat4f) Mat4f {
|
||||
var transposeSelf = self.transpose();
|
||||
const transposeSelf = self.transpose();
|
||||
var result: Mat4f = undefined;
|
||||
for(&result.columns, other.columns) |*resCol, otherCol| {
|
||||
resCol.*[0] = dot(transposeSelf.columns[0], otherCol);
|
||||
@ -180,12 +180,12 @@ pub const Mat4f = struct {
|
||||
}
|
||||
|
||||
pub fn mulVec(self: Mat4f, vec: Vec4f) Vec4f {
|
||||
var transposeSelf = self.transpose();
|
||||
var result: Vec4f = undefined;
|
||||
result[0] = dot(transposeSelf.columns[0], vec);
|
||||
result[1] = dot(transposeSelf.columns[1], vec);
|
||||
result[2] = dot(transposeSelf.columns[2], vec);
|
||||
result[3] = dot(transposeSelf.columns[3], vec);
|
||||
return result;
|
||||
const transposeSelf = self.transpose();
|
||||
return Vec4f {
|
||||
dot(transposeSelf.columns[0], vec),
|
||||
dot(transposeSelf.columns[1], vec),
|
||||
dot(transposeSelf.columns[2], vec),
|
||||
dot(transposeSelf.columns[3], vec),
|
||||
};
|
||||
}
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user