Skip to content

Commit

Permalink
Rewrite nextFreeId to not use a goto
Browse files Browse the repository at this point in the history
  • Loading branch information
UnknownShadow200 committed Jun 30, 2017
1 parent fc0b71b commit 5f1f8e1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 15 deletions.
21 changes: 7 additions & 14 deletions fCraft/Commands/CpeCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,13 @@ private static void EntityHandler(Player player, CommandReader cmd) {
string skinString1 = (cmd.Next() ?? entityName);
if (skinString1 != null) skinString1 = ParseSkin(skinString1);

entity = Entity.Create(entityName, skinString1, requestedModel, player.World, player.Position, getNewID(player.World));
player.Message("Successfully created entity {0}&S with id:{1} and skin {2}.", entity.Name, entity.ID, entity.Skin, entity.Name);
sbyte newEntityId = Entity.NextFreeID(player.World.Name);
if (newEntityId == Packet.SelfId) {
player.Message("No more free ids left! Remove an entity first.");
} else {
entity = Entity.Create(entityName, skinString1, requestedModel, player.World, player.Position, newEntityId);
player.Message("Successfully created entity {0}&S with id:{1} and skin {2}.", entity.Name, entity.ID, entity.Skin, entity.Name);
}
break;
case "remove":
player.Message("{0} was removed from {1}", entity.Name, player.World.Name);
Expand Down Expand Up @@ -273,18 +278,6 @@ private static void EntityHandler(Player player, CommandReader cmd) {
}
}

public static sbyte getNewID(World world) {
sbyte i = 1;
go:
foreach (Entity entity in Entity.AllIn(world)) {
if (entity.ID == i) {
i++;
goto go;
}
}
return i;
}

#endregion

#region ChangeModel
Expand Down
20 changes: 19 additions & 1 deletion fCraft/World/Entity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,23 @@ public static void ReloadAll() {
EntityList.Clear();
LoadAll();
SpawnAll();
}

public unsafe static sbyte NextFreeID(string world) {
byte* used = stackalloc byte[128];
for (int i = 0; i < 128; i++)
used[i] = 0;

foreach (Entity entity in Entity.AllIn(world)) {
if (entity.ID >= 0) used[entity.ID] = 1;
}

for (int i = 0; i <= sbyte.MaxValue; i++ ) {
if (used[i] == 0) return (sbyte)i;
}
return Packet.SelfId;
}


public static void SaveAll(bool verbose) {
try {
Expand Down Expand Up @@ -216,7 +232,9 @@ public static void OldLoad() {
if (entity.World == null) continue;

sbyte id;
if (!sbyte.TryParse(entityData[3], out id)) { id = CpeCommands.getNewID(world); }
if (!sbyte.TryParse(entityData[3], out id)) id = NextFreeID(entity.World);
if (id == Packet.SelfId) continue;

entity.ID = id;
entity.Name = entityData[0] ?? entity.ID.ToString();
entity.Skin = entityData[1] ?? entity.Name;
Expand Down

0 comments on commit 5f1f8e1

Please sign in to comment.