Skip to content
Permalink
Browse files

Rewrite nextFreeId to not use a goto

  • Loading branch information...
UnknownShadow200 committed Jun 30, 2017
1 parent fc0b71b commit 5f1f8e1b02735a0376cf338f91e0df1fbd74371e
Showing with 26 additions and 15 deletions.
  1. +7 −14 fCraft/Commands/CpeCommands.cs
  2. +19 −1 fCraft/World/Entity.cs
@@ -159,8 +159,13 @@ static class CpeCommands {
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);
@@ -273,18 +278,6 @@ static class CpeCommands {
}
}

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
@@ -155,7 +155,23 @@ public sealed class Entity {
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 {
@@ -216,7 +232,9 @@ public sealed class Entity {
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;

0 comments on commit 5f1f8e1

Please sign in to comment.
You can’t perform that action at this time.