The for loop update.

This commit is contained in:
IntegratedQuantum 2023-02-21 21:34:09 +01:00
parent 3e027995b4
commit ff7df1bdbc
16 changed files with 101 additions and 114 deletions

View File

@ -15,7 +15,7 @@ var commonRecipes: std.ArrayList([]const u8) = undefined;
/// Reads json files recursively from all subfolders.
pub fn readAllJsonFilesInAddons(externalAllocator: Allocator, addons: std.ArrayList(std.fs.Dir), addonNames: std.ArrayList([]const u8), subPath: []const u8, output: *std.StringHashMap(JsonElement)) !void {
for(addons.items) |addon, addonIndex| {
for(addons.items, addonNames.items) |addon, addonName| {
var dir: std.fs.IterableDir = addon.openIterableDir(subPath, .{}) catch |err| {
if(err == error.FileNotFound) continue;
return err;
@ -27,7 +27,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 = addonNames.items[addonIndex];
const folderName = addonName;
var id: []u8 = try externalAllocator.alloc(u8, folderName.len + 1 + entry.path.len - 5);
std.mem.copy(u8, id[0..], folderName);
id[folderName.len] = ':';
@ -60,9 +60,9 @@ pub fn readAssets(externalAllocator: Allocator, assetPath: []const u8, blocks: *
}
}
}
defer for(addons.items) |*dir, idx| {
defer for(addons.items, addonNames.items) |*dir, addonName| {
dir.close();
main.threadAllocator.free(addonNames.items[idx]);
main.threadAllocator.free(addonName);
};
try readAllJsonFilesInAddons(externalAllocator, addons, addonNames, "blocks", blocks);
@ -163,7 +163,7 @@ pub const BlockPalette = struct {
.JsonObject = std.StringHashMap(JsonElement).init(allocator),
};
errdefer json.free(allocator);
for(self.palette.items) |item, i| {
for(self.palette.items, 0..) |item, i| {
json.JsonObject.put(try allocator.dupe(u8, item), JsonElement{.JsonInt = @intCast(i64, i)});
}
return json;

View File

@ -335,7 +335,7 @@ pub const meshes = struct {
var buffer: [1024]u8 = undefined;
var path = try std.fmt.bufPrint(&buffer, "{s}/{s}/blocks/textures/{s}.png", .{assetFolder, mod, id});
// Test if it's already in the list:
for(textureIDs.items) |other, j| {
for(textureIDs.items, 0..) |other, j| {
if(std.mem.eql(u8, other, path)) {
result = @intCast(u31, j);
return result;
@ -371,7 +371,7 @@ pub const meshes = struct {
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.
result = @intCast(u31, blockTextures.items.len);
for(textures.JsonArray.items) |item, i| {
for(textures.JsonArray.items, 0..) |item, i| {
if(i == 0) {
try animation.append(.{.frames = @intCast(i32, textures.JsonArray.items.len), .time = animationTime});
} else {
@ -410,10 +410,10 @@ 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;
for(textureIndicesRef) |_, i| {
textureIndicesRef[i] = defaultIndex;
const textureInfo = json.getChild(sideNames[i]);
textureIndicesRef[i] = try readTexture(textureInfo, assetFolder) orelse continue;
for(textureIndicesRef, sideNames) |*ref, name| {
ref.* = defaultIndex;
const textureInfo = json.getChild(name);
ref.* = try readTexture(textureInfo, assetFolder) orelse continue;
}
}

View File

@ -220,7 +220,7 @@ pub const Chunk = struct {
x &= chunkMask;
y &= chunkMask;
z &= chunkMask;
for(Neighbors.relX) |_, i| {
for(Neighbors.relX, 0..) |_, i| {
var xi = x + Neighbors.relX[i];
var yi = y + Neighbors.relY[i];
var zi = z + Neighbors.relZ[i];
@ -286,7 +286,7 @@ pub const Chunk = struct {
// Uses a specific permutation here that keeps high resolution patterns in lower resolution.
const permutationStart = (x & 1)*4 + (z & 1)*2 + (y & 1);
const block = Block{.typ = 0, .data = 0};
for(neighborCount) |_, i| {
for(0..8) |i| {
const appliedPermutation = permutationStart ^ i;
if(neighborCount[appliedPermutation] >= maxCount - 1) { // Avoid pattern breaks at chunk borders.
block = blocks[appliedPermutation];
@ -406,7 +406,7 @@ pub const meshing = struct {
var rawData: [6*3 << (3*chunkShift)]u32 = undefined; // 6 vertices per face, maximum 3 faces/block
const lut = [_]u32{0, 1, 2, 2, 1, 3};
for(rawData) |_, i| {
for(0..rawData.len) |i| {
rawData[i] = @intCast(u32, i)/6*4 + lut[i%6];
}
@ -559,7 +559,7 @@ pub const meshing = struct {
} else {
insertionIndex = self.coreCount;
self.coreCount += 1;
for(self.neighborStart) |*start| {
for(&self.neighborStart) |*start| {
start.* += 1;
}
}
@ -580,12 +580,11 @@ pub const meshing = struct {
searchStart = 0;
searchEnd = self.coreCount;
self.coreCount -= 1;
for(self.neighborStart) |*start| {
for(&self.neighborStart) |*start| {
start.* -= 1;
}
}
var i: u32 = searchStart;
while(i < searchEnd): (i += 1) {
for(searchStart..searchEnd) |i| {
if(std.meta.eql(self.faces.items[i], faceData)) {
_ = self.faces.orderedRemove(i);
return;

View File

@ -190,7 +190,7 @@ pub const ClientEntityManager = struct {
pub fn removeEntity(id: u32) void {
mutex.lock();
defer mutex.unlock();
for(entities.items) |*ent, i| {
for(entities.items, 0..) |*ent, i| {
if(ent.id == id) {
_ = entities.swapRemove(i);
break;

View File

@ -522,7 +522,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 main.threadAllocator.alloc(u32, glyphInfos.len);
defer main.threadAllocator.free(textIndexGuess);
for(textIndexGuess) |*index, i| {
for(textIndexGuess, 0..) |*index, i| {
if(i == 0 or glyphInfos[i-1].cluster != glyphInfos[i].cluster) {
index.* = glyphInfos[i].cluster;
} else {
@ -538,7 +538,7 @@ pub const TextBuffer = struct {
// Merge it all together:
self.glyphs = try allocator.alloc(GlyphData, glyphInfos.len);
for(self.glyphs) |*glyph, i| {
for(self.glyphs, 0..) |*glyph, i| {
glyph.x_advance = @intToFloat(f32, glyphPositions[i].x_advance)/4.0;
glyph.y_advance = @intToFloat(f32, glyphPositions[i].y_advance)/4.0;
glyph.x_offset = @intToFloat(f32, glyphPositions[i].x_offset)/4.0;
@ -571,7 +571,7 @@ pub const TextBuffer = struct {
var lineWidth: f32 = 0;
var lastSpaceWidth: f32 = 0;
var lastSpaceIndex: u32 = 0;
for(self.glyphs) |glyph, i| {
for(self.glyphs, 0..) |glyph, i| {
lineWidth += glyph.x_advance;
if(lineWidth > scaledMaxWidth and lastSpaceIndex != 0) {
lineWidth -= lastSpaceWidth;
@ -937,7 +937,7 @@ pub const LargeBuffer = struct {
fn alloc(self: *LargeBuffer, size: u31) !Allocation {
var smallestBlock: ?*Allocation = null;
for(self.freeBlocks.items) |*block, i| {
for(self.freeBlocks.items, 0..) |*block, i| {
if(size == block.len) {
return self.freeBlocks.swapRemove(i);
}
@ -956,7 +956,7 @@ pub const LargeBuffer = struct {
pub fn free(self: *LargeBuffer, _allocation: Allocation) !void {
var allocation = _allocation;
if(allocation.len == 0) return;
for(self.freeBlocks.items) |*block, i| {
for(self.freeBlocks.items, 0..) |*block, i| {
if(allocation.start + allocation.len == block.start) {
allocation.len += block.len;
_ = self.freeBlocks.swapRemove(i);
@ -991,7 +991,7 @@ pub const LargeBuffer = struct {
try self.freeBlocks.append(.{.start = allocation.start + allocation.len, .len = diff});
} else {
// Check if the buffer can be extended without a problem:
for(self.freeBlocks.items) |*block, i| {
for(self.freeBlocks.items, 0..) |*block, i| {
if(allocation.start + allocation.len == block.start and block.len + allocation.len >= newSize) {
const diff = newSize - allocation.len;
allocation.len += diff;
@ -1108,7 +1108,7 @@ pub const TextureArray = struct {
var g: [4]u32 = undefined;
var b: [4]u32 = undefined;
var a: [4]u32 = undefined;
for(colors) |_, i| {
for(0..4) |i| {
r[i] = colors[i].r;
g[i] = colors[i].g;
b[i] = colors[i].b;
@ -1119,7 +1119,7 @@ pub const TextureArray = struct {
var rSum: u32 = 0;
var gSum: u32 = 0;
var bSum: u32 = 0;
for(colors) |_, i| {
for(0..4) |i| {
aSum += a[i]*a[i];
rSum += r[i]*r[i];
gSum += g[i]*g[i];
@ -1164,11 +1164,11 @@ pub const TextureArray = struct {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
var lodBuffer: [][]Color = try arena.allocator().alloc([]Color, maxLOD);
for(lodBuffer) |*buffer, i| {
for(lodBuffer, 0..) |*buffer, i| {
buffer.* = try arena.allocator().alloc(Color, (maxWidth >> @intCast(u5, i))*(maxHeight >> @intCast(u5, i)));
}
for(images) |image, i| {
for(images, 0..) |image, i| {
// Check if the image contains non-binary alpha values, which makes it transparent.
var isTransparent = false;
for(image.imageData) |color| {
@ -1179,10 +1179,8 @@ pub const TextureArray = struct {
}
// Fill the buffer using nearest sampling. Probably not the best solutions for all textures, but that's what happens when someone doesn't use power of 2 textures...
var x: u32 = 0;
while(x < maxWidth): (x += 1) {
var y: u32 = 0;
while(y < maxHeight): (y += 1) {
for(0..maxWidth) |x| {
for(0..maxHeight) |y| {
const index = x + y*maxWidth;
const imageIndex = (x*image.width)/maxWidth + image.width*(y*image.height)/maxHeight;
lodBuffer[0][index] = image.imageData[imageIndex];
@ -1190,15 +1188,13 @@ pub const TextureArray = struct {
}
// Calculate the mipmap levels:
for(lodBuffer) |_, _lod| {
for(lodBuffer, 0..) |_, _lod| {
const lod = @intCast(u5, _lod);
const curWidth = maxWidth >> lod;
const curHeight = maxHeight >> lod;
if(lod != 0) {
x = 0;
while(x < curWidth): (x += 1) {
var y: u32 = 0;
while(y < curHeight): (y += 1) {
for(0..curWidth) |x| {
for(0..curHeight) |y| {
const index = x + y*curWidth;
const index2 = 2*x + 2*y*2*curWidth;
const colors = [4]Color {

View File

@ -103,7 +103,7 @@ pub fn mainButtonReleased(self: *const GuiWindow) void {
fn snapToOtherWindow(self: *GuiWindow) void {
const scale = @floor(settings.guiScale*self.scale); // TODO
for(self.relativePosition) |*relPos, i| {
for(&self.relativePosition, 0..) |*relPos, i| {
var minDist: f32 = settings.guiScale*2;
var minWindow: ?*GuiWindow = null;
var selfAttachment: AttachmentPoint = undefined;
@ -157,7 +157,7 @@ fn snapToOtherWindow(self: *GuiWindow) void {
fn positionRelativeToFrame(self: *GuiWindow) void {
const scale = @floor(settings.guiScale*self.scale); // TODO
const windowSize = main.Window.getWindowSize();
for(self.relativePosition) |*relPos, i| {
for(&self.relativePosition, 0..) |*relPos, i| {
// Snap to the center:
if(@fabs(self.pos[i] + self.size[i]*scale - windowSize[i]/2) <= settings.guiScale*2) {
relPos.* = .{.attachedToFrame = .{
@ -259,7 +259,7 @@ pub fn updateWindowPosition(self: *GuiWindow) void {
self.size = self.contentSize; // TODO
const scale = @floor(settings.guiScale*self.scale); // TODO
const windowSize = main.Window.getWindowSize();
for(self.relativePosition) |relPos, i| {
for(self.relativePosition, 0..) |relPos, i| {
switch(relPos) {
.ratio => |ratio| {
self.pos[i] = windowSize[i]*ratio - self.size[i]*scale/2;
@ -305,7 +305,7 @@ fn drawOrientationLines(self: *const GuiWindow) void {
const scale = @floor(settings.guiScale*self.scale); // TODO
draw.setColor(0x80000000);
const windowSize = main.Window.getWindowSize();
for(self.relativePosition) |relPos, i| {
for(self.relativePosition, 0..) |relPos, i| {
switch(relPos) {
.ratio, .relativeToWindow => {
continue;

View File

@ -4,7 +4,10 @@ const Allocator = std.mem.Allocator;
const main = @import("root");
const graphics = main.graphics;
const draw = graphics.draw;
const Image = graphics.Image;
const Shader = graphics.Shader;
const TextBuffer = graphics.TextBuffer;
const Texture = graphics.Texture;
const vec = main.vec;
const Vec2f = vec.Vec2f;

View File

@ -77,7 +77,7 @@ pub fn closeWindow(window: *GuiWindow) void {
if(selectedWindow == window) {
selectedWindow = null;
}
for(openWindows.items) |_openWindow, i| {
for(openWindows.items, 0..) |_openWindow, i| {
if(_openWindow == window) {
openWindows.swapRemove(i);
}
@ -88,7 +88,7 @@ pub fn closeWindow(window: *GuiWindow) void {
pub fn mainButtonPressed() void {
selectedWindow = null;
var selectedI: usize = 0;
for(openWindows.items) |window, i| {
for(openWindows.items, 0..) |window, i| {
var mousePosition = main.Window.getMousePosition();
mousePosition -= window.pos;
mousePosition /= @splat(2, window.scale*settings.guiScale);

View File

@ -41,7 +41,7 @@ pub fn onOpen() Allocator.Error!void {
}
pub fn onClose() void {
for(components) |*comp| {
for(&components) |*comp| {
comp.deinit();
}
}

View File

@ -123,9 +123,7 @@ pub const ItemDropManager = struct {
pub fn getPositionAndVelocityData(self: *ItemDropManager, allocator: Allocator) ![]u8 {
const _data = try allocator.alloc(u8, self.size*50);
var data = _data;
var ii: u16 = 0;
while(data.len != 0): (ii += 1) {
const i = self.indices[ii];
for(self.indices) |i| {
std.mem.writeIntBig(u16, data[0..2], i);
std.mem.writeIntBig(u64, data[2..10], @bitCast(u64, self.pos[i][0]));
std.mem.writeIntBig(u64, data[10..18], @bitCast(u64, self.pos[i][1]));
@ -159,9 +157,8 @@ pub const ItemDropManager = struct {
{
self.mutex.lock();
defer self.mutex.unlock();
var ii: u32 = 0;
while(ii < self.size) : (ii += 1) {
const item = try self.storeSingle(allocator, self.indices[ii]);
for(self.indices) |i| {
const item = try self.storeSingle(allocator, i);
try jsonArray.JsonArray.append(item);
}
}
@ -341,7 +338,7 @@ pub const ItemDropManager = struct {
const drag: f64 = self.airDragFactor;
var acceleration: Vec3f = Vec3f{0, -self.gravity*deltaTime, 0};
// Update gravity:
inline for([_]u0{0} ** 3) |_, i| { // TODO: Use the new for loop syntax.
inline for(0..3) |i| {
const old = pos[i];
pos[i] += vel[i]*deltaTime + acceleration[i]*deltaTime;
if(self.checkBlocks(chunk, pos)) {
@ -513,10 +510,10 @@ pub const ClientItemDropManager = struct {
{
super.mutex.lock();
defer super.mutex.unlock();
for(instance.?.interpolation.lastVel) |*lastVel| {
for(&instance.?.interpolation.lastVel) |*lastVel| {
@ptrCast(*align(8)[ItemDropManager.maxCapacity]Vec3d, lastVel)[i] = Vec3d{0, 0, 0};
}
for(instance.?.interpolation.lastPos) |*lastPos| {
for(&instance.?.interpolation.lastPos) |*lastPos| {
@ptrCast(*align(8)[ItemDropManager.maxCapacity]Vec3d, lastPos)[i] = pos;
}
}
@ -576,7 +573,7 @@ pub const ItemDropRenderer = struct {
const img = self.item.getTexture();
self.size = Vec3i{img.width, 1, img.height};
var freeSlot: ?*ItemVoxelModel = null;
for(freeSlots.items) |potentialSlot, i| {
for(freeSlots.items, 0..) |potentialSlot, i| {
if(std.meta.eql(self.size, potentialSlot.size)) {
freeSlot = potentialSlot;
_ = freeSlots.swapRemove(i);

View File

@ -35,9 +35,9 @@ const Material = struct {
self.roughness = @max(0, json.get(f32, "roughness", 1.0));
const colors = json.getChild("colors");
self.colorPalette = try allocator.alloc(Color, colors.JsonArray.items.len);
for(colors.JsonArray.items) |item, i| {
for(colors.JsonArray.items, self.colorPalette) |item, *color| {
const colorInt = item.as(u32, 0xff000000);
self.colorPalette[i] = Color {
color.* = Color {
.r = @intCast(u8, colorInt>>16 & 0xff),
.g = @intCast(u8, colorInt>>8 & 0xff),
.b = @intCast(u8, colorInt>>0 & 0xff),
@ -414,19 +414,15 @@ const TextureGenerator = struct {
pub fn generate(tool: *Tool) !void {
const img = tool.texture;
var pixelMaterials: [16][16]PixelData = undefined;
var x: u8 = 0;
while(x < 16) : (x += 1) {
var y: u8 = 0;
while(y < 16) : (y += 1) {
for(0..16) |x| {
for(0..16) |y| {
pixelMaterials[x][y] = PixelData.init(main.threadAllocator);
}
}
defer { // TODO: Maybe use an ArenaAllocator?
x = 0;
while(x < 16) : (x += 1) {
var y: u8 = 0;
while(y < 16) : (y += 1) {
for(0..16) |x| {
for(0..16) |y| {
pixelMaterials[x][y].deinit();
}
}
@ -437,7 +433,7 @@ const TextureGenerator = struct {
// Count all neighbors:
var neighborCount: [25]u8 = [_]u8{0} ** 25;
x = 0;
var x: u8 = 0;
while(x < 5) : (x += 1) {
var y: u8 = 0;
while(y < 5) : (y += 1) {
@ -683,10 +679,8 @@ const ToolPhysics = struct {
fn calculateDurability(tool: *Tool) void {
// Doesn't do much besides summing up the durability of all it's parts:
var durability: f32 = 0;
var x: u32 = 0;
while(x < 16) : (x += 1) {
var y: u32 = 0;
while(y < 16) : (y += 1) {
for(0..16) |x| {
for(0..16) |y| {
if(tool.materialGrid[x][y]) |item| {
if(item.material) |material| {
durability += material.resistance;
@ -935,7 +929,7 @@ const Tool = struct {
fn extractItemsFromJson(jsonArray: JsonElement) [25]?*const BaseItem {
var items: [25]?*const BaseItem = undefined;
for(items) |*item, i| {
for(&items, 0..) |*item, i| {
item.* = reverseIndices.get(jsonArray.getAtIndex([]const u8, i, "null"));
}
return items;
@ -1203,7 +1197,7 @@ pub const Inventory = struct {
pub fn save(self: Inventory, allocator: Allocator) !JsonElement {
var jsonObject = try JsonElement.initObject(allocator);
try jsonObject.put("capacity", self.items.len);
for(self.items) |stack, i| {
for(self.items, 0..) |stack, i| {
if(!stack.empty()) {
var buf: [1024]u8 = undefined;
try jsonObject.put(buf[0..std.fmt.formatIntBuf(&buf, i, 10, .lower, .{})], try stack.store(allocator));
@ -1213,7 +1207,7 @@ pub const Inventory = struct {
}
pub fn loadFromJson(self: Inventory, allocator: Allocator, json: JsonElement) void {
for(self.items) |*stack, i| {
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, .{})]);

View File

@ -220,8 +220,7 @@ pub const JsonElement = union(JsonType) {
return out.toOwnedSlice();
}
fn writeTabs(writer: std.ArrayList(u8).Writer, tabs: u32) !void {
var i: u32 = 0;
while(i < tabs): (i += 1) {
for(0..tabs) |_| {
try writer.writeByte('\t');
}
}
@ -252,7 +251,7 @@ pub const JsonElement = union(JsonType) {
},
.JsonArray => |array| {
try writer.writeByte('[');
for(array.items) |elem, i| {
for(array.items, 0..) |elem, i| {
if(i != 0) {
try writer.writeByte(',');
}
@ -324,7 +323,7 @@ const Parser = struct {
while(index.* < chars.len) {
whitespaceLoop:
for(whitespaces) |whitespace| {
for(whitespace) |char, i| {
for(whitespace, 0..) |char, i| {
if(char != chars[index.* + i]) {
continue :whitespaceLoop;
}

View File

@ -246,11 +246,11 @@ const STUN = struct {
fn requestAddress(connection: *ConnectionManager) Address {
var oldAddress: ?Address = null;
var attempt: u32 = 0;
var seed = [_]u8 {0} ** std.rand.DefaultCsprng.secret_seed_length;
std.mem.writeIntNative(i128, seed[0..16], std.time.nanoTimestamp()); // Not the best seed, but it's not that important.
var random = std.rand.DefaultCsprng.init(seed);
while(attempt < 16): (attempt += 1) {
for(0..16) |attempt| {
_ = attempt;
// Choose a somewhat random server, so we faster notice if any one of them stopped working.
const server = ipServerList[random.random().intRangeAtMost(usize, 0, ipServerList.len-1)];
var data = [_]u8 {
@ -344,10 +344,10 @@ const STUN = struct {
fn verifyHeader(data: []const u8, transactionID: []const u8) !void {
if(data[0] != 0x01 or data[1] != 0x01) return error.NotABinding;
if(@intCast(u16, data[2] & 0xff)*256 + (data[3] & 0xff) != data.len - 20) return error.BadSize;
for(MAGIC_COOKIE) |cookie, i| {
for(MAGIC_COOKIE, 0..) |cookie, i| {
if(data[i + 4] != cookie) return error.WrongCookie;
}
for(transactionID) |_, i| {
for(transactionID, 0..) |_, i| {
if(data[i+8] != transactionID[i]) return error.WrongTransaction;
}
}
@ -433,7 +433,7 @@ pub const ConnectionManager = struct {
request.requestNotifier.timedWait(&self.mutex, timeout_ns) catch {};
for(self.requests.items) |req, i| {
for(self.requests.items, 0..) |req, i| {
if(req == &request) {
_ = self.requests.swapRemove(i);
break;
@ -472,7 +472,7 @@ pub const ConnectionManager = struct {
self.mutex.lock();
defer self.mutex.unlock();
for(self.connections.items) |other, i| {
for(self.connections.items, 0..) |other, i| {
if(other == conn) {
_ = self.connections.swapRemove(i);
break;
@ -730,7 +730,7 @@ pub const Protocols: struct {
data = _inflatedData;
var ch = try renderer.RenderStructure.allocator.create(chunk.Chunk);
ch.init(pos);
for(ch.blocks) |*block| {
for(&ch.blocks) |*block| {
block.* = Block.fromInt(std.mem.readIntBig(u32, data[0..4]));
data = data[4..];
}
@ -749,7 +749,7 @@ pub const Protocols: struct {
var z = data[16..][2*size..3*size];
var neighbors = data[16..][3*size..4*size];
var visibleBlocks = data[16..][4*size..];
for(visData.visibles.items) |block, i| {
for(visData.visibles.items, 0..) |block, i| {
x[i] = block.x;
y[i] = block.y;
z[i] = block.z;
@ -1400,10 +1400,10 @@ pub const Connection = struct {
for(list.items) |packetID| {
var leftRegion: ?u32 = null;
var rightRegion: ?u32 = null;
for(runLengthEncodingStarts.items) |start, reg| {
for(runLengthEncodingStarts.items, runLengthEncodingLengths.items, 0..) |start, length, reg| {
var diff = packetID -% start;
if(diff < runLengthEncodingLengths.items[reg]) continue;
if(diff == runLengthEncodingLengths.items[reg]) {
if(diff < length) continue;
if(diff == length) {
leftRegion = @intCast(u32, reg);
}
if(diff == std.math.maxInt(u32)) {
@ -1444,7 +1444,7 @@ pub const Connection = struct {
self.lastKeepAliveSent += 1;
std.mem.writeIntBig(u32, output[5..9], self.otherKeepAliveReceived);
var remaining: []u8 = output[9..];
for(runLengthEncodingStarts.items) |_, i| {
for(runLengthEncodingStarts.items, 0..) |_, i| {
std.mem.writeIntBig(u32, remaining[0..4], runLengthEncodingStarts.items[i]);
std.mem.writeIntBig(u32, remaining[4..8], runLengthEncodingLengths.items[i]);
remaining = remaining[8..];
@ -1463,8 +1463,7 @@ pub const Connection = struct {
try self.flush();
if(self.bruteforcingPort) {
// This is called every 100 ms, so if I send 10 requests it shouldn't be too bad.
var i: u16 = 0;
while(i < 5): (i += 1) {
for(0..5) |_| {
var 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});

View File

@ -343,7 +343,7 @@ fn sortChunks(toSort: []*chunk.meshing.ChunkMesh, playerPos: Vec3d) !void {
const distances = try main.threadAllocator.alloc(f64, toSort.len);
defer main.threadAllocator.free(distances);
for(distances) |*dist, i| {
for(distances, 0..) |*dist, i| {
dist.* = vec.length(playerPos - Vec3d{
@intToFloat(f64, toSort[i].pos.wx),
@intToFloat(f64, toSort[i].pos.wy),
@ -812,7 +812,7 @@ pub const RenderStructure = struct {
updatableList = std.ArrayList(chunk.ChunkPosition).init(allocator);
blockUpdateList = std.ArrayList(BlockUpdate).init(allocator);
clearList = std.ArrayList(*ChunkMeshNode).init(allocator);
for(storageLists) |*storageList| {
for(&storageLists) |*storageList| {
storageList.* = try allocator.alloc(?*ChunkMeshNode, 0);
}
}
@ -887,7 +887,7 @@ pub const RenderStructure = struct {
var meshRequests = std.ArrayList(chunk.ChunkPosition).init(main.threadAllocator);
defer meshRequests.deinit();
for(storageLists) |_, _lod| {
for(0..storageLists.len) |_lod| {
const lod = @intCast(u5, _lod);
var maxRenderDistance = renderDistance*chunk.chunkSize << lod;
if(lod != 0) maxRenderDistance = @floatToInt(i32, @ceil(@intToFloat(f32, maxRenderDistance)*LODFactor));
@ -1045,7 +1045,7 @@ pub const RenderStructure = struct {
var closestPriority: f32 = -std.math.floatMax(f32);
var closestIndex: usize = 0;
const playerPos = game.Player.getPosBlocking();
for(updatableList.items) |pos, i| {
for(updatableList.items, 0..) |pos, i| {
const priority = pos.getPriority(playerPos);
if(priority > closestPriority) {
closestPriority = priority;

View File

@ -151,7 +151,7 @@ pub fn BlockingMaxHeap(comptime T: type) type {
pub fn updatePriority(self: *@This()) void {
self.mutex.lock();
defer self.mutex.unlock();
for(self.array[0..self.size/2]) |_, i| {
for(0..self.size/2) |i| {
self.siftDown(i);
}
}
@ -241,7 +241,7 @@ pub const ThreadPool = struct {
.loadList = try BlockingMaxHeap(Task).init(allocator),
.allocator = allocator,
};
for(self.threads) |*thread, i| {
for(self.threads, 0..) |*thread, i| {
thread.* = try std.Thread.spawn(.{}, run, .{self});
var buf: [64]u8 = undefined;
try thread.setName(try std.fmt.bufPrint(&buf, "Worker Thread {}", .{i+1}));
@ -348,7 +348,7 @@ pub fn Cache(comptime T: type, comptime numberOfBuckets: u32, comptime bucketSiz
fn find(self: *@This(), compare: anytype) ?*T {
std.debug.assert(!self.mutex.tryLock()); // The mutex must be locked.
for(self.items) |item, i| {
for(self.items, 0..) |item, i| {
if(compare.equals(item)) {
if(i != 0) {
std.mem.copyBackwards(?*T, self.items[1..], self.items[0..i]);
@ -384,7 +384,7 @@ pub fn Cache(comptime T: type, comptime numberOfBuckets: u32, comptime bucketSiz
fn clear(self: *@This()) void {
self.mutex.lock();
defer self.mutex.unlock();
for(self.items) |*nullItem| {
for(&self.items) |*nullItem| {
if(nullItem.*) |item| {
deinitFunction(item);
nullItem.* = null;
@ -422,13 +422,13 @@ pub fn Cache(comptime T: type, comptime numberOfBuckets: u32, comptime bucketSiz
/// Clears all elements calling the deinitFunction for each element.
pub fn clear(self: *@This()) void {
for(self.buckets) |*bucket| {
for(&self.buckets) |*bucket| {
bucket.clear();
}
}
pub fn foreach(self: *@This(), comptime function: fn(*T) void) void {
for(self.buckets) |*bucket| {
for(&self.buckets) |*bucket| {
bucket.foreach(function);
}
}
@ -517,10 +517,10 @@ pub fn GenericInterpolation(comptime elements: comptime_int) type {
// Need a new point:
var smallestTime: i16 = std.math.maxInt(i16);
var smallestIndex: ?u31 = null;
for(self.lastTimes) |_, i| {
// Only using a future time value that is far enough away to prevent jumping.
if(self.lastTimes[i] -% time >= 50 and self.lastTimes[i] -% time < smallestTime) {
smallestTime = self.lastTimes[i] -% time;
for(self.lastTimes, 0..) |lastTimeI, i| {
// Only using a future time value that is far enough away to prevent jumping.
if(lastTimeI -% time >= 50 and lastTimeI -% time < smallestTime) {
smallestTime = lastTimeI -% time;
smallestIndex = @intCast(u31, i);
}
}
@ -539,16 +539,16 @@ pub fn GenericInterpolation(comptime elements: comptime_int) type {
}
if(self.currentPoint == null) {
for(self.outPos) |*pos, i| {
for(self.outPos, self.outVel) |*pos, *vel| {
// Just move on with the current velocity.
pos.* += self.outVel[i]*deltaTime;
pos.* += (vel.*)*deltaTime;
// Add some drag to prevent moving far away on short connection loss.
self.outVel[i] *= std.math.pow(f64, 0.5, deltaTime);
vel.* *= std.math.pow(f64, 0.5, deltaTime);
}
} else {
const tScale = @intToFloat(f64, self.lastTimes[self.currentPoint.?] -% lastTime)/1000;
const t = deltaTime;
for(self.outPos) |_, i| {
for(self.outPos, 0..) |_, i| {
self.interpolateCoordinate(i, t, tScale);
}
}

View File

@ -192,11 +192,11 @@ pub const Mat4f = struct {
pub fn mul(self: Mat4f, other: Mat4f) Mat4f {
var transposeSelf = self.transpose();
var result: Mat4f = undefined;
for(other.columns) |_, col| {
result.columns[col][0] = dot(transposeSelf.columns[0], other.columns[col]);
result.columns[col][1] = dot(transposeSelf.columns[1], other.columns[col]);
result.columns[col][2] = dot(transposeSelf.columns[2], other.columns[col]);
result.columns[col][3] = dot(transposeSelf.columns[3], other.columns[col]);
for(&result.columns, other.columns) |*resCol, otherCol| {
resCol.*[0] = dot(transposeSelf.columns[0], otherCol);
resCol.*[1] = dot(transposeSelf.columns[1], otherCol);
resCol.*[2] = dot(transposeSelf.columns[2], otherCol);
resCol.*[3] = dot(transposeSelf.columns[3], otherCol);
}
return result;
}