1
0

Merge branch 'master' of https://github.com/SamJBarney/MCServer into MobSpawning

This commit is contained in:
Samuel Barney 2013-10-28 16:40:13 -06:00
commit d7a490a992
42 changed files with 1467 additions and 1241 deletions

View File

@ -693,10 +693,20 @@ World:ForEachChestInChunk(Player:GetChunkX(), Player:GetChunkZ(),
cEnchantments = cEnchantments =
{ {
Desc = [[This class is the storage for enchantments for a single {{cItem|cItem}} object, through its m_Enchantments member variable. Although it is possible to create a standalone object of this class, it is not yet used in any API directly. Desc = [[
</p> This class is the storage for enchantments for a single {{cItem|cItem}} object, through its
<p>Enchantments can be initialized either programmatically by calling the individual functions (SetLevel()), or by using a string description of the enchantment combination. This string description is in the form "id=lvl;id=lvl;...;id=lvl;", where id is either a numerical ID of the enchantment, or its textual representation from the table below, and lvl is the desired enchantment level. The class can also create its string description from its current contents; however that string description will only have the numerical IDs. m_Enchantments member variable. Although it is possible to create a standalone object of this class,
]], it is not yet used in any API directly.</p>
<p>
Enchantments can be initialized either programmatically by calling the individual functions
(SetLevel()), or by using a string description of the enchantment combination. This string
description is in the form "id=lvl;id=lvl;...;id=lvl;", where id is either a numerical ID of the
enchantment, or its textual representation from the table below, and lvl is the desired enchantment
level. The class can also create its string description from its current contents; however that
string description will only have the numerical IDs.</p>
<p>
See the {{cItem}} class for usage examples.
]],
Functions = Functions =
{ {
constructor = constructor =
@ -715,6 +725,29 @@ World:ForEachChestInChunk(Player:GetChunkX(), Player:GetChunkZ(),
}, },
Constants = Constants =
{ {
-- Only list these enchantment IDs, as they don't really need any kind of documentation:
enchAquaAffinity = { Notes = "" },
enchBaneOfArthropods = { Notes = "" },
enchBlastProtection = { Notes = "" },
enchEfficiency = { Notes = "" },
enchFeatherFalling = { Notes = "" },
enchFireAspect = { Notes = "" },
enchFireProtection = { Notes = "" },
enchFlame = { Notes = "" },
enchFortune = { Notes = "" },
enchInfinity = { Notes = "" },
enchKnockback = { Notes = "" },
enchLooting = { Notes = "" },
enchPower = { Notes = "" },
enchProjectileProtection = { Notes = "" },
enchProtection = { Notes = "" },
enchPunch = { Notes = "" },
enchRespiration = { Notes = "" },
enchSharpness = { Notes = "" },
enchSilkTouch = { Notes = "" },
enchSmite = { Notes = "" },
enchThorns = { Notes = "" },
enchUnbreaking = { Notes = "" },
}, },
}, },
@ -982,101 +1015,155 @@ cFile:Delete("/usr/bin/virus.exe");
cIniFile = cIniFile =
{ {
Desc = [[The cIniFile is a class that makes it simple to read from and write to INI files. MCServer uses mostly INI files for settings and options. Desc = [[
]], This class implements a simple name-value storage represented on disk by an INI file. These files
are suitable for low-volume high-latency human-readable information storage, such as for
configuration. MCServer itself uses INI files for settings and options.</p>
<p>
The INI files follow this basic structure:
<pre class="prettyprint lang-ini">
; Header comment line
[KeyName0]
; Key comment line 0
ValueName0=Value0
ValueName1=Value1
[KeyName1]
; Key comment line 0
; Key comment line 1
ValueName0=SomeOtherValue
</pre>
The cIniFile object stores all the objects in numbered arrays and provides access to the information
either based on names (KeyName, ValueName) or zero-based indices.</p>
<p>
The objects of this class are created empty. You need to either load a file using ReadFile(), or
insert values by hand. Then you can store the object's contents to a disk file using WriteFile(), or
just forget everything by destroying the object. Note that the file operations are quite slow.</p>
<p>
For storing high-volume low-latency data, use the {{sqlite3}} class. For storing
hierarchically-structured data, use the XML format, using the LuaExpat parser in the {{lxp}} class.
]],
Functions = Functions =
{ {
constructor = { Return = "{{cIniFile|cIniFile}}" }, constructor = { Params = "", Return = "cIniFile", Notes = "Creates a new empty cIniFile object." },
CaseSensitive = { Return = "" }, AddHeaderComment = { Params = "Comment", Return = "", Notes = "Adds a comment to be stored in the file header." },
CaseInsensitive = { Return = "" }, AddKeyComment =
Path = { Return = "" }, {
Path = { Return = "string" }, { Params = "KeyID, Comment", Return = "", Notes = "Adds a comment to be stored in the file under the specified key" },
SetPath = { Return = "" }, { Params = "KeyName, Comment", Return = "", Notes = "Adds a comment to be stored in the file under the specified key" },
ReadFile = { Return = "bool" }, },
WriteFile = { Return = "bool" }, AddKeyName = { Params = "KeyName", Returns = "number", Notes = "Adds a new key of the specified name. Returns the KeyID of the new key." },
Erase = { Return = "" }, CaseInsensitive = { Params = "", Return = "", Notes = "Sets key names' and value names' comparisons to case insensitive (default)." },
Clear = { Return = "" }, CaseSensitive = { Params = "", Return = "", Notes = "Sets key names and value names comparisons to case sensitive." },
Reset = { Return = "" }, Clear = { Params = "", Return = "", Notes = "Removes all the in-memory data. Note that , like all the other operations, this doesn't affect any file data." },
FindKey = { Notes = "long i" }, DeleteHeaderComment = { Params = "CommentID", Return = "bool" , Notes = "Deletes the specified header comment. Returns true if successful."},
FindValue = { Notes = "long i" }, DeleteHeaderComments = { Params = "", Return = "", Notes = "Deletes all headers comments." },
NumKeys = { Notes = "unsigned i" }, DeleteKey = { Params = "KeyName", Return = "bool", Notes = "Deletes the specified key, and all values in that key. Returns true if successful." },
GetNumKeys = { Notes = "unsigned i" }, DeleteKeyComment =
AddKeyName = { Notes = "unsigned int" }, {
KeyName = { Notes = "Stri" }, { Params = "KeyID, CommentID", Return = "bool", Notes = "Deletes the specified key comment. Returns true if successful." },
GetKeyName = { Notes = "Stri" }, { Params = "KeyName, CommentID", Return = "bool", Notes = "Deletes the specified key comment. Returns true if successful." },
NumValues = { Notes = "unsigned int" }, },
GetNumValues = { Notes = "unsigned int" }, DeleteKeyComments =
NumValues = { Notes = "unsigned int" }, {
GetNumValues = { Notes = "unsigned int" }, { Params = "KeyID", Return = "bool", Notes = "Deletes all comments for the specified key. Returns true if successful." },
ValueName = { Notes = "Stri" }, { Params = "KeyName", Return = "bool", Notes = "Deletes all comments for the specified key. Returns true if successful." },
GetValueName = { Notes = "Stri" }, },
ValueName = { Notes = "Stri" }, DeleteValue = { Params = "KeyName, ValueName", Return = "bool", Notes = "Deletes the specified value. Returns true if successful." },
GetValueName = { Notes = "Stri" }, DeleteValueByID = { Params = "KeyID, ValueID", Return = "bool", Notes = "Deletes the specified value. Returns true if successful." },
GetValue = { Notes = "Stri" }, FindKey = { Params = "KeyName", Return = "number", Notes = "Returns the KeyID for the specified key name, or the noID constant if the key doesn't exist." },
GetValue = { Notes = "Stri" }, FindValue = { Params = "KeyID, ValueName", Return = "numebr", Notes = "Returns the ValueID for the specified value name, or the noID constant if the specified key doesn't contain a value of that name." },
GetValueI = { Notes = "i" }, GetHeaderComment = { Params = "CommentID", Return = "string", Notes = "Returns the specified header comment, or an empty string if such comment doesn't exist" },
GetValueB = { Notes = "bo" }, GetKeyComment =
GetValueF = { Notes = "doub" }, {
GetValueSet = { Notes = "Stri" }, { Params = "KeyID, CommentID", Return = "string", Notes = "Returns the specified key comment, or an empty string if such a comment doesn't exist" },
GetValueSetI = { Notes = "i" }, { Params = "KeyName, CommentID", Return = "string", Notes = "Returns the specified key comment, or an empty string if such a comment doesn't exist" },
GetValueSetB = { Notes = "bo" }, },
GetValueSetF = { Notes = "doub" }, GetKeyName = { Params = "KeyID", Return = "string", Notes = "Returns the key name for the specified key ID. Inverse for FindKey()." },
SetValue = { Return = "bool" }, GetNumHeaderComments = { Params = "", Return = "number", Notes = "Retuns the number of header comments." },
SetValue = { Return = "bool" }, GetNumKeyComments =
SetValueI = { Return = "bool" }, {
SetValueB = { Return = "bool" }, { Params = "KeyID", Return = "number", Notes = "Returns the number of comments under the specified key" },
SetValueF = { Return = "bool" }, { Params = "KeyName", Return = "number", Notes = "Returns the number of comments under the specified key" },
DeleteValueByID = { Return = "bool" }, },
DeleteValue = { Return = "bool" }, GetNumKeys = { Params = "", Return = "number", Notes = "Returns the total number of keys. This is the range for the KeyID (0 .. GetNumKeys() - 1)" },
DeleteKey = { Return = "bool" }, GetNumValues =
NumHeaderComments = { Notes = "unsigned int" }, {
HeaderComment = { Return = "" }, { Params = "KeyID", Return = "number", Notes = "Returns the number of values stored under the specified key." },
HeaderComment = { Notes = "Stri" }, { Params = "KeyName", Return = "number", Notes = "Returns the number of values stored under the specified key." },
DeleteHeaderComment = { Return = "bool" }, },
DeleteHeaderComments = { Return = "" }, GetValue =
NumKeyComments = { Notes = "unsigned i" }, {
NumKeyComments = { Notes = "unsigned i" }, { Params = "KeyName, ValueName", Return = "string", Notes = "Returns the value of the specified name under the specified key. Returns an empty string if the value doesn't exist." },
KeyComment = { Return = "bool" }, { Params = "KeyID, ValueID", Return = "string", Notes = "Returns the value of the specified name under the specified key. Returns an empty string if the value doesn't exist." },
KeyComment = { Return = "bool" }, },
KeyComment = { Notes = "Stri" }, GetValueB = { Params = "KeyName, ValueName", Return = "bool", Notes = "Returns the value of the specified name under the specified key, as a bool. Returns false if the value doesn't exist." },
KeyComment = { Notes = "Stri" }, GetValueF = { Params = "KeyName, ValueName", Return = "number", Notes = "Returns the value of the specified name under the specified key, as a floating-point number. Returns zero if the value doesn't exist." },
DeleteKeyComment = { Return = "bool" }, GetValueI = { Params = "KeyName, ValueName", Return = "number", Notes = "Returns the value of the specified name under the specified key, as an integer. Returns zero if the value doesn't exist." },
DeleteKeyComment = { Return = "bool" }, GetValueName =
DeleteKeyComments = { Return = "bool" }, {
DeleteKeyComments = { Return = "bool" }, { Params = "KeyID, ValueID", Return = "string", Notes = "Returns the name of the specified value Inverse for FindValue()." },
{ Params = "KeyName, ValueID", Return = "string", Notes = "Returns the name of the specified value Inverse for FindValue()." },
},
GetValueSet = { Params = "KeyName, ValueName, Default", Return = "string", Notes = "Returns the value of the specified name under the specified key. If the value doesn't exist, creates it with the specified default." },
GetValueSetB = { Params = "KeyName, ValueName, Default", Return = "bool", Notes = "Returns the value of the specified name under the specified key, as a bool. If the value doesn't exist, creates it with the specified default." },
GetValueSetF = { Params = "KeyName, ValueName, Default", Return = "number", Notes = "Returns the value of the specified name under the specified key, as a floating-point number. If the value doesn't exist, creates it with the specified default." },
GetValueSetI = { Params = "KeyName, ValueName, Default", Return = "number", Notes = "Returns the value of the specified name under the specified key, as an integer. If the value doesn't exist, creates it with the specified default." },
ReadFile = { Params = "FileName, [AllowExampleFallback]", Return = "bool", Notes = "Reads the values from the specified file. Previous in-memory contents are lost. If the file cannot be opened, and AllowExample is true, another file, \"filename.example.ini\", is loaded and then saved as \"filename.ini\". Returns true if successful, false if not." },
SetValue =
{
{ Params = "KeyID, ValueID, NewValue", Return = "bool", Notes = "Overwrites the specified value with a new value. If the specified value doesn't exist, returns false (doesn't add)." },
{ Params = "KeyName, ValueName, NewValue, [CreateIfNotExists]", Return = "bool", Notes = "Overwrites the specified value with a new value. If CreateIfNotExists is true (default) and the value doesn't exist, it is first created. Returns true if the value was successfully set, false if not (didn't exists, CreateIfNotExists false)." },
},
SetValueB = { Params = "KeyName, ValueName, NewValueBool, [CreateIfNotExists]", Return = "bool", Notes = "Overwrites the specified value with a new bool value. If CreateIfNotExists is true (default) and the value doesn't exist, it is first created. Returns true if the value was successfully set, false if not (didn't exists, CreateIfNotExists false)." },
SetValueF = { Params = "KeyName, ValueName, NewValueFloat, [CreateIfNotExists]", Return = "bool", Notes = "Overwrites the specified value with a new floating-point number value. If CreateIfNotExists is true (default) and the value doesn't exist, it is first created. Returns true if the value was successfully set, false if not (didn't exists, CreateIfNotExists false)." },
SetValueI = { Params = "KeyName, ValueName, NewValueInt, [CreateIfNotExists]", Return = "bool", Notes = "Overwrites the specified value with a new integer value. If CreateIfNotExists is true (default) and the value doesn't exist, it is first created. Returns true if the value was successfully set, false if not (didn't exists, CreateIfNotExists false)." },
WriteFile = { Params = "FileName", Return = "bool", Notes = "Writes the current in-memory data into the specified file. Returns true if successful, false if not." },
}, },
Constants = Constants =
{ {
noID = { Notes = "" },
}, },
AdditionalInfo = AdditionalInfo =
{ {
{ {
Header = "Practical usage", Header = "Code example: Reading a simple value",
Contents = [[ Contents = [[
If you want to use cIniFile you need to know a couple of things; what is the key name and what
is the value name. Below is a demonstration of what is what.</p>
<pre class="prettyprint lang-ini">
; Comment line
[KeyName1]
ValueName1=Value1
ValueName2=Value2
[KeyName2]
ValueName1=Value3
</pre></p>
<p>
cIniFile is very easy to use. For example, you can find out what port the server is supposed to cIniFile is very easy to use. For example, you can find out what port the server is supposed to
use according to settings.ini by using this little snippet: use according to settings.ini by using this little snippet:
<pre class="prettyprint lang-lua"> <pre class="prettyprint lang-lua">
local IniFile = cIniFile("settings.ini"); local IniFile = cIniFile();
if (IniFile:ReadFile()) then if (IniFile:ReadFile("settings.ini")) then
ServerPort = IniFile:GetValueI("Server", "Port"); ServerPort = IniFile:GetValueI("Server", "Port");
end end
</pre> </pre>
]], ]],
}, },
}, {
}, Header = "Code example: Enumerating all objects in a file",
Contents = [[
To enumerate all keys in a file, you need to query the total number of keys, using GetNumKeys(),
and then query each key's name using GetKeyName(). Similarly, to enumerate all values under a
key, you need to query the total number of values using GetNumValues() and then query each
value's name using GetValueName().</p>
<p>
The following code logs all keynames and their valuenames into the server log:
<pre class="prettyprint lang-lua">
local IniFile = cIniFile();
IniFile:ReadFile("somefile.ini")
local NumKeys = IniFile:GetNumKeys();
for k = 0, NumKeys do
local NumValues = IniFile:GetNumValues(k);
LOG("key \"" .. IniFile:GetKeyName(k) .. "\" has " .. NumValues .. " values:");
for v = 0, NumValues do
LOG(" value \"" .. IniFile:GetValueName(k, v) .. "\".");
end
end
</pre>
]],
},
}, -- AdditionalInfo
}, -- cIniFile
cInventory = cInventory =
{ {
@ -1134,7 +1221,7 @@ These ItemGrids are available in the API and can be manipulated by the plugins,
invHotbarOffset = { Notes = "Starting slot number of the Hotbar part" }, invHotbarOffset = { Notes = "Starting slot number of the Hotbar part" },
invNumSlots = { Notes = "Total number of slots in a cInventory" }, invNumSlots = { Notes = "Total number of slots in a cInventory" },
}, },
}, }, -- cInventory
cItem = cItem =
{ {
@ -1221,7 +1308,7 @@ local Item5 = cItem(E_ITEM_DIAMOND_CHESTPLATE, 1, 0, "thorns=1;unbreaking=3");
]], ]],
}, },
}, },
}, }, -- cItem
cItemGrid = cItemGrid =
{ {
@ -1260,9 +1347,12 @@ local Item5 = cItem(E_ITEM_DIAMOND_CHESTPLATE, 1, 0, "thorns=1;unbreaking=3");
{ Params = "X, Y", Return = "", Notes = "Destroys the item in the specified slot" }, { Params = "X, Y", Return = "", Notes = "Destroys the item in the specified slot" },
}, },
GetFirstEmptySlot = { Params = "", Return = "number", Notes = "Returns the SlotNumber of the first empty slot, -1 if all slots are full" }, GetFirstEmptySlot = { Params = "", Return = "number", Notes = "Returns the SlotNumber of the first empty slot, -1 if all slots are full" },
GetFirstUsedSlot = { Params = "", Return = "number", Notes = "Returns the SlotNumber of the first non-empty slot, -1 if all slots are empty" },
GetHeight = { Params = "", Return = "number", Notes = "Returns the Y dimension of the grid" }, GetHeight = { Params = "", Return = "number", Notes = "Returns the Y dimension of the grid" },
GetLastEmptySlot = { Params = "", Return = "number", Notes = "Returns the SlotNumber of the last empty slot, -1 if all slots are full" }, GetLastEmptySlot = { Params = "", Return = "number", Notes = "Returns the SlotNumber of the last empty slot, -1 if all slots are full" },
GetLastUsedSlot = { Params = "", Return = "number", Notes = "Returns the SlotNumber of the last non-empty slot, -1 if all slots are empty" },
GetNextEmptySlot = { Params = "StartFrom", Return = "number", Notes = "Returns the SlotNumber of the first empty slot following StartFrom, -1 if all the following slots are full" }, GetNextEmptySlot = { Params = "StartFrom", Return = "number", Notes = "Returns the SlotNumber of the first empty slot following StartFrom, -1 if all the following slots are full" },
GetNextUsedSlot = { Params = "StartFrom", Return = "number", Notes = "Returns the SlotNumber of the first non-empty slot following StartFrom, -1 if all the following slots are full" },
GetNumSlots = { Params = "", Return = "number", Notes = "Returns the total number of slots in the grid (Width * Height)" }, GetNumSlots = { Params = "", Return = "number", Notes = "Returns the total number of slots in the grid (Width * Height)" },
GetSlot = GetSlot =
{ {
@ -1328,7 +1418,7 @@ end
]], ]],
}, },
}, -- AdditionalInfo }, -- AdditionalInfo
}, }, -- cItemGrid
cItems = cItems =
{ {
@ -1358,7 +1448,7 @@ end
Constants = Constants =
{ {
}, },
}, }, -- cItems
cLineBlockTracer = cLineBlockTracer =
{ {
@ -1538,9 +1628,58 @@ a_Player:OpenWindow(Window);
cMonster = cMonster =
{ {
Desc = "", Desc = [[
Functions = {}, This class is the base class for all computer-controlled mobs in the game.</p>
Constants = {}, <p>
To spawn a mob in a world, use the {{cWorld}}:SpawnMob() function.
]],
Functions =
{
FamilyFromType = { Params = "MobType", Return = "MobFamily", Notes = "(STATIC) Returns the mob family (mfXXX constants) based on the mob type (mtXXX constants)" },
GetMobFamily = { Params = "", Return = "MobFamily", Notes = "Returns this mob's family (mfXXX constant)" },
GetMobType = { Params = "", Return = "MobType", Notes = "Returns the type of this mob (mtXXX constant)" },
GetSpawnDelay = { Params = "MobFamily", Return = "number", Notes = "(STATIC) Returns the spawn delay - the number of game ticks between spawn attempts - for the specified mob family." },
MobTypeToString = { Params = "MobType", Return = "string", Notes = "(STATIC) Returns the string representing the given mob type (mtXXX constant), or empty string if unknown type." },
StringToMobType = { Params = "string", Return = "MobType", Notes = "(STATIC) Returns the mob type (mtXXX constant) parsed from the string type (\"creeper\"), or mtInvalidType if unrecognized." },
},
Constants =
{
mfAmbient = { Notes = "Family: ambient (bat)" },
mfHostile = { Notes = "Family: hostile (blaze, cavespider, creeper, enderdragon, enderman, ghast, giant, magmacube, silverfish, skeleton, slime, spider, witch, wither, zombie, zombiepigman)" },
mfMaxplusone = { Notes = "The maximum family value, plus one. Returned when monster family not recognized." },
mfPassive = { Notes = "Family: passive (chicken, cow, horse, irongolem, mooshroom, ocelot, pig, sheep, snowgolem, villager, wolf)" },
mfWater = { Notes = "Family: water (squid)" },
mtBat = { Notes = "" },
mtBlaze = { Notes = "" },
mtCaveSpider = { Notes = "" },
mtChicken = { Notes = "" },
mtCow = { Notes = "" },
mtCreeper = { Notes = "" },
mtEnderDragon = { Notes = "" },
mtEnderman = { Notes = "" },
mtGhast = { Notes = "" },
mtGiant = { Notes = "" },
mtHorse = { Notes = "" },
mtInvalidType = { Notes = "Invalid monster type. Returned when monster type not recognized" },
mtIronGolem = { Notes = "" },
mtMagmaCube = { Notes = "" },
mtMooshroom = { Notes = "" },
mtOcelot = { Notes = "" },
mtPig = { Notes = "" },
mtSheep = { Notes = "" },
mtSilverfish = { Notes = "" },
mtSkeleton = { Notes = "" },
mtSlime = { Notes = "" },
mtSnowGolem = { Notes = "" },
mtSpider = { Notes = "" },
mtSquid = { Notes = "" },
mtVillager = { Notes = "" },
mtWitch = { Notes = "" },
mtWither = { Notes = "" },
mtWolf = { Notes = "" },
mtZombie = { Notes = "" },
mtZombiePigman = { Notes = "" },
},
Inherits = "cPawn", Inherits = "cPawn",
}, },
@ -1565,58 +1704,103 @@ a_Player:OpenWindow(Window);
cPickup = cPickup =
{ {
Desc = [[cPickup is a pickup object representation. It is also commonly known as "drops". With this class you could create your own "drop" or modify automatically created. Desc = [[
]], This class represents a pickup entity (an item that the player or mobs can pick up). It is also
commonly known as "drops". With this class you could create your own "drop" or modify those
created automatically.
]],
Functions = Functions =
{ {
cPickup = { Notes = "[[cPickup}}" }, constructor = { Params = "PosX, PosY, PosZ, {{cItem|Item}}, IsPlayerCreated, [SpeedX, SpeedY, SpeedZ]", Return = "cPickup", Notes = "Creates a new pickup at the specified coords. If IsPlayerCreated is true, the pickup has a longer initial collection interval." },
GetItem = { Notes = "{{cItem|cItem}}" }, CollectedBy = { Params = "{{cPlayer}}", Return = "bool", Notes = "Tries to make the player collect the pickup. Returns true if the pickup was collected, at least partially." },
CollectedBy = { Return = "bool" }, GetAge = { Params = "", Return = "number", Notes = "Returns the number of ticks that the pickup has existed." },
}, GetItem = { Params = "", Return = "{{cItem|cItem}}", Notes = "Returns the item represented by this pickup" },
Constants = IsCollected = { Params = "", Return = "bool", Notes = "Returns true if this pickup has already been collected (is waiting to be destroyed)" },
{ IsPlayerCreated = { Params = "", Return = "bool", Notes = "Returns true if the pickup was created by a player" },
}, },
Inherits = "cEntity", Inherits = "cEntity",
}, }, -- cPickup
cPlayer = cPlayer =
{ {
Desc = [[cPlayer describes a human player in the server. cPlayer inherits all functions and members of {{cPawn|cPawn}} Desc = [[
]], This class describes a player in the server. cPlayer inherits all functions and members of
{{cPawn|cPawn}}. It handles all the aspects of the gameplay, such as hunger, sprinting, inventory
etc.
]],
Functions = Functions =
{ {
GetEyeHeight = { Return = "number" }, AddFoodExhaustion = { Params = "Exhaustion", Return = "", Notes = "Adds the specified number to the food exhaustion. Only positive numbers expected." },
GetEyePosition = { Return = "{{Vector3d|EyePositionVector}}" }, AddToGroup = { Params = "GroupName", Return = "", Notes = "Temporarily adds the player to the specified group. The assignment is lost when the player disconnects." },
GetFlying = { Return = "bool" }, CanUseCommand = { Params = "Command", Return = "bool", Notes = "Returns true if the player is allowed to use the specified command." },
GetStance = { Return = "number" }, CloseWindow = { Params = "[CanRefuse]", Return = "", Notes = "Closes the currently open UI window. If CanRefuse is true (default), the window may refuse the closing." },
GetInventory = { Return = "{{cInventory|Inventory}}" }, CloseWindowIfID = { Params = "WindowID, [CanRefuse]", Return = "", Notes = "Closes the currently open UI window if its ID matches the given ID. If CanRefuse is true (default), the window may refuse the closing." },
Feed = { Params = "AddFood, AddSaturation", Return = "bool", Notes = "Tries to add the specified amounts to food level and food saturation level (only positive amounts expected). Returns true if player was hungry and the food was consumed, false if too satiated." },
FoodPoison = { Params = "NumTicks", Return = "", Notes = "Starts the food poisoning for the specified amount of ticks; if already foodpoisoned, sets FoodPoisonedTicksRemaining to the larger of the two" },
GetAirLevel = { Params = "", Return = "number", Notes = "Returns the air level (number of ticks of air left)." },
GetClientHandle = { Params = "", Return = "{{cClientHandle}}", Notes = "Returns the client handle representing the player's connection. May be nil (AI players)." },
GetColor = { Return = "string", Notes = "Returns the full color code to be used for this player (based on the first group). Prefix player messages with this code." },
GetEquippedItem = { Params = "", Return = "{{cItem}}", Notes = "Returns the item that the player is currently holding; empty item if holding nothing." },
GetEyeHeight = { Return = "number", Notes = "Returns the height of the player's eyes, in absolute coords" },
GetEyePosition = { Return = "{{Vector3d|EyePositionVector}}", Notes = "Returns the position of the player's eyes, as a {{Vector3d}}" },
GetFoodExhaustionLevel = { Params = "", Return = "number", Notes = "Returns the food exhaustion level" },
GetFoodLevel = { Params = "", Return = "number", Notes = "Returns the food level (number of half-drumsticks on-screen)" },
GetFoodPoisonedTicksRemaining = { Params = "", Return = "", Notes = "Returns the number of ticks left for the food posoning effect" },
GetFoodSaturationLevel = { Params = "", Return = "number", Notes = "Returns the food saturation (overcharge of the food level, is depleted before food level)" },
GetFoodTickTimer = { Params = "", Return = "", Notes = "Returns the number of ticks past the last food-based heal or damage action; when this timer reaches 80, a new heal / damage is applied." },
GetGameMode = { Return = "{{eGameMode|GameMode}}", Notes = "Returns the player's gamemode. The player may have their gamemode unassigned, in which case they inherit the gamemode from the current {{cWorld|world}}.<br /> <b>NOTE:</b> Instead of comparing the value returned by this function to the gmXXX constants, use the IsGameModeXXX() functions. These functions handle the gamemode inheritance automatically."}, GetGameMode = { Return = "{{eGameMode|GameMode}}", Notes = "Returns the player's gamemode. The player may have their gamemode unassigned, in which case they inherit the gamemode from the current {{cWorld|world}}.<br /> <b>NOTE:</b> Instead of comparing the value returned by this function to the gmXXX constants, use the IsGameModeXXX() functions. These functions handle the gamemode inheritance automatically."},
GetIP = { Return = "string" }, GetGroups = { Return = "array-table of {{cGroup}}", Notes = "Returns all the groups that this player is member of, as a table. The groups are stored in the array part of the table, beginning with index 1."},
SetGameMode = { Return = "" }, GetIP = { Return = "string", Notes = "Returns the IP address of the player, if available. Returns an empty string if there's no IP to report."},
MoveTo = { Return = "" }, GetInventory = { Return = "{{cInventory|Inventory}}", Notes = "Returns the player's inventory"},
GetClientHandle = { Return = "{{cClientHandle|ClientHandle}}" }, GetMaxSpeed = { Params = "", Return = "number", Notes = "Returns the player's current maximum speed (as reported by the 1.6.1+ protocols)" },
SendMessage = { Return = "" }, GetName = { Return = "string", Notes = "Returns the player's name" },
GetName = { Return = "String" }, GetNormalMaxSpeed = { Params = "", Return = "number", Notes = "Returns the player's maximum walking speed (as reported by the 1.6.1+ protocols)" },
SetName = { Return = "" }, GetResolvedPermissions = { Return = "array-table of string", Notes = "Returns all the player's permissions, as a table. The permissions are stored in the array part of the table, beginning with index 1." },
AddToGroup = { Return = "" }, GetSprintingMaxSpeed = { Params = "", Return = "number", Notes = "Returns the player's maximum sprinting speed (as reported by the 1.6.1+ protocols)" },
CanUseCommand = { Return = "bool" }, GetStance = { Return = "number", Notes = "Returns the player's stance (Y-pos of player's eyes)" },
HasPermission = { Return = "bool" }, GetThrowSpeed = { Params = "SpeedCoeff", Return = "{{Vector3d}}", Notes = "Returns the speed vector for an object thrown with the specified speed coeff. Basically returns the normalized look vector multiplied by the coeff, with a slight random variation." },
IsInGroup = { Return = "bool" }, GetThrowStartPos = { Params = "", Return = "{{Vector3d}}", Notes = "Returns the position where the projectiles should start when thrown by this player." },
GetColor = { Return = "string" }, GetWindow = { Params = "", Return = "{{cWindow}}", Notes = "Returns the currently open UI window. If the player doesn't have any UI window open, returns the inventory window." },
TossItem = { Return = "" }, HasPermission = { Params = "PermissionString", Return = "bool", Notes = "Returns true if the player has the specified permission" },
Heal = { Return = "" }, Heal = { Params = "HitPoints", Return = "", Notes = "Heals the player by the specified amount of HPs. Only positive amounts are expected. Sends a health update to the client." },
TakeDamage = { Return = "" }, IsEating = { Params = "", Return = "bool", Notes = "Returns true if the player is currently eating the item in their hand." },
KilledBy = { Return = "" }, IsGameModeAdventure = { Params = "", Return = "bool", Notes = "Returns true if the player is in the gmAdventure gamemode, or has their gamemode unset and the world is a gmAdventure world." },
Respawn = { Return = "" }, IsGameModeCreative = { Params = "", Return = "bool", Notes = "Returns true if the player is in the gmCreative gamemode, or has their gamemode unset and the world is a gmCreative world." },
SetVisible = { Return = "" }, IsGameModeSurvival = { Params = "", Return = "bool", Notes = "Returns true if the player is in the gmSurvival gamemode, or has their gamemode unset and the world is a gmSurvival world." },
IsVisible = { Return = "bool" }, IsInGroup = { Params = "GroupNameString", Return = "bool", Notes = "Returns true if the player is a member of the specified group." },
MoveToWorld = { Return = "bool" }, IsOnGround = { Params = "", Return = "bool", Notes = "Returns true if the player is on ground (not falling, not jumping, not flying)" },
LoadPermissionsFromDisk = { Return = "" }, IsSatiated = { Params = "", Return = "bool", Notes = "Returns true if the player is satiated (cannot eat)." },
GetGroups = { Return = "list<{{cGroup|cGroup}}>" }, IsSubmerged = { Params = "", Return = "bool", Notes = "Returns true if the player is submerged in water (the player's head is in a water block)" },
GetResolvedPermissions = { Return = "string" }, IsSwimming = { Params = "", Return = "bool", Notes = "Returns true if the player is swimming in water (the player's feet are in a water block)" },
IsVisible = { Params = "", Return = "bool", Notes = "Returns true if the player is visible to other players" },
LoadPermissionsFromDisk = { Params = "", Return = "", Notes = "Reloads the player's permissions from the disk. This loses any temporary changes made to the player's groups." },
MoveTo = { Params = "{{Vector3d|NewPosition}}", Return = "Tries to move the player into the specified position." },
MoveToWorld = { Params = "WorldName", Return = "bool", Return = "Moves the player to the specified world. Returns true if successful." },
OpenWindow = { Params = "{{cWindow|Window}}", Return = "", Notes = "Opens the specified UI window for the player." },
RemoveFromGroup = { Params = "GroupName", Return = "", Notes = "Temporarily removes the player from the specified group. This change is lost when the player disconnects." },
Respawn = { Params = "", Return = "", Notes = "Restores the health, extinguishes fire, makes visible and sends the Respawn packet." },
SendMessage = { Params = "MessageString", Return = "", Notes = "Sends the specified message to the player." },
SetCrouch = { Params = "IsCrouched", Return = "", Notes = "Sets the crouch state, broadcasts the change to other players." },
SetFoodExhaustionLevel = { Params = "ExhaustionLevel", Return = "", Notes = "Sets the food exhaustion to the specified level." },
SetFoodLevel = { Params = "FoodLevel", Return = "", Notes = "Sets the food level (number of half-drumsticks on-screen)" },
SetFoodPoisonedTicksRemaining = { Params = "FoodPoisonedTicksRemaining", Return = "", Notes = "Sets the number of ticks remaining for food poisoning. Doesn't send foodpoisoning effect to the client, use FoodPoison() for that." },
SetFoodSaturationLevel = { Params = "FoodSaturationLevel", Return = "", Notes = "Sets the food saturation (overcharge of the food level)." },
SetFoodTickTimer = { Params = "FoodTickTimer", Return = "", Notes = "Sets the number of ticks past the last food-based heal or damage action; when this timer reaches 80, a new heal / damage is applied." },
SetGameMode = { Params = "{{eGameMode|NewGameMode}}", Return = "", Notes = "Sets the gamemode for the player. The new gamemode overrides the world's default gamemode, unless it is set to gmInherit." },
SetName = { Params = "Name", Return = "", Notes = "Sets the player name. This rename will NOT be visible to any players already in the server who are close enough to see this player." },
SetNormalMaxSpeed = { Params = "NormalMaxSpeed", Return = "", Notes = "Sets the normal (walking) maximum speed (as reported by the 1.6.1+ protocols)" },
SetSprint = { Params = "IsSprinting", Return = "", Notes = "Sets whether the player is sprinting or not." },
SetSprintingMaxSpeed = { Params = "SprintingMaxSpeed", Return = "", Notes = "Sets the sprinting maximum speed (as reported by the 1.6.1+ protocols)" },
SetVisible = { Params = "IsVisible", Return = "", Notes = "Sets the player visibility to other players" },
TossItem = { Params = "DraggedItem, [Amount], [CreateType], [CreateDamage]", Return = "", Notes = "FIXME: This function will be rewritten, avoid it. It tosses an item, either from the inventory, dragged in hand (while in UI window) or a newly created one." },
}, },
Constants = Constants =
{ {
DROWNING_TICKS = { Notes = "Number of ticks per heart of damage when drowning (zero AirLevel)" },
EATING_TICKS = { Notes = "Number of ticks required for consuming an item." },
MAX_AIR_LEVEL = { Notes = "The maximum air level value. AirLevel gets reset to this value when the player exits water." },
MAX_FOOD_LEVEL = { Notes = "The maximum food level value. When the food level is at this value, the player cannot eat." },
MAX_HEALTH = { Notes = "The maximum health value" },
}, },
Inherits = "cPawn", Inherits = "cPawn",
}, },
@ -1759,18 +1943,43 @@ cPluginManager.AddHook(cPluginManager.HOOK_CHAT, OnChatMessage);
cProjectileEntity = cProjectileEntity =
{ {
Desc = "", Desc = "",
Functions = {}, Functions =
Constants = {}, {
GetCreator = { Params = "", Return = "{{cEntity}} descendant", Notes = "Returns the entity who created this projectile. May return nil." },
GetMCAClassName = { Params = "", Return = "string", Notes = "Returns the string that identifies the projectile type (class name) in MCA files" },
GetProjectileKind = { Params = "", Return = "ProjectileKind", Notes = "Returns the kind of this projectile (pkXXX constant)" },
IsInGround = { Params = "", Return = "bool", Notes = "Returns true if this projectile has hit the ground." },
},
Constants =
{
pkArrow = { Notes = "The projectile is an {{cArrowEntity|arrow}}" },
pkEgg = { Notes = "The projectile is a {{cThrownEggEntity|thrown egg}}" },
pkEnderPearl = { Notes = "The projectile is a {{cThrownEnderPearlEntity|thrown enderpearl}}" },
pkExpBottle = { Notes = "The projectile is a thrown exp bottle (NYI)" },
pkFireCharge = { Notes = "The projectile is a {{cFireChargeEntity|fire charge}}" },
pkFishingFloat = { Notes = "The projectile is a fishing float (NYI)" },
pkGhastFireball = { Notes = "The projectile is a {{cGhastFireballEntity|ghast fireball}}" },
pkSnowball = { Notes = "The projectile is a {{cThrownSnowballEntity|thrown snowball}}" },
pkSplashPotion = { Notes = "The projectile is a thrown splash potion (NYI)" },
pkWitherSkull = { Notes = "The projectile is a wither skull (NYI)" },
},
Inherits = "cEntity", Inherits = "cEntity",
}, },
cRoot = cRoot =
{ {
Desc = [[There is always only one cRoot object in MCServer. cRoot manages all the important objects such as {{cServer|cServer}} Desc = [[
]], This class represents the root of MCServer's object hierarchy. There is always only one cRoot
object. It manages and allows querying all the other objects, such as {{cServer}},
{{cPluginManager}}, individual {{cWorld|worlds}} etc.</p>
<p>
To get the singleton instance of this object, you call the cRoot:Get() function. Then you can call
the individual functions on this object. Note that some of the functions are static and don't need
the instance, they are to be called directly on the cRoot class, such as cRoot:GetPhysicalRAMUsage()
]],
Functions = Functions =
{ {
Get = { Params = "", Return = "Root object", Notes = "This function returns the cRoot object." }, Get = { Params = "", Return = "Root object", Notes = "(STATIC)This function returns the cRoot object." },
BroadcastChat = { Params = "Message", Return = "", Notes = "Broadcasts a message to every player in the server." }, BroadcastChat = { Params = "Message", Return = "", Notes = "Broadcasts a message to every player in the server." },
FindAndDoWithPlayer = { Params = "PlayerName, CallbackFunction", Return = "", Notes = "Calls the given callback function for the given player." }, FindAndDoWithPlayer = { Params = "PlayerName, CallbackFunction", Return = "", Notes = "Calls the given callback function for the given player." },
ForEachPlayer = { Params = "CallbackFunction", Return = "", Notes = "Calls the given callback function for each player. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|cPlayer}})</pre>" }, ForEachPlayer = { Params = "CallbackFunction", Return = "", Notes = "Calls the given callback function for each player. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|cPlayer}})</pre>" },
@ -1779,11 +1988,13 @@ cPluginManager.AddHook(cPluginManager.HOOK_CHAT, OnChatMessage);
GetDefaultWorld = { Params = "", Return = "{{cWorld|cWorld}}", Notes = "Returns the world object from the default world." }, GetDefaultWorld = { Params = "", Return = "{{cWorld|cWorld}}", Notes = "Returns the world object from the default world." },
GetFurnaceRecipe = { Params = "", Return = "{{cFurnaceRecipe|cFurnaceRecipe}}", Notes = "Returns the cFurnaceRecipes object." }, GetFurnaceRecipe = { Params = "", Return = "{{cFurnaceRecipe|cFurnaceRecipe}}", Notes = "Returns the cFurnaceRecipes object." },
GetGroupManager = { Params = "", Return = "{{cGroupManager|cGroupManager}}", Notes = "Returns the cGroupManager object." }, GetGroupManager = { Params = "", Return = "{{cGroupManager|cGroupManager}}", Notes = "Returns the cGroupManager object." },
GetPhysicalRAMUsage = { Params = "", Return = "number", Notes = "Returns the amount of physical RAM that the entire MCServer process is using, in KiB. Negative if the OS doesn't support this query." },
GetPluginManager = { Params = "", Return = "{{cPluginManager|cPluginManager}}", Notes = "Returns the cPluginManager object." }, GetPluginManager = { Params = "", Return = "{{cPluginManager|cPluginManager}}", Notes = "Returns the cPluginManager object." },
GetPrimaryServerVersion = { Params = "", Return = "number", Notes = "Returns the servers primary server version." }, GetPrimaryServerVersion = { Params = "", Return = "number", Notes = "Returns the servers primary server version." },
GetProtocolVersionTextFromInt = { Params = "Protocol Version", Return = "string", Notes = "Returns the Minecraft version from the given Protocol. If there is no version found, it returns 'Unknown protocol(Parameter)'" }, GetProtocolVersionTextFromInt = { Params = "Protocol Version", Return = "string", Notes = "Returns the Minecraft version from the given Protocol. If there is no version found, it returns 'Unknown protocol(Parameter)'" },
GetServer = { Params = "", Return = "{{cServer|cServer}}", Notes = "Returns the cServer object." }, GetServer = { Params = "", Return = "{{cServer|cServer}}", Notes = "Returns the cServer object." },
GetTotalChunkCount = { Params = "", Return = "number", Notes = "Returns the amount of loaded chunks." }, GetTotalChunkCount = { Params = "", Return = "number", Notes = "Returns the amount of loaded chunks." },
GetVirtualRAMUsage = { Params = "", Return = "number", Notes = "Returns the amount of virtual RAM that the entire MCServer process is using, in KiB. Negative if the OS doesn't support this query." },
GetWebAdmin = { Params = "", Return = "{{cWebAdmin|cWebAdmin}}", Notes = "Returns the cWebAdmin object." }, GetWebAdmin = { Params = "", Return = "{{cWebAdmin|cWebAdmin}}", Notes = "Returns the cWebAdmin object." },
GetWorld = { Params = "WorldName", Return = "{{cWorld|cWorld}}", Notes = "Returns the cWorld object of the given world. It returns nil if there is no world with the given name." }, GetWorld = { Params = "WorldName", Return = "{{cWorld|cWorld}}", Notes = "Returns the cWorld object of the given world. It returns nil if there is no world with the given name." },
QueueExecuteConsoleCommand = { Params = "Message", Return = "", Notes = "Queues a console command for execution through the cServer class. The command will be executed in the tick thread The command's output will be sent to console " .. '"stop" and "restart" commands have special handling.' }, QueueExecuteConsoleCommand = { Params = "Message", Return = "", Notes = "Queues a console command for execution through the cServer class. The command will be executed in the tick thread The command's output will be sent to console " .. '"stop" and "restart" commands have special handling.' },
@ -1897,36 +2108,48 @@ Sign entities are saved and loaded from disk when the chunk they reside in is sa
cWindow = cWindow =
{ {
Desc = [[This class is the common ancestor for all window classes used by MCServer. It is inherited by the {{cLuaWindow|cLuaWindow}} class that plugins use for opening custom windows. It is planned to be used for window-related hooks in the future. It implements the basic functionality of any window. Desc = [[
</p> This class is the common ancestor for all window classes used by MCServer. It is inherited by the
<p>Note that one cWindow object can be used for multiple players at the same time, and therefore the slot contents are player-specific (e. g. crafting grid, or player inventory). Thus the GetSlot() and SetSlot() functions need to have the {{cPlayer|cPlayer}} parameter that specifies the player for which the contents are to be queried. {{cLuaWindow|cLuaWindow}} class that plugins use for opening custom windows. It is planned to be
]], used for window-related hooks in the future. It implements the basic functionality of any
window.</p>
<p>
Note that one cWindow object can be used for multiple players at the same time, and therefore the
slot contents are player-specific (e. g. crafting grid, or player inventory). Thus the GetSlot() and
SetSlot() functions need to have the {{cPlayer|cPlayer}} parameter that specifies the player for
whom the contents are to be queried.</p>
<p>
Windows also have numeric properties, these are used to set the progressbars for furnaces or the XP
costs for enchantment tables.
]],
Functions = Functions =
{ {
GetSlot = { Params = "{{cPlayer|Player}}, SlotNumber", Return = "{{cItem}}", Notes = "Returns the item at the specified slot for the specified player. Returns nil and logs to server console on error." },
GetWindowID = { Params = "", Return = "number", Notes = "Returns the ID of the window, as used by the network protocol" }, GetWindowID = { Params = "", Return = "number", Notes = "Returns the ID of the window, as used by the network protocol" },
GetWindowTitle = { Params = "", Return = "string", Notes = "Returns the window title that will be displayed to the player" }, GetWindowTitle = { Params = "", Return = "string", Notes = "Returns the window title that will be displayed to the player" },
GetWindowType = { Params = "", Return = "number", Notes = "Returns the type of the window, one of the constants in the table above" }, GetWindowType = { Params = "", Return = "number", Notes = "Returns the type of the window, one of the constants in the table above" },
IsSlotInPlayerHotbar = { Params = "number", Return = "bool", Notes = "Returns true if the specified slot number is in the player hotbar" }, IsSlotInPlayerHotbar = { Params = "SlotNum", Return = "bool", Notes = "Returns true if the specified slot number is in the player hotbar" },
IsSlotInPlayerInventory = { Params = "number", Return = "bool", Notes = "Returns true if the specified slot number is in the player's main inventory or in the hotbar. Note that this returns false for armor slots!" }, IsSlotInPlayerInventory = { Params = "SlotNum", Return = "bool", Notes = "Returns true if the specified slot number is in the player's main inventory or in the hotbar. Note that this returns false for armor slots!" },
IsSlotInPlayerMainInventory = { Params = "number", Return = "bool", Notes = "Returns true if the specified slot number is in the player's main inventory" }, IsSlotInPlayerMainInventory = { Params = "SlotNum", Return = "bool", Notes = "Returns true if the specified slot number is in the player's main inventory" },
SetSlot = { Params = "{{cItem|cItem}}", Return = "", Notes = "Sets the contents of the specified slot for the specified player. Ignored if the slot number is invalid" }, SetProperty = { Params = "PropertyID, PropartyValue, {{cPlayer|Player}}", Return = "", Notes = "Sends the UpdateWindowProperty (0x69) packet to the specified player; or to all players who are viewing this window if Player is not specified or nil." },
SetSlot = { Params = "{{cPlayer|Player}}, SlotNum, {{cItem|cItem}}", Return = "", Notes = "Sets the contents of the specified slot for the specified player. Ignored if the slot number is invalid" },
SetWindowTitle = { Params = "string", Return = "", Notes = "Sets the window title that will be displayed to the player" }, SetWindowTitle = { Params = "string", Return = "", Notes = "Sets the window title that will be displayed to the player" },
}, },
Constants = Constants =
{ {
Inventory = { Notes = "" }, wtInventory = { Notes = "An inventory window" },
Chest = { Notes = "0" }, wtChest = { Notes = "A {{cChestEntity|chest}} or doublechest window" },
Workbench = { Notes = "1" }, wtWorkbench = { Notes = "A workbench (crafting table) window" },
Furnace = { Notes = "2" }, wtFurnace = { Notes = "A {{cFurnaceEntity|furnace}} window" },
DropSpenser = { Notes = "3" }, wtDropSpenser = { Notes = "A {{cDropperEntity|dropper}} or a {{cDispenserEntity|dispenser}} window" },
Enchantment = { Notes = "4" }, wtEnchantment = { Notes = "An enchantment table window" },
Brewery = { Notes = "5" }, wtBrewery = { Notes = "A brewing stand window" },
NPCTrade = { Notes = "6" }, wtNPCTrade = { Notes = "A villager trade window" },
Beacon = { Notes = "7" }, wtBeacon = { Notes = "A beacon window" },
Anvil = { Notes = "8" }, wtAnvil = { Notes = "An anvil window" },
Hopper = { Notes = "9" }, wtHopper = { Notes = "A {{cHopperEntity|hopper}} window" },
}, },
}, }, -- cWindow
cWorld = cWorld =
{ {
@ -2046,6 +2269,7 @@ Sign entities are saved and loaded from disk when the chunk they reside in is sa
QueueBlockForTick = { Params = "BlockX, BlockY, BlockZ, TicksToWait", Return = "", Notes = "Queues the specified block to be ticked after the specified number of gameticks." }, QueueBlockForTick = { Params = "BlockX, BlockY, BlockZ, TicksToWait", Return = "", Notes = "Queues the specified block to be ticked after the specified number of gameticks." },
QueueSaveAllChunks = { Params = "", Return = "", Notes = "Queues all chunks to be saved in the world storage thread" }, QueueSaveAllChunks = { Params = "", Return = "", Notes = "Queues all chunks to be saved in the world storage thread" },
QueueSetBlock = { Params = "BlockX, BlockY, BlockZ, BlockType, BlockMeta, TickDelay", Return = "", Notes = "Queues the block to be set to the specified blocktype and meta after the specified amount of game ticks. Uses SetBlock() for the actual setting, so simulators are woken up and block entities are handled correctly." }, QueueSetBlock = { Params = "BlockX, BlockY, BlockZ, BlockType, BlockMeta, TickDelay", Return = "", Notes = "Queues the block to be set to the specified blocktype and meta after the specified amount of game ticks. Uses SetBlock() for the actual setting, so simulators are woken up and block entities are handled correctly." },
QueueTask = { Params = "TaskFunction", Return = "", Notes = "Queues the specified function to be executed in the tick thread. This is the primary means of interaction with a cWorld from the WebAdmin page handlers (see {{WebWorldThreads}}). The function signature is <pre class=\"pretty-print lang-lua\">function()</pre>All return values from the function are ignored. Note that this function is actually called *after* the QueueTask() function returns." },
RegenerateChunk = { Params = "ChunkX, ChunkZ", Return = "", Notes = "Queues the specified chunk to be re-generated, overwriting the current data. To queue a chunk for generating only if it doesn't exist, use the GenerateChunk() instead." }, RegenerateChunk = { Params = "ChunkX, ChunkZ", Return = "", Notes = "Queues the specified chunk to be re-generated, overwriting the current data. To queue a chunk for generating only if it doesn't exist, use the GenerateChunk() instead." },
SendBlockTo = { Params = "BlockX, BlockY, BlockZ, {{cPlayer|Player}}", Return = "", Notes = "Sends the block at the specified coords to the specified player's client, as an UpdateBlock packet." }, SendBlockTo = { Params = "BlockX, BlockY, BlockZ, {{cPlayer|Player}}", Return = "", Notes = "Sends the block at the specified coords to the specified player's client, as an UpdateBlock packet." },
SetBlock = { Params = "BlockX, BlockY, BlockZ, BlockType, BlockMeta", Return = "", Notes = "Sets the block at the specified coords, replaces the block entities for the previous block type, creates a new block entity for the new block, if appropriate, and wakes up the simulators. This is the preferred way to set blocks, as opposed to FastSetBlock(), which is only to be used under special circumstances." }, SetBlock = { Params = "BlockX, BlockY, BlockZ, BlockType, BlockMeta", Return = "", Notes = "Sets the block at the specified coords, replaces the block entities for the previous block type, creates a new block entity for the new block, if appropriate, and wakes up the simulators. This is the preferred way to set blocks, as opposed to FastSetBlock(), which is only to be used under special circumstances." },
@ -2136,7 +2360,40 @@ World:ForEachEntity(
]], ]],
}, },
}, -- AdditionalInfo }, -- AdditionalInfo
}, }, -- cWorld
HTTPFormData =
{
Desc = "This class stores data for one form element for a {{HTTPRequest|HTTP request}}.",
Variables =
{
Name = { Type = "string", Notes = "Name of the form element" },
Type = { Type = "string", Notes = "Type of the data (usually empty)" },
Value = { Type = "string", Notes = "Value of the form element. Contains the raw data as sent by the browser." },
},
}, -- HTTPFormData
HTTPRequest =
{
Desc = [[
This class encapsulates all the data that is sent to the WebAdmin through one HTTP request. Plugins
receive this class as a parameter to the function handling the web requests, as registered in the
FIXME: {{cPluginLua}}:AddWebPage().
]],
Constants =
{
FormData = { Notes = "Array-table of {{HTTPFormData}}, contains the values of individual form elements submitted by the client" },
Params = { Notes = "Map-table of parameters given to the request in the URL (?param=value); if a form uses GET method, this is the same as FormData. For each parameter given as \"param=value\", there is an entry in the table with \"param\" as its key and \"value\" as its value." },
PostParams = { Notes = "Map-table of data posted through a FORM - either a GET or POST method. Logically the same as FormData, but in a map-table format (for each parameter given as \"param=value\", there is an entry in the table with \"param\" as its key and \"value\" as its value)." },
},
Variables =
{
Method = { Type = "string", Notes = "The HTTP method used to make the request. Usually GET or POST." },
Path = { Type = "string", Notes = "The Path part of the URL (excluding the parameters)" },
Username = { Type = "string", Notes = "Name of the logged-in user." },
},
}, -- HTTPRequest
TakeDamageInfo = TakeDamageInfo =
{ {
@ -2148,7 +2405,7 @@ World:ForEachEntity(
Constants = Constants =
{ {
}, },
}, }, -- TakeDamageInfo
Vector3d = Vector3d =
{ {
@ -2161,7 +2418,7 @@ World:ForEachEntity(
Constants = Constants =
{ {
}, },
}, }, -- Vector3d
Vector3f = Vector3f =
{ {
@ -2173,7 +2430,7 @@ World:ForEachEntity(
Constants = Constants =
{ {
}, },
}, }, -- Vector3f
Vector3i = Vector3i =
{ {
@ -2185,7 +2442,8 @@ World:ForEachEntity(
Constants = Constants =
{ {
}, },
}, }, -- Vector3i
Globals = Globals =
{ {
Desc = [[These functions are available directly, without a class instance. Any plugin cal call them at any time.]], Desc = [[These functions are available directly, without a class instance. Any plugin cal call them at any time.]],

View File

@ -499,6 +499,7 @@ function ReadDescriptions(a_API)
cls.Functions = DoxyFunctions; cls.Functions = DoxyFunctions;
else -- if (APIDesc.Functions ~= nil) else -- if (APIDesc.Functions ~= nil)
for j, func in ipairs(cls.Functions) do for j, func in ipairs(cls.Functions) do
local FnName = func.DocID or func.Name;
if not(IsFunctionIgnored(cls.Name .. "." .. FnName)) then if not(IsFunctionIgnored(cls.Name .. "." .. FnName)) then
table.insert(cls.UndocumentedFunctions, FnName); table.insert(cls.UndocumentedFunctions, FnName);
end end

View File

@ -6,20 +6,27 @@ CX = 0
CZ = 0 CZ = 0
CURRENT = 0 CURRENT = 0
TOTAL = 0 TOTAL = 0
-- AREA Variables -- AREA Variables
AreaStartX = -10 AreaStartX = -10
AreaStartZ = -10 AreaStartZ = -10
AreaEndX = 10 AreaEndX = 10
AreaEndZ = 10 AreaEndZ = 10
-- RADIAL Variables -- RADIAL Variables
RadialX = 0 RadialX = 0
RadialZ = 0 RadialZ = 0
Radius = 1 Radius = 10
-- WORLD -- WORLD
WORK_WORLD = cRoot:Get():GetDefaultWorld():GetName() WORK_WORLD = cRoot:Get():GetDefaultWorld():GetName()
WW_instance = cRoot:Get():GetDefaultWorld() WW_instance = cRoot:Get():GetDefaultWorld()
WORLDS = {} WORLDS = {}
function Initialize(Plugin) function Initialize(Plugin)
PLUGIN = Plugin PLUGIN = Plugin
@ -36,39 +43,25 @@ function Initialize(Plugin)
LOG("" .. PLUGIN:GetName() .. " v" .. PLUGIN:GetVersion() .. ": NO WORLD found :(") LOG("" .. PLUGIN:GetName() .. " v" .. PLUGIN:GetVersion() .. ": NO WORLD found :(")
end end
PLUGIN.IniFile = cIniFile("ChunkWorx.ini") -- Read the stored values:
if (PLUGIN.IniFile:ReadFile() == false) then local SettingsIni = cIniFile();
PLUGIN.IniFile:HeaderComment("ChunkWorx Save") SettingsIni:ReadFile("ChunkWorx.ini"); -- ignore any read errors
PLUGIN.IniFile:AddKeyName("Area data") AreaStartX = SettingsIni:GetValueSetI("Area data", "StartX", AreaStartX)
PLUGIN.IniFile:SetValueI("Area data", "StartX", AreaStartX) AreaStartZ = SettingsIni:GetValueSetI("Area data", "StartZ", AreaStartZ)
PLUGIN.IniFile:SetValueI("Area data", "StartZ", AreaStartZ) AreaEndX = SettingsIni:GetValueSetI("Area data", "EndX", AreaEndX)
PLUGIN.IniFile:SetValueI("Area data", "EndX", AreaEndX) AreaEndZ = SettingsIni:GetValueSetI("Area data", "EndZ", AreaEndZ)
PLUGIN.IniFile:SetValueI("Area data", "EndZ", AreaEndZ) RadialX = SettingsIni:GetValueSetI("Radial data", "RadialX", RadialX)
PLUGIN.IniFile:AddKeyName("Radial data") RadialZ = SettingsIni:GetValueSetI("Radial data", "RadialZ", RadialZ)
PLUGIN.IniFile:SetValueI("Radial data", "RadialX", RadialX) Radius = SettingsIni:GetValueSetI("Radial data", "Radius", Radius)
PLUGIN.IniFile:SetValueI("Radial data", "RadialZ", RadialZ) SettingsIni:WriteFile("ChunkWorx.ini");
PLUGIN.IniFile:SetValueI("Radial data", "Radius", Radius)
PLUGIN.IniFile:WriteFile()
end
AreaStartX = PLUGIN.IniFile:GetValueI("Area data", "StartX")
AreaStartZ = PLUGIN.IniFile:GetValueI("Area data", "StartZ")
AreaEndX = PLUGIN.IniFile:GetValueI("Area data", "EndX")
AreaEndZ = PLUGIN.IniFile:GetValueI("Area data", "EndZ")
RadialX = PLUGIN.IniFile:GetValueI("Radial data", "RadialX")
RadialZ = PLUGIN.IniFile:GetValueI("Radial data", "RadialZ")
Radius = PLUGIN.IniFile:GetValueI("Radial data", "Radius")
LOG("Initialized " .. PLUGIN:GetName() .. " v" .. PLUGIN:GetVersion()) LOG("Initialized " .. PLUGIN:GetName() .. " v" .. PLUGIN:GetVersion())
--LOG("Test1: " .. math.fmod(1.5, 1)) - return fractional part!
return true return true
end end
function OnDisable()
PLUGIN.IniFile:WriteFile()
LOG(PLUGIN:GetName() .. " v" .. PLUGIN:GetVersion() .. " is shutting down...")
end
function OnTick( DeltaTime ) function OnTick( DeltaTime )
if (GENERATION_STATE == 1 or GENERATION_STATE == 3) then if (GENERATION_STATE == 1 or GENERATION_STATE == 3) then
@ -128,7 +121,7 @@ function OnTick( DeltaTime )
end end
end end
end end
WW_instance:SaveAllChunks() WW_instance:QueueSaveAllChunks()
WW_instance:UnloadUnusedChunks() WW_instance:UnloadUnusedChunks()
end end
end end

View File

@ -1,11 +1,44 @@
-- chunkworx_web.lua
-- WebAdmin-related functions
local function Buttons_Player( Name ) local function Buttons_Player( Name )
return "<form method='POST'><input type='hidden' name='PlayerName' value='"..Name.."'><input type='submit' name='PlayerExact' value='Exact'><input type='submit' name='Player3x3' value='3x3'></form>" return "<form method='POST'><input type='hidden' name='PlayerName' value='"..Name.."'><input type='submit' name='PlayerExact' value='Exact'><input type='submit' name='Player3x3' value='3x3'></form>"
end end
local function Button_World( Name ) local function Button_World( Name )
return "<form method='POST'><input type='hidden' name='WorldName' value='"..Name.."'><input type='submit' name='SelectWorld' value='Select'></form>" return "<form method='POST'><input type='hidden' name='WorldName' value='"..Name.."'><input type='submit' name='SelectWorld' value='Select'></form>"
end end
local function SaveSettings()
local SettingsIni = cIniFile()
SettingsIni:SetValueI("Area data", "StartX", AreaStartX)
SettingsIni:SetValueI("Area data", "StartZ", AreaStartZ)
SettingsIni:SetValueI("Area data", "EndX", AreaEndX)
SettingsIni:SetValueI("Area data", "EndZ", AreaEndZ)
SettingsIni:SetValueI("Radial data", "RadialX", RadialX)
SettingsIni:SetValueI("Radial data", "RadialZ", RadialZ)
SettingsIni:SetValueI("Radial data", "Radius", Radius)
SettingsIni:WriteFile("ChunkWorx.ini")
end
function HandleRequest_Generation( Request ) function HandleRequest_Generation( Request )
local Content = "" local Content = ""
if (Request.PostParams["AGHRRRR"] ~= nil) then if (Request.PostParams["AGHRRRR"] ~= nil) then
@ -69,21 +102,12 @@ function HandleRequest_Generation( Request )
AreaStartZ = tonumber(Request.PostParams["FormAreaStartZ"]) AreaStartZ = tonumber(Request.PostParams["FormAreaStartZ"])
AreaEndX = tonumber(Request.PostParams["FormAreaEndX"]) AreaEndX = tonumber(Request.PostParams["FormAreaEndX"])
AreaEndZ = tonumber(Request.PostParams["FormAreaEndZ"]) AreaEndZ = tonumber(Request.PostParams["FormAreaEndZ"])
SaveSettings();
PLUGIN.IniFile:DeleteValue("Area data", "StartX")
PLUGIN.IniFile:DeleteValue("Area data", "StartZ")
PLUGIN.IniFile:DeleteValue("Area data", "EndX")
PLUGIN.IniFile:DeleteValue("Area data", "EndZ")
PLUGIN.IniFile:SetValueI("Area data", "StartX", AreaStartX)
PLUGIN.IniFile:SetValueI("Area data", "StartZ", AreaStartZ)
PLUGIN.IniFile:SetValueI("Area data", "EndX", AreaEndX)
PLUGIN.IniFile:SetValueI("Area data", "EndZ", AreaEndZ)
if (OPERATION_CODE == 0) then if (OPERATION_CODE == 0) then
GENERATION_STATE = 1 GENERATION_STATE = 1
elseif (OPERATION_CODE == 1) then elseif (OPERATION_CODE == 1) then
GENERATION_STATE = 3 GENERATION_STATE = 3
end end
PLUGIN.IniFile:WriteFile()
Content = ProcessingContent() Content = ProcessingContent()
return Content return Content
end end
@ -93,26 +117,19 @@ function HandleRequest_Generation( Request )
and Request.PostParams["FormRadius"] ~= nil ) then --(Re)Generation valid! and Request.PostParams["FormRadius"] ~= nil ) then --(Re)Generation valid!
-- COMMON (Re)gen -- COMMON (Re)gen
if( Request.PostParams["StartRadial"]) then if( Request.PostParams["StartRadial"]) then
RadialX = tonumber(Request.PostParams["FormRadialX"]) RadialX = tonumber(Request.PostParams["FormRadialX"]) or 0
RadialZ = tonumber(Request.PostParams["FormRadialZ"]) RadialZ = tonumber(Request.PostParams["FormRadialZ"]) or 0
Radius = tonumber(Request.PostParams["FormRadius"]) Radius = tonumber(Request.PostParams["FormRadius"]) or 10
AreaStartX = RadialX - Radius AreaStartX = RadialX - Radius
AreaStartZ = RadialZ - Radius AreaStartZ = RadialZ - Radius
AreaEndX = RadialX + Radius AreaEndX = RadialX + Radius
AreaEndZ = RadialZ + Radius AreaEndZ = RadialZ + Radius
SaveSettings()
PLUGIN.IniFile:DeleteValue("Radial data", "RadialX")
PLUGIN.IniFile:DeleteValue("Radial data", "RadialZ")
PLUGIN.IniFile:DeleteValue("Radial data", "Radius")
PLUGIN.IniFile:SetValueI("Radial data", "RadialX", RadialX)
PLUGIN.IniFile:SetValueI("Radial data", "RadialZ", RadialZ)
PLUGIN.IniFile:SetValueI("Radial data", "Radius", Radius)
if (OPERATION_CODE == 0) then if (OPERATION_CODE == 0) then
GENERATION_STATE = 1 GENERATION_STATE = 1
elseif (OPERATION_CODE == 1) then elseif (OPERATION_CODE == 1) then
GENERATION_STATE = 3 GENERATION_STATE = 3
end end
PLUGIN.IniFile:WriteFile()
Content = ProcessingContent() Content = ProcessingContent()
return Content return Content
end end
@ -214,7 +231,7 @@ function HandleRequest_Generation( Request )
Content = Content .. "</form>" Content = Content .. "</form>"
-- SELECTING RADIAL -- SELECTING RADIAL
Content = Content .. "<h4>Radial: </h4>Center X, Center Z, Raduis (0 to any)" Content = Content .. "<h4>Radial: </h4>Center X, Center Z, Radius"
Content = Content .. "<form method='POST'>" Content = Content .. "<form method='POST'>"
Content = Content .. "<input type='text' name='FormRadialX' value='" .. RadialX .. "'><input type='text' name='FormRadialZ' value='" .. RadialZ .. "'><input type='text' name='FormRadius' value='" .. Radius .. "'>" Content = Content .. "<input type='text' name='FormRadialX' value='" .. RadialX .. "'><input type='text' name='FormRadialZ' value='" .. RadialZ .. "'><input type='text' name='FormRadius' value='" .. Radius .. "'>"
Content = Content .. "<input type='submit' name='StartRadial' value='Start'>" Content = Content .. "<input type='submit' name='StartRadial' value='Start'>"

View File

@ -606,7 +606,7 @@ end
function HandleTestWndCmd(a_Split, a_Player) function HandleTestWndCmd(a_Split, a_Player)
local WindowType = cWindow.Hopper; local WindowType = cWindow.wtHopper;
local WindowSizeX = 5; local WindowSizeX = 5;
local WindowSizeY = 1; local WindowSizeY = 1;
if (#a_Split == 4) then if (#a_Split == 4) then
@ -789,7 +789,7 @@ end
function HandleEnchCmd(a_Split, a_Player) function HandleEnchCmd(a_Split, a_Player)
local Wnd = cLuaWindow(cWindow.Enchantment, 1, 1, "Ench"); local Wnd = cLuaWindow(cWindow.wtEnchantment, 1, 1, "Ench");
a_Player:OpenWindow(Wnd); a_Player:OpenWindow(Wnd);
Wnd:SetProperty(0, 10); Wnd:SetProperty(0, 10);
Wnd:SetProperty(1, 15); Wnd:SetProperty(1, 15);

View File

@ -144,15 +144,20 @@ typedef unsigned char Byte;
enum enum
{ {
PACKET_KEEPALIVE = 0x00, // client-bound packets:
PACKET_LOGIN = 0x01, PACKET_C_KEEPALIVE = 0x00,
PACKET_HANDSHAKE = 0x02, PACKET_C_JOIN_GAME = 0x01,
PACKET_CHAT_MESSAGE = 0x03, PACKET_C_CHAT_MESSAGE = 0x02,
PACKET_TIME_UPDATE = 0x04,
PACKET_ENTITY_EQUIPMENT = 0x05, // server-bound packets:
PACKET_COMPASS = 0x06, PACKET_S_KEEPALIVE = 0x00, // Also the initial handshake, as the very first packet
PACKET_S_CHAT_MESSAGE = 0x01,
PACKET_TIME_UPDATE = 0x03,
PACKET_ENTITY_EQUIPMENT = 0x04,
PACKET_SPAWN_POSITION = 0x05,
PACKET_UPDATE_HEALTH = 0x06,
PACKET_USE_ENTITY = 0x07, PACKET_USE_ENTITY = 0x07,
PACKET_UPDATE_HEALTH = 0x08,
PACKET_PLAYER_ON_GROUND = 0x0a, PACKET_PLAYER_ON_GROUND = 0x0a,
PACKET_PLAYER_POSITION = 0x0b, PACKET_PLAYER_POSITION = 0x0b,
PACKET_PLAYER_LOOK = 0x0c, PACKET_PLAYER_LOOK = 0x0c,
@ -270,7 +275,8 @@ cConnection::cConnection(SOCKET a_ClientSocket, cServer & a_Server) :
m_Nonce(0), m_Nonce(0),
m_ClientBuffer(1024 KiB), m_ClientBuffer(1024 KiB),
m_ServerBuffer(1024 KiB), m_ServerBuffer(1024 KiB),
m_HasClientPinged(false) m_HasClientPinged(false),
m_ProtocolState(-1)
{ {
// Create the Logs subfolder, if not already created: // Create the Logs subfolder, if not already created:
#if defined(_WIN32) #if defined(_WIN32)
@ -279,7 +285,7 @@ cConnection::cConnection(SOCKET a_ClientSocket, cServer & a_Server) :
mkdir("Logs", 0777); mkdir("Logs", 0777);
#endif #endif
Printf(m_LogNameBase, "Logs/Log_%d", (int)time(NULL)); Printf(m_LogNameBase, "Logs/Log_%d_%d", (int)time(NULL), a_ClientSocket);
AString fnam(m_LogNameBase); AString fnam(m_LogNameBase);
fnam.append(".log"); fnam.append(".log");
m_LogFile = fopen(fnam.c_str(), "w"); m_LogFile = fopen(fnam.c_str(), "w");
@ -517,7 +523,7 @@ double cConnection::GetRelativeTime(void)
bool cConnection::SendData(SOCKET a_Socket, const char * a_Data, int a_Size, const char * a_Peer) bool cConnection::SendData(SOCKET a_Socket, const char * a_Data, int a_Size, const char * a_Peer)
{ {
DataLog(a_Data, a_Size, "Sending data to %s", a_Peer); DataLog(a_Data, a_Size, "Sending data to %s, %d bytes", a_Peer, a_Size);
int res = send(a_Socket, a_Data, a_Size, 0); int res = send(a_Socket, a_Data, a_Size, 0);
if (res <= 0) if (res <= 0)
@ -590,38 +596,77 @@ bool cConnection::DecodeClientsPackets(const char * a_Data, int a_Size)
while (m_ClientBuffer.CanReadBytes(1)) while (m_ClientBuffer.CanReadBytes(1))
{ {
unsigned char PacketType; UInt32 PacketLen;
m_ClientBuffer.ReadByte(PacketType); if (
Log("Decoding client's packets, there are now %d bytes in the queue; next packet is 0x%02x", m_ClientBuffer.GetReadableSpace(), PacketType); !m_ClientBuffer.ReadVarInt(PacketLen) ||
switch (PacketType) !m_ClientBuffer.CanReadBytes(PacketLen)
)
{ {
case PACKET_BLOCK_DIG: HANDLE_CLIENT_READ(HandleClientBlockDig); break; // Not a complete packet yet
case PACKET_BLOCK_PLACE: HANDLE_CLIENT_READ(HandleClientBlockPlace); break; break;
case PACKET_CHAT_MESSAGE: HANDLE_CLIENT_READ(HandleClientChatMessage); break; }
case PACKET_CLIENT_STATUSES: HANDLE_CLIENT_READ(HandleClientClientStatuses); break; UInt32 PacketType;
case PACKET_CREATIVE_INVENTORY_ACTION: HANDLE_CLIENT_READ(HandleClientCreativeInventoryAction); break; VERIFY(m_ClientBuffer.ReadVarInt(PacketType));
case PACKET_DISCONNECT: HANDLE_CLIENT_READ(HandleClientDisconnect); break; Log("Decoding client's packets, there are now %d bytes in the queue; next packet is 0x%0x, %u bytes long", m_ClientBuffer.GetReadableSpace(), PacketType, PacketLen);
case PACKET_ENCRYPTION_KEY_RESPONSE: HANDLE_CLIENT_READ(HandleClientEncryptionKeyResponse); break; switch (m_ProtocolState)
case PACKET_ENTITY_ACTION: HANDLE_CLIENT_READ(HandleClientEntityAction); break; {
case PACKET_HANDSHAKE: HANDLE_CLIENT_READ(HandleClientHandshake); break; case -1:
case PACKET_KEEPALIVE: HANDLE_CLIENT_READ(HandleClientKeepAlive); break; {
case PACKET_LOCALE_AND_VIEW: HANDLE_CLIENT_READ(HandleClientLocaleAndView); break; // No initial handshake received yet
case PACKET_PING: HANDLE_CLIENT_READ(HandleClientPing); break; switch (PacketType)
case PACKET_PLAYER_ABILITIES: HANDLE_CLIENT_READ(HandleClientPlayerAbilities); break; {
case PACKET_PLAYER_ANIMATION: HANDLE_CLIENT_READ(HandleClientAnimation); break; case 0: HANDLE_CLIENT_READ(HandleClientHandshake); break;
case PACKET_PLAYER_LOOK: HANDLE_CLIENT_READ(HandleClientPlayerLook); break; }
case PACKET_PLAYER_ON_GROUND: HANDLE_CLIENT_READ(HandleClientPlayerOnGround); break; break;
case PACKET_PLAYER_POSITION: HANDLE_CLIENT_READ(HandleClientPlayerPosition); break; } // case -1
case PACKET_PLAYER_POSITION_LOOK: HANDLE_CLIENT_READ(HandleClientPlayerPositionLook); break;
case PACKET_PLUGIN_MESSAGE: HANDLE_CLIENT_READ(HandleClientPluginMessage); break; case 1:
case PACKET_SLOT_SELECT: HANDLE_CLIENT_READ(HandleClientSlotSelect); break; {
case PACKET_TAB_COMPLETION: HANDLE_CLIENT_READ(HandleClientTabCompletion); break; // Status query
case PACKET_UPDATE_SIGN: HANDLE_CLIENT_READ(HandleClientUpdateSign); break; switch (PacketType)
case PACKET_USE_ENTITY: HANDLE_CLIENT_READ(HandleClientUseEntity); break; {
case PACKET_WINDOW_CLICK: HANDLE_CLIENT_READ(HandleClientWindowClick); break; case 0: HANDLE_CLIENT_READ(HandleClientStatusRequest); break;
case PACKET_WINDOW_CLOSE: HANDLE_CLIENT_READ(HandleClientWindowClose); break; case 1: HANDLE_CLIENT_READ(HandleClientStatusPing); break;
}
break;
}
case 2:
{
// Login / game
switch (PacketType)
{
case PACKET_BLOCK_DIG: HANDLE_CLIENT_READ(HandleClientBlockDig); break;
case PACKET_BLOCK_PLACE: HANDLE_CLIENT_READ(HandleClientBlockPlace); break;
case PACKET_S_CHAT_MESSAGE: HANDLE_CLIENT_READ(HandleClientChatMessage); break;
case PACKET_CLIENT_STATUSES: HANDLE_CLIENT_READ(HandleClientClientStatuses); break;
case PACKET_CREATIVE_INVENTORY_ACTION: HANDLE_CLIENT_READ(HandleClientCreativeInventoryAction); break;
case PACKET_DISCONNECT: HANDLE_CLIENT_READ(HandleClientDisconnect); break;
case PACKET_ENCRYPTION_KEY_RESPONSE: HANDLE_CLIENT_READ(HandleClientEncryptionKeyResponse); break;
case PACKET_ENTITY_ACTION: HANDLE_CLIENT_READ(HandleClientEntityAction); break;
case PACKET_S_KEEPALIVE: HANDLE_CLIENT_READ(HandleClientKeepAlive); break;
case PACKET_LOCALE_AND_VIEW: HANDLE_CLIENT_READ(HandleClientLocaleAndView); break;
case PACKET_PING: HANDLE_CLIENT_READ(HandleClientPing); break;
case PACKET_PLAYER_ABILITIES: HANDLE_CLIENT_READ(HandleClientPlayerAbilities); break;
case PACKET_PLAYER_ANIMATION: HANDLE_CLIENT_READ(HandleClientAnimation); break;
case PACKET_PLAYER_LOOK: HANDLE_CLIENT_READ(HandleClientPlayerLook); break;
case PACKET_PLAYER_ON_GROUND: HANDLE_CLIENT_READ(HandleClientPlayerOnGround); break;
case PACKET_PLAYER_POSITION: HANDLE_CLIENT_READ(HandleClientPlayerPosition); break;
case PACKET_PLAYER_POSITION_LOOK: HANDLE_CLIENT_READ(HandleClientPlayerPositionLook); break;
case PACKET_PLUGIN_MESSAGE: HANDLE_CLIENT_READ(HandleClientPluginMessage); break;
case PACKET_SLOT_SELECT: HANDLE_CLIENT_READ(HandleClientSlotSelect); break;
case PACKET_TAB_COMPLETION: HANDLE_CLIENT_READ(HandleClientTabCompletion); break;
case PACKET_UPDATE_SIGN: HANDLE_CLIENT_READ(HandleClientUpdateSign); break;
case PACKET_USE_ENTITY: HANDLE_CLIENT_READ(HandleClientUseEntity); break;
case PACKET_WINDOW_CLICK: HANDLE_CLIENT_READ(HandleClientWindowClick); break;
case PACKET_WINDOW_CLOSE: HANDLE_CLIENT_READ(HandleClientWindowClose); break;
}
break;
} // case 2
default: default:
{ {
// TODO: Move this elsewhere
if (m_ClientState == csEncryptedUnderstood) if (m_ClientState == csEncryptedUnderstood)
{ {
Log("****************** Unknown packet 0x%02x from the client while encrypted; continuing to relay blind only", PacketType); Log("****************** Unknown packet 0x%02x from the client while encrypted; continuing to relay blind only", PacketType);
@ -646,10 +691,10 @@ bool cConnection::DecodeClientsPackets(const char * a_Data, int a_Size)
Log("Unknown packet 0x%02x from the client while unencrypted; aborting connection", PacketType); Log("Unknown packet 0x%02x from the client while unencrypted; aborting connection", PacketType);
return false; return false;
} }
} } // default
} // switch (PacketType) } // switch (m_ProtocolState)
m_ClientBuffer.CommitRead(); m_ClientBuffer.CommitRead();
} // while (CanReadBytes(1)) } // while (true)
return true; return true;
} }
@ -673,66 +718,102 @@ bool cConnection::DecodeServersPackets(const char * a_Data, int a_Size)
// Client hasn't finished encryption handshake yet, don't send them any data yet // Client hasn't finished encryption handshake yet, don't send them any data yet
} }
while (m_ServerBuffer.CanReadBytes(1)) while (true)
{ {
unsigned char PacketType; UInt32 PacketLen;
m_ServerBuffer.ReadByte(PacketType); if (
Log("Decoding server's packets, there are now %d bytes in the queue; next packet is 0x%02x", m_ServerBuffer.GetReadableSpace(), PacketType); !m_ServerBuffer.ReadVarInt(PacketLen) ||
LogFlush(); !m_ServerBuffer.CanReadBytes(PacketLen)
switch (PacketType) )
{ {
case PACKET_ATTACH_ENTITY: HANDLE_SERVER_READ(HandleServerAttachEntity); break; // Not a complete packet yet
case PACKET_BLOCK_ACTION: HANDLE_SERVER_READ(HandleServerBlockAction); break; break;
case PACKET_BLOCK_CHANGE: HANDLE_SERVER_READ(HandleServerBlockChange); break; }
case PACKET_CHANGE_GAME_STATE: HANDLE_SERVER_READ(HandleServerChangeGameState); break; UInt32 PacketType;
case PACKET_CHAT_MESSAGE: HANDLE_SERVER_READ(HandleServerChatMessage); break; VERIFY(m_ServerBuffer.ReadVarInt(PacketType));
case PACKET_COLLECT_PICKUP: HANDLE_SERVER_READ(HandleServerCollectPickup); break; Log("Decoding server's packets, there are now %d bytes in the queue; next packet is 0x%0x, %u bytes long", m_ServerBuffer.GetReadableSpace(), PacketType, PacketLen);
case PACKET_COMPASS: HANDLE_SERVER_READ(HandleServerCompass); break; LogFlush();
case PACKET_DESTROY_ENTITIES: HANDLE_SERVER_READ(HandleServerDestroyEntities); break; switch (m_ProtocolState)
case PACKET_ENCRYPTION_KEY_REQUEST: HANDLE_SERVER_READ(HandleServerEncryptionKeyRequest); break; {
case PACKET_ENCRYPTION_KEY_RESPONSE: HANDLE_SERVER_READ(HandleServerEncryptionKeyResponse); break; case -1:
case PACKET_ENTITY: HANDLE_SERVER_READ(HandleServerEntity); break; {
case PACKET_ENTITY_EQUIPMENT: HANDLE_SERVER_READ(HandleServerEntityEquipment); break; Log("Receiving data from the server without an initial handshake message!");
case PACKET_ENTITY_HEAD_LOOK: HANDLE_SERVER_READ(HandleServerEntityHeadLook); break; break;
case PACKET_ENTITY_LOOK: HANDLE_SERVER_READ(HandleServerEntityLook); break; }
case PACKET_ENTITY_METADATA: HANDLE_SERVER_READ(HandleServerEntityMetadata); break;
case PACKET_ENTITY_PROPERTIES: HANDLE_SERVER_READ(HandleServerEntityProperties); break; case 1:
case PACKET_ENTITY_RELATIVE_MOVE: HANDLE_SERVER_READ(HandleServerEntityRelativeMove); break; {
case PACKET_ENTITY_RELATIVE_MOVE_LOOK: HANDLE_SERVER_READ(HandleServerEntityRelativeMoveLook); break; // Status query:
case PACKET_ENTITY_STATUS: HANDLE_SERVER_READ(HandleServerEntityStatus); break; switch (PacketType)
case PACKET_ENTITY_TELEPORT: HANDLE_SERVER_READ(HandleServerEntityTeleport); break; {
case PACKET_ENTITY_VELOCITY: HANDLE_SERVER_READ(HandleServerEntityVelocity); break; case 0: HANDLE_SERVER_READ(HandleServerStatusResponse); break;
case PACKET_EXPLOSION: HANDLE_SERVER_READ(HandleServerExplosion); break; case 1: HANDLE_SERVER_READ(HandleServerStatusPing); break;
case PACKET_INCREMENT_STATISTIC: HANDLE_SERVER_READ(HandleServerIncrementStatistic); break; }
case PACKET_KEEPALIVE: HANDLE_SERVER_READ(HandleServerKeepAlive); break; break;
case PACKET_KICK: HANDLE_SERVER_READ(HandleServerKick); break; }
case PACKET_LOGIN: HANDLE_SERVER_READ(HandleServerLogin); break;
case PACKET_MAP_CHUNK: HANDLE_SERVER_READ(HandleServerMapChunk); break; case 2:
case PACKET_MAP_CHUNK_BULK: HANDLE_SERVER_READ(HandleServerMapChunkBulk); break; {
case PACKET_MULTI_BLOCK_CHANGE: HANDLE_SERVER_READ(HandleServerMultiBlockChange); break; // Login / game:
case PACKET_NAMED_SOUND_EFFECT: HANDLE_SERVER_READ(HandleServerNamedSoundEffect); break; switch (PacketType)
case PACKET_PLAYER_ABILITIES: HANDLE_SERVER_READ(HandleServerPlayerAbilities); break; {
case PACKET_PLAYER_ANIMATION: HANDLE_SERVER_READ(HandleServerPlayerAnimation); break; case PACKET_ATTACH_ENTITY: HANDLE_SERVER_READ(HandleServerAttachEntity); break;
case PACKET_PLAYER_LIST_ITEM: HANDLE_SERVER_READ(HandleServerPlayerListItem); break; case PACKET_BLOCK_ACTION: HANDLE_SERVER_READ(HandleServerBlockAction); break;
case PACKET_PLAYER_POSITION_LOOK: HANDLE_SERVER_READ(HandleServerPlayerPositionLook); break; case PACKET_BLOCK_CHANGE: HANDLE_SERVER_READ(HandleServerBlockChange); break;
case PACKET_PLUGIN_MESSAGE: HANDLE_SERVER_READ(HandleServerPluginMessage); break; case PACKET_CHANGE_GAME_STATE: HANDLE_SERVER_READ(HandleServerChangeGameState); break;
case PACKET_SET_EXPERIENCE: HANDLE_SERVER_READ(HandleServerSetExperience); break; case PACKET_C_CHAT_MESSAGE: HANDLE_SERVER_READ(HandleServerChatMessage); break;
case PACKET_SET_SLOT: HANDLE_SERVER_READ(HandleServerSetSlot); break; case PACKET_COLLECT_PICKUP: HANDLE_SERVER_READ(HandleServerCollectPickup); break;
case PACKET_SLOT_SELECT: HANDLE_SERVER_READ(HandleServerSlotSelect); break; case PACKET_DESTROY_ENTITIES: HANDLE_SERVER_READ(HandleServerDestroyEntities); break;
case PACKET_SOUND_EFFECT: HANDLE_SERVER_READ(HandleServerSoundEffect); break; case PACKET_ENCRYPTION_KEY_REQUEST: HANDLE_SERVER_READ(HandleServerEncryptionKeyRequest); break;
case PACKET_SPAWN_MOB: HANDLE_SERVER_READ(HandleServerSpawnMob); break; case PACKET_ENCRYPTION_KEY_RESPONSE: HANDLE_SERVER_READ(HandleServerEncryptionKeyResponse); break;
case PACKET_SPAWN_NAMED_ENTITY: HANDLE_SERVER_READ(HandleServerSpawnNamedEntity); break; case PACKET_ENTITY: HANDLE_SERVER_READ(HandleServerEntity); break;
case PACKET_SPAWN_OBJECT_VEHICLE: HANDLE_SERVER_READ(HandleServerSpawnObjectVehicle); break; case PACKET_ENTITY_EQUIPMENT: HANDLE_SERVER_READ(HandleServerEntityEquipment); break;
case PACKET_SPAWN_PAINTING: HANDLE_SERVER_READ(HandleServerSpawnPainting); break; case PACKET_ENTITY_HEAD_LOOK: HANDLE_SERVER_READ(HandleServerEntityHeadLook); break;
case PACKET_SPAWN_PICKUP: HANDLE_SERVER_READ(HandleServerSpawnPickup); break; case PACKET_ENTITY_LOOK: HANDLE_SERVER_READ(HandleServerEntityLook); break;
case PACKET_TAB_COMPLETION: HANDLE_SERVER_READ(HandleServerTabCompletion); break; case PACKET_ENTITY_METADATA: HANDLE_SERVER_READ(HandleServerEntityMetadata); break;
case PACKET_TIME_UPDATE: HANDLE_SERVER_READ(HandleServerTimeUpdate); break; case PACKET_ENTITY_PROPERTIES: HANDLE_SERVER_READ(HandleServerEntityProperties); break;
case PACKET_UPDATE_HEALTH: HANDLE_SERVER_READ(HandleServerUpdateHealth); break; case PACKET_ENTITY_RELATIVE_MOVE: HANDLE_SERVER_READ(HandleServerEntityRelativeMove); break;
case PACKET_UPDATE_SIGN: HANDLE_SERVER_READ(HandleServerUpdateSign); break; case PACKET_ENTITY_RELATIVE_MOVE_LOOK: HANDLE_SERVER_READ(HandleServerEntityRelativeMoveLook); break;
case PACKET_UPDATE_TILE_ENTITY: HANDLE_SERVER_READ(HandleServerUpdateTileEntity); break; case PACKET_ENTITY_STATUS: HANDLE_SERVER_READ(HandleServerEntityStatus); break;
case PACKET_WINDOW_CLOSE: HANDLE_SERVER_READ(HandleServerWindowClose); break; case PACKET_ENTITY_TELEPORT: HANDLE_SERVER_READ(HandleServerEntityTeleport); break;
case PACKET_WINDOW_CONTENTS: HANDLE_SERVER_READ(HandleServerWindowContents); break; case PACKET_ENTITY_VELOCITY: HANDLE_SERVER_READ(HandleServerEntityVelocity); break;
case PACKET_WINDOW_OPEN: HANDLE_SERVER_READ(HandleServerWindowOpen); break; case PACKET_EXPLOSION: HANDLE_SERVER_READ(HandleServerExplosion); break;
case PACKET_INCREMENT_STATISTIC: HANDLE_SERVER_READ(HandleServerIncrementStatistic); break;
case PACKET_C_JOIN_GAME: HANDLE_SERVER_READ(HandleServerLogin); break;
case PACKET_C_KEEPALIVE: HANDLE_SERVER_READ(HandleServerKeepAlive); break;
case PACKET_KICK: HANDLE_SERVER_READ(HandleServerKick); break;
case PACKET_MAP_CHUNK: HANDLE_SERVER_READ(HandleServerMapChunk); break;
case PACKET_MAP_CHUNK_BULK: HANDLE_SERVER_READ(HandleServerMapChunkBulk); break;
case PACKET_MULTI_BLOCK_CHANGE: HANDLE_SERVER_READ(HandleServerMultiBlockChange); break;
case PACKET_NAMED_SOUND_EFFECT: HANDLE_SERVER_READ(HandleServerNamedSoundEffect); break;
case PACKET_PLAYER_ABILITIES: HANDLE_SERVER_READ(HandleServerPlayerAbilities); break;
case PACKET_PLAYER_ANIMATION: HANDLE_SERVER_READ(HandleServerPlayerAnimation); break;
case PACKET_PLAYER_LIST_ITEM: HANDLE_SERVER_READ(HandleServerPlayerListItem); break;
case PACKET_PLAYER_POSITION_LOOK: HANDLE_SERVER_READ(HandleServerPlayerPositionLook); break;
case PACKET_PLUGIN_MESSAGE: HANDLE_SERVER_READ(HandleServerPluginMessage); break;
case PACKET_SET_EXPERIENCE: HANDLE_SERVER_READ(HandleServerSetExperience); break;
case PACKET_SET_SLOT: HANDLE_SERVER_READ(HandleServerSetSlot); break;
case PACKET_SLOT_SELECT: HANDLE_SERVER_READ(HandleServerSlotSelect); break;
case PACKET_SOUND_EFFECT: HANDLE_SERVER_READ(HandleServerSoundEffect); break;
case PACKET_SPAWN_MOB: HANDLE_SERVER_READ(HandleServerSpawnMob); break;
case PACKET_SPAWN_NAMED_ENTITY: HANDLE_SERVER_READ(HandleServerSpawnNamedEntity); break;
case PACKET_SPAWN_OBJECT_VEHICLE: HANDLE_SERVER_READ(HandleServerSpawnObjectVehicle); break;
case PACKET_SPAWN_PAINTING: HANDLE_SERVER_READ(HandleServerSpawnPainting); break;
case PACKET_SPAWN_PICKUP: HANDLE_SERVER_READ(HandleServerSpawnPickup); break;
case PACKET_SPAWN_POSITION: HANDLE_SERVER_READ(HandleServerCompass); break;
case PACKET_TAB_COMPLETION: HANDLE_SERVER_READ(HandleServerTabCompletion); break;
case PACKET_TIME_UPDATE: HANDLE_SERVER_READ(HandleServerTimeUpdate); break;
case PACKET_UPDATE_HEALTH: HANDLE_SERVER_READ(HandleServerUpdateHealth); break;
case PACKET_UPDATE_SIGN: HANDLE_SERVER_READ(HandleServerUpdateSign); break;
case PACKET_UPDATE_TILE_ENTITY: HANDLE_SERVER_READ(HandleServerUpdateTileEntity); break;
case PACKET_WINDOW_CLOSE: HANDLE_SERVER_READ(HandleServerWindowClose); break;
case PACKET_WINDOW_CONTENTS: HANDLE_SERVER_READ(HandleServerWindowContents); break;
case PACKET_WINDOW_OPEN: HANDLE_SERVER_READ(HandleServerWindowOpen); break;
} // switch (PacketType)
break;
} // case 2
// TODO: Move this elsewhere
default: default:
{ {
if (m_ServerState == csEncryptedUnderstood) if (m_ServerState == csEncryptedUnderstood)
@ -760,7 +841,8 @@ bool cConnection::DecodeServersPackets(const char * a_Data, int a_Size)
return false; return false;
} }
} }
} // switch (PacketType) } // switch (m_ProtocolState)
m_ServerBuffer.CommitRead(); m_ServerBuffer.CommitRead();
} // while (CanReadBytes(1)) } // while (CanReadBytes(1))
return true; return true;
@ -937,27 +1019,33 @@ bool cConnection::HandleClientEntityAction(void)
bool cConnection::HandleClientHandshake(void) bool cConnection::HandleClientHandshake(void)
{ {
// Read the packet from the client: // Read the packet from the client:
HANDLE_CLIENT_PACKET_READ(ReadByte, Byte, ProtocolVersion); HANDLE_CLIENT_PACKET_READ(ReadVarInt, UInt32, ProtocolVersion);
HANDLE_CLIENT_PACKET_READ(ReadBEUTF16String16, AString, Username); HANDLE_CLIENT_PACKET_READ(ReadVarUTF8String, AString, ServerHost);
HANDLE_CLIENT_PACKET_READ(ReadBEUTF16String16, AString, ServerHost); HANDLE_CLIENT_PACKET_READ(ReadBEShort, short, ServerPort);
HANDLE_CLIENT_PACKET_READ(ReadBEInt, int, ServerPort); HANDLE_CLIENT_PACKET_READ(ReadVarInt, UInt32, NextState);
m_ClientBuffer.CommitRead(); m_ClientBuffer.CommitRead();
Log("Received a PACKET_HANDSHAKE from the client:"); Log("Received an initial handshake packet from the client:");
Log(" ProtocolVersion = %d", ProtocolVersion); Log(" ProtocolVersion = %u", ProtocolVersion);
Log(" Username = \"%s\"", Username.c_str());
Log(" ServerHost = \"%s\"", ServerHost.c_str()); Log(" ServerHost = \"%s\"", ServerHost.c_str());
Log(" ServerPort = %d", ServerPort); Log(" ServerPort = %d", ServerPort);
Log(" NextState = %u", NextState);
// Send the same packet to the server, but with our port: // Send the same packet to the server, but with our port:
cByteBuffer Packet(512);
Packet.WriteVarInt(0); // Packet type - initial handshake
Packet.WriteVarInt(ProtocolVersion);
Packet.WriteVarUTF8String(ServerHost);
Packet.WriteBEShort(m_Server.GetConnectPort());
Packet.WriteVarInt(NextState);
AString Pkt;
Packet.ReadAll(Pkt);
cByteBuffer ToServer(512); cByteBuffer ToServer(512);
ToServer.WriteByte (PACKET_HANDSHAKE); ToServer.WriteVarUTF8String(Pkt);
ToServer.WriteByte (ProtocolVersion);
ToServer.WriteBEUTF16String16(Username);
ToServer.WriteBEUTF16String16(ServerHost);
ToServer.WriteBEInt (m_Server.GetConnectPort());
SERVERSEND(ToServer); SERVERSEND(ToServer);
m_ProtocolState = (int)NextState;
return true; return true;
} }
@ -1124,6 +1212,30 @@ bool cConnection::HandleClientSlotSelect(void)
bool cConnection::HandleClientStatusPing(void)
{
HANDLE_CLIENT_PACKET_READ(ReadBEInt64, Int64, Time);
Log("Received the status ping packet from the client:");
Log(" Time = %lld", Time);
COPY_TO_SERVER();
return true;
}
bool cConnection::HandleClientStatusRequest(void)
{
Log("Received the status request packet from the client");
COPY_TO_SERVER();
return true;
}
bool cConnection::HandleClientTabCompletion(void) bool cConnection::HandleClientTabCompletion(void)
{ {
HANDLE_CLIENT_PACKET_READ(ReadBEUTF16String16, AString, Query); HANDLE_CLIENT_PACKET_READ(ReadBEUTF16String16, AString, Query);
@ -2267,6 +2379,46 @@ bool cConnection::HandleServerSpawnPickup(void)
bool cConnection::HandleServerStatusPing(void)
{
HANDLE_SERVER_PACKET_READ(ReadBEInt64, Int64, Time);
Log("Received server's ping response:");
Log(" Time = %lld", Time);
COPY_TO_CLIENT();
return true;
}
bool cConnection::HandleServerStatusResponse(void)
{
HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, Response);
Log("Received server's status response:");
Log(" Response: %s", Response.c_str());
// Modify the response to show that it's being proto-proxied:
size_t idx = Response.find("\"description\":\"");
if (idx != AString::npos)
{
Response.assign(Response.substr(0, idx + 15) + "ProtoProxy: " + Response.substr(idx + 15));
}
cByteBuffer Packet(1000);
Packet.WriteVarInt(0); // Packet type - status response
Packet.WriteVarUTF8String(Response);
AString Pkt;
Packet.ReadAll(Pkt);
cByteBuffer ToClient(1000);
ToClient.WriteVarUTF8String(Pkt);
CLIENTSEND(ToClient);
return true;
}
bool cConnection::HandleServerTabCompletion(void) bool cConnection::HandleServerTabCompletion(void)
{ {
HANDLE_SERVER_PACKET_READ(ReadBEUTF16String16, AString, Results); HANDLE_SERVER_PACKET_READ(ReadBEUTF16String16, AString, Results);

View File

@ -79,6 +79,9 @@ protected:
/// Set to true when PACKET_PING is received from the client; will cause special parsing for server kick /// Set to true when PACKET_PING is received from the client; will cause special parsing for server kick
bool m_HasClientPinged; bool m_HasClientPinged;
/// State the protocol is in (as defined by the initial handshake), -1 if no initial handshake received yet
int m_ProtocolState;
bool ConnectToServer(void); bool ConnectToServer(void);
@ -130,6 +133,8 @@ protected:
bool HandleClientPlayerPositionLook(void); bool HandleClientPlayerPositionLook(void);
bool HandleClientPluginMessage(void); bool HandleClientPluginMessage(void);
bool HandleClientSlotSelect(void); bool HandleClientSlotSelect(void);
bool HandleClientStatusPing(void);
bool HandleClientStatusRequest(void);
bool HandleClientTabCompletion(void); bool HandleClientTabCompletion(void);
bool HandleClientUpdateSign(void); bool HandleClientUpdateSign(void);
bool HandleClientUseEntity(void); bool HandleClientUseEntity(void);
@ -181,6 +186,8 @@ protected:
bool HandleServerSpawnObjectVehicle(void); bool HandleServerSpawnObjectVehicle(void);
bool HandleServerSpawnPainting(void); bool HandleServerSpawnPainting(void);
bool HandleServerSpawnPickup(void); bool HandleServerSpawnPickup(void);
bool HandleServerStatusPing(void);
bool HandleServerStatusResponse(void);
bool HandleServerTabCompletion(void); bool HandleServerTabCompletion(void);
bool HandleServerTimeUpdate(void); bool HandleServerTimeUpdate(void);
bool HandleServerUpdateHealth(void); bool HandleServerUpdateHealth(void);

View File

@ -70,6 +70,10 @@ typedef long long Int64;
typedef int Int32; typedef int Int32;
typedef short Int16; typedef short Int16;
typedef unsigned long long UInt64;
typedef unsigned int UInt32;
typedef unsigned short UInt16;

View File

@ -42,34 +42,33 @@ using namespace std;
cIniFile::cIniFile(const string & a_Path) : cIniFile::cIniFile(void) :
m_IsCaseInsensitive(true) m_IsCaseInsensitive(true)
{ {
Path(a_Path);
} }
bool cIniFile::ReadFile(bool a_AllowExampleRedirect) bool cIniFile::ReadFile(const AString & a_FileName, bool a_AllowExampleRedirect)
{ {
// Normally you would use ifstream, but the SGI CC compiler has // Normally you would use ifstream, but the SGI CC compiler has
// a few bugs with ifstream. So ... fstream used. // a few bugs with ifstream. So ... fstream used.
fstream f; fstream f;
string line; AString line;
string keyname, valuename, value; AString keyname, valuename, value;
string::size_type pLeft, pRight; AString::size_type pLeft, pRight;
bool IsFromExampleRedirect = false; bool IsFromExampleRedirect = false;
f.open((FILE_IO_PREFIX + m_Path).c_str(), ios::in); f.open((FILE_IO_PREFIX + a_FileName).c_str(), ios::in);
if (f.fail()) if (f.fail())
{ {
f.clear(); f.clear();
if (a_AllowExampleRedirect) if (a_AllowExampleRedirect)
{ {
// Retry with the .example.ini file instead of .ini: // Retry with the .example.ini file instead of .ini:
string ExPath(m_Path.substr(0, m_Path.length() - 4)); AString ExPath(a_FileName.substr(0, a_FileName.length() - 4));
ExPath.append(".example.ini"); ExPath.append(".example.ini");
f.open((FILE_IO_PREFIX + ExPath).c_str(), ios::in); f.open((FILE_IO_PREFIX + ExPath).c_str(), ios::in);
if (f.fail()) if (f.fail())
@ -91,7 +90,7 @@ bool cIniFile::ReadFile(bool a_AllowExampleRedirect)
// Note that the '\r' will be written to INI files from // Note that the '\r' will be written to INI files from
// Unix so that the created INI file can be read under Win32 // Unix so that the created INI file can be read under Win32
// without change. // without change.
unsigned int lineLength = line.length(); size_t lineLength = line.length();
if (lineLength == 0) if (lineLength == 0)
{ {
continue; continue;
@ -114,7 +113,7 @@ bool cIniFile::ReadFile(bool a_AllowExampleRedirect)
f.close(); f.close();
return false; return false;
} }
if ((pLeft = line.find_first_of(";#[=")) == string::npos) if ((pLeft = line.find_first_of(";#[=")) == AString::npos)
{ {
continue; continue;
} }
@ -124,7 +123,7 @@ bool cIniFile::ReadFile(bool a_AllowExampleRedirect)
case '[': case '[':
{ {
if ( if (
((pRight = line.find_last_of("]")) != string::npos) && ((pRight = line.find_last_of("]")) != AString::npos) &&
(pRight > pLeft) (pRight > pLeft)
) )
{ {
@ -147,11 +146,11 @@ bool cIniFile::ReadFile(bool a_AllowExampleRedirect)
{ {
if (names.size() == 0) if (names.size() == 0)
{ {
HeaderComment(line.substr(pLeft + 1)); AddHeaderComment(line.substr(pLeft + 1));
} }
else else
{ {
KeyComment(keyname, line.substr(pLeft + 1)); AddKeyComment(keyname, line.substr(pLeft + 1));
} }
break; break;
} }
@ -166,7 +165,7 @@ bool cIniFile::ReadFile(bool a_AllowExampleRedirect)
if (IsFromExampleRedirect) if (IsFromExampleRedirect)
{ {
WriteFile(); WriteFile(FILE_IO_PREFIX + a_FileName);
} }
return true; return true;
} }
@ -175,42 +174,42 @@ bool cIniFile::ReadFile(bool a_AllowExampleRedirect)
bool cIniFile::WriteFile(void) const bool cIniFile::WriteFile(const AString & a_FileName) const
{ {
unsigned commentID, keyID, valueID;
// Normally you would use ofstream, but the SGI CC compiler has // Normally you would use ofstream, but the SGI CC compiler has
// a few bugs with ofstream. So ... fstream used. // a few bugs with ofstream. So ... fstream used.
fstream f; fstream f;
f.open((FILE_IO_PREFIX + m_Path).c_str(), ios::out); f.open((FILE_IO_PREFIX + a_FileName).c_str(), ios::out);
if (f.fail()) if (f.fail())
{ {
return false; return false;
} }
// Write header comments. // Write header comments.
for (commentID = 0; commentID < comments.size(); ++commentID) size_t NumComments = comments.size();
for (size_t commentID = 0; commentID < NumComments; ++commentID)
{ {
f << ';' << comments[commentID] << iniEOL; f << ';' << comments[commentID] << iniEOL;
} }
if (comments.size()) if (NumComments > 0)
{ {
f << iniEOL; f << iniEOL;
} }
// Write keys and values. // Write keys and values.
for (keyID = 0; keyID < keys.size(); ++keyID) for (size_t keyID = 0; keyID < keys.size(); ++keyID)
{ {
f << '[' << names[keyID] << ']' << iniEOL; f << '[' << names[keyID] << ']' << iniEOL;
// Comments. // Comments.
for (commentID = 0; commentID < keys[keyID].comments.size(); ++commentID) for (size_t commentID = 0; commentID < keys[keyID].comments.size(); ++commentID)
{ {
f << ';' << keys[keyID].comments[commentID] << iniEOL; f << ';' << keys[keyID].comments[commentID] << iniEOL;
} }
// Values. // Values.
for (valueID = 0; valueID < keys[keyID].names.size(); ++valueID) for (size_t valueID = 0; valueID < keys[keyID].names.size(); ++valueID)
{ {
f << keys[keyID].names[valueID] << '=' << keys[keyID].values[valueID] << iniEOL; f << keys[keyID].names[valueID] << '=' << keys[keyID].values[valueID] << iniEOL;
} }
@ -225,14 +224,14 @@ bool cIniFile::WriteFile(void) const
long cIniFile::FindKey(const string & a_KeyName) const int cIniFile::FindKey(const AString & a_KeyName) const
{ {
string CaseKeyName = CheckCase(a_KeyName); AString CaseKeyName = CheckCase(a_KeyName);
for (unsigned keyID = 0; keyID < names.size(); ++keyID) for (size_t keyID = 0; keyID < names.size(); ++keyID)
{ {
if (CheckCase(names[keyID]) == CaseKeyName) if (CheckCase(names[keyID]) == CaseKeyName)
{ {
return long(keyID); return keyID;
} }
} }
return noID; return noID;
@ -242,19 +241,19 @@ long cIniFile::FindKey(const string & a_KeyName) const
long cIniFile::FindValue(unsigned const keyID, const string & a_ValueName) const int cIniFile::FindValue(const int keyID, const AString & a_ValueName) const
{ {
if (!keys.size() || (keyID >= keys.size())) if (!keys.size() || (keyID >= (int)keys.size()))
{ {
return noID; return noID;
} }
string CaseValueName = CheckCase(a_ValueName); AString CaseValueName = CheckCase(a_ValueName);
for (unsigned valueID = 0; valueID < keys[keyID].names.size(); ++valueID) for (size_t valueID = 0; valueID < keys[keyID].names.size(); ++valueID)
{ {
if (CheckCase(keys[keyID].names[valueID]) == CaseValueName) if (CheckCase(keys[keyID].names[valueID]) == CaseValueName)
{ {
return long(valueID); return int(valueID);
} }
} }
return noID; return noID;
@ -264,7 +263,7 @@ long cIniFile::FindValue(unsigned const keyID, const string & a_ValueName) const
unsigned cIniFile::AddKeyName(const string & keyname) int cIniFile::AddKeyName(const AString & keyname)
{ {
names.resize(names.size() + 1, keyname); names.resize(names.size() + 1, keyname);
keys.resize(keys.size() + 1); keys.resize(keys.size() + 1);
@ -275,9 +274,9 @@ unsigned cIniFile::AddKeyName(const string & keyname)
string cIniFile::KeyName(unsigned const keyID) const AString cIniFile::GetKeyName(const int keyID) const
{ {
if (keyID < names.size()) if (keyID < (int)names.size())
{ {
return names[keyID]; return names[keyID];
} }
@ -291,11 +290,11 @@ string cIniFile::KeyName(unsigned const keyID) const
unsigned cIniFile::NumValues(unsigned const keyID) int cIniFile::GetNumValues(const int keyID) const
{ {
if (keyID < keys.size()) if (keyID < (int)keys.size())
{ {
return keys[keyID].names.size(); return (int)keys[keyID].names.size();
} }
return 0; return 0;
} }
@ -304,23 +303,23 @@ unsigned cIniFile::NumValues(unsigned const keyID)
unsigned cIniFile::NumValues(const string & keyname) int cIniFile::GetNumValues(const AString & keyname) const
{ {
long keyID = FindKey(keyname); int keyID = FindKey(keyname);
if (keyID == noID) if (keyID == noID)
{ {
return 0; return 0;
} }
return keys[keyID].names.size(); return (int)keys[keyID].names.size();
} }
string cIniFile::ValueName(unsigned const keyID, unsigned const valueID) const AString cIniFile::GetValueName(const int keyID, const int valueID) const
{ {
if (keyID < keys.size() && valueID < keys[keyID].names.size()) if ((keyID < (int)keys.size()) && (valueID < (int)keys[keyID].names.size()))
{ {
return keys[keyID].names[valueID]; return keys[keyID].names[valueID];
} }
@ -331,23 +330,23 @@ string cIniFile::ValueName(unsigned const keyID, unsigned const valueID) const
string cIniFile::ValueName(const string & keyname, unsigned const valueID) const AString cIniFile::GetValueName(const AString & keyname, const int valueID) const
{ {
long keyID = FindKey(keyname); int keyID = FindKey(keyname);
if (keyID == noID) if (keyID == noID)
{ {
return ""; return "";
} }
return ValueName(keyID, valueID); return GetValueName(keyID, valueID);
} }
bool cIniFile::SetValue(unsigned const keyID, unsigned const valueID, const string & value) bool cIniFile::SetValue(const int keyID, const int valueID, const AString & value)
{ {
if ((keyID < keys.size()) && (valueID < keys[keyID].names.size())) if ((keyID < (int)keys.size()) && (valueID < (int)keys[keyID].names.size()))
{ {
keys[keyID].values[valueID] = value; keys[keyID].values[valueID] = value;
} }
@ -358,14 +357,14 @@ bool cIniFile::SetValue(unsigned const keyID, unsigned const valueID, const stri
bool cIniFile::SetValue(const string & keyname, const string & valuename, const string & value, bool const create) bool cIniFile::SetValue(const AString & keyname, const AString & valuename, const AString & value, bool const create)
{ {
long keyID = FindKey(keyname); int keyID = FindKey(keyname);
if (keyID == noID) if (keyID == noID)
{ {
if (create) if (create)
{ {
keyID = long(AddKeyName(keyname)); keyID = int(AddKeyName(keyname));
} }
else else
{ {
@ -373,7 +372,7 @@ bool cIniFile::SetValue(const string & keyname, const string & valuename, const
} }
} }
long valueID = FindValue(unsigned(keyID), valuename); int valueID = FindValue(int(keyID), valuename);
if (valueID == noID) if (valueID == noID)
{ {
if (!create) if (!create)
@ -403,7 +402,7 @@ bool cIniFile::SetValue(const string & keyname, const string & valuename, const
bool cIniFile::SetValueI(const string & keyname, const string & valuename, int const value, bool const create) bool cIniFile::SetValueI(const AString & keyname, const AString & valuename, const int value, bool const create)
{ {
AString Data; AString Data;
Printf(Data, "%d", value); Printf(Data, "%d", value);
@ -414,7 +413,7 @@ bool cIniFile::SetValueI(const string & keyname, const string & valuename, int c
bool cIniFile::SetValueF(const string & keyname, const string & valuename, double const value, bool const create) bool cIniFile::SetValueF(const AString & keyname, const AString & valuename, double const value, bool const create)
{ {
AString Data; AString Data;
Printf(Data, "%f", value); Printf(Data, "%f", value);
@ -425,7 +424,7 @@ bool cIniFile::SetValueF(const string & keyname, const string & valuename, doubl
bool cIniFile::SetValueV(const string & keyname, const string & valuename, char * format, ...) bool cIniFile::SetValueV(const AString & keyname, const AString & valuename, char * format, ...)
{ {
va_list args; va_list args;
va_start(args, format); va_start(args, format);
@ -440,9 +439,9 @@ bool cIniFile::SetValueV(const string & keyname, const string & valuename, char
string cIniFile::GetValue(unsigned const keyID, unsigned const valueID, const string & defValue) const AString cIniFile::GetValue(const int keyID, const int valueID, const AString & defValue) const
{ {
if ((keyID < keys.size()) && (valueID < keys[keyID].names.size())) if ((keyID < (int)keys.size()) && (valueID < (int)keys[keyID].names.size()))
{ {
return keys[keyID].values[valueID]; return keys[keyID].values[valueID];
} }
@ -453,15 +452,15 @@ string cIniFile::GetValue(unsigned const keyID, unsigned const valueID, const st
string cIniFile::GetValue(const string & keyname, const string & valuename, const string & defValue) const AString cIniFile::GetValue(const AString & keyname, const AString & valuename, const AString & defValue) const
{ {
long keyID = FindKey(keyname); int keyID = FindKey(keyname);
if (keyID == noID) if (keyID == noID)
{ {
return defValue; return defValue;
} }
long valueID = FindValue(unsigned(keyID), valuename); int valueID = FindValue(int(keyID), valuename);
if (valueID == noID) if (valueID == noID)
{ {
return defValue; return defValue;
@ -474,7 +473,7 @@ string cIniFile::GetValue(const string & keyname, const string & valuename, cons
int cIniFile::GetValueI(const string & keyname, const string & valuename, int const defValue) const int cIniFile::GetValueI(const AString & keyname, const AString & valuename, const int defValue) const
{ {
AString Data; AString Data;
Printf(Data, "%d", defValue); Printf(Data, "%d", defValue);
@ -485,7 +484,7 @@ int cIniFile::GetValueI(const string & keyname, const string & valuename, int co
double cIniFile::GetValueF(const string & keyname, const string & valuename, double const defValue) const double cIniFile::GetValueF(const AString & keyname, const AString & valuename, double const defValue) const
{ {
AString Data; AString Data;
Printf(Data, "%f", defValue); Printf(Data, "%f", defValue);
@ -498,14 +497,14 @@ double cIniFile::GetValueF(const string & keyname, const string & valuename, dou
AString cIniFile::GetValueSet(const AString & keyname, const AString & valuename, const AString & defValue) AString cIniFile::GetValueSet(const AString & keyname, const AString & valuename, const AString & defValue)
{ {
long keyID = FindKey(keyname); int keyID = FindKey(keyname);
if (keyID == noID) if (keyID == noID)
{ {
SetValue(keyname, valuename, defValue); SetValue(keyname, valuename, defValue);
return defValue; return defValue;
} }
long valueID = FindValue(unsigned(keyID), valuename); int valueID = FindValue(int(keyID), valuename);
if (valueID == noID) if (valueID == noID)
{ {
SetValue(keyname, valuename, defValue); SetValue(keyname, valuename, defValue);
@ -541,13 +540,13 @@ int cIniFile::GetValueSetI(const AString & keyname, const AString & valuename, c
bool cIniFile::DeleteValueByID(const unsigned keyID, const unsigned valueID) bool cIniFile::DeleteValueByID(const int keyID, const int valueID)
{ {
if (keyID < keys.size() && valueID < keys[keyID].names.size()) if ((keyID < (int)keys.size()) && (valueID < (int)keys[keyID].names.size()))
{ {
// This looks strange, but is neccessary. // This looks strange, but is neccessary.
vector<string>::iterator npos = keys[keyID].names.begin() + valueID; vector<AString>::iterator npos = keys[keyID].names.begin() + valueID;
vector<string>::iterator vpos = keys[keyID].values.begin() + valueID; vector<AString>::iterator vpos = keys[keyID].values.begin() + valueID;
keys[keyID].names.erase(npos, npos + 1); keys[keyID].names.erase(npos, npos + 1);
keys[keyID].values.erase(vpos, vpos + 1); keys[keyID].values.erase(vpos, vpos + 1);
return true; return true;
@ -559,15 +558,15 @@ bool cIniFile::DeleteValueByID(const unsigned keyID, const unsigned valueID)
bool cIniFile::DeleteValue(const string & keyname, const string & valuename) bool cIniFile::DeleteValue(const AString & keyname, const AString & valuename)
{ {
long keyID = FindKey(keyname); int keyID = FindKey(keyname);
if (keyID == noID) if (keyID == noID)
{ {
return false; return false;
} }
long valueID = FindValue(unsigned(keyID), valuename); int valueID = FindValue(int(keyID), valuename);
if (valueID == noID) if (valueID == noID)
{ {
return false; return false;
@ -580,15 +579,15 @@ bool cIniFile::DeleteValue(const string & keyname, const string & valuename)
bool cIniFile::DeleteKey(const string & keyname) bool cIniFile::DeleteKey(const AString & keyname)
{ {
long keyID = FindKey(keyname); int keyID = FindKey(keyname);
if (keyID == noID) if (keyID == noID)
{ {
return false; return false;
} }
vector<string>::iterator npos = names.begin() + keyID; vector<AString>::iterator npos = names.begin() + keyID;
vector<key>::iterator kpos = keys.begin() + keyID; vector<key>::iterator kpos = keys.begin() + keyID;
names.erase(npos, npos + 1); names.erase(npos, npos + 1);
keys.erase(kpos, kpos + 1); keys.erase(kpos, kpos + 1);
@ -611,7 +610,7 @@ void cIniFile::Clear(void)
void cIniFile::HeaderComment(const string & comment) void cIniFile::AddHeaderComment(const AString & comment)
{ {
comments.push_back(comment); comments.push_back(comment);
// comments.resize(comments.size() + 1, comment); // comments.resize(comments.size() + 1, comment);
@ -621,9 +620,9 @@ void cIniFile::HeaderComment(const string & comment)
string cIniFile::HeaderComment(unsigned const commentID) const AString cIniFile::GetHeaderComment(const int commentID) const
{ {
if (commentID < comments.size()) if (commentID < (int)comments.size())
{ {
return comments[commentID]; return comments[commentID];
} }
@ -634,11 +633,11 @@ string cIniFile::HeaderComment(unsigned const commentID) const
bool cIniFile::DeleteHeaderComment(unsigned commentID) bool cIniFile::DeleteHeaderComment(int commentID)
{ {
if (commentID < comments.size()) if (commentID < (int)comments.size())
{ {
vector<string>::iterator cpos = comments.begin() + commentID; vector<AString>::iterator cpos = comments.begin() + commentID;
comments.erase(cpos, cpos + 1); comments.erase(cpos, cpos + 1);
return true; return true;
} }
@ -649,9 +648,9 @@ bool cIniFile::DeleteHeaderComment(unsigned commentID)
unsigned cIniFile::NumKeyComments(unsigned const keyID) const int cIniFile::GetNumKeyComments(const int keyID) const
{ {
if (keyID < keys.size()) if (keyID < (int)keys.size())
{ {
return keys[keyID].comments.size(); return keys[keyID].comments.size();
} }
@ -662,21 +661,23 @@ unsigned cIniFile::NumKeyComments(unsigned const keyID) const
unsigned cIniFile::NumKeyComments(const string & keyname) const int cIniFile::GetNumKeyComments(const AString & keyname) const
{ {
long keyID = FindKey(keyname); int keyID = FindKey(keyname);
if (keyID == noID) if (keyID == noID)
{
return 0; return 0;
return keys[keyID].comments.size(); }
return (int)keys[keyID].comments.size();
} }
bool cIniFile::KeyComment(unsigned const keyID, const string & comment) bool cIniFile::AddKeyComment(const int keyID, const AString & comment)
{ {
if (keyID < keys.size()) if (keyID < (int)keys.size())
{ {
keys[keyID].comments.resize(keys[keyID].comments.size() + 1, comment); keys[keyID].comments.resize(keys[keyID].comments.size() + 1, comment);
return true; return true;
@ -688,23 +689,23 @@ bool cIniFile::KeyComment(unsigned const keyID, const string & comment)
bool cIniFile::KeyComment(const string & keyname, const string & comment) bool cIniFile::AddKeyComment(const AString & keyname, const AString & comment)
{ {
long keyID = FindKey(keyname); int keyID = FindKey(keyname);
if (keyID == noID) if (keyID == noID)
{ {
return false; return false;
} }
return KeyComment(unsigned(keyID), comment); return AddKeyComment(keyID, comment);
} }
string cIniFile::KeyComment(unsigned const keyID, unsigned const commentID) const AString cIniFile::GetKeyComment(const int keyID, const int commentID) const
{ {
if ((keyID < keys.size()) && (commentID < keys[keyID].comments.size())) if ((keyID < (int)keys.size()) && (commentID < (int)keys[keyID].comments.size()))
{ {
return keys[keyID].comments[commentID]; return keys[keyID].comments[commentID];
} }
@ -715,25 +716,25 @@ string cIniFile::KeyComment(unsigned const keyID, unsigned const commentID) cons
string cIniFile::KeyComment(const string & keyname, unsigned const commentID) const AString cIniFile::GetKeyComment(const AString & keyname, const int commentID) const
{ {
long keyID = FindKey(keyname); int keyID = FindKey(keyname);
if (keyID == noID) if (keyID == noID)
{ {
return ""; return "";
} }
return KeyComment(unsigned(keyID), commentID); return GetKeyComment(int(keyID), commentID);
} }
bool cIniFile::DeleteKeyComment(unsigned const keyID, unsigned const commentID) bool cIniFile::DeleteKeyComment(const int keyID, const int commentID)
{ {
if ((keyID < keys.size()) && (commentID < keys[keyID].comments.size())) if ((keyID < (int)keys.size()) && (commentID < (int)keys[keyID].comments.size()))
{ {
vector<string>::iterator cpos = keys[keyID].comments.begin() + commentID; vector<AString>::iterator cpos = keys[keyID].comments.begin() + commentID;
keys[keyID].comments.erase(cpos, cpos + 1); keys[keyID].comments.erase(cpos, cpos + 1);
return true; return true;
} }
@ -744,23 +745,23 @@ bool cIniFile::DeleteKeyComment(unsigned const keyID, unsigned const commentID)
bool cIniFile::DeleteKeyComment(const string & keyname, unsigned const commentID) bool cIniFile::DeleteKeyComment(const AString & keyname, const int commentID)
{ {
long keyID = FindKey(keyname); int keyID = FindKey(keyname);
if (keyID == noID) if (keyID == noID)
{ {
return false; return false;
} }
return DeleteKeyComment(unsigned(keyID), commentID); return DeleteKeyComment(int(keyID), commentID);
} }
bool cIniFile::DeleteKeyComments(unsigned const keyID) bool cIniFile::DeleteKeyComments(const int keyID)
{ {
if (keyID < keys.size()) if (keyID < (int)keys.size())
{ {
keys[keyID].comments.clear(); keys[keyID].comments.clear();
return true; return true;
@ -772,27 +773,27 @@ bool cIniFile::DeleteKeyComments(unsigned const keyID)
bool cIniFile::DeleteKeyComments(const string & keyname) bool cIniFile::DeleteKeyComments(const AString & keyname)
{ {
long keyID = FindKey(keyname); int keyID = FindKey(keyname);
if (keyID == noID) if (keyID == noID)
{ {
return false; return false;
} }
return DeleteKeyComments(unsigned(keyID)); return DeleteKeyComments(int(keyID));
} }
string cIniFile::CheckCase(const string & s) const AString cIniFile::CheckCase(const AString & s) const
{ {
if (!m_IsCaseInsensitive) if (!m_IsCaseInsensitive)
{ {
return s; return s;
} }
string res(s); AString res(s);
size_t len = res.length(); size_t len = res.length();
for (size_t i = 0; i < len; i++) for (size_t i = 0; i < len; i++)
{ {

View File

@ -36,21 +36,20 @@ class cIniFile
{ {
private: private:
bool m_IsCaseInsensitive; bool m_IsCaseInsensitive;
std::string m_Path;
struct key struct key
{ {
std::vector<std::string> names; std::vector<AString> names;
std::vector<std::string> values; std::vector<AString> values;
std::vector<std::string> comments; std::vector<AString> comments;
} ; } ;
std::vector<key> keys; std::vector<key> keys;
std::vector<std::string> names; std::vector<AString> names;
std::vector<std::string> comments; std::vector<AString> comments;
/// If the object is case-insensitive, returns s as lowercase; otherwise returns s as-is /// If the object is case-insensitive, returns s as lowercase; otherwise returns s as-is
std::string CheckCase(const std::string & s) const; AString CheckCase(const AString & s) const;
public: public:
enum errors enum errors
@ -58,79 +57,60 @@ public:
noID = -1, noID = -1,
}; };
/// Creates a new instance; sets m_Path to a_Path, but doesn't read the file /// Creates a new instance with no data
cIniFile(const std::string & a_Path = ""); cIniFile(void);
// Sets whether or not keynames and valuenames should be case sensitive. // Sets whether or not keynames and valuenames should be case sensitive.
// The default is case insensitive. // The default is case insensitive.
void CaseSensitive (void) { m_IsCaseInsensitive = false; } void CaseSensitive (void) { m_IsCaseInsensitive = false; }
void CaseInsensitive(void) { m_IsCaseInsensitive = true; } void CaseInsensitive(void) { m_IsCaseInsensitive = true; }
// Sets path of ini file to read and write from. /** Reads the contents of the specified ini file
void Path(const std::string & newPath) {m_Path = newPath;}
const std::string & Path(void) const {return m_Path;}
void SetPath(const std::string & newPath) {Path(newPath);}
/** Reads the ini file specified in m_Path
If the file doesn't exist and a_AllowExampleRedirect is true, tries to read <basename>.example.ini, and If the file doesn't exist and a_AllowExampleRedirect is true, tries to read <basename>.example.ini, and
writes its contents as <basename>.ini, if successful. writes its contents as <basename>.ini, if successful.
Returns true if successful, false otherwise. Returns true if successful, false otherwise.
*/ */
bool ReadFile(bool a_AllowExampleRedirect = true); bool ReadFile(const AString & a_FileName, bool a_AllowExampleRedirect = true);
/// Writes data stored in class to ini file specified in m_Path /// Writes data stored in class to the specified ini file
bool WriteFile(void) const; bool WriteFile(const AString & a_FileName) const;
/// Deletes all stored ini data (but doesn't touch the file) /// Deletes all stored ini data (but doesn't touch the file)
void Clear(void); void Clear(void);
void Reset(void) { Clear(); }
void Erase(void) { Clear(); } // OBSOLETE, this name is misguiding and will be removed from the interface
/// Returns index of specified key, or noID if not found /// Returns index of specified key, or noID if not found
long FindKey(const std::string & keyname) const; int FindKey(const AString & keyname) const;
/// Returns index of specified value, in the specified key, or noID if not found /// Returns index of specified value, in the specified key, or noID if not found
long FindValue(const unsigned keyID, const std::string & valuename) const; int FindValue(const int keyID, const AString & valuename) const;
/// Returns number of keys currently in the ini /// Returns number of keys currently in the ini
unsigned NumKeys (void) const {return names.size();} int GetNumKeys(void) const { return (int)keys.size(); }
unsigned GetNumKeys(void) const {return NumKeys();}
/// Add a key name /// Add a key name
unsigned AddKeyName(const std::string & keyname); int AddKeyName(const AString & keyname);
// Returns key names by index. // Returns key names by index.
std::string KeyName(const unsigned keyID) const; AString GetKeyName(const int keyID) const;
std::string GetKeyName(const unsigned keyID) const {return KeyName(keyID);}
// Returns number of values stored for specified key. // Returns number of values stored for specified key.
unsigned NumValues (const std::string & keyname); int GetNumValues(const AString & keyname) const;
unsigned GetNumValues(const std::string & keyname) {return NumValues(keyname);} int GetNumValues(const int keyID) const;
unsigned NumValues (const unsigned keyID);
unsigned GetNumValues(const unsigned keyID) {return NumValues(keyID);}
// Returns value name by index for a given keyname or keyID. // Returns value name by index for a given keyname or keyID.
std::string ValueName( const std::string & keyname, const unsigned valueID) const; AString GetValueName(const AString & keyname, const int valueID) const;
std::string GetValueName( const std::string & keyname, const unsigned valueID) const AString GetValueName(const int keyID, const int valueID) const;
{
return ValueName(keyname, valueID);
}
std::string ValueName (const unsigned keyID, const unsigned valueID) const;
std::string GetValueName(const unsigned keyID, const unsigned valueID) const
{
return ValueName(keyID, valueID);
}
// Gets value of [keyname] valuename =. // Gets value of [keyname] valuename =.
// Overloaded to return string, int, and double. // Overloaded to return string, int, and double.
// Returns defValue if key/value not found. // Returns defValue if key/value not found.
AString GetValue (const AString & keyname, const AString & valuename, const AString & defValue = "") const; AString GetValue (const AString & keyname, const AString & valuename, const AString & defValue = "") const;
AString GetValue (const unsigned keyID, const unsigned valueID, const AString & defValue = "") const; AString GetValue (const int keyID, const int valueID, const AString & defValue = "") const;
double GetValueF(const AString & keyname, const AString & valuename, const double defValue = 0) const; double GetValueF(const AString & keyname, const AString & valuename, const double defValue = 0) const;
int GetValueI(const AString & keyname, const AString & valuename, const int defValue = 0) const; int GetValueI(const AString & keyname, const AString & valuename, const int defValue = 0) const;
bool GetValueB(const AString & keyname, const AString & valuename, const bool defValue = false) const bool GetValueB(const AString & keyname, const AString & valuename, const bool defValue = false) const
{ {
return (GetValueI(keyname, valuename, int(defValue)) > 0); return (GetValueI(keyname, valuename, defValue ? 1 : 0) != 0);
} }
// Gets the value; if not found, write the default to the INI file // Gets the value; if not found, write the default to the INI file
@ -139,50 +119,54 @@ public:
int GetValueSetI(const AString & keyname, const AString & valuename, const int defValue = 0); int GetValueSetI(const AString & keyname, const AString & valuename, const int defValue = 0);
bool GetValueSetB(const AString & keyname, const AString & valuename, const bool defValue = false) bool GetValueSetB(const AString & keyname, const AString & valuename, const bool defValue = false)
{ {
return (GetValueSetI(keyname, valuename, defValue ? 1 : 0) > 0); return (GetValueSetI(keyname, valuename, defValue ? 1 : 0) != 0);
} }
// Sets value of [keyname] valuename =. // Sets value of [keyname] valuename =.
// Specify the optional paramter as false (0) if you do not want it to create // Specify the optional paramter as false (0) if you do not want it to create
// the key if it doesn't exist. Returns true if data entered, false otherwise. // the key if it doesn't exist. Returns true if data entered, false otherwise.
// Overloaded to accept string, int, and double. // Overloaded to accept string, int, and double.
bool SetValue( const unsigned keyID, const unsigned valueID, const std::string & value); bool SetValue( const int keyID, const int valueID, const AString & value);
bool SetValue( const std::string & keyname, const std::string & valuename, const std::string & value, const bool create = true); bool SetValue( const AString & keyname, const AString & valuename, const AString & value, const bool create = true);
bool SetValueI( const std::string & keyname, const std::string & valuename, const int value, const bool create = true); bool SetValueI( const AString & keyname, const AString & valuename, const int value, const bool create = true);
bool SetValueB( const std::string & keyname, const std::string & valuename, const bool value, const bool create = true) bool SetValueB( const AString & keyname, const AString & valuename, const bool value, const bool create = true)
{ {
return SetValueI( keyname, valuename, int(value), create); return SetValueI( keyname, valuename, int(value), create);
} }
bool SetValueF( const std::string & keyname, const std::string & valuename, const double value, const bool create = true); bool SetValueF( const AString & keyname, const AString & valuename, const double value, const bool create = true);
// tolua_end // tolua_end
bool SetValueV( const std::string & keyname, const std::string & valuename, char *format, ...); bool SetValueV( const AString & keyname, const AString & valuename, char *format, ...);
// tolua_begin // tolua_begin
// Deletes specified value. // Deletes specified value.
// Returns true if value existed and deleted, false otherwise. // Returns true if value existed and deleted, false otherwise.
bool DeleteValueByID( const unsigned keyID, const unsigned valueID ); bool DeleteValueByID(const int keyID, const int valueID);
bool DeleteValue( const std::string & keyname, const std::string & valuename); bool DeleteValue(const AString & keyname, const AString & valuename);
// Deletes specified key and all values contained within. // Deletes specified key and all values contained within.
// Returns true if key existed and deleted, false otherwise. // Returns true if key existed and deleted, false otherwise.
bool DeleteKey(const std::string & keyname); bool DeleteKey(const AString & keyname);
// Header comment functions. // Header comment functions.
// Header comments are those comments before the first key. // Header comments are those comments before the first key.
//
// Number of header comments. /// Returns the number of header comments
unsigned NumHeaderComments(void) {return comments.size();} int GetNumHeaderComments(void) {return (int)comments.size();}
// Add a header comment.
void HeaderComment(const std::string & comment); /// Adds a header comment
// Return a header comment. void AddHeaderComment(const AString & comment);
std::string HeaderComment(const unsigned commentID) const;
// Delete a header comment. /// Returns a header comment, or empty string if out of range
bool DeleteHeaderComment(unsigned commentID); AString GetHeaderComment(const int commentID) const;
// Delete all header comments.
void DeleteHeaderComments(void) {comments.clear();} /// Deletes a header comment. Returns true if successful
bool DeleteHeaderComment(int commentID);
/// Deletes all header comments
void DeleteHeaderComments(void) {comments.clear();}
// Key comment functions. // Key comment functions.
@ -190,26 +174,30 @@ public:
// defined within value names will be added to this list. Therefore, // defined within value names will be added to this list. Therefore,
// these comments will be moved to the top of the key definition when // these comments will be moved to the top of the key definition when
// the CIniFile::WriteFile() is called. // the CIniFile::WriteFile() is called.
//
// Number of key comments. /// Get number of key comments
unsigned NumKeyComments( const unsigned keyID) const; int GetNumKeyComments(const int keyID) const;
unsigned NumKeyComments( const std::string & keyname) const;
/// Get number of key comments
int GetNumKeyComments(const AString & keyname) const;
// Add a key comment. /// Add a key comment
bool KeyComment(const unsigned keyID, const std::string & comment); bool AddKeyComment(const int keyID, const AString & comment);
bool KeyComment(const std::string & keyname, const std::string & comment);
/// Add a key comment
bool AddKeyComment(const AString & keyname, const AString & comment);
// Return a key comment. /// Return a key comment
std::string KeyComment(const unsigned keyID, const unsigned commentID) const; AString GetKeyComment(const int keyID, const int commentID) const;
std::string KeyComment(const std::string & keyname, const unsigned commentID) const; AString GetKeyComment(const AString & keyname, const int commentID) const;
// Delete a key comment. // Delete a key comment.
bool DeleteKeyComment(const unsigned keyID, const unsigned commentID); bool DeleteKeyComment(const int keyID, const int commentID);
bool DeleteKeyComment(const std::string & keyname, const unsigned commentID); bool DeleteKeyComment(const AString & keyname, const int commentID);
// Delete all comments for a key. // Delete all comments for a key.
bool DeleteKeyComments(const unsigned keyID); bool DeleteKeyComments(const int keyID);
bool DeleteKeyComments(const std::string & keyname); bool DeleteKeyComments(const AString & keyname);
}; };
// tolua_end // tolua_end

View File

@ -28,7 +28,6 @@ cAuthenticator::cAuthenticator(void) :
m_Address(DEFAULT_AUTH_ADDRESS), m_Address(DEFAULT_AUTH_ADDRESS),
m_ShouldAuthenticate(true) m_ShouldAuthenticate(true)
{ {
ReadINI();
} }
@ -45,14 +44,8 @@ cAuthenticator::~cAuthenticator()
/// Read custom values from INI /// Read custom values from INI
void cAuthenticator::ReadINI(void) void cAuthenticator::ReadINI(cIniFile & IniFile)
{ {
cIniFile IniFile("settings.ini");
if (!IniFile.ReadFile())
{
return;
}
m_Server = IniFile.GetValue("Authentication", "Server"); m_Server = IniFile.GetValue("Authentication", "Server");
m_Address = IniFile.GetValue("Authentication", "Address"); m_Address = IniFile.GetValue("Authentication", "Address");
m_ShouldAuthenticate = IniFile.GetValueB("Authentication", "Authenticate", true); m_ShouldAuthenticate = IniFile.GetValueB("Authentication", "Authenticate", true);
@ -74,7 +67,6 @@ void cAuthenticator::ReadINI(void)
if (bSave) if (bSave)
{ {
IniFile.SetValueB("Authentication", "Authenticate", m_ShouldAuthenticate); IniFile.SetValueB("Authentication", "Authenticate", m_ShouldAuthenticate);
IniFile.WriteFile();
} }
} }
@ -100,8 +92,9 @@ void cAuthenticator::Authenticate(int a_ClientID, const AString & a_UserName, co
void cAuthenticator::Start(void) void cAuthenticator::Start(cIniFile & IniFile)
{ {
ReadINI(IniFile);
m_ShouldTerminate = false; m_ShouldTerminate = false;
super::Start(); super::Start();
} }

View File

@ -37,13 +37,13 @@ public:
~cAuthenticator(); ~cAuthenticator();
/// (Re-)read server and address from INI: /// (Re-)read server and address from INI:
void ReadINI(void); void ReadINI(cIniFile & IniFile);
/// Queues a request for authenticating a user. If the auth fails, the user is kicked /// Queues a request for authenticating a user. If the auth fails, the user is kicked
void Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash); void Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash);
/// Starts the authenticator thread. The thread may be started and stopped repeatedly /// Starts the authenticator thread. The thread may be started and stopped repeatedly
void Start(void); void Start(cIniFile & IniFile);
/// Stops the authenticator thread. The thread may be started and stopped repeatedly /// Stops the authenticator thread. The thread may be started and stopped repeatedly
void Stop(void); void Stop(void);

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
/* /*
** Lua binding: AllToLua ** Lua binding: AllToLua
** Generated automatically by tolua++-1.0.92 on 10/23/13 13:30:24. ** Generated automatically by tolua++-1.0.92 on 10/28/13 13:11:04.
*/ */
/* Exported function */ /* Exported function */

View File

@ -42,20 +42,20 @@ class cBlockIDMap
public: public:
cBlockIDMap(void) cBlockIDMap(void)
{ {
cIniFile Ini("items.ini"); cIniFile Ini;
if (!Ini.ReadFile()) if (!Ini.ReadFile("items.ini"))
{ {
return; return;
} }
long KeyID = Ini.FindKey("Items"); int KeyID = Ini.FindKey("Items");
if (KeyID == cIniFile::noID) if (KeyID == cIniFile::noID)
{ {
return; return;
} }
unsigned NumValues = Ini.GetNumValues(KeyID); int NumValues = Ini.GetNumValues(KeyID);
for (unsigned i = 0; i < NumValues; i++) for (int i = 0; i < NumValues; i++)
{ {
AString Name = Ini.ValueName(KeyID, i); AString Name = Ini.GetValueName(KeyID, i);
if (Name.empty()) if (Name.empty())
{ {
continue; continue;

View File

@ -13,8 +13,54 @@
#define NEEDBYTES(Num) if (!CanReadBytes(Num)) return false; // If a string sent over the protocol is larger than this, a warning is emitted to the console
#define PUTBYTES(Num) if (!CanWriteBytes(Num)) return false; #define MAX_STRING_SIZE (512 KiB)
#define NEEDBYTES(Num) if (!CanReadBytes(Num)) return false; // Check if at least Num bytes can be read from the buffer, return false if not
#define PUTBYTES(Num) if (!CanWriteBytes(Num)) return false; // Check if at least Num bytes can be written to the buffer, return false if not
#if 0
/// Self-test of the VarInt-reading and writing code
class cByteBufferSelfTest
{
public:
cByteBufferSelfTest(void)
{
TestRead();
TestWrite();
}
void TestRead(void)
{
cByteBuffer buf(50);
buf.Write("\x05\xac\x02\x00", 4);
UInt32 v1;
ASSERT(buf.ReadVarInt(v1) && (v1 == 5));
UInt32 v2;
ASSERT(buf.ReadVarInt(v2) && (v2 == 300));
UInt32 v3;
ASSERT(buf.ReadVarInt(v3) && (v3 == 0));
}
void TestWrite(void)
{
cByteBuffer buf(50);
buf.WriteVarInt(5);
buf.WriteVarInt(300);
buf.WriteVarInt(0);
AString All;
buf.ReadAll(All);
ASSERT(All.size() == 4);
ASSERT(memcmp(All.data(), "\x05\xac\x02\x00", All.size()) == 0);
}
} g_ByteBufferTest;
#endif
@ -328,6 +374,48 @@ bool cByteBuffer::ReadBEUTF16String16(AString & a_Value)
bool cByteBuffer::ReadVarInt(UInt32 & a_Value)
{
CHECK_THREAD;
CheckValid();
UInt32 Value = 0;
int Shift = 0;
unsigned char b = 0;
do
{
NEEDBYTES(1);
ReadBuf(&b, 1);
Value = Value | (((Int64)(b & 0x7f)) << Shift);
Shift += 7;
} while ((b & 0x80) != 0);
a_Value = Value;
return true;
}
bool cByteBuffer::ReadVarUTF8String(AString & a_Value)
{
CHECK_THREAD;
CheckValid();
UInt32 Size = 0;
if (!ReadVarInt(Size))
{
return false;
}
if (Size > MAX_STRING_SIZE)
{
LOGWARNING("%s: String too large: %llu (%llu KiB)", __FUNCTION__, Size, Size / 1024);
}
return ReadString(a_Value, (int)Size);
}
bool cByteBuffer::WriteChar(char a_Value) bool cByteBuffer::WriteChar(char a_Value)
{ {
CHECK_THREAD; CHECK_THREAD;
@ -446,6 +534,44 @@ bool cByteBuffer::WriteBEUTF16String16(const AString & a_Value)
bool cByteBuffer::WriteVarInt(UInt32 a_Value)
{
CHECK_THREAD;
CheckValid();
// A 32-bit integer can be encoded by at most 5 bytes:
unsigned char b[5];
int idx = 0;
do
{
b[idx] = (a_Value & 0x7f) | ((a_Value > 0x7f) ? 0x80 : 0x00);
a_Value = a_Value >> 7;
idx++;
} while (a_Value > 0);
return WriteBuf(b, idx);
}
bool cByteBuffer::WriteVarUTF8String(AString & a_Value)
{
CHECK_THREAD;
CheckValid();
PUTBYTES(a_Value.size() + 1); // This is a lower-bound on the bytes that will be actually written. Fail early.
bool res = WriteVarInt(a_Value.size());
if (!res)
{
return false;
}
return WriteBuf(a_Value.data(), a_Value.size());
}
bool cByteBuffer::ReadBuf(void * a_Buffer, int a_Count) bool cByteBuffer::ReadBuf(void * a_Buffer, int a_Count)
{ {
CHECK_THREAD; CHECK_THREAD;

View File

@ -57,8 +57,22 @@ public:
bool ReadBEFloat (float & a_Value); bool ReadBEFloat (float & a_Value);
bool ReadBEDouble (double & a_Value); bool ReadBEDouble (double & a_Value);
bool ReadBool (bool & a_Value); bool ReadBool (bool & a_Value);
bool ReadBEUTF16String16(AString & a_Value); bool ReadBEUTF16String16(AString & a_Value); // string length as BE short, then string as UTF-16BE
bool ReadVarInt (UInt32 & a_Value);
bool ReadVarUTF8String (AString & a_Value); // string length as VarInt, then string as UTF-8
/// Reads VarInt, assigns it to anything that can be assigned from an UInt32 (unsigned short, char, Byte, double, ...)
template <typename T> bool ReadVarUInt(T & a_Value)
{
UInt32 v;
bool res = ReadVarInt(v);
if (res)
{
a_Value = v;
}
return res;
}
// Write the specified datatype; return true if successfully written // Write the specified datatype; return true if successfully written
bool WriteChar (char a_Value); bool WriteChar (char a_Value);
bool WriteByte (unsigned char a_Value); bool WriteByte (unsigned char a_Value);
@ -68,7 +82,9 @@ public:
bool WriteBEFloat (float a_Value); bool WriteBEFloat (float a_Value);
bool WriteBEDouble (double a_Value); bool WriteBEDouble (double a_Value);
bool WriteBool (bool a_Value); bool WriteBool (bool a_Value);
bool WriteBEUTF16String16(const AString & a_Value); bool WriteBEUTF16String16(const AString & a_Value); // string length as BE short, then string as UTF-16BE
bool WriteVarInt (UInt32 a_Value);
bool WriteVarUTF8String (AString & a_Value); // string length as VarInt, then string as UTF-8
/// Reads a_Count bytes into a_Buffer; returns true if successful /// Reads a_Count bytes into a_Buffer; returns true if successful
bool ReadBuf(void * a_Buffer, int a_Count); bool ReadBuf(void * a_Buffer, int a_Count);

View File

@ -1152,6 +1152,29 @@ bool cChunk::UnboundedRelGetBlockSkyLight(int a_RelX, int a_RelY, int a_RelZ, NI
bool cChunk::UnboundedRelGetBlockLights(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE & a_BlockLight, NIBBLETYPE & a_SkyLight) const
{
if ((a_RelY < 0) || (a_RelY >= cChunkDef::Height))
{
LOGWARNING("%s: requesting a block with a_RelY out of range: %d", __FUNCTION__, a_RelY);
return false;
}
cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ);
if ((Chunk == NULL) || !Chunk->IsValid())
{
// The chunk is not available, bail out
return false;
}
int idx = Chunk->MakeIndex(a_RelX, a_RelY, a_RelZ);
a_BlockLight = Chunk->GetBlockLight(idx);
a_SkyLight = Chunk->GetSkyLight(idx);
return true;
}
bool cChunk::UnboundedRelSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) bool cChunk::UnboundedRelSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta)
{ {
if ((a_RelY < 0) || (a_RelY > cChunkDef::Height)) if ((a_RelY < 0) || (a_RelY > cChunkDef::Height))

View File

@ -299,6 +299,8 @@ public:
inline NIBBLETYPE GetBlockLight(int a_RelX, int a_RelY, int a_RelZ) const {return cChunkDef::GetNibble(m_BlockLight, a_RelX, a_RelY, a_RelZ); } inline NIBBLETYPE GetBlockLight(int a_RelX, int a_RelY, int a_RelZ) const {return cChunkDef::GetNibble(m_BlockLight, a_RelX, a_RelY, a_RelZ); }
inline NIBBLETYPE GetSkyLight (int a_RelX, int a_RelY, int a_RelZ) const {return cChunkDef::GetNibble(m_BlockSkyLight, a_RelX, a_RelY, a_RelZ); } inline NIBBLETYPE GetSkyLight (int a_RelX, int a_RelY, int a_RelZ) const {return cChunkDef::GetNibble(m_BlockSkyLight, a_RelX, a_RelY, a_RelZ); }
inline NIBBLETYPE GetBlockLight(int a_Idx) const {return cChunkDef::GetNibble(m_BlockLight, a_Idx); }
inline NIBBLETYPE GetSkyLight (int a_Idx) const {return cChunkDef::GetNibble(m_BlockSkyLight, a_Idx); }
/// Same as GetBlock(), but relative coords needn't be in this chunk (uses m_Neighbor-s or m_ChunkMap in such a case); returns true on success /// Same as GetBlock(), but relative coords needn't be in this chunk (uses m_Neighbor-s or m_ChunkMap in such a case); returns true on success
bool UnboundedRelGetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const; bool UnboundedRelGetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const;
@ -315,6 +317,9 @@ public:
/// Same as GetBlockSkyLight(), but relative coords needn't be in this chunk (uses m_Neighbor-s or m_ChunkMap in such a case); returns true on success /// Same as GetBlockSkyLight(), but relative coords needn't be in this chunk (uses m_Neighbor-s or m_ChunkMap in such a case); returns true on success
bool UnboundedRelGetBlockSkyLight(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE & a_SkyLight) const; bool UnboundedRelGetBlockSkyLight(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE & a_SkyLight) const;
/// Queries both BlockLight and SkyLight, relative coords needn't be in this chunk (uses m_Neighbor-s or m_ChunkMap in such a case); returns true on success
bool UnboundedRelGetBlockLights(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE & a_BlockLight, NIBBLETYPE & a_SkyLight) const;
/// Same as SetBlock(), but relative coords needn't be in this chunk (uses m_Neighbor-s or m_ChunkMap in such a case); returns true on success /// Same as SetBlock(), but relative coords needn't be in this chunk (uses m_Neighbor-s or m_ChunkMap in such a case); returns true on success
bool UnboundedRelSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta); bool UnboundedRelSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta);

View File

@ -469,12 +469,12 @@ bool cClientHandle::HandleLogin(int a_ProtocolVersion, const AString & a_Usernam
void cClientHandle::HandleCreativeInventory(short a_SlotNum, const cItem & a_HeldItem) void cClientHandle::HandleCreativeInventory(short a_SlotNum, const cItem & a_HeldItem)
{ {
// This is for creative Inventory changes // This is for creative Inventory changes
if (m_Player->GetGameMode() != eGameMode_Creative) if (m_Player->IsGameModeCreative())
{ {
LOGWARNING("Got a CreativeInventoryAction packet from user \"%s\" while not in creative mode. Ignoring.", m_Username.c_str()); LOGWARNING("Got a CreativeInventoryAction packet from user \"%s\" while not in creative mode. Ignoring.", m_Username.c_str());
return; return;
} }
if (m_Player->GetWindow()->GetWindowType() != cWindow::Inventory) if (m_Player->GetWindow()->GetWindowType() != cWindow::wtInventory)
{ {
LOGWARNING("Got a CreativeInventoryAction packet from user \"%s\" while not in the inventory window. Ignoring.", m_Username.c_str()); LOGWARNING("Got a CreativeInventoryAction packet from user \"%s\" while not in the inventory window. Ignoring.", m_Username.c_str());
return; return;

View File

@ -24,11 +24,12 @@
cPickup::cPickup(double a_X, double a_Y, double a_Z, const cItem & a_Item, float a_SpeedX /* = 0.f */, float a_SpeedY /* = 0.f */, float a_SpeedZ /* = 0.f */) cPickup::cPickup(double a_PosX, double a_PosY, double a_PosZ, const cItem & a_Item, bool IsPlayerCreated, float a_SpeedX /* = 0.f */, float a_SpeedY /* = 0.f */, float a_SpeedZ /* = 0.f */)
: cEntity(etPickup, a_X, a_Y, a_Z, 0.2, 0.2) : cEntity(etPickup, a_PosX, a_PosY, a_PosZ, 0.2, 0.2)
, m_Timer( 0.f ) , m_Timer( 0.f )
, m_Item(a_Item) , m_Item(a_Item)
, m_bCollected( false ) , m_bCollected( false )
, m_bIsPlayerCreated( IsPlayerCreated )
{ {
m_MaxHealth = 5; m_MaxHealth = 5;
m_Health = 5; m_Health = 5;
@ -126,8 +127,8 @@ bool cPickup::CollectedBy(cPlayer * a_Dest)
return false; // It's already collected! return false; // It's already collected!
} }
// 800 is to long // Two seconds if player created the pickup (vomiting), half a second if anything else
if (m_Timer < 500.f) if (m_Timer < (m_bIsPlayerCreated ? 2000.f : 500.f))
{ {
// LOG("Pickup %d cannot be collected by \"%s\", because it is not old enough.", m_UniqueID, a_Dest->GetName().c_str()); // LOG("Pickup %d cannot be collected by \"%s\", because it is not old enough.", m_UniqueID, a_Dest->GetName().c_str());
return false; // Not old enough return false; // Not old enough

View File

@ -24,14 +24,14 @@ class cPickup :
public: public:
CLASS_PROTODEF(cPickup); CLASS_PROTODEF(cPickup);
cPickup(double a_X, double a_Y, double a_Z, const cItem & a_Item, float a_SpeedX = 0.f, float a_SpeedY = 0.f, float a_SpeedZ = 0.f); // tolua_export cPickup(double a_PosX, double a_PosY, double a_PosZ, const cItem & a_Item, bool IsPlayerCreated, float a_SpeedX = 0.f, float a_SpeedY = 0.f, float a_SpeedZ = 0.f); // tolua_export
cItem & GetItem(void) {return m_Item; } // tolua_export cItem & GetItem(void) {return m_Item; } // tolua_export
const cItem & GetItem(void) const {return m_Item; } const cItem & GetItem(void) const {return m_Item; }
virtual void SpawnOn(cClientHandle & a_ClientHandle) override; virtual void SpawnOn(cClientHandle & a_ClientHandle) override;
virtual bool CollectedBy(cPlayer * a_Dest); // tolua_export bool CollectedBy(cPlayer * a_Dest); // tolua_export
virtual void Tick(float a_Dt, cChunk & a_Chunk) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override;
@ -40,6 +40,9 @@ public:
/// Returns true if the pickup has already been collected /// Returns true if the pickup has already been collected
bool IsCollected(void) const { return m_bCollected; } // tolua_export bool IsCollected(void) const { return m_bCollected; } // tolua_export
/// Returns true if created by player (i.e. vomiting), used for determining picking-up delay time
bool IsPlayerCreated(void) const { return m_bIsPlayerCreated; } // tolua_export
private: private:
Vector3d m_ResultingSpeed; //Can be used to modify the resulting speed for the current tick ;) Vector3d m_ResultingSpeed; //Can be used to modify the resulting speed for the current tick ;)
@ -52,6 +55,8 @@ private:
cItem m_Item; cItem m_Item;
bool m_bCollected; bool m_bCollected;
bool m_bIsPlayerCreated;
}; // tolua_export }; // tolua_export

View File

@ -349,11 +349,8 @@ void cPlayer::SetTouchGround(bool a_bTouchGround)
void cPlayer::Heal(int a_Health) void cPlayer::Heal(int a_Health)
{ {
if (m_Health < GetMaxHealth()) super::Heal(a_Health);
{ SendHealth();
m_Health = (short)std::min((int)a_Health + m_Health, (int)GetMaxHealth());
SendHealth();
}
} }
@ -1183,7 +1180,7 @@ void cPlayer::TossItem(
double vX = 0, vY = 0, vZ = 0; double vX = 0, vY = 0, vZ = 0;
EulerToVector(-GetRotation(), GetPitch(), vZ, vX, vY); EulerToVector(-GetRotation(), GetPitch(), vZ, vX, vY);
vY = -vY * 2 + 1.f; vY = -vY * 2 + 1.f;
m_World->SpawnItemPickups(Drops, GetPosX(), GetPosY() + 1.6f, GetPosZ(), vX * 3, vY * 3, vZ * 3); m_World->SpawnItemPickups(Drops, GetPosX(), GetPosY() + 1.6f, GetPosZ(), vX * 3, vY * 3, vZ * 3, true); // 'true' because created by player
} }
@ -1227,11 +1224,11 @@ void cPlayer::LoadPermissionsFromDisk()
m_Groups.clear(); m_Groups.clear();
m_Permissions.clear(); m_Permissions.clear();
cIniFile IniFile("users.ini"); cIniFile IniFile;
if( IniFile.ReadFile() ) if (IniFile.ReadFile("users.ini"))
{ {
std::string Groups = IniFile.GetValue(m_PlayerName, "Groups", ""); std::string Groups = IniFile.GetValue(m_PlayerName, "Groups", "");
if( Groups.size() > 0 ) if (!Groups.empty())
{ {
AStringVector Split = StringSplit( Groups, "," ); AStringVector Split = StringSplit( Groups, "," );
for( unsigned int i = 0; i < Split.size(); i++ ) for( unsigned int i = 0; i < Split.size(); i++ )
@ -1248,7 +1245,7 @@ void cPlayer::LoadPermissionsFromDisk()
} }
else else
{ {
LOGWARN("WARNING: Failed to read ini file users.ini"); LOGWARN("Failed to read the users.ini file. The player will be added only to the Default group.");
AddToGroup("Default"); AddToGroup("Default");
} }
ResolvePermissions(); ResolvePermissions();

View File

@ -128,8 +128,8 @@ public:
// Sets the current gamemode, doesn't check validity, doesn't send update packets to client // Sets the current gamemode, doesn't check validity, doesn't send update packets to client
void LoginSetGameMode(eGameMode a_GameMode); void LoginSetGameMode(eGameMode a_GameMode);
/// Tries to move to a new position, with collision checks and stuff /// Tries to move to a new position, with attachment-related checks (y == -999)
virtual void MoveTo( const Vector3d & a_NewPos ); // tolua_export void MoveTo(const Vector3d & a_NewPos); // tolua_export
cWindow * GetWindow(void) { return m_CurrentWindow; } // tolua_export cWindow * GetWindow(void) { return m_CurrentWindow; } // tolua_export
const cWindow * GetWindow(void) const { return m_CurrentWindow; } const cWindow * GetWindow(void) const { return m_CurrentWindow; }
@ -159,29 +159,33 @@ public:
/// Adds a player to existing group or creates a new group when it doesn't exist /// Adds a player to existing group or creates a new group when it doesn't exist
void AddToGroup( const AString & a_GroupName ); // tolua_export void AddToGroup( const AString & a_GroupName ); // tolua_export
/// Removes a player from the group, resolves permissions and group inheritance (case sensitive) /// Removes a player from the group, resolves permissions and group inheritance (case sensitive)
void RemoveFromGroup( const AString & a_GroupName ); // tolua_export void RemoveFromGroup( const AString & a_GroupName ); // tolua_export
bool CanUseCommand( const AString & a_Command ); // tolua_export bool CanUseCommand( const AString & a_Command ); // tolua_export
bool HasPermission( const AString & a_Permission ); // tolua_export bool HasPermission( const AString & a_Permission ); // tolua_export
const GroupList & GetGroups() { return m_Groups; } // >> EXPORTED IN MANUALBINDINGS << const GroupList & GetGroups() { return m_Groups; } // >> EXPORTED IN MANUALBINDINGS <<
StringList GetResolvedPermissions(); // >> EXPORTED IN MANUALBINDINGS << StringList GetResolvedPermissions(); // >> EXPORTED IN MANUALBINDINGS <<
bool IsInGroup( const AString & a_Group ); // tolua_export bool IsInGroup( const AString & a_Group ); // tolua_export
AString GetColor(void) const; // tolua_export
void TossItem(bool a_bDraggingItem, char a_Amount = 1, short a_CreateType = 0, short a_CreateHealth = 0); // tolua_export
void Heal( int a_Health ); // tolua_export
// tolua_begin // tolua_begin
/// Returns the full color code to use for this player, based on their primary group or set in m_Color
AString GetColor(void) const;
void TossItem(bool a_bDraggingItem, char a_Amount = 1, short a_CreateType = 0, short a_CreateHealth = 0);
/// Heals the player by the specified amount of HPs (positive only); sends health update
void Heal(int a_Health);
int GetFoodLevel (void) const { return m_FoodLevel; } int GetFoodLevel (void) const { return m_FoodLevel; }
double GetFoodSaturationLevel (void) const { return m_FoodSaturationLevel; } double GetFoodSaturationLevel (void) const { return m_FoodSaturationLevel; }
int GetFoodTickTimer (void) const { return m_FoodTickTimer; } int GetFoodTickTimer (void) const { return m_FoodTickTimer; }
double GetFoodExhaustionLevel (void) const { return m_FoodExhaustionLevel; } double GetFoodExhaustionLevel (void) const { return m_FoodExhaustionLevel; }
int GetFoodPoisonedTicksRemaining(void) const { return m_FoodPoisonedTicksRemaining; } int GetFoodPoisonedTicksRemaining(void) const { return m_FoodPoisonedTicksRemaining; }
int GetAirLevel (void) const { return m_AirLevel; } int GetAirLevel (void) const { return m_AirLevel; }
/// Returns true if the player is satiated, i. e. their foodlevel is at the max and they cannot eat anymore /// Returns true if the player is satiated, i. e. their foodlevel is at the max and they cannot eat anymore
bool IsSatiated(void) const { return (m_FoodLevel >= MAX_FOOD_LEVEL); } bool IsSatiated(void) const { return (m_FoodLevel >= MAX_FOOD_LEVEL); }
@ -302,6 +306,7 @@ protected:
/// Player's air level (for swimming) /// Player's air level (for swimming)
int m_AirLevel; int m_AirLevel;
/// used to time ticks between damage taken via drowning/suffocation /// used to time ticks between damage taken via drowning/suffocation
int m_AirTickTimer; int m_AirTickTimer;

View File

@ -75,8 +75,6 @@ bool cChunkGenerator::Start(cWorld * a_World, cIniFile & a_IniFile)
m_Generator->Initialize(a_World, a_IniFile); m_Generator->Initialize(a_World, a_IniFile);
a_IniFile.WriteFile();
return super::Start(); return super::Start();
} }

View File

@ -44,8 +44,8 @@ cGroupManager::cGroupManager()
: m_pState( new sGroupManagerState ) : m_pState( new sGroupManagerState )
{ {
LOGD("-- Loading Groups --"); LOGD("-- Loading Groups --");
cIniFile IniFile("groups.ini"); cIniFile IniFile;
if (!IniFile.ReadFile()) if (!IniFile.ReadFile("groups.ini"))
{ {
LOGWARNING("groups.ini inaccessible, no groups are defined"); LOGWARNING("groups.ini inaccessible, no groups are defined");
return; return;

View File

@ -31,8 +31,8 @@ cLuaWindow::cLuaWindow(cWindow::WindowType a_WindowType, int a_SlotsX, int a_Slo
// If appropriate, add an Armor slot area: // If appropriate, add an Armor slot area:
switch (a_WindowType) switch (a_WindowType)
{ {
case cWindow::Inventory: case cWindow::wtInventory:
case cWindow::Workbench: case cWindow::wtWorkbench:
{ {
m_SlotAreas.push_back(new cSlotAreaArmor(*this)); m_SlotAreas.push_back(new cSlotAreaArmor(*this));
break; break;

View File

@ -605,7 +605,7 @@ cMonster::eFamily cMonster::FamilyFromType(eType a_Type)
int cMonster::GetSpawnRate(cMonster::eFamily a_MobFamily) int cMonster::GetSpawnDelay(cMonster::eFamily a_MobFamily)
{ {
switch (a_MobFamily) switch (a_MobFamily)
{ {

View File

@ -137,17 +137,17 @@ public:
// tolua_begin // tolua_begin
/// Translates MobType enum to a string /// Translates MobType enum to a string, empty string if unknown
static AString MobTypeToString(eType a_MobType); static AString MobTypeToString(eType a_MobType);
/// Translates MobType string to the enum /// Translates MobType string to the enum, mtInvalidType if not recognized
static eType StringToMobType(const AString & a_MobTypeName); static eType StringToMobType(const AString & a_MobTypeName);
/// Returns the mob family based on the type /// Returns the mob family based on the type
static eFamily FamilyFromType(eType a_MobType); static eFamily FamilyFromType(eType a_MobType);
/// Returns the spawn rate (number of game ticks between spawn attempts) for the given mob family /// Returns the spawn delay (number of game ticks between spawn attempts) for the given mob family
static int GetSpawnRate(cMonster::eFamily a_MobFamily); static int GetSpawnDelay(cMonster::eFamily a_MobFamily);
// tolua_end // tolua_end

View File

@ -33,6 +33,7 @@ void cSheep::GetDrops(cItems & a_Drops, cEntity * a_Killer)
void cSheep::OnRightClicked(cPlayer & a_Player) void cSheep::OnRightClicked(cPlayer & a_Player)
{ {
if ((a_Player.GetEquippedItem().m_ItemType == E_ITEM_SHEARS) && (!m_IsSheared)) if ((a_Player.GetEquippedItem().m_ItemType == E_ITEM_SHEARS) && (!m_IsSheared))
@ -46,7 +47,8 @@ void cSheep::OnRightClicked(cPlayer & a_Player)
} }
cItems Drops; cItems Drops;
Drops.push_back(cItem(E_BLOCK_WOOL, 4, m_WoolColor)); int NumDrops = m_World->GetTickRandomNumber(2) + 1;
Drops.push_back(cItem(E_BLOCK_WOOL, NumDrops, m_WoolColor));
m_World->SpawnItemPickups(Drops, GetPosX(), GetPosY(), GetPosZ(), 10); m_World->SpawnItemPickups(Drops, GetPosX(), GetPosY(), GetPosZ(), 10);
} }
} }
@ -54,3 +56,4 @@ void cSheep::OnRightClicked(cPlayer & a_Player)

View File

@ -55,18 +55,18 @@ cMonsterConfig::~cMonsterConfig()
void cMonsterConfig::Initialize() void cMonsterConfig::Initialize()
{ {
cIniFile MonstersIniFile("monsters.ini"); cIniFile MonstersIniFile;
if (!MonstersIniFile.ReadFile()) if (!MonstersIniFile.ReadFile("monsters.ini"))
{ {
LOGWARNING("%s: Cannot read monsters.ini file, monster attributes not available", __FUNCTION__); LOGWARNING("%s: Cannot read monsters.ini file, monster attributes not available", __FUNCTION__);
return; return;
} }
for (int i = (int)MonstersIniFile.NumKeys(); i >= 0; i--) for (int i = (int)MonstersIniFile.GetNumKeys(); i >= 0; i--)
{ {
sAttributesStruct Attributes; sAttributesStruct Attributes;
AString Name = MonstersIniFile.KeyName(i); AString Name = MonstersIniFile.GetKeyName(i);
Attributes.m_Name = Name; Attributes.m_Name = Name;
Attributes.m_AttackDamage = MonstersIniFile.GetValueF(Name, "AttackDamage", 0); Attributes.m_AttackDamage = MonstersIniFile.GetValueF(Name, "AttackDamage", 0);
Attributes.m_AttackRange = MonstersIniFile.GetValueF(Name, "AttackRange", 0); Attributes.m_AttackRange = MonstersIniFile.GetValueF(Name, "AttackRange", 0);

View File

@ -103,8 +103,8 @@ void cPluginManager::ReloadPluginsNow(void)
cServer::BindBuiltInConsoleCommands(); cServer::BindBuiltInConsoleCommands();
cIniFile IniFile("settings.ini"); cIniFile IniFile;
if (!IniFile.ReadFile()) if (!IniFile.ReadFile("settings.ini"))
{ {
LOGWARNING("cPluginManager: Can't find settings.ini, so can't load any plugins."); LOGWARNING("cPluginManager: Can't find settings.ini, so can't load any plugins.");
} }

View File

@ -963,7 +963,7 @@ void cProtocol125::SendWholeInventory(const cWindow & a_Window)
void cProtocol125::SendWindowClose(const cWindow & a_Window) void cProtocol125::SendWindowClose(const cWindow & a_Window)
{ {
if (a_Window.GetWindowType() == cWindow::Inventory) if (a_Window.GetWindowType() == cWindow::wtInventory)
{ {
// Do not send inventory-window-close // Do not send inventory-window-close
return; return;

View File

@ -116,8 +116,8 @@ void cRoot::Start(void)
m_Server = new cServer(); m_Server = new cServer();
LOG("Reading server config..."); LOG("Reading server config...");
cIniFile IniFile("settings.ini"); cIniFile IniFile;
if (!IniFile.ReadFile()) if (!IniFile.ReadFile("settings.ini"))
{ {
LOGWARNING("settings.ini inaccessible, all settings are reset to default values"); LOGWARNING("settings.ini inaccessible, all settings are reset to default values");
} }
@ -138,7 +138,6 @@ void cRoot::Start(void)
LOGERROR("Failure starting server, aborting..."); LOGERROR("Failure starting server, aborting...");
return; return;
} }
IniFile.WriteFile();
m_WebAdmin = new cWebAdmin(); m_WebAdmin = new cWebAdmin();
m_WebAdmin->Init(); m_WebAdmin->Init();
@ -149,7 +148,7 @@ void cRoot::Start(void)
m_FurnaceRecipe = new cFurnaceRecipe(); m_FurnaceRecipe = new cFurnaceRecipe();
LOGD("Loading worlds..."); LOGD("Loading worlds...");
LoadWorlds(); LoadWorlds(IniFile);
LOGD("Loading plugin manager..."); LOGD("Loading plugin manager...");
m_PluginManager = new cPluginManager(); m_PluginManager = new cPluginManager();
@ -160,8 +159,10 @@ void cRoot::Start(void)
// This sets stuff in motion // This sets stuff in motion
LOGD("Starting Authenticator..."); LOGD("Starting Authenticator...");
m_Authenticator.Start(); m_Authenticator.Start(IniFile);
IniFile.WriteFile("settings.ini");
LOGD("Starting worlds..."); LOGD("Starting worlds...");
StartWorlds(); StartWorlds();
@ -245,10 +246,8 @@ void cRoot::LoadGlobalSettings()
void cRoot::LoadWorlds(void) void cRoot::LoadWorlds(cIniFile & IniFile)
{ {
cIniFile IniFile("settings.ini"); IniFile.ReadFile();
// First get the default world // First get the default world
AString DefaultWorldName = IniFile.GetValueSet("Worlds", "DefaultWorld", "world"); AString DefaultWorldName = IniFile.GetValueSet("Worlds", "DefaultWorld", "world");
m_pDefaultWorld = new cWorld( DefaultWorldName.c_str() ); m_pDefaultWorld = new cWorld( DefaultWorldName.c_str() );

View File

@ -162,7 +162,7 @@ private:
void LoadGlobalSettings(); void LoadGlobalSettings();
/// Loads the worlds from settings.ini, creates the worldmap /// Loads the worlds from settings.ini, creates the worldmap
void LoadWorlds(void); void LoadWorlds(cIniFile & IniFile);
/// Starts each world's life /// Starts each world's life
void StartWorlds(void); void StartWorlds(void);

View File

@ -559,7 +559,7 @@ cSlotAreaInventoryBase::cSlotAreaInventoryBase(int a_NumSlots, int a_SlotOffset,
void cSlotAreaInventoryBase::Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem) void cSlotAreaInventoryBase::Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem)
{ {
if ((a_Player.GetGameMode() == eGameMode_Creative) && (m_ParentWindow.GetWindowType() == cWindow::Inventory)) if (a_Player.IsGameModeCreative() && (m_ParentWindow.GetWindowType() == cWindow::wtInventory))
{ {
// Creative inventory must treat a_ClickedItem as a DraggedItem instead, replacing the inventory slot with it // Creative inventory must treat a_ClickedItem as a DraggedItem instead, replacing the inventory slot with it
SetSlot(a_SlotNum, a_Player, a_ClickedItem); SetSlot(a_SlotNum, a_Player, a_ClickedItem);
@ -793,7 +793,7 @@ void cSlotAreaTemporary::TossItems(cPlayer & a_Player, int a_Begin, int a_End)
double vX = 0, vY = 0, vZ = 0; double vX = 0, vY = 0, vZ = 0;
EulerToVector(-a_Player.GetRotation(), a_Player.GetPitch(), vZ, vX, vY); EulerToVector(-a_Player.GetRotation(), a_Player.GetPitch(), vZ, vX, vY);
vY = -vY * 2 + 1.f; vY = -vY * 2 + 1.f;
a_Player.GetWorld()->SpawnItemPickups(Drops, a_Player.GetPosX(), a_Player.GetPosY() + 1.6f, a_Player.GetPosZ(), vX * 3, vY * 3, vZ * 3); a_Player.GetWorld()->SpawnItemPickups(Drops, a_Player.GetPosX(), a_Player.GetPosY() + 1.6f, a_Player.GetPosZ(), vX * 3, vY * 3, vZ * 3, true); // 'true' because player created
} }

View File

@ -23,7 +23,7 @@ char cWindow::m_WindowIDCounter = 1;
cWindow::cWindow(cWindow::WindowType a_WindowType, const AString & a_WindowTitle) : cWindow::cWindow(WindowType a_WindowType, const AString & a_WindowTitle) :
m_WindowID((++m_WindowIDCounter) % 127), m_WindowID((++m_WindowIDCounter) % 127),
m_WindowType(a_WindowType), m_WindowType(a_WindowType),
m_WindowTitle(a_WindowTitle), m_WindowTitle(a_WindowTitle),
@ -31,7 +31,7 @@ cWindow::cWindow(cWindow::WindowType a_WindowType, const AString & a_WindowTitle
m_IsDestroyed(false), m_IsDestroyed(false),
m_ShouldDistributeToHotbarFirst(true) m_ShouldDistributeToHotbarFirst(true)
{ {
if (a_WindowType == Inventory) if (a_WindowType == wtInventory)
{ {
m_WindowID = 0; m_WindowID = 0;
} }
@ -277,7 +277,7 @@ bool cWindow::ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse)
m_OpenedBy.remove(&a_Player); m_OpenedBy.remove(&a_Player);
if ((m_WindowType != Inventory) && m_OpenedBy.empty()) if ((m_WindowType != wtInventory) && m_OpenedBy.empty())
{ {
Destroy(); Destroy();
} }
@ -703,7 +703,7 @@ void cWindow::SetProperty(int a_Property, int a_Value, cPlayer & a_Player)
// cInventoryWindow: // cInventoryWindow:
cInventoryWindow::cInventoryWindow(cPlayer & a_Player) : cInventoryWindow::cInventoryWindow(cPlayer & a_Player) :
cWindow(cWindow::Inventory, "Inventory"), cWindow(wtInventory, "Inventory"),
m_Player(a_Player) m_Player(a_Player)
{ {
m_SlotAreas.push_back(new cSlotAreaCrafting(2, *this)); // The creative inventory doesn't display it, but it's still counted into slot numbers m_SlotAreas.push_back(new cSlotAreaCrafting(2, *this)); // The creative inventory doesn't display it, but it's still counted into slot numbers
@ -720,7 +720,7 @@ cInventoryWindow::cInventoryWindow(cPlayer & a_Player) :
// cCraftingWindow: // cCraftingWindow:
cCraftingWindow::cCraftingWindow(int a_BlockX, int a_BlockY, int a_BlockZ) : cCraftingWindow::cCraftingWindow(int a_BlockX, int a_BlockY, int a_BlockZ) :
cWindow(cWindow::Workbench, "Crafting Table") cWindow(wtWorkbench, "Crafting Table")
{ {
m_SlotAreas.push_back(new cSlotAreaCrafting(3, *this)); m_SlotAreas.push_back(new cSlotAreaCrafting(3, *this));
m_SlotAreas.push_back(new cSlotAreaInventory(*this)); m_SlotAreas.push_back(new cSlotAreaInventory(*this));
@ -735,7 +735,7 @@ cCraftingWindow::cCraftingWindow(int a_BlockX, int a_BlockY, int a_BlockZ) :
// cChestWindow: // cChestWindow:
cChestWindow::cChestWindow(cChestEntity * a_Chest) : cChestWindow::cChestWindow(cChestEntity * a_Chest) :
cWindow(cWindow::Chest, "Chest"), cWindow(wtChest, "Chest"),
m_World(a_Chest->GetWorld()), m_World(a_Chest->GetWorld()),
m_BlockX(a_Chest->GetPosX()), m_BlockX(a_Chest->GetPosX()),
m_BlockY(a_Chest->GetPosY()), m_BlockY(a_Chest->GetPosY()),
@ -757,7 +757,7 @@ cChestWindow::cChestWindow(cChestEntity * a_Chest) :
cChestWindow::cChestWindow(cChestEntity * a_PrimaryChest, cChestEntity * a_SecondaryChest) : cChestWindow::cChestWindow(cChestEntity * a_PrimaryChest, cChestEntity * a_SecondaryChest) :
cWindow(cWindow::Chest, "Double Chest"), cWindow(wtChest, "Double Chest"),
m_World(a_PrimaryChest->GetWorld()), m_World(a_PrimaryChest->GetWorld()),
m_BlockX(a_PrimaryChest->GetPosX()), m_BlockX(a_PrimaryChest->GetPosX()),
m_BlockY(a_PrimaryChest->GetPosY()), m_BlockY(a_PrimaryChest->GetPosY()),
@ -796,7 +796,7 @@ cChestWindow::~cChestWindow()
// cDropSpenserWindow: // cDropSpenserWindow:
cDropSpenserWindow::cDropSpenserWindow(int a_BlockX, int a_BlockY, int a_BlockZ, cDropSpenserEntity * a_DropSpenser) : cDropSpenserWindow::cDropSpenserWindow(int a_BlockX, int a_BlockY, int a_BlockZ, cDropSpenserEntity * a_DropSpenser) :
cWindow(cWindow::DropSpenser, "Dropspenser") cWindow(wtDropSpenser, "Dropspenser")
{ {
m_ShouldDistributeToHotbarFirst = false; m_ShouldDistributeToHotbarFirst = false;
m_SlotAreas.push_back(new cSlotAreaItemGrid(a_DropSpenser->GetContents(), *this)); m_SlotAreas.push_back(new cSlotAreaItemGrid(a_DropSpenser->GetContents(), *this));
@ -812,7 +812,7 @@ cDropSpenserWindow::cDropSpenserWindow(int a_BlockX, int a_BlockY, int a_BlockZ,
// cHopperWindow: // cHopperWindow:
cHopperWindow::cHopperWindow(int a_BlockX, int a_BlockY, int a_BlockZ, cHopperEntity * a_Hopper) : cHopperWindow::cHopperWindow(int a_BlockX, int a_BlockY, int a_BlockZ, cHopperEntity * a_Hopper) :
super(cWindow::Hopper, "Hopper") super(wtHopper, "Hopper")
{ {
m_ShouldDistributeToHotbarFirst = false; m_ShouldDistributeToHotbarFirst = false;
m_SlotAreas.push_back(new cSlotAreaItemGrid(a_Hopper->GetContents(), *this)); m_SlotAreas.push_back(new cSlotAreaItemGrid(a_Hopper->GetContents(), *this));
@ -828,7 +828,7 @@ cHopperWindow::cHopperWindow(int a_BlockX, int a_BlockY, int a_BlockZ, cHopperEn
// cFurnaceWindow: // cFurnaceWindow:
cFurnaceWindow::cFurnaceWindow(int a_BlockX, int a_BlockY, int a_BlockZ, cFurnaceEntity * a_Furnace) : cFurnaceWindow::cFurnaceWindow(int a_BlockX, int a_BlockY, int a_BlockZ, cFurnaceEntity * a_Furnace) :
cWindow(cWindow::Furnace, "Furnace") cWindow(wtFurnace, "Furnace")
{ {
m_ShouldDistributeToHotbarFirst = false; m_ShouldDistributeToHotbarFirst = false;
m_SlotAreas.push_back(new cSlotAreaFurnace(a_Furnace, *this)); m_SlotAreas.push_back(new cSlotAreaFurnace(a_Furnace, *this));

View File

@ -49,17 +49,17 @@ class cWindow
public: public:
enum WindowType enum WindowType
{ {
Inventory = -1, // This value is never actually sent to a client wtInventory = -1, // This value is never actually sent to a client
Chest = 0, wtChest = 0,
Workbench = 1, wtWorkbench = 1,
Furnace = 2, wtFurnace = 2,
DropSpenser = 3, // Dropper or Dispenser wtDropSpenser = 3, // Dropper or Dispenser
Enchantment = 4, wtEnchantment = 4,
Brewery = 5, wtBrewery = 5,
NPCTrade = 6, wtNPCTrade = 6,
Beacon = 7, wtBeacon = 7,
Anvil = 8, wtAnvil = 8,
Hopper = 9, wtHopper = 9,
}; };
// tolua_end // tolua_end

View File

@ -44,8 +44,7 @@ public:
cWebAdmin::cWebAdmin(void) : cWebAdmin::cWebAdmin(void) :
m_IsInitialized(false), m_IsInitialized(false),
m_TemplateScript("<webadmin_template>"), m_TemplateScript("<webadmin_template>")
m_IniFile("webadmin.ini")
{ {
} }
@ -86,19 +85,19 @@ void cWebAdmin::RemovePlugin( cWebPlugin * a_Plugin )
bool cWebAdmin::Init(void) bool cWebAdmin::Init(void)
{ {
if (!m_IniFile.ReadFile()) if (!m_IniFile.ReadFile("webadmin.ini"))
{ {
return false; return false;
} }
LOG("Initialising WebAdmin...");
if (!m_IniFile.GetValueSetB("WebAdmin", "Enabled", true)) if (!m_IniFile.GetValueSetB("WebAdmin", "Enabled", true))
{ {
// WebAdmin is disabled, bail out faking a success // WebAdmin is disabled, bail out faking a success
return true; return true;
} }
LOG("Initialising WebAdmin...");
AString PortsIPv4 = m_IniFile.GetValueSet("WebAdmin", "Port", "8080"); AString PortsIPv4 = m_IniFile.GetValueSet("WebAdmin", "Port", "8080");
AString PortsIPv6 = m_IniFile.GetValueSet("WebAdmin", "PortsIPv6", ""); AString PortsIPv6 = m_IniFile.GetValueSet("WebAdmin", "PortsIPv6", "");

View File

@ -444,8 +444,8 @@ void cWorld::Start(void)
m_SpawnZ = (double)((m_TickRand.randInt() % 1000) - 500); m_SpawnZ = (double)((m_TickRand.randInt() % 1000) - 500);
m_GameMode = eGameMode_Creative; m_GameMode = eGameMode_Creative;
cIniFile IniFile(m_IniFileName); cIniFile IniFile;
if (!IniFile.ReadFile()) if (!IniFile.ReadFile(m_IniFileName))
{ {
LOGWARNING("Cannot read world settings from \"%s\", defaults will be used.", m_IniFileName.c_str()); LOGWARNING("Cannot read world settings from \"%s\", defaults will be used.", m_IniFileName.c_str());
} }
@ -555,7 +555,7 @@ void cWorld::Start(void)
// Save any changes that the defaults may have done to the ini file: // Save any changes that the defaults may have done to the ini file:
if (!IniFile.WriteFile()) if (!IniFile.WriteFile(m_IniFileName))
{ {
LOGWARNING("Could not write world config to %s", m_IniFileName.c_str()); LOGWARNING("Could not write world config to %s", m_IniFileName.c_str());
} }
@ -755,9 +755,9 @@ void cWorld::TickMobs(float a_Dt)
for (int i = 0; i < ARRAYCOUNT(AllFamilies); i++) for (int i = 0; i < ARRAYCOUNT(AllFamilies); i++)
{ {
cMonster::eFamily Family = AllFamilies[i]; cMonster::eFamily Family = AllFamilies[i];
int spawnrate = cMonster::GetSpawnRate(Family); int SpawnDelay = cMonster::GetSpawnDelay(Family);
if ( if (
(m_LastSpawnMonster[Family] > m_WorldAge - spawnrate) || // Not reached the needed tiks before the next round (m_LastSpawnMonster[Family] > m_WorldAge - SpawnDelay) || // Not reached the needed ticks before the next round
MobCensus.IsCapped(Family) MobCensus.IsCapped(Family)
) )
{ {
@ -1470,7 +1470,7 @@ bool cWorld::WriteBlockArea(cBlockArea & a_Area, int a_MinBlockX, int a_MinBlock
void cWorld::SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double a_BlockY, double a_BlockZ, double a_FlyAwaySpeed) void cWorld::SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double a_BlockY, double a_BlockZ, double a_FlyAwaySpeed, bool IsPlayerCreated)
{ {
MTRand r1; MTRand r1;
a_FlyAwaySpeed /= 1000; // Pre-divide, so that we don't have to divide each time inside the loop a_FlyAwaySpeed /= 1000; // Pre-divide, so that we don't have to divide each time inside the loop
@ -1482,7 +1482,7 @@ void cWorld::SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double
cPickup * Pickup = new cPickup( cPickup * Pickup = new cPickup(
a_BlockX, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ,
*itr, SpeedX, SpeedY, SpeedZ *itr, IsPlayerCreated, SpeedX, SpeedY, SpeedZ
); );
Pickup->Initialize(this); Pickup->Initialize(this);
} }
@ -1492,13 +1492,13 @@ void cWorld::SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double
void cWorld::SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double a_BlockY, double a_BlockZ, double a_SpeedX, double a_SpeedY, double a_SpeedZ) void cWorld::SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double a_BlockY, double a_BlockZ, double a_SpeedX, double a_SpeedY, double a_SpeedZ, bool IsPlayerCreated)
{ {
for (cItems::const_iterator itr = a_Pickups.begin(); itr != a_Pickups.end(); ++itr) for (cItems::const_iterator itr = a_Pickups.begin(); itr != a_Pickups.end(); ++itr)
{ {
cPickup * Pickup = new cPickup( cPickup * Pickup = new cPickup(
a_BlockX, a_BlockY, a_BlockZ, a_BlockX, a_BlockY, a_BlockZ,
*itr, (float)a_SpeedX, (float)a_SpeedY, (float)a_SpeedZ *itr, IsPlayerCreated, (float)a_SpeedX, (float)a_SpeedY, (float)a_SpeedZ
); );
Pickup->Initialize(this); Pickup->Initialize(this);
} }

View File

@ -348,10 +348,10 @@ public:
// tolua_begin // tolua_begin
/// Spawns item pickups for each item in the list. May compress pickups if too many entities: /// Spawns item pickups for each item in the list. May compress pickups if too many entities:
void SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double a_BlockY, double a_BlockZ, double a_FlyAwaySpeed = 1.0); void SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double a_BlockY, double a_BlockZ, double a_FlyAwaySpeed = 1.0, bool IsPlayerCreated = false);
/// Spawns item pickups for each item in the list. May compress pickups if too many entities. All pickups get the speed specified: /// Spawns item pickups for each item in the list. May compress pickups if too many entities. All pickups get the speed specified:
void SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double a_BlockY, double a_BlockZ, double a_SpeedX, double a_SpeedY, double a_SpeedZ); void SpawnItemPickups(const cItems & a_Pickups, double a_BlockX, double a_BlockY, double a_BlockZ, double a_SpeedX, double a_SpeedY, double a_SpeedZ, bool IsPlayerCreated = false);
/// Spawns a new primed TNT entity at the specified block coords and specified fuse duration. Initial velocity is given based on the relative coefficient provided /// Spawns a new primed TNT entity at the specified block coords and specified fuse duration. Initial velocity is given based on the relative coefficient provided
void SpawnPrimedTNT(double a_X, double a_Y, double a_Z, double a_FuseTimeInSec, double a_InitialVelocityCoeff = 1); void SpawnPrimedTNT(double a_X, double a_Y, double a_Z, double a_FuseTimeInSec, double a_InitialVelocityCoeff = 1);

View File

@ -1123,7 +1123,7 @@ void cWSSAnvil::LoadPickupFromNBT(cEntityList & a_Entities, const cParsedNBT & a
{ {
return; return;
} }
std::auto_ptr<cPickup> Pickup(new cPickup(0, 0, 0, Item)); std::auto_ptr<cPickup> Pickup(new cPickup(0, 0, 0, Item, false)); // Pickup delay doesn't matter, just say false
if (!LoadEntityBaseFromNBT(*Pickup.get(), a_NBT, a_TagIdx)) if (!LoadEntityBaseFromNBT(*Pickup.get(), a_NBT, a_TagIdx))
{ {
return; return;