diff --git a/.gitignore b/.gitignore
index fcf26d07..63c18adb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,3 +6,4 @@ world/players
world/whitelist.sqlite
world/world/stats/Pixowl.json
goproxy/goproxy
+dockercraft
diff --git a/world/Plugins/Docker/config.lua b/Docker/config.lua
similarity index 100%
rename from world/Plugins/Docker/config.lua
rename to Docker/config.lua
diff --git a/Docker/container.lua b/Docker/container.lua
new file mode 100644
index 00000000..afc5e722
--- /dev/null
+++ b/Docker/container.lua
@@ -0,0 +1,225 @@
+-- Container object is the representation of a Docker
+-- container in the Minecraft world
+
+-- constant variables
+CONTAINER_CREATED = 0
+CONTAINER_RUNNING = 1
+CONTAINER_STOPPED = 2
+
+-- NewContainer returns a Container object,
+-- representation of a Docker container in
+-- the Minecraft world
+function NewContainer()
+ c = {
+ displayed = false,
+ x = 0,
+ z = 0,
+ name="",
+ id="",
+ imageRepo="",
+ imageTag="",
+ running=false,
+ init=Container.init,
+ setInfos=Container.setInfos,
+ destroy=Container.destroy,
+ display=Container.display,
+ updateMemSign=Container.updateMemSign,
+ updateCPUSign=Container.updateCPUSign,
+ addGround=Container.addGround
+ }
+ return c
+end
+
+Container = {displayed = false, x = 0, z = 0, name="",id="",imageRepo="",imageTag="",running=false}
+
+-- Container:init sets Container's position
+function Container:init(x,z)
+ self.x = x
+ self.z = z
+ self.displayed = false
+end
+
+-- Container:setInfos sets Container's id, name, imageRepo,
+-- image tag and running state
+function Container:setInfos(id,name,imageRepo,imageTag,running)
+ self.id = id
+ self.name = name
+ self.imageRepo = imageRepo
+ self.imageTag = imageTag
+ self.running = running
+end
+
+-- Container:destroy removes all blocks of the
+-- container, it won't be visible on the map anymore
+function Container:destroy(running)
+ local X = self.x+2
+ local Y = GROUND_LEVEL+2
+ local Z = self.z+2
+ LOG("Exploding at X:" .. X .. " Y:" .. Y .. " Z:" .. Z)
+ local World = cRoot:Get():GetDefaultWorld()
+ World:BroadcastSoundEffect("random.explode", X, Y, Z, 1, 1)
+ World:BroadcastParticleEffect("hugeexplosion",X, Y, Z, 0, 0, 0, 1, 1)
+
+ -- if a block is removed before it's button/lever/sign, that object will drop
+ -- and the player can collect it. Remove these first
+
+ -- lever
+ digBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+1)
+ -- signs
+ digBlock(UpdateQueue,self.x+3,GROUND_LEVEL+2,self.z-1)
+ digBlock(UpdateQueue,self.x,GROUND_LEVEL+2,self.z-1)
+ digBlock(UpdateQueue,self.x+1,GROUND_LEVEL+2,self.z-1)
+ -- torch
+ digBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+1)
+ --button
+ digBlock(UpdateQueue,self.x+2,GROUND_LEVEL+3,self.z+2)
+
+ -- rest of the blocks
+ for py = GROUND_LEVEL+1, GROUND_LEVEL+4
+ do
+ for px=self.x-1, self.x+4
+ do
+ for pz=self.z-1, self.z+5
+ do
+ digBlock(UpdateQueue,px,py,pz)
+ end
+ end
+ end
+end
+
+-- Container:display displays all Container's blocks
+-- Blocks will be blue if the container is running,
+-- orange otherwise.
+function Container:display(running)
+
+ local metaPrimaryColor = E_META_WOOL_LIGHTBLUE
+ local metaSecondaryColor = E_META_WOOL_BLUE
+
+ if running == false
+ then
+ metaPrimaryColor = E_META_WOOL_ORANGE
+ metaSecondaryColor = E_META_WOOL_RED
+ end
+
+ self.displayed = true
+
+ for px=self.x, self.x+3
+ do
+ for pz=self.z, self.z+4
+ do
+ setBlock(UpdateQueue,px,GROUND_LEVEL + 1,pz,E_BLOCK_WOOL,metaPrimaryColor)
+ end
+ end
+
+ for py = GROUND_LEVEL+2, GROUND_LEVEL+3
+ do
+ setBlock(UpdateQueue,self.x+1,py,self.z,E_BLOCK_WOOL,metaPrimaryColor)
+
+ -- leave empty space for the door
+ -- setBlock(UpdateQueue,self.x+2,py,self.z,E_BLOCK_WOOL,metaPrimaryColor)
+
+ setBlock(UpdateQueue,self.x,py,self.z,E_BLOCK_WOOL,metaPrimaryColor)
+ setBlock(UpdateQueue,self.x+3,py,self.z,E_BLOCK_WOOL,metaPrimaryColor)
+
+ setBlock(UpdateQueue,self.x,py,self.z+1,E_BLOCK_WOOL,metaSecondaryColor)
+ setBlock(UpdateQueue,self.x+3,py,self.z+1,E_BLOCK_WOOL,metaSecondaryColor)
+
+ setBlock(UpdateQueue,self.x,py,self.z+2,E_BLOCK_WOOL,metaPrimaryColor)
+ setBlock(UpdateQueue,self.x+3,py,self.z+2,E_BLOCK_WOOL,metaPrimaryColor)
+
+ setBlock(UpdateQueue,self.x,py,self.z+3,E_BLOCK_WOOL,metaSecondaryColor)
+ setBlock(UpdateQueue,self.x+3,py,self.z+3,E_BLOCK_WOOL,metaSecondaryColor)
+
+ setBlock(UpdateQueue,self.x,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor)
+ setBlock(UpdateQueue,self.x+3,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor)
+
+ setBlock(UpdateQueue,self.x+1,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor)
+ setBlock(UpdateQueue,self.x+2,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor)
+ end
+
+ -- torch
+ setBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+3,E_BLOCK_TORCH,E_META_TORCH_ZP)
+
+ -- start / stop lever
+ setBlock(UpdateQueue,self.x+1,GROUND_LEVEL + 3,self.z + 2,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_XP)
+ updateSign(UpdateQueue,self.x+1,GROUND_LEVEL + 3,self.z + 2,"","START/STOP","---->","",2)
+
+
+ if running
+ then
+ setBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+1,E_BLOCK_LEVER,1)
+ else
+ setBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+1,E_BLOCK_LEVER,9)
+ end
+
+
+ -- remove button
+
+ setBlock(UpdateQueue,self.x+2,GROUND_LEVEL + 3,self.z + 2,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_XM)
+ updateSign(UpdateQueue,self.x+2,GROUND_LEVEL + 3,self.z + 2,"","REMOVE","---->","",2)
+
+ setBlock(UpdateQueue,self.x+2,GROUND_LEVEL+3,self.z+3,E_BLOCK_STONE_BUTTON,E_BLOCK_BUTTON_XM)
+
+
+ -- door
+ -- Cuberite bug with Minecraft 1.8 apparently, doors are not displayed correctly
+ -- setBlock(UpdateQueue,self.x+2,GROUND_LEVEL+2,self.z,E_BLOCK_WOODEN_DOOR,E_META_CHEST_FACING_ZM)
+
+
+ for px=self.x, self.x+3
+ do
+ for pz=self.z, self.z+4
+ do
+ setBlock(UpdateQueue,px,GROUND_LEVEL + 4,pz,E_BLOCK_WOOL,metaPrimaryColor)
+ end
+ end
+
+ setBlock(UpdateQueue,self.x+3,GROUND_LEVEL + 2,self.z - 1,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_ZM)
+ updateSign(UpdateQueue,self.x+3,GROUND_LEVEL + 2,self.z - 1,string.sub(self.id,1,8),self.name,self.imageRepo,self.imageTag,2)
+
+ -- Mem sign
+ setBlock(UpdateQueue,self.x,GROUND_LEVEL + 2,self.z - 1,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_ZM)
+
+ -- CPU sign
+ setBlock(UpdateQueue,self.x+1,GROUND_LEVEL + 2,self.z - 1,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_ZM)
+end
+
+
+-- Container:updateMemSign updates the mem usage
+-- value displayed on Container's sign
+function Container:updateMemSign(s)
+ updateSign(UpdateQueue,self.x,GROUND_LEVEL + 2,self.z - 1,"Mem usage","",s,"")
+end
+
+-- Container:updateCPUSign updates the mem usage
+-- value displayed on Container's sign
+function Container:updateCPUSign(s)
+ updateSign(UpdateQueue,self.x+1,GROUND_LEVEL + 2,self.z - 1,"CPU usage","",s,"")
+end
+
+-- Container:addGround creates ground blocks
+-- necessary to display the container
+function Container:addGround()
+ local y = GROUND_LEVEL
+ local max_x = GROUND_MAX_X
+
+ if GROUND_MIN_X > self.x - 2
+ then
+ max_x = GROUND_MIN_X
+ GROUND_MIN_X = self.x - 2
+ min_x = GROUND_MIN_X
+ end
+
+ local min_x = GROUND_MIN_X
+ for x= min_x, max_x
+ do
+ for z=GROUND_MIN_Z,GROUND_MAX_Z
+ do
+ setBlock(UpdateQueue,x,y,z,E_BLOCK_WOOL,E_META_WOOL_WHITE)
+ for sky=y+1,y+6
+ do
+ setBlock(UpdateQueue,x,sky,z,E_BLOCK_AIR,0)
+ end
+ end
+ end
+end
diff --git a/Docker/docker.lua b/Docker/docker.lua
new file mode 100644
index 00000000..3c88a82f
--- /dev/null
+++ b/Docker/docker.lua
@@ -0,0 +1,293 @@
+----------------------------------------
+-- GLOBALS
+----------------------------------------
+
+-- queue containing the updates that need to be applied to the minecraft world
+UpdateQueue = nil
+-- array of container objects
+Containers = {}
+--
+SignsToUpdate = {}
+-- as a lua array cannot contain nil values, we store references to this object
+-- in the "Containers" array to indicate that there is no container at an index
+EmptyContainerSpace = {}
+
+----------------------------------------
+-- FUNCTIONS
+----------------------------------------
+
+-- Tick is triggered by cPluginManager.HOOK_TICK
+function Tick(TimeDelta)
+ UpdateQueue:update(MAX_BLOCK_UPDATE_PER_TICK)
+end
+
+-- Plugin initialization
+function Initialize(Plugin)
+ Plugin:SetName("Docker")
+ Plugin:SetVersion(1)
+
+ UpdateQueue = NewUpdateQueue()
+
+ -- Hooks
+
+ cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_JOINED, PlayerJoined);
+ cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_USING_BLOCK, PlayerUsingBlock);
+ cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_FOOD_LEVEL_CHANGE, OnPlayerFoodLevelChange);
+ cPluginManager:AddHook(cPluginManager.HOOK_TAKE_DAMAGE, OnTakeDamage);
+ cPluginManager:AddHook(cPluginManager.HOOK_WEATHER_CHANGING, OnWeatherChanging);
+ cPluginManager:AddHook(cPluginManager.HOOK_SERVER_PING, OnServerPing);
+ cPluginManager:AddHook(cPluginManager.HOOK_TICK, Tick);
+
+ -- Command Bindings
+
+ cPluginManager.BindCommand("/docker", "*", DockerCommand, " - docker CLI commands")
+
+ -- make all players admin
+ cRankManager:SetDefaultRank("Admin")
+
+ cNetwork:Connect("127.0.0.1",25566,TCP_CLIENT)
+
+ LOG("Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion())
+
+ return true
+end
+
+-- updateStats update CPU and memory usage displayed
+-- on container sign (container identified by id)
+function updateStats(id, mem, cpu)
+ for i=1, table.getn(Containers)
+ do
+ if Containers[i] ~= EmptyContainerSpace and Containers[i].id == id
+ then
+ Containers[i]:updateMemSign(mem)
+ Containers[i]:updateCPUSign(cpu)
+ break
+ end
+ end
+end
+
+-- getStartStopLeverContainer returns the container
+-- id that corresponds to lever at x,y coordinates
+function getStartStopLeverContainer(x, z)
+ for i=1, table.getn(Containers)
+ do
+ if Containers[i] ~= EmptyContainerSpace and x == Containers[i].x + 1 and z == Containers[i].z + 1
+ then
+ return Containers[i].id
+ end
+ end
+ return ""
+end
+
+-- getRemoveButtonContainer returns the container
+-- id and state for the button at x,y coordinates
+function getRemoveButtonContainer(x, z)
+ for i=1, table.getn(Containers)
+ do
+ if Containers[i] ~= EmptyContainerSpace and x == Containers[i].x + 2 and z == Containers[i].z + 3
+ then
+ return Containers[i].id, Containers[i].running
+ end
+ end
+ return "", true
+end
+
+-- destroyContainer looks for the first container having the given id,
+-- removes it from the Minecraft world and from the 'Containers' array
+function destroyContainer(id)
+ LOG("destroyContainer: " .. id)
+ -- loop over the containers and remove the first having the given id
+ for i=1, table.getn(Containers)
+ do
+ if Containers[i] ~= EmptyContainerSpace and Containers[i].id == id
+ then
+ -- remove the container from the world
+ Containers[i]:destroy()
+ -- if the container being removed is the last element of the array
+ -- we reduce the size of the "Container" array, but if it is not,
+ -- we store a reference to the "EmptyContainerSpace" object at the
+ -- same index to indicate this is a free space now.
+ -- We use a reference to this object because it is not possible to
+ -- have 'nil' values in the middle of a lua array.
+ if i == table.getn(Containers)
+ then
+ table.remove(Containers, i)
+ -- we have removed the last element of the array. If the array
+ -- has tailing empty container spaces, we remove them as well.
+ while Containers[table.getn(Containers)] == EmptyContainerSpace
+ do
+ table.remove(Containers, table.getn(Containers))
+ end
+ else
+ Containers[i] = EmptyContainerSpace
+ end
+ -- we removed the container, we can exit the loop
+ break
+ end
+ end
+end
+
+-- updateContainer accepts 3 different states: running, stopped, created
+-- sometimes "start" events arrive before "create" ones
+-- in this case, we just ignore the update
+function updateContainer(id,name,imageRepo,imageTag,state)
+ LOG("Update container with ID: " .. id .. " state: " .. state)
+
+ -- first pass, to see if the container is
+ -- already displayed (maybe with another state)
+ for i=1, table.getn(Containers)
+ do
+ -- if container found with same ID, we update it
+ if Containers[i] ~= EmptyContainerSpace and Containers[i].id == id
+ then
+ Containers[i]:setInfos(id,name,imageRepo,imageTag,state == CONTAINER_RUNNING)
+ Containers[i]:display(state == CONTAINER_RUNNING)
+ LOG("found. updated. now return")
+ return
+ end
+ end
+
+ -- if container isn't already displayed, we see if there's an empty space
+ -- in the world to display the container
+ local x = CONTAINER_START_X
+ local index = -1
+
+ for i=1, table.getn(Containers)
+ do
+ -- use first empty location
+ if Containers[i] == EmptyContainerSpace
+ then
+ LOG("Found empty location: Containers[" .. tostring(i) .. "]")
+ index = i
+ break
+ end
+ x = x + CONTAINER_OFFSET_X
+ end
+
+ local container = NewContainer()
+ container:init(x,CONTAINER_START_Z)
+ container:setInfos(id,name,imageRepo,imageTag,state == CONTAINER_RUNNING)
+ container:addGround()
+ container:display(state == CONTAINER_RUNNING)
+
+ if index == -1
+ then
+ table.insert(Containers, container)
+ else
+ Containers[index] = container
+ end
+end
+
+--
+function PlayerJoined(Player)
+ -- enable flying
+ Player:SetCanFly(true)
+ LOG("player joined")
+end
+
+--
+function PlayerUsingBlock(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ, BlockType, BlockMeta)
+ LOG("Using block: " .. tostring(BlockX) .. "," .. tostring(BlockY) .. "," .. tostring(BlockZ) .. " - " .. tostring(BlockType) .. " - " .. tostring(BlockMeta))
+
+ -- lever: 1->OFF 9->ON (in that orientation)
+ -- lever
+ if BlockType == 69
+ then
+ local containerID = getStartStopLeverContainer(BlockX,BlockZ)
+ LOG("Using lever associated with container ID: " .. containerID)
+
+ if containerID ~= ""
+ then
+ -- stop
+ if BlockMeta == 1
+ then
+ Player:SendMessage("docker stop " .. string.sub(containerID,1,8))
+ SendTCPMessage("docker",{"stop",containerID},0)
+ -- start
+ else
+ Player:SendMessage("docker start " .. string.sub(containerID,1,8))
+ SendTCPMessage("docker",{"start",containerID},0)
+ end
+ else
+ LOG("WARNING: no docker container ID attached to this lever")
+ end
+ end
+
+ -- stone button
+ if BlockType == 77
+ then
+ local containerID, running = getRemoveButtonContainer(BlockX,BlockZ)
+
+ if running
+ then
+ Player:SendMessage("A running container can't be removed.")
+ else
+ Player:SendMessage("docker rm " .. string.sub(containerID,1,8))
+ SendTCPMessage("docker",{"rm",containerID},0)
+ end
+ end
+end
+
+
+function DockerCommand(Split, Player)
+ if table.getn(Split) > 0
+ then
+
+ LOG("Split[1]: " .. Split[1])
+
+ if Split[1] == "/docker"
+ then
+ if table.getn(Split) > 1
+ then
+ if Split[2] == "pull" or Split[2] == "create" or Split[2] == "run" or Split[2] == "stop" or Split[2] == "rm" or Split[2] == "rmi" or Split[2] == "start" or Split[2] == "kill"
+ then
+ -- force detach when running a container
+ if Split[2] == "run"
+ then
+ table.insert(Split,3,"-d")
+ end
+ table.remove(Split,1)
+ SendTCPMessage("docker",Split,0)
+ end
+ end
+ end
+ end
+
+ return true
+end
+
+
+function OnPlayerFoodLevelChange(Player, NewFoodLevel)
+ -- Don't allow the player to get hungry
+ return true, Player, NewFoodLevel
+end
+
+function OnTakeDamage(Receiver, TDI)
+ -- Don't allow the player to take falling or explosion damage
+ if Receiver:GetClass() == 'cPlayer'
+ then
+ if TDI.DamageType == dtFall or TDI.DamageType == dtExplosion then
+ return true, Receiver, TDI
+ end
+ end
+ return false, Receiver, TDI
+end
+
+function OnServerPing(ClientHandle, ServerDescription, OnlinePlayers, MaxPlayers, Favicon)
+ -- Change Server Description
+ local serverDescription = "A Docker client for Minecraft"
+ -- Change favicon
+ if cFile:IsFile("/srv/logo.png") then
+ local FaviconData = cFile:ReadWholeFile("/srv/logo.png")
+ if (FaviconData ~= "") and (FaviconData ~= nil) then
+ Favicon = Base64Encode(FaviconData)
+ end
+ end
+ return false, serverDescription, OnlinePlayers, MaxPlayers, Favicon
+end
+
+-- Make it sunny all the time!
+function OnWeatherChanging(World, Weather)
+ return true, wSunny
+end
+
diff --git a/world/Plugins/Docker/error.lua b/Docker/error.lua
similarity index 68%
rename from world/Plugins/Docker/error.lua
rename to Docker/error.lua
index 06abd83c..02789603 100644
--- a/world/Plugins/Docker/error.lua
+++ b/Docker/error.lua
@@ -1,6 +1,6 @@
-- NewError returns an error object.
-- An error has a code and a message
function NewError(code, message)
- err = {code=code, message=message}
- return err
+ err = {code=code, message=message}
+ return err
end
\ No newline at end of file
diff --git a/world/Plugins/Docker/json.lua b/Docker/json.lua
similarity index 100%
rename from world/Plugins/Docker/json.lua
rename to Docker/json.lua
diff --git a/Docker/log.lua b/Docker/log.lua
new file mode 100644
index 00000000..7a4caff2
--- /dev/null
+++ b/Docker/log.lua
@@ -0,0 +1,19 @@
+
+-- Print contents of `tbl`, with indentation.
+-- `indent` sets the initial level of indentation.
+function logTable (tbl, indent)
+ if not indent then indent = 0 end
+ for k, v in pairs(tbl) do
+ formatting = string.rep(" ", indent) .. k .. ": "
+ if type(v) == "table" then
+ print(formatting)
+ logTable(v, indent+1)
+ elseif type(v) == 'boolean' then
+ print(formatting .. tostring(v))
+ elseif type(v) == 'function' then
+ print(formatting .. '') -- TODO: display the function's name
+ else
+ print(formatting .. v)
+ end
+ end
+end
\ No newline at end of file
diff --git a/Docker/tcpclient.lua b/Docker/tcpclient.lua
new file mode 100644
index 00000000..b6606fb2
--- /dev/null
+++ b/Docker/tcpclient.lua
@@ -0,0 +1,133 @@
+json = require "json"
+
+TCP_CONN = nil
+TCP_DATA = ""
+
+TCP_CLIENT = {
+
+ OnConnected = function (TCPConn)
+ -- The specified link has succeeded in connecting to the remote server.
+ -- Only called if the link is being connected as a client (using cNetwork:Connect() )
+ -- Not used for incoming server links
+ -- All returned values are ignored
+ LOG("tcp client connected")
+ TCP_CONN = TCPConn
+
+ -- list containers
+ LOG("listing containers...")
+ SendTCPMessage("info",{"containers"},0)
+ end,
+
+ OnError = function (TCPConn, ErrorCode, ErrorMsg)
+ -- The specified error has occured on the link
+ -- No other callback will be called for this link from now on
+ -- For a client link being connected, this reports a connection error (destination unreachable etc.)
+ -- It is an Undefined Behavior to send data to a_TCPLink in or after this callback
+ -- All returned values are ignored
+ LOG("tcp client OnError: " .. ErrorCode .. ": " .. ErrorMsg)
+
+ -- retry to establish connection
+ LOG("retry cNetwork:Connect")
+ cNetwork:Connect("127.0.0.1",25566,TCP_CLIENT)
+ end,
+
+ OnReceivedData = function (TCPConn, Data)
+ -- Data has been received on the link
+ -- Will get called whenever there's new data on the link
+ -- a_Data contains the raw received data, as a string
+ -- All returned values are ignored
+ -- LOG("TCP_CLIENT OnReceivedData")
+
+ TCP_DATA = TCP_DATA .. Data
+ local shiftLen = 0
+
+ for message in string.gmatch(TCP_DATA, '([^\n]+\n)') do
+ shiftLen = shiftLen + string.len(message)
+ -- remove \n at the end
+ message = string.sub(message,1,string.len(message)-1)
+ ParseTCPMessage(message)
+ end
+
+ TCP_DATA = string.sub(TCP_DATA,shiftLen+1)
+
+ end,
+
+ OnRemoteClosed = function (TCPConn)
+ -- The remote peer has closed the link
+ -- The link is already closed, any data sent to it now will be lost
+ -- No other callback will be called for this link from now on
+ -- All returned values are ignored
+ LOG("tcp client OnRemoteClosed")
+
+ -- retry to establish connection
+ LOG("retry cNetwork:Connect")
+ cNetwork:Connect("127.0.0.1",25566,TCP_CLIENT)
+ end,
+}
+
+-- SendTCPMessage sends a message over global
+-- tcp connection TCP_CONN. args and id are optional
+-- id stands for the request id.
+function SendTCPMessage(cmd, args, id)
+ if TCP_CONN == nil
+ then
+ LOG("can't send TCP message, TCP_CLIENT not connected")
+ return
+ end
+ local v = {cmd=cmd, args=args, id=id}
+ local msg = json.stringify(v) .. "\n"
+ TCP_CONN:Send(msg)
+end
+
+-- ParseTCPMessage parses a message received from
+-- global tcp connection TCP_CONN
+function ParseTCPMessage(message)
+ local m = json.parse(message)
+ if m.cmd == "event" and table.getn(m.args) > 0 and m.args[1] == "containers"
+ then
+ handleContainerEvent(m.data)
+ end
+end
+
+-- handleContainerEvent handles a container
+-- event TCP message.
+function handleContainerEvent(event)
+
+ event.imageTag = event.imageTag or ""
+ event.imageRepo = event.imageRepo or ""
+ event.name = event.name or ""
+
+ if event.action == "containerInfos"
+ then
+ local state = CONTAINER_STOPPED
+ if event.running then
+ state = CONTAINER_RUNNING
+ end
+ updateContainer(event.id,event.name,event.imageRepo,event.imageTag,state)
+ end
+
+ if event.action == "startContainer"
+ then
+ updateContainer(event.id,event.name,event.imageRepo,event.imageTag,CONTAINER_RUNNING)
+ end
+
+ if event.action == "createContainer"
+ then
+ updateContainer(event.id,event.name,event.imageRepo,event.imageTag,CONTAINER_CREATED)
+ end
+
+ if event.action == "stopContainer"
+ then
+ updateContainer(event.id,event.name,event.imageRepo,event.imageTag,CONTAINER_STOPPED)
+ end
+
+ if event.action == "destroyContainer"
+ then
+ destroyContainer(event.id)
+ end
+
+ if event.action == "stats"
+ then
+ updateStats(event.id,event.ram,event.cpu)
+ end
+end
diff --git a/Docker/update.lua b/Docker/update.lua
new file mode 100644
index 00000000..41bd59be
--- /dev/null
+++ b/Docker/update.lua
@@ -0,0 +1,126 @@
+-- UPDATE OPERATIONS
+-- The following functions can be used to update blocks in the map.
+-- There are 3 update types:
+-- UPDATE_SET: set a block
+-- UPDATE_DIG: remove a block
+-- UPDATE_SIGN: update a sign
+-- Update operations are queued.
+-- An new update queue can be created using NewUpdateQueue()
+
+UPDATE_SET = 0
+UPDATE_DIG = 1
+UPDATE_SIGN = 2
+
+function NewUpdateQueue()
+ queue = {first=0, last=-1, current=nil}
+
+ -- queue.newUpdate creates an update operation and
+ -- inserts it in the queue or returns an error
+ -- in case of UPDATE_SIGN, line 1 to 4 should
+ -- be present in meta parameter.
+ -- the delay is optional and will make sure that
+ -- the update is not triggered before given amount
+ -- of ticks (0 by default)
+ function queue:newUpdate(updateType, x, y, z, blockID, meta, delay)
+ if updateType ~= UPDATE_SET and updateType ~= UPDATE_DIG and updateType ~= UPDATE_SIGN
+ then
+ return NewError(1,"NewUpdate: wrong update type")
+ end
+
+ if delay == nil
+ then
+ delay = 0
+ end
+
+ update = {op=updateType,x=x,y=y,z=z,blockID=blockID,meta=meta,delay=delay}
+
+ -- update.exec executes update operation
+ -- and returns an error if it fails
+ function update:exec()
+ if self.op == UPDATE_SET
+ then
+ cRoot:Get():GetDefaultWorld():SetBlock(self.x,self.y,self.z,self.blockID,self.meta)
+ elseif self.op == UPDATE_DIG
+ then
+ cRoot:Get():GetDefaultWorld():DigBlock(self.x,self.y,self.z)
+ elseif self.op == UPDATE_SIGN
+ then
+ cRoot:Get():GetDefaultWorld():SetSignLines(self.x,self.y,self.z,self.meta.line1,self.meta.line2,self.meta.line3,self.meta.line4)
+ else
+ return NewError(1,"update:exec: unknown update type: " .. tostring(self.op))
+ end
+ end
+
+ self:push(update)
+ end -- ends queue.newUpdate
+
+ -- update triggers updates starting from
+ -- the first one. It stops when the limit
+ -- is reached, of if there are no more
+ -- operations in the queue. It returns
+ -- the amount of updates executed.
+ -- When an update has a delay > 0, the delay
+ -- is decremented, and the number of updates
+ -- executed is not incremented.
+ function queue:update(limit)
+ local n = 0
+ if self.current == nil
+ then
+ self.current = self:pop()
+ end
+ while n < limit and self.current ~= nil
+ do
+ if self.current.delay == 0
+ then
+ err = self.current:exec()
+ if err ~= nil
+ then
+ break
+ end
+ n = n + 1
+ self.current = self:pop()
+ else
+ self.current.delay = self.current.delay - 1
+ end
+ end
+ return n
+ end
+
+ function queue:push(value)
+ local last = self.last + 1
+ self.last = last
+ self[last] = value
+ end
+
+ function queue:pop()
+ local first = self.first
+ if first > self.last then return nil end
+ local value = self[first]
+ self[first] = nil -- to allow garbage collection
+ self.first = first + 1
+ return value
+ end
+
+ return queue
+end
+
+-- setBlock adds an update in given queue to
+-- set a block at x,y,z coordinates
+function setBlock(queue,x,y,z,blockID,meta)
+ queue:newUpdate(UPDATE_SET, x, y, z, blockID, meta)
+end
+
+-- setBlock adds an update in given queue to
+-- remove a block at x,y,z coordinates
+function digBlock(queue,x,y,z)
+ queue:newUpdate(UPDATE_DIG, x, y, z)
+end
+
+-- setBlock adds an update in given queue to
+-- update a sign at x,y,z coordinates with
+-- 4 lines of text
+function updateSign(queue,x,y,z,line1,line2,line3,line4,delay)
+ meta = {line1=line1,line2=line2,line3=line3,line4=line4}
+ queue:newUpdate(UPDATE_SIGN, x, y, z, nil, meta, delay)
+end
+
diff --git a/Dockerfile b/Dockerfile
index 619c6adb..7890ca3e 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,6 +1,7 @@
FROM golang:1.7.1
ENV DOCKER_VERSION 1.12.1
+ENV CUBERITE_BUILD 630
# Copy latest docker client(s)
RUN curl -sSL -o docker.tgz https://get.docker.com/builds/Linux/x86_64/docker-${DOCKER_VERSION}.tgz &&\
@@ -8,22 +9,21 @@ RUN curl -sSL -o docker.tgz https://get.docker.com/builds/Linux/x86_64/docker-${
chmod +x /bin/docker-* &&\
ln -s /bin/docker /bin/docker-${DOCKER_VERSION}
-# Copy Go code and install applications
+# Download Cuberite server (Minecraft C++ server)
+WORKDIR /srv
+RUN curl "https://builds.cuberite.org/job/Cuberite Linux x64 Master/${CUBERITE_BUILD}/artifact/Cuberite.tar.gz" | tar -xzf -
+
+# Copy Dockercraft config and plugin
+COPY ./config /srv/Server
+COPY ./docs/img/logo64x64.png /srv/Server/favicon.png
+COPY ./Docker /srv/Server/Plugins/Docker
+
+# Copy Go code and install
WORKDIR /go/src/github.com/docker/dockercraft
COPY . .
RUN go install
-# Download Cuberite server (Minecraft C++ server)
-# and load up a special empty world for Dockercraft
-WORKDIR /srv
-RUN sh -c "$(wget -qO - https://raw.githubusercontent.com/cuberite/cuberite/master/easyinstall.sh)" && mv Server cuberite_server
-RUN ln -s /srv/cuberite_server/Cuberite /usr/bin/cuberite
-COPY ./world world
-COPY ./docs/img/logo64x64.png logo.png
-
EXPOSE 25565
-COPY ./start.sh start.sh
-
-CMD ["/bin/sh", "/srv/start.sh"]
+ENTRYPOINT ["/srv/Server/start.sh"]
diff --git a/Makefile b/Makefile
index fe7c210e..34a5a921 100644
--- a/Makefile
+++ b/Makefile
@@ -6,6 +6,7 @@ PKG_NAME = github.com/${REPO_OWNER}/${REPO_NAME}
IMAGE = golang:1.7.1
IMAGE_NAME = dockercraft-dev
CONTAINER_NAME = dockercraft-dev-container
+PACKAGES=$(shell go list ./... | grep -v vendor)
all: test
@@ -22,15 +23,15 @@ install-deps:
lint:
@echo "+ $@"
- @test -z "$$(golint ./... | grep -v vendor/ | tee /dev/stderr)"
+ @test -z "$$(golint $(PACKAGES) | tee /dev/stderr)"
fmt:
@echo "+ $@"
- @test -z "$$(gofmt -s -l . | grep -v vendor/ | tee /dev/stderr)"
+ @test -z "$$(gofmt -s -l *.go | tee /dev/stderr)"
vet:
@echo "+ $@"
- @go vet .
+ go vet $(PACKAGES)
build:
@echo "+ $@"
diff --git a/README.md b/README.md
index 29ff1b8f..db73127f 100644
--- a/README.md
+++ b/README.md
@@ -62,6 +62,41 @@ A simple Minecraft Docker client, to visualize and manage Docker containers.

+## Customizing Dockercraft
+
+Do you find the plains too plain?
+If so, you are in luck!
+
+Dockercraft can be customised to use any of the [Biomes](https://github.com/cuberite/cuberite/blob/7f8a4eb7264a12ca2035b4e4d412485e01f309d4/src/BiomeDef.cpp#L17) and [Finishers](https://github.com/cuberite/cuberite/blob/7f8a4eb7264a12ca2035b4e4d412485e01f309d4/src/Generating/ComposableGenerator.cpp#L299) supported by Cuberite!
+
+You can pass these additional arguments to your `docker run` command:
+```
+docker run -t -i -d -p 25565:25565 \
+ -v /var/run/docker.sock:/var/run/docker.sock \
+ --name dockercraft \
+ gaetan/dockercraft
+```
+
+Here are some examples:
+
+**Do you long for the calm of the oceans?**
+
+
+Try `Ocean 50 63`, or for a more frozen alternative, `FrozenOcean 50 63 Ice`
+
+**Or perhaps the heat of the desert?**
+
+
+Then `Desert 63 0 DeadBushes` is what you need
+
+**Are you pining for the... Pines?**
+
+We have you covered. Try `Forest 63 0 Trees`
+
+**Or maybe you are looking for fun and games?**
+
+If so, Welcome to the Jungle. `Jungle 63 0 Trees`
+
## Upcoming features
This is just the beginning for Dockercraft! We should be able to support a lot more Docker features like:
diff --git a/world/motd.txt b/config/motd.txt
similarity index 100%
rename from world/motd.txt
rename to config/motd.txt
diff --git a/world/settings.ini b/config/settings.ini
similarity index 95%
rename from world/settings.ini
rename to config/settings.ini
index 6fb99613..f6dd14c7 100644
--- a/world/settings.ini
+++ b/config/settings.ini
@@ -1,49 +1,48 @@
-; This is the main server configuration
-; Most of the settings here can be configured using the webadmin interface, if enabled in webadmin.ini
-; See: http://wiki.mc-server.org/doku.php?id=configure:settings.ini for further configuration help
-
-[Authentication]
-Authenticate=0
-AllowBungeeCord=0
-Server=sessionserver.mojang.com
-Address=/session/minecraft/hasJoined?username=%USERNAME%&serverId=%SERVERID%
-
-[MojangAPI]
-NameToUUIDServer=api.mojang.com
-NameToUUIDAddress=/profiles/minecraft
-UUIDToProfileServer=sessionserver.mojang.com
-UUIDToProfileAddress=/session/minecraft/profile/%UUID%?unsigned=false
-
-[Server]
-Description=MCServer - in C++!
-MaxPlayers=100
-HardcoreEnabled=0
-AllowMultiLogin=0
-Ports=25565
-DefaultViewDistance=10
-
-[RCON]
-Enabled=0
-
-[PlayerData]
-LoadOfflinePlayerData=0
-LoadNamedPlayerData=1
-
-[Worlds]
-DefaultWorld=world
-
-[Plugins]
-; Plugin=Debuggers
-; Plugin=HookNotify
-; Plugin=ChunkWorx
-; Plugin=APIDump
-Plugin=Core
-Plugin=TransAPI
-Plugin=ChatLog
-Plugin=Docker
-
-
-[DeadlockDetect]
-Enabled=1
-IntervalSec=20
-
+; This is the main server configuration
+; Most of the settings here can be configured using the webadmin interface, if enabled in webadmin.ini
+; See: http://wiki.mc-server.org/doku.php?id=configure:settings.ini for further configuration help
+
+[Authentication]
+Authenticate=0
+AllowBungeeCord=0
+Server=sessionserver.mojang.com
+Address=/session/minecraft/hasJoined?username=%USERNAME%&serverId=%SERVERID%
+
+[MojangAPI]
+NameToUUIDServer=api.mojang.com
+NameToUUIDAddress=/profiles/minecraft
+UUIDToProfileServer=sessionserver.mojang.com
+UUIDToProfileAddress=/session/minecraft/profile/%UUID%?unsigned=false
+
+[Server]
+Description=MCServer - in C++!
+MaxPlayers=100
+HardcoreEnabled=0
+AllowMultiLogin=0
+Ports=25565
+DefaultViewDistance=10
+
+[RCON]
+Enabled=0
+
+[PlayerData]
+LoadOfflinePlayerData=0
+LoadNamedPlayerData=1
+
+[Worlds]
+DefaultWorld=world
+
+[Plugins]
+; Plugin=Debuggers
+; Plugin=HookNotify
+; Plugin=ChunkWorx
+; Plugin=APIDump
+Plugin=Core
+Plugin=TransAPI
+Plugin=ChatLog
+Plugin=Docker
+
+[DeadlockDetect]
+Enabled=1
+IntervalSec=20
+
diff --git a/config/start.sh b/config/start.sh
new file mode 100755
index 00000000..39d5fa7d
--- /dev/null
+++ b/config/start.sh
@@ -0,0 +1,32 @@
+#!/bin/sh
+
+set -e
+
+biome="Plains"
+groundlevel="62"
+sealevel="0"
+finishers=""
+
+if [ -n "$1" ]; then
+ biome="$1"
+fi
+
+if [ -n "$2" ]; then
+ groundlevel="$2"
+fi
+
+if [ -n "$3" ]; then
+ sealevel="$3"
+fi
+
+if [ -n "$4" ]; then
+ finishers="$4"
+fi
+
+sed -i "s/@BIOME@/${biome}/g;s/@GROUNDLEVEL@/${groundlevel}/g;s/@SEALEVEL@/${sealevel}/g;s/@FINISHERS@/${finishers}/g" /srv/Server/world/world.ini
+
+echo Starting Dockercraft
+cd /srv/Server
+dockercraft &
+sleep 5
+./Cuberite
diff --git a/config/world/world.ini b/config/world/world.ini
new file mode 100644
index 00000000..15bfd759
--- /dev/null
+++ b/config/world/world.ini
@@ -0,0 +1,58 @@
+; This is the per-world configuration file, managing settings such as generators, simulators, and spawn points
+
+[General]
+Dimension=Overworld
+IsDaylightCycleEnabled=0
+Gamemode=2
+Weather=0
+TimeInTicks=0
+
+[Broadcasting]
+BroadcastDeathMessages=1
+BroadcastAchievementMessages=1
+
+[SpawnPosition]
+MaxViewDistance=12
+X=0.000000
+Y=65.0
+Z=0.000000
+PregenerateDistance=20
+
+[Storage]
+Schema=Default
+CompressionFactor=6
+
+[Mechanics]
+CommandBlocksEnabled=0
+
+[Generator]
+Generator=Composable
+
+; Generate constant plains biome:
+BiomeGen=Constant
+ConstantBiome=@BIOME@
+SeaLevel=@SEALEVEL@
+
+; Generate the same height everywhere, 3 blocks:
+ShapeGen=HeightMap
+HeightGen=Flat
+FlatHeight=@GROUNDLEVEL@
+
+CompositionGen=Biomal
+
+Finishers=@FINISHERS@
+; Do not generate any structures:
+Structures=
+
+[Monsters]
+AnimalsOn=0
+
+[SpawnProtect]
+ProtectRadius=10
+
+[WorldLimit]
+LimitRadius=0
+
+[Difficulty]
+WorldDifficulty=1
+
diff --git a/dockercraft b/dockercraft
deleted file mode 100755
index 62da11c7..00000000
Binary files a/dockercraft and /dev/null differ
diff --git a/docs/img/desert.png b/docs/img/desert.png
new file mode 100644
index 00000000..a0d08f13
Binary files /dev/null and b/docs/img/desert.png differ
diff --git a/docs/img/forest.png b/docs/img/forest.png
new file mode 100644
index 00000000..8dd29963
Binary files /dev/null and b/docs/img/forest.png differ
diff --git a/docs/img/jungle.png b/docs/img/jungle.png
new file mode 100644
index 00000000..ebb2749d
Binary files /dev/null and b/docs/img/jungle.png differ
diff --git a/docs/img/ocean.png b/docs/img/ocean.png
new file mode 100644
index 00000000..eb705ce8
Binary files /dev/null and b/docs/img/ocean.png differ
diff --git a/setup.go b/setup.go
index a581a5f0..df8d5231 100644
--- a/setup.go
+++ b/setup.go
@@ -13,6 +13,11 @@ import (
log "github.com/Sirupsen/logrus"
)
+const (
+ downloadURL = "https://get.docker.com/builds/Linux/x86_64/docker-"
+ rcDownloadURL = "https://test.docker.com/builds/Linux/x86_64/docker-"
+)
+
// GetDockerBinary ensures that we have the right version docker client
// for communicating with the Docker Daemon
func (d *Daemon) GetDockerBinary() error {
@@ -33,6 +38,12 @@ func (d *Daemon) GetDockerBinary() error {
}
defer out.Close()
+ // determine if we're using an RC build of docker
+ url := downloadURL
+ if strings.Contains(d.Version, "rc") {
+ url = rcDownloadURL
+ }
+
// the method of downloading it is different for version >= 1.11.0
// (in which case it is an archive containing multiple binaries)
versionComp, err := compareVersions(d.Version, "1.11.0")
@@ -40,12 +51,12 @@ func (d *Daemon) GetDockerBinary() error {
return err
}
if versionComp >= 0 {
- err = getClient(out, "https://get.docker.com/builds/Linux/x86_64/docker-"+d.Version+".tgz", extractClient)
+ err = getClient(out, url+d.Version+".tgz", extractClient)
if err != nil {
return err
}
} else {
- err = getClient(out, "https://get.docker.com/builds/Linux/x86_64/docker-"+d.Version, copyClient)
+ err = getClient(out, url+d.Version, copyClient)
if err != nil {
return err
}
diff --git a/start.sh b/start.sh
deleted file mode 100755
index 30e48b92..00000000
--- a/start.sh
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/bin/sh
-
-set -e
-
-# Start goproxy
-echo Starting Dockercraft
-dockercraft &
-
-# start Minecraft C++ server
-cd /srv/world
-cuberite
diff --git a/world/MojangAPI.sqlite b/world/MojangAPI.sqlite
deleted file mode 100644
index 3305fe09..00000000
Binary files a/world/MojangAPI.sqlite and /dev/null differ
diff --git a/world/Plugins/APIDump/APIDesc.lua b/world/Plugins/APIDump/APIDesc.lua
deleted file mode 100644
index 8b9f5268..00000000
--- a/world/Plugins/APIDump/APIDesc.lua
+++ /dev/null
@@ -1,19443 +0,0 @@
-return
-{
- Classes =
- {
- --[[
- -- What the APIDump plugin understands / how to document stuff:
- ExampleClassName =
- {
- Desc = "Description, exported as the first paragraph of the class page. Usually enclosed within double brackets."
-
- Functions =
- {
- FunctionName =
- {
- {
- Params =
- {
- { Name = "BuiltInType", Type = "number"},
- { Name = "ClassEnum", Type = "cClass#eEnum"},
- { Name = "GlobalEnum", Type = "eEnum"},
- },
- Returns =
- {
- { Type = "number" },
- { Type = "self" }, -- Returns the same object on which it was called
- },
- Notes = "Notes 1"
- },
- {
- Params = {...},
- Returns = {...},
- Notes = "Notes 2",
- },
- },
- } ,
-
- Constants =
- {
- ConstantName = { Notes = "Notes about the constant" },
- } ,
-
- ConstantGroups =
- {
- eEnum = -- also used as the HTML anchor name
- {
- Include = {"constant1", "constant2", "const_.*"}, -- Constants to include in this group, array of identifiers, accepts wildcards
- TextBefore = "This text will be written in front of the constant list",
- TextAfter = "This text will be written after the constant list",
- ShowInDescendants = false, -- If false, descendant classes won't list these constants
- }
- },
-
- Variables =
- {
- VariableName = { Type = "string", Notes = "Notes about the variable" },
- } ,
-
- AdditionalInfo = -- Paragraphs to be exported after the function definitions table
- {
- {
- Header = "Header 1",
- Contents = "Contents of the additional section 1",
- },
- {
- Header = "Header 2",
- Contents = "Contents of the additional section 2",
- }
- },
-
- Inherits = "ParentClassName", -- Only present if the class inherits from another API class
- },
- --]]
-
- cBlockArea =
- {
- Desc = [[
- This class is used when multiple adjacent blocks are to be manipulated. Because of chunking
- and multithreading, manipulating single blocks using {{cWorld|cWorld:SetBlock}}() is a rather
- time-consuming operation (locks for exclusive access need to be obtained, chunk lookup is done
- for each block), so whenever you need to manipulate multiple adjacent blocks, it's better to wrap
- the operation into a cBlockArea access. cBlockArea is capable of reading / writing across chunk
- boundaries, has no chunk lookups for get and set operations and is not subject to multithreading
- locking (because it is not shared among threads).
-
- cBlockArea remembers its origin (MinX, MinY, MinZ coords in the Read() call) and therefore supports
- absolute as well as relative get / set operations. Despite that, the contents of a cBlockArea can
- be written back into the world at any coords.
-
- cBlockArea can hold any combination of the following datatypes:
-
block types
-
block metas
-
blocklight
-
skylight
-
- Read() and Write() functions have parameters that tell the class which datatypes to read / write.
- Note that a datatype that has not been read cannot be written (FIXME).
-
- Typical usage:
-
Create cBlockArea object
-
Read an area from the world / load from file / create anew
-
Modify blocks inside cBlockArea
-
Write the area back to a world / save to file
-
- ]],
- Functions =
- {
- Clear =
- {
- Notes = "Clears the object, resets it to zero size",
- },
- constructor =
- {
- Returns =
- {
- {
- Type = "cBlockArea",
- },
- },
- Notes = "Creates a new empty cBlockArea object",
- },
- CopyFrom =
- {
- Params =
- {
- {
- Name = "BlockAreaSrc",
- Type = "cBlockArea",
- },
- },
- Notes = "Copies contents from BlockAreaSrc into self",
- },
- CopyTo =
- {
- Params =
- {
- {
- Name = "BlockAreaDst",
- Type = "cBlockArea",
- },
- },
- Notes = "Copies contents from self into BlockAreaDst.",
- },
- CountNonAirBlocks =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the count of blocks that are not air. Returns 0 if blocktypes not available. Block metas are ignored (if present, air with any meta is still considered air).",
- },
- CountSpecificBlocks =
- {
- {
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Counts the number of occurences of the specified blocktype contained in the area.",
- },
- {
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Counts the number of occurrences of the specified blocktype + blockmeta combination contained in the area.",
- },
- },
- Create =
- {
- {
- Params =
- {
- {
- Name = "SizeX",
- Type = "number",
- },
- {
- Name = "SizeY",
- Type = "number",
- },
- {
- Name = "SizeZ",
- Type = "number",
- },
- },
- Notes = "Initializes this BlockArea to an empty area of the specified size and origin of {0, 0, 0}. Datatypes are set to baTypes + baMetas. Any previous contents are lost.",
- },
- {
- Params =
- {
- {
- Name = "SizeX",
- Type = "number",
- },
- {
- Name = "SizeY",
- Type = "number",
- },
- {
- Name = "SizeZ",
- Type = "number",
- },
- {
- Name = "DataTypes",
- Type = "string",
- },
- },
- Notes = "Initializes this BlockArea to an empty area of the specified size and origin of {0, 0, 0}. Any previous contents are lost.",
- },
- {
- Params =
- {
- {
- Name = "Size",
- Type = "Vector3i",
- },
- },
- Notes = "Creates a new area of the specified size. Datatypes are set to baTypes + baMetas. Origin is set to all zeroes. BlockTypes are set to air, block metas to zero, blocklights to zero and skylights to full light.",
- },
- {
- Params =
- {
- {
- Name = "Size",
- Type = "Vector3i",
- },
- {
- Name = "DataTypes",
- Type = "string",
- },
- },
- Notes = "Creates a new area of the specified size and contents. Origin is set to all zeroes. BlockTypes are set to air, block metas to zero, blocklights to zero and skylights to full light.",
- },
- },
- Crop =
- {
- Params =
- {
- {
- Name = "AddMinX",
- Type = "number",
- },
- {
- Name = "SubMaxX",
- Type = "number",
- },
- {
- Name = "AddMinY",
- Type = "number",
- },
- {
- Name = "SubMaxY",
- Type = "number",
- },
- {
- Name = "AddMinZ",
- Type = "number",
- },
- {
- Name = "SubMaxZ",
- Type = "number",
- },
- },
- Notes = "Crops the specified number of blocks from each border. Modifies the size of this blockarea object.",
- },
- DumpToRawFile =
- {
- Params =
- {
- {
- Name = "FileName",
- Type = "string",
- },
- },
- Notes = "Dumps the raw data into a file. For debugging purposes only.",
- },
- Expand =
- {
- Params =
- {
- {
- Name = "SubMinX",
- Type = "number",
- },
- {
- Name = "AddMaxX",
- Type = "number",
- },
- {
- Name = "SubMinY",
- Type = "number",
- },
- {
- Name = "AddMaxY",
- Type = "number",
- },
- {
- Name = "SubMinZ",
- Type = "number",
- },
- {
- Name = "AddMaxZ",
- Type = "number",
- },
- },
- Notes = "Expands the specified number of blocks from each border. Modifies the size of this blockarea object. New blocks created with this operation are filled with zeroes.",
- },
- Fill =
- {
- Params =
- {
- {
- Name = "DataTypes",
- Type = "string",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "BlockLight",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "BlockSkyLight",
- Type = "number",
- IsOptional = true,
- },
- },
- Notes = "Fills the entire block area with the same values, specified. Uses the DataTypes param to determine which content types are modified.",
- },
- FillRelCuboid =
- {
- {
- Params =
- {
- {
- Name = "RelCuboid",
- Type = "cCuboid",
- },
- {
- Name = "DataTypes",
- Type = "string",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "BlockLight",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "BlockSkyLight",
- Type = "number",
- IsOptional = true,
- },
- },
- Notes = "Fills the specified cuboid (in relative coords) with the same values (like Fill() ).",
- },
- {
- Params =
- {
- {
- Name = "MinRelX",
- Type = "number",
- },
- {
- Name = "BlockLight",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "BlockSkyLight",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "MaxRelX",
- Type = "number",
- },
- {
- Name = "MinRelY",
- Type = "number",
- },
- {
- Name = "MaxRelY",
- Type = "number",
- },
- {
- Name = "MinRelZ",
- Type = "number",
- },
- {
- Name = "MaxRelZ",
- Type = "number",
- },
- {
- Name = "DataTypes",
- Type = "string",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- IsOptional = true,
- },
- },
- Notes = "Fills the specified cuboid with the same values (like Fill() ).",
- },
- },
- GetBlockLight =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "NIBBLETYPE",
- Type = "number",
- },
- },
- Notes = "Returns the blocklight at the specified absolute coords",
- },
- GetBlockMeta =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "NIBBLETYPE",
- Type = "number",
- },
- },
- Notes = "Returns the block meta at the specified absolute coords",
- },
- GetBlockSkyLight =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "NIBBLETYPE",
- Type = "number",
- },
- },
- Notes = "Returns the skylight at the specified absolute coords",
- },
- GetBlockType =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "BLOCKTYPE",
- Type = "number",
- },
- },
- Notes = "Returns the block type at the specified absolute coords",
- },
- GetBlockTypeMeta =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "BLOCKTYPE",
- Type = "number",
- },
- {
- Name = "NIBBLETYPE",
- Type = "number",
- },
- },
- Notes = "Returns the block type and meta at the specified absolute coords",
- },
- GetCoordRange =
- {
- Returns =
- {
- {
- Name = "MaxX",
- Type = "number",
- },
- {
- Name = "MaxY",
- Type = "number",
- },
- {
- Name = "MaxZ",
- Type = "number",
- },
- },
- Notes = "Returns the maximum relative coords in all 3 axes. See also GetSize().",
- },
- GetDataTypes =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the mask of datatypes that the object is currently holding",
- },
- GetNonAirCropRelCoords =
- {
- Params =
- {
- {
- Name = "IgnoredBlockType",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "MinRelX",
- Type = "number",
- },
- {
- Name = "MinRelY",
- Type = "number",
- },
- {
- Name = "MinRelZ",
- Type = "number",
- },
- {
- Name = "MaxRelX",
- Type = "number",
- },
- {
- Name = "MaxRelY",
- Type = "number",
- },
- {
- Name = "MaxRelZ",
- Type = "number",
- },
- },
- Notes = "Returns the minimum and maximum coords in each direction for the first block in each direction of type different to IgnoredBlockType (E_BLOCK_AIR by default). If there are no non-ignored blocks within the area, or blocktypes are not present, the returned values are reverse-ranges (MinX <- m_RangeX, MaxX <- 0 etc.). IgnoreBlockType defaults to air.",
- },
- GetOrigin =
- {
- Returns =
- {
- {
- Name = "OriginX",
- Type = "number",
- },
- {
- Name = "OriginY",
- Type = "number",
- },
- {
- Name = "OriginZ",
- Type = "number",
- },
- },
- Notes = "Returns the origin coords of where the area was read from.",
- },
- GetOriginX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the origin x-coord",
- },
- GetOriginY =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the origin y-coord",
- },
- GetOriginZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the origin z-coord",
- },
- GetRelBlockLight =
- {
- Params =
- {
- {
- Name = "RelBlockX",
- Type = "number",
- },
- {
- Name = "RelBlockY",
- Type = "number",
- },
- {
- Name = "RelBlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "NIBBLETYPE",
- Type = "number",
- },
- },
- Notes = "Returns the blocklight at the specified relative coords",
- },
- GetRelBlockMeta =
- {
- Params =
- {
- {
- Name = "RelBlockX",
- Type = "number",
- },
- {
- Name = "RelBlockY",
- Type = "number",
- },
- {
- Name = "RelBlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "NIBBLETYPE",
- Type = "number",
- },
- },
- Notes = "Returns the block meta at the specified relative coords",
- },
- GetRelBlockSkyLight =
- {
- Params =
- {
- {
- Name = "RelBlockX",
- Type = "number",
- },
- {
- Name = "RelBlockY",
- Type = "number",
- },
- {
- Name = "RelBlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "NIBBLETYPE",
- Type = "number",
- },
- },
- Notes = "Returns the skylight at the specified relative coords",
- },
- GetRelBlockType =
- {
- Params =
- {
- {
- Name = "RelBlockX",
- Type = "number",
- },
- {
- Name = "RelBlockY",
- Type = "number",
- },
- {
- Name = "RelBlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "BLOCKTYPE",
- Type = "number",
- },
- },
- Notes = "Returns the block type at the specified relative coords",
- },
- GetRelBlockTypeMeta =
- {
- Params =
- {
- {
- Name = "RelBlockX",
- Type = "number",
- },
- {
- Name = "RelBlockY",
- Type = "number",
- },
- {
- Name = "RelBlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "BLOCKTYPE",
- Type = "number",
- },
- {
- Name = "NIBBLETYPE",
- Type = "number",
- },
- },
- Notes = "Returns the block type and meta at the specified relative coords",
- },
- GetSize =
- {
- Returns =
- {
- {
- Name = "SizeX",
- Type = "number",
- },
- {
- Name = "SizeY",
- Type = "number",
- },
- {
- Name = "SizeZ",
- Type = "number",
- },
- },
- Notes = "Returns the size of the area in all 3 axes. See also GetCoordRange().",
- },
- GetSizeX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the size of the held data in the x-axis",
- },
- GetSizeY =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the size of the held data in the y-axis",
- },
- GetSizeZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the size of the held data in the z-axis",
- },
- GetVolume =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the volume of the area - the total number of blocks stored within.",
- },
- GetWEOffset =
- {
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns the WE offset, a data value sometimes stored in the schematic files. Cuberite doesn't use this value, but provides access to it using this method. The default is {0, 0, 0}.",
- },
- HasBlockLights =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if current datatypes include blocklight",
- },
- HasBlockMetas =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if current datatypes include block metas",
- },
- HasBlockSkyLights =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if current datatypes include skylight",
- },
- HasBlockTypes =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if current datatypes include block types",
- },
- LoadFromSchematicFile =
- {
- Params =
- {
- {
- Name = "FileName",
- Type = "string",
- },
- },
- Notes = "Clears current content and loads new content from the specified schematic file. Returns true if successful. Returns false and logs error if unsuccessful, old content is preserved in such a case.",
- },
- LoadFromSchematicString =
- {
- Params =
- {
- {
- Name = "SchematicData",
- Type = "string",
- },
- },
- Notes = "Clears current content and loads new content from the specified string (assumed to contain .schematic data). Returns true if successful. Returns false and logs error if unsuccessful, old content is preserved in such a case.",
- },
- Merge =
- {
- {
- Params =
- {
- {
- Name = "BlockAreaSrc",
- Type = "cBlockArea",
- },
- {
- Name = "RelMinCoords",
- Type = "number",
- },
- {
- Name = "Strategy",
- Type = "string",
- },
- },
- Notes = "Merges BlockAreaSrc into this object at the specified relative coords, using the specified strategy",
- },
- {
- Params =
- {
- {
- Name = "BlockAreaSrc",
- Type = "cBlockArea",
- },
- {
- Name = "RelX",
- Type = "number",
- },
- {
- Name = "RelY",
- Type = "number",
- },
- {
- Name = "RelZ",
- Type = "number",
- },
- {
- Name = "Strategy",
- Type = "string",
- },
- },
- Notes = "Merges BlockAreaSrc into this object at the specified relative coords, using the specified strategy",
- },
- },
- MirrorXY =
- {
- Notes = "Mirrors this block area around the XY plane. Modifies blocks' metas (if present) to match (i. e. furnaces facing the opposite direction).",
- },
- MirrorXYNoMeta =
- {
- Notes = "Mirrors this block area around the XY plane. Doesn't modify blocks' metas.",
- },
- MirrorXZ =
- {
- Notes = "Mirrors this block area around the XZ plane. Modifies blocks' metas (if present)",
- },
- MirrorXZNoMeta =
- {
- Notes = "Mirrors this block area around the XZ plane. Doesn't modify blocks' metas.",
- },
- MirrorYZ =
- {
- Notes = "Mirrors this block area around the YZ plane. Modifies blocks' metas (if present)",
- },
- MirrorYZNoMeta =
- {
- Notes = "Mirrors this block area around the YZ plane. Doesn't modify blocks' metas.",
- },
- Read =
- {
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "Cuboid",
- Type = "cCuboid",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Reads the area from World, returns true if successful. baTypes and baMetas are read.",
- },
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "Cuboid",
- Type = "cCuboid",
- },
- {
- Name = "DataTypes",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Reads the area from World, returns true if successful. DataTypes is the sum of baXXX datatypes to be read",
- },
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "Point1",
- Type = "Vector3i",
- },
- {
- Name = "Point2",
- Type = "Vector3i",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Reads the area from World, returns true if successful. baTypes and baMetas are read.",
- },
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "Point1",
- Type = "Vector3i",
- },
- {
- Name = "Point2",
- Type = "Vector3i",
- },
- {
- Name = "DataTypes",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Reads the area from World, returns true if successful. DataTypes is a sum of baXXX datatypes to be read.",
- },
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "MinX",
- Type = "number",
- },
- {
- Name = "MaxX",
- Type = "number",
- },
- {
- Name = "MinY",
- Type = "number",
- },
- {
- Name = "MaxY",
- Type = "number",
- },
- {
- Name = "MinZ",
- Type = "number",
- },
- {
- Name = "MaxZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Reads the area from World, returns true if successful. baTypes and baMetas are read.",
- },
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "MinX",
- Type = "number",
- },
- {
- Name = "MaxX",
- Type = "number",
- },
- {
- Name = "MinY",
- Type = "number",
- },
- {
- Name = "MaxY",
- Type = "number",
- },
- {
- Name = "MinZ",
- Type = "number",
- },
- {
- Name = "MaxZ",
- Type = "number",
- },
- {
- Name = "DataTypes",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Reads the area from World, returns true if successful. DataTypes is a sum of baXXX datatypes to read.",
- },
- },
- RelLine =
- {
- {
- Params =
- {
- {
- Name = "RelPoint1",
- Type = "Vector3i",
- },
- {
- Name = "RelPoint2",
- Type = "Vector3i",
- },
- {
- Name = "DataTypes",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "BlockLight",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "BlockSkyLight",
- Type = "number",
- IsOptional = true,
- },
- },
- Notes = "Draws a line between the two specified points. Sets only datatypes specified by DataTypes (baXXX constants).",
- },
- {
- Params =
- {
- {
- Name = "RelX1",
- Type = "number",
- },
- {
- Name = "BlockLight",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "BlockSkyLight",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "RelY1",
- Type = "number",
- },
- {
- Name = "RelZ1",
- Type = "number",
- },
- {
- Name = "RelX2",
- Type = "number",
- },
- {
- Name = "RelY2",
- Type = "number",
- },
- {
- Name = "RelZ2",
- Type = "number",
- },
- {
- Name = "DataTypes",
- Type = "string",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- IsOptional = true,
- },
- },
- Notes = "Draws a line between the two specified points. Sets only datatypes specified by DataTypes (baXXX constants).",
- },
- },
- RotateCCW =
- {
- Notes = "Rotates the block area around the Y axis, counter-clockwise (east -> north). Modifies blocks' metas (if present) to match.",
- },
- RotateCCWNoMeta =
- {
- Notes = "Rotates the block area around the Y axis, counter-clockwise (east -> north). Doesn't modify blocks' metas.",
- },
- RotateCW =
- {
- Notes = "Rotates the block area around the Y axis, clockwise (north -> east). Modifies blocks' metas (if present) to match.",
- },
- RotateCWNoMeta =
- {
- Notes = "Rotates the block area around the Y axis, clockwise (north -> east). Doesn't modify blocks' metas.",
- },
- SaveToSchematicFile =
- {
- Params =
- {
- {
- Name = "FileName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Saves the current contents to a schematic file. Returns true if successful.",
- },
- SaveToSchematicString =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Saves the current contents to a string (in a .schematic file format). Returns the data if successful, nil if failed.",
- },
- SetBlockLight =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockLight",
- Type = "number",
- },
- },
- Notes = "Sets the blocklight at the specified absolute coords",
- },
- SetBlockMeta =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Sets the block meta at the specified absolute coords",
- },
- SetBlockSkyLight =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockSkyLight",
- Type = "number",
- },
- },
- Notes = "Sets the skylight at the specified absolute coords",
- },
- SetBlockType =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Notes = "Sets the block type at the specified absolute coords",
- },
- SetBlockTypeMeta =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Sets the block type and meta at the specified absolute coords",
- },
- SetOrigin =
- {
- {
- Params =
- {
- {
- Name = "Origin",
- Type = "Vector3i",
- },
- },
- Notes = "Resets the origin for the absolute coords. Only affects how absolute coords are translated into relative coords.",
- },
- {
- Params =
- {
- {
- Name = "OriginX",
- Type = "number",
- },
- {
- Name = "OriginY",
- Type = "number",
- },
- {
- Name = "OriginZ",
- Type = "number",
- },
- },
- Notes = "Resets the origin for the absolute coords. Only affects how absolute coords are translated into relative coords.",
- },
- },
- SetRelBlockLight =
- {
- Params =
- {
- {
- Name = "RelBlockX",
- Type = "number",
- },
- {
- Name = "RelBlockY",
- Type = "number",
- },
- {
- Name = "RelBlockZ",
- Type = "number",
- },
- {
- Name = "BlockLight",
- Type = "number",
- },
- },
- Notes = "Sets the blocklight at the specified relative coords",
- },
- SetRelBlockMeta =
- {
- Params =
- {
- {
- Name = "RelBlockX",
- Type = "number",
- },
- {
- Name = "RelBlockY",
- Type = "number",
- },
- {
- Name = "RelBlockZ",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Sets the block meta at the specified relative coords",
- },
- SetRelBlockSkyLight =
- {
- Params =
- {
- {
- Name = "RelBlockX",
- Type = "number",
- },
- {
- Name = "RelBlockY",
- Type = "number",
- },
- {
- Name = "RelBlockZ",
- Type = "number",
- },
- {
- Name = "BlockSkyLight",
- Type = "number",
- },
- },
- Notes = "Sets the skylight at the specified relative coords",
- },
- SetRelBlockType =
- {
- Params =
- {
- {
- Name = "RelBlockX",
- Type = "number",
- },
- {
- Name = "RelBlockY",
- Type = "number",
- },
- {
- Name = "RelBlockZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Notes = "Sets the block type at the specified relative coords",
- },
- SetRelBlockTypeMeta =
- {
- Params =
- {
- {
- Name = "RelBlockX",
- Type = "number",
- },
- {
- Name = "RelBlockY",
- Type = "number",
- },
- {
- Name = "RelBlockZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Sets the block type and meta at the specified relative coords",
- },
- SetWEOffset =
- {
- {
- Params =
- {
- {
- Name = "Offset",
- Type = "Vector3i",
- },
- },
- Notes = "Sets the WE offset, a data value sometimes stored in the schematic files. Mostly used for WorldEdit. Cuberite doesn't use this value, but provides access to it using this method.",
- },
- {
- Params =
- {
- {
- Name = "OffsetX",
- Type = "number",
- },
- {
- Name = "OffsetY",
- Type = "number",
- },
- {
- Name = "OffsetZ",
- Type = "number",
- },
- },
- Notes = "Sets the WE offset, a data value sometimes stored in the schematic files. Mostly used for WorldEdit. Cuberite doesn't use this value, but provides access to it using this method.",
- },
- },
- Write =
- {
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "MinPoint",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Writes the area into World at the specified coords, returns true if successful. baTypes and baMetas are written.",
- },
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "MinPoint",
- Type = "number",
- },
- {
- Name = "DataTypes",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Writes the area into World at the specified coords, returns true if successful. DataTypes is the sum of baXXX datatypes to write.",
- },
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "MinX",
- Type = "number",
- },
- {
- Name = "MinY",
- Type = "number",
- },
- {
- Name = "MinZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Writes the area into World at the specified coords, returns true if successful. baTypes and baMetas are written.",
- },
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "MinX",
- Type = "number",
- },
- {
- Name = "MinY",
- Type = "number",
- },
- {
- Name = "MinZ",
- Type = "number",
- },
- {
- Name = "DataTypes",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Writes the area into World at the specified coords, returns true if successful. DataTypes is the sum of baXXX datatypes to write.",
- },
- },
- },
- Constants =
- {
- baLight =
- {
- Notes = "Operations should work on block (emissive) light",
- },
- baMetas =
- {
- Notes = "Operations should work on block metas",
- },
- baSkyLight =
- {
- Notes = "Operations should work on skylight",
- },
- baTypes =
- {
- Notes = "Operation should work on block types",
- },
- msDifference =
- {
- Notes = "Block becomes air if 'self' and src are the same. Otherwise it becomes the src block.",
- },
- msFillAir =
- {
- Notes = "'self' is overwritten by Src only where 'self' has air blocks",
- },
- msImprint =
- {
- Notes = "Src overwrites 'self' anywhere where 'self' has non-air blocks",
- },
- msLake =
- {
- Notes = "Special mode for merging lake images",
- },
- msMask =
- {
- Notes = "The blocks that are exactly the same are kept in 'self', all differing blocks are replaced by air",
- },
- msOverwrite =
- {
- Notes = "Src overwrites anything in 'self'",
- },
- msSimpleCompare =
- {
- Notes = "The blocks that are exactly the same are replaced with air, all differing blocks are replaced by stone",
- },
- msSpongePrint =
- {
- Notes = "Similar to msImprint, sponge block doesn't overwrite anything, all other blocks overwrite everything",
- },
- },
- ConstantGroups =
- {
- BATypes =
- {
- Include = "ba.*",
- TextBefore = [[
- The following constants are used to signalize the datatype to read or write:
- ]],
- },
- MergeStrategies =
- {
- Include = "ms.*",
- TextAfter = "See below for a detailed explanation of the individual merge strategies.",
- TextBefore = [[
- The Merge() function can use different strategies to combine the source and destination blocks.
- The following constants are used:
- ]],
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Merge strategies",
- Contents = [[
-
The strategy parameter specifies how individual blocks are combined together, using the table below.
-
-
-
-
area block
result
-
-
-
this
Src
msOverwrite
msFillAir
msImprint
-
-
-
air
air
air
air
air
-
-
-
A
air
air
A
A
-
-
-
air
B
B
B
B
-
-
-
A
B
B
A
B
-
-
-
A
A
A
A
A
-
-
-
-
- So to sum up:
-
-
msOverwrite completely overwrites all blocks with the Src's blocks
-
msFillAir overwrites only those blocks that were air
-
msImprint overwrites with only those blocks that are non-air
-
-
-
-
Special strategies
-
For each strategy, evaluate the table rows from top downwards, the first match wins.
-
-
- msDifference - changes all the blocks which are the same to air. Otherwise the source block gets placed.
-
-
-
area block
Notes
-
-
*
B
B
The blocks are different so we use block B
-
-
B
B
Air
The blocks are the same so we get air.
-
-
-
-
-
- msLake - used for merging areas with lava and water lakes, in the appropriate generator.
-
-
-
area block
Notes
-
-
self
Src
result
-
-
A
sponge
A
Sponge is the NOP block
-
-
*
air
air
Air always gets hollowed out, even under the oceans
-
-
water
*
water
Water is never overwritten
-
-
lava
*
lava
Lava is never overwritten
-
-
*
water
water
Water always overwrites anything
-
-
*
lava
lava
Lava always overwrites anything
-
-
dirt
stone
stone
Stone overwrites dirt
-
-
grass
stone
stone
... and grass
-
-
mycelium
stone
stone
... and mycelium
-
-
A
stone
A
... but nothing else
-
-
A
*
A
Everything else is left as it is
-
-
-
-
- msSpongePrint - used for most prefab-generators to merge the prefabs. Similar to
- msImprint, but uses the sponge block as the NOP block instead, so that the prefabs may carve out air
- pockets, too.
-
-
-
area block
Notes
-
-
self
Src
result
-
-
A
sponge
A
Sponge is the NOP block
-
-
*
B
B
Everything else overwrites anything
-
-
-
-
- msMask - the blocks that are the same in the other area are kept, all the
- differing blocks are replaced with air. Meta is used in the comparison, too, two blocks of the
- same type but different meta are considered different and thus replaced with air.
-
-
-
area block
Notes
-
-
self
Src
result
-
-
A
A
A
Same blocks are kept
-
-
A
non-A
air
Differing blocks are replaced with air
-
-
-
-
- msDifference - the blocks that are the same in both areas are replaced with air, all the
- differing blocks are kept from the first area. Meta is used in the comparison, too, two blocks of the
- same type but different meta are considered different.
-
-
-
area block
Notes
-
-
self
Src
result
-
-
A
A
air
Same blocks are replaced with air
-
-
A
non-A
A
Differing blocks are kept from 'self'
-
-
-
-
- msSimpleCompare - the blocks that are the same in both areas are replaced with air, all the
- differing blocks are replaced with stone. Meta is used in the comparison, too, two blocks of the
- same type but different meta are considered different.
-
-
-
area block
Notes
-
-
self
Src
result
-
-
A
A
air
Same blocks are replaced with air
-
-
A
non-A
stone
Differing blocks are replaced with stone
-
-
-]],
- },
- },
- },
- cBlockInfo =
- {
- Desc = [[
- This class is used to query and register block properties.
- ]],
- Functions =
- {
- CanBeTerraformed =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the block is suitable to be changed by a generator",
- },
- FullyOccupiesVoxel =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether the specified block fully occupies its voxel.",
- },
- Get =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cBlockInfo",
- },
- },
- Notes = "Returns the {{cBlockInfo}} structure for the specified block type.",
- },
- GetBlockHeight =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the block's hitbox height.",
- },
- GetLightValue =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns how much light the specified block emits on its own.",
- },
- GetPlaceSound =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Notes = "Returns the name of the sound that is played when placing the block of this type.",
- },
- GetSpreadLightFalloff =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns how much light the specified block type consumes.",
- },
- IsOneHitDig =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether the specified block type will be destroyed after a single hit.",
- },
- IsPistonBreakable =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether a piston can break the specified block type.",
- },
- IsSnowable =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether the specified block type can hold snow atop.",
- },
- IsSolid =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether the specified block type is solid.",
- },
- IsTransparent =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether the specified block is transparent.",
- },
- RequiresSpecialTool =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether the specified block requires a special tool to drop resources.",
- },
- },
- Variables =
- {
- m_CanBeTerraformed =
- {
- Type = "bool",
- Notes = "Is this block suited to be terraformed?",
- },
- m_FullyOccupiesVoxel =
- {
- Type = "bool",
- Notes = "Does this block fully occupy its voxel - is it a 'full' block?",
- },
- m_IsSnowable =
- {
- Type = "bool",
- Notes = "Can this block hold snow atop?",
- },
- m_IsSolid =
- {
- Type = "bool",
- Notes = "Is this block solid (player cannot walk through)?",
- },
- m_LightValue =
- {
- Type = "number",
- Notes = "How much light do the blocks emit on their own?",
- },
- m_OneHitDig =
- {
- Type = "bool",
- Notes = "Is a block destroyed after a single hit?",
- },
- m_PistonBreakable =
- {
- Type = "bool",
- Notes = "Can a piston break this block?",
- },
- m_PlaceSound =
- {
- Type = "string",
- Notes = "The name of the sound that is placed when a block is placed.",
- },
- m_RequiresSpecialTool =
- {
- Type = "bool",
- Notes = "Does this block require a tool to drop?",
- },
- m_SpreadLightFalloff =
- {
- Type = "number",
- Notes = "How much light do the blocks consume?",
- },
- m_Transparent =
- {
- Type = "bool",
- Notes = "Is a block completely transparent? (light doesn't get decreased(?))",
- },
- },
- },
- cChatColor =
- {
- Desc = [[
- A wrapper class for constants representing colors or effects.
- ]],
- Functions =
- {
-
- },
- Constants =
- {
- Black =
- {
- Notes = "",
- },
- Blue =
- {
- Notes = "",
- },
- Bold =
- {
- Notes = "",
- },
- Color =
- {
- Notes = "The first character of the color-code-sequence, §",
- },
- DarkPurple =
- {
- Notes = "",
- },
- Delimiter =
- {
- Notes = "The first character of the color-code-sequence, §",
- },
- Gold =
- {
- Notes = "",
- },
- Gray =
- {
- Notes = "",
- },
- Green =
- {
- Notes = "",
- },
- Italic =
- {
- Notes = "",
- },
- LightBlue =
- {
- Notes = "",
- },
- LightGray =
- {
- Notes = "",
- },
- LightGreen =
- {
- Notes = "",
- },
- LightPurple =
- {
- Notes = "",
- },
- Navy =
- {
- Notes = "",
- },
- Plain =
- {
- Notes = "Resets all formatting to normal",
- },
- Purple =
- {
- Notes = "",
- },
- Random =
- {
- Notes = "Random letters and symbols animate instead of the text",
- },
- Red =
- {
- Notes = "",
- },
- Rose =
- {
- Notes = "",
- },
- Strikethrough =
- {
- Notes = "",
- },
- Underlined =
- {
- Notes = "",
- },
- White =
- {
- Notes = "",
- },
- Yellow =
- {
- Notes = "",
- },
- },
- },
- cChunkDesc =
- {
- Desc = [[
- The cChunkDesc class is a container for chunk data while the chunk is being generated. As such, it is
- only used as a parameter for the {{OnChunkGenerating|OnChunkGenerating}} and
- {{OnChunkGenerated|OnChunkGenerated}} hooks and cannot be constructed on its own. Plugins can use this
- class in both those hooks to manipulate generated chunks.
- ]],
- Functions =
- {
- FillBlocks =
- {
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Fills the entire chunk with the specified blocks",
- },
- FillRelCuboid =
- {
- {
- Params =
- {
- {
- Name = "RelCuboid",
- Type = "cCuboid",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Fills the cuboid, specified in relative coords, by the specified block type and block meta. The cuboid may reach outside of the chunk, only the part intersecting with this chunk is filled.",
- },
- {
- Params =
- {
- {
- Name = "MinRelX",
- Type = "number",
- },
- {
- Name = "MaxRelX",
- Type = "number",
- },
- {
- Name = "MinRelY",
- Type = "number",
- },
- {
- Name = "MaxRelY",
- Type = "number",
- },
- {
- Name = "MinRelZ",
- Type = "number",
- },
- {
- Name = "MaxRelZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Fills the cuboid, specified in relative coords, by the specified block type and block meta. The cuboid may reach outside of the chunk, only the part intersecting with this chunk is filled.",
- },
- },
- FloorRelCuboid =
- {
- {
- Params =
- {
- {
- Name = "RelCuboid",
- Type = "cCuboid",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Fills those blocks of the cuboid (specified in relative coords) that are considered non-floor (air, water) with the specified block type and meta. Cuboid may reach outside the chunk, only the part intersecting with this chunk is filled.",
- },
- {
- Params =
- {
- {
- Name = "MinRelX",
- Type = "number",
- },
- {
- Name = "MaxRelX",
- Type = "number",
- },
- {
- Name = "MinRelY",
- Type = "number",
- },
- {
- Name = "MaxRelY",
- Type = "number",
- },
- {
- Name = "MinRelZ",
- Type = "number",
- },
- {
- Name = "MaxRelZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Fills those blocks of the cuboid (specified in relative coords) that are considered non-floor (air, water) with the specified block type and meta. Cuboid may reach outside the chunk, only the part intersecting with this chunk is filled.",
- },
- },
- GetBiome =
- {
- Params =
- {
- {
- Name = "RelX",
- Type = "number",
- },
- {
- Name = "RelZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "EMCSBiome",
- },
- },
- Notes = "Returns the biome at the specified relative coords",
- },
- GetBlockEntity =
- {
- Params =
- {
- {
- Name = "RelX",
- Type = "number",
- },
- {
- Name = "RelY",
- Type = "number",
- },
- {
- Name = "RelZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cBlockEntity",
- },
- },
- Notes = "Returns the block entity for the block at the specified coords. Creates it if it doesn't exist. Returns nil if the block has no block entity capability.",
- },
- GetBlockMeta =
- {
- Params =
- {
- {
- Name = "RelX",
- Type = "number",
- },
- {
- Name = "RelY",
- Type = "number",
- },
- {
- Name = "RelZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "NIBBLETYPE",
- Type = "number",
- },
- },
- Notes = "Returns the block meta at the specified relative coords",
- },
- GetBlockType =
- {
- Params =
- {
- {
- Name = "RelX",
- Type = "number",
- },
- {
- Name = "RelY",
- Type = "number",
- },
- {
- Name = "RelZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "BLOCKTYPE",
- Type = "number",
- },
- },
- Notes = "Returns the block type at the specified relative coords",
- },
- GetBlockTypeMeta =
- {
- Params =
- {
- {
- Name = "RelX",
- Type = "number",
- },
- {
- Name = "RelY",
- Type = "number",
- },
- {
- Name = "RelZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "BLOCKTYPE",
- Type = "number",
- },
- {
- Name = "NIBBLETYPE",
- Type = "number",
- },
- },
- Notes = "Returns the block type and meta at the specified relative coords",
- },
- GetChunkX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the X coord of the chunk contained.",
- },
- GetChunkZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the Z coord of the chunk contained.",
- },
- GetHeight =
- {
- Params =
- {
- {
- Name = "RelX",
- Type = "number",
- },
- {
- Name = "RelZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the height at the specified relative coords",
- },
- GetMaxHeight =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the maximum height contained in the heightmap.",
- },
- GetMinHeight =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the minimum height value in the heightmap.",
- },
- IsUsingDefaultBiomes =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the chunk is set to use default biome generator",
- },
- IsUsingDefaultComposition =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the chunk is set to use default composition generator",
- },
- IsUsingDefaultFinish =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the chunk is set to use default finishers",
- },
- IsUsingDefaultHeight =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the chunk is set to use default height generator",
- },
- IsUsingDefaultStructures =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the chunk is set to use default structures",
- },
- RandomFillRelCuboid =
- {
- {
- Params =
- {
- {
- Name = "RelCuboid",
- Type = "cCuboid",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- {
- Name = "RandomSeed",
- Type = "number",
- },
- {
- Name = "ChanceOutOf10k",
- Type = "number",
- },
- },
- Notes = "Fills the specified relative cuboid with block type and meta in random locations. RandomSeed is used for the random number genertion (same seed produces same results); ChanceOutOf10k specifies the density (how many out of every 10000 blocks should be filled). Cuboid may reach outside the chunk, only the part intersecting with this chunk is filled.",
- },
- {
- Params =
- {
- {
- Name = "MinRelX",
- Type = "number",
- },
- {
- Name = "ChanceOutOf10k",
- Type = "number",
- },
- {
- Name = "MaxRelX",
- Type = "number",
- },
- {
- Name = "MinRelY",
- Type = "number",
- },
- {
- Name = "MaxRelY",
- Type = "number",
- },
- {
- Name = "MinRelZ",
- Type = "number",
- },
- {
- Name = "MaxRelZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- {
- Name = "RandomSeed",
- Type = "number",
- },
- },
- Notes = "Fills the specified relative cuboid with block type and meta in random locations. RandomSeed is used for the random number genertion (same seed produces same results); ChanceOutOf10k specifies the density (how many out of every 10000 blocks should be filled). Cuboid may reach outside the chunk, only the part intersecting with this chunk is filled.",
- },
- },
- ReadBlockArea =
- {
- Params =
- {
- {
- Name = "BlockArea",
- Type = "cBlockArea",
- },
- {
- Name = "MinRelX",
- Type = "number",
- },
- {
- Name = "MaxRelX",
- Type = "number",
- },
- {
- Name = "MinRelY",
- Type = "number",
- },
- {
- Name = "MaxRelY",
- Type = "number",
- },
- {
- Name = "MinRelZ",
- Type = "number",
- },
- {
- Name = "MaxRelZ",
- Type = "number",
- },
- },
- Notes = "Reads data from the chunk into the block area object. Block types and metas are processed.",
- },
- ReplaceRelCuboid =
- {
- {
- Params =
- {
- {
- Name = "RelCuboid",
- Type = "cCuboid",
- },
- {
- Name = "SrcBlockType",
- Type = "number",
- },
- {
- Name = "SrcBlockMeta",
- Type = "number",
- },
- {
- Name = "DstBlockType",
- Type = "number",
- },
- {
- Name = "DstBlockMeta",
- Type = "number",
- },
- },
- Notes = "Replaces all SrcBlockType + SrcBlockMeta blocks in the cuboid (specified in relative coords) with DstBlockType + DstBlockMeta blocks. Cuboid may reach outside the chunk, only the part intersecting with this chunk is filled.",
- },
- {
- Params =
- {
- {
- Name = "MinRelX",
- Type = "number",
- },
- {
- Name = "MaxRelX",
- Type = "number",
- },
- {
- Name = "MinRelY",
- Type = "number",
- },
- {
- Name = "MaxRelY",
- Type = "number",
- },
- {
- Name = "MinRelZ",
- Type = "number",
- },
- {
- Name = "MaxRelZ",
- Type = "number",
- },
- {
- Name = "SrcBlockType",
- Type = "number",
- },
- {
- Name = "SrcBlockMeta",
- Type = "number",
- },
- {
- Name = "DstBlockType",
- Type = "number",
- },
- {
- Name = "DstBlockMeta",
- Type = "number",
- },
- },
- Notes = "Replaces all SrcBlockType + SrcBlockMeta blocks in the cuboid (specified in relative coords) with DstBlockType + DstBlockMeta blocks. Cuboid may reach outside the chunk, only the part intersecting with this chunk is filled.",
- },
- },
- SetBiome =
- {
- Params =
- {
- {
- Name = "RelX",
- Type = "number",
- },
- {
- Name = "RelZ",
- Type = "number",
- },
- {
- Name = "Biome",
- Type = "EMCSBiome",
- },
- },
- Notes = "Sets the biome at the specified relative coords",
- },
- SetBlockMeta =
- {
- Params =
- {
- {
- Name = "RelX",
- Type = "number",
- },
- {
- Name = "RelY",
- Type = "number",
- },
- {
- Name = "RelZ",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Sets the block meta at the specified relative coords",
- },
- SetBlockType =
- {
- Params =
- {
- {
- Name = "RelX",
- Type = "number",
- },
- {
- Name = "RelY",
- Type = "number",
- },
- {
- Name = "RelZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Notes = "Sets the block type at the specified relative coords",
- },
- SetBlockTypeMeta =
- {
- Params =
- {
- {
- Name = "RelX",
- Type = "number",
- },
- {
- Name = "RelY",
- Type = "number",
- },
- {
- Name = "RelZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Sets the block type and meta at the specified relative coords",
- },
- SetHeight =
- {
- Params =
- {
- {
- Name = "RelX",
- Type = "number",
- },
- {
- Name = "RelZ",
- Type = "number",
- },
- {
- Name = "Height",
- Type = "number",
- },
- },
- Notes = "Sets the height at the specified relative coords",
- },
- SetUseDefaultBiomes =
- {
- Params =
- {
- {
- Name = "ShouldUseDefaultBiomes",
- Type = "boolean",
- },
- },
- Notes = "Sets the chunk to use default biome generator or not",
- },
- SetUseDefaultComposition =
- {
- Params =
- {
- {
- Name = "ShouldUseDefaultComposition",
- Type = "boolean",
- },
- },
- Notes = "Sets the chunk to use default composition generator or not",
- },
- SetUseDefaultFinish =
- {
- Params =
- {
- {
- Name = "ShouldUseDefaultFinish",
- Type = "boolean",
- },
- },
- Notes = "Sets the chunk to use default finishers or not",
- },
- SetUseDefaultHeight =
- {
- Params =
- {
- {
- Name = "ShouldUseDefaultHeight",
- Type = "boolean",
- },
- },
- Notes = "Sets the chunk to use default height generator or not",
- },
- SetUseDefaultStructures =
- {
- Params =
- {
- {
- Name = "ShouldUseDefaultStructures",
- Type = "boolean",
- },
- },
- Notes = "Sets the chunk to use default structures or not",
- },
- UpdateHeightmap =
- {
- Notes = "Updates the heightmap to match current contents. The plugins should do that if they modify the contents and don't modify the heightmap accordingly; Cuberite expects (and checks in Debug mode) that the heightmap matches the contents when the cChunkDesc is returned from a plugin.",
- },
- WriteBlockArea =
- {
- Params =
- {
- {
- Name = "BlockArea",
- Type = "cBlockArea",
- },
- {
- Name = "MinRelX",
- Type = "number",
- },
- {
- Name = "MinRelY",
- Type = "number",
- },
- {
- Name = "MinRelZ",
- Type = "number",
- },
- {
- Name = "MergeStrategy",
- Type = "cBlockArea",
- IsOptional = true,
- },
- },
- Notes = "Writes data from the block area into the chunk",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Manipulating block entities",
- Contents = [[
- To manipulate block entities while the chunk is generated, first use SetBlockTypeMeta() to set
- the correct block type and meta at the position. Then use the GetBlockEntity() to create and
- return the correct block entity instance. Finally, use {{tolua}}.cast() to cast to the proper
- type.
- Note that you don't need to check if a block entity has previously existed at the place, because
- GetBlockEntity() will automatically re-create the correct type for you.
-
- The following code is taken from the Debuggers plugin, it creates a sign at each chunk's [0, 0]
- coords, with the text being the chunk coords:
-
-function OnChunkGenerated(a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc)
- -- Get the topmost block coord:
- local Height = a_ChunkDesc:GetHeight(0, 0);
-
- -- Create a sign there:
- a_ChunkDesc:SetBlockTypeMeta(0, Height + 1, 0, E_BLOCK_SIGN_POST, 0);
- local BlockEntity = a_ChunkDesc:GetBlockEntity(0, Height + 1, 0);
- if (BlockEntity ~= nil) then
- LOG("Setting sign lines...");
- local SignEntity = tolua.cast(BlockEntity, "cSignEntity");
- SignEntity:SetLines("Chunk:", tonumber(a_ChunkX) .. ", " .. tonumber(a_ChunkZ), "", "(Debuggers)");
- end
-
- -- Update the heightmap:
- a_ChunkDesc:SetHeight(0, 0, Height + 1);
-end
-
- ]],
- },
- },
- },
- cClientHandle =
- {
- Desc = [[
- A cClientHandle represents the technical aspect of a connected player - their game client
- connection. Internally, it handles all the incoming and outgoing packets, the chunks that are to be
- sent to the client, ping times etc.
- ]],
- Functions =
- {
- GenerateOfflineUUID =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Username",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Generates an UUID based on the player name provided. This is used for the offline (non-auth) mode, when there's no UUID source. Each username generates a unique and constant UUID, so that when the player reconnects with the same name, their UUID is the same. Returns a 32-char UUID (no dashes).",
- },
- GetClientBrand =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the brand that the client has sent in their MC|Brand plugin message.",
- },
- GetIPString =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the IP address of the connection, as a string. Only the address part is returned, without the port number.",
- },
- GetLocale =
- {
- Returns =
- {
- {
- Name = "Locale",
- Type = "string",
- },
- },
- Notes = "Returns the locale string that the client sends as part of the protocol handshake. Can be used to provide localized strings.",
- },
- GetPing =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the ping time, in ms",
- },
- GetPlayer =
- {
- Returns =
- {
- {
- Type = "cPlayer",
- },
- },
- Notes = "Returns the player object connected to this client. Note that this may be nil, for example if the player object is not yet spawned.",
- },
- GetProtocolVersion =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the protocol version number of the protocol that the client is talking. Returns zero if the protocol version is not (yet) known.",
- },
- GetRequestedViewDistance =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the view distance that the player request, not the used view distance.",
- },
- GetUniqueID =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the UniqueID of the client used to identify the client in the server",
- },
- GetUsername =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the username that the client has provided",
- },
- GetUUID =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the authentication-based UUID of the client. This UUID should be used to identify the player when persisting any player-related data. Returns a 32-char UUID (no dashes)",
- },
- GetViewDistance =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the viewdistance (number of chunks loaded for the player in each direction)",
- },
- HasPluginChannel =
- {
- Params =
- {
- {
- Name = "ChannelName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the client has registered to receive messages on the specified plugin channel.",
- },
- IsUUIDOnline =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "UUID",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the UUID is generated by online auth, false if it is an offline-generated UUID. We use Version-3 UUIDs for offline UUIDs, online UUIDs are Version-4, thus we can tell them apart. Accepts both 32-char and 36-char UUIDs (with and without dashes). If the string given is not a valid UUID, returns false.",
- },
- Kick =
- {
- Params =
- {
- {
- Name = "Reason",
- Type = "string",
- },
- },
- Notes = "Kicks the user with the specified reason",
- },
- SendBlockChange =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Sends a BlockChange packet to the client. This can be used to create fake blocks only for that player.",
- },
- SendEntityAnimation =
- {
- Params =
- {
- {
- Name = "Entity",
- Type = "cEntity",
- },
- {
- Name = "AnimationNumber",
- Type = "number",
- },
- },
- Notes = "Sends the specified animation of the specified entity to the client. The AnimationNumber is protocol-specific.",
- },
- SendPluginMessage =
- {
- Params =
- {
- {
- Name = "Channel",
- Type = "string",
- },
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Sends the plugin message on the specified channel.",
- },
- SendSoundEffect =
- {
- Params =
- {
- {
- Name = "SoundName",
- Type = "string",
- },
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "Volume",
- Type = "number",
- },
- {
- Name = "Pitch",
- Type = "number",
- },
- },
- Notes = "Sends a sound effect request to the client. The sound is played at the specified coords, with the specified volume (a float, 1.0 is full volume, can be more) and pitch (0-255, 63 is 100%)",
- },
- SendTimeUpdate =
- {
- Params =
- {
- {
- Name = "WorldAge",
- Type = "number",
- },
- {
- Name = "TimeOfDay",
- Type = "number",
- },
- {
- Name = "DoDaylightCycle",
- Type = "boolean",
- },
- },
- Notes = "Sends the specified time update to the client. WorldAge is the total age of the world, in ticks. TimeOfDay is the current day's time, in ticks (0 - 24000). DoDaylightCycle is a bool that specifies whether the client should automatically move the sun (true) or keep it in the same place (false).",
- },
- SetClientBrand =
- {
- Params =
- {
- {
- Name = "ClientBrand",
- Type = "string",
- },
- },
- Notes = "Sets the value of the client's brand. Normally this value is received from the client by a MC|Brand plugin message, this function lets plugins overwrite the value.",
- },
- SetLocale =
- {
- Params =
- {
- {
- Name = "Locale",
- Type = "string",
- },
- },
- Notes = "Sets the locale that Cuberite keeps on record. Initially the locale is initialized in protocol handshake, this function allows plugins to override the stored value (but only server-side and only until the user disconnects).",
- },
- SetUsername =
- {
- Params =
- {
- {
- Name = "Name",
- Type = "string",
- },
- },
- Notes = "Sets the username",
- },
- SetViewDistance =
- {
- Params =
- {
- {
- Name = "ViewDistance",
- Type = "number",
- },
- },
- Notes = "Sets the viewdistance (number of chunks loaded for the player in each direction)",
- },
- },
- Constants =
- {
- MAX_VIEW_DISTANCE =
- {
- Notes = "The maximum value of the view distance",
- },
- MIN_VIEW_DISTANCE =
- {
- Notes = "The minimum value of the view distance",
- },
- },
- },
- cCompositeChat =
- {
- Desc = [[
- Encapsulates a chat message that can contain various formatting, URLs, commands executed on click
- and commands suggested on click. The chat message can be sent by the regular chat-sending functions,
- {{cPlayer}}:SendMessage(), {{cWorld}}:BroadcastChat() and {{cRoot}}:BroadcastChat().
-
- Note that most of the functions in this class are so-called chaining modifiers - they modify the
- object and then return the object itself, so that they can be chained one after another. See the
- Chaining example below for details.
-
- Each part of the composite chat message takes a "Style" parameter, this is a string that describes
- the formatting. It uses the following strings, concatenated together:
-
-
String
Style
-
b
Bold text
-
i
Italic text
-
u
Underlined text
-
s
Strikethrough text
-
o
Obfuscated text
-
@X
color X (X is 0 - 9 or a - f, same as dye meta
-
- The following picture, taken from MineCraft Wiki, illustrates the color codes:
-
- ]],
- Functions =
- {
- AddRunCommandPart =
- {
- Params =
- {
- {
- Name = "Text",
- Type = "string",
- },
- {
- Name = "Command",
- Type = "string",
- },
- {
- Name = "Style",
- Type = "string",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "self",
- },
- },
- Notes = "Adds a text which, when clicked, runs the specified command. Chaining.",
- },
- AddShowAchievementPart =
- {
- Params =
- {
- {
- Name = "PlayerName",
- Type = "string",
- },
- {
- Name = "AchievementName",
- Type = "string",
- },
- {
- Name = "Style",
- Type = "string",
- IsOptional = true,
- },
- },
- Notes = "Adds a text that represents the 'Achievement get' message.",
- },
- AddSuggestCommandPart =
- {
- Params =
- {
- {
- Name = "Text",
- Type = "string",
- },
- {
- Name = "Command",
- Type = "string",
- },
- {
- Name = "Style",
- Type = "string",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "self",
- },
- },
- Notes = "Adds a text which, when clicked, puts the specified command into the player's chat input area. Chaining.",
- },
- AddTextPart =
- {
- Params =
- {
- {
- Name = "Text",
- Type = "string",
- },
- {
- Name = "Style",
- Type = "string",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "self",
- },
- },
- Notes = "Adds a regular text. Chaining.",
- },
- AddUrlPart =
- {
- Params =
- {
- {
- Name = "Text",
- Type = "string",
- },
- {
- Name = "Url",
- Type = "string",
- },
- {
- Name = "Style",
- Type = "string",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "self",
- },
- },
- Notes = "Adds a text which, when clicked, opens up a browser at the specified URL. Chaining.",
- },
- Clear =
- {
- Returns = "self",
- Notes = "Removes all parts from this object",
- },
- constructor =
- {
- {
- Returns = { {Type = "cCompositeChat"} },
- Notes = "Creates an empty chat message",
- },
- {
- Params =
- {
- {
- Name = "Text",
- Type = "string",
- },
- {
- Name = "MessageType",
- Type = "eMessageType",
- IsOptional = true,
- },
- },
- Returns = { {Type = "cCompositeChat"} },
- Notes = "Creates a chat message containing the specified text, parsed by the ParseText() function. This allows easy migration from old chat messages.",
- },
- },
- CreateJsonString =
- {
- Params =
- {
- {
- Name = "AddPrefixes",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the entire object serialized into JSON, as it would be sent to a client. AddPrefixes specifies whether the chat prefixes should be prepended to the message, true by default.",
- },
- ExtractText =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the text from the parts that comprises the human-readable data. Used for older protocols that don't support composite chat, and for console-logging.",
- },
- GetAdditionalMessageTypeData =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the AdditionalData associated with the message, such as the sender's name for mtPrivateMessage",
- },
- GetMessageType =
- {
- Returns =
- {
- {
- Type = "eMessageType",
- },
- },
- Notes = "Returns the MessageType (mtXXX constant) that is associated with this message. When sent to a player, the message will be formatted according to this message type and the player's settings (adding \"[INFO]\" prefix etc.)",
- },
- ParseText =
- {
- Params =
- {
- {
- Name = "Text",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "self",
- },
- },
- Notes = "Adds text, while recognizing http and https URLs and old-style formatting codes (\"@2\"). Chaining.",
- },
- SetMessageType =
- {
- Params =
- {
- {
- Name = "MessageType",
- Type = "eMessageType",
- },
- {
- Name = "AdditionalData",
- Type = "string",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "self",
- },
- },
- Notes = "Sets the MessageType (mtXXX constant) that is associated with this message. Also sets the additional data (string) associated with the message, which is specific for the message type - such as the sender's name for mtPrivateMessage. When sent to a player, the message will be formatted according to this message type and the player's settings (adding \"[INFO]\" prefix etc.). Chaining.",
- },
- UnderlineUrls =
- {
- Returns =
- {
- {
- Type = "self",
- },
- },
- Notes = "Makes all URL parts contained in the message underlined. Doesn't affect parts added in the future. Chaining.",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Chaining example",
- Contents = [[
- Sending a chat message that is composed of multiple different parts has been made easy thanks to
- chaining. Consider the following example that shows how a message containing all kinds of parts
- is sent (adapted from the Debuggers plugin):
-
-function OnPlayerJoined(a_Player)
- -- Send an example composite chat message to the player:
- a_Player:SendMessage(cCompositeChat()
- :AddTextPart("Hello, ")
- :AddUrlPart(a_Player:GetName(), "http://cuberite.org", "u@2") -- Colored underlined link
- :AddSuggestCommandPart(", and welcome.", "/help", "u") -- Underlined suggest-command
- :AddRunCommandPart(" SetDay", "/time set 0") -- Regular text that will execute command when clicked
- :SetMessageType(mtJoin) -- It is a join-message
- )
-end
- ]],
- },
- },
- },
- cCraftingGrid =
- {
- Desc = [[
- cCraftingGrid represents the player's crafting grid. It is used in
- {{OnCraftingNoRecipe|OnCraftingNoRecipe}}, {{OnPostCrafting|OnPostCrafting}} and
- {{OnPreCrafting|OnPreCrafting}} hooks. Plugins may use it to inspect the items the player placed
- on their crafting grid.
-
- Also, an object of this type is used in {{cCraftingRecipe}}'s ConsumeIngredients() function for
- specifying the exact number of ingredients to consume in that recipe; plugins may use this to
- apply the crafting recipe.
- ]],
- Functions =
- {
- Clear =
- {
- Notes = "Clears the entire grid",
- },
- constructor =
- {
- Params =
- {
- {
- Name = "Width",
- Type = "number",
- },
- {
- Name = "Height",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cCraftingGrid",
- },
- },
- Notes = "Creates a new CraftingGrid object. This new crafting grid is not related to any player, but may be needed for {{cCraftingRecipe}}'s ConsumeIngredients function.",
- },
- ConsumeGrid =
- {
- Params =
- {
- {
- Name = "CraftingGrid",
- Type = "cCraftingGrid",
- },
- },
- Notes = "Consumes items specified in CraftingGrid from the current contents. Used internally by {{cCraftingRecipe}}'s ConsumeIngredients() function, but available to plugins, too.",
- },
- Dump =
- {
- Notes = "DEBUG build: Dumps the contents of the grid to the log. RELEASE build: no action",
- },
- GetHeight =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the height of the grid",
- },
- GetItem =
- {
- Params =
- {
- {
- Name = "x",
- Type = "number",
- },
- {
- Name = "y",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item at the specified coords",
- },
- GetWidth =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the width of the grid",
- },
- SetItem =
- {
- {
- Params =
- {
- {
- Name = "x",
- Type = "number",
- },
- {
- Name = "y",
- Type = "number",
- },
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the item at the specified coords",
- },
- {
- Params =
- {
- {
- Name = "x",
- Type = "number",
- },
- {
- Name = "y",
- Type = "number",
- },
- {
- Name = "ItemType",
- Type = "number",
- },
- {
- Name = "ItemCount",
- Type = "number",
- },
- {
- Name = "ItemDamage",
- Type = "number",
- },
- },
- Notes = "Sets the item at the specified coords",
- },
- },
- },
- },
- cCraftingRecipe =
- {
- Desc = [[
- This class is used to represent a crafting recipe, either a built-in one, or one created dynamically in a plugin. It is used only as a parameter for {{OnCraftingNoRecipe|OnCraftingNoRecipe}}, {{OnPostCrafting|OnPostCrafting}} and {{OnPreCrafting|OnPreCrafting}} hooks. Plugins may use it to inspect or modify a crafting recipe that a player views in their crafting window, either at a crafting table or the survival inventory screen.
-
-
Internally, the class contains a {{cCraftingGrid}} for the ingredients and a {{cItem}} for the result.
-]],
- Functions =
- {
- Clear =
- {
- Notes = "Clears the entire recipe, both ingredients and results",
- },
- ConsumeIngredients =
- {
- Params =
- {
- {
- Name = "CraftingGrid",
- Type = "cCraftingGrid",
- },
- },
- Notes = "Consumes ingredients specified in the given {{cCraftingGrid|cCraftingGrid}} class",
- },
- Dump =
- {
- Notes = "DEBUG build: dumps ingredients and result into server log. RELEASE build: no action",
- },
- GetIngredient =
- {
- Params =
- {
- {
- Name = "x",
- Type = "number",
- },
- {
- Name = "y",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the ingredient stored in the recipe at the specified coords",
- },
- GetIngredientsHeight =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the height of the ingredients' grid",
- },
- GetIngredientsWidth =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the width of the ingredients' grid",
- },
- GetResult =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the result of the recipe",
- },
- SetIngredient =
- {
- {
- Params =
- {
- {
- Name = "x",
- Type = "number",
- },
- {
- Name = "y",
- Type = "number",
- },
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the ingredient at the specified coords",
- },
- {
- Params =
- {
- {
- Name = "x",
- Type = "number",
- },
- {
- Name = "y",
- Type = "number",
- },
- {
- Name = "ItemType",
- Type = "number",
- },
- {
- Name = "ItemCount",
- Type = "number",
- },
- {
- Name = "ItemDamage",
- Type = "number",
- },
- },
- Notes = "Sets the ingredient at the specified coords",
- },
- },
- SetResult =
- {
- {
- Params =
- {
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the result item",
- },
- {
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- {
- Name = "ItemCount",
- Type = "number",
- },
- {
- Name = "ItemDamage",
- Type = "number",
- },
- },
- Notes = "Sets the result item",
- },
- },
- },
- },
- cCryptoHash =
- {
- Desc = [[
- Provides functions for generating cryptographic hashes.
-
- Note that all functions in this class are super-static, so they are to be called in the dot convention:
-
Each cryptographic hash has two variants, one returns the hash as a raw binary string, the other returns the hash as a hex-encoded string twice as long as the binary string.
- ]],
- Functions =
- {
- md5 =
- {
- IsStatic = true,
- IsGlobal = true,
- Params =
- {
- {
- Name = "Data",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Calculates the md5 hash of the data, returns it as a raw (binary) string of 16 characters.",
- },
- md5HexString =
- {
- IsStatic = true,
- IsGlobal = true,
- Params =
- {
- {
- Name = "Data",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Calculates the md5 hash of the data, returns it as a hex-encoded string of 32 characters.",
- },
- sha1 =
- {
- IsStatic = true,
- IsGlobal = true,
- Params =
- {
- {
- Name = "Data",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Calculates the sha1 hash of the data, returns it as a raw (binary) string of 20 characters.",
- },
- sha1HexString =
- {
- IsStatic = true,
- IsGlobal = true,
- Params =
- {
- {
- Name = "Data",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Calculates the sha1 hash of the data, returns it as a hex-encoded string of 40 characters.",
- },
- },
- },
- 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.
-
- 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.
-
- See the {{cItem}} class for usage examples.
- ]],
- Functions =
- {
- Add =
- {
- Params =
- {
- {
- Name = "Other",
- Type = "cEnchantments",
- },
- },
- Notes = "Adds the enchantments contained in Other into this object. Existing enchantments are preserved, unless Other specifies a different level, in which case the level is changed to the Other's one.",
- },
- AddFromString =
- {
- Params =
- {
- {
- Name = "StringSpec",
- Type = "string",
- },
- },
- Notes = "Adds the enchantments in the string description into the object. If a specified enchantment already existed, it is overwritten.",
- },
- Clear =
- {
- Notes = "Removes all enchantments",
- },
- constructor =
- {
- {
- Returns =
- {
- {
- Type = "cEnchantments",
- },
- },
- Notes = "Creates a new empty cEnchantments object",
- },
- {
- Params =
- {
- {
- Name = "StringSpec",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "cEnchantments",
- },
- },
- Notes = "Creates a new cEnchantments object filled with enchantments based on the string description",
- },
- },
- Count =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Get the count of enchantments contained within the class",
- },
- GetLevel =
- {
- Params =
- {
- {
- Name = "EnchantmentNumID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the level of the specified enchantment stored in this object; 0 if not stored",
- },
- IsEmpty =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the object stores no enchantments",
- },
- operator_eq =
- {
- Params =
- {
- {
- Name = "OtherEnchantments",
- Type = "cEnchantments",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if this enchantments object has the same enchantments as OtherEnchantments.",
- },
- SetLevel =
- {
- Params =
- {
- {
- Name = "EnchantmentNumID",
- Type = "number",
- },
- {
- Name = "Level",
- Type = "number",
- },
- },
- Notes = "Sets the level for the specified enchantment, adding it if not stored before, or removing it if Level < = 0",
- },
- StringToEnchantmentID =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "EnchantmentName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the enchantment numerical ID, -1 if not understood. Case insensitive. Also understands plain numbers.",
- },
- ToString =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the string description of all the enchantments stored in this object, in numerical-ID form",
- },
- },
- Constants =
- {
- enchAquaAffinity =
- {
- Notes = "",
- },
- enchBaneOfArthropods =
- {
- Notes = "",
- },
- enchBlastProtection =
- {
- Notes = "",
- },
- enchEfficiency =
- {
- Notes = "",
- },
- enchFeatherFalling =
- {
- Notes = "",
- },
- enchFireAspect =
- {
- Notes = "",
- },
- enchFireProtection =
- {
- Notes = "",
- },
- enchFlame =
- {
- Notes = "",
- },
- enchFortune =
- {
- Notes = "",
- },
- enchInfinity =
- {
- Notes = "",
- },
- enchKnockback =
- {
- Notes = "",
- },
- enchLooting =
- {
- Notes = "",
- },
- enchLuckOfTheSea =
- {
- Notes = "",
- },
- enchLure =
- {
- Notes = "",
- },
- enchPower =
- {
- Notes = "",
- },
- enchProjectileProtection =
- {
- Notes = "",
- },
- enchProtection =
- {
- Notes = "",
- },
- enchPunch =
- {
- Notes = "",
- },
- enchRespiration =
- {
- Notes = "",
- },
- enchSharpness =
- {
- Notes = "",
- },
- enchSilkTouch =
- {
- Notes = "",
- },
- enchSmite =
- {
- Notes = "",
- },
- enchThorns =
- {
- Notes = "",
- },
- enchUnbreaking =
- {
- Notes = "",
- },
- },
- },
- cEntity =
- {
- Desc = [[
- A cEntity object represents an object in the world, it has a position and orientation. cEntity is an
- abstract class, and can not be instantiated directly, instead, all entities are implemented as
- subclasses. The cEntity class works as the common interface for the operations that all (most)
- entities support.
-
- All cEntity objects have an Entity Type so it can be determined what kind of entity it is
- efficiently. Entities also have a class inheritance awareness, they know their class name,
- their parent class' name and can decide if there is a class within their inheritance chain.
- Since these functions operate on strings, they are slightly slower than checking the entity type
- directly, on the other hand, they are more specific directly. To check if the entity is a spider,
- you need to call IsMob(), then cast the object to {{cMonster}} and finally compare
- {{cMonster}}:GetMonsterType() to mtSpider. GetClass(), on the other hand, returns "cSpider"
- directly.
-
- Note that you should not store a cEntity object between two hooks' calls, because Cuberite may
- despawn / remove that entity in between the calls. If you need to refer to an entity later, use its
- UniqueID and {{cWorld|cWorld}}'s entity manipulation functions DoWithEntityByID(), ForEachEntity()
- or ForEachEntityInChunk() to access the entity again.
- ]],
- Functions =
- {
- AddPosition =
- {
- {
- Params =
- {
- {
- Name = "OffsetX",
- Type = "number",
- },
- {
- Name = "OffsetY",
- Type = "number",
- },
- {
- Name = "OffsetZ",
- Type = "number",
- },
- },
- Notes = "Moves the entity by the specified amount in each axis direction",
- },
- {
- Params =
- {
- {
- Name = "Offset",
- Type = "Vector3d",
- },
- },
- Notes = "Moves the entity by the specified amount in each direction",
- },
- },
- AddPosX =
- {
- Params =
- {
- {
- Name = "OffsetX",
- Type = "number",
- },
- },
- Notes = "Moves the entity by the specified amount in the X axis direction",
- },
- AddPosY =
- {
- Params =
- {
- {
- Name = "OffsetY",
- Type = "number",
- },
- },
- Notes = "Moves the entity by the specified amount in the Y axis direction",
- },
- AddPosZ =
- {
- Params =
- {
- {
- Name = "OffsetZ",
- Type = "number",
- },
- },
- Notes = "Moves the entity by the specified amount in the Z axis direction",
- },
- AddSpeed =
- {
- {
- Params =
- {
- {
- Name = "AddX",
- Type = "number",
- },
- {
- Name = "AddY",
- Type = "number",
- },
- {
- Name = "AddZ",
- Type = "number",
- },
- },
- Notes = "Adds the specified amount of speed in each axis direction.",
- },
- {
- Params =
- {
- {
- Name = "Add",
- Type = "Vector3d",
- },
- },
- Notes = "Adds the specified amount of speed in each axis direction.",
- },
- },
- AddSpeedX =
- {
- Params =
- {
- {
- Name = "AddX",
- Type = "number",
- },
- },
- Notes = "Adds the specified amount of speed in the X axis direction.",
- },
- AddSpeedY =
- {
- Params =
- {
- {
- Name = "AddY",
- Type = "number",
- },
- },
- Notes = "Adds the specified amount of speed in the Y axis direction.",
- },
- AddSpeedZ =
- {
- Params =
- {
- {
- Name = "AddZ",
- Type = "number",
- },
- },
- Notes = "Adds the specified amount of speed in the Z axis direction.",
- },
- ArmorCoversAgainst =
- {
- Params =
- {
- {
- Name = "DamageType",
- Type = "eDamageType",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether armor will protect against the specified damage type",
- },
- Destroy =
- {
- Params =
- {
- {
- Name = "ShouldBroadcast",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Notes = "Schedules the entity to be destroyed; if ShouldBroadcast is not present or set to true, broadcasts the DestroyEntity packet",
- },
- GetAirLevel =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the air level (number of ticks of air left). Note, this function is only updated with mobs or players.",
- },
- GetArmorCoverAgainst =
- {
- Params =
- {
- {
- Name = "AttackerEntity",
- Type = "cEntity",
- },
- {
- Name = "DamageType",
- Type = "eDamageType",
- },
- {
- Name = "RawDamage",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of hitpoints out of RawDamage that the currently equipped armor would cover. See {{TakeDamageInfo}} for more information on attack damage.",
- },
- GetChunkX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the X-coord of the chunk in which the entity is placed",
- },
- GetChunkZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the Z-coord of the chunk in which the entity is placed",
- },
- GetClass =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the classname of the entity, such as \"cSpider\" or \"cPickup\"",
- },
- GetClassStatic =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the entity classname that this class implements. Each descendant overrides this function. Is static",
- },
- GetEntityType =
- {
- Returns =
- {
- {
- Name = "EntityType",
- Type = "cEntity#EntityType",
- },
- },
- Notes = "Returns the type of the entity, one of the {{cEntity#EntityType|etXXX}} constants. Note that to check specific entity type, you should use one of the IsXXX functions instead of comparing the value returned by this call.",
- },
- GetEquippedBoots =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the boots that the entity has equipped. Returns an empty cItem if no boots equipped or not applicable.",
- },
- GetEquippedChestplate =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the chestplate that the entity has equipped. Returns an empty cItem if no chestplate equipped or not applicable.",
- },
- GetEquippedHelmet =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the helmet that the entity has equipped. Returns an empty cItem if no helmet equipped or not applicable.",
- },
- GetEquippedLeggings =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the leggings that the entity has equipped. Returns an empty cItem if no leggings equipped or not applicable.",
- },
- GetEquippedWeapon =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the weapon that the entity has equipped. Returns an empty cItem if no weapon equipped or not applicable.",
- },
- GetGravity =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number that is used as the gravity for physics simulation. 1G (9.78) by default.",
- },
- GetHeadYaw =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the pitch of the entity's head (FIXME: Rename to GetHeadPitch() ).",
- },
- GetHealth =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the current health of the entity.",
- },
- GetHeight =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the height (Y size) of the entity",
- },
- GetInvulnerableTicks =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of ticks that this entity will be invulnerable for. This is used for after-hit recovery - the entities are invulnerable for half a second after being hit.",
- },
- GetKnockbackAmountAgainst =
- {
- Params =
- {
- {
- Name = "ReceiverEntity",
- Type = "cEntity",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the amount of knockback that the currently equipped items would cause when attacking the ReceiverEntity.",
- },
- GetLookVector =
- {
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Returns the vector that defines the direction in which the entity is looking",
- },
- GetMass =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the mass of the entity. Currently unused.",
- },
- GetMaxHealth =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the maximum number of hitpoints this entity is allowed to have.",
- },
- GetParentClass =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the direct parent class for this entity",
- },
- GetPitch =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the pitch (nose-down rotation) of the entity. Measured in degrees, normal values range from -90 to +90. +90 means looking down, 0 means looking straight ahead, -90 means looking up.",
- },
- GetPosition =
- {
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns the entity's pivot position as a 3D vector",
- },
- GetPosX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the X-coord of the entity's pivot",
- },
- GetPosY =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the Y-coord of the entity's pivot",
- },
- GetPosZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the Z-coord of the entity's pivot",
- },
- GetRawDamageAgainst =
- {
- Params =
- {
- {
- Name = "ReceiverEntity",
- Type = "cEntity",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the raw damage that this entity's equipment would cause when attacking the ReceiverEntity. This includes this entity's weapon {{cEnchantments|enchantments}}, but excludes the receiver's armor or potion effects. See {{TakeDamageInfo}} for more information on attack damage.",
- },
- GetRoll =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the roll (sideways rotation) of the entity. Currently unused.",
- },
- GetRot =
- {
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "(OBSOLETE) Returns the entire rotation vector (Yaw, Pitch, Roll)",
- },
- GetSpeed =
- {
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns the complete speed vector of the entity",
- },
- GetSpeedX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the X-part of the speed vector",
- },
- GetSpeedY =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the Y-part of the speed vector",
- },
- GetSpeedZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the Z-part of the speed vector",
- },
- GetTicksAlive =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of ticks that this entity has been alive for.",
- },
- GetUniqueID =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the ID that uniquely identifies the entity within the running server. Note that this ID is not persisted to the data files.",
- },
- GetWidth =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the width (X and Z size) of the entity.",
- },
- GetWorld =
- {
- Returns =
- {
- {
- Type = "cWorld",
- },
- },
- Notes = "Returns the world where the entity resides",
- },
- GetYaw =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the yaw (direction) of the entity. Measured in degrees, values range from -180 to +180. 0 means ZP, 90 means XM, -180 means ZM, -90 means XP.",
- },
- HandleSpeedFromAttachee =
- {
- Params =
- {
- {
- Name = "ForwardAmount",
- Type = "number",
- },
- {
- Name = "SidewaysAmount",
- Type = "number",
- },
- },
- Notes = "Updates the entity's speed based on the attachee exerting the specified force forward and sideways. Used for entities being driven by other entities attached to them - usually players driving minecarts and boats.",
- },
- Heal =
- {
- Params =
- {
- {
- Name = "Hitpoints",
- Type = "number",
- },
- },
- Notes = "Heals the specified number of hitpoints. Hitpoints is expected to be a positive number.",
- },
- IsA =
- {
- Params =
- {
- {
- Name = "ClassName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity class is a descendant of the specified class name, or the specified class itself",
- },
- IsBoat =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity is a {{cBoat|boat}}.",
- },
- IsCrouched =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity is crouched. Always false for entities that don't support crouching.",
- },
- IsDestroyed =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "(DEPRECATED) Please use cEntity:IsTicking().",
- },
- IsEnderCrystal =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity is an ender crystal.",
- },
- IsExpOrb =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity represents an experience orb",
- },
- IsFallingBlock =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity represents a {{cFallingBlock}} entity.",
- },
- IsFireproof =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity takes no damage from being on fire.",
- },
- IsFloater =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity represents a fishing rod floater",
- },
- IsInvisible =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity is invisible",
- },
- IsItemFrame =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity is an item frame.",
- },
- IsMinecart =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity represents a {{cMinecart|minecart}}",
- },
- IsMob =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity represents any {{cMonster|mob}}.",
- },
- IsOnFire =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity is on fire",
- },
- IsOnGround =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity is on ground (not falling, not jumping, not flying)",
- },
- IsPainting =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns if this entity is a painting.",
- },
- IsPawn =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity is a {{cPawn}} descendant.",
- },
- IsPickup =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity represents a {{cPickup|pickup}}.",
- },
- IsPlayer =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity represents a {{cPlayer|player}}",
- },
- IsProjectile =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity is a {{cProjectileEntity}} descendant.",
- },
- IsRclking =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Currently unimplemented",
- },
- IsRiding =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity is attached to (riding) another entity.",
- },
- IsSprinting =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity is sprinting. Entities that cannot sprint return always false",
- },
- IsSubmerged =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the mob or player is submerged in water (head is in a water block). Note, this function is only updated with mobs or players.",
- },
- IsSwimming =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the mob or player is swimming in water (feet are in a water block). Note, this function is only updated with mobs or players.",
- },
- IsTicking =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity is valid and ticking. Returns false if the entity is not ticking and is about to leave its current world either via teleportation or destruction. If this returns false, you must stop using the cEntity pointer you have.",
- },
- IsTNT =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the entity represents a {{cTNTEntity|TNT entity}}",
- },
- Killed =
- {
- Params =
- {
- {
- Name = "Victim",
- Type = "cEntity",
- },
- },
- Notes = "This entity has killed another entity (the Victim). For players, adds the scoreboard statistics about the kill.",
- },
- KilledBy =
- {
- Notes = "FIXME: Remove this from API",
- },
- MoveToWorld =
- {
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "ShouldSendRespawn",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Removes the entity from this world and starts moving it to the specified world's spawn point. Note that to avoid deadlocks, the move is asynchronous - the entity is moved into a queue and will be moved from that queue into the destination world at some (unpredictable) time in the future. ShouldSendRespawn is used only for players, it specifies whether the player should be sent a Respawn packet upon leaving the world (The client handles respawns only between different dimensions). OBSOLETE, use ScheduleMoveToWorld() instead.",
- },
- {
- Params =
- {
- {
- Name = "WorldName",
- Type = "string",
- },
- {
- Name = "ShouldSendRespawn",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Removes the entity from this world and starts moving it to the specified world's spawn point. Note that to avoid deadlocks, the move is asynchronous - the entity is moved into a queue and will be moved from that queue into the destination world at some (unpredictable) time in the future. ShouldSendRespawn is used only for players, it specifies whether the player should be sent a Respawn packet upon leaving the world (The client handles respawns only between different dimensions). OBSOLETE, use ScheduleMoveToWorld() instead.",
- },
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "ShouldSendRespawn",
- Type = "boolean",
- },
- {
- Name = "Position",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Removes the entity from this world and starts moving it to the specified world. Note that to avoid deadlocks, the move is asynchronous - the entity is moved into a queue and will be moved from that queue into the destination world at some (unpredictable) time in the future. ShouldSendRespawn is used only for players, it specifies whether the player should be sent a Respawn packet upon leaving the world (The client handles respawns only between different dimensions). The Position parameter specifies the location that the entity should be placed in, in the new world. OBSOLETE, use ScheduleMoveToWorld() instead.",
- },
- },
- ScheduleMoveToWorld =
- {
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "NewPosition",
- Type = "Vector3d",
- },
- {
- Name = "ShouldSetPortalCooldown",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Notes = "Schedules a MoveToWorld call to occur on the next Tick of the entity. If ShouldSetPortalCooldown is false (default), doesn't set any portal cooldown, if it is true, the default portal cooldown is applied to the entity.",
- },
- SetGravity =
- {
- Params =
- {
- {
- Name = "Gravity",
- Type = "number",
- },
- },
- Notes = "Sets the number that is used as the gravity for physics simulation. 1G (9.78) by default.",
- },
- SetHeadYaw =
- {
- Params =
- {
- {
- Name = "HeadPitch",
- Type = "number",
- },
- },
- Notes = "Sets the head pitch (FIXME: Rename to SetHeadPitch() ).",
- },
- SetHealth =
- {
- Params =
- {
- {
- Name = "Hitpoints",
- Type = "number",
- },
- },
- Notes = "Sets the entity's health to the specified amount of hitpoints. Doesn't broadcast any hurt animation. Doesn't kill the entity if health drops below zero. Use the TakeDamage() function instead for taking damage.",
- },
- SetHeight =
- {
- Notes = "FIXME: Remove this from API",
- },
- SetInvulnerableTicks =
- {
- Params =
- {
- {
- Name = "NumTicks",
- Type = "number",
- },
- },
- Notes = "Sets the amount of ticks for which the entity will not receive any damage from other entities.",
- },
- SetIsFireproof =
- {
- Params =
- {
- {
- Name = "IsFireproof",
- Type = "boolean",
- },
- },
- Notes = "Sets whether the entity receives damage from being on fire.",
- },
- SetMass =
- {
- Params =
- {
- {
- Name = "Mass",
- Type = "number",
- },
- },
- Notes = "Sets the mass of the entity. Currently unused.",
- },
- SetMaxHealth =
- {
- Params =
- {
- {
- Name = "MaxHitpoints",
- Type = "number",
- },
- },
- Notes = "Sets the maximum hitpoints of the entity. If current health is above MaxHitpoints, it is capped to MaxHitpoints.",
- },
- SetPitch =
- {
- Params =
- {
- {
- Name = "Pitch",
- Type = "number",
- },
- },
- Notes = "Sets the pitch (nose-down rotation) of the entity",
- },
- SetPitchFromSpeed =
- {
- Notes = "Sets the entity pitch to match its speed (entity looking forwards as it moves)",
- },
- SetPosition =
- {
- {
- Params =
- {
- {
- Name = "PosX",
- Type = "number",
- },
- {
- Name = "PosY",
- Type = "number",
- },
- {
- Name = "PosZ",
- Type = "number",
- },
- },
- Notes = "Sets all three coords of the entity's pivot",
- },
- {
- Params =
- {
- {
- Name = "Vector3d",
- Type = "Vector3d",
- },
- },
- Notes = "Sets all three coords of the entity's pivot",
- },
- },
- SetPosX =
- {
- Params =
- {
- {
- Name = "PosX",
- Type = "number",
- },
- },
- Notes = "Sets the X-coord of the entity's pivot",
- },
- SetPosY =
- {
- Params =
- {
- {
- Name = "PosY",
- Type = "number",
- },
- },
- Notes = "Sets the Y-coord of the entity's pivot",
- },
- SetPosZ =
- {
- Params =
- {
- {
- Name = "PosZ",
- Type = "number",
- },
- },
- Notes = "Sets the Z-coord of the entity's pivot",
- },
- SetRoll =
- {
- Params =
- {
- {
- Name = "Roll",
- Type = "number",
- },
- },
- Notes = "Sets the roll (sideways rotation) of the entity. Currently unused.",
- },
- SetRot =
- {
- Params =
- {
- {
- Name = "Rotation",
- Type = "Vector3f",
- },
- },
- Notes = "Sets the entire rotation vector (Yaw, Pitch, Roll)",
- },
- SetSpeed =
- {
- {
- Params =
- {
- {
- Name = "SpeedX",
- Type = "number",
- },
- {
- Name = "SpeedY",
- Type = "number",
- },
- {
- Name = "SpeedZ",
- Type = "number",
- },
- },
- Notes = "Sets the current speed of the entity",
- },
- {
- Params =
- {
- {
- Name = "Speed",
- Type = "Vector3d",
- },
- },
- Notes = "Sets the current speed of the entity",
- },
- },
- SetSpeedX =
- {
- Params =
- {
- {
- Name = "SpeedX",
- Type = "number",
- },
- },
- Notes = "Sets the X component of the entity speed",
- },
- SetSpeedY =
- {
- Params =
- {
- {
- Name = "SpeedY",
- Type = "number",
- },
- },
- Notes = "Sets the Y component of the entity speed",
- },
- SetSpeedZ =
- {
- Params =
- {
- {
- Name = "SpeedZ",
- Type = "number",
- },
- },
- Notes = "Sets the Z component of the entity speed",
- },
- SetWidth =
- {
- Notes = "FIXME: Remove this from API",
- },
- SetYaw =
- {
- Params =
- {
- {
- Name = "Yaw",
- Type = "number",
- },
- },
- Notes = "Sets the yaw (direction) of the entity.",
- },
- SetYawFromSpeed =
- {
- Notes = "Sets the entity's yaw to match its current speed (entity looking forwards as it moves).",
- },
- StartBurning =
- {
- Params =
- {
- {
- Name = "NumTicks",
- Type = "number",
- },
- },
- Notes = "Sets the entity on fire for the specified number of ticks. If entity is on fire already, makes it burn for either NumTicks or the number of ticks left from the previous fire, whichever is larger.",
- },
- SteerVehicle =
- {
- Params =
- {
- {
- Name = "ForwardAmount",
- Type = "number",
- },
- {
- Name = "SidewaysAmount",
- Type = "number",
- },
- },
- Notes = "Applies the specified steering to the vehicle this entity is attached to. Ignored if not attached to any entity.",
- },
- StopBurning =
- {
- Notes = "Extinguishes the entity fire, cancels all fire timers.",
- },
- TakeDamage =
- {
- {
- Params =
- {
- {
- Name = "AttackerEntity",
- Type = "cEntity",
- },
- },
- Notes = "Causes this entity to take damage that AttackerEntity would inflict. Includes their weapon and this entity's armor.",
- },
- {
- Params =
- {
- {
- Name = "DamageType",
- Type = "eDamageType",
- },
- {
- Name = "AttackerEntity",
- Type = "cEntity",
- },
- {
- Name = "RawDamage",
- Type = "number",
- },
- {
- Name = "KnockbackAmount",
- Type = "number",
- },
- },
- Notes = "Causes this entity to take damage of the specified type, from the specified attacker (may be nil). The final damage is calculated from RawDamage using the currently equipped armor.",
- },
- {
- Params =
- {
- {
- Name = "DamageType",
- Type = "eDamageType",
- },
- {
- Name = "AttackerEntity",
- Type = "cEntity",
- },
- {
- Name = "RawDamage",
- Type = "number",
- },
- {
- Name = "FinalDamage",
- Type = "number",
- },
- {
- Name = "KnockbackAmount",
- Type = "number",
- },
- },
- Notes = "Causes this entity to take damage of the specified type, from the specified attacker (may be nil). The values are wrapped into a {{TakeDamageInfo}} structure and applied directly.",
- },
- },
- TeleportToCoords =
- {
- Params =
- {
- {
- Name = "PosX",
- Type = "number",
- },
- {
- Name = "PosY",
- Type = "number",
- },
- {
- Name = "PosZ",
- Type = "number",
- },
- },
- Notes = "Teleports the entity to the specified coords. Asks plugins if the teleport is allowed.",
- },
- TeleportToEntity =
- {
- Params =
- {
- {
- Name = "DestEntity",
- Type = "cEntity",
- },
- },
- Notes = "Teleports this entity to the specified destination entity. Asks plugins if the teleport is allowed.",
- },
- },
- Constants =
- {
- etBoat =
- {
- Notes = "The entity is a {{cBoat}}",
- },
- etEnderCrystal =
- {
- Notes = "",
- },
- etEntity =
- {
- Notes = "No further specialization available",
- },
- etExpOrb =
- {
- Notes = "The entity is a {{cExpOrb}}",
- },
- etFallingBlock =
- {
- Notes = "The entity is a {{cFallingBlock}}",
- },
- etFloater =
- {
- Notes = "The entity is a fishing rod floater",
- },
- etItemFrame =
- {
- Notes = "",
- },
- etMinecart =
- {
- Notes = "The entity is a {{cMinecart}} descendant",
- },
- etMob =
- {
- Notes = "The entity is a {{cMonster}} descendant",
- },
- etMonster =
- {
- Notes = "The entity is a {{cMonster}} descendant",
- },
- etPainting =
- {
- Notes = "The entity is a {{cPainting}}",
- },
- etPickup =
- {
- Notes = "The entity is a {{cPickup}}",
- },
- etPlayer =
- {
- Notes = "The entity is a {{cPlayer}}",
- },
- etProjectile =
- {
- Notes = "The entity is a {{cProjectileEntity}} descendant",
- },
- etTNT =
- {
- Notes = "The entity is a {{cTNTEntity}}",
- },
- },
- ConstantGroups =
- {
- EntityType =
- {
- Include = "et.*",
- TextBefore = "The following constants are used to distinguish between different entity types:",
- },
- },
- },
- cEntityEffect =
- {
- Functions =
- {
- GetPotionColor =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemDamage",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the potion color (used by the client for visuals), based on the potion's damage value",
- },
- GetPotionEffectDuration =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemDamage",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the effect duration, in ticks, based on the potion's damage value",
- },
- GetPotionEffectIntensity =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemDamage",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "short",
- Type = "number",
- },
- },
- Notes = "Retrieves the intensity level from the potion's damage value. Returns 0 for level I potions, 1 for level II potions.",
- },
- GetPotionEffectType =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemDamage",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "eType",
- Type = "cEntityEffect#eType",
- },
- },
- Notes = "Translates the potion's damage value into the entity effect that the potion gives",
- },
- IsPotionDrinkable =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemDamage",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the potion with the given damage is drinkable",
- },
- },
- },
- cFile =
- {
- Desc = [[
- Provides helper functions for manipulating and querying the filesystem. Most functions are static,
- so they should be called directly on the cFile class itself:
-
-cFile:DeleteFile("/usr/bin/virus.exe");
-
- ]],
- Functions =
- {
- ChangeFileExt =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "FileName",
- Type = "string",
- },
- {
- Name = "NewExt",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns FileName with its extension changed to NewExt. NewExt may begin with a dot, but needn't, the result is the same in both cases (the first dot, if present, is ignored). FileName may contain path elements, extension is recognized as the last dot after the last path separator in the string.",
- },
- Copy =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "SrcFileName",
- Type = "string",
- },
- {
- Name = "DstFileName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Copies a single file to a new destination. Returns true if successful. Fails if the destination already exists.",
- },
- CreateFolder =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "FolderPath",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Creates a new folder. Returns true if successful. Only a single level can be created at a time, use CreateFolderRecursive() to create multiple levels of folders at once.",
- },
- CreateFolderRecursive =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "FolderPath",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Creates a new folder, creating its parents if needed. Returns true if successful.",
- },
- Delete =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Path",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Deletes the specified file or folder. Returns true if successful. Only deletes folders that are empty. NOTE: If you already know if the object is a file or folder, use DeleteFile() or DeleteFolder() explicitly.",
- },
- DeleteFile =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "FilePath",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Deletes the specified file. Returns true if successful.",
- },
- DeleteFolder =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "FolderPath",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Deletes the specified file or folder. Returns true if successful. Only deletes folders that are empty.",
- },
- DeleteFolderContents =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "FolderPath",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Deletes everything from the specified folder, recursively. The specified folder stays intact. Returns true if successful.",
- },
- Exists =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Path",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "Exists",
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified file or folder exists. OBSOLETE, use IsFile() or IsFolder() instead",
- },
- GetExecutableExt =
- {
- IsStatic = true,
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the customary executable extension (including the dot) used by the current platform (\".exe\" on Windows, empty string on Linux). ",
- },
- GetFolderContents =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "FolderName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns the contents of the specified folder, as an array table of strings. Each filesystem object is listed. Use the IsFile() and IsFolder() functions to determine the object type. Note that \".\" and \"..\" are NOT returned. The order of the names is arbitrary (as returned by OS, no sorting).",
- },
- GetLastModificationTime =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Path",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the last modification time (in current timezone) of the specified file or folder. Returns zero if file not found / not accessible. The returned value is in the same units as values returned by os.time().",
- },
- GetPathSeparator =
- {
- IsStatic = true,
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the primary path separator used by the current platform. Returns \"\\\" on Windows and \"/\" on Linux. Note that the platform or CRT may support additional path separators, those are not reported.",
- },
- GetSize =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "FileName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the size of the file, or -1 on failure.",
- },
- IsFile =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Path",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified path points to an existing file.",
- },
- IsFolder =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Path",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified path points to an existing folder.",
- },
- ReadWholeFile =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "FileName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the entire contents of the specified file. Returns an empty string if the file cannot be opened.",
- },
- Rename =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "OrigPath",
- Type = "string",
- },
- {
- Name = "NewPath",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Renames a file or a folder. Returns true if successful. Undefined result if NewPath already exists.",
- },
- },
- },
- cFloater =
- {
- Desc = [[
- Manages the floater created when a player uses their fishing rod.
- ]],
- Functions =
- {
- CanPickup =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the floater gives an item when the player right clicks.",
- },
- GetAttachedMobID =
- {
- Returns =
- {
- {
- Name = "EntityID",
- Type = "number",
- },
- },
- Notes = "Returns the EntityID of a mob that this floater is attached to. Returns -1 if not attached to any mob.",
- },
- GetOwnerID =
- {
- Returns =
- {
- {
- Name = "EntityID",
- Type = "number",
- },
- },
- Notes = "Returns the EntityID of the player who owns the floater.",
- },
- },
- Inherits = "cEntity",
- },
- cHangingEntity =
- {
- Functions =
- {
- GetFacing =
- {
- Returns =
- {
- {
- Name = "BlockFace",
- Type = "eBlockFace",
- },
- },
- Notes = "Returns the direction in which the entity is facing.",
- },
- SetFacing =
- {
- Params =
- {
- {
- Name = "BlockFace",
- Type = "eBlockFace",
- },
- },
- Notes = "Set the direction in which the entity is facing.",
- },
- },
- Inherits = "cEntity",
- },
- cIniFile =
- {
- 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. Cuberite itself uses INI files for settings and options.
-
- The INI files follow this basic structure:
-
-; Header comment line
-[KeyName0]
-; Key comment line 0
-ValueName0=Value0
-ValueName1=Value1
-
-[KeyName1]
-; Key comment line 0
-; Key comment line 1
-ValueName0=SomeOtherValue
-
- 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.
-
- 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.
-
- 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 =
- {
- AddHeaderComment =
- {
- Params =
- {
- {
- Name = "Comment",
- Type = "string",
- },
- },
- Notes = "Adds a comment to be stored in the file header.",
- },
- AddKeyComment =
- {
- {
- Params =
- {
- {
- Name = "KeyID",
- Type = "number",
- },
- {
- Name = "Comment",
- Type = "string",
- },
- },
- Notes = "Adds a comment to be stored in the file under the specified key",
- },
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "Comment",
- Type = "string",
- },
- },
- Notes = "Adds a comment to be stored in the file under the specified key",
- },
- },
- AddKeyName =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Adds a new key of the specified name. Returns the KeyID of the new key.",
- },
- AddValue =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "Value",
- Type = "string",
- },
- },
- Notes = "Adds a new value of the specified name to the specified key. If another value of the same name exists in the key, both are kept (nonstandard INI file)",
- },
- AddValueB =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "Value",
- Type = "boolean",
- },
- },
- Notes = "Adds a new bool value of the specified name to the specified key. If another value of the same name exists in the key, both are kept (nonstandard INI file)",
- },
- AddValueF =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "Value",
- Type = "number",
- },
- },
- Notes = "Adds a new float value of the specified name to the specified key. If another value of the same name exists in the key, both are kept (nonstandard INI file)",
- },
- AddValueI =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "Value",
- Type = "number",
- },
- },
- Notes = "Adds a new integer value of the specified name to the specified key. If another value of the same name exists in the key, both are kept (nonstandard INI file)",
- },
- CaseInsensitive =
- {
- Notes = "Sets key names' and value names' comparisons to case insensitive (default).",
- },
- CaseSensitive =
- {
- Notes = "Sets key names and value names comparisons to case sensitive.",
- },
- Clear =
- {
- Notes = "Removes all the in-memory data. Note that , like all the other operations, this doesn't affect any file data.",
- },
- constructor =
- {
- Returns =
- {
- {
- Type = "cIniFile",
- },
- },
- Notes = "Creates a new empty cIniFile object.",
- },
- DeleteHeaderComment =
- {
- Params =
- {
- {
- Name = "CommentID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Deletes the specified header comment. Returns true if successful.",
- },
- DeleteHeaderComments =
- {
- Notes = "Deletes all headers comments.",
- },
- DeleteKey =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Deletes the specified key, and all values in that key. Returns true if successful.",
- },
- DeleteKeyComment =
- {
- {
- Params =
- {
- {
- Name = "KeyID",
- Type = "number",
- },
- {
- Name = "CommentID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Deletes the specified key comment. Returns true if successful.",
- },
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "CommentID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Deletes the specified key comment. Returns true if successful.",
- },
- },
- DeleteKeyComments =
- {
- {
- Params =
- {
- {
- Name = "KeyID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Deletes all comments for the specified key. Returns true if successful.",
- },
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Deletes all comments for the specified key. Returns true if successful.",
- },
- },
- DeleteValue =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Deletes the specified value. Returns true if successful.",
- },
- DeleteValueByID =
- {
- Params =
- {
- {
- Name = "KeyID",
- Type = "number",
- },
- {
- Name = "ValueID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Deletes the specified value. Returns true if successful.",
- },
- FindKey =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the KeyID for the specified key name, or the noID constant if the key doesn't exist.",
- },
- FindValue =
- {
- Params =
- {
- {
- Name = "KeyID",
- Type = "number",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "ValueID",
- Type = "number",
- },
- },
- 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.",
- },
- Flush =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Writes the data stored in the object to the file that was last associated with the object (ReadFile() or WriteFile()). Returns true on success, false on failure.",
- },
- GetHeaderComment =
- {
- Params =
- {
- {
- Name = "CommentID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the specified header comment, or an empty string if such comment doesn't exist",
- },
- GetKeyComment =
- {
- {
- Params =
- {
- {
- Name = "KeyID",
- Type = "number",
- },
- {
- Name = "CommentID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the specified key comment, or an empty string if such a comment doesn't exist",
- },
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "CommentID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the specified key comment, or an empty string if such a comment doesn't exist",
- },
- },
- GetKeyName =
- {
- Params =
- {
- {
- Name = "KeyID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the key name for the specified key ID. Inverse for FindKey().",
- },
- GetNumHeaderComments =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Retuns the number of header comments.",
- },
- GetNumKeyComments =
- {
- {
- Params =
- {
- {
- Name = "KeyID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of comments under the specified key",
- },
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of comments under the specified key",
- },
- },
- GetNumKeys =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the total number of keys. This is the range for the KeyID (0 .. GetNumKeys() - 1)",
- },
- GetNumValues =
- {
- {
- Params =
- {
- {
- Name = "KeyID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of values stored under the specified key.",
- },
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of values stored under the specified key.",
- },
- },
- GetValue =
- {
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "DefaultValue",
- Type = "string",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the value of the specified name under the specified key. Returns DefaultValue (empty string if not given) if the value doesn't exist.",
- },
- {
- Params =
- {
- {
- Name = "KeyID",
- Type = "number",
- },
- {
- Name = "ValueID",
- Type = "number",
- },
- {
- Name = "DefaultValue",
- Type = "string",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the value of the specified name under the specified key. Returns DefaultValue (empty string if not given) if the value doesn't exist.",
- },
- },
- GetValueB =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "DefaultValue",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns the value of the specified name under the specified key, as a bool. Returns DefaultValue (false if not given) if the value doesn't exist.",
- },
- GetValueF =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "DefaultValue",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the value of the specified name under the specified key, as a floating-point number. Returns DefaultValue (zero if not given) if the value doesn't exist.",
- },
- GetValueI =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "DefaultValue",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the value of the specified name under the specified key, as an integer. Returns DefaultValue (zero if not given) if the value doesn't exist.",
- },
- GetValueName =
- {
- {
- Params =
- {
- {
- Name = "KeyID",
- Type = "number",
- },
- {
- Name = "ValueID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the value specified by its ID. Inverse for FindValue().",
- },
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the value specified by its ID. Inverse for FindValue().",
- },
- },
- GetValueSet =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "DefaultValue",
- Type = "string",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "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 (empty string if not given).",
- },
- GetValueSetB =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "DefaultValue",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- 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 (false if not given).",
- },
- GetValueSetF =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "DefaultValue",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "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 (zero if not given).",
- },
- GetValueSetI =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "DefaultValue",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "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 (zero if not given).",
- },
- HasValue =
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified value is present.",
- },
- ReadFile =
- {
- Params =
- {
- {
- Name = "FileName",
- Type = "string",
- },
- {
- Name = "AllowExampleFallback",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- 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 =
- {
- {
- Name = "KeyID",
- Type = "number",
- },
- {
- Name = "ValueID",
- Type = "number",
- },
- {
- Name = "NewValue",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Overwrites the specified value with a new value. If the specified value doesn't exist, returns false (doesn't add).",
- },
- {
- Params =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "NewValue",
- Type = "string",
- },
- {
- Name = "CreateIfNotExists",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- 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 =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "NewValue",
- Type = "boolean",
- },
- {
- Name = "CreateIfNotExists",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- 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 =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "NewValue",
- Type = "number",
- },
- {
- Name = "CreateIfNotExists",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- 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 =
- {
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "ValueName",
- Type = "string",
- },
- {
- Name = "NewValue",
- Type = "number",
- },
- {
- Name = "CreateIfNotExists",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- 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 =
- {
- {
- Name = "FileName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Writes the current in-memory data into the specified file. Returns true if successful, false if not.",
- },
- },
- Constants =
- {
- noID =
- {
- Notes = "",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Code example: Reading a simple value",
- Contents = [[
- 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:
-
- ]],
- },
- {
- 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().
-
- The following code logs all keynames and their valuenames into the server log:
-
-local IniFile = cIniFile();
-IniFile:ReadFile("somefile.ini")
-local NumKeys = IniFile:GetNumKeys();
-for k = 0, (NumKeys - 1) do
- local NumValues = IniFile:GetNumValues(k);
- LOG("key \"" .. IniFile:GetKeyName(k) .. "\" has " .. NumValues .. " values:");
- for v = 0, (NumValues - 1) do
- LOG(" value \"" .. IniFile:GetValueName(k, v) .. "\".");
- end
-end
-
- ]],
- },
- },
- },
- cInventory =
- {
- Desc = [[
-This object is used to store the items that a {{cPlayer|cPlayer}} has. It also keeps track of what item the player has currently selected in their hotbar.
-Internally, the class uses three {{cItemGrid|cItemGrid}} objects to store the contents:
-
Armor
-
Inventory
-
Hotbar
-These ItemGrids are available in the API and can be manipulated by the plugins, too.
-
- When using the raw slot access functions, such as GetSlot() and SetSlot(), the slots are numbered
- consecutively, each ItemGrid has its offset and count. To future-proff your plugins, use the named
- constants instead of hard-coded numbers.
- ]],
- Functions =
- {
- AddItem =
- {
- Params =
- {
- {
- Name = "cItem",
- Type = "cItem",
- },
- {
- Name = "AllowNewStacks",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Adds an item to the storage; if AllowNewStacks is true (default), will also create new stacks in empty slots. Returns the number of items added",
- },
- AddItems =
- {
- Params =
- {
- {
- Name = "cItems",
- Type = "cItems",
- },
- {
- Name = "AllowNewStacks",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Same as AddItem, but for several items at once",
- },
- ChangeSlotCount =
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- {
- Name = "AddToCount",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Adds AddToCount to the count of items in the specified slot. If the slot was empty, ignores the call. Returns the new count in the slot, or -1 if invalid SlotNum",
- },
- Clear =
- {
- Notes = "Empties all slots",
- },
- CopyToItems =
- {
- Params =
- {
- {
- Name = "cItems",
- Type = "cItems",
- },
- },
- Notes = "Copies all non-empty slots into the cItems object provided; original cItems contents are preserved",
- },
- DamageEquippedItem =
- {
- Params =
- {
- {
- Name = "DamageAmount",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "HasDestroyed",
- Type = "boolean",
- },
- },
- Notes = "Adds the specified damage (1 by default) to the currently equipped item. Removes the item and returns true if the item reached its max damage and was destroyed.",
- },
- DamageItem =
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- {
- Name = "DamageAmount",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "HasDestroyed",
- Type = "boolean",
- },
- },
- Notes = "Adds the specified damage (1 by default) to the specified item. Removes the item and returns true if the item reached its max damage and was destroyed.",
- },
- GetArmorGrid =
- {
- Returns =
- {
- {
- Type = "cItemGrid",
- },
- },
- Notes = "Returns the ItemGrid representing the armor grid (1 x 4 slots)",
- },
- GetArmorSlot =
- {
- Params =
- {
- {
- Name = "ArmorSlotNum",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the specified armor slot contents. Note that the returned item is read-only",
- },
- GetEquippedBoots =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the \"boots\" slot of the armor grid. Note that the returned item is read-only",
- },
- GetEquippedChestplate =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the \"chestplate\" slot of the armor grid. Note that the returned item is read-only",
- },
- GetEquippedHelmet =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the \"helmet\" slot of the armor grid. Note that the returned item is read-only",
- },
- GetEquippedItem =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the currently selected item from the hotbar. Note that the returned item is read-only",
- },
- GetEquippedLeggings =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the \"leggings\" slot of the armor grid. Note that the returned item is read-only",
- },
- GetEquippedSlotNum =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the hotbar slot number for the currently selected item",
- },
- GetHotbarGrid =
- {
- Returns =
- {
- {
- Type = "cItemGrid",
- },
- },
- Notes = "Returns the ItemGrid representing the hotbar grid (9 x 1 slots)",
- },
- GetHotbarSlot =
- {
- Params =
- {
- {
- Name = "HotBarSlotNum",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the specified hotbar slot contents. Note that the returned item is read-only",
- },
- GetInventoryGrid =
- {
- Returns =
- {
- {
- Type = "cItemGrid",
- },
- },
- Notes = "Returns the ItemGrid representing the main inventory (9 x 3 slots)",
- },
- GetInventorySlot =
- {
- Params =
- {
- {
- Name = "InventorySlotNum",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the specified main inventory slot contents. Note that the returned item is read-only",
- },
- GetOwner =
- {
- Returns =
- {
- {
- Type = "cPlayer",
- },
- },
- Notes = "Returns the player whose inventory this object represents",
- },
- GetSlot =
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the contents of the specified slot. Note that the returned item is read-only",
- },
- HasItems =
- {
- Params =
- {
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if there are at least as many items of the specified type as in the parameter",
- },
- HowManyCanFit =
- {
- {
- Params =
- {
- {
- Name = "ItemStack",
- Type = "cItem",
- },
- {
- Name = "AllowNewStacks",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns number of items out of a_ItemStack that can fit in the storage. If AllowNewStacks is false, only considers slots already containing the specified item. AllowNewStacks defaults to true if not given.",
- },
- {
- Params =
- {
- {
- Name = "ItemStack",
- Type = "cItem",
- },
- {
- Name = "BeginSlotNum",
- Type = "number",
- },
- {
- Name = "EndSlotNum",
- Type = "number",
- },
- {
- Name = "AllowNewStacks",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns how many items of the specified type would fit into the slot range specified. If AllowNewStacks is false, only considers slots already containing the specified item. AllowNewStacks defaults to true if not given.",
- },
- },
- HowManyItems =
- {
- Params =
- {
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of the specified items that are currently stored",
- },
- RemoveItem =
- {
- Params =
- {
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Removes the specified item from the inventory, as many as possible, up to the item's m_ItemCount. Returns the number of items that were removed.",
- },
- RemoveOneEquippedItem =
- {
- Notes = "Removes one item from the hotbar's currently selected slot",
- },
- SendEquippedSlot =
- {
- Notes = "Sends the equipped item slot to the client",
- },
- SetArmorSlot =
- {
- Params =
- {
- {
- Name = "ArmorSlotNum",
- Type = "number",
- },
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the specified armor slot contents",
- },
- SetEquippedSlotNum =
- {
- Params =
- {
- {
- Name = "EquippedSlotNum",
- Type = "number",
- },
- },
- Notes = "Sets the currently selected hotbar slot number",
- },
- SetHotbarSlot =
- {
- Params =
- {
- {
- Name = "HotbarSlotNum",
- Type = "number",
- },
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the specified hotbar slot contents",
- },
- SetInventorySlot =
- {
- Params =
- {
- {
- Name = "InventorySlotNum",
- Type = "number",
- },
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the specified main inventory slot contents",
- },
- SetSlot =
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the specified slot contents",
- },
- },
- Constants =
- {
- invArmorCount =
- {
- Notes = "Number of slots in the Armor part",
- },
- invArmorOffset =
- {
- Notes = "Starting slot number of the Armor part",
- },
- invHotbarCount =
- {
- Notes = "Number of slots in the Hotbar part",
- },
- invHotbarOffset =
- {
- Notes = "Starting slot number of the Hotbar part",
- },
- invInventoryCount =
- {
- Notes = "Number of slots in the main inventory part",
- },
- invInventoryOffset =
- {
- Notes = "Starting slot number of the main inventory part",
- },
- invNumSlots =
- {
- Notes = "Total number of slots in a cInventory",
- },
- },
- ConstantGroups =
- {
- SlotIndices =
- {
- Include = "inv.*",
- TextBefore = [[
- Rather than hardcoding numbers, use the following constants for slot indices and counts:
- ]],
- },
- },
- },
- cItem =
- {
- Desc = [[
- cItem is what defines an item or stack of items in the game, it contains the item ID, damage,
- quantity and enchantments. Each slot in a {{cInventory}} class or a {{cItemGrid}} class is a cItem
- and each {{cPickup}} contains a cItem. The enchantments are contained in a separate
- {{cEnchantments}} class and are accessible through the m_Enchantments variable.
-
- To test if a cItem object represents an empty item, do not compare the item type nor the item count,
- but rather use the IsEmpty() function.
-
- To translate from a cItem to its string representation, use the {{Globals#functions|global function}}
- ItemToString(), ItemTypeToString() or ItemToFullString(). To translate from a string to a cItem,
- use the StringToItem() global function.
- ]],
- Functions =
- {
- AddCount =
- {
- Params =
- {
- {
- Name = "AmountToAdd",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Adds the specified amount to the item count. Returns self (useful for chaining).",
- },
- Clear =
- {
- Notes = "Resets the instance to an empty item",
- },
- constructor =
- {
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Creates a new empty cItem object",
- },
- {
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- {
- Name = "Count",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "Damage",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "EnchantmentString",
- Type = "string",
- IsOptional = true,
- },
- {
- Name = "CustomName",
- Type = "string",
- IsOptional = true,
- },
- {
- Name = "Lore",
- Type = "string",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Creates a new cItem object of the specified type, count (1 by default), damage (0 by default), enchantments (non-enchanted by default), CustomName (empty by default) and Lore (string, empty by default)",
- },
- {
- Params =
- {
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Creates an exact copy of the cItem object in the parameter",
- },
- },
- CopyOne =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Creates a copy of this object, with its count set to 1",
- },
- DamageItem =
- {
- Params =
- {
- {
- Name = "Amount",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "HasReachedMaxDamage",
- Type = "boolean",
- },
- },
- Notes = "Adds the specified damage. Returns true when damage reaches max value and the item should be destroyed (but doesn't destroy the item)",
- },
- Empty =
- {
- Notes = "Resets the instance to an empty item",
- },
- EnchantByXPLevels =
- {
- Params =
- {
- {
- Name = "NumXPLevels",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "HasEnchanted",
- Type = "boolean",
- },
- },
- Notes = "Randomly enchants the item using the specified number of XP levels. Returns true if the item was enchanted, false if not (not enchantable / too many enchantments already).",
- },
- GetEnchantability =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the enchantability of the item. Returns zero if the item doesn't have enchantability.",
- },
- GetMaxDamage =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the maximum value for damage that this item can get before breaking; zero if damage is not accounted for for this item type",
- },
- GetMaxStackSize =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the maximum stack size for this item.",
- },
- IsBothNameAndLoreEmpty =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns if both the custom name and lore are not set.",
- },
- IsCustomNameEmpty =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns if the custom name is empty.",
- },
- IsDamageable =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if this item does account for its damage",
- },
- IsEmpty =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if this object represents an empty item (zero count or invalid ItemType)",
- },
- IsEnchantable =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- {
- Name = "WithBook",
- Type = "boolean",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is enchantable. If WithBook is true, the function is used in the anvil inventory with book enchantments. So it checks the \"only book enchantments\" too. Example: You can only enchant a hoe with a book.",
- },
- IsEqual =
- {
- Params =
- {
- {
- Name = "OtherItem",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the item in the parameter is the same as the one stored in the object (type, damage, lore, name and enchantments)",
- },
- IsFullStack =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the item is stacked up to its maximum stacking",
- },
- IsLoreEmpty =
- {
- Notes = "Returns if the lore of the cItem is empty.",
- },
- IsSameType =
- {
- Params =
- {
- {
- Name = "OtherItem",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the item in the parameter is of the same ItemType as the one stored in the object. This is true even if the two items have different enchantments",
- },
- },
- Variables =
- {
- m_CustomName =
- {
- Type = "string",
- Notes = "The custom name for an item.",
- },
- m_Enchantments =
- {
- Type = "{{cEnchantments|cEnchantments}}}",
- Notes = "The enchantments of the item.",
- },
- m_ItemCount =
- {
- Type = "number",
- Notes = "Number of items in this stack",
- },
- m_ItemDamage =
- {
- Type = "number",
- Notes = "The damage of the item. Zero means no damage. Maximum damage can be queried with GetMaxDamage()",
- },
- m_ItemType =
- {
- Type = "number",
- Notes = "The item type. One of E_ITEM_ or E_BLOCK_ constants",
- },
- m_Lore =
- {
- Type = "string",
- Notes = "The lore for an item. Line breaks are represented by the ` character.",
- },
- m_RepairCost =
- {
- Type = "number",
- Notes = "The repair cost of the item. The anvil need this value",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Usage notes",
- Contents = [[
- Note that the object contained in a cItem class is quite complex and quite often new Minecraft
- versions add more stuff. Therefore it is recommended to copy cItem objects using the
- copy-constructor ("local copy = cItem(original);"), this is the only way that guarantees that
- the object will be copied at full, even with future versions of Cuberite.
- ]],
- },
- {
- Header = "Example code",
- Contents = [[
- The following code shows how to create items in several different ways (adapted from the Debuggers plugin):
-
-]],
- },
- },
- },
- cItemFrame =
- {
- Functions =
- {
- GetItem =
- {
- Returns =
- {
- {
- Type = "cItem",
- IsConst = true,
- },
- },
- Notes = "Returns the item in the frame (readonly object, do not modify)",
- },
- GetItemRotation =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the rotation from the item in the frame",
- },
- SetItem =
- {
- Params =
- {
- {
- Name = "Item",
- Type = "cItem",
- },
- },
- Notes = "Set the item in the frame",
- },
- SetItemRotation =
- {
- Params =
- {
- {
- Name = "ItemRotation",
- Type = "number",
- },
- },
- Notes = "Set the rotation from the item in the frame",
- },
- },
- },
- cItemGrid =
- {
- Desc = [[
-This class represents a 2D array of items. It is used as the underlying storage and API for all cases that use a grid of items:
-
{{cChestEntity|Chest}} contents
-
(TODO) Chest minecart contents
-
{{cDispenserEntity|Dispenser}} contents
-
{{cDropperEntity|Dropper}} contents
-
{{cFurnaceEntity|Furnace}} contents (?)
-
{{cHopperEntity|Hopper}} contents
-
(TODO) Hopper minecart contents
-
{{cPlayer|Player}} Inventory areas
-
(TODO) Trapped chest contents
-
-
The items contained in this object are accessed either by a pair of XY coords, or a slot number (x + Width * y). There are functions available for converting between the two formats.
-]],
- Functions =
- {
- AddItem =
- {
- Params =
- {
- {
- Name = "ItemStack",
- Type = "cItem",
- },
- {
- Name = "AllowNewStacks",
- Type = "boolean",
- IsOptional = true,
- },
- {
- Name = "PrioritarySlot",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Adds as many items out of ItemStack as can fit. If AllowNewStacks is set to false, only existing stacks can be topped up. If AllowNewStacks is set to true (default), empty slots can be used for the rest. If PrioritarySlot is set to a non-negative value, then the corresponding slot will be used first (if empty or compatible with added items). If PrioritarySlot is set to -1 (default), regular order applies. Returns the number of items that fit.",
- },
- AddItems =
- {
- Params =
- {
- {
- Name = "ItemStackList",
- Type = "cItems",
- },
- {
- Name = "AllowNewStacks",
- Type = "boolean",
- IsOptional = true,
- },
- {
- Name = "PrioritarySlot",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Same as AddItem, but works on an entire list of item stacks. The a_ItemStackList is modified to reflect the leftover items. If a_AllowNewStacks is set to false, only existing stacks can be topped up. If AllowNewStacks is set to true, empty slots can be used for the rest. If PrioritarySlot is set to a non-negative value, then the corresponding slot will be used first (if empty or compatible with added items). If PrioritarySlot is set to -1 (default), regular order applies. Returns the total number of items that fit.",
- },
- ChangeSlotCount =
- {
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- {
- Name = "AddToCount",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Adds AddToCount to the count of items in the specified slot. If the slot was empty, ignores the call. Returns the new count in the slot, or -1 if invalid SlotNum",
- },
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "AddToCount",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Adds AddToCount to the count of items in the specified slot. If the slot was empty, ignores the call. Returns the new count in the slot, or -1 if invalid slot coords",
- },
- },
- Clear =
- {
- Notes = "Empties all slots",
- },
- CopyToItems =
- {
- Params =
- {
- {
- Name = "cItems",
- Type = "cItems",
- },
- },
- Notes = "Copies all non-empty slots into the {{cItems}} object provided; original cItems contents are preserved as well.",
- },
- DamageItem =
- {
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- {
- Name = "DamageAmount",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "HasReachedMaxDamage",
- Type = "boolean",
- },
- },
- Notes = "Adds the specified damage (1 by default) to the specified item, returns true if the item reached its max damage and should be destroyed (but doesn't destroy the item).",
- },
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "DamageAmount",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "HasReachedMaxDamage",
- Type = "boolean",
- },
- },
- Notes = "Adds the specified damage (1 by default) to the specified item, returns true if the item reached its max damage and should be destroyed (but doesn't destroy the item).",
- },
- },
- EmptySlot =
- {
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- },
- Notes = "Destroys the item in the specified slot",
- },
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- },
- Notes = "Destroys the item in the specified slot",
- },
- },
- GetFirstEmptySlot =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the SlotNumber of the first empty slot, -1 if all slots are full",
- },
- GetFirstUsedSlot =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the SlotNumber of the first non-empty slot, -1 if all slots are empty",
- },
- GetHeight =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the Y dimension of the grid",
- },
- GetLastEmptySlot =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the SlotNumber of the last empty slot, -1 if all slots are full",
- },
- GetLastUsedSlot =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the SlotNumber of the last non-empty slot, -1 if all slots are empty",
- },
- GetNextEmptySlot =
- {
- Params =
- {
- {
- Name = "StartFrom",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the SlotNumber of the first empty slot following StartFrom, -1 if all the following slots are full",
- },
- GetNextUsedSlot =
- {
- Params =
- {
- {
- Name = "StartFrom",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the SlotNumber of the first non-empty slot following StartFrom, -1 if all the following slots are full",
- },
- GetNumSlots =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the total number of slots in the grid (Width * Height)",
- },
- GetSlot =
- {
- {
- Params =
- {
- {
- Name = "SlotNumber",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the specified slot. Note that the item is read-only",
- },
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the specified slot. Note that the item is read-only",
- },
- },
- GetSlotCoords =
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- {
- Type = "number",
- },
- },
- Notes = "Returns the X and Y coords for the specified SlotNumber. Returns \"-1, -1\" on invalid SlotNumber",
- },
- GetSlotNum =
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the SlotNumber for the specified slot coords. Returns -1 on invalid coords",
- },
- GetWidth =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the X dimension of the grid",
- },
- HasItems =
- {
- Params =
- {
- {
- Name = "ItemStack",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if there are at least as many items of the specified type as in the parameter",
- },
- HowManyCanFit =
- {
- Params =
- {
- {
- Name = "ItemStack",
- Type = "cItem",
- },
- {
- Name = "AllowNewStacks",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of the specified items that can fit in the storage. If AllowNewStacks is true (default), includes empty slots in the returned count.",
- },
- HowManyItems =
- {
- Params =
- {
- {
- Name = "Item",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of the specified item that are currently stored",
- },
- IsSlotEmpty =
- {
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified slot is empty, or an invalid slot is specified",
- },
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified slot is empty, or an invalid slot is specified",
- },
- },
- RemoveItem =
- {
- Params =
- {
- {
- Name = "ItemStack",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Removes the specified item from the grid, as many as possible, up to ItemStack's m_ItemCount. Returns the number of items that were removed.",
- },
- RemoveOneItem =
- {
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Removes one item from the stack in the specified slot and returns it as a single cItem. Empty slots are skipped and an empty item is returned",
- },
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Removes one item from the stack in the specified slot and returns it as a single cItem. Empty slots are skipped and an empty item is returned",
- },
- },
- SetSlot =
- {
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the specified slot to the specified item",
- },
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- {
- Name = "ItemType",
- Type = "number",
- },
- {
- Name = "ItemCount",
- Type = "number",
- },
- {
- Name = "ItemDamage",
- Type = "number",
- },
- },
- Notes = "Sets the specified slot to the specified item",
- },
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the specified slot to the specified item",
- },
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "ItemType",
- Type = "number",
- },
- {
- Name = "ItemCount",
- Type = "number",
- },
- {
- Name = "ItemDamage",
- Type = "number",
- },
- },
- Notes = "Sets the specified slot to the specified item",
- },
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Code example: Add items to player inventory",
- Contents = [[
- The following code tries to add 32 sticks to a player's main inventory:
-
-local Items = cItem(E_ITEM_STICK, 32);
-local PlayerMainInventory = Player:GetInventorySlots(); -- PlayerMainInventory is of type cItemGrid
-local NumAdded = PlayerMainInventory:AddItem(Items);
-if (NumAdded == Items.m_ItemCount) then
- -- All the sticks did fit
- LOG("Added 32 sticks");
-else
- -- Some (or all) of the sticks didn't fit
- LOG("Tried to add 32 sticks, but only " .. NumAdded .. " could fit");
-end
-
- ]],
- },
- {
- Header = "Code example: Damage an item",
- Contents = [[
- The following code damages the helmet in the player's armor and destroys it if it reaches max damage:
-
-local PlayerArmor = Player:GetArmorSlots(); -- PlayerArmor is of type cItemGrid
-if (PlayerArmor:DamageItem(0)) then -- Helmet is at SlotNum 0
- -- The helmet has reached max damage, destroy it:
- PlayerArmor:EmptySlot(0);
-end
-
- ]],
- },
- },
- },
- cItems =
- {
- Desc = [[
- This class represents a numbered collection (array) of {{cItem}} objects. The array indices start at
- zero, each consecutive item gets a consecutive index. This class is used for spawning multiple
- pickups or for mass manipulating an inventory.
- ]],
- Functions =
- {
- Add =
- {
- {
- Params =
- {
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Adds a new item to the end of the collection",
- },
- {
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- {
- Name = "ItemCount",
- Type = "number",
- },
- {
- Name = "ItemDamage",
- Type = "number",
- },
- },
- Notes = "Adds a new item to the end of the collection",
- },
- },
- Clear =
- {
- Notes = "Removes all items from the collection",
- },
- constructor =
- {
- Returns =
- {
- {
- Type = "cItems",
- },
- },
- Notes = "Creates a new cItems object",
- },
- Contains =
- {
- Params =
- {
- {
- Name = "Item",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the collection contains an item that is fully equivalent to the parameter",
- },
- ContainsType =
- {
- Params =
- {
- {
- Name = "Item",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the collection contains an item that is the same type as the parameter",
- },
- Delete =
- {
- Params =
- {
- {
- Name = "Index",
- Type = "number",
- },
- },
- Notes = "Deletes item at the specified index",
- },
- Get =
- {
- Params =
- {
- {
- Name = "Index",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item at the specified index",
- },
- Set =
- {
- {
- Params =
- {
- {
- Name = "Index",
- Type = "number",
- },
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the item at the specified index to the specified item",
- },
- {
- Params =
- {
- {
- Name = "Index",
- Type = "number",
- },
- {
- Name = "ItemType",
- Type = "number",
- },
- {
- Name = "ItemCount",
- Type = "number",
- },
- {
- Name = "ItemDamage",
- Type = "number",
- },
- },
- Notes = "Sets the item at the specified index to the specified item",
- },
- },
- Size =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of items in the collection",
- },
- },
- },
- cJson =
- {
- Desc = [[
- Exposes the Json parser and serializer available in the server. Plugins can parse Json strings into
- Lua tables, and serialize Lua tables into Json strings easily.
- ]],
- Functions =
- {
- Parse =
- {
- Params =
- {
- {
- Name = "InputString",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Parses the Json in the input string into a Lua table. Returns nil and detailed error message if parsing fails.",
- },
- Serialize =
- {
- Params =
- {
- {
- Name = "table",
- Type = "table",
- },
- {
- Name = "options",
- Type = "table",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Serializes the input table into a Json string. The options table, if present, is used to adjust the formatting of the serialized string, see below for details.",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Serializer options",
- Contents = [[
- The "options" parameter given to the cJson:Serialize() function is a dictionary-table of "option
- name" -> "option value". The serializer warns if any unknown options are used; the following
- options are recognized:
-
-
commentStyle - either "All" or "None", specifies whether comments are written to the
- output. Currently unused since comments cannot be represented in a Lua table
-
indentation - the string that is repeated for each level of indentation of the output.
- If empty, the Json is compressed (without linebreaks).
-
enableYAMLCompatibility - bool manipulating the whitespace around the colons.
-
dropNullPlaceholders - bool specifying whether null placeholders should be dropped
- from the output
-
- ]],
- },
- {
- Header = "Code example: Parsing a Json string",
- Contents = [==[
- The following code, adapted from the Debuggers plugin, parses a simple Json string and verifies
- the results:
-
- ]==],
- },
- {
- Header = "Code example: Serializing into a Json string",
- Contents = [[
- The following code, adapted from the Debuggers plugin, serializes a simple Lua table into a
- string, using custom indentation:
-
-local s1 = cJson:Serialize({a = 1, b = "2", c = {3, "4", 5}}, {indentation = " "})
-LOG("Serialization result: " .. (s1 or ""))
-
- ]],
- },
- },
- },
- cLuaWindow =
- {
- Desc = [[
-This class is used by plugins wishing to display a custom window to the player, unrelated to block entities or entities near the player. The window can be of any type and have any contents that the plugin defines. Callbacks for when the player modifies the window contents and when the player closes the window can be set.
-
-
This class inherits from the {{cWindow|cWindow}} class, so all cWindow's functions and constants can be used, in addition to the cLuaWindow-specific functions listed below.
-
-
The contents of this window are represented by a {{cWindow|cWindow}}:GetSlot() etc. or {{cPlayer|cPlayer}}:GetInventory() to access the player inventory.
-
-
When creating a new cLuaWindow object, you need to specify both the window type and the contents' width and height. Note that Cuberite accepts any combination of these, but opening a window for a player may crash their client if the contents' dimensions don't match the client's expectations.
-
-
To open the window for a player, call {{cPlayer|cPlayer}}:OpenWindow(). Multiple players can open window of the same cLuaWindow object. All players see the same items in the window's contents (like chest, unlike crafting table).
-]],
- Functions =
- {
- constructor =
- {
- Params =
- {
- {
- Name = "WindowType",
- Type = "cWindow#WindowType",
- },
- {
- Name = "ContentsWidth",
- Type = "number",
- },
- {
- Name = "ContentsHeight",
- Type = "number",
- },
- {
- Name = "Title",
- Type = "string",
- },
- },
- Notes = "Creates a new object of this class. The window is not shown to any player yet.",
- },
- GetContents =
- {
- Returns =
- {
- {
- Type = "cItemGrid",
- },
- },
- Notes = "Returns the cItemGrid object representing the internal storage in this window",
- },
- SetOnClosing =
- {
- Params =
- {
- {
- Name = "OnClosingCallback",
- Type = "function",
- },
- },
- Notes = "Sets the function that the window will call when it is about to be closed by a player",
- },
- SetOnSlotChanged =
- {
- Params =
- {
- {
- Name = "OnSlotChangedCallback",
- Type = "function",
- },
- },
- Notes = "Sets the function that the window will call when a slot is changed by a player",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Callbacks",
- Contents = [[
- The object calls the following functions at the appropriate time:
- ]],
- },
- {
- Header = "OnClosing Callback",
- Contents = [[
- This callback, settable via the SetOnClosing() function, will be called when the player tries to close the window, or the window is closed for any other reason (such as a player disconnecting).
- The a_Window parameter is the cLuaWindow object representing the window, a_Player is the player for whom the window is about to close. a_CanRefuse specifies whether the callback can refuse the closing. If the callback returns true and a_CanRefuse is true, the window is not closed (internally, the server sends a new OpenWindow packet to the client).
- ]],
- },
- {
- Header = "OnSlotChanged Callback",
- Contents = [[
- This callback, settable via the SetOnSlotChanged() function, will be called whenever the contents of any slot in the window's contents (i. e. NOT in the player inventory!) changes.
The a_Window parameter is the cLuaWindow object representing the window, a_SlotNum is the slot number. There is no reference to a {{cPlayer}}, because the slot change needn't originate from the player action. To get or set the slot, you'll need to retrieve a cPlayer object, for example by calling {{cWorld|cWorld}}:DoWithPlayer().
-
-
Any returned values are ignored.
- ]],
- },
- {
- Header = "Example",
- Contents = [[
- This example is taken from the Debuggers plugin, used to test the API functionality. It opens a window and refuse to close it 3 times. It also logs slot changes to the server console.
-
--- Callback that refuses to close the window twice, then allows:
-local Attempt = 1;
-local OnClosing = function(Window, Player, CanRefuse)
- Player:SendMessage("Window closing attempt #" .. Attempt .. "; CanRefuse = " .. tostring(CanRefuse));
- Attempt = Attempt + 1;
- return CanRefuse and (Attempt <= 3); -- refuse twice, then allow, unless CanRefuse is set to true
-end
-
--- Log the slot changes:
-local OnSlotChanged = function(Window, SlotNum)
- LOG("Window \"" .. Window:GetWindowTitle() .. "\" slot " .. SlotNum .. " changed.");
-end
-
--- Set window contents:
--- a_Player is a cPlayer object received from the outside of this code fragment
-local Window = cLuaWindow(cWindow.wtHopper, 3, 3, "TestWnd");
-Window:SetSlot(a_Player, 0, cItem(E_ITEM_DIAMOND, 64));
-Window:SetOnClosing(OnClosing);
-Window:SetOnSlotChanged(OnSlotChanged);
-
--- Open the window:
-a_Player:OpenWindow(Window);
-
- ]],
- },
- },
- Inherits = "cWindow",
- },
- cMap =
- {
- Desc = [[
- This class encapsulates a single in-game colored map.
-
- The contents (i.e. pixel data) of a cMap are dynamically updated by each
- tracked {{cPlayer}} instance. Furthermore, a cMap maintains and periodically
- updates a list of map decorators, which are objects drawn on the map that
- can freely move (e.g. Player and item frame pointers).
- ]],
- Functions =
- {
- EraseData =
- {
- Notes = "Erases all pixel data.",
- },
- GetCenterX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the X coord of the map's center.",
- },
- GetCenterZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the Y coord of the map's center.",
- },
- GetDimension =
- {
- Returns =
- {
- {
- Type = "eDimension",
- },
- },
- Notes = "Returns the dimension of the associated world.",
- },
- GetHeight =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the height of the map.",
- },
- GetID =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the numerical ID of the map. (The item damage value)",
- },
- GetName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the map.",
- },
- GetNumPixels =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of pixels in this map.",
- },
- GetPixel =
- {
- Params =
- {
- {
- Name = "PixelX",
- Type = "number",
- },
- {
- Name = "PixelZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "ColorID",
- Type = "number",
- },
- },
- Notes = "Returns the color of the specified pixel.",
- },
- GetPixelWidth =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the width of a single pixel in blocks.",
- },
- GetScale =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the scale of the map. Range: [0,4]",
- },
- GetWidth =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the width of the map.",
- },
- GetWorld =
- {
- Returns =
- {
- {
- Type = "cWorld",
- },
- },
- Notes = "Returns the associated world.",
- },
- Resize =
- {
- Params =
- {
- {
- Name = "Width",
- Type = "number",
- },
- {
- Name = "Height",
- Type = "number",
- },
- },
- Notes = "Resizes the map. WARNING: This will erase the pixel data.",
- },
- SetPixel =
- {
- Params =
- {
- {
- Name = "PixelX",
- Type = "number",
- },
- {
- Name = "PixelZ",
- Type = "number",
- },
- {
- Name = "ColorID",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- },
- Notes = "Sets the color of the specified pixel. Returns false on error (Out of range).",
- },
- SetPosition =
- {
- Params =
- {
- {
- Name = "CenterX",
- Type = "number",
- },
- {
- Name = "CenterZ",
- Type = "number",
- },
- },
- Notes = "Relocates the map. The pixel data will not be modified.",
- },
- SetScale =
- {
- Params =
- {
- {
- Name = "Scale",
- Type = "number",
- },
- },
- Notes = "Rescales the map. The pixel data will not be modified.",
- },
- },
- Constants =
- {
- E_BASE_COLOR_BLUE =
- {
- Notes = "",
- },
- E_BASE_COLOR_BROWN =
- {
- Notes = "",
- },
- E_BASE_COLOR_DARK_BROWN =
- {
- Notes = "",
- },
- E_BASE_COLOR_DARK_GRAY =
- {
- Notes = "",
- },
- E_BASE_COLOR_DARK_GREEN =
- {
- Notes = "",
- },
- E_BASE_COLOR_GRAY_1 =
- {
- Notes = "",
- },
- E_BASE_COLOR_GRAY_2 =
- {
- Notes = "",
- },
- E_BASE_COLOR_LIGHT_BROWN =
- {
- Notes = "",
- },
- E_BASE_COLOR_LIGHT_GRAY =
- {
- Notes = "",
- },
- E_BASE_COLOR_LIGHT_GREEN =
- {
- Notes = "",
- },
- E_BASE_COLOR_PALE_BLUE =
- {
- Notes = "",
- },
- E_BASE_COLOR_RED =
- {
- Notes = "",
- },
- E_BASE_COLOR_TRANSPARENT =
- {
- Notes = "",
- },
- E_BASE_COLOR_WHITE =
- {
- Notes = "",
- },
- },
- },
- cMapManager =
- {
- Desc = [[
- This class is associated with a single {{cWorld}} instance and manages a list of maps.
- ]],
- Functions =
- {
- DoWithMap =
- {
- Params =
- {
- {
- Name = "MapID",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If a map with the specified ID exists, calls the CallbackFunction for that map. The CallbackFunction has the following signature:
function Callback({{cMap|Map}})
Returns true if the map was found and the callback called, false if map not found.",
- },
- GetNumMaps =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of registered maps.",
- },
- },
- },
- cMojangAPI =
- {
- Desc = [[
- Provides interface to various API functions that Mojang provides through their servers. Note that
- some of these calls will wait for a response from the network, and so shouldn't be used while the
- server is fully running (or at least when there are players connected) to avoid percepted lag.
-
- All the functions are static, call them using the cMojangAPI:Function() convention.
-
- Mojang uses two formats for UUIDs, short and dashed. Cuberite works with short UUIDs internally, but
- will convert to dashed UUIDs where needed - in the protocol login for example. The MakeUUIDShort()
- and MakeUUIDDashed() functions are provided for plugins to use for conversion between the two
- formats.
-
- This class will cache values returned by the API service. The cache will hold the values for 7 days
- by default, after that, they will no longer be available. This is in order to not let the server get
- banned from using the API service, since they are rate-limited to 600 queries per 10 minutes. The
- cache contents also gets updated whenever a player successfully joins, since that makes the server
- contact the API service, too, and retrieve the relevant data.
- ]],
- Functions =
- {
- AddPlayerNameToUUIDMapping =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "PlayerName",
- Type = "string",
- },
- {
- Name = "UUID",
- Type = "string",
- },
- },
- Notes = "Adds the specified PlayerName-to-UUID mapping into the cache, with current timestamp. Accepts both short or dashed UUIDs. ",
- },
- GetPlayerNameFromUUID =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "UUID",
- Type = "string",
- },
- {
- Name = "UseOnlyCached",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "PlayerName",
- Type = "string",
- },
- },
- Notes = "Returns the playername that corresponds to the given UUID, or an empty string on error. If UseOnlyCached is false (the default), queries the Mojang servers if the UUID is not in the cache. The UUID can be either short or dashed. WARNING: Do NOT use this function with UseOnlyCached set to false while the server is running. Only use it when the server is starting up (inside the Initialize() method), otherwise you will lag the server severely.",
- },
- GetUUIDFromPlayerName =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "PlayerName",
- Type = "string",
- },
- {
- Name = "UseOnlyCached",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "UUID",
- Type = "string",
- },
- },
- Notes = "Returns the (short) UUID that corresponds to the given playername, or an empty string on error. If UseOnlyCached is false (the default), queries the Mojang servers if the playername is not in the cache. WARNING: Do NOT use this function with UseOnlyCached set to false while the server is running. Only use it when the server is starting up (inside the Initialize() method), otherwise you will lag the server severely.",
- },
- GetUUIDsFromPlayerNames =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "PlayerNames",
- Type = "string",
- },
- {
- Name = "UseOnlyCached",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns a table that contains the map, 'PlayerName' -> '(short) UUID', for all valid playernames in the input array-table. PlayerNames not recognized will not be set in the returned map. If UseOnlyCached is false (the default), queries the Mojang servers for the results that are not in the cache. WARNING: Do NOT use this function with UseOnlyCached set to false while the server is running. Only use it when the server is starting up (inside the Initialize() method), otherwise you will lag the server severely.",
- },
- MakeUUIDDashed =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "UUID",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "DashedUUID",
- Type = "string",
- },
- },
- Notes = "Converts the UUID to a dashed format (\"01234567-8901-2345-6789-012345678901\"). Accepts both dashed or short UUIDs. Logs a warning and returns an empty string if UUID format not recognized.",
- },
- MakeUUIDShort =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "UUID",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "ShortUUID",
- Type = "string",
- },
- },
- Notes = "Converts the UUID to a short format (without dashes, \"01234567890123456789012345678901\"). Accepts both dashed or short UUIDs. Logs a warning and returns an empty string if UUID format not recognized.",
- },
- },
- },
- cMonster =
- {
- Desc = [[
- This class is the base class for all computer-controlled mobs in the game.
-
- To spawn a mob in a world, use the {{cWorld}}:SpawnMob() function.
- ]],
- Functions =
- {
- FamilyFromType =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "MobType",
- Type = "Globals#eMonsterType",
- },
- },
- Returns =
- {
- {
- Name = "MobFamily",
- Type = "cMonster#eFamily",
- },
- },
- Notes = "Returns the mob family ({{cMonster#eFamily|mfXXX}} constants) based on the mob type ({{Globals#eMonsterType|mtXXX}} constants)",
- },
- GetAge =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the age of the monster",
- },
- GetCustomName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Gets the custom name of the monster. If no custom name is set, the function returns an empty string.",
- },
- GetMobFamily =
- {
- Returns =
- {
- {
- Name = "MobFamily",
- Type = "cMonster#eFamily",
- },
- },
- Notes = "Returns this mob's family ({{cMonster#eFamily|mfXXX}} constant)",
- },
- GetMobType =
- {
- Returns =
- {
- {
- Name = "MobType",
- Type = "Globals#eMonsterType",
- },
- },
- Notes = "Returns the type of this mob ({{Globals#eMonsterType|mtXXX}} constant)",
- },
- GetRelativeWalkSpeed =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the relative walk speed of this mob. Standard is 1.0",
- },
- GetSpawnDelay =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "MobFamily",
- Type = "cMonster#eFamily",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the spawn delay - the number of game ticks between spawn attempts - for the specified mob family.",
- },
- HasCustomName =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the monster has a custom name.",
- },
- IsBaby =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the monster is a baby",
- },
- IsCustomNameAlwaysVisible =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Is the custom name of this monster always visible? If not, you only see the name when you sight the mob.",
- },
- MobTypeToString =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "MobType",
- Type = "Globals#eMonsterType",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the string representing the given mob type ({{Globals#eMonsterType|mtXXX}} constant), or empty string if unknown type.",
- },
- MobTypeToVanillaName =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "MobType",
- Type = "Globals#MobType",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the vanilla name of the given mob type, or empty string if unknown type.",
- },
- MoveToPosition =
- {
- Params =
- {
- {
- Name = "Position",
- Type = "Vector3d",
- },
- },
- Notes = "Start moving (using a pathfinder) towards the specified position",
- },
- SetAge =
- {
- Params =
- {
- {
- Name = "Age",
- Type = "number",
- },
- },
- Notes = "Sets the age of the monster",
- },
- SetCustomName =
- {
- Params =
- {
- {
- Name = "CustomName",
- Type = "string",
- },
- },
- Notes = "Sets the custom name of the monster. You see the name over the monster. If you want to disable the custom name, simply set an empty string.",
- },
- SetCustomNameAlwaysVisible =
- {
- Params =
- {
- {
- Name = "IsCustomNameAlwaysVisible",
- Type = "boolean",
- },
- },
- Notes = "Sets the custom name visiblity of this monster. If it's false, you only see the name when you sight the mob. If it's true, you always see the custom name.",
- },
- SetRelativeWalkSpeed =
- {
- Params =
- {
- {
- Name = "RelativeWalkSpeed",
- Type = "number",
- },
- },
- Notes = "Sets the relative walk speed of this mob. The default relative speed is 1.0.",
- },
- StringToMobType =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "MobTypeString",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "MobType",
- Type = "Globals#eMonsterType",
- },
- },
- Notes = "Returns the mob type ({{Globals#eMonsterType|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 = "",
- },
- },
- ConstantGroups =
- {
- eFamily =
- {
- Include = "mf.*",
- TextBefore = [[
- Mobs are divided into families. The following constants are used for individual family types:
- ]],
- },
- },
- Inherits = "cPawn",
- },
- cObjective =
- {
- Desc = [[
- This class represents a single scoreboard objective.
- ]],
- Functions =
- {
- AddScore =
- {
- Params =
- {
- {
- Name = "string",
- Type = "string",
- },
- {
- Name = "number",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "Score",
- Type = "",
- },
- },
- Notes = "Adds a value to the score of the specified player and returns the new value.",
- },
- GetDisplayName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the display name of the objective. This name will be shown to the connected players.",
- },
- GetName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the internal name of the objective.",
- },
- GetScore =
- {
- Params =
- {
- {
- Name = "string",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "Score",
- Type = "",
- },
- },
- Notes = "Returns the score of the specified player.",
- },
- GetType =
- {
- Returns =
- {
- {
- Name = "eType",
- Type = "",
- },
- },
- Notes = "Returns the type of the objective. (i.e what is being tracked)",
- },
- Reset =
- {
- Notes = "Resets the scores of the tracked players.",
- },
- ResetScore =
- {
- Params =
- {
- {
- Name = "string",
- Type = "string",
- },
- },
- Notes = "Reset the score of the specified player.",
- },
- SetDisplayName =
- {
- Params =
- {
- {
- Name = "string",
- Type = "string",
- },
- },
- Notes = "Sets the display name of the objective.",
- },
- SetScore =
- {
- Params =
- {
- {
- Name = "string",
- Type = "string",
- },
- {
- Name = "Score",
- Type = "",
- },
- },
- Notes = "Sets the score of the specified player.",
- },
- SubScore =
- {
- Params =
- {
- {
- Name = "string",
- Type = "string",
- },
- {
- Name = "number",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "Score",
- Type = "",
- },
- },
- Notes = "Subtracts a value from the score of the specified player and returns the new value.",
- },
- },
- Constants =
- {
- otAchievement =
- {
- Notes = "",
- },
- otDeathCount =
- {
- Notes = "",
- },
- otDummy =
- {
- Notes = "",
- },
- otHealth =
- {
- Notes = "",
- },
- otPlayerKillCount =
- {
- Notes = "",
- },
- otStat =
- {
- Notes = "",
- },
- otStatBlockMine =
- {
- Notes = "",
- },
- otStatEntityKill =
- {
- Notes = "",
- },
- otStatEntityKilledBy =
- {
- Notes = "",
- },
- otStatItemBreak =
- {
- Notes = "",
- },
- otStatItemCraft =
- {
- Notes = "",
- },
- otStatItemUse =
- {
- Notes = "",
- },
- otTotalKillCount =
- {
- Notes = "",
- },
- },
- },
- cPainting =
- {
- Desc = "This class represents a painting in the world. These paintings are special and different from Vanilla in that they can be critical-hit.",
- Functions =
- {
- GetDirection =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the direction the painting faces. Directions: ZP - 0, ZM - 2, XM - 1, XP - 3. Note that these are not the BLOCK_FACE constants.",
- },
- GetName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the painting",
- },
- },
- },
- cPawn =
- {
- Desc = "cPawn is a controllable pawn object, controlled by either AI or a player. cPawn inherits all functions and members of {{cEntity}}\
-",
- Functions =
- {
- AddEntityEffect =
- {
- Params =
- {
- {
- Name = "EffectType",
- Type = "cEntityEffect",
- },
- {
- Name = "EffectDurationTicks",
- Type = "number",
- },
- {
- Name = "EffectIntensity",
- Type = "number",
- },
- {
- Name = "DistanceModifier",
- Type = "number",
- },
- },
- Notes = "Applies an entity effect. Checks with plugins if they allow the addition. EffectIntensity is the level of the effect (0 = Potion I, 1 = Potion II, etc). DistanceModifier is the scalar multiplied to the potion duration (only applies to splash potions).",
- },
- ClearEntityEffects =
- {
- Notes = "Removes all currently applied entity effects",
- },
- GetHealth =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- },
- HasEntityEffect =
- {
- Params =
- {
- {
- Name = "EffectType",
- Type = "cEntityEffect",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true, if the supplied entity effect type is currently applied",
- },
- Heal =
- {
-
- },
- KilledBy =
- {
-
- },
- RemoveEntityEffect =
- {
- Params =
- {
- {
- Name = "EffectType",
- Type = "cEntityEffect",
- },
- },
- Notes = "Removes a currently applied entity effect",
- },
- TakeDamage =
- {
-
- },
- TeleportTo =
- {
-
- },
- TeleportToEntity =
- {
-
- },
- },
- Inherits = "cEntity",
- },
- cPickup =
- {
- 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 =
- {
- CollectedBy =
- {
- Params =
- {
- {
- Name = "Player",
- Type = "cPlayer",
- },
- },
- Returns =
- {
- {
- Name = "WasCollected",
- Type = "boolean",
- },
- },
- Notes = "Tries to make the player collect the pickup. Returns true if the pickup was collected, at least partially.",
- },
- GetAge =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of ticks that the pickup has existed.",
- },
- GetItem =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item represented by this pickup",
- },
- IsCollected =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if this pickup has already been collected (is waiting to be destroyed)",
- },
- IsPlayerCreated =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the pickup was created by a player",
- },
- SetAge =
- {
- Params =
- {
- {
- Name = "AgeTicks",
- Type = "number",
- },
- },
- Notes = "Sets the pickup's age, in ticks.",
- },
- },
- Inherits = "cEntity",
- },
- cPlayer =
- {
- 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 =
- {
- AddFoodExhaustion =
- {
- Params =
- {
- {
- Name = "Exhaustion",
- Type = "number",
- },
- },
- Notes = "Adds the specified number to the food exhaustion. Only positive numbers expected.",
- },
- CalcLevelFromXp =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "XPAmount",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the level which is reached with the specified amount of XP. Inverse of XpForLevel().",
- },
- CanFly =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns if the player is able to fly.",
- },
- CloseWindow =
- {
- Params =
- {
- {
- Name = "CanRefuse",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Notes = "Closes the currently open UI window. If CanRefuse is true (default), the window may refuse the closing.",
- },
- CloseWindowIfID =
- {
- Params =
- {
- {
- Name = "WindowID",
- Type = "number",
- },
- {
- Name = "CanRefuse",
- Type = "boolean",
- IsOptional = true,
- },
- },
- 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.",
- },
- DeltaExperience =
- {
- Params =
- {
- {
- Name = "DeltaXP",
- Type = "number",
- },
- },
- Notes = "Adds or removes XP from the current XP amount. Won't allow XP to go negative. Returns the new experience, -1 on error (XP overflow).",
- },
- Feed =
- {
- Params =
- {
- {
- Name = "AddFood",
- Type = "number",
- },
- {
- Name = "AddSaturation",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- 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 =
- {
- {
- Name = "NumTicks",
- Type = "number",
- },
- },
- Notes = "Starts the food poisoning for the specified amount of ticks; if already foodpoisoned, sets FoodPoisonedTicksRemaining to the larger of the two",
- },
- ForceSetSpeed =
- {
- Params =
- {
- {
- Name = "Direction",
- Type = "Vector3d",
- },
- },
- Notes = "Forces the player to move to the given direction.",
- },
- Freeze =
- {
- Params =
- {
- {
- Name = "Location",
- Type = "Vector3d",
- },
- },
- Notes = "Teleports the player to \"Location\" and prevents them from moving, locking them in place until unfreeze() is called",
- },
- GetClientHandle =
- {
- Returns =
- {
- {
- Type = "cClientHandle",
- },
- },
- Notes = "Returns the client handle representing the player's connection. May be nil (AI players).",
- },
- GetColor =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the full color code to be used for this player's messages (based on their rank). Prefix player messages with this code.",
- },
- GetCurrentXp =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the current amount of XP",
- },
- GetCustomName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the custom name of this player. If the player hasn't a custom name, it will return an empty string.",
- },
- GetEffectiveGameMode =
- {
- Returns =
- {
- {
- Name = "GameMode",
- Type = "Globals#GameMode",
- },
- },
- Notes = "(OBSOLETE) Returns the current resolved game mode of the player. If the player is set to inherit the world's gamemode, returns that instead. See also GetGameMode() and IsGameModeXXX() functions. Note that this function is the same as GetGameMode(), use that function instead.",
- },
- GetEquippedItem =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item that the player is currently holding; empty item if holding nothing.",
- },
- GetEyeHeight =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the height of the player's eyes, in absolute coords",
- },
- GetEyePosition =
- {
- Returns =
- {
- {
- Name = "EyePositionVector",
- Type = "Vector3d",
- },
- },
- Notes = "Returns the position of the player's eyes, as a {{Vector3d}}",
- },
- GetFloaterID =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the Entity ID of the fishing hook floater that belongs to the player. Returns -1 if no floater is associated with the player. FIXME: Undefined behavior when the player has used multiple fishing rods simultanously.",
- },
- GetFlyingMaxSpeed =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the maximum flying speed, relative to the default game flying speed. Defaults to 1, but plugins may modify it for faster or slower flying.",
- },
- GetFoodExhaustionLevel =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the food exhaustion level",
- },
- GetFoodLevel =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the food level (number of half-drumsticks on-screen)",
- },
- GetFoodPoisonedTicksRemaining =
- {
- Notes = "Returns the number of ticks left for the food posoning effect",
- },
- GetFoodSaturationLevel =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the food saturation (overcharge of the food level, is depleted before food level)",
- },
- GetFoodTickTimer =
- {
- 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 =
- {
- Returns =
- {
- {
- Name = "GameMode",
- Type = "Globals#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}}. NOTE: Instead of comparing the value returned by this function to the gmXXX constants, use the IsGameModeXXX() functions. These functions handle the gamemode inheritance automatically.",
- },
- GetInventory =
- {
- Returns =
- {
- {
- Name = "Inventory",
- Type = "cInventory",
- },
- },
- Notes = "Returns the player's inventory",
- },
- GetIP =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the IP address of the player, if available. Returns an empty string if there's no IP to report.",
- },
- GetLastBedPos =
- {
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns the position of the last bed the player has slept in, or the world's spawn if no such position was recorded.",
- },
- GetMaxSpeed =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the player's current maximum speed, relative to the game default speed. Takes into account the sprinting / flying status.",
- },
- GetName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the player's name",
- },
- GetNormalMaxSpeed =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the player's maximum walking speed, relative to the game default speed. Defaults to 1, but plugins may modify it for faster or slower walking.",
- },
- GetPermissions =
- {
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns an array-table of all permissions (strings) that the player has assigned to them through their rank.",
- },
- GetPlayerListName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name that is used in the playerlist.",
- },
- GetResolvedPermissions =
- {
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns all the player's permissions, as an array-table of strings.",
- },
- GetSprintingMaxSpeed =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the player's maximum sprinting speed, relative to the game default speed. Defaults to 1.3, but plugins may modify it for faster or slower sprinting.",
- },
- GetStance =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the player's stance (Y-pos of player's eyes)",
- },
- GetTeam =
- {
- Returns =
- {
- {
- Type = "cTeam",
- },
- },
- Notes = "Returns the team that the player belongs to, or nil if none.",
- },
- GetThrowSpeed =
- {
- Params =
- {
- {
- Name = "SpeedCoeff",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "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.",
- },
- GetThrowStartPos =
- {
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns the position where the projectiles should start when thrown by this player.",
- },
- GetUUID =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the (short) UUID that the player is using. Could be empty string for players that don't have a Mojang account assigned to them (in the future, bots for example).",
- },
- GetWindow =
- {
- Returns =
- {
- {
- Type = "cWindow",
- },
- },
- Notes = "Returns the currently open UI window. If the player doesn't have any UI window open, returns the inventory window.",
- },
- GetXpLevel =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the current XP level (based on current XP amount).",
- },
- GetXpLifetimeTotal =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the amount of XP that has been accumulated throughout the player's lifetime.",
- },
- GetXpPercentage =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the percentage of the experience bar - the amount of XP towards the next XP level. Between 0 and 1.",
- },
- HasCustomName =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player has a custom name.",
- },
- HasPermission =
- {
- Params =
- {
- {
- Name = "PermissionString",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player has the specified permission",
- },
- Heal =
- {
- Params =
- {
- {
- Name = "HitPoints",
- Type = "number",
- },
- },
- Notes = "Heals the player by the specified amount of HPs. Only positive amounts are expected. Sends a health update to the client.",
- },
- IsEating =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player is currently eating the item in their hand.",
- },
- IsFishing =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player is currently fishing",
- },
- IsFlying =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player is flying.",
- },
- IsFrozen =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player is frozen. See Freeze()",
- },
- IsGameModeAdventure =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player is in the gmAdventure gamemode, or has their gamemode unset and the world is a gmAdventure world.",
- },
- IsGameModeCreative =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player is in the gmCreative gamemode, or has their gamemode unset and the world is a gmCreative world.",
- },
- IsGameModeSpectator =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player is in the gmSpectator gamemode, or has their gamemode unset and the world is a gmSpectator world.",
- },
- IsGameModeSurvival =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player is in the gmSurvival gamemode, or has their gamemode unset and the world is a gmSurvival world.",
- },
- IsInBed =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player is currently lying in a bed.",
- },
- IsSatiated =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player is satiated (cannot eat).",
- },
- IsVisible =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the player is visible to other players",
- },
- LoadRank =
- {
- Notes = "Reloads the player's rank, message visuals and permissions from the {{cRankManager}}, based on the player's current rank.",
- },
- MoveTo =
- {
- Params =
- {
- {
- Name = "NewPosition",
- Type = "Vector3d",
- },
- },
- Notes = "Tries to move the player into the specified position.",
- },
- OpenWindow =
- {
- Params =
- {
- {
- Name = "Window",
- Type = "cWindow",
- },
- },
- Notes = "Opens the specified UI window for the player.",
- },
- PermissionMatches =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Permission",
- Type = "string",
- },
- {
- Name = "Template",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified permission matches the specified template. The template may contain asterisk as a wildcard for any word.",
- },
- PlaceBlock =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Places a block while impersonating the player. The {{OnPlayerPlacingBlock|HOOK_PLAYER_PLACING_BLOCK}} hook is called before the placement, and if it succeeds, the block is placed and the {{OnPlayerPlacedBlock|HOOK_PLAYER_PLACED_BLOCK}} hook is called. Returns true iff the block is successfully placed. Assumes that the block is in a currently loaded chunk.",
- },
- Respawn =
- {
- Notes = "Restores the health, extinguishes fire, makes visible and sends the Respawn packet.",
- },
- SendAboveActionBarMessage =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Sends the specified message to the player (shows above action bar, doesn't show for < 1.8 clients).",
- },
- SendBlocksAround =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockRange",
- Type = "number",
- IsOptional = true,
- },
- },
- Notes = "Sends all the world's blocks in BlockRange from the specified coords to the player, as a BlockChange packet. Range defaults to 1 (only one block sent).",
- },
- SendMessage =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Sends the specified message to the player.",
- },
- SendMessageFailure =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Prepends Rose [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and sends message to player. For a command that failed to run because of insufficient permissions, etc.",
- },
- SendMessageFatal =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Prepends Red [FATAL] / colours entire text (depending on ShouldUseChatPrefixes()) and sends message to player. For something serious, such as a plugin crash, etc.",
- },
- SendMessageInfo =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Prepends Yellow [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and sends message to player. Informational message, such as command usage, etc.",
- },
- SendMessagePrivateMsg =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- {
- Name = "SenderName",
- Type = "string",
- },
- },
- Notes = "Prepends Light Blue [MSG: *SenderName*] / prepends SenderName and colours entire text (depending on ShouldUseChatPrefixes()) and sends message to player. For private messaging.",
- },
- SendMessageSuccess =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Prepends Green [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and sends message to player. Success notification.",
- },
- SendMessageWarning =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Prepends Rose [WARN] / colours entire text (depending on ShouldUseChatPrefixes()) and sends message to player. Denotes that something concerning, such as plugin reload, is about to happen.",
- },
- SendRotation =
- {
- Params =
- {
- {
- Name = "YawDegrees",
- Type = "number",
- },
- {
- Name = "PitchDegrees",
- Type = "number",
- },
- },
- Notes = "Sends the specified rotation to the player, forcing them to look that way",
- },
- SendSystemMessage =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Sends the specified message to the player (doesn't show for < 1.8 clients).",
- },
- SetBedPos =
- {
- Params =
- {
- {
- Name = "Position",
- Type = "Vector3i",
- },
- {
- Name = "World",
- Type = "cWorld*",
- IsOptional = true,
- },
- },
- Notes = "Sets the position and world of the player's respawn point, which is also known as the bed position. The player will respawn at this position and world upon death. If the world is not specified, it is set to the player's current world.",
- },
- SetCanFly =
- {
- Params =
- {
- {
- Name = "CanFly",
- Type = "boolean",
- },
- },
- Notes = "Sets if the player can fly or not.",
- },
- SetCrouch =
- {
- Params =
- {
- {
- Name = "IsCrouched",
- Type = "boolean",
- },
- },
- Notes = "Sets the crouch state, broadcasts the change to other players.",
- },
- SetCurrentExperience =
- {
- Params =
- {
- {
- Name = "XPAmount",
- Type = "number",
- },
- },
- Notes = "Sets the current amount of experience (and indirectly, the XP level).",
- },
- SetCustomName =
- {
- Params =
- {
- {
- Name = "CustomName",
- Type = "string",
- },
- },
- Notes = "Sets the custom name for this player. If you want to disable the custom name, simply set an empty string. The custom name will be used in the tab-list, in the player nametag and in the tab-completion.",
- },
- SetFlying =
- {
- Params =
- {
- {
- Name = "IsFlying",
- Type = "boolean",
- },
- },
- Notes = "Sets if the player is flying or not.",
- },
- SetFlyingMaxSpeed =
- {
- Params =
- {
- {
- Name = "FlyingMaxSpeed",
- Type = "number",
- },
- },
- Notes = "Sets the flying maximum speed, relative to the game default speed. The default value is 1. Sends the updated speed to the client.",
- },
- SetFoodExhaustionLevel =
- {
- Params =
- {
- {
- Name = "ExhaustionLevel",
- Type = "number",
- },
- },
- Notes = "Sets the food exhaustion to the specified level.",
- },
- SetFoodLevel =
- {
- Params =
- {
- {
- Name = "FoodLevel",
- Type = "number",
- },
- },
- Notes = "Sets the food level (number of half-drumsticks on-screen)",
- },
- SetFoodPoisonedTicksRemaining =
- {
- Params =
- {
- {
- Name = "FoodPoisonedTicksRemaining",
- Type = "number",
- },
- },
- Notes = "Sets the number of ticks remaining for food poisoning. Doesn't send foodpoisoning effect to the client, use FoodPoison() for that.",
- },
- SetFoodSaturationLevel =
- {
- Params =
- {
- {
- Name = "FoodSaturationLevel",
- Type = "number",
- },
- },
- Notes = "Sets the food saturation (overcharge of the food level).",
- },
- SetFoodTickTimer =
- {
- Params =
- {
- {
- Name = "FoodTickTimer",
- Type = "number",
- },
- },
- 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 =
- {
- {
- Name = "NewGameMode",
- Type = "Globals#GameMode",
- },
- },
- Notes = "Sets the gamemode for the player. The new gamemode overrides the world's default gamemode, unless it is set to gmInherit.",
- },
- SetIsFishing =
- {
- Params =
- {
- {
- Name = "IsFishing",
- Type = "boolean",
- },
- {
- Name = "FloaterEntityID",
- Type = "number",
- IsOptional = true,
- },
- },
- Notes = "Sets the 'IsFishing' flag for the player. The floater entity ID is expected for the true variant, it can be omitted when IsFishing is false. FIXME: Undefined behavior when multiple fishing rods are used simultanously",
- },
- SetName =
- {
- Params =
- {
- {
- Name = "Name",
- Type = "string",
- },
- },
- 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 =
- {
- {
- Name = "NormalMaxSpeed",
- Type = "number",
- },
- },
- Notes = "Sets the normal (walking) maximum speed, relative to the game default speed. The default value is 1. Sends the updated speed to the client, if appropriate.",
- },
- SetSprint =
- {
- Params =
- {
- {
- Name = "IsSprinting",
- Type = "boolean",
- },
- },
- Notes = "Sets whether the player is sprinting or not.",
- },
- SetSprintingMaxSpeed =
- {
- Params =
- {
- {
- Name = "SprintingMaxSpeed",
- Type = "number",
- },
- },
- Notes = "Sets the sprinting maximum speed, relative to the game default speed. The default value is 1.3. Sends the updated speed to the client, if appropriate.",
- },
- SetTeam =
- {
- Params =
- {
- {
- Name = "Team",
- Type = "cTeam",
- },
- },
- Notes = "Moves the player to the specified team.",
- },
- SetVisible =
- {
- Params =
- {
- {
- Name = "IsVisible",
- Type = "boolean",
- },
- },
- Notes = "Sets the player visibility to other players",
- },
- TossEquippedItem =
- {
- Params =
- {
- {
- Name = "Amount",
- Type = "number",
- IsOptional = true,
- },
- },
- Notes = "Tosses the item that the player has selected in their hotbar. Amount defaults to 1.",
- },
- TossHeldItem =
- {
- Params =
- {
- {
- Name = "Amount",
- Type = "number",
- IsOptional = true,
- },
- },
- Notes = "Tosses the item held by the cursor, when the player is in a UI window. Amount defaults to 1.",
- },
- TossPickup =
- {
- Params =
- {
- {
- Name = "Item",
- Type = "cItem",
- },
- },
- Notes = "Tosses a pickup newly created from the specified item.",
- },
- Unfreeze =
- {
- Notes = "Allows the player to move again, canceling the effects of Freeze()",
- },
- XpForLevel =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "XPLevel",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the total amount of XP needed for the specified XP level. Inverse of CalcLevelFromXp().",
- },
- },
- Constants =
- {
- EATING_TICKS =
- {
- Notes = "Number of ticks required for consuming an item.",
- },
- 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",
- },
- cRankManager =
- {
- Desc = [[
- Manages the players' permissions. The players are assigned a single rank, which contains groups of
- permissions. The functions in this class query or modify these.
-
- All the functions are static, call them using the cRankManager:Function() convention.
-
- The players are identified by their UUID, to support player renaming.
-
- The rank also contains specific "mesage visuals" - bits that are used for formatting messages from the
- players. There's a message prefix, which is put in front of every message the player sends, and the
- message suffix that is appended to each message. There's also a PlayerNameColorCode, which holds the
- color that is used for the player's name in the messages.
-
- Each rank can contain any number of permission groups. These groups allow for an easier setup of the
- permissions - you can share groups among ranks, so the usual approach is to group similar permissions
- together and add that group to any rank that should use those permissions.
-
- Permissions are added to individual groups. Each group can support unlimited permissions. Note that
- adding a permission to a group will make the permission available to all the ranks that contain that
- permission group.
-
- One rank is reserved as the Default rank. All players that don't have an explicit rank assigned to them
- will behave as if assigned to this rank. The default rank can be changed to any other rank at any time.
- Note that the default rank cannot be removed from the RankManager - RemoveRank() will change the default
- rank to the replacement rank, if specified, and fail if no replacement rank is specified. Renaming the
- default rank using RenameRank() will change the default rank to the new name.
- ]],
- Functions =
- {
- AddGroup =
- {
- Params =
- {
- {
- Name = "GroupName",
- Type = "string",
- },
- },
- Notes = "Adds the group of the specified name. Logs a warning and does nothing if the group already exists.",
- },
- AddGroupToRank =
- {
- Params =
- {
- {
- Name = "GroupName",
- Type = "string",
- },
- {
- Name = "RankName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Adds the specified group to the specified rank. Returns true on success, false on failure - if the group name or the rank name is not found.",
- },
- AddPermissionToGroup =
- {
- Params =
- {
- {
- Name = "Permission",
- Type = "string",
- },
- {
- Name = "GroupName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Adds the specified permission to the specified group. Returns true on success, false on failure - if the group name is not found.",
- },
- AddRank =
- {
- Params =
- {
- {
- Name = "RankName",
- Type = "string",
- },
- {
- Name = "MsgPrefix",
- Type = "string",
- },
- {
- Name = "MsgSuffix",
- Type = "string",
- },
- {
- Name = "MsgNameColorCode",
- Type = "string",
- },
- },
- Notes = "Adds a new rank of the specified name and with the specified message visuals. Logs an info message and does nothing if the rank already exists.",
- },
- ClearPlayerRanks =
- {
- Notes = "Removes all player ranks from the database. Note that this doesn't change the cPlayer instances for the already connected players, you need to update all the instances manually.",
- },
- GetAllGroups =
- {
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns an array-table containing the names of all the groups that are known to the manager.",
- },
- GetAllPermissions =
- {
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns an array-table containing all the permissions that are known to the manager.",
- },
- GetAllPlayerUUIDs =
- {
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns the short uuids of all players stored in the rank DB, sorted by the players' names (case insensitive).",
- },
- GetAllRanks =
- {
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns an array-table containing the names of all the ranks that are known to the manager.",
- },
- GetDefaultRank =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the default rank. ",
- },
- GetGroupPermissions =
- {
- Params =
- {
- {
- Name = "GroupName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns an array-table containing the permissions that the specified group contains.",
- },
- GetPlayerGroups =
- {
- Params =
- {
- {
- Name = "PlayerUUID",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns an array-table of the names of the groups that are assigned to the specified player through their rank. Returns an empty table if the player is not known or has no rank or groups assigned to them.",
- },
- GetPlayerMsgVisuals =
- {
- Params =
- {
- {
- Name = "PlayerUUID",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "MsgPrefix",
- Type = "string",
- },
- {
- Name = "MsgSuffix",
- Type = "string",
- },
- {
- Name = "MsgNameColorCode",
- Type = "string",
- },
- },
- Notes = "Returns the message visuals assigned to the player. If the player is not explicitly assigned a rank, the default rank's visuals are returned. If there is an error, no value is returned at all.",
- },
- GetPlayerName =
- {
- Params =
- {
- {
- Name = "PlayerUUID",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "PlayerName",
- Type = "string",
- },
- },
- Notes = "Returns the last name that the specified player has, for a player in the ranks database. An empty string is returned if the player isn't in the database.",
- },
- GetPlayerPermissions =
- {
- Params =
- {
- {
- Name = "PlayerUUID",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns an array-table containing all permissions that the specified player is assigned through their rank. Returns the default rank's permissions if the player has no explicit rank assigned to them. Returns an empty array on error.",
- },
- GetPlayerRankName =
- {
- Params =
- {
- {
- Name = "PlayerUUID",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "RankName",
- Type = "string",
- },
- },
- Notes = "Returns the name of the rank that is assigned to the specified player. An empty string (NOT the default rank) is returned if the player has no rank assigned to them.",
- },
- GetRankGroups =
- {
- Params =
- {
- {
- Name = "RankName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns an array-table of the names of all the groups that are assigned to the specified rank. Returns an empty table if there is no such rank.",
- },
- GetRankPermissions =
- {
- Params =
- {
- {
- Name = "RankName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns an array-table of all the permissions that are assigned to the specified rank through its groups. Returns an empty table if there is no such rank.",
- },
- GetRankVisuals =
- {
- Params =
- {
- {
- Name = "RankName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "MsgPrefix",
- Type = "string",
- },
- {
- Name = "MsgSuffix",
- Type = "string",
- },
- {
- Name = "MsgNameColorCode",
- Type = "string",
- },
- },
- Notes = "Returns the message visuals for the specified rank. Returns no value if the specified rank does not exist.",
- },
- GroupExists =
- {
- Params =
- {
- {
- Name = "GroupName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true iff the specified group exists.",
- },
- IsGroupInRank =
- {
- Params =
- {
- {
- Name = "GroupName",
- Type = "string",
- },
- {
- Name = "RankName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true iff the specified group is assigned to the specified rank.",
- },
- IsPermissionInGroup =
- {
- Params =
- {
- {
- Name = "Permission",
- Type = "string",
- },
- {
- Name = "GroupName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true iff the specified permission is assigned to the specified group.",
- },
- IsPlayerRankSet =
- {
- Params =
- {
- {
- Name = "PlayerUUID",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true iff the specified player has a rank assigned to them.",
- },
- RankExists =
- {
- Params =
- {
- {
- Name = "RankName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true iff the specified rank exists.",
- },
- RemoveGroup =
- {
- Params =
- {
- {
- Name = "GroupName",
- Type = "string",
- },
- },
- Notes = "Removes the specified group completely. The group will be removed from all the ranks using it and then erased from the manager. Logs an info message and does nothing if the group doesn't exist.",
- },
- RemoveGroupFromRank =
- {
- Params =
- {
- {
- Name = "GroupName",
- Type = "string",
- },
- {
- Name = "RankName",
- Type = "string",
- },
- },
- Notes = "Removes the specified group from the specified rank. The group will still exist, even if it isn't assigned to any rank. Logs an info message and does nothing if the group or rank doesn't exist.",
- },
- RemovePermissionFromGroup =
- {
- Params =
- {
- {
- Name = "Permission",
- Type = "string",
- },
- {
- Name = "GroupName",
- Type = "string",
- },
- },
- Notes = "Removes the specified permission from the specified group. Logs an info message and does nothing if the group doesn't exist.",
- },
- RemovePlayerRank =
- {
- Params =
- {
- {
- Name = "PlayerUUID",
- Type = "string",
- },
- },
- Notes = "Removes the player's rank; the player's left without a rank. Note that this doesn't change the {{cPlayer}} instances for the already connected players, you need to update all the instances manually. No action if the player has no rank assigned to them already.",
- },
- RemoveRank =
- {
- Params =
- {
- {
- Name = "RankName",
- Type = "string",
- },
- {
- Name = "ReplacementRankName",
- Type = "string",
- IsOptional = true,
- },
- },
- Notes = "Removes the specified rank. If ReplacementRankName is given, the players that have RankName will get their rank set to ReplacementRankName. If it isn't given, or is an invalid rank, the players will be removed from the manager, their ranks will be unset completely. Logs an info message and does nothing if the rank is not found.",
- },
- RenameGroup =
- {
- Params =
- {
- {
- Name = "OldName",
- Type = "string",
- },
- {
- Name = "NewName",
- Type = "string",
- },
- },
- Notes = "Renames the specified group. Logs an info message and does nothing if the group is not found or the new name is already used.",
- },
- RenameRank =
- {
- Params =
- {
- {
- Name = "OldName",
- Type = "string",
- },
- {
- Name = "NewName",
- Type = "string",
- },
- },
- Notes = "Renames the specified rank. Logs an info message and does nothing if the rank is not found or the new name is already used.",
- },
- SetDefaultRank =
- {
- Params =
- {
- {
- Name = "RankName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Sets the specified rank as the default rank. Returns true on success, false on failure (rank doesn't exist).",
- },
- SetPlayerRank =
- {
- Params =
- {
- {
- Name = "PlayerUUID",
- Type = "string",
- },
- {
- Name = "PlayerName",
- Type = "string",
- },
- {
- Name = "RankName",
- Type = "string",
- },
- },
- Notes = "Updates the rank for the specified player. The player name is provided for reference, the UUID is used for identification. Logs a warning and does nothing if the rank is not found.",
- },
- SetRankVisuals =
- {
- Params =
- {
- {
- Name = "RankName",
- Type = "string",
- },
- {
- Name = "MsgPrefix",
- Type = "string",
- },
- {
- Name = "MsgSuffix",
- Type = "string",
- },
- {
- Name = "MsgNameColorCode",
- Type = "string",
- },
- },
- Notes = "Updates the rank's message visuals. Logs an info message and does nothing if rank not found.",
- },
- },
- },
- cRoot =
- {
- Desc = [[
- This class represents the root of Cuberite'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.
-
- 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 =
- {
- BroadcastChat =
- {
- {
- Params =
- {
- {
- Name = "MessageText",
- Type = "string",
- },
- {
- Name = "MessageType",
- Type = "eMessageType",
- },
- },
- Notes = "Broadcasts a message to all players, with its message type set to MessageType (default: mtCustom).",
- },
- {
- Params =
- {
- {
- Name = "CompositeChat",
- Type = "cCompositeChat",
- },
- },
- Notes = "Broadcasts a {{cCompositeChat|composite chat message}} to all players.",
- },
- },
- BroadcastChatDeath =
- {
- Params =
- {
- {
- Name = "MessageText",
- Type = "string",
- },
- },
- Notes = "Broadcasts the specified message to all players, with its message type set to mtDeath. Use for when a player has died.",
- },
- BroadcastChatFailure =
- {
- Params =
- {
- {
- Name = "MessageText",
- Type = "string",
- },
- },
- Notes = "Broadcasts the specified message to all players, with its message type set to mtFailure. Use for a command that failed to run because of insufficient permissions, etc.",
- },
- BroadcastChatFatal =
- {
- Params =
- {
- {
- Name = "MessageText",
- Type = "string",
- },
- },
- Notes = "Broadcasts the specified message to all players, with its message type set to mtFatal. Use for a plugin that crashed, or similar.",
- },
- BroadcastChatInfo =
- {
- Params =
- {
- {
- Name = "MessageText",
- Type = "string",
- },
- },
- Notes = "Broadcasts the specified message to all players, with its message type set to mtInfo. Use for informational messages, such as command usage.",
- },
- BroadcastChatJoin =
- {
- Params =
- {
- {
- Name = "MessageText",
- Type = "string",
- },
- },
- Notes = "Broadcasts the specified message to all players, with its message type set to mtJoin. Use for players joining the server.",
- },
- BroadcastChatLeave =
- {
- Params =
- {
- {
- Name = "MessageText",
- Type = "string",
- },
- },
- Notes = "Broadcasts the specified message to all players, with its message type set to mtLeave. Use for players leaving the server.",
- },
- BroadcastChatSuccess =
- {
- Params =
- {
- {
- Name = "MessageText",
- Type = "string",
- },
- },
- Notes = "Broadcasts the specified message to all players, with its message type set to mtSuccess. Use for success messages.",
- },
- BroadcastChatWarning =
- {
- Params =
- {
- {
- Name = "MessageText",
- Type = "string",
- },
- },
- Notes = "Broadcasts the specified message to all players, with its message type set to mtWarning. Use for concerning events, such as plugin reload etc.",
- },
- DoWithPlayerByUUID =
- {
- Params =
- {
- {
- Name = "PlayerUUID",
- Type = "string",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is the player with the uuid, calls the CallbackFunction with the {{cPlayer}} parameter representing the player. The CallbackFunction has the following signature:
function Callback({{cPlayer|Player}})
The function returns false if the player was not found, or whatever bool value the callback returned if the player was found.",
- },
- FindAndDoWithPlayer =
- {
- Params =
- {
- {
- Name = "PlayerName",
- Type = "string",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the given callback function for the player with the name best matching the name string provided. This function is case-insensitive and will match partial names. Returns false if player not found or there is ambiguity, true otherwise. The CallbackFunction has the following signature:
function Callback({{cPlayer|Player}})
",
- },
- ForEachPlayer =
- {
- Params =
- {
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Notes = "Calls the given callback function for each player. The callback function has the following signature:
function Callback({{cPlayer|cPlayer}})
",
- },
- ForEachWorld =
- {
- Params =
- {
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Notes = "Calls the given callback function for each world. The callback function has the following signature:
function Callback({{cWorld|cWorld}})
",
- },
- Get =
- {
- IsStatic = true,
- Returns =
- {
- {
- Type = "cRoot",
- },
- },
- Notes = "Returns the one and only cRoot object.",
- },
- GetBrewingRecipe =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Bottle",
- Type = "cItem",
- },
- {
- Name = "Ingredient",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the result item, if a recipe has been found to brew the Ingredient into Bottle. If no recipe is found, returns no value.",
- },
- GetBuildCommitID =
- {
- IsStatic = true,
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "For official builds (Travis CI / Jenkins) it returns the exact commit hash used for the build. For unofficial local builds, returns the approximate commit hash (since the true one cannot be determined), formatted as \"approx: <CommitHash>\".",
- },
- GetBuildDateTime =
- {
- IsStatic = true,
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "For official builds (Travic CI / Jenkins) it returns the date and time of the build. For unofficial local builds, returns the approximate datetime of the commit (since the true one cannot be determined), formatted as \"approx: <DateTime-iso8601>\".",
- },
- GetBuildID =
- {
- IsStatic = true,
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "For official builds (Travis CI / Jenkins) it returns the unique ID of the build, as recognized by the build system. For unofficial local builds, returns the string \"Unknown\".",
- },
- GetBuildSeriesName =
- {
- IsStatic = true,
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "For official builds (Travis CI / Jenkins) it returns the series name of the build (for example \"Cuberite Windows x64 Master\"). For unofficial local builds, returns the string \"local build\".",
- },
- GetCraftingRecipes =
- {
- Returns =
- {
- {
- Type = "cCraftingRecipe",
- },
- },
- Notes = "Returns the CraftingRecipes object",
- },
- GetDefaultWorld =
- {
- Returns =
- {
- {
- Type = "cWorld",
- },
- },
- Notes = "Returns the world object from the default world.",
- },
- GetFurnaceFuelBurnTime =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Fuel",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of ticks for how long the item would fuel a furnace. Returns zero if not a fuel.",
- },
- GetFurnaceRecipe =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "InItem",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Name = "OutItem",
- Type = "cItem",
- },
- {
- Name = "NumTicks",
- Type = "number",
- },
- {
- Name = "InItem",
- Type = "cItem",
- },
- },
- Notes = "Returns the furnace recipe for smelting the specified input. If a recipe is found, returns the smelted result, the number of ticks required for the smelting operation, and the input consumed (note that Cuberite supports smelting M items into N items and different smelting rates). If no recipe is found, returns no value.",
- },
- GetPhysicalRAMUsage =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the amount of physical RAM that the entire Cuberite process is using, in KiB. Negative if the OS doesn't support this query.",
- },
- GetPluginManager =
- {
- Returns =
- {
- {
- Type = "cPluginManager",
- },
- },
- Notes = "Returns the cPluginManager object.",
- },
- GetPrimaryServerVersion =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the servers primary server version.",
- },
- GetProtocolVersionTextFromInt =
- {
- Params =
- {
- {
- Name = "ProtocolVersionNumber",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the Minecraft client version from the given Protocol version number. If there is no version found, it returns 'Unknown protocol (Number)'",
- },
- GetServer =
- {
- Returns =
- {
- {
- Type = "cServer",
- },
- },
- Notes = "Returns the cServer object.",
- },
- GetServerUpTime =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the uptime of the server in seconds.",
- },
- GetTotalChunkCount =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the amount of loaded chunks.",
- },
- GetVirtualRAMUsage =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the amount of virtual RAM that the entire Cuberite process is using, in KiB. Negative if the OS doesn't support this query.",
- },
- GetWebAdmin =
- {
- Returns =
- {
- {
- Type = "cWebAdmin",
- },
- },
- Notes = "Returns the cWebAdmin object.",
- },
- GetWorld =
- {
- Params =
- {
- {
- Name = "WorldName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "cWorld",
- },
- },
- Notes = "Returns the cWorld object of the given world. It returns nil if there is no world with the given name.",
- },
- QueueExecuteConsoleCommand =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- 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.",
- },
- SaveAllChunks =
- {
- Notes = "Saves all the chunks in all the worlds. Note that the saving is queued on each world's tick thread and this functions returns before the chunks are actually saved.",
- },
- SetPrimaryServerVersion =
- {
- Params =
- {
- {
- Name = "Protocol Version",
- Type = "number",
- },
- },
- Notes = "Sets the servers PrimaryServerVersion to the given protocol number.",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Querying a furnace recipe",
- Contents = [[
- To find the furnace recipe for an item, use the following code (adapted from the Debuggers plugin's /fr command):
-
-local HeldItem = a_Player:GetEquippedItem();
-local Out, NumTicks, In = cRoot:GetFurnaceRecipe(HeldItem); -- Note STATIC call - no need for a Get()
-if (Out ~= nil) then
- -- There is a recipe, list it:
- a_Player:SendMessage(
- "Furnace turns " .. ItemToFullString(In) ..
- " to " .. ItemToFullString(Out) ..
- " in " .. NumTicks .. " ticks (" ..
- tostring(NumTicks / 20) .. " seconds)."
- );
-else
- -- No recipe found
- a_Player:SendMessage("There is no furnace recipe that would smelt " .. ItemToString(HeldItem));
-end
-
- ]],
- },
- },
- },
- cScoreboard =
- {
- Desc = [[
- This class manages the objectives and teams of a single world.
- ]],
- Functions =
- {
- AddPlayerScore =
- {
- Params =
- {
- {
- Name = "Name",
- Type = "string",
- },
- {
- Name = "Type",
- Type = "",
- },
- {
- Name = "Value",
- Type = "",
- },
- },
- Notes = "Adds a value to all player scores of the specified objective type.",
- },
- ForEachObjective =
- {
- Params =
- {
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the specified callback for each objective in the scoreboard. Returns true if all objectives have been processed (including when there are zero objectives), or false if the callback function has aborted the enumeration by returning true. The callback function has the following signature:
function Callback({{cObjective|Objective}})
The callback should return false or no value to continue with the next objective, or true to abort the enumeration.",
- },
- ForEachTeam =
- {
- Params =
- {
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the specified callback for each team in the scoreboard. Returns true if all teams have been processed (including when there are zero teams), or false if the callback function has aborted the enumeration by returning true. The callback function has the following signature:
function Callback({{cObjective|Objective}})
The callback should return false or no value to continue with the next team, or true to abort the enumeration.",
- },
- GetNumObjectives =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the nuber of registered objectives.",
- },
- GetNumTeams =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of registered teams.",
- },
- GetObjective =
- {
- Params =
- {
- {
- Name = "string",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "cObjective",
- },
- },
- Notes = "Returns the objective with the specified name.",
- },
- GetObjectiveIn =
- {
- Params =
- {
- {
- Name = "DisplaySlot",
- Type = "",
- },
- },
- Returns =
- {
- {
- Type = "cObjective",
- },
- },
- Notes = "Returns the objective in the specified display slot. Can be nil.",
- },
- GetTeam =
- {
- Params =
- {
- {
- Name = "TeamName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "cTeam",
- },
- },
- Notes = "Returns the team with the specified name.",
- },
- GetTeamNames =
- {
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns the names of all teams, as an array-table of strings",
- },
- RegisterObjective =
- {
- Params =
- {
- {
- Name = "Name",
- Type = "string",
- },
- {
- Name = "DisplayName",
- Type = "string",
- },
- {
- Name = "Type",
- Type = "",
- },
- },
- Returns =
- {
- {
- Type = "cObjective",
- },
- },
- Notes = "Registers a new scoreboard objective. Returns the {{cObjective}} instance, nil on error.",
- },
- RegisterTeam =
- {
- Params =
- {
- {
- Name = "Name",
- Type = "string",
- },
- {
- Name = "DisplayName",
- Type = "string",
- },
- {
- Name = "Prefix",
- Type = "",
- },
- {
- Name = "Suffix",
- Type = "",
- },
- },
- Returns =
- {
- {
- Type = "cTeam",
- },
- },
- Notes = "Registers a new team. Returns the {{cTeam}} instance, nil on error.",
- },
- RemoveObjective =
- {
- Params =
- {
- {
- Name = "Name",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Removes the objective with the specified name. Returns true if operation was successful.",
- },
- RemoveTeam =
- {
- Params =
- {
- {
- Name = "TeamName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Removes the team with the specified name. Returns true if operation was successful.",
- },
- SetDisplay =
- {
- Params =
- {
- {
- Name = "Name",
- Type = "string",
- },
- {
- Name = "DisplaySlot",
- Type = "",
- },
- },
- Notes = "Updates the currently displayed objective.",
- },
- },
- Constants =
- {
- dsCount =
- {
- Notes = "",
- },
- dsList =
- {
- Notes = "",
- },
- dsName =
- {
- Notes = "",
- },
- dsSidebar =
- {
- Notes = "",
- },
- },
- },
- cServer =
- {
- Desc = [[
- This class manages all the client connections internally. In the API layer, it allows to get and set
- the general properties of the server, such as the description and max players.
-
- It used to support broadcasting chat messages to all players, this functionality has been moved to
- {{cRoot}}:BroadcastChat().
- ]],
- Functions =
- {
- DoesAllowMultiLogin =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if players can log in multiple times from the same account (normally used for debugging), false if only one player per name is allowed.",
- },
- GetDescription =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the server description set in the settings.ini.",
- },
- GetMaxPlayers =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the max amount of players who can join the server.",
- },
- GetNumPlayers =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the amount of players online.",
- },
- GetServerID =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the ID of the server?",
- },
- IsHardcore =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the server is hardcore (players get banned on death).",
- },
- IsPlayerInQueue =
- {
- Params =
- {
- {
- Name = "Username",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified player is queued to be transferred to a World.",
- },
- SetMaxPlayers =
- {
- Params =
- {
- {
- Name = "MaxPlayers",
- Type = "number",
- },
- },
- Notes = "Sets the max amount of players who can join.",
- },
- ShouldAuthenticate =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true iff the server is set to authenticate players (\"online mode\").",
- },
- },
- },
- cStringCompression =
- {
- Desc = [[
- Provides functions to compress or decompress string
-
- All functions in this class are static, so they should be called in the dot convention:
-
- ]],
- Functions =
- {
- CompressStringGZIP =
- {
- Params =
- {
- {
- Name = "Data",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Compresses data in a string using GZIP",
- },
- CompressStringZLIB =
- {
- Params =
- {
- {
- Name = "Data",
- Type = "string",
- },
- {
- Name = "factor",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Compresses data in a string using ZLIB. Factor 0 is no compression and factor 9 is maximum compression.",
- },
- InflateString =
- {
- Params =
- {
- {
- Name = "Data",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Uncompresses a string using Inflate",
- },
- UncompressStringGZIP =
- {
- Params =
- {
- {
- Name = "Data",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Uncompress a string using GZIP",
- },
- UncompressStringZLIB =
- {
- Params =
- {
- {
- Name = "Data",
- Type = "string",
- },
- {
- Name = "UncompressedLength",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Uncompresses Data using ZLIB",
- },
- },
- },
- cTeam =
- {
- Desc = [[
- This class manages a single player team.
- ]],
- Functions =
- {
- AddPlayer =
- {
- Params =
- {
- {
- Name = "PlayerName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Adds a player to this team. Returns true if the operation was successful.",
- },
- AllowsFriendlyFire =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether team friendly fire is allowed.",
- },
- CanSeeFriendlyInvisible =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether players can see invisible teammates.",
- },
- GetDisplayName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the display name of the team.",
- },
- GetName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the internal name of the team.",
- },
- GetNumPlayers =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of registered players.",
- },
- GetPrefix =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the prefix prepended to the names of the members of this team.",
- },
- GetSuffix =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the suffix appended to the names of the members of this team.",
- },
- HasPlayer =
- {
- Params =
- {
- {
- Name = "PlayerName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether the specified player is a member of this team.",
- },
- RemovePlayer =
- {
- Params =
- {
- {
- Name = "PlayerName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Removes the player with the specified name from this team. Returns true if the operation was successful.",
- },
- Reset =
- {
- Notes = "Removes all players from this team.",
- },
- SetCanSeeFriendlyInvisible =
- {
- Params =
- {
- {
- Name = "CanSeeFriendlyInvisible",
- Type = "boolean",
- },
- },
- Notes = "Set whether players can see invisible teammates.",
- },
- SetDisplayName =
- {
- Params =
- {
- {
- Name = "DisplayName",
- Type = "string",
- },
- },
- Notes = "Sets the display name of this team. (i.e. what will be shown to the players)",
- },
- SetFriendlyFire =
- {
- Params =
- {
- {
- Name = "AllowFriendlyFire",
- Type = "boolean",
- },
- },
- Notes = "Sets whether team friendly fire is allowed.",
- },
- SetPrefix =
- {
- Params =
- {
- {
- Name = "Prefix",
- Type = "string",
- },
- },
- Notes = "Sets the prefix prepended to the names of the members of this team.",
- },
- SetSuffix =
- {
- Params =
- {
- {
- Name = "Suffix",
- Type = "string",
- },
- },
- Notes = "Sets the suffix appended to the names of the members of this team.",
- },
- },
- },
- cTNTEntity =
- {
- Desc = "This class manages a TNT entity.",
- Functions =
- {
- Explode =
- {
- Notes = "Explode the tnt.",
- },
- GetFuseTicks =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the fuse ticks - the number of game ticks until the tnt explodes.",
- },
- SetFuseTicks =
- {
- Params =
- {
- {
- Name = "TicksUntilExplosion",
- Type = "number",
- },
- },
- Notes = "Set the fuse ticks until the tnt will explode.",
- },
- },
- Inherits = "cEntity",
- },
- cUrlParser =
- {
- Desc = [[
- Provides a parser for generic URLs that returns the individual components of the URL.
-
- Note that all functions are static. Call them by using "cUrlParser:Parse(...)" etc.
- ]],
- Functions =
- {
- GetDefaultPort =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Scheme",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the default port that should be used for the given scheme (protocol). Returns zero if the scheme is not known.",
- },
- IsKnownScheme =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Scheme",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the scheme (protocol) is recognized by the parser.",
- },
- Parse =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "URL",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "Scheme",
- Type = "string",
- },
- {
- Name = "Username",
- Type = "string",
- },
- {
- Name = "Password",
- Type = "string",
- },
- {
- Name = "Host",
- Type = "string",
- },
- {
- Name = "Port",
- Type = "string",
- },
- {
- Name = "Path",
- Type = "string",
- },
- {
- Name = "Query",
- Type = "string",
- },
- {
- Name = "Fragment",
- Type = "string",
- },
- },
- Notes = "Returns the individual parts of the URL. Parts that are not explicitly specified in the URL are empty, the default port for the scheme is used. If parsing fails, the function returns nil and an error message.",
- },
- ParseAuthorityPart =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "AuthPart",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "Username",
- Type = "string",
- },
- {
- Name = "Password",
- Type = "string",
- },
- {
- Name = "Host",
- Type = "string",
- },
- {
- Name = "Port",
- Type = "string",
- },
- },
- Notes = "Parses the Authority part of the URL. Parts that are not explicitly specified in the AuthPart are returned empty, the port is returned zero. If parsing fails, the function returns nil and an error message.",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Code example",
- Contents = [[
- The following code fragment uses the cUrlParser to parse an URL string into its components, and
- prints those components out:
-
-local Scheme, Username, Password, Host, Port, Path, Query, Fragment = cUrlParser:Parse(
- "http://anonymous:user@example.com@ftp.cuberite.org:9921/releases/2015/?sort=date#files"
-)
-if not(Scheme) then
- -- Parsing failed, the second returned value (in Username) is the error message:
- LOG(" Error: " .. (Username or ""))
-else
- LOG(" Scheme = " .. Scheme) -- "http"
- LOG(" Username = " .. Username) -- "anonymous"
- LOG(" Password = " .. Password) -- "user@example.com"
- LOG(" Host = " .. Host) -- "ftp.cuberite.org"
- LOG(" Port = " .. Port) -- 9921
- LOG(" Path = " .. Path) -- "releases/2015/"
- LOG(" Query = " .. Query) -- "sort=date"
- LOG(" Fragment = " .. Fragment) -- "files"
-end
-
- ]],
- },
- },
- },
- cWebPlugin =
- {
- Desc = "",
- Functions =
- {
-
- },
- },
- cWindow =
- {
- Desc = [[
- This class is the common ancestor for all window classes used by Cuberite. 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.
-
- 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.
-
- Windows also have numeric properties, these are used to set the progressbars for furnaces or the XP
- costs for enchantment tables.
- ]],
- Functions =
- {
- GetSlot =
- {
- Params =
- {
- {
- Name = "Player",
- Type = "cPlayer",
- },
- {
- Name = "SlotNumber",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item at the specified slot for the specified player. Returns nil and logs to server console on error.",
- },
- GetWindowID =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the ID of the window, as used by the network protocol",
- },
- GetWindowTitle =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the window title that will be displayed to the player",
- },
- GetWindowType =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the type of the window, one of the constants in the table above",
- },
- GetWindowTypeName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the textual representation of the window's type, such as \"minecraft:chest\".",
- },
- IsSlotInPlayerHotbar =
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified slot number is in the player hotbar",
- },
- IsSlotInPlayerInventory =
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- 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 =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified slot number is in the player's main inventory",
- },
- SetProperty =
- {
- Params =
- {
- {
- Name = "PropertyID",
- Type = "number",
- },
- {
- Name = "PropertyValue",
- Type = "number",
- },
- {
- Name = "Player",
- Type = "cPlayer",
- IsOptional = true,
- },
- },
- Notes = "Updates a numerical property associated with the window. Typically used for furnace progressbars. Sends the UpdateWindowProperty packet to the specified Player, or to all current clients of the window if Player is not specified.",
- },
- SetSlot =
- {
- Params =
- {
- {
- Name = "Player",
- Type = "cPlayer",
- },
- {
- Name = "SlotNum",
- Type = "number",
- },
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the contents of the specified slot for the specified player. Ignored if the slot number is invalid",
- },
- SetWindowTitle =
- {
- Params =
- {
- {
- Name = "WindowTitle",
- Type = "string",
- },
- },
- Notes = "Sets the window title that will be displayed to the player",
- },
- },
- Constants =
- {
- wtAnimalChest =
- {
- Notes = "A horse or donkey window",
- },
- wtAnvil =
- {
- Notes = "An anvil window",
- },
- wtBeacon =
- {
- Notes = "A beacon window",
- },
- wtBrewery =
- {
- Notes = "A brewing stand window",
- },
- wtChest =
- {
- Notes = "A {{cChestEntity|chest}} or doublechest window",
- },
- wtDropSpenser =
- {
- Notes = "A {{cDropperEntity|dropper}} or a {{cDispenserEntity|dispenser}} window",
- },
- wtEnchantment =
- {
- Notes = "An enchantment table window",
- },
- wtFurnace =
- {
- Notes = "A {{cFurnaceEntity|furnace}} window",
- },
- wtHopper =
- {
- Notes = "A {{cHopperEntity|hopper}} window",
- },
- wtInventory =
- {
- Notes = "An inventory window",
- },
- wtNPCTrade =
- {
- Notes = "A villager trade window",
- },
- wtWorkbench =
- {
- Notes = "A workbench (crafting table) window",
- },
- },
- },
- cWorld =
- {
- Desc = [[
- cWorld is the game world. It is the hub of all the information managed by individual classes,
- providing convenient access to them. Cuberite supports multiple worlds in any combination of
- world types. You can have two overworlds, three nethers etc. To enumerate all world the server
- provides, use the {{cRoot}}:ForEachWorld() function.
-
- The world data is held in individual chunks. Each chunk consists of 16 (x) * 16 (z) * 256 (y)
- blocks, each block is specified by its block type (8-bit) and block metadata (4-bit).
- Additionally, each block has two light values calculated - skylight (how much daylight it receives)
- and blocklight (how much light from light-emissive blocks it receives), both 4-bit.
-
- Each world runs several separate threads used for various housekeeping purposes, the most important
- of those is the Tick thread. This thread updates the game logic 20 times per second, and it is
- the thread where all the gameplay actions are evaluated. Liquid physics, entity interactions,
- player ovement etc., all are applied in this thread.
-
- Additional threads include the generation thread (generates new chunks as needed, storage thread
- (saves and loads chunk from the disk), lighting thread (updates block light values) and the
- chunksender thread (compresses chunks to send to the clients).
-
- The world provides access to all its {{cPlayer|players}}, {{cEntity|entities}} and {{cBlockEntity|block
- entities}}. Because of multithreading issues, individual objects cannot be retrieved for indefinite
- handling, but rather must be modified in callbacks, within which they are guaranteed to stay valid.
-
- Physics for individual blocks are handled by the simulators. These will fire in each tick for all
- blocks that have been scheduled for simulator update ("simulator wakeup"). The simulators include
- liquid physics, falling blocks, fire spreading and extinguishing and redstone.
-
- Game time is also handled by the world. It provides the time-of-day and the total world age.
- ]],
- Functions =
- {
- AreCommandBlocksEnabled =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether command blocks are enabled on the (entire) server",
- },
- BroadcastBlockAction =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "ActionByte1",
- Type = "number",
- },
- {
- Name = "ActionByte2",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "ExcludeClient",
- Type = "cClientHandle",
- IsOptional = true,
- },
- },
- Notes = "Broadcasts the BlockAction packet to all clients who have the appropriate chunk loaded (except ExcludeClient). The contents of the packet are specified by the parameters for the call, the blocktype needn't match the actual block that is present in the world data at the specified location.",
- },
- BroadcastChat =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- {
- Name = "ExcludeClient",
- Type = "cClientHandle",
- IsOptional = true,
- },
- {
- Name = "ChatPrefix",
- Type = "eMessageType",
- IsOptional = true,
- },
- },
- Notes = "Sends the Message to all players in this world, except the optional ExcludeClient. No formatting is done by the server.",
- },
- BroadcastChatDeath =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- {
- Name = "ExcludeClient",
- Type = "cClientHandle",
- IsOptional = true,
- },
- },
- Notes = "Prepends Gray [DEATH] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For when a player dies.",
- },
- BroadcastChatFailure =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- {
- Name = "ExcludeClient",
- Type = "cClientHandle",
- IsOptional = true,
- },
- },
- Notes = "Prepends Rose [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For a command that failed to run because of insufficient permissions, etc.",
- },
- BroadcastChatFatal =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- {
- Name = "ExcludeClient",
- Type = "cClientHandle",
- IsOptional = true,
- },
- },
- Notes = "Prepends Red [FATAL] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For a plugin that crashed, or similar.",
- },
- BroadcastChatInfo =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- {
- Name = "ExcludeClient",
- Type = "cClientHandle",
- IsOptional = true,
- },
- },
- Notes = "Prepends Yellow [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For informational messages, such as command usage.",
- },
- BroadcastChatSuccess =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- {
- Name = "ExcludeClient",
- Type = "cClientHandle",
- IsOptional = true,
- },
- },
- Notes = "Prepends Green [INFO] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For success messages.",
- },
- BroadcastChatWarning =
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- {
- Name = "ExcludeClient",
- Type = "cClientHandle",
- IsOptional = true,
- },
- },
- Notes = "Prepends Rose [WARN] / colours entire text (depending on ShouldUseChatPrefixes()) and broadcasts message. For concerning events, such as plugin reload etc.",
- },
- BroadcastEntityAnimation =
- {
- Params =
- {
- {
- Name = "TargetEntity",
- Type = "cEntity",
- },
- {
- Name = "Animation",
- Type = "number",
- },
- {
- Name = "ExcludeClient",
- Type = "cClientHandle",
- IsOptional = true,
- },
- },
- Notes = "Sends an animation of an entity to all clienthandles (except ExcludeClient if given)",
- },
- BroadcastParticleEffect =
- {
- Params =
- {
- {
- Name = "ParticleName",
- Type = "string",
- },
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "OffsetX",
- Type = "number",
- },
- {
- Name = "OffsetY",
- Type = "number",
- },
- {
- Name = "OffsetZ",
- Type = "number",
- },
- {
- Name = "ParticleData",
- Type = "number",
- },
- {
- Name = "ParticleAmount",
- Type = "number",
- },
- {
- Name = "ExcludeClient",
- Type = "cClientHandle",
- IsOptional = true,
- },
- },
- Notes = "Spawns the specified particles to all players in the world exept the optional ExeptClient. A list of available particles by thinkofdeath can be found {{https://gist.github.com/thinkofdeath/5110835|Here}}",
- },
- BroadcastSoundEffect =
- {
- Params =
- {
- {
- Name = "SoundName",
- Type = "string",
- },
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "Volume",
- Type = "number",
- },
- {
- Name = "Pitch",
- Type = "number",
- },
- {
- Name = "ExcludeClient",
- Type = "cClientHandle",
- IsOptional = true,
- },
- },
- Notes = "Sends the specified sound effect to all players in this world, except the optional ExceptClient",
- },
- BroadcastSoundParticleEffect =
- {
- Params =
- {
- {
- Name = "EffectID",
- Type = "number",
- },
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "EffectData",
- Type = "string",
- },
- {
- Name = "ExcludeClient",
- Type = "cClientHandle",
- IsOptional = true,
- },
- },
- Notes = "Sends the specified effect to all players in this world, except the optional ExceptClient",
- },
- CastThunderbolt =
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Notes = "Creates a thunderbolt at the specified coords",
- },
- ChangeWeather =
- {
- Notes = "Forces the weather to change in the next game tick. Weather is changed according to the normal rules: wSunny <-> wRain <-> wStorm",
- },
- ChunkStay =
- {
- Params =
- {
- {
- Name = "ChunkCoordTable",
- Type = "table",
- },
- {
- Name = "OnChunkAvailable",
- Type = "function",
- },
- {
- Name = "OnAllChunksAvailable",
- Type = "function",
- },
- },
- Notes = "Queues the specified chunks to be loaded or generated and calls the specified callbacks once they are loaded. ChunkCoordTable is an arra-table of chunk coords, each coord being a table of 2 numbers: { {Chunk1x, Chunk1z}, {Chunk2x, Chunk2z}, ...}. When any of those chunks are made available (including being available at the start of this call), the OnChunkAvailable() callback is called. When all the chunks are available, the OnAllChunksAvailable() callback is called. The function signatures are:
function OnChunkAvailable(ChunkX, ChunkZ)\
-function OnAllChunksAvailable()
All return values from the callbacks are ignored.",
- },
- CreateProjectile =
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "ProjectileKind",
- Type = "cProjectileEntity#eKind",
- },
- {
- Name = "Creator",
- Type = "cEntity",
- },
- {
- Name = "Originating Item",
- Type = "cItem",
- },
- {
- Name = "Speed",
- Type = "Vector3d",
- IsOptional = true,
- },
- },
- Notes = "Creates a new projectile of the specified kind at the specified coords. The projectile's creator is set to Creator (may be nil). The item that created the projectile entity, commonly the {{cPlayer|player}}'s currently equipped item, is used at present for fireworks to correctly set their entity metadata. It is not used for any other projectile. Optional speed indicates the initial speed for the projectile.",
- },
- DigBlock =
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Notes = "Replaces the specified block with air, without dropping the usual pickups for the block. Wakes up the simulators for the block and its neighbors.",
- },
- DoExplosionAt =
- {
- Params =
- {
- {
- Name = "Force",
- Type = "number",
- },
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "CanCauseFire",
- Type = "boolean",
- },
- {
- Name = "Source",
- Type = "eExplosionSource",
- },
- {
- Name = "SourceData",
- Type = "any",
- },
- },
- Notes = "Creates an explosion of the specified relative force in the specified position. If CanCauseFire is set, the explosion will set blocks on fire, too. The Source parameter specifies the source of the explosion, one of the esXXX constants. The SourceData parameter is specific to each source type, usually it provides more info about the source.",
- },
- DoWithBeaconAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a beacon at the specified coords, calls the CallbackFunction with the {{cBeaconEntity}} parameter representing the beacon. The CallbackFunction has the following signature:
function Callback({{cBeaconEntity|BeaconEntity}})
The function returns false if there is no beacon, or if there is, it returns the bool value that the callback has returned.",
- },
- DoWithBlockEntityAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a block entity at the specified coords, calls the CallbackFunction with the {{cBlockEntity}} parameter representing the block entity. The CallbackFunction has the following signature:
function Callback({{cBlockEntity|BlockEntity}})
The function returns false if there is no block entity, or if there is, it returns the bool value that the callback has returned. Use {{tolua}}.cast() to cast the Callback's BlockEntity parameter to the correct {{cBlockEntity}} descendant.",
- },
- DoWithBrewingstandAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a brewingstand at the specified coords, calls the CallbackFunction with the {{cBrewingstandEntity}} parameter representing the brewingstand. The CallbackFunction has the following signature:
function Callback({{cBrewingstandEntity|cBrewingstandEntity}})
The function returns false if there is no brewingstand, or if there is, it returns the bool value that the callback has returned.",
- },
- DoWithChestAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a chest at the specified coords, calls the CallbackFunction with the {{cChestEntity}} parameter representing the chest. The CallbackFunction has the following signature:
function Callback({{cChestEntity|ChestEntity}})
The function returns false if there is no chest, or if there is, it returns the bool value that the callback has returned.",
- },
- DoWithCommandBlockAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a command block at the specified coords, calls the CallbackFunction with the {{cCommandBlockEntity}} parameter representing the command block. The CallbackFunction has the following signature:
function Callback({{cCommandBlockEntity|CommandBlockEntity}})
The function returns false if there is no command block, or if there is, it returns the bool value that the callback has returned.",
- },
- DoWithDispenserAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a dispenser at the specified coords, calls the CallbackFunction with the {{cDispenserEntity}} parameter representing the dispenser. The CallbackFunction has the following signature:
function Callback({{cDispenserEntity|DispenserEntity}})
The function returns false if there is no dispenser, or if there is, it returns the bool value that the callback has returned.",
- },
- DoWithDropperAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a dropper at the specified coords, calls the CallbackFunction with the {{cDropperEntity}} parameter representing the dropper. The CallbackFunction has the following signature:
function Callback({{cDropperEntity|DropperEntity}})
The function returns false if there is no dropper, or if there is, it returns the bool value that the callback has returned.",
- },
- DoWithDropSpenserAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a dropper or a dispenser at the specified coords, calls the CallbackFunction with the {{cDropSpenserEntity}} parameter representing the dropper or dispenser. The CallbackFunction has the following signature:
function Callback({{cDropSpenserEntity|DropSpenserEntity}})
Note that this can be used to access both dispensers and droppers in a similar way. The function returns false if there is neither dispenser nor dropper, or if there is, it returns the bool value that the callback has returned.",
- },
- DoWithEntityByID =
- {
- Params =
- {
- {
- Name = "EntityID",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If an entity with the specified ID exists, calls the callback with the {{cEntity}} parameter representing the entity. The CallbackFunction has the following signature:
function Callback({{cEntity|Entity}})
The function returns false if the entity was not found, and it returns the same bool value that the callback has returned if the entity was found.",
- },
- DoWithFlowerPotAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a flower pot at the specified coords, calls the CallbackFunction with the {{cFlowerPotEntity}} parameter representing the flower pot. The CallbackFunction has the following signature:
function Callback({{cFlowerPotEntity|FlowerPotEntity}})
The function returns false if there is no flower pot, or if there is, it returns the bool value that the callback has returned.",
- },
- DoWithFurnaceAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a furnace at the specified coords, calls the CallbackFunction with the {{cFurnaceEntity}} parameter representing the furnace. The CallbackFunction has the following signature:
function Callback({{cFurnaceEntity|FurnaceEntity}})
The function returns false if there is no furnace, or if there is, it returns the bool value that the callback has returned.",
- },
- DoWithMobHeadAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a mob head at the specified coords, calls the CallbackFunction with the {{cMobHeadEntity}} parameter representing the furnace. The CallbackFunction has the following signature:
function Callback({{cMobHeadEntity|MobHeadEntity}})
The function returns false if there is no mob head, or if there is, it returns the bool value that the callback has returned.",
- },
- DoWithNoteBlockAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a note block at the specified coords, calls the CallbackFunction with the {{cNoteEntity}} parameter representing the note block. The CallbackFunction has the following signature:
function Callback({{cNoteEntity|NoteEntity}})
The function returns false if there is no note block, or if there is, it returns the bool value that the callback has returned.",
- },
- DoWithPlayer =
- {
- Params =
- {
- {
- Name = "PlayerName",
- Type = "string",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is a player of the specified name (exact match), calls the CallbackFunction with the {{cPlayer}} parameter representing the player. The CallbackFunction has the following signature:
function Callback({{cPlayer|Player}})
The function returns false if the player was not found, or whatever bool value the callback returned if the player was found.",
- },
- DoWithPlayerByUUID =
- {
- Params =
- {
- {
- Name = "PlayerUUID",
- Type = "string",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "If there is the player with the uuid, calls the CallbackFunction with the {{cPlayer}} parameter representing the player. The CallbackFunction has the following signature:
function Callback({{cPlayer|Player}})
The function returns false if the player was not found, or whatever bool value the callback returned if the player was found.",
- },
- FastSetBlock =
- {
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Sets the block at the specified coords, without waking up the simulators or replacing the block entities for the previous block type. Do not use if the block being replaced has a block entity tied to it!",
- },
- {
- Params =
- {
- {
- Name = "BlockCoords",
- Type = "Vector3i",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Sets the block at the specified coords, without waking up the simulators or replacing the block entities for the previous block type. Do not use if the block being replaced has a block entity tied to it!",
- },
- },
- FindAndDoWithPlayer =
- {
- Params =
- {
- {
- Name = "PlayerName",
- Type = "string",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the given callback function for the player with the name best matching the name string provided. This function is case-insensitive and will match partial names. Returns false if player not found or there is ambiguity, true otherwise. The CallbackFunction has the following signature:
function Callback({{cPlayer|Player}})
",
- },
- ForEachBlockEntityInChunk =
- {
- Params =
- {
- {
- Name = "ChunkX",
- Type = "number",
- },
- {
- Name = "ChunkZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the specified callback for each block entity in the chunk. Returns true if all block entities in the chunk have been processed (including when there are zero block entities), or false if the callback has aborted the enumeration by returning true. The CallbackFunction has the following signature:
function Callback({{cBlockEntity|BlockEntity}})
The callback should return false or no value to continue with the next block entity, or true to abort the enumeration. Use {{tolua}}.cast() to cast the Callback's BlockEntity parameter to the correct {{cBlockEntity}} descendant.",
- },
- ForEachBrewingstandInChunk =
- {
- Params =
- {
- {
- Name = "ChunkX",
- Type = "number",
- },
- {
- Name = "ChunkZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the specified callback for each brewingstand in the chunk. Returns true if all brewingstands in the chunk have been processed (including when there are zero brewingstands), or false if the callback has aborted the enumeration by returning true. The CallbackFunction has the following signature:
function Callback({{cBrewingstandEntity|cBrewingstandEntity}})
The callback should return false or no value to continue with the next brewingstand, or true to abort the enumeration.",
- },
- ForEachChestInChunk =
- {
- Params =
- {
- {
- Name = "ChunkX",
- Type = "number",
- },
- {
- Name = "ChunkZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the specified callback for each chest in the chunk. Returns true if all chests in the chunk have been processed (including when there are zero chests), or false if the callback has aborted the enumeration by returning true. The CallbackFunction has the following signature:
function Callback({{cChestEntity|ChestEntity}})
The callback should return false or no value to continue with the next chest, or true to abort the enumeration.",
- },
- ForEachEntity =
- {
- Params =
- {
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the specified callback for each entity in the loaded world. Returns true if all the entities have been processed (including when there are zero entities), or false if the callback function has aborted the enumeration by returning true. The callback function has the following signature:
function Callback({{cEntity|Entity}})
The callback should return false or no value to continue with the next entity, or true to abort the enumeration.",
- },
- ForEachEntityInBox =
- {
- Params =
- {
- {
- Name = "Box",
- Type = "cBoundingBox",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the specified callback for each entity in the specified bounding box. Returns true if all the entities have been processed (including when there are zero entities), or false if the callback function has aborted the enumeration by returning true. If any chunk within the bounding box is not valid, it is silently skipped without any notification. The callback function has the following signature:
function Callback({{cEntity|Entity}})
The callback should return false or no value to continue with the next entity, or true to abort the enumeration.",
- },
- ForEachEntityInChunk =
- {
- Params =
- {
- {
- Name = "ChunkX",
- Type = "number",
- },
- {
- Name = "ChunkZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the specified callback for each entity in the specified chunk. Returns true if all the entities have been processed (including when there are zero entities), or false if the chunk is not loaded or the callback function has aborted the enumeration by returning true. The callback function has the following signature:
function Callback({{cEntity|Entity}})
The callback should return false or no value to continue with the next entity, or true to abort the enumeration.",
- },
- ForEachFurnaceInChunk =
- {
- Params =
- {
- {
- Name = "ChunkX",
- Type = "number",
- },
- {
- Name = "ChunkZ",
- Type = "number",
- },
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the specified callback for each furnace in the chunk. Returns true if all furnaces in the chunk have been processed (including when there are zero furnaces), or false if the callback has aborted the enumeration by returning true. The CallbackFunction has the following signature:
function Callback({{cFurnaceEntity|FurnaceEntity}})
The callback should return false or no value to continue with the next furnace, or true to abort the enumeration.",
- },
- ForEachPlayer =
- {
- Params =
- {
- {
- Name = "CallbackFunction",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the specified callback for each player in the loaded world. Returns true if all the players have been processed (including when there are zero players), or false if the callback function has aborted the enumeration by returning true. The callback function has the following signature:
function Callback({{cPlayer|Player}})
The callback should return false or no value to continue with the next player, or true to abort the enumeration.",
- },
- GenerateChunk =
- {
- Params =
- {
- {
- Name = "ChunkX",
- Type = "number",
- },
- {
- Name = "ChunkZ",
- Type = "number",
- },
- },
- Notes = "Queues the specified chunk in the chunk generator. Ignored if the chunk is already generated (use RegenerateChunk() to force chunk re-generation).",
- },
- GetBiomeAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "eBiome",
- Type = "EMCSBiome",
- },
- },
- Notes = "Returns the biome at the specified coords. Reads the biome from the chunk, if it is loaded, otherwise it uses the chunk generator to provide the biome value.",
- },
- GetBlock =
- {
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "BLOCKTYPE",
- Type = "number",
- },
- },
- Notes = "Returns the block type of the block at the specified coords, or 0 if the appropriate chunk is not loaded.",
- },
- {
- Params =
- {
- {
- Name = "BlockCoords",
- Type = "Vector3i",
- },
- },
- Returns =
- {
- {
- Name = "BLOCKTYPE",
- Type = "number",
- },
- },
- Notes = "Returns the block type of the block at the specified coords, or 0 if the appropriate chunk is not loaded.",
- },
- },
- GetBlockBlockLight =
- {
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the amount of block light at the specified coords, or 0 if the appropriate chunk is not loaded.",
- },
- {
- Params =
- {
- {
- Name = "Pos",
- Type = "Vector3i",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the amount of block light at the specified coords, or 0 if the appropriate chunk is not loaded.",
- },
- },
- GetBlockInfo =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsBlockValid",
- Type = "boolean",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- {
- Name = "BlockSkyLight",
- Type = "number",
- },
- {
- Name = "BlockBlockLight",
- Type = "number",
- },
- },
- Notes = "Returns the complete block info for the block at the specified coords. The first value specifies if the block is in a valid loaded chunk, the other values are valid only if BlockValid is true.",
- },
- GetBlockMeta =
- {
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the block metadata of the block at the specified coords, or 0 if the appropriate chunk is not loaded.",
- },
- {
- Params =
- {
- {
- Name = "BlockCoords",
- Type = "Vector3i",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the block metadata of the block at the specified coords, or 0 if the appropriate chunk is not loaded.",
- },
- },
- GetBlockSkyLight =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the block skylight of the block at the specified coords, or 0 if the appropriate chunk is not loaded.",
- },
- GetBlockTypeMeta =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsBlockValid",
- Type = "boolean",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Returns the block type and metadata for the block at the specified coords. The first value specifies if the block is in a valid loaded chunk, the other values are valid only if BlockValid is true.",
- },
- GetDefaultWeatherInterval =
- {
- Params =
- {
- {
- Name = "Weather",
- Type = "eWeather",
- },
- },
- Notes = "Returns the default weather interval for the specific weather type. Returns -1 for any unknown weather.",
- },
- GetDimension =
- {
- Returns =
- {
- {
- Type = "eDimension",
- },
- },
- Notes = "Returns the dimension of the world - dimOverworld, dimNether or dimEnd.",
- },
- GetGameMode =
- {
- Returns =
- {
- {
- Type = "eGameMode",
- },
- },
- Notes = "Returns the gamemode of the world - gmSurvival, gmCreative or gmAdventure.",
- },
- GetGeneratorQueueLength =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of chunks that are queued in the chunk generator.",
- },
- GetHeight =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the maximum height of the particula block column in the world. If the chunk is not loaded, it waits for it to load / generate. WARNING: Do not use, Use TryGetHeight() instead for a non-waiting version, otherwise you run the risk of a deadlock!",
- },
- GetIniFileName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the world.ini file that the world uses to store the information.",
- },
- GetLightingQueueLength =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of chunks in the lighting thread's queue.",
- },
- GetLinkedEndWorldName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the end world this world is linked to.",
- },
- GetLinkedNetherWorldName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the Netherworld linked to this world.",
- },
- GetLinkedOverworldName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the world this world is linked to.",
- },
- GetMapManager =
- {
- Returns =
- {
- {
- Type = "cMapManager",
- },
- },
- Notes = "Returns the {{cMapManager|MapManager}} object used by this world.",
- },
- GetMaxCactusHeight =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the configured maximum height to which cacti will grow naturally.",
- },
- GetMaxNetherPortalHeight =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the maximum height for a nether portal",
- },
- GetMaxNetherPortalWidth =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the maximum width for a nether portal",
- },
- GetMaxSugarcaneHeight =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the configured maximum height to which sugarcane will grow naturally.",
- },
- GetMaxViewDistance =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the maximum viewdistance that players can see in this world. The view distance is the amount of chunks around the player that the player can see.",
- },
- GetMinNetherPortalHeight =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the minimum height for a nether portal",
- },
- GetMinNetherPortalWidth =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the minimum width for a nether portal",
- },
- GetName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the world, as specified in the settings.ini file.",
- },
- GetNumChunks =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of chunks currently loaded.",
- },
- GetNumUnusedDirtyChunks =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of unused dirty chunks. That's the number of chunks that we can save and then unload.",
- },
- GetScoreBoard =
- {
- Returns =
- {
- {
- Type = "cScoreBoard",
- },
- },
- Notes = "Returns the {{cScoreBoard|ScoreBoard}} object used by this world. ",
- },
- GetSeed =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the seed of the world.",
- },
- GetSignLines =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsValid",
- Type = "boolean",
- },
- {
- Name = "Line1",
- Type = "string",
- IsOptional = true,
- },
- {
- Name = "Line2",
- Type = "string",
- IsOptional = true,
- },
- {
- Name = "Line3",
- Type = "string",
- IsOptional = true,
- },
- {
- Name = "Line4",
- Type = "string",
- IsOptional = true,
- },
- },
- Notes = "Returns true and the lines of a sign at the specified coords, or false if there is no sign at the coords.",
- },
- GetSpawnX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the X coord of the default spawn",
- },
- GetSpawnY =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the Y coord of the default spawn",
- },
- GetSpawnZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the Z coord of the default spawn",
- },
- GetStorageLoadQueueLength =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of chunks queued up for loading",
- },
- GetStorageSaveQueueLength =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of chunks queued up for saving",
- },
- GetTicksUntilWeatherChange =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of ticks that will pass before the weather is changed",
- },
- GetTimeOfDay =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of ticks that have passed from the sunrise, 0 .. 24000.",
- },
- GetTNTShrapnelLevel =
- {
- Returns =
- {
- {
- Name = "ShrapnelLevel",
- Type = "Globals#eShrapnelLevel",
- },
- },
- Notes = "Returns the shrapnel level, representing the block types that are propelled outwards following an explosion. Based on this value and a random picker, blocks are selectively converted to physics entities (FallingSand) and flung outwards.",
- },
- GetWeather =
- {
- Returns =
- {
- {
- Type = "eWeather",
- },
- },
- Notes = "Returns the current weather in the world (wSunny, wRain, wStorm). To check for weather, use IsWeatherXXX() functions instead.",
- },
- GetWorldAge =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the total age of the world, in ticks. The age always grows, cannot be set by plugins and is unrelated to TimeOfDay.",
- },
- GrowCactus =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "NumBlocksToGrow",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Grows a cactus block at the specified coords, by up to the specified number of blocks. Adheres to the world's maximum cactus growth (GetMaxCactusHeight()). Returns the amount of blocks the cactus grew inside this call.",
- },
- GrowMelonPumpkin =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "StemBlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Grows a melon or pumpkin, based on the stem block type specified (assumed to be at the coords provided). Checks for normal melon / pumpkin growth conditions - stem not having another produce next to it and suitable ground below. Returns true if the melon or pumpkin grew successfully.",
- },
- GrowRipePlant =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "IsByBonemeal",
- Type = "boolean",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Grows the plant at the specified coords. If IsByBonemeal is true, checks first if the specified plant type is bonemealable in the settings. Returns true if the plant was grown, false if not.",
- },
- GrowSugarcane =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "NumBlocksToGrow",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Grows a sugarcane block at the specified coords, by up to the specified number of blocks. Adheres to the world's maximum sugarcane growth (GetMaxSugarcaneHeight()). Returns the amount of blocks the sugarcane grew inside this call.",
- },
- GrowTree =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Notes = "Grows a tree based at the specified coords. If there is a sapling there, grows the tree based on that sapling, otherwise chooses a tree image based on the biome.",
- },
- GrowTreeByBiome =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Notes = "Grows a tree based at the specified coords. The tree type is picked from types available for the biome at those coords.",
- },
- GrowTreeFromSapling =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "SaplingMeta",
- Type = "number",
- },
- },
- Notes = "Grows a tree based at the specified coords. The tree type is determined from the sapling meta (the sapling itself needn't be present).",
- },
- IsBlockDirectlyWatered =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified block has a water block right next to it (on the X/Z axes)",
- },
- IsDaylightCycleEnabled =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the daylight cycle is enabled.",
- },
- IsDeepSnowEnabled =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether the configuration has DeepSnow enabled.",
- },
- IsGameModeAdventure =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the current gamemode is gmAdventure.",
- },
- IsGameModeCreative =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the current gamemode is gmCreative.",
- },
- IsGameModeSpectator =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the current gamemode is gmSpectator.",
- },
- IsGameModeSurvival =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the current gamemode is gmSurvival.",
- },
- IsPVPEnabled =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether PVP is enabled in the world settings.",
- },
- IsTrapdoorOpen =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns false if there is no trapdoor there or if the block isn't a trapdoor or if the chunk wasn't loaded. Returns true if trapdoor is open.",
- },
- IsWeatherRain =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the current world is raining (no thunderstorm).",
- },
- IsWeatherRainAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified location is raining (takes biomes into account - it never rains in a desert).",
- },
- IsWeatherStorm =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the current world is stormy.",
- },
- IsWeatherStormAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified location is stormy (takes biomes into account - no storm in a desert).",
- },
- IsWeatherSunny =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the current weather is sunny.",
- },
- IsWeatherSunnyAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the current weather is sunny at the specified location (takes into account biomes).",
- },
- IsWeatherWet =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the current world has any precipitation (rain or storm).",
- },
- IsWeatherWetAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified location has any precipitation (rain or storm) (takes biomes into account, deserts are never wet).",
- },
- PrepareChunk =
- {
- Params =
- {
- {
- Name = "ChunkX",
- Type = "number",
- },
- {
- Name = "ChunkZ",
- Type = "number",
- },
- {
- Name = "Callback",
- Type = "function",
- IsOptional = true,
- },
- },
- Notes = "Queues the chunk for preparing - making sure that it's generated and lit. It is legal to call with no callback. The callback function has the following signature:
function Callback(ChunkX, ChunkZ)
",
- },
- QueueBlockForTick =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "TicksToWait",
- Type = "number",
- },
- },
- Notes = "Queues the specified block to be ticked after the specified number of gameticks.",
- },
- QueueSaveAllChunks =
- {
- Notes = "Queues all chunks to be saved in the world storage thread",
- },
- QueueSetBlock =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- {
- Name = "TickDelay",
- Type = "number",
- },
- },
- 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 =
- {
- {
- Name = "TaskFunction",
- Type = "function",
- },
- },
- 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
function()
All return values from the function are ignored. Note that this function is actually called *after* the QueueTask() function returns. Note that it is unsafe to store references to Cuberite objects, such as entities, across from the caller to the task handler function; store the EntityID instead.",
- },
- QueueUnloadUnusedChunks =
- {
- Notes = "Queues a cTask that unloads chunks that are no longer needed and are saved.",
- },
- RegenerateChunk =
- {
- Params =
- {
- {
- Name = "ChunkX",
- Type = "number",
- },
- {
- Name = "ChunkZ",
- Type = "number",
- },
- },
- 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.",
- },
- ScheduleTask =
- {
- Params =
- {
- {
- Name = "DelayTicks",
- Type = "number",
- },
- {
- Name = "TaskFunction",
- Type = "function",
- },
- },
- Notes = "Queues the specified function to be executed in the world's tick thread after a the specified number of ticks. This enables operations to be queued for execution in the future. The function signature is
function({{cWorld|World}})
All return values from the function are ignored. Note that it is unsafe to store references to Cuberite objects, such as entities, across from the caller to the task handler function; store the EntityID instead.",
- },
- SendBlockTo =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "Player",
- Type = "cPlayer",
- },
- },
- Notes = "Sends the block at the specified coords to the specified player's client, as an UpdateBlock packet.",
- },
- SetAreaBiome =
- {
- {
- Params =
- {
- {
- Name = "MinX",
- Type = "number",
- },
- {
- Name = "MaxX",
- Type = "number",
- },
- {
- Name = "MinZ",
- Type = "number",
- },
- {
- Name = "MaxZ",
- Type = "number",
- },
- {
- Name = "Biome",
- Type = "EMCSBiome",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Sets the biome in the rectangular area specified. Returns true if successful, false if any of the chunks were unloaded.",
- },
- {
- Params =
- {
- {
- Name = "Cuboid",
- Type = "cCuboid",
- },
- {
- Name = "Biome",
- Type = "EMCSBiome",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Sets the biome in the cuboid specified. Returns true if successful, false if any of the chunks were unloaded. The cuboid needn't be sorted.",
- },
- },
- SetBiomeAt =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "Biome",
- Type = "EMCSBiome",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Sets the biome at the specified block coords. Returns true if successful, false otherwise.",
- },
- SetBlock =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- {
- Name = "ShouldSendToClients",
- Type = "boolean",
- IsOptional = true,
- },
- },
- 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. If ShouldSendToClients is true (default), the change is broadcast to all players who have this chunk loaded; if false, the change is made server-side only.",
- },
- SetBlockMeta =
- {
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- {
- Name = "ShouldMarkChunkDirty",
- Type = "boolean",
- IsOptional = true,
- },
- {
- Name = "ShouldSendToClients",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Notes = "Sets the meta for the block at the specified coords. If ShouldMarkChunkDirty is true (default), the chunk is marked dirty and will be saved later on. If ShouldSendToClients is true (default), the change is broadcast to all clients who have the chunk loaded, if false, the change is kept server-side only.",
- },
- {
- Params =
- {
- {
- Name = "BlockCoords",
- Type = "Vector3i",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Notes = "Sets the meta for the block at the specified coords.",
- },
- },
- SetChunkAlwaysTicked =
- {
- Params =
- {
- {
- Name = "ChunkX",
- Type = "number",
- },
- {
- Name = "ChunkZ",
- Type = "number",
- },
- {
- Name = "IsAlwaysTicked",
- Type = "boolean",
- },
- },
- Notes = "Sets the chunk to always be ticked even when it doesn't contain any clients. IsAlwaysTicked set to true turns forced ticking on, set to false turns it off. Every call with 'true' should be paired with a later call with 'false', otherwise the ticking won't stop. Multiple actions can request ticking independently, the ticking will continue until the last call with 'false'. Note that when the chunk unloads, it loses the value of this flag.",
- },
- SetCommandBlockCommand =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "Command",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Sets the command to be executed in a command block at the specified coordinates. Returns if command was changed.",
- },
- SetCommandBlocksEnabled =
- {
- Params =
- {
- {
- Name = "AreEnabled",
- Type = "boolean",
- },
- },
- Notes = "Sets whether command blocks should be enabled on the (entire) server.",
- },
- SetDaylightCycleEnabled =
- {
- Params =
- {
- {
- Name = "IsEnabled",
- Type = "boolean",
- },
- },
- Notes = "Starts or stops the daylight cycle.",
- },
- SetLinkedEndWorldName =
- {
- Params =
- {
- {
- Name = "WorldName",
- Type = "string",
- },
- },
- Notes = "Sets the name of the world that the end portal should link to.",
- },
- SetLinkedNetherWorldName =
- {
- Params =
- {
- {
- Name = "WorldName",
- Type = "string",
- },
- },
- Notes = "Sets the name of the world that the nether portal should link to.",
- },
- SetLinkedOverworldName =
- {
- Params =
- {
- {
- Name = "WorldName",
- Type = "string",
- },
- },
- Notes = "Sets the name of the world that the nether portal should link to?",
- },
- SetMaxNetherPortalHeight =
- {
- Params =
- {
- {
- Name = "Height",
- Type = "number",
- },
- },
- Notes = "Sets the maximum height for a nether portal",
- },
- SetMaxNetherPortalWidth =
- {
- Params =
- {
- {
- Name = "Width",
- Type = "number",
- },
- },
- Notes = "Sets the maximum width for a nether portal",
- },
- SetMaxViewDistance =
- {
- Params =
- {
- {
- Name = "MaxViewDistance",
- Type = "number",
- },
- },
- Notes = "Sets the maximum viewdistance of the players in the world. This maximum takes precedence over each player's ViewDistance setting.",
- },
- SetMinNetherPortalHeight =
- {
- Params =
- {
- {
- Name = "Height",
- Type = "number",
- },
- },
- Notes = "Sets the minimum height for a nether portal",
- },
- SetMinNetherPortalWidth =
- {
- Params =
- {
- {
- Name = "Width",
- Type = "number",
- },
- },
- Notes = "Sets the minimum width for a nether portal",
- },
- SetNextBlockTick =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Notes = "Sets the blockticking to start at the specified block in the next tick.",
- },
- SetShouldUseChatPrefixes =
- {
- Returns =
- {
- {
- Name = "ShouldUseChatPrefixes",
- Type = "boolean",
- },
- },
- Notes = "Sets whether coloured chat prefixes such as [INFO] is used with the SendMessageXXX() or BroadcastChatXXX(), or simply the entire message is coloured in the respective colour.",
- },
- SetSignLines =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "Line1",
- Type = "string",
- },
- {
- Name = "Line2",
- Type = "string",
- },
- {
- Name = "Line3",
- Type = "string",
- },
- {
- Name = "Line4",
- Type = "string",
- },
- {
- Name = "Player",
- Type = "cPlayer",
- IsOptional = true,
- },
- },
- Notes = "Sets the sign text at the specified coords. The sign-updating hooks are called for the change. The Player parameter is used to indicate the player from whom the change has come, it may be nil.",
- },
- SetSpawn =
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Sets the default spawn at the specified coords. Returns false if the new spawn couldn't be stored in the INI file.",
- },
- SetTicksUntilWeatherChange =
- {
- Params =
- {
- {
- Name = "NumTicks",
- Type = "number",
- },
- },
- Notes = "Sets the number of ticks after which the weather will be changed.",
- },
- SetTimeOfDay =
- {
- Params =
- {
- {
- Name = "TimeOfDayTicks",
- Type = "number",
- },
- },
- Notes = "Sets the time of day, expressed as number of ticks past sunrise, in the range 0 .. 24000.",
- },
- SetTNTShrapnelLevel =
- {
- Params =
- {
- {
- Name = "ShrapnelLevel",
- Type = "Globals#eShrapnelLevel",
- },
- },
- Notes = "Sets the Shrapnel level of the world.",
- },
- SetTrapdoorOpen =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "IsOpen",
- Type = "boolean",
- },
- },
- Notes = "Opens or closes a trapdoor at the specific coordinates.",
- },
- SetWeather =
- {
- Params =
- {
- {
- Name = "Weather",
- Type = "eWeather",
- },
- },
- Notes = "Sets the current weather (wSunny, wRain, wStorm) and resets the TicksUntilWeatherChange to the default value for the new weather. The normal weather-changing hooks are called for the change.",
- },
- ShouldBroadcastAchievementMessages =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the server should broadcast achievement messages in this world.",
- },
- ShouldBroadcastDeathMessages =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the server should broadcast death messages in this world.",
- },
- ShouldLavaSpawnFire =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the world is configured to spawn fires near lava (world.ini: [Physics].ShouldLavaSpawnFire value)",
- },
- ShouldUseChatPrefixes =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns whether coloured chat prefixes are prepended to chat messages or the entire message is simply coloured.",
- },
- SpawnBoat =
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "EntityID",
- Type = "number",
- },
- },
- Notes = "Spawns a boat at the specific coordinates. Returns the entity ID of the new boat, or {{cEntity#NO_ID|cEntity.NO_ID}} if no boat was created.",
- },
- SpawnExperienceOrb =
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "Reward",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "EntityID",
- Type = "number",
- },
- },
- Notes = "Spawns an {{cExpOrb|experience orb}} at the specified coords, with the given reward",
- },
- SpawnFallingBlock =
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "BlockType",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "EntityID",
- Type = "number",
- },
- },
- Notes = "Spawns a {{cFallingBlock|Falling Block}} entity at the specified coords with the given block type/meta",
- },
- SpawnItemPickups =
- {
- {
- Params =
- {
- {
- Name = "Pickups",
- Type = "cItems",
- },
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "FlyAwaySpeed",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "IsPlayerCreated",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Notes = "Spawns the specified pickups at the position specified. The FlyAwaySpeed is a coefficient (default: 1) used to initialize the random speed in which the pickups fly away from the spawn position. The IsPlayerCreated parameter (default: false) is used to initialize the created {{cPickup}} object's IsPlayerCreated value.",
- },
- {
- Params =
- {
- {
- Name = "Pickups",
- Type = "cItems",
- },
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "SpeedX",
- Type = "number",
- },
- {
- Name = "SpeedY",
- Type = "number",
- },
- {
- Name = "SpeedZ",
- Type = "number",
- },
- {
- Name = "IsPlayerCreated",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Notes = "Spawns the specified pickups at the position specified. All the pickups fly away from the spawn position using the specified speed. The IsPlayerCreated parameter (default: false) is used to initialize the created {{cPickup}} object's IsPlayerCreated value.",
- },
- },
- SpawnMinecart =
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "MinecartType",
- Type = "number",
- },
- {
- Name = "Item",
- Type = "cItem",
- IsOptional = true,
- },
- {
- Name = "BlockHeight",
- Type = "number",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "EntityID",
- Type = "number",
- },
- },
- Notes = "Spawns a minecart at the specific coordinates. MinecartType is the item type of the minecart. If the minecart is an empty minecart then the given Item (default: empty) is the block to be displayed inside the minecart, and BlockHeight (default: 1) is the relative distance of the block from the minecart. Returns the entity ID of the new minecart, or {{cEntity#NO_ID|cEntity.NO_ID}} if no minecart was created.",
- },
- SpawnMob =
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "MonsterType",
- Type = "cMonster",
- },
- {
- Name = "IsBaby",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "EntityID",
- Type = "number",
- },
- },
- Notes = "Spawns the specified type of mob at the specified coords. If the Baby parameter is true, the mob will be a baby. Returns the EntityID of the creates entity, or -1 on failure. ",
- },
- SpawnPrimedTNT =
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- {
- Name = "FuseTicks",
- Type = "number",
- },
- {
- Name = "InitialVelocityCoeff",
- Type = "number",
- },
- },
- Notes = "Spawns a {{cTNTEntity|primed TNT entity}} at the specified coords, with the given fuse ticks. The entity gets a random speed multiplied by the InitialVelocityCoeff, 1 being the default value.",
- },
- TryGetHeight =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsValid",
- Type = "boolean",
- },
- {
- Name = "Height",
- Type = "number",
- },
- },
- Notes = "Returns true and height of the highest non-air block if the chunk is loaded, or false otherwise.",
- },
- UpdateSign =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "Line1",
- Type = "string",
- },
- {
- Name = "Line2",
- Type = "string",
- },
- {
- Name = "Line3",
- Type = "string",
- },
- {
- Name = "Line4",
- Type = "string",
- },
- {
- Name = "Player",
- Type = "cPlayer",
- IsOptional = true,
- },
- },
- Notes = "(DEPRECATED) Please use SetSignLines().",
- },
- UseBlockEntity =
- {
- Params =
- {
- {
- Name = "Player",
- Type = "cPlayer",
- },
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Notes = "Makes the specified Player use the block entity at the specified coords (open chest UI, etc.) If the cords are in an unloaded chunk or there's no block entity, ignores the call.",
- },
- VillagersShouldHarvestCrops =
- {
- Notes = "Returns true if villagers can harvest crops.",
- },
- WakeUpSimulators =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Notes = "Wakes up the simulators for the specified block.",
- },
- WakeUpSimulatorsInArea =
- {
- Params =
- {
- {
- Name = "MinBlockX",
- Type = "number",
- },
- {
- Name = "MaxBlockX",
- Type = "number",
- },
- {
- Name = "MinBlockY",
- Type = "number",
- },
- {
- Name = "MaxBlockY",
- Type = "number",
- },
- {
- Name = "MinBlockZ",
- Type = "number",
- },
- {
- Name = "MaxBlockZ",
- Type = "number",
- },
- },
- Notes = "Wakes up the simulators for all the blocks in the specified area (edges inclusive).",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Using callbacks",
- Contents = [[
- To avoid problems with stale objects, the cWorld class will not let plugins get a direct pointer
- to an {{cEntity|entity}}, {{cBlockEntity|block entity}} or a {{cPlayer|player}}. Such an object
- could be modified or even destroyed by another thread while the plugin holds it, so it would be
- rather unsafe.
-
- Instead, the cWorld provides access to these objects using callbacks. The plugin provides a
- function that is called and receives the object as a parameter; cWorld guarantees that while
- the callback is executing, the object will stay valid. If a plugin needs to "remember" the
- object outside of the callback, it needs to store the entity ID, blockentity coords or player
- name.
-
- The following code examples show how to use the callbacks
-
- This code teleports player Player to another player named ToName in the same world:
-
--- Player is a cPlayer object
--- ToName is a string
--- World is a cWorld object
-World:ForEachPlayer(
- function (a_OtherPlayer)
- if (a_OtherPlayer:GetName() == ToName) then
- Player:TeleportToEntity(a_OtherPlayer);
- end
-);
-
-
- This code fills each furnace in the chunk with 64 coals:
-
--- Player is a cPlayer object
--- World is a cWorld object
-World:ForEachFurnaceInChunk(Player:GetChunkX(), Player:GetChunkZ(),
- function (a_Furnace)
- a_Furnace:SetFuelSlot(cItem(E_ITEM_COAL, 64));
- end
-);
-
-
- This code teleports all spiders up by 100 blocks:
-
--- World is a cWorld object
-World:ForEachEntity(
- function (a_Entity)
- if not(a_Entity:IsMob()) then
- return;
- end
-
- -- Get the cMonster out of cEntity, now that we know the entity represents one.
- local Monster = tolua.cast(a_Entity, "cMonster");
- if (Monster:GetMobType() == mtSpider) then
- Monster:TeleportToCoords(Monster:GetPosX(), Monster:GetPosY() + 100, Monster:GetPosZ());
- end
- end
-);
-
- ]],
- },
- },
- },
- Globals =
- {
- Desc = [[
- These functions are available directly, without a class instance. Any plugin can call them at any
- time.
- ]],
- Functions =
- {
- AddFaceDirection =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockFace",
- Type = "eBlockFace",
- },
- {
- Name = "IsInverse",
- Type = "boolean",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Notes = "Returns the coords of a block adjacent to the specified block through the specified {{Globals#BlockFaces|face}}",
- },
- BlockFaceToString =
- {
- Params =
- {
- {
- Name = "eBlockFace",
- Type = "eBlockFace",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the string representation of the {{Globals#BlockFaces|eBlockFace}} constant. Uses the axis-direction-based names, such as BLOCK_FACE_XP.",
- },
- BlockStringToType =
- {
- Params =
- {
- {
- Name = "BlockTypeString",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "BLOCKTYPE",
- Type = "number",
- },
- },
- Notes = "Returns the block type parsed from the given string",
- },
- Clamp =
- {
- Params =
- {
- {
- Name = "Number",
- Type = "number",
- },
- {
- Name = "Min",
- Type = "number",
- },
- {
- Name = "Max",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Clamp the number to the specified range.",
- },
- ClickActionToString =
- {
- Params =
- {
- {
- Name = "ClickAction",
- Type = "eClickAction",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns a string description of the ClickAction enumerated value",
- },
- DamageTypeToString =
- {
- Params =
- {
- {
- Name = "DamageType",
- Type = "eDamageType",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Converts the {{Globals#eDamageType|DamageType}} to a string representation ",
- },
- EscapeString =
- {
- Params =
- {
- {
- Name = "Input",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns a copy of the string with all quotes and backslashes escaped by a backslash",
- },
- GetChar =
- {
- Params =
- {
- {
- Name = "Input",
- Type = "string",
- },
- {
- Name = "Index",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "(OBSOLETE, use standard Lua string.sub() instead) Returns one character from the string, specified by index. ",
- },
- GetIniItemSet =
- {
- Params =
- {
- {
- Name = "IniFile",
- Type = "cIniFile",
- },
- {
- Name = "SectionName",
- Type = "string",
- },
- {
- Name = "KeyName",
- Type = "string",
- },
- {
- Name = "DefaultValue",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item that has been read from the specified INI file value. If the value is not present in the INI file, the DefaultValue is stored in the file and parsed as the result. Returns empty item if the value cannot be parsed. ",
- },
- GetTime =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the current OS time, as a unix time stamp (number of seconds since Jan 1, 1970)",
- },
- IsBiomeNoDownfall =
- {
- Params =
- {
- {
- Name = "Biome",
- Type = "EMCSBiome",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the biome is 'dry', that is, there is no precipitation during rains and storms.",
- },
- IsValidBlock =
- {
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if BlockType is a known block type",
- },
- IsValidItem =
- {
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if ItemType is a known item type",
- },
- ItemToFullString =
- {
- Params =
- {
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the string representation of the item, in the format 'ItemTypeText:ItemDamage * Count'",
- },
- ItemToString =
- {
- Params =
- {
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the string representation of the item type",
- },
- ItemTypeToString =
- {
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the string representation of ItemType ",
- },
- LOG =
- {
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Logs a text into the server console and logfile using 'normal' severity (gray text)",
- },
- {
- Params =
- {
- {
- Name = "Message",
- Type = "cCompositeChat",
- },
- },
- Notes = "Logs the {{cCompositeChat}}'s human-readable text into the server console. The severity is converted from the CompositeChat's MessageType.",
- },
- },
- LOGERROR =
- {
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Logs a text into the server console and logfile using 'error' severity (black text on red background)",
- },
- {
- Params =
- {
- {
- Name = "Message",
- Type = "cCompositeChat",
- },
- },
- Notes = "Logs the {{cCompositeChat}}'s human-readable text into the server console and logfile using 'error' severity (black text on red background)",
- },
- },
- LOGINFO =
- {
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Logs a text into the server console and logfile using 'info' severity (yellow text)",
- },
- {
- Params =
- {
- {
- Name = "Message",
- Type = "cCompositeChat",
- },
- },
- Notes = "Logs the {{cCompositeChat}}'s human-readable text into the server console and logfile using 'info' severity (yellow text)",
- },
- },
- LOGWARN =
- {
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Logs a text into the server console and logfile using 'warning' severity (red text); OBSOLETE, use LOGWARNING() instead",
- },
- {
- Params =
- {
- {
- Name = "Message",
- Type = "cCompositeChat",
- },
- },
- Notes = "Logs the {{cCompositeChat}}'s human-readable text into the server console and logfile using 'warning' severity (red text); OBSOLETE, use LOGWARNING() instead",
- },
- },
- LOGWARNING =
- {
- {
- Params =
- {
- {
- Name = "Message",
- Type = "string",
- },
- },
- Notes = "Logs a text into the server console and logfile using 'warning' severity (red text)",
- },
- {
- Params =
- {
- {
- Name = "Message",
- Type = "cCompositeChat",
- },
- },
- Notes = "Logs the {{cCompositeChat}}'s human-readable text into the server console and logfile using 'warning' severity (red text)",
- },
- },
- md5 =
- {
- Params =
- {
- {
- Name = "Data",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "OBSOLETE, use the {{cCryptoHash}} functions instead. Converts a string to a raw binary md5 hash.",
- },
- MirrorBlockFaceY =
- {
- Params =
- {
- {
- Name = "eBlockFace",
- Type = "eBlockFace",
- },
- },
- Returns =
- {
- {
- Type = "eBlockFace",
- },
- },
- Notes = "Returns the {{Globals#BlockFaces|eBlockFace}} that corresponds to the given {{Globals#BlockFaces|eBlockFace}} after mirroring it around the Y axis (or rotating 180 degrees around it).",
- },
- NoCaseCompare =
- {
- Params =
- {
- {
- Name = "Value1",
- Type = "string",
- },
- {
- Name = "Value2",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Case-insensitive string comparison; returns 0 if the strings are the same, -1 if Value1 is smaller and 1 if Value2 is smaller",
- },
- NormalizeAngleDegrees =
- {
- Params =
- {
- {
- Name = "AngleDegrees",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "AngleDegrees",
- Type = "number",
- },
- },
- Notes = "Returns the angle, wrapped into the [-180, +180) range.",
- },
- ReplaceString =
- {
- Params =
- {
- {
- Name = "full-string",
- Type = "string",
- },
- {
- Name = "to-be-replaced-string",
- Type = "string",
- },
- {
- Name = "to-replace-string",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Replaces *each* occurence of to-be-replaced-string in full-string with to-replace-string",
- },
- RotateBlockFaceCCW =
- {
- Params =
- {
- {
- Name = "eBlockFace",
- Type = "eBlockFace",
- },
- },
- Returns =
- {
- {
- Type = "eBlockFace",
- },
- },
- Notes = "Returns the {{Globals#BlockFaces|eBlockFace}} that corresponds to the given {{Globals#BlockFaces|eBlockFace}} after rotating it around the Y axis 90 degrees counter-clockwise.",
- },
- RotateBlockFaceCW =
- {
- Params =
- {
- {
- Name = "eBlockFace",
- Type = "eBlockFace",
- },
- },
- Returns =
- {
- {
- Type = "eBlockFace",
- },
- },
- Notes = "Returns the {{Globals#BlockFaces|eBlockFace}} that corresponds to the given {{Globals#BlockFaces|eBlockFace}} after rotating it around the Y axis 90 degrees clockwise.",
- },
- StringSplit =
- {
- Params =
- {
- {
- Name = "Input",
- Type = "string",
- },
- {
- Name = "SeperatorsString",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Seperates string into multiple by splitting every time any of the characters in SeperatorsString is encountered. Returns and array-table of strings.",
- },
- StringSplitAndTrim =
- {
- Params =
- {
- {
- Name = "Input",
- Type = "string",
- },
- {
- Name = "SeperatorsString",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Seperates string into multiple by splitting every time any of the characters in SeperatorsString is encountered. Each of the separate strings is trimmed (whitespace removed from the beginning and end of the string). Returns an array-table of strings.",
- },
- StringSplitWithQuotes =
- {
- Params =
- {
- {
- Name = "Input",
- Type = "string",
- },
- {
- Name = "SeperatorsString",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Seperates string into multiple by splitting every time any of the characters in SeperatorsString is encountered. Whitespace wrapped with single or double quotes will be ignored. Returns an array-table of strings.",
- },
- StringToBiome =
- {
- Params =
- {
- {
- Name = "Input",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "BiomeType",
- Type = "Globals#BiomeTypes",
- },
- },
- Notes = "Converts a string representation to a {{Globals#BiomeTypes|BiomeType}} enumerated value. Returns biInvalidBiome if the input is not a recognized biome.",
- },
- StringToDamageType =
- {
- Params =
- {
- {
- Name = "Input",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "DamageType",
- Type = "Globals#DamageType",
- },
- },
- Notes = "Converts a string representation to a {{Globals#DamageType|DamageType}} enumerated value. Returns -1 if the inupt is not a recognized damage type.",
- },
- StringToDimension =
- {
- Params =
- {
- {
- Name = "Input",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "Dimension",
- Type = "Globals#WorldDimension",
- },
- },
- Notes = "Converts a string representation to a {{Globals#WorldDimension|Dimension}} enumerated value. Returns dimNotSet if the input is not a recognized dimension.",
- },
- StringToItem =
- {
- Params =
- {
- {
- Name = "StringToParse",
- Type = "string",
- },
- {
- Name = "DestItem",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Parses the item specification in the given string and sets it into DestItem; returns true if successful",
- },
- StringToMobType =
- {
- Params =
- {
- {
- Name = "MobTypeString",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "MobType",
- Type = "Globals#MobType",
- },
- },
- Notes = "(DEPRECATED!) Please use cMonster:StringToMobType(). Converts a string representation to a {{Globals#MobType|MobType}} enumerated value",
- },
- StripColorCodes =
- {
- Params =
- {
- {
- Name = "Input",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Removes all control codes used by MC for colors and styles",
- },
- TrimString =
- {
- Params =
- {
- {
- Name = "Input",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Removes whitespace at both ends of the string",
- },
- },
- Constants =
- {
- BLOCK_FACE_BOTTOM =
- {
- Notes = "Please use BLOCK_FACE_YM instead. Interacting with the bottom face of the block.",
- },
- BLOCK_FACE_EAST =
- {
- Notes = "Please use BLOCK_FACE_XM instead. Interacting with the eastern face of the block.",
- },
- BLOCK_FACE_MAX =
- {
- Notes = "Used for range checking - highest legal value for an {{Globals#eBlockFace|eBlockFace}}",
- },
- BLOCK_FACE_MIN =
- {
- Notes = "Used for range checking - lowest legal value for an {{Globals#eBlockFace|eBlockFace}}",
- },
- BLOCK_FACE_NONE =
- {
- Notes = "Interacting with no block face - swinging the item in the air",
- },
- BLOCK_FACE_NORTH =
- {
- Notes = "Please use BLOCK_FACE_ZM instead. Interacting with the northern face of the block.",
- },
- BLOCK_FACE_SOUTH =
- {
- Notes = "Please use BLOCK_FACE_ZP instead. Interacting with the southern face of the block.",
- },
- BLOCK_FACE_TOP =
- {
- Notes = "Please use BLOCK_FACE_YP instead. Interacting with the top face of the block.",
- },
- BLOCK_FACE_WEST =
- {
- Notes = "Please use BLOCK_FACE_XP instead. Interacting with the western face of the block.",
- },
- BLOCK_FACE_XM =
- {
- Notes = "Interacting with the X- face of the block",
- },
- BLOCK_FACE_XP =
- {
- Notes = "Interacting with the X+ face of the block",
- },
- BLOCK_FACE_YM =
- {
- Notes = "Interacting with the Y- face of the block",
- },
- BLOCK_FACE_YP =
- {
- Notes = "Interacting with the Y+ face of the block",
- },
- BLOCK_FACE_ZM =
- {
- Notes = "Interacting with the Z- face of the block",
- },
- BLOCK_FACE_ZP =
- {
- Notes = "Interacting with the Z+ face of the block",
- },
- DIG_STATUS_CANCELLED =
- {
- Notes = "The player has let go of the mine block key before finishing mining the block",
- },
- DIG_STATUS_DROP_HELD =
- {
- Notes = "The player has dropped a single item using the Drop Item key (default: Q)",
- },
- DIG_STATUS_DROP_STACK =
- {
- Notes = "The player has dropped a full stack of items using the Drop Item key (default: Q) while holding down a specific modifier key (in windows, control)",
- },
- DIG_STATUS_FINISHED =
- {
- Notes = "The player thinks that it has finished mining a block",
- },
- DIG_STATUS_SHOOT_EAT =
- {
- Notes = "The player has finished shooting a bow or finished eating",
- },
- DIG_STATUS_STARTED =
- {
- Notes = "The player has started digging",
- },
- DIG_STATUS_SWAP_ITEM_IN_HAND =
- {
- Notes = "The player has swapped their held item with the item in their offhand slot (1.9)",
- },
- E_META_DROPSPENSER_ACTIVATED =
- {
- Notes = "A flag in the metadata of droppers and dispensers that indicates that the dropper or dispenser is currently activated. If this flag is set, the block must be unpowered first and powered again to shoot the next item.",
- },
- E_META_DROPSPENSER_FACING_MASK =
- {
- Notes = "A mask that indicates the bits of the metadata that specify the facing of droppers and dispensers.",
- },
- E_META_DROPSPENSER_FACING_XM =
- {
- Notes = "A flag in the metadata of droppers and dispensers that indicates that the dropper or dispenser is looking in the negative X direction.",
- },
- E_META_DROPSPENSER_FACING_XP =
- {
- Notes = "A flag in the metadata of droppers and dispensers that indicates that the dropper or dispenser is looking in the positive X direction.",
- },
- E_META_DROPSPENSER_FACING_YM =
- {
- Notes = "A flag in the metadata of droppers and dispensers that indicates that the dropper or dispenser is looking in the negative Y direction.",
- },
- E_META_DROPSPENSER_FACING_YP =
- {
- Notes = "A flag in the metadata of droppers and dispensers that indicates that the dropper or dispenser is looking in the positive Y direction.",
- },
- E_META_DROPSPENSER_FACING_ZM =
- {
- Notes = "A flag in the metadata of droppers and dispensers that indicates that the dropper or dispenser is looking in the negative Z direction.",
- },
- E_META_DROPSPENSER_FACING_ZP =
- {
- Notes = "A flag in the metadata of droppers and dispensers that indicates that the dropper or dispenser is looking in the positive Z direction.",
- },
- esBed =
- {
- Notes = "A bed explosion. The SourceData param is the {{Vector3i|position}} of the bed.",
- },
- esEnderCrystal =
- {
- Notes = "An ender crystal entity explosion. The SourceData param is the {{cEntity|ender crystal entity}} object.",
- },
- esGhastFireball =
- {
- Notes = "A ghast fireball explosion. The SourceData param is the {{cGhastFireballEntity|ghast fireball entity}} object.",
- },
- esMonster =
- {
- Notes = "A monster explosion (creeper). The SourceData param is the {{cMonster|monster entity}} object.",
- },
- esOther =
- {
- Notes = "Any other explosion. The SourceData param is unused.",
- },
- esPlugin =
- {
- Notes = "An explosion started by a plugin, without any further information. The SourceData param is unused. ",
- },
- esPrimedTNT =
- {
- Notes = "A TNT explosion. The SourceData param is the {{cTNTEntity|TNT entity}} object.",
- },
- esWitherBirth =
- {
- Notes = "An explosion at a wither's birth. The SourceData param is the {{cMonster|wither entity}} object.",
- },
- esWitherSkull =
- {
- Notes = "A wither skull explosion. The SourceData param is the {{cWitherSkullEntity|wither skull entity}} object.",
- },
- mtCustom =
- {
- Notes = "Send raw data without any processing",
- },
- mtDeath =
- {
- Notes = "Denotes death of player",
- },
- mtError =
- {
- Notes = "Something could not be done (i.e. command not executed due to insufficient privilege)",
- },
- mtFail =
- {
- Notes = "Something could not be done (i.e. command not executed due to insufficient privilege)",
- },
- mtFailure =
- {
- Notes = "Something could not be done (i.e. command not executed due to insufficient privilege)",
- },
- mtFatal =
- {
- Notes = "Something catastrophic occured (i.e. plugin crash)",
- },
- mtInfo =
- {
- Notes = "Informational message (i.e. command usage)",
- },
- mtInformation =
- {
- Notes = "Informational message (i.e. command usage)",
- },
- mtJoin =
- {
- Notes = "A player has joined the server",
- },
- mtLeave =
- {
- Notes = "A player has left the server",
- },
- mtMaxPlusOne =
- {
- Notes = "The first invalid type, used for checking on LuaAPI boundaries",
- },
- mtPM =
- {
- Notes = "Player to player messaging identifier",
- },
- mtPrivateMessage =
- {
- Notes = "Player to player messaging identifier",
- },
- mtSuccess =
- {
- Notes = "Something executed successfully",
- },
- mtWarning =
- {
- Notes = "Something concerning (i.e. reload) is about to happen",
- },
- },
- ConstantGroups =
- {
- eBlockFace =
- {
- Include = "^BLOCK_FACE_.*",
- TextBefore = [[
- These constants are used to describe individual faces of the block. They are used when the
- client is interacting with a block in the {{OnPlayerBreakingBlock|HOOK_PLAYER_BREAKING_BLOCK}},
- {{OnPlayerBrokenBlock|HOOK_PLAYER_BROKEN_BLOCK}}, {{OnPlayerLeftClick|HOOK_PLAYER_LEFT_CLICK}},
- {{OnPlayerPlacedBlock|HOOK_PLAYER_PLACED_BLOCK}}, {{OnPlayerPlacingBlock|HOOK_PLAYER_PLACING_BLOCK}},
- {{OnPlayerRightClick|HOOK_PLAYER_RIGHT_CLICK}}, {{OnPlayerUsedBlock|HOOK_PLAYER_USED_BLOCK}},
- {{OnPlayerUsedItem|HOOK_PLAYER_USED_ITEM}}, {{OnPlayerUsingBlock|HOOK_PLAYER_USING_BLOCK}},
- and {{OnPlayerUsingItem|HOOK_PLAYER_USING_ITEM}} hooks, or when the {{cLineBlockTracer}} hits a
- block, etc.
- ]],
- },
- eBlockType =
- {
- Include = "^E_BLOCK_.*",
- TextBefore = [[
- These constants are used for block types. They correspond directly with MineCraft's data values
- for blocks.
- ]],
- },
- eClickAction =
- {
- Include = "^ca.*",
- TextBefore = [[
- These constants are used to signalize various interactions that the user can do with the
- {{cWindow|UI windows}}. The server translates the protocol events into these constants. Note
- that there is a global ClickActionToString() function that can translate these constants into
- their textual representation.
- ]],
- },
- eDamageType =
- {
- Include = "^dt.*",
- TextBefore = [[
- These constants are used for specifying the cause of damage to entities. They are used in the
- {{TakeDamageInfo}} structure, as well as in {{cEntity}}'s damage-related API functions.
- ]],
- },
- DigStatuses =
- {
- Include = "^DIG_STATUS_.*",
- TextBefore = [[
- These constants are used to describe digging statuses, but in reality cover several more cases.
- They are used with {{OnPlayerLeftClick|HOOK_PLAYER_LEFT_CLICK}}.
- ]],
- },
- eDimension =
- {
- Include = "^dim.*",
- TextBefore = [[
- These constants represent dimension of a world. In Cuberite, the dimension is only reflected in
- the world's overall tint - overworld gets sky-like colors and dark shades, the nether gets
- reddish haze and the end gets dark haze. World generator is not directly affected by the
- dimension, same as fluid simulators; those only default to the expected values if not set
- specifically otherwise in the world.ini file.
- ]],
- },
- eExplosionSource =
- {
- Include = "^es.*",
- TextBefore = [[
- These constants are used to differentiate the various sources of explosions. They are used in
- the {{OnExploded|HOOK_EXPLODED}} hook, {{OnExploding|HOOK_EXPLODING}} hook and in the
- {{cWorld}}:DoExplosionAt() function. These constants also dictate the type of the additional
- data provided with the explosions, such as the exploding creeper {{cEntity|entity}} or the
- {{Vector3i|coords}} of the exploding bed.
- ]],
- },
- eGameMode =
- {
- Include =
- {
- "^gm.*",
- "^eGameMode_.*",
- },
- TextBefore = [[
- The following constants are used for the gamemode - survival, creative or adventure. Use the
- gmXXX constants, the eGameMode_ constants are deprecated and will be removed from the API.
- ]],
- },
- EMCSBiome =
- {
- Include = "^bi.*",
- TextBefore = [[
- These constants represent the biomes that the server understands. Note that there is a global
- StringToBiome() function that can convert a string into one of these constants.
- ]],
- },
- eMessageType =
- {
- -- Need to be specified explicitly, because there's also eMonsterType using the same "mt" prefix
- Include =
- {
- "mtCustom",
- "mtDeath",
- "mtError",
- "mtFail",
- "mtFailure",
- "mtFatal",
- "mtInfo",
- "mtInformation",
- "mtJoin",
- "mtLeave",
- "mtMaxPlusOne",
- "mtPrivateMessage",
- "mtPM",
- "mtSuccess",
- "mtWarning",
- },
- TextBefore = [[
- These constants are used together with messaging functions and classes, they specify the type of
- message being sent. The server can be configured to modify the message text (add prefixes) based
- on the message's type.
- ]],
- },
- eMonsterType =
- {
- Include =
- {
- "mtInvalidType",
- "mtBat",
- "mtBlaze",
- "mtCaveSpider",
- "mtChicken",
- "mtCow",
- "mtCreeper",
- "mtEnderDragon",
- "mtEnderman",
- "mtGhast",
- "mtGiant",
- "mtGuardian",
- "mtHorse",
- "mtIronGolem",
- "mtMagmaCube",
- "mtMooshroom",
- "mtOcelot",
- "mtPig",
- "mtRabbit",
- "mtSheep",
- "mtSilverfish",
- "mtSkeleton",
- "mtSlime",
- "mtSnowGolem",
- "mtSpider",
- "mtSquid",
- "mtVillager",
- "mtWitch",
- "mtWither",
- "mtWolf",
- "mtZombie",
- "mtZombiePigman",
- "mtMax",
- },
- TextBefore = [[
- The following constants are used for distinguishing between the individual mob types:
- ]],
- },
- eShrapnelLevel =
- {
- Include = "^sl.*",
- TextBefore = [[
- The following constants define the block types that are propelled outwards after an explosion.
- ]],
- },
- eSpreadSource =
- {
- Include = "^ss.*",
- TextBefore = [[
- These constants are used to differentiate the various sources of spreads, such as grass growing.
- They are used in the {{OnBlockSpread|HOOK_BLOCK_SPREAD}} hook.
- ]],
- },
- eWeather =
- {
- Include =
- {
- "^eWeather_.*",
- "wSunny",
- "wRain",
- "wStorm",
- "wThunderstorm",
- },
- TextBefore = [[
- These constants represent the weather in the world. Note that unlike vanilla, Cuberite allows
- different weathers even in non-overworld {{Globals#eDimension|dimensions}}.
- ]],
- },
- ItemTypes =
- {
- Include = "^E_ITEM_.*",
- TextBefore = [[
- These constants are used for item types. They correspond directly with MineCraft's data values
- for items.
- ]],
- },
- MetaValues =
- {
- Include = "^E_META_.*",
- },
- },
- },
- ItemCategory =
- {
- Desc = [[
- This class contains static functions for determining item categories. All of the functions are
- called directly on the class table, unlike most other object, which require an instance first.
- ]],
- Functions =
- {
- IsArmor =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is any kind of an armor.",
- },
- IsAxe =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is any kind of an axe.",
- },
- IsBoots =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is any kind of boots.",
- },
- IsChestPlate =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is any kind of a chestplate.",
- },
- IsHelmet =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is any kind of a helmet.",
- },
- IsHoe =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is any kind of a hoe.",
- },
- IsLeggings =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is any kind of a leggings.",
- },
- IsMinecart =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is any kind of a minecart.",
- },
- IsPickaxe =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is any kind of a pickaxe.",
- },
- IsShovel =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is any kind of a shovel.",
- },
- IsSword =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is any kind of a sword.",
- },
- IsTool =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item type is any kind of a tool (axe, hoe, pickaxe, shovel or FIXME: sword)",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Code example",
- Contents = [[
- The following code snippet checks if the player holds a shovel.
-
--- a_Player is a {{cPlayer}} object, possibly received as a hook param
-local HeldItem = a_Player:GetEquippedItem()
-if (ItemCategory.IsShovel(HeldItem.m_ItemType)) then
- -- It's a shovel
-end
-
- ]],
- },
- },
- },
- lxp =
- {
- Desc = [[
- This class provides an interface to the XML parser,
- {{http://matthewwild.co.uk/projects/luaexpat/|LuaExpat}}. It provides a SAX interface with an
- incremental XML parser.
-
- With an event-based API like SAX the XML document can be fed to the parser in chunks, and the
- parsing begins as soon as the parser receives the first document chunk. LuaExpat reports parsing
- events (such as the start and end of elements) directly to the application through callbacks. The
- parsing of huge documents can benefit from this piecemeal operation.
-
- See the online
- {{http://matthewwild.co.uk/projects/luaexpat/manual.html#parser|LuaExpat documentation}} for details
- on how to work with this parser. The code examples below should provide some basic help, too.
- ]],
- Functions =
- {
- new =
- {
- Params =
- {
- {
- Name = "CallbacksTable",
- Type = "table",
- },
- {
- Name = "SeparatorChar",
- Type = "string",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "XMLParser object",
- Type = "table",
- },
- },
- Notes = "Creates a new XML parser object, with the specified callbacks table and optional separator character.",
- },
- },
- Constants =
- {
- _COPYRIGHT =
- {
- Notes = "",
- },
- _DESCRIPTION =
- {
- Notes = "",
- },
- _VERSION =
- {
- Notes = "",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Parser callbacks",
- Contents = [[
- The callbacks table passed to the new() function specifies the Lua functions that the parser
- calls upon various events. The following table lists the most common functions used, for a
- complete list see the online
- {{http://matthewwild.co.uk/projects/luaexpat/manual.html#parser|LuaExpat documentation}}.
-
-
Function name
Parameters
Notes
-
CharacterData
Parser, string
Called when the parser recognizes a raw string inside the element
-
EndElement
Parser, ElementName
Called when the parser detects the ending of an XML element
-
StartElement
Parser, ElementName, AttributesTable
Called when the parser detects the start of an XML element. The AttributesTable is a Lua table containing all the element's attributes, both in the array section (in the order received) and in the dictionary section.
-
- ]],
- },
- {
- Header = "XMLParser object",
- Contents = [[
- The XMLParser object returned by lxp.new provides the functions needed to parse the XML. The
- following list provides the most commonly used ones, for a complete list see the online
- {{http://matthewwild.co.uk/projects/luaexpat/manual.html#parser|LuaExpat documentation}}.
-
-
close() - closes the parser, freeing all memory used by it.
-
getCallbacks() - returns the callbacks table for this parser.
-
parse(string) - parses more document data. the string contains the next part (or possibly all) of the document. Returns non-nil for success or nil, msg, line, col, pos for error.
-
stop() - aborts parsing (can be called from within the parser callbacks).
-
- ]],
- },
- {
- Header = "Code example",
- Contents = [[
- The following code reads an entire XML file and outputs its logical structure into the console:
-
-local Depth = 0;
-
--- Define the callbacks:
-local Callbacks = {
- CharacterData = function(a_Parser, a_String)
- LOG(string.rep(" ", Depth) .. "* " .. a_String);
- end
-
- EndElement = function(a_Parser, a_ElementName)
- Depth = Depth - 1;
- LOG(string.rep(" ", Depth) .. "- " .. a_ElementName);
- end
-
- StartElement = function(a_Parser, a_ElementName, a_Attribs)
- LOG(string.rep(" ", Depth) .. "+ " .. a_ElementName);
- Depth = Depth + 1;
- end
-}
-
--- Create the parser:
-local Parser = lxp.new(Callbacks);
-
--- Parse the XML file:
-local f = io.open("file.xml", "rb");
-while (true) do
- local block = f:read(128 * 1024); -- Use a 128KiB buffer for reading
- if (block == nil) then
- -- End of file
- break;
- end
- Parser:parse(block);
-end
-
--- Signalize to the parser that no more data is coming
-Parser:parse();
-
--- Close the parser:
-Parser:close();
-
- ]],
- },
- },
- },
- sqlite3 =
- {
- Desc = [[
- ]],
- Functions =
- {
- complete =
- {
- IsStatic = true,
- IsGlobal = true, -- Emulate a global function without a self parameter - this is called with a dot convention
- Params =
- {
- {
- Name = "SQL",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the input string comprises one or more complete SQL statements.",
- },
- open =
- {
- IsStatic = true,
- IsGlobal = true, -- Emulate a global function without a self parameter - this is called with a dot convention
- Params =
- {
- {
- Name = "FileName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "DBClass",
- Type = "SQLite DB object",
- },
- },
- Notes = [[
- Opens (or creates if it does not exist) an SQLite database with name filename and returns its
- handle (the returned object should be used for all further method calls in connection
- with this specific database, see
- {{http://lua.sqlite.org/index.cgi/doc/tip/doc/lsqlite3.wiki#database_methods|Database methods}}).
- Example:
-
--- open the database:
-myDB = sqlite3.open('MyDatabaseFile.sqlite3')
-
--- do some database calls...
-
--- Close the database:
-myDB:close()
-
- ]],
- },
- open_memory =
- {
- IsStatic = true,
- IsGlobal = true, -- Emulate a global function without a self parameter - this is called with a dot convention
- Returns =
- {
- {
- Name = "DBClass",
- Type = "SQLite DB object",
- },
- },
- Notes = "Opens an SQLite database in memory and returns its handle. In case of an error, the function returns nil, an error code and an error message. (In-memory databases are volatile as they are never stored on disk.)",
- },
- version =
- {
- IsStatic = true,
- IsGlobal = true, -- Emulate a global function without a self parameter - this is called with a dot convention
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns a string with SQLite version information, in the form 'x.y[.z]'.",
- },
- },
- },
- TakeDamageInfo =
- {
- Desc = [[
- This class contains the amount of damage, and the entity that caused the damage. It is used in the
- {{OnTakeDamage|HOOK_TAKE_DAMAGE}} hook and in the {{cEntity}}'s TakeDamage() function.
- ]],
- Variables =
- {
- Attacker =
- {
- Type = "{{cEntity}}",
- Notes = "The entity who is attacking. Only valid if dtAttack.",
- },
- DamageType =
- {
- Type = "eDamageType",
- Notes = "Source of the damage. One of the dtXXX constants.",
- },
- FinalDamage =
- {
- Type = "number",
- Notes = "The final amount of damage that will be applied to the Receiver. It is the RawDamage minus any Receiver's armor-protection.",
- },
- Knockback =
- {
- Type = "{{Vector3d}}",
- Notes = "Vector specifying the amount and direction of knockback that will be applied to the Receiver ",
- },
- RawDamage =
- {
- Type = "number",
- Notes = "Amount of damage that the attack produces on the Receiver, including the Attacker's equipped weapon, but excluding the Receiver's armor.",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "",
- Contents = [[
- The TDI is passed as the second parameter in the HOOK_TAKE_DAMAGE hook, and can be used to
- modify the damage before it is applied to the receiver:
-
-function OnTakeDamage(Receiver, TDI)
- LOG("Damage: Raw ".. TDI.RawDamage .. ", Final:" .. TDI.FinalDamage);
-
- -- If the attacker is a spider, make it deal 999 points of damage (insta-death spiders):
- if ((TDI.Attacker ~= nil) and TDI.Attacker:IsA("cSpider")) then
- TDI.FinalDamage = 999;
- end
-end
-
- ]],
- },
- },
- },
- tolua =
- {
- Desc = [[
- This class represents the tolua bridge between the Lua API and Cuberite. It supports some low
- level operations and queries on the objects. See also the tolua++'s documentation at
- {{http://www.codenix.com/~tolua/tolua++.html#utilities}}. Normally you shouldn't use any of these
- functions except for type()
- ]],
- Functions =
- {
- cast =
- {
- Params =
- {
- {
- Name = "Object",
- Type = "any",
- },
- {
- Name = "TypeStr",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "Object",
- Type = "any",
- },
- },
- Notes = "Casts the object to the specified type. Note: This is a potentially unsafe operation and it could crash the server. There is normally no need to use this function at all, so don't use it unless you know exactly what you're doing.",
- },
- getpeer =
- {
- Notes = "",
- },
- inherit =
- {
- Notes = "",
- },
- releaseownership =
- {
- Notes = "",
- },
- setpeer =
- {
- Notes = "",
- },
- takeownership =
- {
- Notes = "",
- },
- type =
- {
- Params =
- {
- {
- Name = "Object",
- Type = "any",
- },
- },
- Returns =
- {
- {
- Name = "TypeStr",
- Type = "string",
- },
- },
- Notes = "Returns a string representing the type of the object. This works similar to Lua's built-in type() function, but recognizes the underlying C++ classes, too.",
- },
- },
- },
- },
- ExtraPages =
- {
- {
- FileName = "Writing-a-Cuberite-plugin.html",
- Title = "Writing a Cuberite plugin",
- },
- {
- FileName = "InfoFile.html",
- Title = "Using the Info.lua file",
- },
- {
- FileName = "SettingUpDecoda.html",
- Title = "Setting up the Decoda Lua IDE",
- },
- {
- FileName = "SettingUpZeroBrane.html",
- Title = "Setting up the ZeroBrane Studio Lua IDE",
- },
- {
- FileName = "UsingChunkStays.html",
- Title = "Using ChunkStays",
- },
- {
- FileName = "WebWorldThreads.html",
- Title = "Webserver vs World threads",
- },
- },
- IgnoreClasses =
- {
- "^coroutine$",
- "^g_TrackedPages$",
- "^debug$",
- "^io$",
- "^math$",
- "^package$",
- "^os$",
- "^string$",
- "^table$",
- "^g_Stats$",
- },
- IgnoreFunctions =
- {
- "Globals.assert",
- "%a+%.delete",
- "CreateAPITables",
- "DumpAPIHtml",
- "DumpAPITxt",
- "Initialize",
- "LinkifyString",
- "ListMissingPages",
- "ListUndocumentedObjects",
- "ListUnexportedObjects",
- "LoadAPIFiles",
- "Globals.collectgarbage",
- "ReadDescriptions",
- "ReadHooks",
- "WriteHtmlClass",
- "WriteHtmlHook",
- "WriteStats",
- "Globals.xpcall",
- "Globals.decoda_output",
- "sqlite3.__newindex",
- "%a+%.__%a+",
- "%a+%.%.collector",
- "%a+%.new",
- "%a+%.new_local",
- },
- IgnoreConstants =
- {
- "cChestEntity.__cBlockEntityWindowOwner__",
- "cDropSpenserEntity.__cBlockEntityWindowOwner__",
- "cFurnaceEntity.__cBlockEntityWindowOwner__",
- "cHopperEntity.__cBlockEntityWindowOwner__",
- "cLuaWindow.__cItemGrid__cListener__",
- "Globals._CuberiteInternal_.*",
- "Globals.esMax",
- },
- IgnoreVariables =
- {
- "__.*__",
- },
-}
diff --git a/world/Plugins/APIDump/Classes/BlockEntities.lua b/world/Plugins/APIDump/Classes/BlockEntities.lua
deleted file mode 100644
index 3f3552c9..00000000
--- a/world/Plugins/APIDump/Classes/BlockEntities.lua
+++ /dev/null
@@ -1,1445 +0,0 @@
-return
-{
- cBeaconEntity =
- {
- Desc = [[
- A beacon entity is a {{cBlockEntityWithItems}} descendant that represents a beacon
- in the world.
- ]],
- Functions =
- {
- CalculatePyramidLevel =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Calculate the amount of layers the pyramid below the beacon has.",
- },
- GetBeaconLevel =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the beacon level. (0 - 4)",
- },
- GetPrimaryEffect =
- {
- Returns =
- {
- {
- Name = "EffectType",
- Type = "cEntityEffect#eType",
- },
- },
- Notes = "Returns the primary effect.",
- },
- GetSecondaryEffect =
- {
- Returns =
- {
- {
- Name = "EffectType",
- Type = "cEntityEffect#eType",
- },
- },
- Notes = "Returns the secondary effect.",
- },
- GiveEffects =
- {
- Notes = "Give the near-players the effects.",
- },
- IsActive =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Is the beacon active?",
- },
- IsBeaconBlocked =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Is the beacon blocked by non-transparent blocks that are higher than the beacon?",
- },
- IsMineralBlock =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the block is a diamond block, a golden block, an iron block or an emerald block.",
- },
- IsValidEffect =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "EffectType",
- Type = "cEntityEffect#eType",
- },
- {
- Name = "BeaconLevel",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the effect can be used.",
- },
- SetPrimaryEffect =
- {
- Params =
- {
- {
- Name = "EffectType",
- Type = "cEntityEffect#eType",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Select the primary effect. Returns false when the effect is invalid.",
- },
- SetSecondaryEffect =
- {
- Params =
- {
- {
- Name = "EffectType",
- Type = "cEntityEffect#eType",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Select the secondary effect. Returns false when the effect is invalid.",
- },
- UpdateBeacon =
- {
- Notes = "Update the beacon.",
- },
- },
- Inherits = "cBlockEntityWithItems",
- },
- cBlockEntity =
- {
- Desc = [[
- Block entities are simply blocks in the world that have persistent data, such as the text for a sign
- or contents of a chest. All block entities are also saved in the chunk data of the chunk they reside in.
- The cBlockEntity class acts as a common ancestor for all the individual block entities.
- ]],
- Functions =
- {
- GetBlockType =
- {
- Returns =
- {
- {
- Name = "BLOCKTYPE",
- Type = "number",
- },
- },
- Notes = "Returns the blocktype which is represented by this blockentity. This is the primary means of type-identification",
- },
- GetChunkX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the chunk X-coord of the block entity's chunk",
- },
- GetChunkZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the chunk Z-coord of the block entity's chunk",
- },
- GetPos =
- {
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns the name of the parent class, or empty string if no parent class.",
- },
- GetPosX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the block X-coord of the block entity's block",
- },
- GetPosY =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the block Y-coord of the block entity's block",
- },
- GetPosZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the block Z-coord of the block entity's block",
- },
- GetRelX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the relative X coord of the block entity's block within the chunk",
- },
- GetRelZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the relative Z coord of the block entity's block within the chunk",
- },
- GetWorld =
- {
- Returns =
- {
- {
- Type = "cWorld",
- },
- },
- Notes = "Returns the world to which the block entity belongs",
- },
- },
- },
- cBlockEntityWithItems =
- {
- Desc = [[
- This class is a common ancestor for all {{cBlockEntity|block entities}} that provide item storage.
- Internally, the object has a {{cItemGrid|cItemGrid}} object for storing the items; this ItemGrid is
- accessible through the API. The storage is a grid of items, items in it can be addressed either by a slot
- number, or by XY coords within the grid. If a UI window is opened for this block entity, the item storage
- is monitored for changes and the changes are immediately sent to clients of the UI window.
- ]],
- Functions =
- {
- GetContents =
- {
- Returns =
- {
- {
- Type = "cItemGrid",
- },
- },
- Notes = "Returns the cItemGrid object representing the items stored within this block entity",
- },
- GetSlot =
- {
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the cItem for the specified slot number. Returns nil for invalid slot numbers",
- },
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the cItem for the specified slot coords. Returns nil for invalid slot coords",
- },
- },
- SetSlot =
- {
- {
- Params =
- {
- {
- Name = "SlotNum",
- Type = "number",
- },
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the cItem for the specified slot number. Ignored if invalid slot number",
- },
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "cItem",
- Type = "cItem",
- },
- },
- Notes = "Sets the cItem for the specified slot coords. Ignored if invalid slot coords",
- },
- },
- },
- Inherits = "cBlockEntity",
- },
- cBrewingstandEntity =
- {
- Desc = [[
- This class represents a brewingstand entity in the world.
-
- See also the {{cRoot}}:GetBrewingRecipe() function.
- ]],
- Functions =
- {
- GetBrewingTimeLeft =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the time until the current items finishes brewing, in ticks",
- },
- GetIndgredientSlot =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the ingredient slot",
- },
- GetLeftBottleSlot =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the left bottle slot",
- },
- GetMiddleBottleSlot =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the middle bottle slot",
- },
- GetResultItem =
- {
- Params =
- {
- {
- Name = "SlotNumber",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the expected result item for the given slot number.",
- },
- GetRightBottleSlot =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the right bottle slot",
- },
- GetTimeBrewed =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the time that the current items has been brewing, in ticks",
- },
- SetIngredientSlot =
- {
- Params =
- {
- {
- Name = "Ingredient",
- Type = "cItem",
- },
- },
- Notes = "Sets the item in the ingredient bottle slot",
- },
- SetLeftBottleSlot =
- {
- Params =
- {
- {
- Name = "LeftSlot",
- Type = "cItem",
- },
- },
- Notes = "Sets the item in the left bottle slot",
- },
- SetMiddleBottleSlot =
- {
- Params =
- {
- {
- Name = "MiddleSlot",
- Type = "cItem",
- },
- },
- Notes = "Sets the item in the middle bottle slot",
- },
- SetRightBottleSlot =
- {
- Params =
- {
- {
- Name = "RightSlot",
- Type = "cItem",
- },
- },
- Notes = "Sets the item in the right bottle slot",
- },
- },
- Constants =
- {
- bsIngredient =
- {
- Notes = "Index of the ingredient slot",
- },
- bsLeftBottle =
- {
- Notes = "Index of the left bottle slot",
- },
- bsMiddleBottle =
- {
- Notes = "Index of the middle bottle slot",
- },
- bsRightBottle =
- {
- Notes = "Index of the right bottle slot",
- },
- ContentsHeight =
- {
- Notes = "Height (Y) of the {{cItemGrid|cItemGrid}} representing the contents",
- },
- ContentsWidth =
- {
- Notes = "Width (X) of the {{cItemGrid|cItemGrid}} representing the contents",
- },
- },
- ConstantGroups =
- {
- SlotIndices =
- {
- Include = "bs.*",
- TextBefore = "When using the GetSlot() or SetSlot() function, use these constants for slot index:",
- },
- },
- Inherits = "cBlockEntityWithItems",
- },
- cChestEntity =
- {
- Desc = [[
- A chest entity is a {{cBlockEntityWithItems|cBlockEntityWithItems}} descendant that represents a chest
- in the world. Note that doublechests consist of two separate cChestEntity objects, they do not collaborate
- in any way.
-
- To manipulate a chest already in the game, you need to use {{cWorld}}'s callback mechanism with
- either DoWithChestAt() or ForEachChestInChunk() function. See the code example below
- ]],
- Constants =
- {
- ContentsHeight =
- {
- Notes = "Height of the contents' {{cItemGrid|ItemGrid}}, as required by the parent class, {{cBlockEntityWithItems}}",
- },
- ContentsWidth =
- {
- Notes = "Width of the contents' {{cItemGrid|ItemGrid}}, as required by the parent class, {{cBlockEntityWithItems}}",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Code example",
- Contents = [[
- The following example code sets the top-left item of each chest in the same chunk as Player to
- 64 * diamond:
-
--- Player is a {{cPlayer}} object instance
-local World = Player:GetWorld();
-World:ForEachChestInChunk(Player:GetChunkX(), Player:GetChunkZ(),
- function (ChestEntity)
- ChestEntity:SetSlot(0, 0, cItem(E_ITEM_DIAMOND, 64));
- end
-);
-
- ]],
- },
- },
- Inherits = "cBlockEntityWithItems",
- },
- cCommandBlockEntity =
- {
- Functions =
- {
- Activate =
- {
- Notes = "Sets the command block to execute a command in the next tick",
- },
- GetCommand =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Retrieves stored command",
- },
- GetLastOutput =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Retrieves the last line of output generated by the command block",
- },
- GetResult =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Retrieves the result (signal strength) of the last operation",
- },
- SetCommand =
- {
- Params =
- {
- {
- Name = "Command",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Sets the command",
- },
- },
- Inherits = "cBlockEntity",
- },
- cDispenserEntity =
- {
- Desc = [[
- This class represents a dispenser block entity in the world. Most of this block entity's
- functionality is implemented in the {{cDropSpenserEntity}} class that represents
- the behavior common with the {{cDropperEntity|dropper}} block entity.
- ]],
- Functions =
- {
- GetShootVector =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns a unit vector in the cardinal direction of where the dispenser with the specified meta would be facing.",
- },
- SpawnProjectileFromDispenser =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "Kind",
- Type = "cProjectileEntity#eKind",
- },
- {
- Name = "Speed",
- Type = "Vector3d",
- },
- {
- Name = "Item",
- Type = "cItem",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Spawns a projectile of the given kind in front of the dispenser with the specified speed. Returns the UniqueID of the spawned projectile, or {{cEntity#INVALID_ID|cEntity.INVALID_ID}} on failure.",
- },
- },
- Inherits = "cDropSpenserEntity",
- },
- cDropperEntity =
- {
- Desc = [[
- This class represents a dropper block entity in the world. Most of this block entity's functionality
- is implemented in the {{cDropSpenserEntity|cDropSpenserEntity}} class that represents the behavior
- common with the {{cDispenserEntity|dispenser}} entity.
-
- An object of this class can be created from scratch when generating chunks ({{OnChunkGenerated|OnChunkGenerated}} and {{OnChunkGenerating|OnChunkGenerating}} hooks).
- ]],
- Inherits = "cDropSpenserEntity",
- },
- cDropSpenserEntity =
- {
- Desc = [[
- This is a class that implements behavior common to both {{cDispenserEntity|dispensers}} and {{cDropperEntity|droppers}}.
- ]],
- Functions =
- {
- Activate =
- {
- Notes = "Sets the block entity to dropspense an item in the next tick",
- },
- AddDropSpenserDir =
- {
- Params =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Notes = "Adjusts the block coords to where the dropspenser items materialize",
- },
- SetRedstonePower =
- {
- Params =
- {
- {
- Name = "IsPowered",
- Type = "boolean",
- },
- },
- Notes = "Sets the redstone status of the dropspenser. If the redstone power goes from off to on, the dropspenser will be activated",
- },
- },
- Constants =
- {
- ContentsHeight =
- {
- Notes = "Height (Y) of the {{cItemGrid}} representing the contents",
- },
- ContentsWidth =
- {
- Notes = "Width (X) of the {{cItemGrid}} representing the contents",
- },
- },
- Inherits = "cBlockEntityWithItems",
- },
- cFlowerPotEntity =
- {
- Desc = [[
- This class represents a flower pot entity in the world.
- ]],
- Functions =
- {
- GetItem =
- {
- Returns =
- {
- {
- Name = "Item",
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the flower pot.",
- },
- IsItemInPot =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Is a flower in the pot?",
- },
- SetItem =
- {
- Params =
- {
- {
- Name = "Item",
- Type = "cItem",
- },
- },
- Notes = "Set the item in the flower pot",
- },
- },
- Inherits = "cBlockEntity",
- },
- cFurnaceEntity =
- {
- Desc = [[
- This class represents a furnace block entity in the world.
-
- See also {{cRoot}}'s GetFurnaceRecipe() and GetFurnaceFuelBurnTime() functions
- ]],
- Functions =
- {
- GetCookTimeLeft =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the time until the current item finishes cooking, in ticks",
- },
- GetFuelBurnTimeLeft =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the time until the current fuel is depleted, in ticks",
- },
- GetFuelSlot =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the fuel slot",
- },
- GetInputSlot =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the input slot",
- },
- GetOutputSlot =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item in the output slot",
- },
- GetTimeCooked =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the time that the current item has been cooking, in ticks",
- },
- HasFuelTimeLeft =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if there's time before the current fuel is depleted",
- },
- SetFuelSlot =
- {
- Params =
- {
- {
- Name = "Fuel",
- Type = "cItem",
- },
- },
- Notes = "Sets the item in the fuel slot",
- },
- SetInputSlot =
- {
- Params =
- {
- {
- Name = "Input",
- Type = "cItem",
- },
- },
- Notes = "Sets the item in the input slot",
- },
- SetOutputSlot =
- {
- Params =
- {
- {
- Name = "Output",
- Type = "cItem",
- },
- },
- Notes = "Sets the item in the output slot",
- },
- },
- Constants =
- {
- ContentsHeight =
- {
- Notes = "Height (Y) of the {{cItemGrid|cItemGrid}} representing the contents",
- },
- ContentsWidth =
- {
- Notes = "Width (X) of the {{cItemGrid|cItemGrid}} representing the contents",
- },
- fsFuel =
- {
- Notes = "Index of the fuel slot",
- },
- fsInput =
- {
- Notes = "Index of the input slot",
- },
- fsOutput =
- {
- Notes = "Index of the output slot",
- },
- },
- ConstantGroups =
- {
- SlotIndices =
- {
- Include = "fs.*",
- TextBefore = "When using the GetSlot() or SetSlot() function, use these constants for slot index:",
- },
- },
- Inherits = "cBlockEntityWithItems",
- },
- cHopperEntity =
- {
- Desc = [[
- This class represents a hopper block entity in the world.
- ]],
- Functions =
- {
- GetOutputBlockPos =
- {
- Params =
- {
- {
- Name = "BlockMeta",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Name = "IsAttached",
- Type = "boolean",
- },
- {
- Name = "BlockX",
- Type = "number",
- },
- {
- Name = "BlockY",
- Type = "number",
- },
- {
- Name = "BlockZ",
- Type = "number",
- },
- },
- Notes = "Returns whether the hopper is attached, and if so, the block coords of the block receiving the output items, based on the given meta.",
- },
- },
- Constants =
- {
- ContentsHeight =
- {
- Notes = "Height (Y) of the internal {{cItemGrid}} representing the hopper contents.",
- },
- ContentsWidth =
- {
- Notes = "Width (X) of the internal {{cItemGrid}} representing the hopper contents.",
- },
- TICKS_PER_TRANSFER =
- {
- Notes = "Number of ticks between when the hopper transfers items.",
- },
- },
- Inherits = "cBlockEntityWithItems",
- },
- cJukeboxEntity =
- {
- Desc = [[
- This class represents a jukebox in the world. It can play the records, either when the
- {{cPlayer|player}} uses the record on the jukebox, or when a plugin instructs it to play.
- ]],
- Functions =
- {
- EjectRecord =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Ejects the current record as a {{cPickup|pickup}}. No action if there's no current record. To remove record without generating the pickup, use SetRecord(0). Returns true if pickup ejected.",
- },
- GetRecord =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the record currently present. Zero for no record, E_ITEM_*_DISC for records.",
- },
- IsPlayingRecord =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the jukebox is playing a record.",
- },
- IsRecordItem =
- {
- Params =
- {
- {
- Name = "ItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified item is a record that can be played.",
- },
- PlayRecord =
- {
- Params =
- {
- {
- Name = "RecordItemType",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Plays the specified Record. Return false if the parameter isn't a playable Record (E_ITEM_XXX_DISC). If there is a record already playing, ejects it first.",
- },
- SetRecord =
- {
- Params =
- {
- {
- Name = "RecordItemType",
- Type = "number",
- },
- },
- Notes = "Sets the currently present record. Use zero for no record, or E_ITEM_*_DISC for records.",
- },
- },
- Inherits = "cBlockEntity",
- },
- cMobHeadEntity =
- {
- Desc = [[
- This class represents a mob head block entity in the world.
- ]],
- Functions =
- {
- GetOwnerName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the player name of the mob head",
- },
- GetOwnerTexture =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the player texture of the mob head",
- },
- GetOwnerTextureSignature =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the signature of the player texture of the mob head",
- },
- GetOwnerUUID =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the player UUID of the mob head",
- },
- GetRotation =
- {
- Returns =
- {
- {
- Type = "eMobHeadRotation",
- },
- },
- Notes = "Returns the rotation of the mob head",
- },
- GetType =
- {
- Returns =
- {
- {
- Type = "eMobHeadType",
- },
- },
- Notes = "Returns the type of the mob head",
- },
- SetOwner =
- {
- {
- Params =
- {
- {
- Name = "cPlayer",
- Type = "cPlayer",
- },
- },
- Notes = "Set the {{cPlayer|player}} for mob heads with player type",
- },
- {
- Params =
- {
- {
- Name = "OwnerUUID",
- Type = "string",
- },
- {
- Name = "OwnerName",
- Type = "string",
- },
- {
- Name = "OwnerTexture",
- Type = "string",
- },
- {
- Name = "OwnerTextureSignature",
- Type = "string",
- },
- },
- Notes = "Sets the player components for the mob heads with player type",
- },
- },
- SetRotation =
- {
- Params =
- {
- {
- Name = "Rotation",
- Type = "eMobHeadRotation",
- },
- },
- Notes = "Sets the rotation of the mob head.",
- },
- SetType =
- {
- Params =
- {
- {
- Name = "HeadType",
- Type = "eMobHeadType",
- },
- },
- Notes = "Set the type of the mob head",
- },
- },
- Inherits = "cBlockEntity",
- },
- cMobSpawnerEntity =
- {
- Desc = [[
- This class represents a mob spawner block entity in the world.
- ]],
- Functions =
- {
- GetEntity =
- {
- Returns =
- {
- {
- Name = "MobType",
- Type = "Globals#MobType",
- },
- },
- Notes = "Returns the entity type that will be spawn by this mob spawner.",
- },
- GetNearbyMonsterNum =
- {
- Params =
- {
- {
- Name = "MobType",
- Type = "eMonsterType",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the amount of this monster type in a 8-block radius (Y: 4-block radius).",
- },
- GetNearbyPlayersNum =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the amount of the nearby players in a 16-block radius.",
- },
- GetSpawnDelay =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the spawn delay. This is the tick delay that is needed to spawn new monsters.",
- },
- ResetTimer =
- {
- Notes = "Sets the spawn delay to a new random value.",
- },
- SetEntity =
- {
- Params =
- {
- {
- Name = "MobType",
- Type = "Globals#MobType",
- },
- },
- Notes = "Sets the type of the mob that will be spawned by this mob spawner.",
- },
- SetSpawnDelay =
- {
- Params =
- {
- {
- Name = "SpawnDelayTicks",
- Type = "number",
- },
- },
- Notes = "Sets the spawn delay.",
- },
- SpawnEntity =
- {
- Notes = "Spawns the entity. This function automaticly change the spawn delay!",
- },
- UpdateActiveState =
- {
- Notes = "Upate the active flag from the mob spawner. This function is called every 5 seconds from the Tick() function.",
- },
- },
- Inherits = "cBlockEntity",
- },
- cNoteEntity =
- {
- Desc = [[
- This class represents a note block entity in the world. It takes care of the note block's pitch,
- and also can play the sound, either when the {{cPlayer|player}} right-clicks it, redstone activates
- it, or upon a plugin's request.
-
- The pitch is stored as an integer between 0 and 24.
- ]],
- Functions =
- {
- GetPitch =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the current pitch set for the block",
- },
- IncrementPitch =
- {
- Notes = "Adds 1 to the current pitch. Wraps around to 0 when the pitch cannot go any higher.",
- },
- MakeSound =
- {
- Notes = "Plays the sound for all {{cClientHandle|clients}} near this block.",
- },
- SetPitch =
- {
- Params =
- {
- {
- Name = "Pitch",
- Type = "number",
- },
- },
- Notes = "Sets a new pitch for the block.",
- },
- },
- Inherits = "cBlockEntity",
- },
- cSignEntity =
- {
- Desc = [[
- A sign entity represents a sign in the world. This class is only used when generating chunks, so
- that the plugins may generate signs within new chunks. See the code example in {{cChunkDesc}}.
- ]],
- Functions =
- {
- GetLine =
- {
- Params =
- {
- {
- Name = "LineIndex",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the specified line. LineIndex is expected between 0 and 3. Returns empty string and logs to server console when LineIndex is invalid.",
- },
- SetLine =
- {
- Params =
- {
- {
- Name = "LineIndex",
- Type = "number",
- },
- {
- Name = "LineText",
- Type = "string",
- },
- },
- Notes = "Sets the specified line. LineIndex is expected between 0 and 3. Logs to server console when LineIndex is invalid.",
- },
- SetLines =
- {
- Params =
- {
- {
- Name = "Line1",
- Type = "string",
- },
- {
- Name = "Line2",
- Type = "string",
- },
- {
- Name = "Line3",
- Type = "string",
- },
- {
- Name = "Line4",
- Type = "string",
- },
- },
- Notes = "Sets all the sign's lines at once. Note that plugins should prefer to use {{cWorld}}:SetSignLines(), so that they can specify the player on whose behalf the sign is being set.",
- },
- },
- Inherits = "cBlockEntity",
- },
-}
diff --git a/world/Plugins/APIDump/Classes/Geometry.lua b/world/Plugins/APIDump/Classes/Geometry.lua
deleted file mode 100644
index fa0fe995..00000000
--- a/world/Plugins/APIDump/Classes/Geometry.lua
+++ /dev/null
@@ -1,2635 +0,0 @@
-
--- Geometry.lua
-
--- Defines the documentation for geometry-related classes:
--- cBoundingBox, cCuboid, cLineBlockTracer, cTracer, Vector3X
-
-
-
-
-return
-{
- cBoundingBox =
- {
- Desc = [[
- Represents two sets of coordinates, minimum and maximum for each direction; thus defining an
- axis-aligned cuboid with floating-point boundaries. It supports operations changing the size and
- position of the box, as well as querying whether a point or another BoundingBox is inside the box.
-
- All the points within the coordinate limits (inclusive the edges) are considered "inside" the box.
- However, for intersection purposes, if the intersection is "sharp" in any coord (min1 == max2, i. e.
- zero volume), the boxes are considered non-intersecting.
- ]],
- Functions =
- {
- CalcLineIntersection =
- {
- {
- Params =
- {
- {
- Name = "LineStart",
- Type = "Vector3d",
- },
- {
- Name = "LinePt2",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Name = "DoesIntersect",
- Type = "boolean",
- },
- {
- Name = "LineCoeff",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "Face",
- Type = "eBlockFace",
- IsOptional = true,
- },
- },
- Notes = "Calculates the intersection of a ray (half-line), given by two of its points, with the bounding box. Returns false if the line doesn't intersect the bounding box, or true, together with coefficient of the intersection (how much of the difference between the two ray points is needed to reach the intersection), and the face of the box which is intersected.",
- },
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "BoxMin",
- Type = "number",
- },
- {
- Name = "BoxMax",
- Type = "number",
- },
- {
- Name = "LineStart",
- Type = "Vector3d",
- },
- {
- Name = "LinePt2",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Name = "DoesIntersect",
- Type = "boolean",
- },
- {
- Name = "LineCoeff",
- Type = "number",
- IsOptional = true,
- },
- {
- Name = "Face",
- Type = "eBlockFace",
- IsOptional = true,
- },
- },
- Notes = "Calculates the intersection of a ray (half-line), given by two of its points, with the bounding box specified as its minimum and maximum coords. Returns false if the line doesn't intersect the bounding box, or true, together with coefficient of the intersection (how much of the difference between the two ray points is needed to reach the intersection), and the face of the box which is intersected.",
- },
- },
- constructor =
- {
- {
- Params =
- {
- {
- Name = "MinX",
- Type = "number",
- },
- {
- Name = "MaxX",
- Type = "number",
- },
- {
- Name = "MinY",
- Type = "number",
- },
- {
- Name = "MaxY",
- Type = "number",
- },
- {
- Name = "MinZ",
- Type = "number",
- },
- {
- Name = "MaxZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cBoundingBox",
- },
- },
- Notes = "Creates a new bounding box with the specified edges",
- },
- {
- Params =
- {
- {
- Name = "Min",
- Type = "number",
- },
- {
- Name = "Max",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cBoundingBox",
- },
- },
- Notes = "Creates a new bounding box with the coords specified as two vectors",
- },
- {
- Params =
- {
- {
- Name = "Pos",
- Type = "Vector3d",
- },
- {
- Name = "Radius",
- Type = "number",
- },
- {
- Name = "Height",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cBoundingBox",
- },
- },
- Notes = "Creates a new bounding box from the position given and radius (X/Z) and height. Radius is added from X/Z to calculate the maximum coords and subtracted from X/Z to get the minimum; minimum Y is set to Pos.y and maxumim Y to Pos.y plus Height. This corresponds with how {{cEntity|entities}} are represented in Minecraft.",
- },
- {
- Params =
- {
- {
- Name = "OtherBoundingBox",
- Type = "cBoundingBox",
- },
- },
- Returns =
- {
- {
- Type = "cBoundingBox",
- },
- },
- Notes = "Creates a new copy of the given bounding box. Same result can be achieved by using a simple assignment.",
- },
- {
- Params =
- {
- {
- Name = "Pos",
- Type = "Vector3d",
- },
- {
- Name = "CubeSideLength",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cBoundingBox",
- },
- },
- Notes = "Creates a new bounding box as a cube with the specified side length centered around the specified point.",
- },
- },
- DoesIntersect =
- {
- Params =
- {
- {
- Name = "OtherBoundingBox",
- Type = "cBoundingBox",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the two bounding boxes have an intersection of nonzero volume.",
- },
- Expand =
- {
- Params =
- {
- {
- Name = "ExpandX",
- Type = "number",
- },
- {
- Name = "ExpandY",
- Type = "number",
- },
- {
- Name = "ExpandZ",
- Type = "number",
- },
- },
- Notes = "Expands this bounding box by the specified amount in each direction (so the box becomes larger by 2 * Expand in each axis).",
- },
- GetMax =
- {
- Returns =
- {
- {
- Name = "Point",
- Type = "Vector3d",
- },
- },
- Notes = "Returns the boundary point with the maximum coords",
- },
- GetMaxX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the maximum X coord of the bounding box",
- },
- GetMaxY =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the maximum Y coord of the bounding box",
- },
- GetMaxZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the maximum Z coord of the bounding box",
- },
- GetMin =
- {
- Returns =
- {
- {
- Name = "Point",
- Type = "Vector3d",
- },
- },
- Notes = "Returns the boundary point with the minimum coords",
- },
- GetMinX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the minimum X coord of the bounding box",
- },
- GetMinY =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the minimum Y coord of the bounding box",
- },
- GetMinZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the minimum Z coord of the bounding box",
- },
- Intersect =
- {
- Params =
- {
- {
- Name = "OtherBbox",
- Type = "cBoundingBox",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- {
- Name = "Intersection",
- Type = "cBoundingBox",
- IsOptional = true,
- },
- },
- Notes = "Checks if the intersection between this bounding box and another one is non-empty. Returns false if the intersection is empty, true and a new cBoundingBox representing the intersection of the two boxes.",
- },
- IsInside =
- {
- {
- Params =
- {
- {
- Name = "Point",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified point is inside (including on the edge) of the box.",
- },
- {
- Params =
- {
- {
- Name = "PointX",
- Type = "number",
- },
- {
- Name = "PointY",
- Type = "number",
- },
- {
- Name = "PointZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified point is inside (including on the edge) of the box.",
- },
- {
- Params =
- {
- {
- Name = "OtherBoundingBox",
- Type = "cBoundingBox",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if OtherBoundingBox is inside of this box.",
- },
- {
- Params =
- {
- {
- Name = "OtherBoxMin",
- Type = "number",
- },
- {
- Name = "OtherBoxMax",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the other bounding box, specified by its 2 corners, is inside of this box.",
- },
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Min",
- Type = "number",
- },
- {
- Name = "Max",
- Type = "number",
- },
- {
- Name = "Point",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified point is inside the bounding box specified by its min / max corners",
- },
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Min",
- Type = "number",
- },
- {
- Name = "Max",
- Type = "number",
- },
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified point is inside the bounding box specified by its min / max corners",
- },
- },
- Move =
- {
- {
- Params =
- {
- {
- Name = "OffsetX",
- Type = "number",
- },
- {
- Name = "OffsetY",
- Type = "number",
- },
- {
- Name = "OffsetZ",
- Type = "number",
- },
- },
- Notes = "Moves the bounding box by the specified offset in each axis",
- },
- {
- Params =
- {
- {
- Name = "Offset",
- Type = "Vector3d",
- },
- },
- Notes = "Moves the bounding box by the specified offset in each axis",
- },
- },
- Union =
- {
- Params =
- {
- {
- Name = "OtherBoundingBox",
- Type = "cBoundingBox",
- },
- },
- Returns =
- {
- {
- Type = "cBoundingBox",
- },
- },
- Notes = "Returns the smallest bounding box that contains both OtherBoundingBox and this bounding box. Note that unlike the strict geometrical meaning of \"union\", this operation actually returns a cBoundingBox.",
- },
- },
- },
- cCuboid =
- {
- Desc = [[
- cCuboid offers some native support for integral-boundary cuboids. A cuboid internally consists of
- two {{Vector3i}}-s. By default the cuboid doesn't make any assumptions about the defining points,
- but for most of the operations in the cCuboid class, the p1 member variable is expected to be the
- minima and the p2 variable the maxima. The Sort() function guarantees this condition.
-
- The Cuboid considers both its edges inclusive.
- ]],
- Functions =
- {
- Assign =
- {
- {
- Params =
- {
- {
- Name = "SrcCuboid",
- Type = "cCuboid",
- },
- },
- Notes = "Copies all the coords from the src cuboid to this cuboid. Sort-state is ignored.",
- },
- {
- Params =
- {
- {
- Name = "X1",
- Type = "number",
- },
- {
- Name = "Y1",
- Type = "number",
- },
- {
- Name = "Z1",
- Type = "number",
- },
- {
- Name = "X2",
- Type = "number",
- },
- {
- Name = "Y2",
- Type = "number",
- },
- {
- Name = "Z2",
- Type = "number",
- },
- },
- Notes = "Assigns all the coords to the specified values. Sort-state is ignored.",
- },
- },
- ClampX =
- {
- Params =
- {
- {
- Name = "MinX",
- Type = "number",
- },
- {
- Name = "MaxX",
- Type = "number",
- },
- },
- Notes = "Clamps both X coords into the range provided. Sortedness-agnostic.",
- },
- ClampY =
- {
- Params =
- {
- {
- Name = "MinY",
- Type = "number",
- },
- {
- Name = "MaxY",
- Type = "number",
- },
- },
- Notes = "Clamps both Y coords into the range provided. Sortedness-agnostic.",
- },
- ClampZ =
- {
- Params =
- {
- {
- Name = "MinZ",
- Type = "number",
- },
- {
- Name = "MaxZ",
- Type = "number",
- },
- },
- Notes = "Clamps both Z coords into the range provided. Sortedness-agnostic.",
- },
- constructor =
- {
- {
- Returns =
- {
- {
- Type = "cCuboid",
- },
- },
- Notes = "Creates a new Cuboid object with all-zero coords",
- },
- {
- Params =
- {
- {
- Name = "OtherCuboid",
- Type = "cCuboid",
- },
- },
- Returns =
- {
- {
- Type = "cCuboid",
- },
- },
- Notes = "Creates a new Cuboid object as a copy of OtherCuboid",
- },
- {
- Params =
- {
- {
- Name = "Point1",
- Type = "Vector3i",
- },
- {
- Name = "Point2",
- Type = "Vector3i",
- },
- },
- Returns =
- {
- {
- Type = "cCuboid",
- },
- },
- Notes = "Creates a new Cuboid object with the specified points as its corners.",
- },
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cCuboid",
- },
- },
- Notes = "Creates a new Cuboid object with the specified point as both its corners (the cuboid has a size of 1 in each direction).",
- },
- {
- Params =
- {
- {
- Name = "X1",
- Type = "number",
- },
- {
- Name = "Y1",
- Type = "number",
- },
- {
- Name = "Z1",
- Type = "number",
- },
- {
- Name = "X2",
- Type = "number",
- },
- {
- Name = "Y2",
- Type = "number",
- },
- {
- Name = "Z2",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "cCuboid",
- },
- },
- Notes = "Creates a new Cuboid object with the specified points as its corners.",
- },
- },
- DifX =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the difference between the two X coords (X-size minus 1). Assumes sorted.",
- },
- DifY =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the difference between the two Y coords (Y-size minus 1). Assumes sorted.",
- },
- DifZ =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the difference between the two Z coords (Z-size minus 1). Assumes sorted.",
- },
- DoesIntersect =
- {
- Params =
- {
- {
- Name = "OtherCuboid",
- Type = "cCuboid",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if this cuboid has at least one voxel in common with OtherCuboid. Note that edges are considered inclusive. Assumes both sorted.",
- },
- Engulf =
- {
- Params =
- {
- {
- Name = "Point",
- Type = "Vector3i",
- },
- },
- Notes = "If needed, expands the cuboid to include the specified point. Doesn't shrink. Assumes sorted. ",
- },
- Expand =
- {
- Params =
- {
- {
- Name = "SubMinX",
- Type = "number",
- },
- {
- Name = "AddMaxX",
- Type = "number",
- },
- {
- Name = "SubMinY",
- Type = "number",
- },
- {
- Name = "AddMaxY",
- Type = "number",
- },
- {
- Name = "SubMinZ",
- Type = "number",
- },
- {
- Name = "AddMaxZ",
- Type = "number",
- },
- },
- Notes = "Expands the cuboid by the specified amount in each direction. Works on unsorted cuboids as well. NOTE: this function doesn't check for underflows.",
- },
- GetVolume =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the volume of the cuboid, in blocks. Note that the volume considers both coords inclusive. Works on unsorted cuboids, too.",
- },
- IsCompletelyInside =
- {
- Params =
- {
- {
- Name = "OuterCuboid",
- Type = "cCuboid",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if this cuboid is completely inside (in all directions) in OuterCuboid. Assumes both sorted.",
- },
- IsInside =
- {
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified point (integral coords) is inside this cuboid. Assumes sorted.",
- },
- {
- Params =
- {
- {
- Name = "Point",
- Type = "Vector3i",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified point (integral coords) is inside this cuboid. Assumes sorted.",
- },
- {
- Params =
- {
- {
- Name = "Point",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified point (floating-point coords) is inside this cuboid. Assumes sorted.",
- },
- },
- IsSorted =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if this cuboid is sorted",
- },
- Move =
- {
- Params =
- {
- {
- Name = "OffsetX",
- Type = "number",
- },
- {
- Name = "OffsetY",
- Type = "number",
- },
- {
- Name = "OffsetZ",
- Type = "number",
- },
- },
- Notes = "Adds the specified offsets to each respective coord, effectively moving the Cuboid. Sort-state is ignored and preserved.",
- },
- Sort =
- {
- Notes = "Sorts the internal representation so that p1 contains the lesser coords and p2 contains the greater coords.",
- },
- },
- Variables =
- {
- p1 =
- {
- Type = "{{Vector3i}}",
- Notes = "The first corner. Usually the lesser of the two coords in each set",
- },
- p2 =
- {
- Type = "{{Vector3i}}",
- Notes = "The second corner. Usually the larger of the two coords in each set",
- },
- },
- },
- cLineBlockTracer =
- {
- Desc = [[
-This class provides an easy-to-use interface for tracing lines through individual
-blocks in the world. It will call the provided callbacks according to what events it encounters along the
-way.
-
-For the Lua API, there's only one static function exported that takes all the parameters necessary to do
-the tracing. The Callbacks parameter is a table containing all the functions that will be called upon the
-various events. See below for further information.
- ]],
- Functions =
- {
- Trace =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "World",
- Type = "cWorld",
- },
- {
- Name = "Callbacks",
- Type = "table",
- },
- {
- Name = "StartX",
- Type = "number",
- },
- {
- Name = "StartY",
- Type = "number",
- },
- {
- Name = "StartZ",
- Type = "number",
- },
- {
- Name = "EndX",
- Type = "number",
- },
- {
- Name = "EndY",
- Type = "number",
- },
- {
- Name = "EndZ",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Performs the trace on the specified line. Returns true if the entire trace was processed (no callback returned true)",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Callbacks",
- Contents = [[
-The Callbacks in the Trace() function is a table that contains named functions. Cuberite will call
-individual functions from that table for the events that occur on the line - hitting a block, going out of
-valid world data etc. The following table lists all the available callbacks. If the callback function is
-not defined, Cuberite skips it. Each function can return a bool value, if it returns true, the tracing is
-aborted and Trace() returns false.
Called when the ray hits a new valid block. The block type and meta is given. EntryFace is one of the
- BLOCK_FACE_ constants indicating which "side" of the block got hit by the ray.
-
OnNextBlockNoData
BlockX, BlockY, BlockZ, EntryFace
-
Called when the ray hits a new block, but the block is in an unloaded chunk - no valid data is
- available. Only the coords and the entry face are given.
-
OnOutOfWorld
X, Y, Z
-
Called when the ray goes outside of the world (Y-wise); the coords specify the exact exit point. Note
- that for other paths than lines (considered for future implementations) the path may leave the world and
- go back in again later, in such a case this callback is followed by OnIntoWorld() and further
- OnNextBlock() calls.
-
OnIntoWorld
X, Y, Z
-
Called when the ray enters the world (Y-wise); the coords specify the exact entry point.
-
OnNoMoreHits
-
Called when the path is sure not to hit any more blocks. This is the final callback, no more
- callbacks are called after this function. Unlike the other callbacks, this function doesn't have a return
- value.
-
OnNoChunk
-
Called when the ray enters a chunk that is not loaded. This usually means that the tracing is aborted.
- Unlike the other callbacks, this function doesn't have a return value.
The following example is taken from the Debuggers plugin. It is a command handler function for the
-"/spidey" command that creates a line of cobweb blocks from the player's eyes up to 50 blocks away in
-the direction they're looking, but only through the air.
-
-function HandleSpideyCmd(a_Split, a_Player)
- local World = a_Player:GetWorld();
-
- local Callbacks = {
- OnNextBlock = function(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta)
- if (a_BlockType ~= E_BLOCK_AIR) then
- -- abort the trace
- return true;
- end
- World:SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_COBWEB, 0);
- end
- };
-
- local EyePos = a_Player:GetEyePosition();
- local LookVector = a_Player:GetLookVector();
- LookVector:Normalize(); -- Make the vector 1 m long
-
- -- Start cca 2 blocks away from the eyes
- local Start = EyePos + LookVector + LookVector;
- local End = EyePos + LookVector * 50;
-
- cLineBlockTracer.Trace(World, Callbacks, Start.x, Start.y, Start.z, End.x, End.y, End.z);
-
- return true;
-end
-
-
- ]],
- },
- },
- },
- cTracer =
- {
- Desc = [[
- A cTracer object is used to trace lines in the world. One thing you can use the cTracer for, is
- tracing what block a player is looking at, but you can do more with it if you want.
-
- The cTracer is still a work in progress and is not documented at all.
-
- See also the {{cLineBlockTracer}} class for an alternative approach using callbacks.
- ]],
- Functions =
- {
-
- },
- },
- Vector3d =
- {
- Desc = [[
- A Vector3d object uses double precision floating point values to describe a point in 3D space.
-
- See also {{Vector3f}} for single-precision floating point 3D coords and {{Vector3i}} for integer
- 3D coords.
- ]],
- Functions =
- {
- Abs =
- {
- Notes = "Updates each coord to its absolute value.",
- },
- abs =
- {
- Notes = "OBSOLETE, use Abs() instead.",
- },
- Clamp =
- {
- Params =
- {
- {
- Name = "min",
- Type = "number",
- },
- {
- Name = "max",
- Type = "number",
- },
- },
- Notes = "Clamps each coord into the specified range.",
- },
- clamp =
- {
- Params =
- {
- {
- Name = "min",
- Type = "number",
- },
- {
- Name = "max",
- Type = "number",
- },
- },
- Notes = "OBSOLETE, use Clamp() instead.",
- },
- constructor =
- {
- {
- Params =
- {
- {
- Name = "Vector",
- Type = "Vector3f",
- },
- },
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Creates a new Vector3d object by copying the coords from the given Vector3f.",
- },
- {
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Creates a new Vector3d object with all its coords set to 0.",
- },
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Creates a new Vector3d object with its coords set to the specified values.",
- },
- },
- Cross =
- {
- Params =
- {
- {
- Name = "Other",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns a new Vector3d that is a {{http://en.wikipedia.org/wiki/Cross_product|cross product}} of this vector and the specified vector.",
- },
- Dot =
- {
- Params =
- {
- {
- Name = "Other",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the dot product of this vector and the specified vector.",
- },
- Equals =
- {
- Params =
- {
- {
- Name = "AnotherVector",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if this vector is exactly equal to the specified vector. Note that this is subject to (possibly imprecise) floating point math.",
- },
- EqualsEps =
- {
- Params =
- {
- {
- Name = "AnotherVector",
- Type = "Vector3d",
- },
- {
- Name = "Eps",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the differences between each corresponding coords of this vector and the one specified are less than the specified Eps.",
- },
- Floor =
- {
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns a new {{Vector3i}} object with coords set to math.floor of this vector's coords.",
- },
- HasNonZeroLength =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the vector has at least one coord non-zero. Note that this is subject to (possibly imprecise) floating point math.",
- },
- Length =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the (euclidean) length of the vector.",
- },
- LineCoeffToXYPlane =
- {
- Params =
- {
- {
- Name = "Vector3d",
- Type = "Vector3d",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the coefficient for the line from the specified vector through this vector to reach the specified Z coord. The result satisfies the following equation: (this + Result * (Param - this)).z = Z. Returns the NO_INTERSECTION constant if there's no intersection.",
- },
- LineCoeffToXZPlane =
- {
- Params =
- {
- {
- Name = "Vector3d",
- Type = "Vector3d",
- },
- {
- Name = "Y",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the coefficient for the line from the specified vector through this vector to reach the specified Y coord. The result satisfies the following equation: (this + Result * (Param - this)).y = Y. Returns the NO_INTERSECTION constant if there's no intersection.",
- },
- LineCoeffToYZPlane =
- {
- Params =
- {
- {
- Name = "Vector3d",
- Type = "Vector3d",
- },
- {
- Name = "X",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the coefficient for the line from the specified vector through this vector to reach the specified X coord. The result satisfies the following equation: (this + Result * (Param - this)).x = X. Returns the NO_INTERSECTION constant if there's no intersection.",
- },
- Move =
- {
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Notes = "Adds the specified offsets to each coord, effectively moving the vector by the specified coord offsets.",
- },
- {
- Params =
- {
- {
- Name = "Diff",
- Type = "Vector3d",
- },
- },
- Notes = "Adds the specified vector to this vector. Is slightly better performant than adding with a \"+\" because this doesn't create a new object for the result.",
- },
- },
- Normalize =
- {
- Notes = "Changes this vector so that it keeps current direction but is exactly 1 unit long. FIXME: Fails for a zero vector.",
- },
- NormalizeCopy =
- {
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns a new vector that has the same direction as this but is exactly 1 unit long. FIXME: Fails for a zero vector.",
- },
- operator_div =
- {
- {
- Params =
- {
- {
- Name = "ParCoordDivisors",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns a new Vector3d object with each coord divided by the corresponding coord from the given vector.",
- },
- {
- Params =
- {
- {
- Name = "Divisor",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns a new Vector3d object with each coord divided by the specified number.",
- },
- },
- operator_mul =
- {
- {
- Params =
- {
- {
- Name = "PerCoordMultiplier",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns a new Vector3d object with each coord multiplied by the corresponding coord from the given vector.",
- },
- {
- Params =
- {
- {
- Name = "Multiplier",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns a new Vector3d object with each coord multiplied.",
- },
- },
- operator_plus =
- {
- Params =
- {
- {
- Name = "Addend",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns a new Vector3d containing the sum of this vector and the specified vector",
- },
- operator_sub =
- {
- {
- Params =
- {
- {
- Name = "Subtrahend",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns a new Vector3d object containing the difference between this object and the specified vector.",
- },
- {
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns a new Vector3d object that is a negative of this vector (all coords multiplied by -1).",
- },
- },
- Set =
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Notes = "Sets all the coords in this object.",
- },
- SqrLength =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the (euclidean) length of this vector, squared. This operation is slightly less computationally expensive than Length(), while it conserves some properties of Length(), such as comparison. ",
- },
- TurnCCW =
- {
- Notes = "Rotates the vector 90 degrees counterclockwise around the vertical axis. Note that this is specific to minecraft's axis ordering, which is X+ left, Z+ down.",
- },
- TurnCW =
- {
- Notes = "Rotates the vector 90 degrees clockwise around the vertical axis. Note that this is specific to minecraft's axis ordering, which is X+ left, Z+ down.",
- },
- },
- Constants =
- {
- EPS =
- {
- Notes = "The max difference between two coords for which the coords are assumed equal (in LineCoeffToXYPlane() et al).",
- },
- NO_INTERSECTION =
- {
- Notes = "Special return value for the LineCoeffToXYPlane() et al meaning that there's no intersection with the plane.",
- },
- },
- Variables =
- {
- x =
- {
- Type = "number",
- Notes = "The X coord of the vector.",
- },
- y =
- {
- Type = "number",
- Notes = "The Y coord of the vector.",
- },
- z =
- {
- Type = "number",
- Notes = "The Z coord of the vector.",
- },
- },
- },
- Vector3f =
- {
- Desc = [[
- A Vector3f object uses floating point values to describe a point in space.
-
- See also {{Vector3d}} for double-precision floating point 3D coords and {{Vector3i}} for integer
- 3D coords.
- ]],
- Functions =
- {
- Abs =
- {
- Notes = "Updates each coord to its absolute value.",
- },
- abs =
- {
- Notes = "OBSOLETE, use Abs() instead.",
- },
- Clamp =
- {
- Params =
- {
- {
- Name = "min",
- Type = "number",
- },
- {
- Name = "max",
- Type = "number",
- },
- },
- Notes = "Clamps each coord into the specified range.",
- },
- clamp =
- {
- Params =
- {
- {
- Name = "min",
- Type = "number",
- },
- {
- Name = "max",
- Type = "number",
- },
- },
- Notes = "OBSOLETE, use Clamp() instead.",
- },
- constructor =
- {
- {
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Creates a new Vector3f object with zero coords",
- },
- {
- Params =
- {
- {
- Name = "x",
- Type = "number",
- },
- {
- Name = "y",
- Type = "number",
- },
- {
- Name = "z",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Creates a new Vector3f object with the specified coords",
- },
- {
- Params =
- {
- {
- Name = "Vector3f",
- Type = "Vector3f",
- },
- },
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Creates a new Vector3f object as a copy of the specified vector",
- },
- {
- Params =
- {
- {
- Name = "Vector3d",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Creates a new Vector3f object as a copy of the specified {{Vector3d}}",
- },
- {
- Params =
- {
- {
- Name = "Vector3i",
- Type = "Vector3i",
- },
- },
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Creates a new Vector3f object as a copy of the specified {{Vector3i}}",
- },
- },
- Cross =
- {
- Params =
- {
- {
- Name = "Other",
- Type = "Vector3f",
- },
- },
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Returns a new Vector3f object that holds the cross product of this vector and the specified vector.",
- },
- Dot =
- {
- Params =
- {
- {
- Name = "Other",
- Type = "Vector3f",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the dot product of this vector and the specified vector.",
- },
- Equals =
- {
- Params =
- {
- {
- Name = "Other",
- Type = "Vector3f",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified vector is exactly equal to this vector. Note that this is subject to (possibly imprecise) floating point math.",
- },
- EqualsEps =
- {
- Params =
- {
- {
- Name = "Other",
- Type = "Vector3f",
- },
- {
- Name = "Eps",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the differences between each corresponding coords of this vector and the one specified, are less than the specified Eps.",
- },
- Floor =
- {
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns a new {{Vector3i}} object with coords set to math.floor of this vector's coords.",
- },
- HasNonZeroLength =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the vector has at least one coord non-zero. Note that this is subject to (possibly imprecise) floating point math.",
- },
- Length =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the (euclidean) length of this vector",
- },
- LineCoeffToXYPlane =
- {
- Params =
- {
- {
- Name = "Vector3f",
- Type = "Vector3f",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the coefficient for the line from the specified vector through this vector to reach the specified Z coord. The result satisfies the following equation: (this + Result * (Param - this)).z = Z. Returns the NO_INTERSECTION constant if there's no intersection.",
- },
- LineCoeffToXZPlane =
- {
- Params =
- {
- {
- Name = "Vector3f",
- Type = "Vector3f",
- },
- {
- Name = "Y",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the coefficient for the line from the specified vector through this vector to reach the specified Y coord. The result satisfies the following equation: (this + Result * (Param - this)).y = Y. Returns the NO_INTERSECTION constant if there's no intersection.",
- },
- LineCoeffToYZPlane =
- {
- Params =
- {
- {
- Name = "Vector3f",
- Type = "Vector3f",
- },
- {
- Name = "X",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the coefficient for the line from the specified vector through this vector to reach the specified X coord. The result satisfies the following equation: (this + Result * (Param - this)).x = X. Returns the NO_INTERSECTION constant if there's no intersection.",
- },
- Move =
- {
- {
- Params =
- {
- {
- Name = "X",
- Type = "number",
- },
- {
- Name = "Y",
- Type = "number",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Notes = "Adds the specified offsets to each coord, effectively moving the vector by the specified coord offsets.",
- },
- {
- Params =
- {
- {
- Name = "Diff",
- Type = "Vector3f",
- },
- },
- Notes = "Adds the specified vector to this vector. Is slightly better performant than adding with a \"+\" because this doesn't create a new object for the result.",
- },
- },
- Normalize =
- {
- Notes = "Normalizes this vector (makes it 1 unit long while keeping the direction). FIXME: Fails for zero vectors.",
- },
- NormalizeCopy =
- {
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Returns a copy of this vector that is normalized (1 unit long while keeping the same direction). FIXME: Fails for zero vectors.",
- },
- operator_div =
- {
- {
- Params =
- {
- {
- Name = "PerCoordDivisor",
- Type = "Vector3f",
- },
- },
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Returns a new Vector3f object with each coord divided by the corresponding coord from the given vector.",
- },
- {
- Params =
- {
- {
- Name = "Divisor",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Returns a new Vector3f object with each coord divided by the specified number.",
- },
- },
- operator_mul =
- {
- {
- Params =
- {
- {
- Name = "PerCoordMultiplier",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Returns a new Vector3f object that has each of its coords multiplied by the specified number",
- },
- {
- Params =
- {
- {
- Name = "Multiplier",
- Type = "Vector3f",
- },
- },
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Returns a new Vector3f object that has each of its coords multiplied by the respective coord of the specified vector.",
- },
- },
- operator_plus =
- {
- Params =
- {
- {
- Name = "Other",
- Type = "Vector3f",
- },
- },
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Returns a new Vector3f object that holds the vector sum of this vector and the specified vector.",
- },
- operator_sub =
- {
- {
- Params =
- {
- {
- Name = "Subtrahend",
- Type = "Vector3f",
- },
- },
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Returns a new Vector3f object that holds the vector differrence between this vector and the specified vector.",
- },
- {
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Returns a new Vector3f that is a negative of this vector (all coords multiplied by -1).",
- },
- },
- Set =
- {
- Params =
- {
- {
- Name = "x",
- Type = "number",
- },
- {
- Name = "y",
- Type = "number",
- },
- {
- Name = "z",
- Type = "number",
- },
- },
- Notes = "Sets all the coords of the vector at once.",
- },
- SqrLength =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the (euclidean) length of this vector, squared. This operation is slightly less computationally expensive than Length(), while it conserves some properties of Length(), such as comparison.",
- },
- TurnCCW =
- {
- Notes = "Rotates the vector 90 degrees counterclockwise around the vertical axis. Note that this is specific to minecraft's axis ordering, which is X+ left, Z+ down.",
- },
- TurnCW =
- {
- Notes = "Rotates the vector 90 degrees clockwise around the vertical axis. Note that this is specific to minecraft's axis ordering, which is X+ left, Z+ down.",
- },
- },
- Constants =
- {
- EPS =
- {
- Notes = "The max difference between two coords for which the coords are assumed equal (in LineCoeffToXYPlane() et al).",
- },
- NO_INTERSECTION =
- {
- Notes = "Special return value for the LineCoeffToXYPlane() et al meaning that there's no intersection with the plane.",
- },
- },
- Variables =
- {
- x =
- {
- Type = "number",
- Notes = "The X coord of the vector.",
- },
- y =
- {
- Type = "number",
- Notes = "The Y coord of the vector.",
- },
- z =
- {
- Type = "number",
- Notes = "The Z coord of the vector.",
- },
- },
- },
- Vector3i =
- {
- Desc = [[
- A Vector3i object uses integer values to describe a point in space.
-
- See also {{Vector3d}} for double-precision floating point 3D coords and {{Vector3f}} for
- single-precision floating point 3D coords.
- ]],
- Functions =
- {
- Abs =
- {
- Notes = "Updates each coord to its absolute value.",
- },
- abs =
- {
- Notes = "OBSOLETE, use Abs() instead.",
- },
- Clamp =
- {
- Params =
- {
- {
- Name = "min",
- Type = "number",
- },
- {
- Name = "max",
- Type = "number",
- },
- },
- Notes = "Clamps each coord into the specified range.",
- },
- clamp =
- {
- Params =
- {
- {
- Name = "min",
- Type = "number",
- },
- {
- Name = "max",
- Type = "number",
- },
- },
- Notes = "OBSOLETE, use Clamp() instead.",
- },
- constructor =
- {
- {
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Creates a new Vector3i object with zero coords.",
- },
- {
- Params =
- {
- {
- Name = "x",
- Type = "number",
- },
- {
- Name = "y",
- Type = "number",
- },
- {
- Name = "z",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Creates a new Vector3i object with the specified coords.",
- },
- {
- Params =
- {
- {
- Name = "Vector3d",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Creates a new Vector3i object with coords copied and floor()-ed from the specified {{Vector3d}}.",
- },
- },
- Cross =
- {
- Params =
- {
- {
- Name = "Other",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "Vector3d",
- },
- },
- Notes = "Returns a new Vector3d that is a {{http://en.wikipedia.org/wiki/Cross_product|cross product}} of this vector and the specified vector.",
- },
- Dot =
- {
- Params =
- {
- {
- Name = "Other",
- Type = "Vector3d",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the dot product of this vector and the specified vector.",
- },
- Equals =
- {
- Params =
- {
- {
- Name = "Other",
- Type = "Vector3i",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if this vector is exactly the same as the specified vector.",
- },
- EqualsEps =
- {
- Params =
- {
- {
- Name = "Other",
- Type = "Vector3i",
- },
- {
- Name = "Eps",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the differences between each corresponding coords of this vector and the one specified, are less than the specified Eps. Normally not too useful for integer-only vectors, but still included for API completeness.",
- },
- Floor =
- {
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns a new {{Vector3i}} object with coords set to math.floor of this vector's coords. Normally not too useful with integer-only vectors, but still included for API completeness.",
- },
- HasNonZeroLength =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the vector has at least one coord non-zero.",
- },
- Length =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the (euclidean) length of this vector.",
- },
- LineCoeffToXYPlane =
- {
- Params =
- {
- {
- Name = "Vector3i",
- Type = "Vector3i",
- },
- {
- Name = "Z",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the coefficient for the line from the specified vector through this vector to reach the specified Z coord. The result satisfies the following equation: (this + Result * (Param - this)).z = Z. Returns the NO_INTERSECTION constant if there's no intersection.",
- },
- LineCoeffToXZPlane =
- {
- Params =
- {
- {
- Name = "Vector3i",
- Type = "Vector3i",
- },
- {
- Name = "Y",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the coefficient for the line from the specified vector through this vector to reach the specified Y coord. The result satisfies the following equation: (this + Result * (Param - this)).y = Y. Returns the NO_INTERSECTION constant if there's no intersection.",
- },
- LineCoeffToYZPlane =
- {
- Params =
- {
- {
- Name = "Vector3i",
- Type = "Vector3i",
- },
- {
- Name = "X",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the coefficient for the line from the specified vector through this vector to reach the specified X coord. The result satisfies the following equation: (this + Result * (Param - this)).x = X. Returns the NO_INTERSECTION constant if there's no intersection.",
- },
- Move =
- {
- {
- Params =
- {
- {
- Name = "x",
- Type = "number",
- },
- {
- Name = "y",
- Type = "number",
- },
- {
- Name = "z",
- Type = "number",
- },
- },
- Notes = "Moves the vector by the specified amount in each axis direction.",
- },
- {
- Params =
- {
- {
- Name = "Diff",
- Type = "Vector3i",
- },
- },
- Notes = "Adds the specified vector to this vector. Is slightly better performant than adding with a \"+\" because this doesn't create a new object for the result.",
- },
- },
- Normalize =
- {
- Notes = "Normalizes this vector (makes it 1 unit long while keeping the direction). Quite useless for integer-only vectors, since the normalized vector will almost always truncate to zero vector. FIXME: Fails for zero vectors.",
- },
- NormalizeCopy =
- {
- Returns =
- {
- {
- Type = "Vector3f",
- },
- },
- Notes = "Returns a copy of this vector that is normalized (1 unit long while keeping the same direction). Quite useless for integer-only vectors, since the normalized vector will almost always truncate to zero vector. FIXME: Fails for zero vectors.",
- },
- operator_div =
- {
- {
- Params =
- {
- {
- Name = "Divisor",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns a new Vector3i object that has each of its coords divided by the specified number",
- },
- {
- Params =
- {
- {
- Name = "PerCoordDivisors",
- Type = "Vector3i",
- },
- },
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns a new Vector3i object that has each of its coords divided by the respective coord of the specified vector.",
- },
- },
- operator_mul =
- {
- {
- Params =
- {
- {
- Name = "Multiplier",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns a new Vector3i object that has each of its coords multiplied by the specified number",
- },
- {
- Params =
- {
- {
- Name = "PerCoordMultipliers",
- Type = "Vector3i",
- },
- },
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns a new Vector3i object that has each of its coords multiplied by the respective coord of the specified vector.",
- },
- },
- operator_plus =
- {
- Params =
- {
- {
- Name = "Addend",
- Type = "Vector3i",
- },
- },
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns a new Vector3f object that holds the vector sum of this vector and the specified vector.",
- },
- operator_sub =
- {
- {
- Params =
- {
- {
- Name = "Subtrahend",
- Type = "Vector3i",
- },
- },
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns a new Vector3i object that holds the vector differrence between this vector and the specified vector.",
- },
- {
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- Notes = "Returns a new Vector3i that is a negative of this vector (all coords multiplied by -1).",
- },
- },
- Set =
- {
- Params =
- {
- {
- Name = "x",
- Type = "number",
- },
- {
- Name = "y",
- Type = "number",
- },
- {
- Name = "z",
- Type = "number",
- },
- },
- Notes = "Sets all the coords of the vector at once",
- },
- SqrLength =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the (euclidean) length of this vector, squared. This operation is slightly less computationally expensive than Length(), while it conserves some properties of Length(), such as comparison.",
- },
- TurnCCW =
- {
- Notes = "Rotates the vector 90 degrees counterclockwise around the vertical axis. Note that this is specific to minecraft's axis ordering, which is X+ left, Z+ down.",
- },
- TurnCW =
- {
- Notes = "Rotates the vector 90 degrees clockwise around the vertical axis. Note that this is specific to minecraft's axis ordering, which is X+ left, Z+ down.",
- },
- },
- Constants =
- {
- EPS =
- {
- Notes = "The max difference between two coords for which the coords are assumed equal (in LineCoeffToXYPlane() et al). Quite useless with integer-only vector.",
- },
- NO_INTERSECTION =
- {
- Notes = "Special return value for the LineCoeffToXYPlane() et al meaning that there's no intersection with the plane.",
- },
- },
- Variables =
- {
- x =
- {
- Type = "number",
- Notes = "The X coord of the vector.",
- },
- y =
- {
- Type = "number",
- Notes = "The Y coord of the vector.",
- },
- z =
- {
- Type = "number",
- Notes = "The Z coord of the vector.",
- },
- },
- },
-}
diff --git a/world/Plugins/APIDump/Classes/Network.lua b/world/Plugins/APIDump/Classes/Network.lua
deleted file mode 100644
index 3c47e3c6..00000000
--- a/world/Plugins/APIDump/Classes/Network.lua
+++ /dev/null
@@ -1,1025 +0,0 @@
-
--- Network.lua
-
--- Defines the documentation for the cNetwork-related classes and cUrlClient
-
-
-
-
-
-return
-{
- cNetwork =
- {
- Desc = [[
- This is the namespace for high-level network-related operations. Allows plugins to make TCP
- connections to the outside world using a callback-based API.
-
- All functions in this namespace are static, they should be called on the cNetwork class itself:
-
-local Server = cNetwork:Listen(1024, ListenCallbacks);
-
- ]],
- Functions =
- {
- Connect =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Host",
- Type = "string",
- },
- {
- Name = "Port",
- Type = "number",
- },
- {
- Name = "LinkCallbacks",
- Type = "table",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Begins establishing a (client) TCP connection to the specified host. Uses the LinkCallbacks table to report progress, success, errors and incoming data. Returns false if it fails immediately (bad port value, bad hostname format), true otherwise. Host can be either an IP address or a hostname.",
- },
- CreateUDPEndpoint =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Port",
- Type = "number",
- },
- {
- Name = "UDPCallbacks",
- Type = "table",
- },
- },
- Returns =
- {
- {
- Type = "cUDPEndpoint",
- },
- },
- Notes = "Creates a UDP endpoint that listens for incoming datagrams on the specified port, and can be used to send or broadcast datagrams. Uses the UDPCallbacks to report incoming datagrams or errors. If the endpoint cannot be created, the OnError callback is called with the error details and the returned endpoint will report IsOpen() == false. The plugin needs to store the returned endpoint object for as long as it needs the UDP port open; if the endpoint is garbage-collected by Lua, the socket will be closed and no more incoming data will be reported. If the Port is zero, the OS chooses an available UDP port for the endpoint; use {{cUDPEndpoint}}:GetPort() to query the port number in such case.",
- },
- EnumLocalIPAddresses =
- {
- IsStatic = true,
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns all local IP addresses for network interfaces currently available on the machine, as an array-table of strings.",
- },
- HostnameToIP =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Host",
- Type = "string",
- },
- {
- Name = "LookupCallbacks",
- Type = "table",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Begins a DNS lookup to find the IP address(es) for the specified host. Uses the LookupCallbacks table to report progress, success or errors. Returns false if it fails immediately (bad hostname format), true if the lookup started successfully. Host can be either a hostname or an IP address.",
- },
- IPToHostname =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Address",
- Type = "string",
- },
- {
- Name = "LookupCallbacks",
- Type = "table",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Begins a reverse-DNS lookup to find out the hostname for the specified IP address. Uses the LookupCallbacks table to report progress, success or errors. Returns false if it fails immediately (bad address format), true if the lookup started successfully.",
- },
- Listen =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Port",
- Type = "number",
- },
- {
- Name = "ListenCallbacks",
- Type = "table",
- },
- },
- Returns =
- {
- {
- Type = "cServerHandle",
- },
- },
- Notes = "Starts listening on the specified port. Uses the ListenCallbacks to report incoming connections or errors. Returns a {{cServerHandle}} object representing the server. If the listen operation failed, the OnError callback is called with the error details and the returned server handle will report IsListening() == false. The plugin needs to store the server handle object for as long as it needs the server running, if the server handle is garbage-collected by Lua, the listening socket will be closed and all current connections dropped.",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Using callbacks",
- Contents = [[
- The entire Networking API is callback-based. Whenever an event happens on the network object, a
- specific plugin-provided function is called. The callbacks are stored in tables which are passed
- to the API functions, each table contains multiple callbacks for the various situations.
-
- There are four different callback variants used: LinkCallbacks, LookupCallbacks, ListenCallbacks
- and UDPCallbacks. Each is used in the situation appropriate by its name - LinkCallbacks are used
- for handling the traffic on a single network link (plus additionally creation of such link when
- connecting as a client), LookupCallbacks are used when doing DNS and reverse-DNS lookups,
- ListenCallbacks are used for handling incoming connections as a server and UDPCallbacks are used
- for incoming UDP datagrams.
-
- LinkCallbacks have the following structure:
-
-local LinkCallbacks =
-{
- OnConnected = function ({{cTCPLink|a_TCPLink}})
- -- The specified {{cTCPLink|link}} has succeeded in connecting to the remote server.
- -- Only called if the link is being connected as a client (using cNetwork:Connect() )
- -- Not used for incoming server links
- -- All returned values are ignored
- end,
-
- OnError = function ({{cTCPLink|a_TCPLink}}, a_ErrorCode, a_ErrorMsg)
- -- The specified error has occured on the {{cTCPLink|link}}
- -- No other callback will be called for this link from now on
- -- For a client link being connected, this reports a connection error (destination unreachable etc.)
- -- It is an Undefined Behavior to send data to a_TCPLink in or after this callback
- -- All returned values are ignored
- end,
-
- OnReceivedData = function ({{cTCPLink|a_TCPLink}}, a_Data)
- -- Data has been received on the {{cTCPLink|link}}
- -- Will get called whenever there's new data on the {{cTCPLink|link}}
- -- a_Data contains the raw received data, as a string
- -- All returned values are ignored
- end,
-
- OnRemoteClosed = function ({{cTCPLink|a_TCPLink}})
- -- The remote peer has closed the {{cTCPLink|link}}
- -- The link is already closed, any data sent to it now will be lost
- -- No other callback will be called for this link from now on
- -- All returned values are ignored
- end,
-}
-
-
- LookupCallbacks have the following structure:
-
-local LookupCallbacks =
-{
- OnError = function (a_Query, a_ErrorCode, a_ErrorMsg)
- -- The specified error has occured while doing the lookup
- -- a_Query is the hostname or IP being looked up
- -- No other callback will be called for this lookup from now on
- -- All returned values are ignored
- end,
-
- OnFinished = function (a_Query)
- -- There are no more DNS records for this query
- -- a_Query is the hostname or IP being looked up
- -- No other callback will be called for this lookup from now on
- -- All returned values are ignored
- end,
-
- OnNameResolved = function (a_Hostname, a_IP)
- -- A DNS record has been found, the specified hostname resolves to the IP
- -- Called for both Hostname -> IP and IP -> Hostname lookups
- -- May be called multiple times if a hostname resolves to multiple IPs
- -- All returned values are ignored
- end,
-}
-
-
- ListenCallbacks have the following structure:
-
-local ListenCallbacks =
-{
- OnAccepted = function ({{cTCPLink|a_TCPLink}})
- -- A new connection has been accepted and a {{cTCPLink|Link}} for it created
- -- It is safe to send data to the link now
- -- All returned values are ignored
- end,
-
- OnError = function (a_ErrorCode, a_ErrorMsg)
- -- The specified error has occured while trying to listen
- -- No other callback will be called for this server handle from now on
- -- This callback is called before the cNetwork:Listen() call returns
- -- All returned values are ignored
- end,
-
- OnIncomingConnection = function (a_RemoteIP, a_RemotePort, a_LocalPort)
- -- A new connection is being accepted, from the specified remote peer
- -- This function needs to return either nil to drop the connection,
- -- or valid LinkCallbacks to use for the new connection's {{cTCPLink|TCPLink}} object
- return SomeLinkCallbacks
- end,
-}
-
-
- UDPCallbacks have the following structure:
-
-local UDPCallbacks =
-{
- OnError = function (a_ErrorCode, a_ErrorMsg)
- -- The specified error has occured when trying to listen for incoming UDP datagrams
- -- No other callback will be called for this endpoint from now on
- -- This callback is called before the cNetwork:CreateUDPEndpoint() call returns
- -- All returned values are ignored
- end,
-
- OnReceivedData = function ({{cUDPEndpoint|a_UDPEndpoint}}, a_Data, a_RemotePeer, a_RemotePort)
- -- A datagram has been received on the {{cUDPEndpoint|endpoint}} from the specified remote peer
- -- a_Data contains the raw received data, as a string
- -- All returned values are ignored
- end,
-}
-
- ]],
- },
- {
- Header = "Example client connection",
- Contents = [[
- The following example, adapted from the NetworkTest plugin, shows a simple example of a client
- connection using the cNetwork API. It connects to www.google.com on port 80 (http) and sends a http
- request for the front page. It dumps the received data to the console.
-
- First, the callbacks are defined in a table. The OnConnected() callback takes care of sending the http
- request once the socket is connected. The OnReceivedData() callback sends all data to the console. The
- OnError() callback logs any errors. Then, the connection is initiated using the cNetwork::Connect() API
- function.
-
-
--- Define the callbacks to use for the client connection:
-local ConnectCallbacks =
-{
- OnConnected = function (a_Link)
- -- Connection succeeded, send the http request:
- a_Link:Send("GET / HTTP/1.0\r\nHost: www.google.com\r\n\r\n")
- end,
-
- OnError = function (a_Link, a_ErrorCode, a_ErrorMsg)
- -- Log the error to console:
- LOG("An error has occurred while talking to google.com: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
- end,
-
- OnReceivedData = function (a_Link, a_Data)
- -- Log the received data to console:
- LOG("Incoming http data:\r\n" .. a_Data)
- end,
-
- OnRemoteClosed = function (a_Link)
- -- Log the event into the console:
- LOG("Connection to www.google.com closed")
- end,
-}
-
--- Connect:
-if not(cNetwork:Connect("www.google.com", 80, ConnectCallbacks)) then
- -- Highly unlikely, but better check for errors
- LOG("Cannot queue connection to www.google.com")
-end
--- Note that the connection is being made on the background,
--- there's no guarantee that it's already connected at this point in code
-
- ]],
- },
- {
- Header = "Example server implementation",
- Contents = [[
- The following example, adapted from the NetworkTest plugin, shows a simple example of creating a
- server listening on a TCP port using the cNetwork API. The server listens on port 9876 and for
- each incoming connection it sends a welcome message and then echoes back whatever the client has
- sent ("echo server").
-
- First, the callbacks for the listening server are defined. The most important of those is the
- OnIncomingConnection() callback that must return the LinkCallbacks that will be used for the new
- connection. In our simple scenario each connection uses the same callbacks, so a predefined
- callbacks table is returned; it is, however, possible to define different callbacks for each
- connection. This allows the callbacks to be "personalised", for example by the remote IP or the
- time of connection. The OnAccepted() and OnError() callbacks only log that they occurred, there's
- no processing needed for them.
-
- Finally, the cNetwork:Listen() API function is used to create the listening server. The status of
- the server is checked and if it is successfully listening, it is stored in a global variable, so
- that Lua doesn't garbage-collect it until we actually want the server closed.
-
-
--- Define the callbacks used for the incoming connections:
-local EchoLinkCallbacks =
-{
- OnConnected = function (a_Link)
- -- This will not be called for a server connection, ever
- assert(false, "Unexpected Connect callback call")
- end,
-
- OnError = function (a_Link, a_ErrorCode, a_ErrorMsg)
- -- Log the error to console:
- local RemoteName = "'" .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. "'"
- LOG("An error has occurred while talking to " .. RemoteName .. ": " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")")
- end,
-
- OnReceivedData = function (a_Link, a_Data)
- -- Send the received data back to the remote peer
- a_Link:Send(Data)
- end,
-
- OnRemoteClosed = function (a_Link)
- -- Log the event into the console:
- local RemoteName = "'" .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. "'"
- LOG("Connection to '" .. RemoteName .. "' closed")
- end,
-}
-
--- Define the callbacks used by the server:
-local ListenCallbacks =
-{
- OnAccepted = function (a_Link)
- -- No processing needed, just log that this happened:
- LOG("OnAccepted callback called")
- end,
-
- OnError = function (a_ErrorCode, a_ErrorMsg)
- -- An error has occured while listening for incoming connections, log it:
- LOG("Cannot listen, error " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")"
- end,
-
- OnIncomingConnection = function (a_RemoteIP, a_RemotePort, a_LocalPort)
- -- A new connection is being accepted, give it the EchoCallbacks
- return EchoLinkCallbacks
- end,
-}
-
--- Start the server:
-local Server = cNetwork:Listen(9876, ListenCallbacks)
-if not(Server:IsListening()) then
- -- The error has been already printed in the OnError() callbacks
- -- Just bail out
- return;
-end
-
--- Store the server globally, so that it stays open:
-g_Server = Server
-
-...
-
--- Elsewhere in the code, when terminating:
--- Close the server and let it be garbage-collected:
-g_Server:Close()
-g_Server = nil
-
- ]],
- },
- },
- },
- cServerHandle =
- {
- Desc = [[
- This class provides an interface for TCP sockets listening for a connection. In order to listen, the
- plugin needs to use the {{cNetwork}}:Listen() function to create the listening socket.
-
- Note that when Lua garbage-collects this class, the listening socket is closed. Therefore the plugin
- should keep it referenced in a global variable for as long as it wants the server running.
- ]],
- Functions =
- {
- Close =
- {
- Notes = "Closes the listening socket. No more connections will be accepted, and all current connections will be closed.",
- },
- IsListening =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the socket is listening.",
- },
- },
- },
- cTCPLink =
- {
- Desc = [[
- This class wraps a single TCP connection, that has been established. Plugins can create these by
- calling {{cNetwork}}:Connect() to connect to a remote server, or by listening using
- {{cNetwork}}:Listen() and accepting incoming connections. The links are callback-based - when an event
- such as incoming data or remote disconnect happens on the link, a specific callback is called. See the
- additional information in {{cNetwork}} documentation for details.
-
- The link can also optionally perform TLS encryption. Plugins can use the StartTLSClient() function to
- start the TLS handshake as the client side. Since that call, the OnReceivedData() callback is
- overridden internally so that the data is first routed through the TLS decryptor, and the plugin's
- callback is only called for the decrypted data, once it starts arriving. The Send function changes its
- behavior so that the data written by the plugin is first encrypted and only then sent over the
- network. Note that calling Send() before the TLS handshake finishes is supported, but the data is
- queued internally and only sent once the TLS handshake is completed.
- ]],
- Functions =
- {
- Close =
- {
- Notes = "Closes the link forcefully (TCP RST). There's no guarantee that the last sent data is even being delivered. See also the Shutdown() method.",
- },
- GetLocalIP =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the IP address of the local endpoint of the TCP connection.",
- },
- GetLocalPort =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the port of the local endpoint of the TCP connection.",
- },
- GetRemoteIP =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the IP address of the remote endpoint of the TCP connection.",
- },
- GetRemotePort =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the port of the remote endpoint of the TCP connection.",
- },
- Send =
- {
- Params =
- {
- {
- Name = "Data",
- Type = "string",
- },
- },
- Notes = "Sends the data (raw string) to the remote peer. The data is sent asynchronously and there is no report on the success of the send operation, other than the connection being closed or reset by the underlying OS.",
- },
- Shutdown =
- {
- Notes = "Shuts the socket down for sending data. Notifies the remote peer that there will be no more data coming from us (TCP FIN). The data that is in flight will still be delivered. The underlying socket will be closed when the remote end shuts down as well, or after a timeout.",
- },
- StartTLSClient =
- {
- Params =
- {
- {
- Name = "OwnCert",
- Type = "string",
- },
- {
- Name = "OwnPrivateKey",
- Type = "string",
- },
- {
- Name = "OwnPrivateKeyPassword",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- {
- Name = "ErrorMessage",
- Type = "string",
- IsOptional = true,
- },
- },
- Notes = "Starts a TLS handshake on the link, as a client side of the TLS. The Own___ parameters specify the client certificate and its corresponding private key and password; all three parameters are optional and no client certificate is presented to the remote peer if they are not used or all empty. Once the TLS handshake is started by this call, all incoming data is first decrypted before being sent to the OnReceivedData callback, and all outgoing data is queued until the TLS handshake completes, and then sent encrypted over the link. Returns true on success, nil and optional error message on immediate failure. NOTE: The TLS support in the API is currently experimental and shouldn't be considered safe - there's no peer certificate verification and the error reporting is only basic.",
- },
- StartTLSServer =
- {
- Params =
- {
- {
- Name = "Certificate",
- Type = "string",
- },
- {
- Name = "PrivateKey",
- Type = "string",
- },
- {
- Name = "PrivateKeyPassword",
- Type = "string",
- },
- {
- Name = "StartTLSData",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- {
- Name = "ErrorMessage",
- Type = "string",
- IsOptional = true,
- },
- },
- Notes = "Starts a TLS handshake on the link, as a server side of the TLS. The plugin needs to specify the server certificate and its corresponding private key and password. The StartTLSData can contain data that the link has already reported as received but it should be used as part of the TLS handshake. Once the TLS handshake is started by this call, all incoming data is first decrypted before being sent to the OnReceivedData callback, and all outgoing data is queued until the TLS handshake completes, and then sent encrypted over the link. Returns true on success, nil and optional error message on immediate failure. NOTE: The TLS support in the API is currently experimental and shouldn't be considered safe - there's no peer certificate verification and the error reporting is only basic.",
- },
- },
- },
- cUDPEndpoint =
- {
- Desc = [[
- Represents a UDP socket that is listening for incoming datagrams on a UDP port and can send or broadcast datagrams to other peers on the network. Plugins can create an instance of the endpoint by calling {{cNetwork}}:CreateUDPEndpoint(). The endpoints are callback-based - when a datagram is read from the network, the OnRececeivedData() callback is called with details about the datagram. See the additional information in {{cNetwork}} documentation for details.
-
- Note that when Lua garbage-collects this class, the listening socket is closed. Therefore the plugin should keep this object referenced in a global variable for as long as it wants the endpoint open.
- ]],
- Functions =
- {
- Close =
- {
- Notes = "Closes the UDP endpoint. No more datagrams will be reported through the callbacks, the UDP port will be closed.",
- },
- EnableBroadcasts =
- {
- Notes = "Some OSes need this call before they allow UDP broadcasts on an endpoint.",
- },
- GetPort =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the local port number of the UDP endpoint listening for incoming datagrams. Especially useful if the UDP endpoint was created with auto-assign port (0).",
- },
- IsOpen =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the UDP endpoint is listening for incoming datagrams.",
- },
- Send =
- {
- Params =
- {
- {
- Name = "RawData",
- Type = "string",
- },
- {
- Name = "RemoteHost",
- Type = "string",
- },
- {
- Name = "RemotePort",
- Type = "number",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Sends the specified raw data (string) to the specified remote host. The RemoteHost can be either a hostname or an IP address; if it is a hostname, the endpoint will queue a DNS lookup first, if it is an IP address, the send operation is executed immediately. Returns true if there was no immediate error, false on any failure. Note that the return value needn't represent whether the packet was actually sent, only if it was successfully queued.",
- },
- },
- },
- cUrlClient =
- {
- Desc = [[
- Implements high-level asynchronous access to URLs, such as downloading webpages over HTTP(S).
-
- Note that unlike other languages' URL access libraries, this class implements asynchronous requests.
- This means that the functions only start a request and return immediately. The request is then
- fulfilled in the background, while the server continues to run. The response is delivered back to the
- plugin using callbacks. This allows the plugin to start requests and not block the server until the
- response is received.
-
- The functions that make network requests are all static and have a dual interface. Either you can use
- a single callback function, which gets called once the entire response is received or an error is
- encountered. Or you can use a table of callback functions, each function being called whenever the
- specific event happens during the request and response lifetime. See the Simple Callback and Callback
- Table chapters later on this page for details and examples.
-
- All the request function also support optional parameters for further customization of the request -
- the Headers parameter specifies additional HTTP headers that are to be sent (as a dictionary-table of
- key -> value), the RequestBody parameter specifying the optional body of the request (used mainly for
- POST and PUT requests), and an Options parameter specifying additional options specific to the protocol
- used.
- ]],
- Functions =
- {
- Delete =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "URL",
- Type = "string",
- },
- {
- Name = "Callbacks",
- Type = "table",
- },
- {
- Name = "Headers",
- Type = "table",
- IsOptional = true,
- },
- {
- Name = "RequestBody",
- Type = "string",
- IsOptional = true,
- },
- {
- Name = "Options",
- Type = "table",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- {
- Name = "ErrorMessagge",
- Type = "string",
- IsOptional = true,
- },
- },
- Notes = "Starts a HTTP DELETE request. Alias for Request(\"DELETE\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.).",
- },
- Get =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "URL",
- Type = "string",
- },
- {
- Name = "Callbacks",
- Type = "table",
- },
- {
- Name = "Headers",
- Type = "table",
- IsOptional = true,
- },
- {
- Name = "RequestBody",
- Type = "string",
- IsOptional = true,
- },
- {
- Name = "Options",
- Type = "table",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- {
- Name = "ErrMsg",
- Type = "string",
- IsOptional = true,
- },
- },
- Notes = "Starts a HTTP GET request. Alias for Request(\"GET\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.).",
- },
- Post =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "URL",
- Type = "string",
- },
- {
- Name = "Callbacks",
- Type = "table",
- },
- {
- Name = "Headers",
- Type = "table",
- IsOptional = true,
- },
- {
- Name = "RequestBody",
- Type = "string",
- IsOptional = true,
- },
- {
- Name = "Options",
- Type = "table",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- {
- Name = "ErrMsg",
- Type = "string",
- IsOptional = true,
- },
- },
- Notes = "Starts a HTTP POST request. Alias for Request(\"POST\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.).",
- },
- Put =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "URL",
- Type = "string",
- },
- {
- Name = "Callbacks",
- Type = "table",
- },
- {
- Name = "Headers",
- Type = "table",
- IsOptional = true,
- },
- {
- Name = "RequestBody",
- Type = "string",
- IsOptional = true,
- },
- {
- Name = "Options",
- Type = "table",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- {
- Name = "ErrMsg",
- Type = "string",
- IsOptional = true,
- },
- },
- Notes = "Starts a HTTP PUT request. Alias for Request(\"PUT\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.).",
- },
- Request =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Method",
- Type = "string",
- },
- {
- Name = "URL",
- Type = "string",
- },
- {
- Name = "Callbacks",
- Type = "table",
- },
- {
- Name = "Headers",
- Type = "table",
- IsOptional = true,
- },
- {
- Name = "RequestBody",
- Type = "string",
- IsOptional = true,
- },
- {
- Name = "Options",
- Type = "table",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "IsSuccess",
- Type = "boolean",
- },
- {
- Name = "ErrMsg",
- Type = "string",
- IsOptional = true,
- },
- },
- Notes = "Starts a request with the specified Method. Returns true on succes, false and error message on immediate failure (unparsable URL etc.).",
- },
- },
- AdditionalInfo =
- {
- {
- Header = "Simple Callback",
- Contents = [[
- When you don't need fine control for receiving the requests and are interested only in the result,
- you can use the simple callback approach. Pass a single function as the Callback parameter, the
- function will get called when the response is fully processed, either with the body of the response,
- or with an error message:
-
-cUrlClient:Get(url,
- function (a_Body, a_Data)
- if (a_Body) then
- -- Response received correctly, a_Body contains the entire response body,
- -- a_Data is a dictionary-table of the response's HTTP headers
- else
- -- There was an error, a_Data is the error message string
- end
- end
-)
-
- ]],
- },
- {
- Header = "Callback Table",
- Contents = [[
- To provide complete control over the request and response handling, Cuberite allows plugins to pass
- a table of callbacks as the Callback parameter. Then the respective functions are called for their
- respective events during the lifetime of the request and response. This way it is possible to
- process huge downloads that wouldn't fit into memory otherwise, or display detailed progress.
- Each callback function receives a "self" as its first parameter, this allows the functions to
- access the Callback table and any of its other members, allowing the use of Lua object idiom for
- the table. See this forum post for an
- example.
-
- The following callback functions are used by Cuberite. Any callback that is not assigned is
- silently ignored. The table may also contain other functions and other values, those are silently
- ignored.
-
-
Callback
Params
Notes
-
OnConnected
self, {{cTCPLink}}, RemoteIP, RemotePort
Called when the connection to the remote host is established. Note that current implementation doesn't provide the {{cTCPLink}} parameter and passes nil instead.
-
OnCertificateReceived
self
Called for HTTPS URLs when the server's certificate is received. If the callback returns anything else than true, the connection is aborted. Note that the current implementation doesn't provide the certificate because there is no representation for the cert in Lua.
-
OnTlsHandshakeCompleted
self
Called for HTTPS URLs when the TLS is established on the connection.
-
OnRequestSent
self
Called after the entire request is sent to the server.
-
OnStatusLine
self, HttpVersion, StatusCode, Rest
The initial line of the response has been parsed. HttpVersion is typically "HTTP/1.1", StatusCode is the numerical HTTP status code reported by the server (200 being OK), Rest is the rest of the line, usually a short message in case of an error.
-
OnHeader
self, Name, Value
A new HTTP response header line has been received.
-
OnHeadersFinished
self, AllHeaders
All HTTP response headers have been parsed. AllHeaders is a dictionary-table containing all the headers received.
-
OnBodyData
self, Data
A piece of the response body has been received. This callback is called repeatedly until the entire body is reported through its Data parameter.
-
OnBodyFinished
self
The entire response body has been reported by OnBodyData(), the response has finished.
-
OnError
self, ErrorMsg
Called whenever an error is detected. After this call, no other callback will get called.
-
OnRedirecting
self, NewUrl
Called if the server returned a valid redirection HTTP status code and a Location header, and redirection is allowed by the Options.
-
-
- The following example is adapted from the Debuggers plugin's "download" command, it downloads the
- contents of an URL into a file.
-
-function HandleConsoleDownload(a_Split) -- Console command handler
- -- Read the params from the command:
- local url = a_Split[2]
- local fnam = a_Split[3]
- if (not(url) or not(fnam)) then
- return true, "Missing parameters. Usage: download "
- end
-
- -- Define the cUrlClient callbacks
- local callbacks =
- {
- OnStatusLine = function (self, a_HttpVersion, a_Status, a_Rest)
- -- Only open the output file if the server reports a success:
- if (a_Status ~= 200) then
- LOG("Cannot download " .. url .. ", HTTP error code " .. a_Status)
- return
- end
- local f, err = io.open(fnam, "wb")
- if not(f) then
- LOG("Cannot download " .. url .. ", error opening the file " .. fnam .. ": " .. (err or ""))
- return
- end
- self.m_File = f
- end,
-
- OnBodyData = function (self, a_Data)
- -- If the file has been opened, write the data:
- if (self.m_File) then
- self.m_File:write(a_Data)
- end
- end,
-
- OnBodyFinished = function (self)
- -- If the file has been opened, close it and report success
- if (self.m_File) then
- self.m_File:close()
- LOG("File " .. fnam .. " has been downloaded.")
- end
- end,
- }
-
- -- Start the URL download:
- local isSuccess, msg = cUrlClient:Get(url, callbacks)
- if not(isSuccess) then
- LOG("Cannot start an URL download: " .. (msg or ""))
- return true
- end
- return true
-end
-
-]],
- },
- {
- Header = "Options",
- Contents = [[
- The requests support the following options, specified in the optional Options table parameter:
-
-
Option name
Description
-
MaxRedirects
Maximum number of HTTP redirects that the cUrlClient will follow. If the server still reports a redirect after reaching this many redirects, the cUrlClient reports an error. May be specified as either a number or a string parsable into a number. Default: 30.
-
OwnCert
The client certificate to use, if requested by the server. A string containing a PEM- or DER-encoded cert is expected.
-
OwnPrivKey
The private key appropriate for OwnCert. A string containing a PEM- or DER-encoded private key is expected.
-
OwnPrivKeyPassword
The password for OwnPrivKey. If not present or empty, no password is assumed.
-
-
- Redirection:
-
-
If a redirect is received, and redirection is allowed by MaxRedirects, the redirection is
- reported via OnRedirecting() callback and the request is restarted at the redirect URL, without
- reporting any of the redirect's headers nor body.
-
If a redirect is received and redirection is not allowed (maximum redirection attempts have
- been reached), the OnRedirecting() callback is called with the redirect URL and then the request
- terminates with an OnError() callback, without reporting the redirect's headers nor body.
-
- ]],
- },
- },
- },
-}
diff --git a/world/Plugins/APIDump/Classes/Plugins.lua b/world/Plugins/APIDump/Classes/Plugins.lua
deleted file mode 100644
index 7f69a8c9..00000000
--- a/world/Plugins/APIDump/Classes/Plugins.lua
+++ /dev/null
@@ -1,997 +0,0 @@
-return
-{
- cPlugin =
- {
- Desc = "cPlugin describes a Lua plugin. Each plugin has its own cPlugin object.",
- Functions =
- {
- GetDirectory =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "OBSOLETE, use GetFolderName() instead!",
- },
- GetFolderName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the folder where the plugin's files are. (APIDump)",
- },
- GetLoadError =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "If the plugin failed to load, returns the error message for the failure.",
- },
- GetLocalDirectory =
- {
- Notes = "OBSOLETE, use GetLocalFolder instead.",
- },
- GetLocalFolder =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the path where the plugin's files are. (Plugins/APIDump)",
- },
- GetName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the plugin.",
- },
- GetStatus =
- {
- Returns =
- {
- {
- Name = "PluginStatus",
- Type = "cPluginManager#PluginStatus",
- },
- },
- Notes = "Returns the status of the plugin (loaded, disabled, unloaded, error, not found)",
- },
- GetVersion =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the version of the plugin.",
- },
- IsLoaded =
- {
- Notes = "",
- },
- SetName =
- {
- Params =
- {
- {
- Name = "PluginApiName",
- Type = "string",
- },
- },
- Notes = "Sets the API name of the Plugin that is used by {{cPluginManager}}:CallPlugin() to identify the plugin.",
- },
- SetVersion =
- {
- Params =
- {
- {
- Name = "PluginApiVersion",
- Type = "number",
- },
- },
- Notes = "Sets the API version of the plugin. Currently unused.",
- },
- },
- },
- cPluginLua =
- {
- Desc = "(OBSOLETE) This class is no longer useful in the API and will be removed as soon as all core plugins are migrated away from it. The {{cPlugin}} class serves as the main plugin instance's interface.",
- Functions =
- {
- AddWebTab =
- {
- Params =
- {
- {
- Name = "Title",
- Type = "string",
- },
- {
- Name = "HandlerFn",
- Type = "function",
- },
- },
- Notes = "OBSOLETE - Use {{cWebAdmin}}:AddWebTab() instead.",
- },
- },
- Inherits = "cPlugin",
- },
- cPluginManager =
- {
- Desc = [[
- This class is used for generic plugin-related functionality. The plugin manager has a list of all
- plugins, can enable or disable plugins, manages hooks and in-game console commands.
-
- Plugins can be identified by either the PluginFolder or PluginName. Note that these two can differ,
- refer to the forum for detailed discussion.
-
- There is one instance of cPluginManager in Cuberite, to get it, call either
- {{cRoot|cRoot}}:Get():GetPluginManager() or cPluginManager:Get() function.
-
- Note that some functions are "static", that means that they are called using a dot operator instead
- of the colon operator. For example:
-
- ]],
- Functions =
- {
- AddHook =
- {
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "HookType",
- Type = "cPluginManager#PluginHook",
- },
- {
- Name = "Callback",
- Type = "function",
- IsOptional = true,
- },
- },
- Notes = "Informs the plugin manager that it should call the specified function when the specified hook event occurs. If a function is not specified, a default global function name is looked up, based on the hook type",
- },
- },
- BindCommand =
- {
- {
- Params =
- {
- {
- Name = "Command",
- Type = "string",
- },
- {
- Name = "Permission",
- Type = "string",
- },
- {
- Name = "Callback",
- Type = "function",
- },
- {
- Name = "HelpString",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Binds an in-game command with the specified callback function, permission and help string. By common convention, providing an empty string for HelpString will hide the command from the /help display. Returns true if successful, logs to console and returns no value on error. The callback uses the following signature:
function(Split, {{cPlayer|Player}})
The Split parameter contains an array-table of the words that the player has sent, Player is the {{cPlayer}} object representing the player who sent the command. If the callback returns true, the command is assumed to have executed successfully; in all other cases the server sends a warning to the player that the command is unknown (this is so that subcommands can be implemented).",
- },
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Command",
- Type = "string",
- },
- {
- Name = "Permission",
- Type = "string",
- },
- {
- Name = "Callback",
- Type = "function",
- },
- {
- Name = "HelpString",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Binds an in-game command with the specified callback function, permission and help string. By common convention, providing an empty string for HelpString will hide the command from the /help display. Returns true if successful, logs to console and returns no value on error. The callback uses the following signature:
function(Split, {{cPlayer|Player}})
The Split parameter contains an array-table of the words that the player has sent, Player is the {{cPlayer}} object representing the player who sent the command. If the callback returns true, the command is assumed to have executed successfully; in all other cases the server sends a warning to the player that the command is unknown (this is so that subcommands can be implemented).",
- },
- },
- BindConsoleCommand =
- {
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Command",
- Type = "string",
- },
- {
- Name = "Callback",
- Type = "function",
- },
- {
- Name = "HelpString",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- IsOptional = true,
- },
- },
- Notes = "Binds a console command with the specified callback function and help string. By common convention, providing an empty string for HelpString will hide the command from the \"help\" console command. Returns true if successful, logs to console and returns no value on error. The callback uses the following signature:
function(Split)
The Split parameter contains an array-table of the words that the admin has typed. If the callback returns true, the command is assumed to have executed successfully; in all other cases the server issues a warning to the console that the command is unknown (this is so that subcommands can be implemented).",
- },
- {
- Params =
- {
- {
- Name = "Command",
- Type = "string",
- },
- {
- Name = "Callback",
- Type = "function",
- },
- {
- Name = "HelpString",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- IsOptional = true,
- },
- },
- Notes = "Binds a console command with the specified callback function and help string. By common convention, providing an empty string for HelpString will hide the command from the \"help\" console command. Returns true if successful, logs to console and returns no value on error. The callback uses the following signature:
function(Split)
The Split parameter contains an array-table of the words that the admin has typed. If the callback returns true, the command is assumed to have executed successfully; in all other cases the server issues a warning to the console that the command is unknown (this is so that subcommands can be implemented).",
- },
- },
- CallPlugin =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "PluginName",
- Type = "string",
- },
- {
- Name = "FunctionName",
- Type = "string",
- },
- {
- Name = "FunctionArgs...",
- Type = "...",
- IsOptional = true,
- },
- },
- Returns =
- {
- {
- Name = "FunctionRets",
- Type = "...",
- IsOptional = true,
- },
- },
- Notes = "Calls the specified function in the specified plugin, passing all the given arguments to it. If it succeeds, it returns all the values returned by that function. If it fails, returns no value at all. Note that only strings, numbers, bools, nils, API classes and simple tables can be used for parameters and return values; functions cannot be copied across plugins.",
- },
- DoWithPlugin =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "PluginName",
- Type = "string",
- },
- {
- Name = "CallbackFn",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the CallbackFn for the specified plugin, if found. A plugin can be found even if it is currently unloaded, disabled or errored, the callback should check the plugin status. If the plugin is not found, this function returns false, otherwise it returns the bool value that the callback has returned. The CallbackFn has the following signature:
function ({{cPlugin|Plugin}})
",
- },
- ExecuteCommand =
- {
- Params =
- {
- {
- Name = "Player",
- Type = "cPlayer",
- },
- {
- Name = "CommandStr",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "CommandResult",
- Type = "cPluginManager#CommandResult",
- },
- },
- Notes = "Executes the command as if given by the specified Player. Checks permissions.",
- },
- ExecuteConsoleCommand =
- {
- Params =
- {
- {
- Name = "CommandStr",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- {
- Type = "string",
- },
- },
- Notes = "Executes the console command as if given by the admin on the console. If the command is successfully executed, returns true and the text that would be output to the console normally. On error it returns false and an error message.",
- },
- FindPlugins =
- {
- Notes = "OBSOLETE, use RefreshPluginList() instead",
- },
- ForceExecuteCommand =
- {
- Params =
- {
- {
- Name = "Player",
- Type = "cPlayer",
- },
- {
- Name = "CommandStr",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "CommandResult",
- Type = "cPluginManager#CommandResult",
- },
- },
- Notes = "Same as ExecuteCommand, but doesn't check permissions",
- },
- ForEachCommand =
- {
- Params =
- {
- {
- Name = "CallbackFn",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the CallbackFn function for each command that has been bound using BindCommand(). The CallbackFn has the following signature:
function(Command, Permission, HelpString)
If the callback returns true, the enumeration is aborted and this API function returns false; if it returns false or no value, the enumeration continues with the next command, and the API function returns true.",
- },
- ForEachConsoleCommand =
- {
- Params =
- {
- {
- Name = "CallbackFn",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the CallbackFn function for each command that has been bound using BindConsoleCommand(). The CallbackFn has the following signature:
function (Command, HelpString)
If the callback returns true, the enumeration is aborted and this API function returns false; if it returns false or no value, the enumeration continues with the next command, and the API function returns true.",
- },
- ForEachPlugin =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "CallbackFn",
- Type = "function",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Calls the CallbackFn function for each plugin that is currently discovered by Cuberite (including disabled, unloaded and errrored plugins). The CallbackFn has the following signature:
function ({{cPlugin|Plugin}})
If the callback returns true, the enumeration is aborted and this API function returns false; if it returns false or no value, the enumeration continues with the next command, and the API function returns true.",
- },
- Get =
- {
- IsStatic = true,
- Returns =
- {
- {
- Type = "cPluginManager",
- },
- },
- Notes = "Returns the single instance of the plugin manager",
- },
- GetAllPlugins =
- {
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns a table (dictionary) of all plugins, [name => value], where value is a valid {{cPlugin}} if the plugin is loaded, or the bool value false if the plugin is not loaded.",
- },
- GetCommandPermission =
- {
- Params =
- {
- {
- Name = "Command",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Name = "Permission",
- Type = "string",
- },
- },
- Notes = "Returns the permission needed for executing the specified command",
- },
- GetCurrentPlugin =
- {
- Returns =
- {
- {
- Type = "cPlugin",
- },
- },
- Notes = "Returns the {{cPlugin}} object for the calling plugin. This is the same object that the Initialize function receives as the argument.",
- },
- GetNumLoadedPlugins =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of loaded plugins (psLoaded only)",
- },
- GetNumPlugins =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of plugins, including the disabled, errored, unloaded and not-found ones",
- },
- GetPlugin =
- {
- Params =
- {
- {
- Name = "PluginName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "cPlugin",
- },
- },
- Notes = "(DEPRECATED, UNSAFE) Returns a plugin handle of the specified plugin, or nil if such plugin is not loaded. Note thatdue to multithreading the handle is not guaranteed to be safe for use when stored - a single-plugin reload may have been triggered in the mean time for the requested plugin.",
- },
- GetPluginFolderName =
- {
- Params =
- {
- {
- Name = "PluginName",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the folder from which the plugin was loaded (without the \"Plugins\" part). Used as a plugin's display name.",
- },
- GetPluginsPath =
- {
- IsStatic = true,
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the path where the individual plugin folders are located. Doesn't include the path separator at the end of the returned string.",
- },
- IsCommandBound =
- {
- Params =
- {
- {
- Name = "Command",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if in-game Command is already bound (by any plugin)",
- },
- IsConsoleCommandBound =
- {
- Params =
- {
- {
- Name = "Command",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if console Command is already bound (by any plugin)",
- },
- IsPluginLoaded =
- {
- Params =
- {
- {
- Name = "PluginName",
- Type = "string",
- },
- },
- Notes = "Returns true if the specified plugin is loaded.",
- },
- LoadPlugin =
- {
- Params =
- {
- {
- Name = "PluginFolder",
- Type = "string",
- },
- },
- Notes = "(DEPRECATED) Loads a plugin from the specified folder. NOTE: Loading plugins may be an unsafe operation and may result in a deadlock or a crash. This API is deprecated and might be removed.",
- },
- LogStackTrace =
- {
- IsStatic = true,
- Notes = "Logs a current stack trace of the Lua engine to the server console log. Same format as is used when the plugin fails.",
- },
- RefreshPluginList =
- {
- Notes = "Refreshes the list of plugins to include all folders inside the Plugins folder (potentially new disabled plugins)",
- },
- ReloadPlugins =
- {
- Notes = "Reloads all active plugins",
- },
- UnloadPlugin =
- {
- Params =
- {
- {
- Name = "PluginName",
- Type = "string",
- },
- },
- Notes = "Queues the specified plugin to be unloaded. To avoid deadlocks, the unloading happens in the main tick thread asynchronously.",
- },
- },
- Constants =
- {
- crBlocked =
- {
- Notes = "When a plugin stopped the command using the OnExecuteCommand hook",
- },
- crError =
- {
- Notes = "When the command handler for the given command results in an error",
- },
- crExecuted =
- {
- Notes = "When the command is successfully executed.",
- },
- crNoPermission =
- {
- Notes = "When the player doesn't have permission to execute the given command.",
- },
- crUnknownCommand =
- {
- Notes = "When the given command doesn't exist.",
- },
- HOOK_BLOCK_SPREAD =
- {
- Notes = "Called when a block spreads based on world conditions",
- },
- HOOK_BLOCK_TO_PICKUPS =
- {
- Notes = "Called when a block has been dug and is being converted to pickups. The server has provided the default pickups and the plugins may modify them.",
- },
- HOOK_BREWING_COMPLETED =
- {
- Notes = "Called when a brewing stand completed a brewing process.",
- },
- HOOK_BREWING_COMPLETING =
- {
- Notes = "Called before a brewing stand completes a brewing process.",
- },
- HOOK_CHAT =
- {
- Notes = "Called when a client sends a chat message that is not a command. The plugin may modify the chat message",
- },
- HOOK_CHUNK_AVAILABLE =
- {
- Notes = "Called when a chunk is loaded or generated and becomes available in the {{cWorld|world}}.",
- },
- HOOK_CHUNK_GENERATED =
- {
- Notes = "Called after a chunk is generated. A plugin may do last modifications on the generated chunk before it is handed of to the {{cWorld|world}}.",
- },
- HOOK_CHUNK_GENERATING =
- {
- Notes = "Called before a chunk is generated. A plugin may override some parts of the generation algorithm.",
- },
- HOOK_CHUNK_UNLOADED =
- {
- Notes = "Called after a chunk has been unloaded from a {{cWorld|world}}.",
- },
- HOOK_CHUNK_UNLOADING =
- {
- Notes = "Called before a chunk is unloaded from a {{cWorld|world}}. The chunk has already been saved.",
- },
- HOOK_COLLECTING_PICKUP =
- {
- Notes = "Called when a player is about to collect a pickup.",
- },
- HOOK_CRAFTING_NO_RECIPE =
- {
- Notes = "Called when a player has items in the crafting slots and the server cannot locate any recipe. Plugin may provide a recipe.",
- },
- HOOK_DISCONNECT =
- {
- Notes = "Called after the player has disconnected.",
- },
- HOOK_ENTITY_ADD_EFFECT =
- {
- Notes = "Called when an effect is being added to an {{cEntity|entity}}. Plugin may refuse the effect.",
- },
- HOOK_ENTITY_CHANGED_WORLD =
- {
- Notes = "Called after a entity has changed the world.",
- },
- HOOK_ENTITY_CHANGING_WORLD =
- {
- Notes = "Called before a entity has changed the world. Plugin may disallow a entity to change the world.",
- },
- HOOK_ENTITY_TELEPORT =
- {
- Notes = "Called when an {{cEntity|entity}} is being teleported. Plugin may refuse the teleportation.",
- },
- HOOK_EXECUTE_COMMAND =
- {
- Notes = "Called when a client sends a chat message that is recognized as a command, before handing that command to the regular command handler. A plugin may stop the command from being handled. This hook is called even when the player doesn't have permissions for the command.",
- },
- HOOK_EXPLODED =
- {
- Notes = "Called after an explosion has been processed in a {{cWorld|world}}.",
- },
- HOOK_EXPLODING =
- {
- Notes = "Called before an explosion is processed in a {{cWorld|world}}. A plugin may alter the explosion parameters or cancel the explosion altogether.",
- },
- HOOK_HANDSHAKE =
- {
- Notes = "Called when a Handshake packet is received from a client.",
- },
- HOOK_HOPPER_PULLING_ITEM =
- {
- Notes = "Called when a hopper is pulling an item from the container above it.",
- },
- HOOK_HOPPER_PUSHING_ITEM =
- {
- Notes = "Called when a hopper is pushing an item into the container it is aimed at.",
- },
- HOOK_KILLED =
- {
- Notes = "Called when an entity has been killed.",
- },
- HOOK_KILLING =
- {
- Notes = "Called when an entity has just been killed. A plugin may resurrect the entity by setting its health to above zero.",
- },
- HOOK_LOGIN =
- {
- Notes = "Called when a Login packet is sent to the client, before the client is queued for authentication.",
- },
- HOOK_PLAYER_ANIMATION =
- {
- Notes = "Called when a client send the Animation packet.",
- },
- HOOK_PLAYER_BREAKING_BLOCK =
- {
- Notes = "Called when a player is about to break a block. A plugin may cancel the event.",
- },
- HOOK_PLAYER_BROKEN_BLOCK =
- {
- Notes = "Called after a player has broken a block.",
- },
- HOOK_PLAYER_DESTROYED =
- {
- Notes = "Called when the {{cPlayer}} object is destroyed - a player has disconnected.",
- },
- HOOK_PLAYER_EATING =
- {
- Notes = "Called when the player starts eating a held item. Plugins may abort the eating.",
- },
- HOOK_PLAYER_FISHED =
- {
- Notes = "Called when the player reels the fishing rod back in, after the server decides the player's fishing reward.",
- },
- HOOK_PLAYER_FISHING =
- {
- Notes = "Called when the player reels the fishing rod back in, plugins may alter the fishing reward.",
- },
- HOOK_PLAYER_FOOD_LEVEL_CHANGE =
- {
- Notes = "Called when the player's food level is changing. Plugins may refuse the change.",
- },
- HOOK_PLAYER_JOINED =
- {
- Notes = "Called when the player entity has been created. It has not yet been fully initialized.",
- },
- HOOK_PLAYER_LEFT_CLICK =
- {
- Notes = "Called when the client sends the LeftClick packet.",
- },
- HOOK_PLAYER_MOVING =
- {
- Notes = "Called when the player has moved and the movement is now being applied.",
- },
- HOOK_PLAYER_PLACED_BLOCK =
- {
- Notes = "Called when the player has just placed a block",
- },
- HOOK_PLAYER_PLACING_BLOCK =
- {
- Notes = "Called when the player is about to place a block. A plugin may cancel the event.",
- },
- HOOK_PLAYER_RIGHT_CLICK =
- {
- Notes = "Called when the client sends the RightClick packet.",
- },
- HOOK_PLAYER_RIGHT_CLICKING_ENTITY =
- {
- Notes = "Called when the client sends the UseEntity packet.",
- },
- HOOK_PLAYER_SHOOTING =
- {
- Notes = "Called when the player releases the mouse button to fire their bow.",
- },
- HOOK_PLAYER_SPAWNED =
- {
- Notes = "Called after the player entity has been created. The entity is fully initialized and is spawning in the {{cWorld|world}}.",
- },
- HOOK_PLAYER_TOSSING_ITEM =
- {
- Notes = "Called when the player is tossing the held item (keypress Q)",
- },
- HOOK_PLAYER_USED_BLOCK =
- {
- Notes = "Called after the player has right-clicked a block",
- },
- HOOK_PLAYER_USED_ITEM =
- {
- Notes = "Called after the player has right-clicked with a usable item in their hand.",
- },
- HOOK_PLAYER_USING_BLOCK =
- {
- Notes = "Called when the player is about to use (right-click) a block",
- },
- HOOK_PLAYER_USING_ITEM =
- {
- Notes = "Called when the player is about to right-click with a usable item in their hand.",
- },
- HOOK_PLUGIN_MESSAGE =
- {
- Notes = "Called when a PluginMessage packet is received from a client.",
- },
- HOOK_PLUGINS_LOADED =
- {
- Notes = "Called after all plugins have loaded.",
- },
- HOOK_POST_CRAFTING =
- {
- Notes = "Called after a valid recipe has been chosen for the current contents of the crafting grid. Plugins may modify the recipe.",
- },
- HOOK_PRE_CRAFTING =
- {
- Notes = "Called before a recipe is searched for the current contents of the crafting grid. Plugins may provide a recipe and cancel the built-in search.",
- },
- HOOK_PROJECTILE_HIT_BLOCK =
- {
- Notes = "Called when a {{cProjectileEntity|projectile}} hits a block.",
- },
- HOOK_PROJECTILE_HIT_ENTITY =
- {
- Notes = "Called when a {{cProjectileEntity|projectile}} hits an {{cEntity|entity}}.",
- },
- HOOK_SERVER_PING =
- {
- Notes = "Called when a client pings the server from the server list. Plugins may change the favicon, server description, players online and maximum players values.",
- },
- HOOK_SPAWNED_ENTITY =
- {
- Notes = "Called after an entity is spawned in a {{cWorld|world}}. The entity is already part of the world.",
- },
- HOOK_SPAWNED_MONSTER =
- {
- Notes = "Called after a mob is spawned in a {{cWorld|world}}. The mob is already part of the world.",
- },
- HOOK_SPAWNING_ENTITY =
- {
- Notes = "Called just before an entity is spawned in a {{cWorld|world}}.",
- },
- HOOK_SPAWNING_MONSTER =
- {
- Notes = "Called just before a mob is spawned in a {{cWorld|world}}.",
- },
- HOOK_TAKE_DAMAGE =
- {
- Notes = "Called when an entity is taking any kind of damage. Plugins may modify the damage value, effects, source or cancel the damage.",
- },
- HOOK_TICK =
- {
- Notes = "Called when the main server thread ticks - 20 times a second.",
- },
- HOOK_UPDATED_SIGN =
- {
- Notes = "Called after a {{cSignEntity|sign}} text has been updated, either by a player or by any external means.",
- },
- HOOK_UPDATING_SIGN =
- {
- Notes = "Called before a {{cSignEntity|sign}} text is updated, either by a player or by any external means.",
- },
- HOOK_WEATHER_CHANGED =
- {
- Notes = "Called after the weather has changed.",
- },
- HOOK_WEATHER_CHANGING =
- {
- Notes = "Called just before the weather changes",
- },
- HOOK_WORLD_STARTED =
- {
- Notes = "Called when a world has been started.",
- },
- HOOK_WORLD_TICK =
- {
- Notes = "Called in each world's tick thread when the game logic is about to tick (20 times a second).",
- },
- psDisabled =
- {
- Notes = "The plugin is not enabled in settings.ini",
- },
- psError =
- {
- Notes = "The plugin is enabled in settings.ini, but it has run into an error while loading. Use {{cPlugin}}:GetLoadError() to identify the error.",
- },
- psLoaded =
- {
- Notes = "The plugin is enabled and loaded.",
- },
- psNotFound =
- {
- Notes = "The plugin has been loaded, but is no longer present on disk.",
- },
- psUnloaded =
- {
- Notes = "The plugin is enabled in settings.ini, but it has been unloaded (by a command).",
- },
- },
- ConstantGroups =
- {
- CommandResult =
- {
- Include =
- {
- "^cr.*",
- },
- TextBefore = "Results that the (Force)ExecuteCommand functions return. This gives information whether the command was executed or not, and the reason.",
- },
- PluginHook =
- {
- Include =
- {
- "HOOK_.*",
- },
- TextBefore = [[
- These constants identify individual hooks. To register the plugin to receive notifications on hooks, use the
- cPluginManager:AddHook() function. For detailed description of each hook, see the
- hooks reference.]],
- },
- PluginStatus =
- {
- Include =
- {
- "ps.*",
- },
- TextBefore = [[
- These constants are used to report status of individual plugins. Use {{cPlugin}}:GetStatus() to query the
- status of a plugin; use cPluginManager::ForEachPlugin() to iterate over plugins.]],
- },
- },
- },
-}
diff --git a/world/Plugins/APIDump/Classes/Projectiles.lua b/world/Plugins/APIDump/Classes/Projectiles.lua
deleted file mode 100644
index b92f6d2a..00000000
--- a/world/Plugins/APIDump/Classes/Projectiles.lua
+++ /dev/null
@@ -1,457 +0,0 @@
-return
-{
- cArrowEntity =
- {
- Desc = [[
- Represents the arrow when it is shot from the bow. A subclass of the {{cProjectileEntity}}.
- ]],
- Functions =
- {
- CanPickup =
- {
- Params =
- {
- {
- Name = "Player",
- Type = "cPlayer",
- },
- },
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the specified player can pick the arrow when it's on the ground",
- },
- GetBlockHit =
- {
- Desc = "Gets the block arrow is in",
- Returns =
- {
- {
- Type = "Vector3i",
- },
- },
- },
- GetDamageCoeff =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the damage coefficient stored within the arrow. The damage dealt by this arrow is multiplied by this coeff",
- },
- GetPickupState =
- {
- Returns =
- {
- {
- Type = "cArrowEntity#ePickupState",
- },
- },
- Notes = "Returns the pickup state (one of the psXXX constants, above)",
- },
- IsCritical =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- Notes = "Returns true if the arrow should deal critical damage. Based on the bow charge when the arrow was shot.",
- },
- SetDamageCoeff =
- {
- Params =
- {
- {
- Name = "DamageCoeff",
- Type = "number",
- },
- },
- Notes = "Sets the damage coefficient. The damage dealt by this arrow is multiplied by this coeff",
- },
- SetIsCritical =
- {
- Params =
- {
- {
- Name = "IsCritical",
- Type = "boolean",
- },
- },
- Notes = "Sets the IsCritical flag on the arrow. Critical arrow deal additional damage",
- },
- SetPickupState =
- {
- Params =
- {
- {
- Name = "PickupState",
- Type = "cArrowEntity#ePickupState",
- },
- },
- Notes = "Sets the pickup state (one of the psXXX constants, above)",
- },
- },
- Constants =
- {
- psInCreative =
- {
- Notes = "The arrow can be picked up only by players in creative gamemode",
- },
- psInSurvivalOrCreative =
- {
- Notes = "The arrow can be picked up by players in survival or creative gamemode",
- },
- psNoPickup =
- {
- Notes = "The arrow cannot be picked up at all",
- },
- },
- ConstantGroups =
- {
- ePickupState =
- {
- Include = "ps.*",
- TextBefore = [[
- The following constants are used to signalize whether the arrow, once it lands, can be picked by
- players:
- ]],
- },
- },
- Inherits = "cProjectileEntity",
- },
- cExpBottleEntity =
- {
- Desc = [[
- Represents a thrown ExpBottle. A subclass of the {{cProjectileEntity}}.
- ]],
- Functions =
- {
-
- },
- Inherits = "cProjectileEntity",
- },
- cFireChargeEntity =
- {
- Desc = [[
- Represents a fire charge that has been shot by a Blaze or a {{cDispenserEntity|Dispenser}}. A subclass
- of the {{cProjectileEntity}}.
- ]],
- Functions =
- {
-
- },
- Inherits = "cProjectileEntity",
- },
- cFireworkEntity =
- {
- Desc = [[
- Represents a firework rocket.
- ]],
- Functions =
- {
- GetItem =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Returns the item that has been used to create the firework rocket. The item's m_FireworkItem member contains all the firework-related data.",
- },
- GetTicksToExplosion =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the number of ticks left until the firework explodes.",
- },
- SetItem =
- {
- Params =
- {
- {
- Name = "FireworkItem",
- Type = "cItem",
- },
- },
- Notes = "Sets a new item to be used for the firework.",
- },
- SetTicksToExplosion =
- {
- Params =
- {
- {
- Name = "NumTicks",
- Type = "number",
- },
- },
- Notes = "Sets the number of ticks left until the firework explodes.",
- },
- },
- Inherits = "cProjectileEntity",
- },
- cGhastFireballEntity =
- {
- Desc = "",
- Functions =
- {
-
- },
- Inherits = "cProjectileEntity",
- },
- cProjectileEntity =
- {
- Desc = "Base class for all projectiles, such as arrows and fireballs.",
- Functions =
- {
- GetCreator =
- {
- Returns =
- {
- {
- Type = "cEntity",
- },
- },
- Notes = "Returns the entity who created this projectile. May return nil.",
- },
- GetCreatorName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the name of the player that created the projectile. Will be empty for non-player creators",
- },
- GetCreatorUniqueID =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the unique ID of the entity who created this projectile, or {{cEntity#INVALID_ID|cEntity.INVALID_ID}} if the projectile wasn't created by an entity.",
- },
- GetMCAClassName =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the string that identifies the projectile type (class name) in MCA files",
- },
- GetProjectileKind =
- {
- Returns =
- {
- {
- Type = "cProjectileEntity#eKind",
- },
- },
- Notes = "Returns the kind of this projectile (pkXXX constant)",
- },
- IsInGround =
- {
- Returns =
- {
- {
- Type = "boolean",
- },
- },
- 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 {{cExpBottleEntity|thrown exp bottle}}",
- },
- pkFireCharge =
- {
- Notes = "The projectile is a {{cFireChargeEntity|fire charge}}",
- },
- pkFirework =
- {
- Notes = "The projectile is a (flying) {{cFireworkEntity|firework}}",
- },
- pkFishingFloat =
- {
- Notes = "The projectile is a {{cFloater|fishing float}}",
- },
- pkGhastFireball =
- {
- Notes = "The projectile is a {{cGhastFireballEntity|ghast fireball}}",
- },
- pkSnowball =
- {
- Notes = "The projectile is a {{cThrownSnowballEntity|thrown snowball}}",
- },
- pkSplashPotion =
- {
- Notes = "The projectile is a {{cSplashPotionEntity|thrown splash potion}}",
- },
- pkWitherSkull =
- {
- Notes = "The projectile is a {{cWitherSkullEntity|wither skull}}",
- },
- },
- ConstantGroups =
- {
- eKind =
- {
- Include = "pk.*",
- TextBefore = "The following constants are used to distinguish between the different projectile kinds:",
- },
- },
- Inherits = "cEntity",
- },
- cSplashPotionEntity =
- {
- Desc = [[
- Represents a thrown splash potion.
- ]],
- Functions =
- {
- GetEntityEffect =
- {
- Returns =
- {
- {
- Type = "cEntityEffect",
- },
- },
- Notes = "Returns the entity effect in this potion",
- },
- GetEntityEffectType =
- {
- Returns =
- {
- {
- Type = "cEntityEffect",
- },
- },
- Notes = "Returns the effect type of this potion",
- },
- GetItem =
- {
- Returns =
- {
- {
- Type = "cItem",
- },
- },
- Notes = "Gets the potion item that was thrown.",
- },
- GetPotionColor =
- {
- Returns =
- {
- {
- Type = "number",
- },
- },
- Notes = "Returns the color index of the particles emitted by this potion",
- },
- SetEntityEffect =
- {
- Params =
- {
- {
- Name = "EntityEffect",
- Type = "cEntityEffect",
- },
- },
- Notes = "Sets the entity effect for this potion",
- },
- SetEntityEffectType =
- {
- Params =
- {
- {
- Name = "EntityEffectType",
- Type = "cEntityEffect#eType",
- },
- },
- Notes = "Sets the effect type of this potion",
- },
- SetPotionColor =
- {
- Params =
- {
- {
- Name = "PotionColor",
- Type = "number",
- },
- },
- Notes = "Sets the color index of the particles for this potion",
- },
- },
- Inherits = "cProjectileEntity",
- },
- cThrownEggEntity =
- {
- Desc = [[
- Represents a thrown egg.
- ]],
- Functions =
- {
-
- },
- Inherits = "cProjectileEntity",
- },
- cThrownEnderPearlEntity =
- {
- Desc = "Represents a thrown ender pearl.",
- Functions =
- {
-
- },
- Inherits = "cProjectileEntity",
- },
- cThrownSnowballEntity =
- {
- Desc = "Represents a thrown snowball.",
- Functions =
- {
-
- },
- Inherits = "cProjectileEntity",
- },
- cWitherSkullEntity =
- {
- Desc = "Represents a wither skull being shot.",
- Functions =
- {
-
- },
- Inherits = "cProjectileEntity",
- },
-}
diff --git a/world/Plugins/APIDump/Classes/WebAdmin.lua b/world/Plugins/APIDump/Classes/WebAdmin.lua
deleted file mode 100644
index faa81dc8..00000000
--- a/world/Plugins/APIDump/Classes/WebAdmin.lua
+++ /dev/null
@@ -1,227 +0,0 @@
-return
-{
- cWebAdmin =
- {
- Desc = "",
- Functions =
- {
- AddWebTab =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Title",
- Type = "string",
- },
- {
- Name = "UrlPath",
- Type = "string",
- },
- {
- Name = "HandlerFn",
- Type = "function",
- },
- },
- Notes = "Adds a new web tab to webadmin. The tab uses \"Title\" as its display string and is identified in the URL using the UrlPath (https://server.domain.com/webadmin/{PluginName}/{UrlPath}). The HandlerFn is the callback function that is called when the admin accesses the page, it has the following signature:
function ({{a_Request|HTTPRequest}}, a_UrlPath) return Content, ContentType end
URLPath must not contain a '/', the recommendation is to use only 7-bit-clean ASCII character set.",
- },
- GetAllWebTabs =
- {
- IsStatic = true,
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns an array-table with each item describing a web tab, for all web tabs registered in the WebAdmin, for all plugins. The returned table has the following format:
{ { PluginName = \"Plugin's API name\", UrlPath = \"UrlPath given to AddWebTab\", Title = \"Title given to AddWebTab\", }, ... }",
- },
- GetBaseURL =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "URL",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the string that is the path of the base webadmin (\"../../../webadmin\") relative to the given URL.",
- },
- GetContentTypeFromFileExt =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "FileExt",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the content-type that should be used for files with the specified extension (without the dot), such as \"text/plain\" for the \"txt\" extension. If the extension is not known, returns an empty string.",
- },
- GetHTMLEscapedString =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Input",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Gets the HTML-escaped representation of a requested string. This is useful for user input and game data that is not guaranteed to be escaped already.",
- },
- GetPage =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "HTTPRequest",
- Type = "Request",
- },
- },
- Returns =
- {
- {
- Type = "table",
- },
- },
- Notes = "Returns the (inner HTML) page contents for the specified request. Calls the appropriate WebTab handler registered via AddWebTab() and returns the information from that plugin wrapped in a table with the following structure:
{ Content = \"\", -- Content returned by the plugin ContentType = \"\", -- Content type returned by the plugin, or \"text/html\" if none returned UrlPath = \"\", -- UrlPath decoded from the request TabTitle = \"\", -- Title of the tab that handled the request, as given to AddWebTab() PluginName = \"\", -- API name of the plugin that handled the request PluginFolder = \"\", -- Folder name (= display name) of the plugin that handled the request }
This function is mainly used in the webadmin template file.",
- },
- GetPorts =
- {
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns a comma-separated list of ports on which the webadmin is configured to listen. Note that this list does include ports that may currently be unavailable (another server was already listening on them prior to launching Cuberite).",
- },
- GetURLEncodedString =
- {
- IsStatic = true,
- Params =
- {
- {
- Name = "Input",
- Type = "string",
- },
- },
- Returns =
- {
- {
- Type = "string",
- },
- },
- Notes = "Returns the string given to it escaped by URL encoding, which makes the string suitable for transmission in an URL. Invalid characters are turned into \"%xy\" values.",
- },
- Reload =
- {
- Notes = "Reloads the webadmin's config - the allowed logins, the template script and the login page. Note that reloading will not change the \"enabled\" state of the server, and it will not update listening ports. Existing WebTabs will be kept registered even after the reload.",
- },
- },
- },
- 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.",
- },
- },
- },
- 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
- {{cPluginLua}}:AddWebPage().
- ]],
- Constants =
- {
- 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.",
- },
- FormData =
- {
- Notes = "Array-table of {{HTTPFormData}}, contains the values of individual form elements submitted by the client",
- },
- 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)",
- },
- URL =
- {
- Type = "string",
- Notes = "The entire URL used for the request.",
- },
- Username =
- {
- Type = "string",
- Notes = "Name of the logged-in user.",
- },
- },
- },
- HTTPTemplateRequest =
- {
- Desc = [[
-This class is used only in the WebAdmin template script as the parameter to the function that provides the template.
- ]],
- Variables =
- {
- Request =
- {
- Type = "HTTPRequest",
- Notes = "The request for which the template is being built.",
- },
- },
- },
-}
diff --git a/world/Plugins/APIDump/Hooks/OnBlockSpread.lua b/world/Plugins/APIDump/Hooks/OnBlockSpread.lua
deleted file mode 100644
index 4d6dac21..00000000
--- a/world/Plugins/APIDump/Hooks/OnBlockSpread.lua
+++ /dev/null
@@ -1,56 +0,0 @@
-return
-{
- HOOK_BLOCK_SPREAD =
- {
- CalledWhen = "Called when a block spreads based on world conditions",
- DefaultFnName = "OnBlockSpread", -- also used as pagename
- Desc = [[
- This hook is called when a block spreads.
-
- The spread carries with it the type of its source - whether it's a block spreads.
- It also carries the identification of the actual source. The exact type of the identification
- depends on the source kind:
-
-
Source
Notes
-
ssFireSpread
Fire spreading
-
ssGrassSpread
Grass spreading
-
ssMushroomSpread
Mushroom spreading
-
ssMycelSpread
Mycel spreading
-
ssVineSpread
Vine spreading
-
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world in which the block resides" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
- { Name = "Source", Type = "eSpreadSource", Notes = "Source of the spread. See the table above." },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called, and finally
- Cuberite will process the spread. If the function
- returns true, no other callback is called for this event and the spread will not occur.
- ]],
- Examples =
- {
- {
- Title = "Stop fire spreading",
- Desc = "Stops fire from spreading, but does not remove any player-placed fire.",
- Code = [[
- function OnBlockSpread(World, BlockX, Blocky, BlockZ, source)
- if (source == ssFireSpread) then
- -- Return true to block the fire spreading.
- return true
- end
- -- We don't care about any other events, let them continue.
- return false
- end
-
- -- Add the callback.
- cPluginManager:AddHook(cPluginManager.HOOK_BLOCK_SPREAD, OnBlockSpread);
- ]],
- },
- },
- }, -- HOOK_BLOCK_SPREAD
-}
diff --git a/world/Plugins/APIDump/Hooks/OnBlockToPickups.lua b/world/Plugins/APIDump/Hooks/OnBlockToPickups.lua
deleted file mode 100644
index d404da07..00000000
--- a/world/Plugins/APIDump/Hooks/OnBlockToPickups.lua
+++ /dev/null
@@ -1,62 +0,0 @@
-return
-{
- HOOK_BLOCK_TO_PICKUPS =
- {
- CalledWhen = "A block is about to be dug ({{cPlayer|player}}, {{cEntity|entity}} or natural reason), plugins may override what pickups that will produce.",
- DefaultFnName = "OnBlockToPickups", -- also used as pagename
- Desc = [[
- This callback gets called whenever a block is about to be dug. This includes {{cPlayer|players}}
- digging blocks, entities causing blocks to disappear ({{cTNTEntity|TNT}}, Endermen) and natural
- causes (water washing away a block). Plugins may override the amount and kinds of pickups this
- action produces.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world in which the block resides" },
- { Name = "Digger", Type = "{{cEntity}} descendant", Notes = "The entity causing the digging. May be a {{cPlayer}}, {{cTNTEntity}} or even nil (natural causes)" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
- { Name = "BlockType", Type = "BLOCKTYPE", Notes = "Block type of the block" },
- { Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "Block meta of the block" },
- { Name = "Pickups", Type = "{{cItems}}", Notes = "Items that will be spawned as pickups" },
- },
- Returns = [[
- If the function returns false or no value, the next callback in the hook chain will be called. If
- the function returns true, no other callbacks in the chain will be called.
-
- Either way, the server will then spawn pickups specified in the Pickups parameter, so to disable
- pickups, you need to Clear the object first, then return true.
- ]],
- CodeExamples =
- {
- {
- Title = "Modify pickups",
- Desc = "This example callback function makes tall grass drop diamonds when digged by natural causes (washed away by water).",
- Code = [[
-function OnBlockToPickups(a_World, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_Pickups)
- if (a_Digger ~= nil) then
- -- Not a natural cause
- return false;
- end
- if (a_BlockType ~= E_BLOCK_TALL_GRASS) then
- -- Not a tall grass being washed away
- return false;
- end
-
- -- Remove all pickups suggested by Cuberite:
- a_Pickups:Clear();
-
- -- Drop a diamond:
- a_Pickups:Add(cItem(E_ITEM_DIAMOND));
- return true;
-end;
- ]],
- },
- } , -- CodeExamples
- }, -- HOOK_BLOCK_TO_PICKUPS
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnBrewingCompleted.lua b/world/Plugins/APIDump/Hooks/OnBrewingCompleted.lua
deleted file mode 100644
index 31622773..00000000
--- a/world/Plugins/APIDump/Hooks/OnBrewingCompleted.lua
+++ /dev/null
@@ -1,26 +0,0 @@
-return
-{
- HOOK_BREWING_COMPLETED =
- {
- CalledWhen = "A brewing process is completed.",
- DefaultFnName = "OnBrewingCompleted", -- also used as pagename
- Desc = [[
- This hook is called whenever a {{cBrewingstand|brewing stand}} has completed the brewing process.
- See also the {{OnBrewingCompleting|HOOK_BREWING_COMPLETING}} hook for a similar hook, is called when a
- brewing process is completing.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "World where the brewing stand resides." },
- { Name = "Brewingstand", Type = "{{cBrewingstand}}", Notes = "The brewing stand that completed the brewing process." },
- },
- Returns = [[
- If the function returns false or no value, Cuberite calls other plugins with this event. If the
- function returns true, no other plugin is called for this event.
- ]],
- }, -- HOOK_BREWING_COMPLETED
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnBrewingCompleting.lua b/world/Plugins/APIDump/Hooks/OnBrewingCompleting.lua
deleted file mode 100644
index 14429c8f..00000000
--- a/world/Plugins/APIDump/Hooks/OnBrewingCompleting.lua
+++ /dev/null
@@ -1,28 +0,0 @@
-return
-{
- HOOK_BREWING_COMPLETING =
- {
- CalledWhen = "A brewing process is completing.",
- DefaultFnName = "OnBrewingCompleting", -- also used as pagename
- Desc = [[
- This hook is called whenever a {{cBrewingstand|brewing stand}} is completing the brewing process. Plugins may
- refuse the completing of the brewing process.
- See also the {{OnBrewingCompleted|HOOK_BREWING_COMPLETED}} hook for a similar hook, is called after the
- brewing process has been completed.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "World where the brewing stand resides." },
- { Name = "Brewingstand", Type = "{{cBrewingstand}}", Notes = "The brewing stand that completes the brewing process." },
- },
- Returns = [[
- If the function returns false or no value, Cuberite calls other plugins with this event. If the function returns true,
- no other plugin's callback is called and the brewing process is canceled.
-
- ]],
- }, -- HOOK_BREWING_COMPLETING
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnChat.lua b/world/Plugins/APIDump/Hooks/OnChat.lua
deleted file mode 100644
index a15d09cc..00000000
--- a/world/Plugins/APIDump/Hooks/OnChat.lua
+++ /dev/null
@@ -1,30 +0,0 @@
-return
-{
- HOOK_CHAT =
- {
- CalledWhen = "Player sends a chat message",
- DefaultFnName = "OnChat", -- also used as pagename
- Desc = [[
- A plugin may implement an OnChat() function and register it as a Hook to process chat messages from
- the players. The function is then called for every in-game message sent from any player. Note that
- registered in-game commands are not sent through this hook. Use the
- {{OnExecuteCommand|HOOK_EXECUTE_COMMAND}} to intercept registered in-game commands.
- ]],
- Params = {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who sent the message" },
- { Name = "Message", Type = "string", Notes = "The message" },
- },
- Returns = [[
- The plugin may return 2 values. The first is a boolean specifying whether the hook handling is to be
- stopped or not. If it is false, the message is broadcast to all players in the world. If it is true,
- no message is broadcast and no further action is taken.
-
- The second value is specifies the message to broadcast. This way, plugins may modify the message. If
- the second value is not provided, the original message is used.
- ]],
- }, -- HOOK_CHAT
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnChunkAvailable.lua b/world/Plugins/APIDump/Hooks/OnChunkAvailable.lua
deleted file mode 100644
index 61c191c5..00000000
--- a/world/Plugins/APIDump/Hooks/OnChunkAvailable.lua
+++ /dev/null
@@ -1,27 +0,0 @@
-return
-{
- HOOK_CHUNK_AVAILABLE =
- {
- CalledWhen = "A chunk has just been added to world, either generated or loaded. ",
- DefaultFnName = "OnChunkAvailable", -- also used as pagename
- Desc = [[
- This hook is called after a chunk is either generated or loaded from the disk. The chunk is
- already available for manipulation using the {{cWorld}} API. This is a notification-only callback,
- there is no behavior that plugins could override.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world to which the chunk belongs" },
- { Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" },
- { Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event.
- ]],
- }, -- HOOK_CHUNK_AVAILABLE
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnChunkGenerated.lua b/world/Plugins/APIDump/Hooks/OnChunkGenerated.lua
deleted file mode 100644
index 64bfdad5..00000000
--- a/world/Plugins/APIDump/Hooks/OnChunkGenerated.lua
+++ /dev/null
@@ -1,67 +0,0 @@
-return
-{
- HOOK_CHUNK_GENERATED =
- {
- CalledWhen = "After a chunk was generated. Notification only.",
- DefaultFnName = "OnChunkGenerated", -- also used as pagename
- Desc = [[
- This hook is called when world generator finished its work on a chunk. The chunk data has already
- been generated and is about to be stored in the {{cWorld|world}}. A plugin may provide some
- last-minute finishing touches to the generated data. Note that the chunk is not yet stored in the
- world, so regular {{cWorld}} block API will not work! Instead, use the {{cChunkDesc}} object
- received as the parameter.
-
- See also the {{OnChunkGenerating|HOOK_CHUNK_GENERATING}} hook.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world to which the chunk will be added" },
- { Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" },
- { Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" },
- { Name = "ChunkDesc", Type = "{{cChunkDesc}}", Notes = "Generated chunk data. Plugins may still modify the chunk data contained." },
- },
- Returns = [[
- If the plugin returns false or no value, Cuberite will call other plugins' callbacks for this event.
- If a plugin returns true, no other callback is called for this event.
-
- In either case, Cuberite will then store the data from ChunkDesc as the chunk's contents in the world.
- ]],
- CodeExamples =
- {
- {
- Title = "Generate emerald ore",
- Desc = "This example callback function generates one block of emerald ore in each chunk, under the condition that the randomly chosen location is in an ExtremeHills biome.",
- Code = [[
-function OnChunkGenerated(a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc)
- -- Generate a psaudorandom value that is always the same for the same X/Z pair, but is otherwise random enough:
- -- This is actually similar to how Cuberite does its noise functions
- local PseudoRandom = (a_ChunkX * 57 + a_ChunkZ) * 57 + 19785486
- PseudoRandom = PseudoRandom * 8192 + PseudoRandom;
- PseudoRandom = ((PseudoRandom * (PseudoRandom * PseudoRandom * 15731 + 789221) + 1376312589) % 0x7fffffff;
- PseudoRandom = PseudoRandom / 7;
-
- -- Based on the PseudoRandom value, choose a location for the ore:
- local OreX = PseudoRandom % 16;
- local OreY = 2 + ((PseudoRandom / 16) % 20);
- local OreZ = (PseudoRandom / 320) % 16;
-
- -- Check if the location is in ExtremeHills:
- if (a_ChunkDesc:GetBiome(OreX, OreZ) ~= biExtremeHills) then
- return false;
- end
-
- -- Only replace allowed blocks with the ore:
- local CurrBlock = a_ChunDesc:GetBlockType(OreX, OreY, OreZ);
- if (
- (CurrBlock == E_BLOCK_STONE) or
- (CurrBlock == E_BLOCK_DIRT) or
- (CurrBlock == E_BLOCK_GRAVEL)
- ) then
- a_ChunkDesc:SetBlockTypeMeta(OreX, OreY, OreZ, E_BLOCK_EMERALD_ORE, 0);
- end
-end;
- ]],
- },
- } , -- CodeExamples
- }, -- HOOK_CHUNK_GENERATED
-}
\ No newline at end of file
diff --git a/world/Plugins/APIDump/Hooks/OnChunkGenerating.lua b/world/Plugins/APIDump/Hooks/OnChunkGenerating.lua
deleted file mode 100644
index 0db0e272..00000000
--- a/world/Plugins/APIDump/Hooks/OnChunkGenerating.lua
+++ /dev/null
@@ -1,35 +0,0 @@
-return
-{
- HOOK_CHUNK_GENERATING =
- {
- CalledWhen = "A chunk is about to be generated. Plugin can override the built-in generator.",
- DefaultFnName = "OnChunkGenerating", -- also used as pagename
- Desc = [[
- This hook is called before the world generator starts generating a chunk. The plugin may provide
- some or all parts of the generation, by-passing the built-in generator. The function is given access
- to the {{cChunkDesc|ChunkDesc}} object representing the contents of the chunk. It may override parts
- of the built-in generator by using the object's SetUseDefaultXXX(false) functions. After all
- the callbacks for a chunk have been processed, the server will generate the chunk based on the
- {{cChunkDesc|ChunkDesc}} description - those parts that are set for generating (by default
- everything) are generated, the rest are read from the ChunkDesc object.
-
- See also the {{OnChunkGenerated|HOOK_CHUNK_GENERATED}} hook.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world to which the chunk will be added" },
- { Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" },
- { Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" },
- { Name = "ChunkDesc", Type = "{{cChunkDesc}}", Notes = "Generated chunk data." },
- },
- Returns = [[
- If this function returns true, the server will not call any other plugin with the same chunk. If
- this function returns false, the server will call the rest of the plugins with the same chunk,
- possibly overwriting the ChunkDesc's contents.
- ]],
- }, -- HOOK_CHUNK_GENERATING
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnChunkUnloaded.lua b/world/Plugins/APIDump/Hooks/OnChunkUnloaded.lua
deleted file mode 100644
index a67d5d46..00000000
--- a/world/Plugins/APIDump/Hooks/OnChunkUnloaded.lua
+++ /dev/null
@@ -1,28 +0,0 @@
-return
-{
- HOOK_CHUNK_UNLOADED =
- {
- CalledWhen = "A chunk has been unloaded from the memory.",
- DefaultFnName = "OnChunkUnloaded", -- also used as pagename
- Desc = [[
- This hook is called when a chunk is unloaded from the memory. Though technically still in memory,
- the plugin should behave as if the chunk was already not present. In particular, {{cWorld}} block
- API should not be used in the area of the specified chunk.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world from which the chunk is unloading" },
- { Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" },
- { Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event. There is no behavior that plugins could
- override.
- ]],
- }, -- HOOK_CHUNK_UNLOADED
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnChunkUnloading.lua b/world/Plugins/APIDump/Hooks/OnChunkUnloading.lua
deleted file mode 100644
index 98e0a71f..00000000
--- a/world/Plugins/APIDump/Hooks/OnChunkUnloading.lua
+++ /dev/null
@@ -1,30 +0,0 @@
-return
-{
- HOOK_CHUNK_UNLOADING =
- {
- CalledWhen = " A chunk is about to be unloaded from the memory. Plugins may refuse the unload.",
- DefaultFnName = "OnChunkUnloading", -- also used as pagename
- Desc = [[
- Cuberite calls this function when a chunk is about to be unloaded from the memory. A plugin may
- force Cuberite to keep the chunk in memory by returning true.
-
- FIXME: The return value should be used only for event propagation stopping, not for the actual
- decision whether to unload.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world from which the chunk is unloading" },
- { Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" },
- { Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called and finally Cuberite
- unloads the chunk. If the function returns true, no other callback is called for this event and the
- chunk is left in the memory.
- ]],
- }, -- HOOK_CHUNK_UNLOADING
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnCollectingPickup.lua b/world/Plugins/APIDump/Hooks/OnCollectingPickup.lua
deleted file mode 100644
index 2a451da9..00000000
--- a/world/Plugins/APIDump/Hooks/OnCollectingPickup.lua
+++ /dev/null
@@ -1,32 +0,0 @@
-return
-{
- HOOK_COLLECTING_PICKUP =
- {
- CalledWhen = "Player is about to collect a pickup. Plugin can refuse / override behavior. ",
- DefaultFnName = "OnCollectingPickup", -- also used as pagename
- Desc = [[
- This hook is called when a player is about to collect a pickup. Plugins may refuse the action.
-
- Pickup collection happens within the world tick, so if the collecting is refused, it will be tried
- again in the next world tick, as long as the player is within reach of the pickup.
-
- FIXME: There is no OnCollectedPickup() callback.
-
- FIXME: This callback is called even if the pickup doesn't fit into the player's inventory.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who's collecting the pickup" },
- { Name = "Pickup", Type = "{{cPickup}}", Notes = "The pickup being collected" },
- },
- Returns = [[
- If the function returns false or no value, Cuberite calls other plugins' callbacks and finally the
- pickup is collected. If the function returns true, no other plugins are called for this event and
- the pickup is not collected.
- ]],
- }, -- HOOK_COLLECTING_PICKUP
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnCraftingNoRecipe.lua b/world/Plugins/APIDump/Hooks/OnCraftingNoRecipe.lua
deleted file mode 100644
index 7cd86b8b..00000000
--- a/world/Plugins/APIDump/Hooks/OnCraftingNoRecipe.lua
+++ /dev/null
@@ -1,32 +0,0 @@
-return
-{
- HOOK_CRAFTING_NO_RECIPE =
- {
- CalledWhen = " No built-in crafting recipe is found. Plugin may provide a recipe.",
- DefaultFnName = "OnCraftingNoRecipe", -- also used as pagename
- Desc = [[
- This callback is called when a player places items in their {{cCraftingGrid|crafting grid}} and
- Cuberite cannot find a built-in {{cCraftingRecipe|recipe}} for the combination. Plugins may provide
- a recipe for the ingredients given.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player whose crafting is reported in this hook" },
- { Name = "Grid", Type = "{{cCraftingGrid}}", Notes = "Contents of the player's crafting grid" },
- { Name = "Recipe", Type = "{{cCraftingRecipe}}", Notes = "The recipe that will be used (can be filled by plugins)" },
- },
- Returns = [[
- If the function returns false or no value, no recipe will be used. If the function returns true, no
- other plugin will have their callback called for this event and Cuberite will use the crafting
- recipe in Recipe.
-
- FIXME: To allow plugins give suggestions and overwrite other plugins' suggestions, we should change
- the behavior with returning false, so that the recipe will still be used, but fill the recipe with
- empty values by default.
- ]],
- }, -- HOOK_CRAFTING_NO_RECIPE
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnDisconnect.lua b/world/Plugins/APIDump/Hooks/OnDisconnect.lua
deleted file mode 100644
index ae872a3a..00000000
--- a/world/Plugins/APIDump/Hooks/OnDisconnect.lua
+++ /dev/null
@@ -1,38 +0,0 @@
-return
-{
- HOOK_DISCONNECT =
- {
- CalledWhen = [[
- A client has disconnected, either by explicitly sending the disconnect packet (in older protocols) or
- their connection was terminated
- ]],
- DefaultFnName = "OnDisconnect", -- also used as pagename
- Desc = [[
- This hook is called when a client has disconnected from the server, for whatever reason. It is also
- called when the client sends the Disconnect packet (only in pre-1.7 protocols). This hook is not called
- for server ping connections.
-
- Note that the hook is called even for connections to players who failed to auth. In such a case there's
- no {{cPlayer}} object associated with the client.
-
- See also the {{OnHandshake|HOOK_HANDSHAKE}} hook which is called when the client connects (and presents
- a handshake message, so that they are not just status-pinging). If you need to store a per-player
- object, use the {{OnPlayerJoined|HOOK_PLAYER_JOINED}} and {{OnPlayerDestroyed|HOOK_PLAYER_DESTROYED}}
- hooks instead, those are guaranteed to have the {{cPlayer}} object associated.
- ]],
- Params =
- {
- { Name = "Client", Type = "{{cClientHandle}}", Notes = "The client who has disconnected" },
- { Name = "Reason", Type = "string", Notes = "The reason that the client has sent in the disconnect packet" },
- },
- Returns = [[
- If the function returns false or no value, Cuberite calls other plugins' callbacks for this event.
- If the function returns true, no other plugins are called for this event. In either case,
- the client is disconnected.
- ]],
- }, -- HOOK_DISCONNECT
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnEntityAddEffect.lua b/world/Plugins/APIDump/Hooks/OnEntityAddEffect.lua
deleted file mode 100644
index 155abc41..00000000
--- a/world/Plugins/APIDump/Hooks/OnEntityAddEffect.lua
+++ /dev/null
@@ -1,33 +0,0 @@
-return
-{
- HOOK_ENTITY_ADD_EFFECT =
- {
- CalledWhen = "An entity effect is about to get added to an entity.",
- DefaultFnName = "OnEntityAddEffect", -- also used as pagename
- Desc = [[
- This hook is called whenever an entity effect is about to be added to an entity. The plugin may
- disallow the addition by returning true.
-
Note that this hook only fires for adding the effect, but not for the actual effect application. See
- also the {{OnEntityRemoveEffect|HOOK_ENTITY_REMOVE_EFFECT}} for notification about effects expiring /
- removing, and {{OnEntityApplyEffect|HOOK_ENTITY_APPLY_EFFECT}} for the actual effect application to the
- entity.
- ]],
- Params =
- {
- { Name = "Entity", Type = "{{cEntity}}", Notes = "The entity to which the effect is about to be added" },
- { Name = "EffectType", Type = "number", Notes = "The type of the effect to be added. One of the effXXX constants." },
- { Name = "EffectDuration", Type = "number", Notes = "The duration of the effect to be added, in ticks." },
- { Name = "EffectIntensity", Type = "number", Notes = "The intensity (level) of the effect to be added. " },
- { Name = "DistanceModifier", Type = "number", Notes = "The modifier for the effect intensity, based on distance. Used mainly for splash potions." },
- },
- Returns = [[
- If the plugin returns true, the effect will not be added and none of the remaining hook handlers will
- be called. If the plugin returns false, Cuberite calls all the remaining hook handlers and finally
- the effect is added to the entity.
- ]],
- }, -- HOOK_EXECUTE_COMMAND
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnEntityChangedWorld.lua b/world/Plugins/APIDump/Hooks/OnEntityChangedWorld.lua
deleted file mode 100644
index 6675fdbe..00000000
--- a/world/Plugins/APIDump/Hooks/OnEntityChangedWorld.lua
+++ /dev/null
@@ -1,28 +0,0 @@
-return
-{
- HOOK_ENTITY_CHANGED_WORLD =
- {
- CalledWhen = "After a entity has changed the world.",
- DefaultFnName = "OnEntityChangedWorld", -- also used as pagename
- Desc = [[
- This hook is called after the server has moved the {{cEntity|entity}} to the given world. This is an information-only
- callback, the entity is already in the new world.
- See also the {{OnEntityChangingWorld|HOOK_ENTITY_CHANGING_WORLD}} hook for a similar hook called before the
- entity is moved to the new world.
- ]],
- Params =
- {
- { Name = "Entity", Type = "{{cEntity}}", Notes = "The entity that has changed the world" },
- { Name = "World", Type = "{{cWorld}}", Notes = "The world from which the entity has come" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event.
- ]],
- }, -- HOOK_ENTITY_CHANGED_WORLD
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnEntityChangingWorld.lua b/world/Plugins/APIDump/Hooks/OnEntityChangingWorld.lua
deleted file mode 100644
index 521f829c..00000000
--- a/world/Plugins/APIDump/Hooks/OnEntityChangingWorld.lua
+++ /dev/null
@@ -1,29 +0,0 @@
-return
-{
- HOOK_ENTITY_CHANGING_WORLD =
- {
- CalledWhen = "Before a entity is changing the world.",
- DefaultFnName = "OnEntityChangingWorld", -- also used as pagename
- Desc = [[
- This hook is called before the server moves the {{cEntity|entity}} to the given world. Plugins may
- refuse the changing of the entity to the new world.
- See also the {{OnEntityChangedWorld|HOOK_ENTITY_CHANGED_WORLD}} hook for a similar hook is called after the
- entity has been moved to the world.
- ]],
- Params =
- {
- { Name = "Entity", Type = "{{cEntity}}", Notes = "The entity that wants to change the world" },
- { Name = "World", Type = "{{cWorld}}", Notes = "The world to which the entity wants to change" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event and the change of the entity to the world is
- cancelled.
- ]],
- }, -- HOOK_ENTITY_CHANGING_WORLD
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnEntityTeleport.lua b/world/Plugins/APIDump/Hooks/OnEntityTeleport.lua
deleted file mode 100644
index cdeb0947..00000000
--- a/world/Plugins/APIDump/Hooks/OnEntityTeleport.lua
+++ /dev/null
@@ -1,29 +0,0 @@
-return
-{
- HOOK_ENTITY_TELEPORT =
- {
- CalledWhen = "Any entity teleports. Plugin may refuse teleport.",
- DefaultFnName = "OnEntityTeleport", -- also used as pagename
- Desc = [[
- This function is called in each server tick for each {{cEntity|Entity}} that has
- teleported. Plugins may refuse the teleport.
- ]],
- Params =
- {
- { Name = "Entity", Type = "{{cEntity}}", Notes = "The entity who has teleported. New position is set in the object after successfull teleport" },
- { Name = "OldPosition", Type = "{{Vector3d}}", Notes = "The old position." },
- { Name = "NewPosition", Type = "{{Vector3d}}", Notes = "The new position." },
- },
- Returns = [[
- If the function returns true, teleport is prohibited.
-
- If the function returns false or no value, other plugins' callbacks are called and finally the new
- position is permanently stored in the cEntity object.
- ]],
- }, -- HOOK_ENTITY_TELEPORT
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnExecuteCommand.lua b/world/Plugins/APIDump/Hooks/OnExecuteCommand.lua
deleted file mode 100644
index 4aa31bbd..00000000
--- a/world/Plugins/APIDump/Hooks/OnExecuteCommand.lua
+++ /dev/null
@@ -1,41 +0,0 @@
-return
-{
- HOOK_EXECUTE_COMMAND =
- {
- CalledWhen = [[
- A player executes an in-game command, or the admin issues a console command. Note that built-in
- console commands are exempt to this hook - they are always performed and the hook is not called.
- ]],
- DefaultFnName = "OnExecuteCommand", -- also used as pagename
- Desc = [[
- A plugin may implement a callback for this hook to intercept both in-game commands executed by the
- players and console commands executed by the server admin. The function is called for every in-game
- command sent from any player and for those server console commands that are not built in in the
- server.
-
- If the command is in-game, the first parameter to the hook function is the {{cPlayer|player}} who's
- executing the command. If the command comes from the server console, the first parameter is nil.
-
- The server calls this hook even for unregistered (unknown) console commands. It also calls the hook
- for unknown in-game commands, as long as they begin with a slash ('/'). If a plugin needs to intercept
- in-game chat messages not beginning with a slash, it should use the {{OnChat|HOOK_CHAT}} hook.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "For in-game commands, the player who has sent the message. For console commands, nil" },
- { Name = "CommandSplit", Type = "array-table of strings", Notes = "The command and its parameters, broken into a table by spaces" },
- { Name = "EntireCommand", Type = "string", Notes = "The entire command as a single string" },
- },
- Returns = [[
- If the plugin returns false, Cuberite calls all the remaining hook handlers and finally the command
- will be executed. If the plugin returns true, the none of the remaining hook handlers will be called.
- In this case the plugin can return a second value, specifying whether what the command result should
- be set to, one of the {{cPluginManager#CommandResult|CommandResult}} constants. If not
- provided, the value defaults to crBlocked.
- ]],
- }, -- HOOK_EXECUTE_COMMAND
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnExploded.lua b/world/Plugins/APIDump/Hooks/OnExploded.lua
deleted file mode 100644
index daca3123..00000000
--- a/world/Plugins/APIDump/Hooks/OnExploded.lua
+++ /dev/null
@@ -1,36 +0,0 @@
-return
-{
- HOOK_EXPLODED =
- {
- CalledWhen = "An explosion has happened",
- DefaultFnName = "OnExploded", -- also used as pagename
- Desc = [[
- This hook is called after an explosion has been processed in a world.
-
- See also {{OnExploding|HOOK_EXPLODING}} for a similar hook called before the explosion.
-
- The explosion carries with it the type of its source - whether it's a creeper exploding, or TNT,
- etc. It also carries the identification of the actual source. The exact type of the identification
- depends on the source kind, see the {{Globals#ExplosionSource|esXXX}} constants' descriptions for details.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world where the explosion happened" },
- { Name = "ExplosionSize", Type = "number", Notes = "The relative explosion size" },
- { Name = "CanCauseFire", Type = "bool", Notes = "True if the explosion has turned random air blocks to fire (such as a ghast fireball)" },
- { Name = "X", Type = "number", Notes = "X-coord of the explosion center" },
- { Name = "Y", Type = "number", Notes = "Y-coord of the explosion center" },
- { Name = "Z", Type = "number", Notes = "Z-coord of the explosion center" },
- { Name = "Source", Type = "eExplosionSource", Notes = "Source of the explosion. See the table above." },
- { Name = "SourceData", Type = "varies", Notes = "Additional data for the source. The exact type varies by the source. See the {{Globals#ExplosionSource|esXXX}} constants' descriptions." },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event. There is no overridable behaviour.
- ]],
- }, -- HOOK_EXPLODED
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnExploding.lua b/world/Plugins/APIDump/Hooks/OnExploding.lua
deleted file mode 100644
index 873202dc..00000000
--- a/world/Plugins/APIDump/Hooks/OnExploding.lua
+++ /dev/null
@@ -1,41 +0,0 @@
-return
-{
- HOOK_EXPLODING =
- {
- CalledWhen = "An explosion is about to be processed",
- DefaultFnName = "OnExploding", -- also used as pagename
- Desc = [[
- This hook is called before an explosion has been processed in a world.
-
- See also {{OnExploded|HOOK_EXPLODED}} for a similar hook called after the explosion.
-
- The explosion carries with it the type of its source - whether it's a creeper exploding, or TNT,
- etc. It also carries the identification of the actual source. The exact type of the identification
- depends on the source kind, see the {{Globals#ExplosionSource|esXXX}} constants' descriptions for details
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world where the explosion happens" },
- { Name = "ExplosionSize", Type = "number", Notes = "The relative explosion size" },
- { Name = "CanCauseFire", Type = "bool", Notes = "True if the explosion will turn random air blocks to fire (such as a ghast fireball)" },
- { Name = "X", Type = "number", Notes = "X-coord of the explosion center" },
- { Name = "Y", Type = "number", Notes = "Y-coord of the explosion center" },
- { Name = "Z", Type = "number", Notes = "Z-coord of the explosion center" },
- { Name = "Source", Type = "eExplosionSource", Notes = "Source of the explosion. See the table above." },
- { Name = "SourceData", Type = "varies", Notes = "Additional data for the source. The exact type varies by the source. See the {{Globals#ExplosionSource|esXXX}} constants' description." },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called, and finally
- Cuberite will process the explosion - destroy blocks and push + hurt entities. If the function
- returns true, no other callback is called for this event and the explosion will not occur.
-
- The hook handler may return up to two more values after the initial bool. The second returned value
- overrides the CanCauseFire parameter for subsequent hook calls and the final explosion, the third
- returned value overrides the ExplosionSize parameter for subsequent hook calls and the final explosion.
- ]],
- }, -- HOOK_EXPLODING
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnHandshake.lua b/world/Plugins/APIDump/Hooks/OnHandshake.lua
deleted file mode 100644
index 6183cc50..00000000
--- a/world/Plugins/APIDump/Hooks/OnHandshake.lua
+++ /dev/null
@@ -1,29 +0,0 @@
-return
-{
- HOOK_HANDSHAKE =
- {
- CalledWhen = "A client is connecting.",
- DefaultFnName = "OnHandshake", -- also used as pagename
- Desc = [[
- This hook is called when a client sends the Handshake packet. At this stage, only the client IP and
- (unverified) username are known. Plugins may refuse access to the server based on this
- information.
-
- Note that the username is not authenticated - the authentication takes place only after this hook is
- processed.
- ]],
- Params =
- {
- { Name = "Client", Type = "{{cClientHandle}}", Notes = "The client handle representing the connection. Note that there's no {{cPlayer}} object for this client yet." },
- { Name = "UserName", Type = "string", Notes = "The username presented in the packet. Note that this username is unverified." },
- },
- Returns = [[
- If the function returns false, the user is let in to the server. If the function returns true, no
- other plugin's callback is called, the user is kicked and the connection is closed.
- ]],
- }, -- HOOK_HANDSHAKE
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnHopperPullingItem.lua b/world/Plugins/APIDump/Hooks/OnHopperPullingItem.lua
deleted file mode 100644
index b268a76b..00000000
--- a/world/Plugins/APIDump/Hooks/OnHopperPullingItem.lua
+++ /dev/null
@@ -1,30 +0,0 @@
-return
-{
- HOOK_HOPPER_PULLING_ITEM =
- {
- CalledWhen = "A hopper is pulling an item from another block entity.",
- DefaultFnName = "OnHopperPullingItem", -- also used as pagename
- Desc = [[
- This callback is called whenever a {{cHopperEntity|hopper}} transfers an {{cItem|item}} from another
- block entity into its own internal storage. A plugin may decide to disallow the move by returning
- true. Note that in such a case, the hook may be called again for the same hopper, with different
- slot numbers.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "World where the hopper resides" },
- { Name = "Hopper", Type = "{{cHopperEntity}}", Notes = "The hopper that is pulling the item" },
- { Name = "DstSlot", Type = "number", Notes = "The destination slot in the hopper's {{cItemGrid|internal storage}}" },
- { Name = "SrcBlockEntity", Type = "{{cBlockEntityWithItems}}", Notes = "The block entity that is losing the item" },
- { Name = "SrcSlot", Type = "number", Notes = "Slot in SrcBlockEntity from which the item will be pulled" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event and the hopper will not pull the item.
- ]],
- }, -- HOOK_HOPPER_PULLING_ITEM
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnHopperPushingItem.lua b/world/Plugins/APIDump/Hooks/OnHopperPushingItem.lua
deleted file mode 100644
index bd570251..00000000
--- a/world/Plugins/APIDump/Hooks/OnHopperPushingItem.lua
+++ /dev/null
@@ -1,30 +0,0 @@
-return
-{
- HOOK_HOPPER_PUSHING_ITEM =
- {
- CalledWhen = "A hopper is pushing an item into another block entity. ",
- DefaultFnName = "OnHopperPushingItem", -- also used as pagename
- Desc = [[
- This hook is called whenever a {{cHopperEntity|hopper}} transfers an {{cItem|item}} from its own
- internal storage into another block entity. A plugin may decide to disallow the move by returning
- true. Note that in such a case, the hook may be called again for the same hopper and block, with
- different slot numbers.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "World where the hopper resides" },
- { Name = "Hopper", Type = "{{cHopperEntity}}", Notes = "The hopper that is pushing the item" },
- { Name = "SrcSlot", Type = "number", Notes = "Slot in the hopper that will lose the item" },
- { Name = "DstBlockEntity", Type = "{{cBlockEntityWithItems}}", Notes = " The block entity that will receive the item" },
- { Name = "DstSlot", Type = "number", Notes = " Slot in DstBlockEntity's internal storage where the item will be stored" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event and the hopper will not push the item.
- ]],
- }, -- HOOK_HOPPER_PUSHING_ITEM
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnKilled.lua b/world/Plugins/APIDump/Hooks/OnKilled.lua
deleted file mode 100644
index 9289b8f3..00000000
--- a/world/Plugins/APIDump/Hooks/OnKilled.lua
+++ /dev/null
@@ -1,22 +0,0 @@
-return
-{
- HOOK_KILLED =
- {
- CalledWhen = "A player or a mob died.",
- DefaultFnName = "OnKilled",
- Desc = [[
- This hook is called whenever player or a mob dies. It can be used to change the death message.
- ]],
- Params =
- {
- { Name = "Victim", Type = "{{cEntity}}", Notes = "The player or mob that died" },
- { Name = "TDI", Type = "{{TakeDamageInfo}}", Notes = "Informations about the death" },
- { Name = "DeathMessage", Type = "string", Notes = "The default death message. An empty string if the victim is not a player" },
- },
- Returns = [[
- The function may return two values. The first value is a boolean specifying whether other plugins should be called. If it is true, the other plugins won't get notified of the death. If it is false, the other plugins will get notified.
-
The second value is a string containing the death message. If the victim is a player, this death message is broadcasted instead of the default death message. If it is empty, no death message is broadcasted. If it is nil, the message is left unchanged. If the victim is not a player, the death message is never broadcasted.
-
In either case, the victim is dead.
- ]],
- }, -- HOOK_KILLED
-}
diff --git a/world/Plugins/APIDump/Hooks/OnKilling.lua b/world/Plugins/APIDump/Hooks/OnKilling.lua
deleted file mode 100644
index 6bfd75fb..00000000
--- a/world/Plugins/APIDump/Hooks/OnKilling.lua
+++ /dev/null
@@ -1,30 +0,0 @@
-return
-{
- HOOK_KILLING =
- {
- CalledWhen = "A player or a mob is dying.",
- DefaultFnName = "OnKilling", -- also used as pagename
- Desc = [[
- This hook is called whenever a {{cPawn|pawn}}'s (a player's or a mob's) health reaches zero. This
- means that the pawn is about to be killed, unless a plugin "revives" them by setting their health
- back to a positive value.
- ]],
- Params =
- {
- { Name = "Victim", Type = "{{cPawn}}", Notes = "The player or mob that is about to be killed" },
- { Name = "Killer", Type = "{{cEntity}}", Notes = "The entity that has caused the victim to lose the last point of health. May be nil for environment damage" },
- { Name = "TDI", Type = "{{TakeDamageInfo}}", Notes = "The damage type, cause and effects." },
- },
- Returns = [[
- If the function returns false or no value, Cuberite calls other plugins with this event. If the
- function returns true, no other plugin is called for this event.
-
- In either case, the victim's health is then re-checked and if it is greater than zero, the victim is
- "revived" with that health amount. If the health is less or equal to zero, the victim is killed.
- ]],
- }, -- HOOK_KILLING
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnLogin.lua b/world/Plugins/APIDump/Hooks/OnLogin.lua
deleted file mode 100644
index f71c3ade..00000000
--- a/world/Plugins/APIDump/Hooks/OnLogin.lua
+++ /dev/null
@@ -1,31 +0,0 @@
-return
-{
- HOOK_LOGIN =
- {
- CalledWhen = "Right before player authentication. If auth is disabled, right after the player sends their name.",
- DefaultFnName = "OnLogin", -- also used as pagename
- Desc = [[
- This hook is called whenever a client logs in. It is called right before the client's name is sent
- to be authenticated. Plugins may refuse the client from accessing the server. Note that when this
- callback is called, the {{cPlayer}} object for this client doesn't exist yet - the client has no
- representation in any world. To process new players when their world is known, use a later callback,
- such as {{OnPlayerJoined|HOOK_PLAYER_JOINED}} or {{OnPlayerSpawned|HOOK_PLAYER_SPAWNED}}.
- ]],
- Params =
- {
- { Name = "Client", Type = "{{cClientHandle}}", Notes = "The client handle representing the connection" },
- { Name = "ProtocolVersion", Type = "number", Notes = "Versio of the protocol that the client is talking" },
- { Name = "UserName", Type = "string", Notes = "The name that the client has presented for authentication. This name will be given to the {{cPlayer}} object when it is created for this client." },
- },
- Returns = [[
- If the function returns true, no other plugins are called for this event and the client is kicked.
- If the function returns false or no value, Cuberite calls other plugins' callbacks and finally
- sends an authentication request for the client's username to the auth server. If the auth server
- is disabled in the server settings, the player object is immediately created.
- ]],
- }, -- HOOK_LOGIN
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerAnimation.lua b/world/Plugins/APIDump/Hooks/OnPlayerAnimation.lua
deleted file mode 100644
index baf99834..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerAnimation.lua
+++ /dev/null
@@ -1,28 +0,0 @@
-return
-{
- HOOK_PLAYER_ANIMATION =
- {
- CalledWhen = "A client has sent an Animation packet (0x12)",
- DefaultFnName = "OnPlayerAnimation", -- also used as pagename
- Desc = [[
- This hook is called when the server receives an Animation packet (0x12) from the client.
-
- For the list of animations that are sent by the client, see the
- Protocol wiki.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player from whom the packet was received" },
- { Name = "Animation", Type = "number", Notes = "The kind of animation" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. Afterwards, the
- server broadcasts the animation packet to all nearby clients. If the function returns true, no other
- callback is called for this event and the packet is not broadcasted.
- ]],
- }, -- HOOK_PLAYER_ANIMATION
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerBreakingBlock.lua b/world/Plugins/APIDump/Hooks/OnPlayerBreakingBlock.lua
deleted file mode 100644
index 18f19f24..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerBreakingBlock.lua
+++ /dev/null
@@ -1,36 +0,0 @@
-return
-{
- HOOK_PLAYER_BREAKING_BLOCK =
- {
- CalledWhen = "Just before a player breaks a block. Plugin may override / refuse. ",
- DefaultFnName = "OnPlayerBreakingBlock", -- also used as pagename
- Desc = [[
- This hook is called when a {{cPlayer|player}} breaks a block, before the block is actually broken in
- the {{cWorld|World}}. Plugins may refuse the breaking.
-
- See also the {{OnPlayerBrokenBlock|HOOK_PLAYER_BROKEN_BLOCK}} hook for a similar hook called after
- the block is broken.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is digging the block" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
- { Name = "BlockFace", Type = "number", Notes = "Face of the block upon which the player is acting. One of the BLOCK_FACE_ constants" },
- { Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block being broken" },
- { Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block being broken " },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called, and then the block
- is broken. If the function returns true, no other plugin's callback is called and the block breaking
- is cancelled. The server re-sends the block back to the player to replace it (the player's client
- already thinks the block was broken).
- ]],
- }, -- HOOK_PLAYER_BREAKING_BLOCK
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerBrokenBlock.lua b/world/Plugins/APIDump/Hooks/OnPlayerBrokenBlock.lua
deleted file mode 100644
index e718c5d9..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerBrokenBlock.lua
+++ /dev/null
@@ -1,36 +0,0 @@
-return
-{
- HOOK_PLAYER_BROKEN_BLOCK =
- {
- CalledWhen = "After a player has broken a block. Notification only.",
- DefaultFnName = "OnPlayerBrokenBlock", -- also used as pagename
- Desc = [[
- This function is called after a {{cPlayer|player}} breaks a block. The block is already removed
- from the {{cWorld|world}} and {{cPickup|pickups}} have been spawned. To get the world in which the
- block has been dug, use the {{cPlayer}}:GetWorld() function.
-
- See also the {{OnPlayerBreakingBlock|HOOK_PLAYER_BREAKING_BLOCK}} hook for a similar hook called
- before the block is broken. To intercept the creation of pickups, see the
- {{OnBlockToPickups|HOOK_BLOCK_TO_PICKUPS}} hook.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who broke the block" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
- { Name = "BlockFace", Type = "number", Notes = "Face of the block upon which the player interacted. One of the BLOCK_FACE_ constants" },
- { Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block" },
- { Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event.
- ]],
- }, -- HOOK_PLAYER_BROKEN_BLOCK
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerDestroyed.lua b/world/Plugins/APIDump/Hooks/OnPlayerDestroyed.lua
deleted file mode 100644
index dc033197..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerDestroyed.lua
+++ /dev/null
@@ -1,27 +0,0 @@
-return
-{
- HOOK_PLAYER_DESTROYED =
- {
- CalledWhen = "A player object is about to be destroyed.",
- DefaultFnName = "OnPlayerDestroyed", -- also used as pagename
- Desc = [[
- This function is called before a {{cPlayer|player}} is about to be destroyed.
- The player has disconnected for whatever reason and is no longer in the server.
- If a plugin returns true, a leave message is not broadcast, and vice versa.
- However, whatever the return value, the player object is removed from memory.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The destroyed player" },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called and a leave message is broadcast.
- If the function returns true, no other callbacks are called for this event and no leave message appears. Either way the player is removed internally.
- ]],
- }, -- HOOK_PLAYER_DESTROYED
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerEating.lua b/world/Plugins/APIDump/Hooks/OnPlayerEating.lua
deleted file mode 100644
index e77d02a9..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerEating.lua
+++ /dev/null
@@ -1,27 +0,0 @@
-return
-{
- HOOK_PLAYER_EATING =
- {
- CalledWhen = "When the player starts eating",
- DefaultFnName = "OnPlayerEating", -- also used as pagename
- Desc = [[
- This hook gets called when the {{cPlayer|player}} starts eating, after the server checks that the
- player can indeed eat (is not satiated and is holding food). Plugins may still refuse the eating by
- returning true.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who started eating" },
- },
- Returns = [[
- If the function returns false or no value, the server calls the next plugin handler, and finally
- lets the player eat. If the function returns true, the server doesn't call any more callbacks for
- this event and aborts the eating. A "disallow" packet is sent to the client.
- ]],
- }, -- HOOK_PLAYER_EATING
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerFished.lua b/world/Plugins/APIDump/Hooks/OnPlayerFished.lua
deleted file mode 100644
index 4e093f4a..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerFished.lua
+++ /dev/null
@@ -1,20 +0,0 @@
-return
-{
- HOOK_PLAYER_FISHED =
- {
- CalledWhen = "A player gets a reward from fishing.",
- DefaultFnName = "OnPlayerFished", -- also used as pagename
- Desc = [[
- This hook gets called after a player reels in the fishing rod. This is a notification-only hook, the reward has already been decided. If a plugin needs to modify the reward, use the {{OnPlayerFishing|HOOK_PLAYER_FISHING}} hook.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who pulled the fish in." },
- { Name = "Reward", Type = "{{cItems}}", Notes = "The reward the player gets. It can be a fish, treasure and junk." },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function returns true, no other
- callback is called for this event.
- ]],
- }, -- HOOK_PLAYER_FISHED
-};
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerFishing.lua b/world/Plugins/APIDump/Hooks/OnPlayerFishing.lua
deleted file mode 100644
index c5aaecd9..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerFishing.lua
+++ /dev/null
@@ -1,21 +0,0 @@
-return
-{
- HOOK_PLAYER_FISHING =
- {
- CalledWhen = "A player is about to get a reward from fishing.",
- DefaultFnName = "OnPlayerFishing", -- also used as pagename
- Desc = [[
- This hook gets called when a player right clicks with a fishing rod while the floater is under water. The reward is already descided, but the plugin may change it.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who pulled the fish in." },
- { Name = "Reward", Type = "{{cItems}}", Notes = "The reward the player gets. It can be a fish, treasure and junk." },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. Afterwards, the
- server gives the player his reward. If the function returns true, no other
- callback is called for this event and the player doesn't get his reward.
- ]],
- }, -- HOOK_PLAYER_FISHING
-};
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerFoodLevelChange.lua b/world/Plugins/APIDump/Hooks/OnPlayerFoodLevelChange.lua
deleted file mode 100644
index 53637d5f..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerFoodLevelChange.lua
+++ /dev/null
@@ -1,27 +0,0 @@
-return
-{
- HOOK_PLAYER_FOOD_LEVEL_CHANGE =
- {
- CalledWhen = "Called before the player food level changed. Plugin may override",
- DefaultFnName = "OnPlayerFoodLevelChange", -- also used as pagename
- Desc = [[
- This hook is called before the food level changes.
- The food level is not changed yet, plugins may choose
- to refuse the change.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who changes the food level." },
- { Name = "NewFoodLevel", Type = "number", Notes = "The new food level." },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. Afterwards, the
- server changes the food level of the player. If the function returns true, no
- other callback is called for this event and the player's food level doesn't change.
- ]],
- }, -- HOOK_PLAYER_FOOD_LEVEL_CHANGE
-};
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerJoined.lua b/world/Plugins/APIDump/Hooks/OnPlayerJoined.lua
deleted file mode 100644
index dcd16ed0..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerJoined.lua
+++ /dev/null
@@ -1,29 +0,0 @@
-return
-{
- HOOK_PLAYER_JOINED =
- {
- CalledWhen = "After Login and before Spawned, before being added to world. ",
- DefaultFnName = "OnPlayerJoined", -- also used as pagename
- Desc = [[
- This hook is called whenever a {{cPlayer|player}} has completely logged in. If authentication is
- enabled, this function is called after their name has been authenticated. It is called after
- {{OnLogin|HOOK_LOGIN}} and before {{OnPlayerSpawned|HOOK_PLAYER_SPAWNED}}, right after the player's
- entity is created, but not added to the world yet. The player is not yet visible to other players.
- Returning true will block a join message from being broadcast, but otherwise, the player is still allowed to join.
- Plugins wishing to refuse player's entry should kick the player using the {{cPlayer}}:Kick() function.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has joined the game" },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called and a join message is broadcast. If the function
- returns true, no other callbacks are called for this event and a join message is not sent. Either way the player is let in.
- ]],
- }, -- HOOK_PLAYER_JOINED
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerLeftClick.lua b/world/Plugins/APIDump/Hooks/OnPlayerLeftClick.lua
deleted file mode 100644
index 3d4c0795..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerLeftClick.lua
+++ /dev/null
@@ -1,47 +0,0 @@
-return
-{
- HOOK_PLAYER_LEFT_CLICK =
- {
- CalledWhen = "A left-click packet is received from the client. Plugin may override / refuse.",
- DefaultFnName = "OnPlayerLeftClick", -- also used as pagename
- Desc = [[
- This hook is called when Cuberite receives a left-click packet from the {{cClientHandle|client}}. It
- is called before any processing whatsoever is performed on the packet, meaning that hacked /
- malicious clients may be trigerring this event very often and with unchecked parameters. Therefore
- plugin authors are advised to use extreme caution with this callback.
-
- Plugins may refuse the default processing for the packet, causing Cuberite to behave as if the
- packet has never arrived. This may, however, create inconsistencies in the client - the client may
- think that they broke a block, while the server didn't process the breaking, etc. For this reason,
- if a plugin refuses the processing, Cuberite sends the block specified in the packet back to the
- client (as if placed anew), if the status code specified a block-break action. For other actions,
- plugins must rectify the situation on their own.
-
- The client sends the left-click packet for several other occasions, such as dropping the held item
- (Q keypress) or shooting an arrow. This is reflected in the Status code. Consult the
- protocol documentation for details on the actions.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player whose client sent the packet" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
- { Name = "BlockFace", Type = "number", Notes = "Face of the block upon which the player interacted. One of the BLOCK_FACE_ constants" },
- { Name = "Action", Type = "number", Notes = "Action to be performed on the block (\"status\" in the protocol docs)" },
- },
- Returns = [[
- If the function returns false or no value, Cuberite calls other plugins' callbacks and finally sends
- the packet for further processing.
-
- If the function returns true, no other plugins are called, processing is halted. If the action was a
- block dig, Cuberite sends the block specified in the coords back to the client. The packet is
- dropped.
- ]],
- }, -- HOOK_PLAYER_LEFT_CLICK
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerMoving.lua b/world/Plugins/APIDump/Hooks/OnPlayerMoving.lua
deleted file mode 100644
index 4385bf94..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerMoving.lua
+++ /dev/null
@@ -1,29 +0,0 @@
-return
-{
- HOOK_PLAYER_MOVING =
- {
- CalledWhen = "Player tried to move in the tick being currently processed. Plugin may refuse movement.",
- DefaultFnName = "OnPlayerMoving", -- also used as pagename
- Desc = [[
- This function is called in each server tick for each {{cPlayer|player}} that has sent any of the
- player-move packets. Plugins may refuse the movement.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has moved. The object already has the new position stored in it." },
- { Name = "OldPosition", Type = "{{Vector3d}}", Notes = "The old position." },
- { Name = "NewPosition", Type = "{{Vector3d}}", Notes = "The new position." },
- },
- Returns = [[
- If the function returns true, movement is prohibited.
-
- If the function returns false or no value, other plugins' callbacks are called and finally the new
- position is permanently stored in the cPlayer object.
- ]],
- }, -- HOOK_PLAYER_MOVING
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerPlacedBlock.lua b/world/Plugins/APIDump/Hooks/OnPlayerPlacedBlock.lua
deleted file mode 100644
index 74d4c19e..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerPlacedBlock.lua
+++ /dev/null
@@ -1,40 +0,0 @@
-return
-{
- HOOK_PLAYER_PLACED_BLOCK =
- {
- CalledWhen = "After a player has placed a block. Notification only.",
- DefaultFnName = "OnPlayerPlacedBlock", -- also used as pagename
- Desc = [[
- This hook is called after a {{cPlayer|player}} has placed a block in the {{cWorld|world}}. The block
- is already added to the world and the corresponding item removed from player's
- {{cInventory|inventory}}.
-
- Use the {{cPlayer}}:GetWorld() function to get the world to which the block belongs.
-
- See also the {{OnPlayerPlacingBlock|HOOK_PLAYER_PLACING_BLOCK}} hook for a similar hook called
- before the placement.
-
- If the client action results in multiple blocks being placed (such as a bed or a door), each separate
- block is reported through this hook. All the blocks are already present in the world before the first
- instance of this hook is called.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who placed the block" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
- { Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block" },
- { Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block" },
- },
- Returns = [[
- If this function returns false or no value, Cuberite calls other plugins with the same event. If
- this function returns true, no other plugin is called for this event.
- ]],
- }, -- HOOK_PLAYER_PLACED_BLOCK
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerPlacingBlock.lua b/world/Plugins/APIDump/Hooks/OnPlayerPlacingBlock.lua
deleted file mode 100644
index b78acc32..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerPlacingBlock.lua
+++ /dev/null
@@ -1,45 +0,0 @@
-return
-{
- HOOK_PLAYER_PLACING_BLOCK =
- {
- CalledWhen = "Just before a player places a block. Plugin may override / refuse.",
- DefaultFnName = "OnPlayerPlacingBlock", -- also used as pagename
- Desc = [[
- This hook is called just before a {{cPlayer|player}} places a block in the {{cWorld|world}}. The
- block is not yet placed, plugins may choose to override the default behavior or refuse the placement
- at all.
-
- Note that the client already expects that the block has been placed. For that reason, if a plugin
- refuses the placement, Cuberite sends the old block at the provided coords to the client.
-
- Use the {{cPlayer}}:GetWorld() function to get the world to which the block belongs.
-
- See also the {{OnPlayerPlacedBlock|HOOK_PLAYER_PLACED_BLOCK}} hook for a similar hook called after
- the placement.
-
- If the client action results in multiple blocks being placed (such as a bed or a door), each separate
- block is reported through this hook and only if all of them succeed, all the blocks are placed. If
- any one of the calls are refused by the plugin, all the blocks are refused and reverted on the client.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is placing the block" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
- { Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block" },
- { Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block" },
- },
- Returns = [[
- If this function returns false or no value, Cuberite calls other plugins with the same event and
- finally places the block and removes the corresponding item from player's inventory. If this
- function returns true, no other plugin is called for this event, Cuberite sends the old block at
- the specified coords to the client and drops the packet.
- ]],
- }, -- HOOK_PLAYER_PLACING_BLOCK
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerRightClick.lua b/world/Plugins/APIDump/Hooks/OnPlayerRightClick.lua
deleted file mode 100644
index e1b95197..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerRightClick.lua
+++ /dev/null
@@ -1,40 +0,0 @@
-return
-{
- HOOK_PLAYER_RIGHT_CLICK =
- {
- CalledWhen = "A right-click packet is received from the client. Plugin may override / refuse.",
- DefaultFnName = "OnPlayerRightClick", -- also used as pagename
- Desc = [[
- This hook is called when Cuberite receives a right-click packet from the {{cClientHandle|client}}. It
- is called before any processing whatsoever is performed on the packet, meaning that hacked /
- malicious clients may be trigerring this event very often and with unchecked parameters. Therefore
- plugin authors are advised to use extreme caution with this callback.
-
- Plugins may refuse the default processing for the packet, causing Cuberite to behave as if the
- packet has never arrived. This may, however, create inconsistencies in the client - the client may
- think that they placed a block, while the server didn't process the placing, etc.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player whose client sent the packet" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
- { Name = "BlockFace", Type = "number", Notes = "Face of the block upon which the player interacted. One of the BLOCK_FACE_ constants" },
- { Name = "CursorX", Type = "number", Notes = "X-coord of the mouse crosshair on the block" },
- { Name = "CursorY", Type = "number", Notes = "Y-coord of the mouse crosshair on the block" },
- { Name = "CursorZ", Type = "number", Notes = "Z-coord of the mouse crosshair on the block" },
- },
- Returns = [[
- If the function returns false or no value, Cuberite calls other plugins' callbacks and finally sends
- the packet for further processing.
-
- If the function returns true, no other plugins are called, processing is halted.
- ]],
- }, -- HOOK_PLAYER_RIGHT_CLICK
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerRightClickingEntity.lua b/world/Plugins/APIDump/Hooks/OnPlayerRightClickingEntity.lua
deleted file mode 100644
index b271cf05..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerRightClickingEntity.lua
+++ /dev/null
@@ -1,27 +0,0 @@
-return
-{
- HOOK_PLAYER_RIGHT_CLICKING_ENTITY =
- {
- CalledWhen = "A player has right-clicked an entity. Plugins may override / refuse.",
- DefaultFnName = "OnPlayerRightClickingEntity", -- also used as pagename
- Desc = [[
- This hook is called when the {{cPlayer|player}} right-clicks an {{cEntity|entity}}. Plugins may
- override the default behavior or even cancel the default processing.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has right-clicked the entity" },
- { Name = "Entity", Type = "{{cEntity}} descendant", Notes = "The entity that has been right-clicked" },
- },
- Returns = [[
- If the functino returns false or no value, Cuberite calls other plugins' callbacks and finally does
- the default processing for the right-click. If the function returns true, no other callbacks are
- called and the default processing is skipped.
- ]],
- }, -- HOOK_PLAYER_RIGHT_CLICKING_ENTITY
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerShooting.lua b/world/Plugins/APIDump/Hooks/OnPlayerShooting.lua
deleted file mode 100644
index 7315ede7..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerShooting.lua
+++ /dev/null
@@ -1,32 +0,0 @@
-return
-{
- HOOK_PLAYER_SHOOTING =
- {
- CalledWhen = "When the player releases the bow, shooting an arrow (other projectiles: unknown)",
- DefaultFnName = "OnPlayerShooting", -- also used as pagename
- Desc = [[
- This hook is called when the {{cPlayer|player}} shoots their bow. It is called for the actual
- release of the {{cArrowEntity|arrow}}. FIXME: It is currently unknown whether other
- {{cProjectileEntity|projectiles}} (snowballs, eggs) trigger this hook.
-
- To get the player's position and direction, use the {{cPlayer}}:GetEyePosition() and
- cPlayer:GetLookVector() functions. Note that for shooting a bow, the position for the arrow creation
- is not at the eye pos, some adjustments are required. FIXME: Export the {{cPlayer}} function for
- this adjustment.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player shooting" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called, and finally
- Cuberite creates the projectile. If the functino returns true, no other callback is called and no
- projectile is created.
- ]],
- }, -- HOOK_PLAYER_SHOOTING
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerSpawned.lua b/world/Plugins/APIDump/Hooks/OnPlayerSpawned.lua
deleted file mode 100644
index 190909ee..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerSpawned.lua
+++ /dev/null
@@ -1,32 +0,0 @@
-return
-{
- HOOK_PLAYER_SPAWNED =
- {
- CalledWhen = "After a player (re)spawns in the world to which they belong to.",
- DefaultFnName = "OnPlayerSpawned", -- also used as pagename
- Desc = [[
- This hook is called after a {{cPlayer|player}} has spawned in the world. It is called after
- {{OnLogin|HOOK_LOGIN}} and {{OnPlayerJoined|HOOK_PLAYER_JOINED}}, after the player name has been
- authenticated, the initial worldtime, inventory and health have been sent to the player and the
- player spawn packet has been broadcast to all players near enough to the player spawn place. This is
- a notification-only event, plugins wishing to refuse player's entry should kick the player using the
- {{cPlayer}}:Kick() function.
-
- This hook is also called when the player respawns after death (and a respawn packet is received from
- the client, meaning the player has already clicked the Respawn button).
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has (re)spawned" },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called. If the function
- returns true, no other callbacks are called for this event. There is no overridable behavior.
- ]],
- }, -- HOOK_PLAYER_SPAWNED
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerTossingItem.lua b/world/Plugins/APIDump/Hooks/OnPlayerTossingItem.lua
deleted file mode 100644
index 880404bf..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerTossingItem.lua
+++ /dev/null
@@ -1,31 +0,0 @@
-return
-{
- HOOK_PLAYER_TOSSING_ITEM =
- {
- CalledWhen = "A player is tossing an item. Plugin may override / refuse.",
- DefaultFnName = "OnPlayerTossingItem", -- also used as pagename
- Desc = [[
- This hook is called when a {{cPlayer|player}} has tossed an item. The
- {{cPickup|pickup}} has not been spawned yet. Plugins may disallow the tossing, but in that case they
- need to clean up - the player's client already thinks the item has been tossed so the
- {{cInventory|inventory}} needs to be re-sent to the player.
-
- To get the item that is about to be tossed, call the {{cPlayer}}:GetEquippedItem() function.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player tossing an item" },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called and finally Cuberite
- creates the pickup for the item and tosses it, using {{cPlayer}}:TossHeldItem, {{cPlayer}}:TossEquippedItem,
- or {{cPlayer}}:TossPickup. If the function returns true, no other callbacks are called for this event
- and Cuberite doesn't toss the item.
- ]],
- }, -- HOOK_PLAYER_TOSSING_ITEM
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerUsedBlock.lua b/world/Plugins/APIDump/Hooks/OnPlayerUsedBlock.lua
deleted file mode 100644
index babd70fc..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerUsedBlock.lua
+++ /dev/null
@@ -1,46 +0,0 @@
-return
-{
- HOOK_PLAYER_USED_BLOCK =
- {
- CalledWhen = "A player has just used a block (chest, furnace...). Notification only.",
- DefaultFnName = "OnPlayerUsedBlock", -- also used as pagename
- Desc = [[
- This hook is called after a {{cPlayer|player}} has right-clicked a block that can be used, such as a
- {{cChestEntity|chest}} or a lever. It is called after Cuberite processes the usage (sends the UI
- handling packets / toggles redstone). Note that for UI-related blocks, the player is most likely
- still using the UI. This is a notification-only event.
-
- Note that the block coords given in this callback are for the (solid) block that is being clicked,
- not the air block between it and the player.
-
- To get the world at which the right-click occurred, use the {{cPlayer}}:GetWorld() function.
-
- See also the {{OnPlayerUsingBlock|HOOK_PLAYER_USING_BLOCK}} for a similar hook called before the
- use, the {{OnPlayerUsingItem|HOOK_PLAYER_USING_ITEM}} and {{OnPlayerUsedItem|HOOK_PLAYER_USED_ITEM}}
- for similar hooks called when a player interacts with any block with a usable item in hand, such as
- a bucket.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who used the block" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the clicked block" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the clicked block" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the clicked block" },
- { Name = "BlockFace", Type = "number", Notes = "Face of clicked block which has been clicked. One of the BLOCK_FACE_ constants" },
- { Name = "CursorX", Type = "number", Notes = "X-coord of the cursor crosshair on the block being clicked" },
- { Name = "CursorY", Type = "number", Notes = "Y-coord of the cursor crosshair on the block being clicked" },
- { Name = "CursorZ", Type = "number", Notes = "Z-coord of the cursor crosshair on the block being clicked" },
- { Name = "BlockType", Type = "number", Notes = "Block type of the clicked block" },
- { Name = "BlockMeta", Type = "number", Notes = "Block meta of the clicked block" },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called. If the function
- returns true, no other callbacks are called for this event.
- ]],
- }, -- HOOK_PLAYER_USED_BLOCK
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerUsedItem.lua b/world/Plugins/APIDump/Hooks/OnPlayerUsedItem.lua
deleted file mode 100644
index 6089928e..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerUsedItem.lua
+++ /dev/null
@@ -1,46 +0,0 @@
-return
-{
- HOOK_PLAYER_USED_ITEM =
- {
- CalledWhen = "A player has used an item in hand (bucket...)",
- DefaultFnName = "OnPlayerUsedItem", -- also used as pagename
- Desc = [[
- This hook is called after a {{cPlayer|player}} has right-clicked a block with an {{cItem|item}} that
- can be used (is not placeable, is not food and clicked block is not use-able), such as a bucket or a
- hoe. It is called after Cuberite processes the usage (places fluid / turns dirt to farmland).
- This is an information-only hook, there is no way to cancel the event anymore.
-
- Note that the block coords given in this callback are for the (solid) block that is being clicked,
- not the air block between it and the player.
-
- To get the world at which the right-click occurred, use the {{cPlayer}}:GetWorld() function. To get
- the item that the player is using, use the {{cPlayer}}:GetEquippedItem() function.
-
- See also the {{OnPlayerUsingItem|HOOK_PLAYER_USING_ITEM}} for a similar hook called before the use,
- the {{OnPlayerUsingBlock|HOOK_PLAYER_USING_BLOCK}} and {{OnPlayerUsedBlock|HOOK_PLAYER_USED_BLOCK}}
- for similar hooks called when a player interacts with a block, such as a chest.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who used the item" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the clicked block" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the clicked block" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the clicked block" },
- { Name = "BlockFace", Type = "number", Notes = "Face of clicked block which has been clicked. One of the BLOCK_FACE_ constants" },
- { Name = "CursorX", Type = "number", Notes = "X-coord of the cursor crosshair on the block being clicked" },
- { Name = "CursorY", Type = "number", Notes = "Y-coord of the cursor crosshair on the block being clicked" },
- { Name = "CursorZ", Type = "number", Notes = "Z-coord of the cursor crosshair on the block being clicked" },
- { Name = "BlockType", Type = "number", Notes = "Block type of the clicked block" },
- { Name = "BlockMeta", Type = "number", Notes = "Block meta of the clicked block" },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called. If the function
- returns true, no other callbacks are called for this event.
- ]],
- }, -- HOOK_PLAYER_USED_ITEM
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerUsingBlock.lua b/world/Plugins/APIDump/Hooks/OnPlayerUsingBlock.lua
deleted file mode 100644
index 3c496cfb..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerUsingBlock.lua
+++ /dev/null
@@ -1,47 +0,0 @@
-return
-{
- HOOK_PLAYER_USING_BLOCK =
- {
- CalledWhen = "Just before a player uses a block (chest, furnace...). Plugin may override / refuse.",
- DefaultFnName = "OnPlayerUsingBlock", -- also used as pagename
- Desc = [[
- This hook is called when a {{cPlayer|player}} has right-clicked a block that can be used, such as a
- {{cChestEntity|chest}} or a lever. It is called before Cuberite processes the usage (sends the UI
- handling packets / toggles redstone). Plugins may refuse the interaction by returning true.
-
- Note that the block coords given in this callback are for the (solid) block that is being clicked,
- not the air block between it and the player.
-
- To get the world at which the right-click occurred, use the {{cPlayer}}:GetWorld() function.
-
- See also the {{OnPlayerUsedBlock|HOOK_PLAYER_USED_BLOCK}} for a similar hook called after the use, the
- {{OnPlayerUsingItem|HOOK_PLAYER_USING_ITEM}} and {{OnPlayerUsedItem|HOOK_PLAYER_USED_ITEM}} for
- similar hooks called when a player interacts with any block with a usable item in hand, such as a
- bucket.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is using the block" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the clicked block" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the clicked block" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the clicked block" },
- { Name = "BlockFace", Type = "number", Notes = "Face of clicked block which has been clicked. One of the BLOCK_FACE_ constants" },
- { Name = "CursorX", Type = "number", Notes = "X-coord of the cursor crosshair on the block being clicked" },
- { Name = "CursorY", Type = "number", Notes = "Y-coord of the cursor crosshair on the block being clicked" },
- { Name = "CursorZ", Type = "number", Notes = "Z-coord of the cursor crosshair on the block being clicked" },
- { Name = "BlockType", Type = "number", Notes = "Block type of the clicked block" },
- { Name = "BlockMeta", Type = "number", Notes = "Block meta of the clicked block" },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called and then Cuberite
- processes the interaction. If the function returns true, no other callbacks are called for this
- event and the block is treated like any other block (i.e. if it's possible to place a torch on,
- it will be placed, and so on.)
- ]],
- }, -- HOOK_PLAYER_USING_BLOCK
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPlayerUsingItem.lua b/world/Plugins/APIDump/Hooks/OnPlayerUsingItem.lua
deleted file mode 100644
index 9b2949f9..00000000
--- a/world/Plugins/APIDump/Hooks/OnPlayerUsingItem.lua
+++ /dev/null
@@ -1,47 +0,0 @@
-return
-{
- HOOK_PLAYER_USING_ITEM =
- {
- CalledWhen = "Just before a player uses an item in hand (bucket...). Plugin may override / refuse.",
- DefaultFnName = "OnPlayerUsingItem", -- also used as pagename
- Desc = [[
- This hook is called when a {{cPlayer|player}} has right-clicked a block with an {{cItem|item}} that
- can be used (is not placeable, is not food and clicked block is not use-able), such as a bucket or a
- hoe. It is called before Cuberite processes the usage (places fluid / turns dirt to farmland).
- Plugins may refuse the interaction by returning true.
-
- Note that the block coords given in this callback are for the (solid) block that is being clicked,
- not the air block between it and the player.
-
- To get the world at which the right-click occurred, use the {{cPlayer}}:GetWorld() function. To get
- the item that the player is using, use the {{cPlayer}}:GetEquippedItem() function.
-
- See also the {{OnPlayerUsedItem|HOOK_PLAYER_USED_ITEM}} for a similar hook called after the use, the
- {{OnPlayerUsingBlock|HOOK_PLAYER_USING_BLOCK}} and {{OnPlayerUsedBlock|HOOK_PLAYER_USED_BLOCK}} for
- similar hooks called when a player interacts with a block, such as a chest.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is using the item" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the clicked block" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the clicked block" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the clicked block" },
- { Name = "BlockFace", Type = "number", Notes = "Face of clicked block which has been clicked. One of the BLOCK_FACE_ constants" },
- { Name = "CursorX", Type = "number", Notes = "X-coord of the cursor crosshair on the block being clicked" },
- { Name = "CursorY", Type = "number", Notes = "Y-coord of the cursor crosshair on the block being clicked" },
- { Name = "CursorZ", Type = "number", Notes = "Z-coord of the cursor crosshair on the block being clicked" },
- { Name = "BlockType", Type = "number", Notes = "Block type of the clicked block" },
- { Name = "BlockMeta", Type = "number", Notes = "Block meta of the clicked block" },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called and then Cuberite
- processes the interaction. If the function returns true, no other callbacks are called for this
- event and the interaction is silently dropped.
- ]],
- }, -- HOOK_PLAYER_USING_ITEM
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPluginMessage.lua b/world/Plugins/APIDump/Hooks/OnPluginMessage.lua
deleted file mode 100644
index 743d3bb5..00000000
--- a/world/Plugins/APIDump/Hooks/OnPluginMessage.lua
+++ /dev/null
@@ -1,25 +0,0 @@
-return
-{
- HOOK_PLUGIN_MESSAGE =
- {
- CalledWhen = "The server receives a plugin message from a client",
- DefaultFnName = "OnPluginMessage", -- also used as pagename
- Desc = [[
- A plugin may implement an OnPluginMessage() function and register it as a Hook to process plugin messages
- from the players. The function is then called for every plugin message sent from any player.
- ]],
- Params = {
- { Name = "Client", Type = "{{cClientHandle}}", Notes = "The client who sent the plugin message" },
- { Name = "Channel", Type = "string", Notes = "The channel on which the message was sent" },
- { Name = "Message", Type = "string", Notes = "The message's payload" },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called. If the function
- returns true, no other callbacks are called for this event.
- ]],
- }, -- HOOK_CHAT
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPluginsLoaded.lua b/world/Plugins/APIDump/Hooks/OnPluginsLoaded.lua
deleted file mode 100644
index 2c8a5a2c..00000000
--- a/world/Plugins/APIDump/Hooks/OnPluginsLoaded.lua
+++ /dev/null
@@ -1,84 +0,0 @@
-return
-{
- HOOK_PLUGINS_LOADED =
- {
- CalledWhen = "All the enabled plugins have been loaded",
- DefaultFnName = "OnPluginsLoaded", -- also used as pagename
- Desc = [[
- This callback gets called when the server finishes loading and initializing plugins. This is the
- perfect occasion for a plugin to query other plugins through {{cPluginManager}}:GetPlugin() and
- possibly start communicating with them using the {{cPlugin}}:Call() function.
- ]],
- Params = {},
- Returns = [[
- The return value is ignored, all registered callbacks are called.
- ]],
- CodeExamples =
- {
- {
- Title = "CoreMessaging",
- Desc = [[
- This example shows how to implement the CoreMessaging functionality - messages to players will be
- sent through the Core plugin, formatted by that plugin. As a fallback for when the Core plugin is
- not present, the messages are sent directly by this code, unformatted.
- ]],
- Code = [[
--- These are the fallback functions used when the Core is not present:
-local function SendMessageFallback(a_Player, a_Message)
- a_Player:SendMessage(a_Message);
-end
-
-local function SendMessageSuccessFallback(a_Player, a_Message)
- a_Player:SendMessage(a_Message);
-end
-
-local function SendMessageFailureFallback(a_Player, a_Message)
- a_Player:SendMessage(a_Message);
-end
-
--- These three "variables" will hold the actual functions to call.
--- By default they are initialized to the Fallback variants,
--- but will be redirected to Core when all plugins load
-SendMessage = SendMessageFallback;
-SendMessageSuccess = SendMessageSuccessFallback;
-SendMessageFailure = SendMessageFailureFallback;
-
--- The callback tries to connect to the Core
--- If successful, overwrites the three functions with Core ones
-local function OnPluginsLoaded()
- local CorePlugin = cPluginManager:Get():GetPlugin("Core");
- if (CorePlugin == nil) then
- -- The Core is not loaded, keep the Fallback functions
- return;
- end
-
- -- Overwrite the three functions with Core functionality:
- SendMessage = function(a_Player, a_Message)
- CorePlugin:Call("SendMessage", a_Player, a_Message);
- end
- SendMessageSuccess = function(a_Player, a_Message)
- CorePlugin:Call("SendMessageSuccess", a_Player, a_Message);
- end
- SendMessageFailure = function(a_Player, a_Message)
- CorePlugin:Call("SendMessageFailure", a_Player, a_Message);
- end
-end
-
--- Global scope, register the callback:
-cPluginManager.AddHook(cPluginManager.HOOK_PLUGINS_LOADED, CoreMessagingPluginsLoaded);
-
-
--- Usage, anywhere else in the plugin:
-SendMessageFailure(
- a_Player,
- "Cannot teleport to player, the destination player " .. PlayerName .. " was not found"
-);
- ]],
- },
- } , -- CodeExamples
- }, -- HOOK_PLUGINS_LOADED
-}
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPostCrafting.lua b/world/Plugins/APIDump/Hooks/OnPostCrafting.lua
deleted file mode 100644
index 0dc9d4c7..00000000
--- a/world/Plugins/APIDump/Hooks/OnPostCrafting.lua
+++ /dev/null
@@ -1,36 +0,0 @@
-return
-{
- HOOK_POST_CRAFTING =
- {
- CalledWhen = "After the built-in recipes are checked and a recipe was found.",
- DefaultFnName = "OnPostCrafting", -- also used as pagename
- Desc = [[
- This hook is called when a {{cPlayer|player}} changes contents of their
- {{cCraftingGrid|crafting grid}}, after the recipe has been established by Cuberite. Plugins may use
- this to modify the resulting recipe or provide an alternate recipe.
-
- If a plugin implements custom recipes, it should do so using the {{OnPreCrafting|HOOK_PRE_CRAFTING}}
- hook, because that will save the server from going through the built-in recipes. The
- HOOK_POST_CRAFTING hook is intended as a notification, with a chance to tweak the result.
-
- Note that this hook is not called if a built-in recipe is not found;
- {{OnCraftingNoRecipe|HOOK_CRAFTING_NO_RECIPE}} is called instead in such a case.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has changed their crafting grid contents" },
- { Name = "Grid", Type = "{{cCraftingGrid}}", Notes = "The new crafting grid contents" },
- { Name = "Recipe", Type = "{{cCraftingRecipe}}", Notes = "The recipe that Cuberite has decided to use (can be tweaked by plugins)" },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called. If the function
- returns true, no other callbacks are called for this event. In either case, Cuberite uses the value
- of Recipe as the recipe to be presented to the player.
- ]],
- }, -- HOOK_POST_CRAFTING
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnPreCrafting.lua b/world/Plugins/APIDump/Hooks/OnPreCrafting.lua
deleted file mode 100644
index 8f24fc88..00000000
--- a/world/Plugins/APIDump/Hooks/OnPreCrafting.lua
+++ /dev/null
@@ -1,37 +0,0 @@
-return
-{
- HOOK_PRE_CRAFTING =
- {
- CalledWhen = "Before the built-in recipes are checked.",
- DefaultFnName = "OnPreCrafting", -- also used as pagename
- Desc = [[
- This hook is called when a {{cPlayer|player}} changes contents of their
- {{cCraftingGrid|crafting grid}}, before the built-in recipes are searched for a match by Cuberite.
- Plugins may use this hook to provide a custom recipe.
-
- If you intend to tweak built-in recipes, use the {{OnPostCrafting|HOOK_POST_CRAFTING}} hook, because
- that will be called once the built-in recipe is matched.
-
- Also note a third hook, {{OnCraftingNoRecipe|HOOK_CRAFTING_NO_RECIPE}}, that is called when Cuberite
- cannot find any built-in recipe for the given ingredients.
- ]],
- Params =
- {
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has changed their crafting grid contents" },
- { Name = "Grid", Type = "{{cCraftingGrid}}", Notes = "The new crafting grid contents" },
- { Name = "Recipe", Type = "{{cCraftingRecipe}}", Notes = "The recipe that Cuberite will use. Modify this object to change the recipe" },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called and then Cuberite
- searches the built-in recipes. The Recipe output parameter is ignored in this case.
-
- If the function returns true, no other callbacks are called for this event and Cuberite uses the
- recipe stored in the Recipe output parameter.
- ]],
- }, -- HOOK_PRE_CRAFTING
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnProjectileHitBlock.lua b/world/Plugins/APIDump/Hooks/OnProjectileHitBlock.lua
deleted file mode 100644
index 72cf8582..00000000
--- a/world/Plugins/APIDump/Hooks/OnProjectileHitBlock.lua
+++ /dev/null
@@ -1,29 +0,0 @@
-return
-{
- HOOK_PROJECTILE_HIT_BLOCK =
- {
- CalledWhen = "A projectile hits a solid block.",
- DefaultFnName = "OnProjectileHitBlock", -- also used as pagename
- Desc = [[
- This hook is called when a {{cProjectileEntity|projectile}} hits a solid block..
- ]],
- Params =
- {
- { Name = "ProjectileEntity", Type = "{{cProjectileEntity}}", Notes = "The projectile that hit an entity." },
- { Name = "BlockX", Type = "number", Notes = "The X-coord where the projectile hit." },
- { Name = "BlockY", Type = "number", Notes = "The Y-coord where the projectile hit." },
- { Name = "BlockZ", Type = "number", Notes = "The Z-coord where the projectile hit." },
- { Name = "BlockFace", Type = "number", Notes = "The side of the block where the projectile hit." },
- { Name = "BlockHitPos", Type = "Vector3d", Notes = "The exact position where the projectile hit." },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event and the projectile flies through block..
- ]],
- }, -- HOOK_PROJECTILE_HIT_BLOCK
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnProjectileHitEntity.lua b/world/Plugins/APIDump/Hooks/OnProjectileHitEntity.lua
deleted file mode 100644
index dd949fb4..00000000
--- a/world/Plugins/APIDump/Hooks/OnProjectileHitEntity.lua
+++ /dev/null
@@ -1,25 +0,0 @@
-return
-{
- HOOK_PROJECTILE_HIT_ENTITY =
- {
- CalledWhen = "A projectile hits another entity.",
- DefaultFnName = "OnProjectileHitEntity", -- also used as pagename
- Desc = [[
- This hook is called when a {{cProjectileEntity|projectile}} hits another entity.
- ]],
- Params =
- {
- { Name = "ProjectileEntity", Type = "{{cProjectileEntity}}", Notes = "The projectile that hit an entity." },
- { Name = "Entity", Type = "{{cEntity}}", Notes = "The entity wich was hit." },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event and the projectile flies through the entity.
- ]],
- }, -- HOOK_PROJECTILE_HIT_ENTITY
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnServerPing.lua b/world/Plugins/APIDump/Hooks/OnServerPing.lua
deleted file mode 100644
index 43046578..00000000
--- a/world/Plugins/APIDump/Hooks/OnServerPing.lua
+++ /dev/null
@@ -1,53 +0,0 @@
-return
-{
- HOOK_SERVER_PING =
- {
- CalledWhen = "Client pings the server from the server list.",
- DefaultFnName = "OnServerPing", -- also used as pagename
- Desc = [[
- A plugin may implement an OnServerPing() function and register it as a Hook to process pings from
- clients in the server server list. It can change the logged in players and player capacity, as well
- as the server description and the favicon, that are displayed to the client in the server list.
-
- The client handle already has its protocol version assigned to it, so the plugin can check that; however,
- there's no username associated with the client yet, and no player object.
- ]],
- Params = {
- { Name = "ClientHandle", Type = "{{cClientHandle}}", Notes = "The client handle that pinged the server" },
- { Name = "ServerDescription", Type = "string", Notes = "The server description" },
- { Name = "OnlinePlayersCount", Type = "number", Notes = "The number of players currently on the server" },
- { Name = "MaxPlayersCount", Type = "number", Notes = "The current player cap for the server" },
- { Name = "Favicon", Type = "string", Notes = "The base64 encoded favicon to be displayed in the server list for compatible clients" },
- },
- Returns = [[
- The plugin can return whether to continue processing of the hook with other plugins, the server description to
- be displayed to the client, the currently online players, the player cap and the base64/png favicon data, in that order.
- ]],
- CodeExamples = {
- {
- Title = "Change information returned to the player",
- Desc = "Tells the client that the server description is 'test', there are one more players online than there actually are, and that the player cap is zero. It also changes the favicon data.",
- Code = [[
-function OnServerPing(ClientHandle, ServerDescription, OnlinePlayers, MaxPlayers, Favicon)
- -- Change Server Description
- ServerDescription = "Test"
-
- -- Change online / max players
- OnlinePlayers = OnlinePlayers + 1
- MaxPlayers = 0
-
- -- Change favicon
- if cFile:IsFile("my-favicon.png") then
- local FaviconData = cFile:ReadWholeFile("my-favicon.png")
- if (FaviconData ~= "") and (FaviconData ~= nil) then
- Favicon = Base64Encode(FaviconData)
- end
- end
-
- return false, ServerDescription, OnlinePlayers, MaxPlayers, Favicon
-end
- ]],
- },
- },
- }, -- HOOK_SERVER_PING
-}
diff --git a/world/Plugins/APIDump/Hooks/OnSpawnedEntity.lua b/world/Plugins/APIDump/Hooks/OnSpawnedEntity.lua
deleted file mode 100644
index 037a90f1..00000000
--- a/world/Plugins/APIDump/Hooks/OnSpawnedEntity.lua
+++ /dev/null
@@ -1,31 +0,0 @@
-return
-{
- HOOK_SPAWNED_ENTITY =
- {
- CalledWhen = "After an entity is spawned in the world.",
- DefaultFnName = "OnSpawnedEntity", -- also used as pagename
- Desc = [[
- This hook is called after the server spawns an {{cEntity|entity}}. This is an information-only
- callback, the entity is already spawned by the time it is called. If the entity spawned is a
- {{cMonster|monster}}, the {{OnSpawnedMonster|HOOK_SPAWNED_MONSTER}} hook is called before this
- hook.
-
- See also the {{OnSpawningEntity|HOOK_SPAWNING_ENTITY}} hook for a similar hook called before the
- entity is spawned.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world in which the entity has spawned" },
- { Name = "Entity", Type = "{{cEntity}} descentant", Notes = "The entity that has spawned" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event.
- ]],
- }, -- HOOK_SPAWNED_ENTITY
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnSpawnedMonster.lua b/world/Plugins/APIDump/Hooks/OnSpawnedMonster.lua
deleted file mode 100644
index c319a77e..00000000
--- a/world/Plugins/APIDump/Hooks/OnSpawnedMonster.lua
+++ /dev/null
@@ -1,30 +0,0 @@
-return
-{
- HOOK_SPAWNED_MONSTER =
- {
- CalledWhen = "After a monster is spawned in the world",
- DefaultFnName = "OnSpawnedMonster", -- also used as pagename
- Desc = [[
- This hook is called after the server spawns a {{cMonster|monster}}. This is an information-only
- callback, the monster is already spawned by the time it is called. After this hook is called, the
- {{OnSpawnedEntity|HOOK_SPAWNED_ENTITY}} is called for the monster entity.
-
- See also the {{OnSpawningMonster|HOOK_SPAWNING_MONSTER}} hook for a similar hook called before the
- monster is spawned.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world in which the monster has spawned" },
- { Name = "Monster", Type = "{{cMonster}} descendant", Notes = "The monster that has spawned" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event.
- ]],
- }, -- HOOK_SPAWNED_MONSTER
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnSpawningEntity.lua b/world/Plugins/APIDump/Hooks/OnSpawningEntity.lua
deleted file mode 100644
index e2bd1c94..00000000
--- a/world/Plugins/APIDump/Hooks/OnSpawningEntity.lua
+++ /dev/null
@@ -1,33 +0,0 @@
-return
-{
- HOOK_SPAWNING_ENTITY =
- {
- CalledWhen = "Before an entity is spawned in the world.",
- DefaultFnName = "OnSpawningEntity", -- also used as pagename
- Desc = [[
- This hook is called before the server spawns an {{cEntity|entity}}. The plugin can either modify the
- entity before it is spawned, or disable the spawning altogether. You can't disable the spawning if the
- entity is a player. If the entity spawning is a monster, the {{OnSpawningMonster|HOOK_SPAWNING_MONSTER}}
- hook is called before this hook.
-
- See also the {{OnSpawnedEntity|HOOK_SPAWNED_ENTITY}} hook for a similar hook called after the
- entity is spawned.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world in which the entity will spawn" },
- { Name = "Entity", Type = "{{cEntity}} descentant", Notes = "The entity that will spawn" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. Finally, the server
- spawns the entity with whatever parameters have been set on the {{cEntity}} object by the callbacks.
- If the function returns true, no other callback is called for this event and the entity is not
- spawned.
- ]],
- }, -- HOOK_SPAWNING_ENTITY
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnSpawningMonster.lua b/world/Plugins/APIDump/Hooks/OnSpawningMonster.lua
deleted file mode 100644
index 4c0519e2..00000000
--- a/world/Plugins/APIDump/Hooks/OnSpawningMonster.lua
+++ /dev/null
@@ -1,33 +0,0 @@
-return
-{
- HOOK_SPAWNING_MONSTER =
- {
- CalledWhen = "Before a monster is spawned in the world.",
- DefaultFnName = "OnSpawningMonster", -- also used as pagename
- Desc = [[
- This hook is called before the server spawns a {{cMonster|monster}}. The plugins may modify the
- monster's parameters in the {{cMonster}} class, or disallow the spawning altogether. This hook is
- called before the {{OnSpawningEntity|HOOK_SPAWNING_ENTITY}} is called for the monster entity.
-
- See also the {{OnSpawnedMonster|HOOK_SPAWNED_MONSTER}} hook for a similar hook called after the
- monster is spawned.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world in which the entity will spawn" },
- { Name = "Monster", Type = "{{cMonster}} descentant", Notes = "The monster that will spawn" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. Finally, the server
- spawns the monster with whatever parameters the plugins set in the cMonster parameter.
-
- If the function returns true, no other callback is called for this event and the monster won't
- spawn.
- ]],
- }, -- HOOK_SPAWNING_MONSTER
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnTakeDamage.lua b/world/Plugins/APIDump/Hooks/OnTakeDamage.lua
deleted file mode 100644
index 608126f2..00000000
--- a/world/Plugins/APIDump/Hooks/OnTakeDamage.lua
+++ /dev/null
@@ -1,31 +0,0 @@
-return
-{
- HOOK_TAKE_DAMAGE =
- {
- CalledWhen = "An {{cEntity|entity}} is taking any kind of damage",
- DefaultFnName = "OnTakeDamage", -- also used as pagename
- Desc = [[
- This hook is called when any {{cEntity}} descendant, such as a {{cPlayer|player}} or a
- {{cMonster|mob}}, takes any kind of damage. The plugins may modify the amount of damage or effects
- with this hook by editting the {{TakeDamageInfo}} object passed.
-
- This hook is called after the final damage is calculated, including all the possible weapon
- {{cEnchantments|enchantments}}, armor protection and potion effects.
- ]],
- Params =
- {
- { Name = "Receiver", Type = "{{cEntity}} descendant", Notes = "The entity taking damage" },
- { Name = "TDI", Type = "{{TakeDamageInfo}}", Notes = "The damage type, cause and effects. Plugins may modify this object to alter the final damage applied." },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called and then the server
- applies the final values from the TDI object to Receiver. If the function returns true, no other
- callbacks are called, and no damage nor effects are applied.
- ]],
- }, -- HOOK_TAKE_DAMAGE
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnTick.lua b/world/Plugins/APIDump/Hooks/OnTick.lua
deleted file mode 100644
index d8c32925..00000000
--- a/world/Plugins/APIDump/Hooks/OnTick.lua
+++ /dev/null
@@ -1,29 +0,0 @@
-return
-{
- HOOK_TICK =
- {
- CalledWhen = "Every server tick (approximately 20 times per second)",
- DefaultFnName = "OnTick", -- also used as pagename
- Desc = [[
- This hook is called every game tick (50 msec, or 20 times a second). If the server is overloaded,
- the interval is larger, which is indicated by the TimeDelta parameter.
-
- This hook is called in the context of the server-tick thread, that is, the thread that takes care of
- {{cClientHandle|client connections}} before they're assigned to {{cPlayer|player entities}}, and
- processing console commands.
- ]],
- Params =
- {
- { Name = "TimeDelta", Type = "number", Notes = "The number of milliseconds elapsed since the last server tick. Will not be less than 50 msec." },
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called. If the function
- returns true, no other callbacks are called. There is no overridable behavior.
- ]],
- }, -- HOOK_TICK
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnUpdatedSign.lua b/world/Plugins/APIDump/Hooks/OnUpdatedSign.lua
deleted file mode 100644
index 937e6b98..00000000
--- a/world/Plugins/APIDump/Hooks/OnUpdatedSign.lua
+++ /dev/null
@@ -1,38 +0,0 @@
-return
-{
- HOOK_UPDATED_SIGN =
- {
- CalledWhen = "After the sign text is updated. Notification only.",
- DefaultFnName = "OnUpdatedSign", -- also used as pagename
- Desc = [[
- This hook is called after a sign has had its text updated. The text is already updated at this
- point.
-
The update may have been caused either by a {{cPlayer|player}} directly updating the sign, or by
- a plugin changing the sign text using the API.
-
- See also the {{OnUpdatingSign|HOOK_UPDATING_SIGN}} hook for a similar hook called before the update,
- with a chance to modify the text.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world in which the sign resides" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the sign" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the sign" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the sign" },
- { Name = "Line1", Type = "string", Notes = "1st line of the new text" },
- { Name = "Line2", Type = "string", Notes = "2nd line of the new text" },
- { Name = "Line3", Type = "string", Notes = "3rd line of the new text" },
- { Name = "Line4", Type = "string", Notes = "4th line of the new text" },
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is changing the text. May be nil for non-player updates." }
- },
- Returns = [[
- If the function returns false or no value, other plugins' callbacks are called. If the function
- returns true, no other callbacks are called. There is no overridable behavior.
- ]],
- }, -- HOOK_UPDATED_SIGN
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnUpdatingSign.lua b/world/Plugins/APIDump/Hooks/OnUpdatingSign.lua
deleted file mode 100644
index d7445818..00000000
--- a/world/Plugins/APIDump/Hooks/OnUpdatingSign.lua
+++ /dev/null
@@ -1,58 +0,0 @@
-return
-{
- HOOK_UPDATING_SIGN =
- {
- CalledWhen = "Before the sign text is updated. Plugin may modify the text / refuse.",
- DefaultFnName = "OnUpdatingSign", -- also used as pagename
- Desc = [[
- This hook is called when a sign text is about to be updated, either as a result of player's
- manipulation or any other event, such as a plugin setting the sign text. Plugins may modify the text
- or refuse the update altogether.
-
- See also the {{OnUpdatedSign|HOOK_UPDATED_SIGN}} hook for a similar hook called after the update.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "The world in which the sign resides" },
- { Name = "BlockX", Type = "number", Notes = "X-coord of the sign" },
- { Name = "BlockY", Type = "number", Notes = "Y-coord of the sign" },
- { Name = "BlockZ", Type = "number", Notes = "Z-coord of the sign" },
- { Name = "Line1", Type = "string", Notes = "1st line of the new text" },
- { Name = "Line2", Type = "string", Notes = "2nd line of the new text" },
- { Name = "Line3", Type = "string", Notes = "3rd line of the new text" },
- { Name = "Line4", Type = "string", Notes = "4th line of the new text" },
- { Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is changing the text. May be nil for non-player updates." }
- },
- Returns = [[
- The function may return up to five values. If the function returns true as the first value, no other
- callbacks are called for this event and the sign is not updated. If the function returns no value or
- false as its first value, other plugins' callbacks are called.
-
- The other up to four values returned are used to update the sign text, line by line, respectively.
- Note that other plugins may again update the texts (if the first value returned is false).
- ]],
- CodeExamples =
- {
- {
- Title = "Add player signature",
- Desc = "The following example appends a player signature to the last line, if the sign is updated by a player:",
- Code = [[
-function OnUpdatingSign(World, BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4, Player)
- if (Player == nil) then
- -- Not changed by a player
- return false;
- end
-
- -- Sign with playername, allow other plugins to interfere:
- return false, Line1, Line2, Line3, Line4 .. Player:GetName();
-end
- ]],
- }
- } ,
- }, -- HOOK_UPDATING_SIGN
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnWeatherChanged.lua b/world/Plugins/APIDump/Hooks/OnWeatherChanged.lua
deleted file mode 100644
index 2a3bbe92..00000000
--- a/world/Plugins/APIDump/Hooks/OnWeatherChanged.lua
+++ /dev/null
@@ -1,28 +0,0 @@
-return
-{
- HOOK_WEATHER_CHANGED =
- {
- CalledWhen = "The weather has changed",
- DefaultFnName = "OnWeatherChanged", -- also used as pagename
- Desc = [[
- This hook is called after the weather has changed in a {{cWorld|world}}. The new weather has already
- been sent to the clients.
-
- See also the {{OnWeatherChanging|HOOK_WEATHER_CHANGING}} hook for a similar hook called before the
- change.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "World for which the weather has changed" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event. There is no overridable behavior.
- ]],
- }, -- HOOK_WEATHER_CHANGED
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnWeatherChanging.lua b/world/Plugins/APIDump/Hooks/OnWeatherChanging.lua
deleted file mode 100644
index bb809af1..00000000
--- a/world/Plugins/APIDump/Hooks/OnWeatherChanging.lua
+++ /dev/null
@@ -1,35 +0,0 @@
-return
-{
- HOOK_WEATHER_CHANGING =
- {
- CalledWhen = "The weather is about to change",
- DefaultFnName = "OnWeatherChanging", -- also used as pagename
- Desc = [[
- This hook is called when the current weather has expired and a new weather is selected. Plugins may
- override the new weather being set.
-
- The new weather setting is sent to the clients only after this hook has been processed.
-
- See also the {{OnWeatherChanged|HOOK_WEATHER_CHANGED}} hook for a similar hook called after the
- change.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "World for which the weather is changing" },
- { Name = "Weather", Type = "number", Notes = "The newly selected weather. One of wSunny, wRain, wStorm" },
- },
- Returns = [[
- The hook handler can return up to two values. If the first value is false or not present, the server
- calls other plugins' callbacks and finally sets the weather. If it is true, the server doesn't call any
- more callbacks for this hook. The second value returned is used as the new weather. If no value is
- given, the weather from the parameters is used as the weather. Returning false as the first value and a
- specific weather constant as the second value makes the server call the rest of the hook handlers with
- the new weather value.
- ]],
- }, -- HOOK_WEATHER_CHANGING
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnWorldStarted.lua b/world/Plugins/APIDump/Hooks/OnWorldStarted.lua
deleted file mode 100644
index 61e3de86..00000000
--- a/world/Plugins/APIDump/Hooks/OnWorldStarted.lua
+++ /dev/null
@@ -1,24 +0,0 @@
-return
-{
- HOOK_WORLD_STARTED =
- {
- CalledWhen = "A {{cWorld|world}} is initialized",
- DefaultFnName = "OnWorldStarted", -- also used as pagename
- Desc = [[
- This hook is called whenever a {{cWorld|world}} is initialized.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "World that is started" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event. There is no overridable behavior.
- ]],
- }, -- HOOK_WORLD_STARTED
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/Hooks/OnWorldTick.lua b/world/Plugins/APIDump/Hooks/OnWorldTick.lua
deleted file mode 100644
index 657716d9..00000000
--- a/world/Plugins/APIDump/Hooks/OnWorldTick.lua
+++ /dev/null
@@ -1,29 +0,0 @@
-return
-{
- HOOK_WORLD_TICK =
- {
- CalledWhen = "Every world tick (about 20 times per second), separately for each world",
- DefaultFnName = "OnWorldTick", -- also used as pagename
- Desc = [[
- This hook is called for each {{cWorld|world}} every tick (50 msec, or 20 times a second). If the
- world is overloaded, the interval is larger, which is indicated by the TimeDelta parameter.
-
- This hook is called in the world's tick thread context and thus has access to all world data
- guaranteed without blocking.
- ]],
- Params =
- {
- { Name = "World", Type = "{{cWorld}}", Notes = "World that is ticking" },
- { Name = "TimeDelta", Type = "number", Notes = "The number of milliseconds since the previous game tick. Will not be less than 50 msec" },
- },
- Returns = [[
- If the function returns false or no value, the next plugin's callback is called. If the function
- returns true, no other callback is called for this event. There is no overridable behavior.
- ]],
- }, -- HOOK_WORLD_TICK
-}
-
-
-
-
-
diff --git a/world/Plugins/APIDump/InfoFile.html b/world/Plugins/APIDump/InfoFile.html
deleted file mode 100644
index 6f70e5b5..00000000
--- a/world/Plugins/APIDump/InfoFile.html
+++ /dev/null
@@ -1,264 +0,0 @@
-
-
-
For a long time Cuberite plugins were plagued by poor documentation. The plugins worked, people who wrote them knew how to use them, but for anyone new to the plugin it was a terrible ordeal learning how to use it. Most of the times, the plugin authors only wrote what commands the plugin supported, sometimes not even that. Then, there was a call to action to put an end to this, to make documenting the plugins easy and at the same time centralized. Thus, the Info.lua file was born.
-
-
Most plugins have some parts that are the same across all the plugins. These are commands, console commands and their permissions. If a plugin implemented a command, it would practically copy & paste the same code over and over again. So it makes sense to extract only unique information, centralize it and automate all the parts around it. This was another reason for the Info.lua file - it is a central hub of commands, console commands and their permissions.
-
-
Last, but not least, we want to make a plugin repository on the web in the future, a repository that would store plugins, their descriptions, comments. It makes sense that the centralized information can be parsed by the repository automatically, so that advanced things, such as searching for a plugin based on a command, or determining whether two plugins collide command-wise, are possible.
-
-
After this file format has been devised, a tool has been written that allows for an easy generation of the documentation for the plugin in various formats. It outputs the documentation in a format that is perfect for pasting into the forum. It generates documentation in a Markup format to use in README.md on GitHub and similar sites. The clever thing is that you don't need to keep all those formats in sync manually - you edit the Info.lua file and this tool will re-generate the documentation for you.
-
-
So to sum up, the Info.lua file contains the plugins' commands, console commands, their permissions and possibly the overall plugin documentation, in a structured manner that can be parsed by a program, yet is human readable and editable.
The file consist of a declaration of a single Lua table, g_PluginInfo. This table contains all the information, structured, as its members. Each member can be a structure by itself. The entire file is a valid Lua source file, so any tool that syntax-checks Lua source can syntax-check this file. The file is somewhat forward- and backward- compatible, in the sense that it can be extended in any way without breaking.
-
Here's a skeleton of the file:
-
-g_PluginInfo =
-{
- Name = "Example Plugin",
- Date = "2014-06-12",
- Description = "This is an example plugin that shows how to use the Info.lua file",
-
- -- The following members will be documented in greater detail later:
- AdditionalInfo = {},
- Commands = {},
- ConsoleCommands = {},
- Permissions = {},
-}
-
-
As you can see, the structure is pretty straightforward. Note that the order of the elements inside the table is not important (Lua property).
-
-
The first few elements are for book-keeping. They declare the plugin's name, the date in ISO-format, representing the version of the plugin, and the description. The idea is that the description sums up what the plugin is all about, within some two or three sentences.
This table is used for more detailed description of the plugin. If there is any non-trivial setup process, dependencies, describe them here. This is where the description should get detailed. Don't worry about using several paragraphs of text here, if it makes the plugin easier to understand.
-
-
The table should have the following layout:
-
-AdditionalInfo =
-{
- {
- Title = "Chapter 1",
- Contents = "Describe one big aspect of the plugin here",
- },
- {
- Title = "Chapter 2",
- Contents = "Describe another big topic",
- },
-}
-
-
The idea here is that the tool that is used to generate the documentation from the Info.lua file will create a linkified table of contents and then each of the information elements' contents. This information should be all that is needed to successfully configure, run and manage the plugin.
The commands table lists all the commands that the plugin implements, together with their handler functions, required permissions, help strings and further information. The table supports recursion, which allows plugins to create multi-word commands easily (such as "//schematic load" and "//schematic save"), each having its own separate handler.
-
-
The table uses structure similar to the following:
-
-Commands =
-{
- ["/cmd1"] =
- {
- HelpString = "Performs the first action",
- Permission = "firstplugin.cmds.1",
- Alias = "/c1",
- Handler = HandleCmd1,
- ParameterCombinations =
- {
- {
- Params = "x y z",
- Help = "Performs the first action at the specified coordinates",
- },
- {
- Params = "-p",
- Help = "Performs the first action at the player's coordinates",
- }
- },
- },
- ["/cmd2"] =
- {
- Alias = {"/c2", "//c2" },
- Subcommands =
- {
- sub1 = -- This declares a "/cmd2 sub1" command
- {
- HelpString = "Performs the second action's first subcommand",
- Permission = "firstplugin.cmds.2.1",
- Alias = "1",
- Handler = HandleCmd2Sub1,
- ParameterCombinations =
- {
- {
- Params = "x y z",
- Help = "Performs the second action's first subcommand at the specified coordinates",
- },
- {
- Params = "-p",
- Help = "Performs the second action's first subcommand at the player's coordinates",
- }
- },
- },
- sub2 = -- Declares a "/cmd2 sub2" command
- {
- HelpString = "Performs the second action's second subcommand",
- Permission = "firstplugin.cmds.2.2",
- Handler = HandleCmd2Sub2,
- },
- },
- },
-}
-
-
-
Although it may seem overwhelming at first, there is a "method to this madness". Each element of the Commands table defines one command. Most commands start with a slash, so the special Lua syntax for table elements with non-standard names needs to be applied (["/cmd1"] =). The command can either specify subcommands, or a handler function (specifying both is UndefinedBehavior). Subcommands uses the same structure as the entire Commands table, recursively.
-
-
The permission element specifies that the command is only available with the specified permission. Note that the permission for subcommand's parent isn't checked when the subcommand is called. This means that specifying the permission for a command that has subcommands has no effect whatsoever, but is discouraged because we may add processing for that in the future.
-
-
The ParameterCombinations table is used only for generating the documentation, it lists the various combinations of parameters that the command supports. It's worth specifying even if the command supports only one combination, because that combination will get documented this way.
-
-
The Alias member specifies any possible aliases for the command. Each alias is registered separately and if there is a subcommand table, it is applied to all aliases, just as one would expect. You can specify either a single string as the value (if there's only one alias), or a table of strings for multiple aliases. Commands with no aliases do not need to specify this member at all.
The purpose of this table is to document permissions that the plugin uses. The documentation generator automatically collects the permissions specified in the Command table; the Permissions table adds a description for these permissions and may declare other permissions that aren't specifically included in the Command table.
-
-
-Permissions =
-{
- ["firstplugin.cmd.1.1"] =
- {
- Description = "Allows the players to build high towers using the first action.",
- RecommendedGroups = "players",
- },
- ["firstplugin.cmd.2.1"] =
- {
- Description = "Allows the players to kill entities using the second action. Note that this may be misused to kill other players, too.",
- RecommendedGroups = "admins, mods",
- },
-}
-
-
-
The RecommendedGroup element lists, in plain English, the intended groups for which the permission should be enabled on a typical server. Plugin authors are advised to create reasonable defaults, prefering security to openness, so that admins using these settings blindly don't expose their servers to malicious users.
Just writing the Info.lua file and saving it to the plugin folder is not enough for it to actually be used. Your plugin needs to include the following boilerplate code, preferably in its Initialize() function:
-
--- Use the InfoReg shared library to process the Info.lua file:
-dofile(cPluginManager:GetPluginsPath() .. "/InfoReg.lua")
-RegisterPluginInfoCommands()
-RegisterPluginInfoConsoleCommands()
-
-
-
Of course, if your plugin doesn't have any console commands, it doesn't need to call the RegisterPluginInfoConsoleCommands() function, and similarly if it doesn't have any in-game commands, it doesn't need to call the RegisterPluginInfoCommands() function.
There are several plugins that already implement this approach. You can visit them for inspiration and to see what the generated documentation looks like:
-
-
-
-
-
-
-
-
diff --git a/world/Plugins/APIDump/LICENSE-prettify.txt b/world/Plugins/APIDump/LICENSE-prettify.txt
deleted file mode 100644
index b7f86df2..00000000
--- a/world/Plugins/APIDump/LICENSE-prettify.txt
+++ /dev/null
@@ -1,191 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- Copyright 2011 Mike Samuel et al
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/world/Plugins/APIDump/SettingUpDecoda.html b/world/Plugins/APIDump/SettingUpDecoda.html
deleted file mode 100644
index d9b91ed3..00000000
--- a/world/Plugins/APIDump/SettingUpDecoda.html
+++ /dev/null
@@ -1,67 +0,0 @@
-
-
-
-
- Cuberite - Setting up Decoda
-
-
-
-
-
-
-
-
-
-
Setting up the Decoda IDE
-
- This article will explain how to set up Decoda, an IDE for writing Lua code, so that you can develop Cuberite plugins with the comfort of an IDE.
-
-
About Decoda
-
-
To quickly introduce Decoda, it is an IDE for writing Lua code. It has the basic features expected of an IDE - you can group files into project, you can edit multiple files in a tabbed editor, the code is syntax-highlighted. Code completion, symbol browsing, and more. It also features a Lua debugger that allows you to debug your Lua code within any application that embeds the Lua runtime or uses Lua as a dynamic-link library (DLL). Although it is written using the multiplatform WxWidgets toolkit, it hasn't yet been ported to any platform other than 32-bit Windows. This unfortunately means that Linux users will not be able to use it. It can be used on 64-bit Windows, but the debugger only works for 32-bit programs.
-
Here's a screenshot of a default Decoda window with the debugger stepping through the code (scaled down):
-
-
As you can see, you can set breakpoints in the code, inspect variables' values, view both the Lua and native (C++) call-stacks. Decoda also breaks program execution when a faulty Lua script is executed, providing a detailed error message and pointing you directly to the faulting code. It is even possible to attach a C++ debugger to a process that is being debugged by Decoda, this way you can trap both C++ and Lua errors.
To begin using Decoda, you need to create a project, or load an existing one. Decoda projects have a .deproj extension, and are simply a list of Lua files that are to be opened. You can create a project through menu Project -> New Project. Save your project first, so that Decoda knows what relative paths to use for the files. Then either add existing Lua files or create new one, through menu Project -> Add Add New File / Add Existing File.
-
Next you need to set up the executable that Decoda will run when debugging your files. Select menu Project -> Settings. A new dialog will open:
-
-
In the debugging section, fill in the full path to Cuberite.exe, or click the triple-dot button to browse for the file. Note that the Working directory will be automatically filled in for you with the folder where the executable is (until the last backslash). This is how it's supposed to work, don't change it; if it for some reason doesn't update, copy and paste the folder name from the Command edit box. All done, you can close this dialog now.
-
-
Debugging
-
You are now ready to debug your code. Before doing that, though, don't forget to save your project file. If you haven't done so already, enable your plugin in the settings.ini file. If you want the program to break at a certain line, it is best to set the breakpoint before starting the program. Set the cursor on the line and hit F9 (or use menu Debug -> Toggle Breakpoint) to toggle a breakpoint on that line. Finally, hit F5, or select menu Debug -> Start to launch Cuberite under the debugger. The Cuberite window comes up and loads your plugin. If Decoda displays the Project Settings dialog instead, you haven't set up the executable to run, see the Project management section for instructions.
-
At this point you will see that Decoda starts adding new items to your project. All the files for all plugins are added temporarily. Don't worry, they are only temporary, they will be removed again once the debugging session finishes. You can tell the temporary files from the regular files by their icon, it's faded out. Decoda handles all the files that Cuberite loads, so you can actually debug any of those faded files, too.
-
If there's an error in the code, the Decoda window will flash and a dialog box will come up, describing the error and taking you to the line where it occured. Note that the execution is paused in the thread executing the plugin, so until you select Debug -> Continue from the menu (F5), Cuberite won't be fully running. You can fix the error and issue a "reload" command in Cuberite console to reload the plugin code anew (Cuberite doesn't detect changes in plugin code automatically).
-
If the execution hits a breakpoint, the Decoda window will flash and a yellow arrow is displayed next to the line. You can step through the code using F10 and F11, just like in MSVS. You can also use the Watch window to inspect variable values, or simply hover your mouse over a variable to display its value in the tooltip.
-
-
Limitations
-
So far everything seems wonderful. Unfortunately, it doesn't always go as easy. There are several limits to what Decoda can do:
-
-
When the program encounters a logical bug (using a nil value, calling a non-existent function etc.), Decoda will break, but usually the Watch window and the tooltips are showing nonsense values. You shouldn't trust them in such a case, if you kep running into such a problem regularly, put console logging functions (LOG) in the code to print out any info you need prior to the failure.
-
Sometimes breakpoints just don't work. This is especially true if there are multiple plugins that have files of the same name. Breakpoints will never work after changing the code and reloading the plugin in Cuberite; you need to stop the server and start again to reenable breakpoints.
-
Most weirdly, sometimes Decoda reports an error, but instead of opening the current version of the file, opens up another window with old contents of the file. Watch for this, because you could overwrite your new code if you saved this file over your newer file. Fortunately enough, Decoda will always ask you for a filename before saving such a file.
-
Decoda stores the project in two files. The .deproj file has the file list, and should be put into version control systems. The .deuser file has the settings (debugged application etc.) and is per-user specific. This file shouldn't go to version control systems, because each user may have different paths for the debuggee.
-
Unfortunately for us Windows users, the Decoda project file uses Unix-lineends (CR only). This makes it problematic when checking the file into a version control system, since those usually expect windows (CRLF) lineends; I personally convert the lineends each time I edit the project file using TED Notepad.
- This article will explain how to set up ZeroBrane Studio, an IDE for writing Lua code, so that you can develop Cuberite plugins with the comfort of an IDE.
-
-
About ZeroBrane Studio
-
-
To quickly introduce ZeroBrane Studio, it is an IDE for writing Lua code. It has the basic features expected of an IDE - it allows you to manage groups of files as a project, you can edit multiple files in a tabbed editor, the code is syntax-highlighted. Code completion, symbol browsing, and more. It also features a Lua debugger that allows you to debug your Lua code within any application that uses Lua and can load Lua packages. It is written using the multiplatform WxWidgets toolkit, and runs on multiple platforms, including Windows, Linux and MacOS.
-
Here's a screenshot of a default ZBS window with the debugger stepping through the code (scaled down):
-
-
As you can see, you can set breakpoints in the code, inspect variables' values, view the Lua call-stacks.
Since ZBS is a universal Lua IDE, you need to first set it up so that it is ready for Cuberite plugin development. For that, you need to download one file, cuberite.lua from the ZBS's plugin repository. Place that file in the "packages" folder inside your ZBS's folder. Note that there are other useful plugins in the repository and you may want to have a look there later on to further customize your ZBS. To install them, simply save them into the same folder.
-
Next you should install the code-completion support specific for Cuberite. You should repeat this step from time to time, because the API evolves in time so new functions and classes are added to it quite often. You should have an APIDump plugin in your Cuberite installation. Enable the APIDump plugin in the server settings, it's very cheap to keep it enabled and it doesn't cost any performance during normal gameplay. To generate the code-completion support file, enter the api command into the server console. This will create a new file, "cuberite_api.lua", next to the Cuberite executable. Move that file into the "api/lua" subfolder inside your ZBS's folder. (Note that if you had the "mcserver_api.lua" file from previous versions, you should remove it)
-
After you download the cuberite.lua file and install the completion support, you need to restart ZBS in order for the plugin to load. If there are no errors, you should see two new items in the Project -> Lua Interpreter submenu: "Cuberite - debug mode" and "Cuberite - release mode". The only difference between the two is which filename they use to launch Cuberite - cuberite_debug(.exe) for the debug option and "cuberite(.exe)" for the release option. If you built your own Cuberite executable and you built it in debug mode, you should select the debug mode option. In all other cases, including if you downloaded the already-compiled Cuberite executable from the internet, you should select the release mode option.
-
For a first time user, it might be a bit overwhelming that there are no GUI settings in the ZBS, yet the IDE is very configurable. There are two files that you edit in order to change settings, either system-wide (all users of the computer share those settings) or user-wide (the settings are only for a specific user of the computer). Those files are regular Lua sources and you can quickly locate them and edit them from within the IDE itself, select Edit -> Preferences -> Settings: XYZ from the menu, with XYZ being either System or User.
-
There is a documentation on most of the settings on ZBS's webpage, have a look at http://studio.zerobrane.com/documentation.html, especially the Preferences section. Personally I recommend setting editor.usetabs to true and possibly adjusting the editor.tabwidth, turn off the editor.smartindent feature and for debugging the option debugger.alloweditting should be set to true unless you feel like punishing yourself.
-
-
Project management
-
ZBS works with projects, it considers all files and subfolder in a specific folder to be a project. There's no need for a special project file nor for adding individual files to the workspace, all files are added automatically. To open a Cuberite plugin as the project, click the triple-dot button in the Project pane, or select Project -> Project directory -> Choose... from the menu. Browse and select the Cuberite plugin's folder. ZBS will load all the files in the plugin's folder and you can start editting code.
-
Note that although ZBS allows you to work with subfolders in your plugins (and you should, especially with larger plugins), the current Cuberite ZBS plugin will not be able to start debugging unless you have a file open in the editor that is at the root level of the Cuberite plugin's folder.
-
-
Debugging
-
You are now ready to debug your code. Before doing that, though, don't forget to save your project files. If you haven't done so already, enable your plugin in the settings.ini file. If you want the program to break at a certain line, it is best to set the breakpoint before starting the program. Set the cursor on the line and hit F9 (or use menu Project -> Toggle Breakpoint) to toggle a breakpoint on that line. Finally, hit F5, or select menu Project -> Start Debugging to launch Cuberite under the debugger. The Cuberite window comes up and loads your plugin. If the window doesn't come up, inspect the Output pane in ZBS, there are usually two reasons for failure:
-
Your code in the currently open file has a hard syntax error. These are reported as "Compilation error" in the Output pane, double-click the line to go to the error
-
ZBS cannot find the Cuberite executable. Make sure you are editting a file two or three levels down the folder hierarchy from the Cuberite executable and that the Cuberite executable is named properly (cuberite[.exe] or cuberite_debug[.exe]). Also make sure you have selected the right Interpreter (menu Project -> Lua Interpreter).
-
-
Once running, if the execution hits a breakpoint, the ZBS window will come up and a green arrow is displayed next to the breakpoint line. You can step through the code using F10 (Step Into) and Shift+F10 (Step Over). You can also use the Watch window to inspect variable values, or simply hover your mouse over a variable to display its value in the tooltip. Use the Remote console pane to execute commands directly *inside* the Cuberite's plugin context.
-
You can also use the Project -> Break menu item to break into the debugger as soon as possible. You can also set breakpoints while the Cuberite plugin is running. Note that due to the way in which the debugger is implemented, Cuberite may execute some more Lua code before the break / breakpoint comes into effect. If Cuberite is not executing any Lua code in your plugin, it will not break until the plugin code kicks in again. This may result in missed breakpoints and delays before the Break command becomes effective. Therefore it's best to set breakpoints before running the program, or while the program is waiting in another breakpoint.
- A plugin may need to manipulate data in arbitrary chunks, and it needs a way to make the server
- guarantee that the chunks are available in memory.
-
-
The problem
-
- Usually when plugins want to manipulate larger areas of world data, they need to make sure that the
- server has the appropriate chunks loaded in the memory. When the data being manipulated can be further
- away from the connected players, or the data is being manipulated from a console handler, there is a
- real chance that the chunks are not loaded.
-
- This gets even more important when using the cBlockArea class for reading
- and writing. Those functions will fail when any of the required chunks aren't valid. This means that
- either the block area has incomplete data (Read() failed) or incomplete data has been written to the
- world (Write() failed). Recovery from this is near impossible - you can't simply read or write again
- later, because the world may have changed in the meantime.
-
-
The solution
-
- The naive solution would be to monitor chunk loads and unloads, and postpone the operations until all
- the chunks are available. This would be quite ineffective and also very soon it would become very
- difficult to maintain, if there were multiple code paths requiring this handling.
-
- An alternate approach has been implemented, accessible through a single (somewhat hidden) function
- call: cWorld:ChunkStay(). All that this call basically does is, it tells the
- server "Load these chunks for me, and call this callback function once you have them all." And the
- server does exactly that - it remembers the callback and asks the world loader / generator to provide
- the chunks. Once the chunks become available, it calls the callback function for the plugin.
-
- There are a few gotcha-s, though. If the code that was requesting the read or write had access to some
- of the volatile objects, such as cPlayer or
- cEntity objects, those cannot be accessed by the callback anymore, because
- they may have become invalid in the meantime - the player may have disconnected, the entity may have
- despawned. So the callback must use the longer way to access such objects, such as calling
- cWorld:DoWithEntityByID() or
- cWorld:DoWithPlayer().
-
-
The example
-
- As a simple example, consider a theoretical plugin that allows a player to save the immediate
- surroundings of the spawn into a schematic file. The player issues a command to initiate the save, and
- the plugin reads a 50 x 50 x 50 block area around the spawn into a cBlockArea and saves it on the disk
- as "_spawn.schematic". When it's done with the saving, it wants to send a message to the
- player to let them know the command has succeeded.
-
- The first attempt shows the naive approach. It simply reads the block area and saves it, then sends the
- message. I'll repeat once more, this code is the wrong way to do it!
-
-function HandleCommandSaveSpawn(a_Split, a_Player)
- -- Get the coords for the spawn:
- local SpawnX = a_Player:GetWorld():GetSpawnX()
- local SpawnY = a_Player:GetWorld():GetSpawnY()
- local SpawnZ = a_Player:GetWorld():GetSpawnZ()
- local Bounds = cCuboid(SpawnX - 25, SpawnY - 25, SpawnZ - 25, SpawnX + 25, SpawnY + 25, SpawnZ + 25)
- Bounds:ClampY(0, 255)
-
- -- Read the area around spawn into a cBlockArea, save to file:
- local Area = cBlockArea()
- local FileName = a_Player:GetName() .. "_spawn.schematic"
- Area:Read(a_Player:GetWorld(), Bounds, cBlockArea.baTypes + cBlockArea.baMetas)
- Area:SaveToSchematicFile(FileName)
-
- -- Notify the player:
- a_Player:SendMessage(cCompositeChat("The spawn has been saved", mtInfo))
- return true
-end
-
-
- Now if the player goes exploring far and uses the command to save their spawn, the chunks aren't
- loaded, so the BlockArea reading fails, the BlockArea contains bad data. Note that the plugin fails to
- do any error checking and if the area isn't read from the world, it happily saves the incomplete data
- and says "hey, everything's right", althought it has just trashed any previous backup of the spawn
- schematic with nonsense data.
-
-
- The following script uses the ChunkStay method to alleviate chunk-related problems. This is the
- right way of doing it:
-
-function HandleCommandSaveSpawn(a_Split, a_Player)
- -- Get the coords for the spawn:
- local SpawnX = a_Player:GetWorld():GetSpawnX()
- local SpawnY = a_Player:GetWorld():GetSpawnY()
- local SpawnZ = a_Player:GetWorld():GetSpawnZ()
- local Bounds = cCuboid(SpawnX - 25, SpawnY - 25, SpawnZ - 25, SpawnX + 25, SpawnY + 25, SpawnZ + 25)
- Bounds:ClampY(0, 255)
-
- -- Get a list of chunks that we need loaded:
- local MinChunkX = math.floor((SpawnX - 25) / 16)
- local MaxChunkX = math.ceil ((SpawnX + 25) / 16)
- local MinChunkZ = math.floor((SpawnZ - 25) / 16)
- local MaxChunkZ = math.ceil ((SpawnZ + 25) / 16)
- local Chunks = {}
- for x = MinChunkX, MaxChunkX do
- for z = MinChunkZ, MaxChunkZ do
- table.insert(Chunks, {x, z})
- end
- end -- for x
-
- -- Store the player's name and world to use in the callback, because the a_Player object may no longer be valid:
- local PlayerName = a_Player:GetName()
- local World = a_Player:GetWorld()
-
- -- This is the callback that is executed once all the chunks are loaded:
- local OnAllChunksAvailable = function()
- -- Read the area around spawn into a cBlockArea, save to file:
- local Area = cBlockArea()
- local FileName = PlayerName .. "_spawn.schematic"
- if (Area:Read(World, Bounds, cBlockArea.baTypes + cBlockArea.baMetas)) then
- Area:SaveToSchematicFile(FileName)
- Msg = cCompositeChat("The spawn has been saved", mtInfo)
- else
- Msg = cCompositeChat("Cannot save the spawn", mtFailure)
- end
-
- -- Notify the player:
- -- Note that we cannot use a_Player here, because it may no longer be valid (if the player disconnected before the command completes)
- World:DoWithPlayer(PlayerName,
- function (a_CBPlayer)
- a_CBPlayer:SendMessage(Msg)
- end
- )
- end
-
- -- Ask the server to load our chunks and notify us once it's done:
- World:ChunkStay(Chunks, nil, OnAllChunksAvailable)
-
- -- Note that code here may get executed before the callback is called!
- -- The ChunkStay says "once you have the chunks", not "wait until you have the chunks"
- -- So you can't notify the player here, because the saving needn't have occurred yet.
-
- return true
-end
-
-
- Note that this code does its error checking of the Area:Read() function, and it will not overwrite the
- previous file unless it actually has the correct data. If you're wondering how the reading could fail
- when we've got the chunks loaded, there's still the issue of free RAM - if the memory for the area
- cannot be allocated, it cannot be read even with all the chunks present. So we still do need that
- check.
-
-
The conclusion
-
- Although it makes the code a little bit longer and is a bit more difficult to grasp at first, the
- ChunkStay is a useful technique to add to your repertoire. It is to be used whenever you need access to
- chunks that may potentially be inaccessible, and you really need the data.
-
Possibly the biggest hurdle in using the ChunkStay is the fact that it does its work in the
- background, thus invalidating all cPlayer and cEntity objects your function may hold, so you need to
- re-acquire them from their IDs and names. This is the penalty for using multi-threaded code.
- This article will explain the threading issues that arise between the webserver and world threads are of concern to plugin authors.
-
- Generally, plugins that provide webadmin pages should be quite careful about their interactions. Most operations on Cuberite objects requires synchronization, that Cuberite provides automatically and transparently to plugins - when a block is written, the chunkmap is locked, or when an entity is being manipulated, the entity list is locked. Each plugin also has a mutex lock, so that only one thread at a time may be executing plugin code.
-
- This locking can be a source of deadlocks for plugins that are not written carefully.
-
-
Example scenario
-
Consider the following example. A plugin provides a webadmin page that allows the admin to kick players off the server. When the admin presses the "Kick" button, the plugin calls cWorld:DoWithPlayer() with a callback to kick the player. Everything seems to be working fine now.
-
- A new feature is developed in the plugin, now the plugin adds a new in-game command so that the admins can kick players while they're playing the game. The plugin registers a command callback with cPluginManager.AddCommand(). Now there are problems bound to happen.
-
- Suppose that two admins are in, one is using the webadmin and the other is in-game. Both try to kick a player at the same time. The webadmin locks the plugin, so that it can execute the plugin code, but right at this moment the OS switches threads. The world thread locks the world so that it can access the list of in-game commands, receives the in-game command, it tries to lock the plugin. The plugin is already locked, so the world thread is put on hold. After a while, the webadmin thread is woken up again and continues processing. It tries to lock the world so that it can traverse the playerlist, but the lock is already held by the world thread. Now both threads are holding one lock each and trying to grab the other lock, and are therefore deadlocked.
-
-
How to avoid the deadlock
-
- There are two main ways to avoid such a deadlock. The first approach is using tasks: Everytime you need to execute a task inside a world, instead of executing it, queue it, using cWorld:QueueTask(). This handy utility can will call the given function inside the world's TickThread, thus eliminating the deadlock, because now there's only one thread. However, this approach will not let you get data back. You cannot query the player list, or the entities, or anything - because when the task runs, the webadmin page has already been served to the browser.
-
- To accommodate this, you'll need to use the second approach - preparing and caching data in the tick thread, possibly using callbacks. This means that the plugin will have global variables that will store the data, and update those variables when the data changes; then the webserver thread will only read those variables, instead of calling the world functions. For example, if a webpage was to display the list of currently connected players, the plugin should maintain a global variable, g_WorldPlayers, which would be a table of worlds, each item being a list of currently connected players. The webadmin handler would read this variable and create the page from it; the plugin would use HOOK_PLAYER_JOINED and HOOK_DISCONNECT to update the variable.
-
-
What to avoid
-
- Now that we know what the danger is and how to avoid it, how do we know if our code is susceptible?
-
- The general rule of thumb is to avoid calling any functions that read or write lists of things in the webserver thread. This means most ForEach() and DoWith() functions. Only cRoot:ForEachWorld() is safe - because the list of worlds is not expected to change, so it is not guarded by a mutex. Getting and setting world's blocks is, naturally, unsafe, as is calling other plugins, or creating entities.
-
-
Example
- The Core has the facility to kick players using the web interface. It used the following code for the kicking (inside the webadmin handler):
-
-local KickPlayerName = Request.Params["players-kick"]
-local FoundPlayerCallback = function(Player)
- if (Player:GetName() == KickPlayerName) then
- Player:GetClientHandle():Kick("You were kicked from the game!")
- end
-end
-cRoot:Get():FindAndDoWithPlayer(KickPlayerName, FoundPlayerCallback)
-
-The cRoot:FindAndDoWithPlayer() is unsafe and could have caused a deadlock. The new solution is queue a task; but since we don't know in which world the player is, we need to queue the task to all worlds:
-
-cRoot:Get():ForEachWorld( -- For each world...
- function(World)
- World:QueueTask( -- ... queue a task...
- function(a_World)
- a_World:DoWithPlayer(KickPlayerName, -- ... to walk the playerlist...
- function (a_Player)
- a_Player:GetClientHandle():Kick("You were kicked from the game!") -- ... and kick the player
- end
- )
- end
- )
- end
-)
-
- This article will explain how to write a basic plugin. It details basic requirements
- for a plugin, explains how to register a hook and bind a command, and gives plugin
- standards details.
-
-
- Let us begin. In order to begin development, we must firstly obtain a compiled copy
- of Cuberite, and make sure that the Core plugin is within the Plugins folder, and activated.
- Core handles much of the Cuberite end-user experience and gameplay will be very bland without it.
-
-
Creating the basic template
-
- Plugins are written in Lua. Therefore, create a new Lua file. You can create as many files as you wish, with
- any filename - Cuberite bungs them all together at runtime, however, let us create a file called main.lua for now.
- Format it like so:
-
-
-PLUGIN = nil
-
-function Initialize(Plugin)
- Plugin:SetName("NewPlugin")
- Plugin:SetVersion(1)
-
- -- Hooks
-
- PLUGIN = Plugin -- NOTE: only needed if you want OnDisable() to use GetName() or something like that
-
- -- Command Bindings
-
- LOG("Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion())
- return true
-end
-
-function OnDisable()
- LOG(PLUGIN:GetName() .. " is shutting down...")
-end
-
-
- Now for an explanation of the basics.
-
-
function Initialize is called on plugin startup. It is the place where the plugin is set up.
-
Plugin:SetName sets the name of the plugin.
-
Plugin:SetVersion sets the revision number of the plugin. This must be an integer.
-
LOG logs to console a message, in this case, it prints that the plugin was initialised.
-
The PLUGIN variable just stores this plugin's object, so GetName() can be called in OnDisable (as no Plugin parameter is passed there, contrary to Initialize).
- This global variable is only needed if you want to know the plugin details (name, etc.) when shutting down.
-
function OnDisable is called when the plugin is disabled, commonly when the server is shutting down. Perform cleanup and logging here.
-
- Be sure to return true for this function, else Cuberite thinks you plugin had failed to initialise and prints a stacktrace with an error message.
-
-
-
Registering hooks
-
- Hooks are things that Cuberite calls when an internal event occurs. For example, a hook is fired when a player places a block, moves,
- logs on, eats, and many other things. For a full list, see the API documentation.
-
-
- A hook can be either informative or overridable. In any case, returning false will not trigger a response, but returning true will cancel
- the hook and prevent it from being propagated further to other plugins. An overridable hook simply means that there is visible behaviour
- to a hook's cancellation, such as a chest being prevented from being opened. There are some exceptions to this where only changing the value the
- hook passes has an effect, and not the actual return value, an example being the HOOK_KILLING hook. See the API docs for details.
-
-
- To register a hook, insert the following code template into the "-- Hooks" area in the previous code example.
-
cPluginManager.AddHook registers the hook. The hook name is the second parameter. See the previous API documentation link for a list of all hooks.
-
- What about the third parameter, you ask? Well, it is the name of the function that Cuberite calls when the hook fires. It is in this
- function that you should handle or cancel the hook.
-
-
- So in total, this is a working representation of what we have so far covered.
-
-
-function Initialize(Plugin)
- Plugin:SetName("DerpyPlugin")
- Plugin:SetVersion(1)
-
- cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_MOVING, OnPlayerMoving)
-
- LOG("Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion())
- return true
-end
-
-function OnPlayerMoving(Player) -- See API docs for parameters of all hooks
- return true -- Prohibit player movement, see docs for whether a hook is cancellable
-end
-
-
- So, that code stops the player from moving. Not particularly helpful, but yes :P. Note that ALL documentation is available
- on the main API docs page, so if ever in doubt, go there.
-
-
Binding a command
-
Format
-
- So now we know how to hook into Cuberite, how do we bind a command, such as /explode, for a player to type? That is more complicated.
- We firstly add this template to the "-- Command bindings" section of the initial example:
-
-
--- ADD THIS IF COMMAND DOES NOT REQUIRE A PARAMETER (/explode)
-cPluginManager.BindCommand("/commandname", "permissionnode", FunctionToCall, " - Description of command")
-
--- ADD THIS IF COMMAND DOES REQUIRE A PARAMETER (/explode Notch)
-cPluginManager.BindCommand("/commandname", "permissionnode", FunctionToCall, " ~ Description of command and parameter(s)")
-
-
- What does it do, and why are there two?
-
-
PluginManager:BindCommand binds a command. It takes the command name (with a slash), the permission a player needs to execute the command, the function
- to call when the command is executed, and a description of the command.
-
- The command name is pretty self explanatory. The permission node is basically just a string that the player's group needs to have, so you can have anything in there,
- though we recommend a style such as "derpyplugin.explode". The function to call is like the ones with Hooks, but with some fixed parameters which we will come on to later,
- and the description is a description of the command which is shown when "/help" is typed.
-
-
- So why are there two? Standards. A plugin that accepts a parameter MUST use a format for the description of " ~ Description of command and parms"
- whereas a command that doesn't accept parameters MUST use " - Description of command" instead. Be sure to put a space before the tildes or dashes.
- Additionally, try to keep the description brief and on one line on the client.
-
-
Parameters
-
- What parameters are in the function Cuberite calls when the command is executed? A 'Split' array and a 'Player' object.
-
-
The Split Array
-
- The Split array is an array of all text submitted to the server, including the actual command. Cuberite automatically splits the text into the array,
- so plugin authors do not need to worry about that. An example of a Split array passed for the command, "/derp zubby explode" would be:
-    /derp (Split[1])
-    zubby (Split[2])
-    explode (Split[3])
-
-    The total amount of parameters passed were: 3 (#Split)
-
-
The Player Object and sending them messages
-
- The Player object is basically a pointer to the player that has executed the command. You can do things with them, but most common is sending
- a message. Again, see the API documentation for fuller details. But, you ask, how do we send a message to the client?
-
-
- There are dedicated functions used for sending a player formatted messages. By format, I refer to coloured prefixes/coloured text (depending on configuration)
- that clearly categorise what type of message a player is being sent. For example, an informational message has a yellow coloured [INFO] prefix, and a warning message
- has a rose coloured [WARNING] prefix. A few of the most used functions are listed here, but see the API docs for more details. Look in the cRoot, cWorld, and cPlayer sections
- for functions that broadcast to the entire server, the whole world, and a single player, respectively.
-
-
--- Format: §yellow[INFO] §white%text% (yellow [INFO], white text following it)
--- Use: Informational message, such as instructions for usage of a command
-Player:SendMessageInfo("Usage: /explode [player]")
-
--- Format: §green[INFO] §white%text% (green [INFO] etc.)
--- Use: Success message, like when a command executes successfully
-Player:SendMessageSuccess("Notch was blown up!")
-
--- Format: §rose[INFO] §white%text% (rose coloured [INFO] etc.)
--- Use: Failure message, like when a command was entered correctly but failed to run, such as when the destination player wasn't found in a /tp command
-Player:SendMessageFailure("Player Salted was not found")
-
-
- Those are the basics. If you want to output text to the player for a reason other than the three listed above, and you want to colour the text, simply concatenate
- "cChatColor.*colorhere*" with your desired text, concatenate being "..". See the API docs for more details of all colours, as well as details on logging to console with
- LOG("Text").
-
-
Final example and conclusion
-
- So, a working example that checks the validity of a command, and blows up a player, and also refuses pickup collection to players with >100ms ping.
-
-
-function Initialize(Plugin)
- Plugin:SetName("DerpyPluginThatBlowsPeopleUp")
- Plugin:SetVersion(9001)
-
- cPluginManager.BindCommand("/explode", "derpyplugin.explode", Explode, " ~ Explode a player");
-
- cPluginManager:AddHook(cPluginManager.HOOK_COLLECTING_PICKUP, OnCollectingPickup)
-
- LOG("Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion())
- return true
-end
-
-function Explode(Split, Player)
- if (#Split ~= 2) then
- -- There was more or less than one argument (excluding the "/explode" bit)
- -- Send the proper usage to the player and exit
- Player:SendMessage("Usage: /explode [playername]")
- return true
- end
-
- -- Create a callback ExplodePlayer with parameter Explodee, which Cuberite calls for every player on the server
- local HasExploded = false
- local ExplodePlayer = function(Explodee)
- -- If the player name matches exactly
- if (Explodee:GetName() == Split[2]) then
- -- Create an explosion of force level 2 at the same position as they are
- -- see API docs for further details of this function
- Player:GetWorld():DoExplosionAt(2, Explodee:GetPosX(), Explodee:GetPosY(), Explodee:GetPosZ(), false, esPlugin)
- Player:SendMessageSuccess(Split[2] .. " was successfully exploded")
- HasExploded = true;
- return true -- Signalize to Cuberite that we do not need to call this callback for any more players
- end
- end
-
- -- Tell Cuberite to loop through all players and call the callback above with the Player object it has found
- cRoot:Get():FindAndDoWithPlayer(Split[2], ExplodePlayer)
-
- if not(HasExploded) then
- -- We have not broken out so far, therefore, the player must not exist, send failure
- Player:SendMessageFailure(Split[2] .. " was not found")
- end
-
- return true
-end
-
-function OnCollectingPickup(Player, Pickup) -- Again, see the API docs for parameters of all hooks. In this case, it is a Player and Pickup object
- if (Player:GetClientHandle():GetPing() > 100) then -- Get ping of player, in milliseconds
- return true -- Discriminate against high latency - you don't get drops :D
- else
- return false -- You do get the drops! Yay~
- end
-end
-
-
- Make sure to read the comments for a description of what everything does. Also be sure to return true for all command handlers, unless you want Cuberite to print out an "Unknown command" message
- when the command gets executed :P. Make sure to follow standards - use CoreMessaging.lua functions for messaging, dashes for no parameter commands and tildes for vice versa,
- and finally, the API documentation is your friend!
-
-
- Happy coding ;)
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/world/Plugins/APIDump/lang-lua.js b/world/Plugins/APIDump/lang-lua.js
deleted file mode 100644
index 7e44cca0..00000000
--- a/world/Plugins/APIDump/lang-lua.js
+++ /dev/null
@@ -1,2 +0,0 @@
-PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null,"\t\n\r \u00a0"],["str",/^(?:"(?:[^"\\]|\\[\S\s])*(?:"|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$))/,null,"\"'"]],[["com",/^--(?:\[(=*)\[[\S\s]*?(?:]\1]|$)|[^\n\r]*)/],["str",/^\[(=*)\[[\S\s]*?(?:]\1]|$)/],["kwd",/^(?:and|break|do|else|elseif|end|false|for|function|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/,null],["lit",/^[+-]?(?:0x[\da-f]+|(?:\.\d+|\d+(?:\.\d*)?)(?:e[+-]?\d+)?)/i],
-["pln",/^[_a-z]\w*/i],["pun",/^[^\w\t\n\r \xa0][^\w\t\n\r "'+=\xa0-]*/]]),["lua"]);
diff --git a/world/Plugins/APIDump/main.css b/world/Plugins/APIDump/main.css
deleted file mode 100644
index e5685caa..00000000
--- a/world/Plugins/APIDump/main.css
+++ /dev/null
@@ -1,68 +0,0 @@
-html
-{
- background-color: #C0C0C0;
-}
-
-table
-{
- background-color: #fff;
- border-spacing: 0px;
- border-collapse: collapse;
- border-color: gray;
-}
-
-tr
-{
- display: table-row;
- vertical-align: inherit;
- border-color: inherit;
-}
-
-td, th
-{
- display: table-cell;
- vertical-align: inherit;
- padding: 3px;
- border: 1px solid #ccc;
-}
-
-pre
-{
- border: 1px solid #ccc;
- background-color: #eee;
- -moz-tab-size: 2;
- -o-tab-size: 2;
- -webkit-tab-size: 2;
- -ms-tab-size: 2;
- tab-size: 2;
-}
-
-body
-{
- min-width: 400px;
- max-width: 1200px;
- width: 95%;
- margin: 10px auto;
- background-color: white;
- border: 4px #FF8C00 solid;
- border-radius: 20px;
- font-family: Calibri, Trebuchet MS;
-}
-
-header
-{
- text-align: center;
- font-family: Segoe UI Light, Helvetica;
-}
-
-footer
-{
- text-align: center;
- font-family: Segoe UI Light, Helvetica;
-}
-
-#content, #timestamp
-{
- padding: 0px 25px 25px 25px;
-}
-
diff --git a/world/Plugins/APIDump/main_APIDump.lua b/world/Plugins/APIDump/main_APIDump.lua
deleted file mode 100644
index 6dec8e15..00000000
--- a/world/Plugins/APIDump/main_APIDump.lua
+++ /dev/null
@@ -1,1950 +0,0 @@
--- main.lua
-
--- Implements the plugin entrypoint (in this case the entire plugin)
-
-
-
-
-
--- Global variables:
-local g_Plugin = nil
-local g_PluginFolder = ""
-local g_Stats = {}
-local g_TrackedPages = {}
-
-
-
-
-
-
-local function LoadAPIFiles(a_Folder, a_DstTable)
- assert(type(a_Folder) == "string")
- assert(type(a_DstTable) == "table")
-
- local Folder = g_PluginFolder .. a_Folder;
- for _, fnam in ipairs(cFile:GetFolderContents(Folder)) do
- local FileName = Folder .. fnam;
- -- We only want .lua files from the folder:
- if (cFile:IsFile(FileName) and fnam:match(".*%.lua$")) then
- local TablesFn, Err = loadfile(FileName);
- if (type(TablesFn) ~= "function") then
- LOGWARNING("Cannot load API descriptions from " .. FileName .. ", Lua error '" .. Err .. "'.");
- else
- local Tables = TablesFn();
- if (type(Tables) ~= "table") then
- LOGWARNING("Cannot load API descriptions from " .. FileName .. ", returned object is not a table (" .. type(Tables) .. ").");
- break
- end
- for k, cls in pairs(Tables) do
- if (a_DstTable[k]) then
- -- The class is documented in two files, warn and store into a file (so that CIs can mark build as failure):
- LOGWARNING(string.format(
- "APIDump warning: class %s is documented at two places, the documentation in file %s will overwrite the previously loaded one!",
- k, FileName
- ))
- local f = io.open("DuplicateDocs.txt", "a")
- f:write(k, "\t", FileName)
- f:close()
- end
- a_DstTable[k] = cls;
- end
- end -- if (TablesFn)
- end -- if (is lua file)
- end -- for fnam - Folder[]
-end
-
-
-
-
-
---- Returns the API currently detected from the global environment
-local function CreateAPITables()
- --[[
- We want an API table of the following shape:
- local API = {
- {
- Name = "cCuboid",
- Functions = {
- {Name = "Sort"},
- {Name = "IsInside"}
- },
- Constants = {
- },
- Variables = {
- },
- Descendants = {}, -- Will be filled by ReadDescriptions(), array of class APIs (references to other member in the tree)
- },
- {
- Name = "cBlockArea",
- Functions = {
- {Name = "Clear"},
- {Name = "CopyFrom"},
- ...
- },
- Constants = {
- {Name = "baTypes", Value = 0},
- {Name = "baMetas", Value = 1},
- ...
- },
- Variables = {
- },
- ...
- },
-
- cCuboid = {} -- Each array item also has the map item by its name
- };
- local Globals = {
- Functions = {
- ...
- },
- Constants = {
- ...
- }
- };
- --]]
-
- local Globals = {Functions = {}, Constants = {}, Variables = {}, Descendants = {}};
- local API = {};
-
- local function Add(a_APIContainer, a_ObjName, a_ObjValue)
- if (type(a_ObjValue) == "function") then
- table.insert(a_APIContainer.Functions, {Name = a_ObjName});
- elseif (
- (type(a_ObjValue) == "number") or
- (type(a_ObjValue) == "string")
- ) then
- table.insert(a_APIContainer.Constants, {Name = a_ObjName, Value = a_ObjValue});
- end
- end
-
- local function ParseClass(a_ClassName, a_ClassObj)
- local res = {Name = a_ClassName, Functions = {}, Constants = {}, Variables = {}, Descendants = {}};
- -- Add functions and constants:
- for i, v in pairs(a_ClassObj) do
- Add(res, i, v);
- end
-
- -- Member variables:
- local SetField = a_ClassObj[".set"] or {};
- if ((a_ClassObj[".get"] ~= nil) and (type(a_ClassObj[".get"]) == "table")) then
- for k in pairs(a_ClassObj[".get"]) do
- if (SetField[k] == nil) then
- -- It is a read-only variable, add it as a constant:
- table.insert(res.Constants, {Name = k, Value = ""});
- else
- -- It is a read-write variable, add it as a variable:
- table.insert(res.Variables, { Name = k });
- end
- end
- end
- return res;
- end
-
- for i, v in pairs(_G) do
- if (
- (v ~= _G) and -- don't want the global namespace
- (v ~= _G.packages) and -- don't want any packages
- (v ~= _G[".get"])
- ) then
- if (type(v) == "table") then
- local cls = ParseClass(i, v)
- table.insert(API, cls);
- API[cls.Name] = cls
- else
- Add(Globals, i, v);
- end
- end
- end
-
- -- Remove the built-in Lua libraries:
- API.debug = nil
- API.io = nil
- API.string = nil
- API.table = nil
-
- return API, Globals;
-end
-
-
-
-
-
---- Returns the timestamp in HTML format
--- The timestamp will be inserted to all generated HTML files
-local function GetHtmlTimestamp()
- return string.format("
Generated on %s, Build ID %s, Commit %s
",
- os.date("%Y-%m-%d %H:%M:%S"),
- cRoot:GetBuildID(), cRoot:GetBuildCommitID()
- )
-end
-
-
-
-
-
---- Writes links to articles in a bullet format into the output HTML file
--- f is the output file stream
--- a_APIDesc is the API description as read from APIDesc.lua
-local function WriteArticles(f, a_APIDesc)
- f:write([[
-
The following articles provide various extra information on plugin development
-
- ]]);
- for _, extra in ipairs(a_APIDesc.ExtraPages) do
- local SrcFileName = g_PluginFolder .. "/" .. extra.FileName;
- if (cFile:IsFile(SrcFileName)) then
- local DstFileName = "API/" .. extra.FileName;
- cFile:Delete(DstFileName);
- cFile:Copy(SrcFileName, DstFileName);
- f:write("
");
-end
-
-
-
-
-
--- Make a link out of anything with the special linkifying syntax {{link|title}}
-local function LinkifyString(a_String, a_Referrer)
- assert(a_Referrer ~= nil);
- assert(a_Referrer ~= "");
-
- --- Adds a page to the list of tracked pages (to be checked for existence at the end)
- local function AddTrackedPage(a_PageName)
- local Pg = (g_TrackedPages[a_PageName] or {});
- table.insert(Pg, a_Referrer);
- g_TrackedPages[a_PageName] = Pg;
- end
-
- --- Creates the HTML for the specified link and title
- local function CreateLink(Link, Title)
- if (Link:sub(1, 7) == "http://") then
- -- The link is a full absolute URL, do not modify, do not track:
- return "" .. Title .. "";
- end
- local idxHash = Link:find("#");
- if (idxHash ~= nil) then
- -- The link contains an anchor:
- if (idxHash == 1) then
- -- Anchor in the current page, no need to track:
- return "" .. Title .. "";
- end
- -- Anchor in another page:
- local PageName = Link:sub(1, idxHash - 1);
- AddTrackedPage(PageName);
- return "" .. Title .. "";
- end
- -- Link without anchor:
- AddTrackedPage(Link);
- return "" .. Title .. "";
- end
-
- -- Linkify the strings using the CreateLink() function:
- local txt = a_String:gsub("{{([^|}]*)|([^}]*)}}", CreateLink) -- {{link|title}}
- txt = txt:gsub("{{([^|}]*)}}", -- {{LinkAndTitle}}
- function(LinkAndTitle)
- local idxHash = LinkAndTitle:find("#");
- if (idxHash ~= nil) then
- -- The LinkAndTitle contains a hash, remove the hashed part from the title:
- return CreateLink(LinkAndTitle, LinkAndTitle:sub(1, idxHash - 1));
- end
- return CreateLink(LinkAndTitle, LinkAndTitle);
- end
- );
- return txt;
-end
-
-
-
-
-
-local function WriteHtmlHook(a_Hook, a_HookNav)
- local fnam = "API/" .. a_Hook.DefaultFnName .. ".html";
- local f, error = io.open(fnam, "w");
- if (f == nil) then
- LOG("Cannot write \"" .. fnam .. "\": \"" .. error .. "\".");
- return;
- end
- local HookName = a_Hook.DefaultFnName;
-
- f:write([[
-
- Cuberite API - ]], HookName, [[ Hook
-
-
-
-
-
-
-
-
The default name for the callback function is ");
- f:write(a_Hook.DefaultFnName, ". It has the following signature:\n");
- f:write("
function ", HookName, "(");
- if (a_Hook.Params == nil) then
- a_Hook.Params = {};
- end
- for i, param in ipairs(a_Hook.Params) do
- if (i > 1) then
- f:write(", ");
- end
- f:write(param.Name);
- end
- f:write(")
\n
Parameters:
\n
Name
Type
Notes
\n");
- for _, param in ipairs(a_Hook.Params) do
- f:write("
", param.Name, "
", LinkifyString(param.Type, HookName), "
", LinkifyString(param.Notes, HookName), "
\n");
- end
- f:write("
\n
" .. LinkifyString(a_Hook.Returns or "", HookName) .. "
\n\n");
- local Examples = a_Hook.CodeExamples or {};
- for _, example in ipairs(Examples) do
- f:write("
", (example.Title or "missing Title"), "
\n");
- f:write("
", (example.Desc or "missing Desc"), "
\n");
- f:write("
", (example.Code or "missing Code"), "\n
\n\n");
- end
- f:write([[
]])
- f:write(GetHtmlTimestamp())
- f:write([[
-
-
-
- ]])
- f:write([[]])
- f:close();
-end
-
-
-
-
-
---- Writes all hooks into HTML output file as links in a sorted bullet list, as well as the individual hook HTML files
--- f is the output HTML index file
--- a_Hooks is an array of hook descriptions
--- a_UndocumentedHooks is a table that will be filled with the names of hooks that are not documented
--- a_HookNav is the HTML code for the menu on the left that is constant for all hook pages
-local function WriteHooks(f, a_Hooks, a_UndocumentedHooks, a_HookNav)
- f:write([[
-
- A plugin can register to be called whenever an "interesting event" occurs. It does so by calling
- cPluginManager's AddHook() function and implementing a callback
- function to handle the event.
-
- A plugin can decide whether it will let the event pass through to the rest of the plugins, or hide it
- from them. This is determined by the return value from the hook callback function. If the function
- returns false or no value, the event is propagated further. If the function returns true, the processing
- is stopped, no other plugin receives the notification (and possibly Cuberite disables the default
- behavior for the event). See each hook's details to see the exact behavior.
-
-
-
Hook name
-
Called when
-
- ]]);
- for _, hook in ipairs(a_Hooks) do
- if (hook.DefaultFnName == nil) then
- -- The hook is not documented yet
- f:write("
\n");
- WriteHtmlHook(hook, a_HookNav);
- end
- end
- f:write([[
-
-
- ]]);
-end
-
-
-
-
-
---- Fills the API in a_API table with descriptions from a_Desc
--- a_API is the API detected from current global environment
--- a_Desc is the description loaded from APIDesc.lua and Classes files
-local function ReadDescriptions(a_API, a_Desc)
- -- Returns true if the class of the specified name is to be ignored
- local function IsClassIgnored(a_ClsName)
- if (a_Desc.IgnoreClasses == nil) then
- return false;
- end
- for _, name in ipairs(a_Desc.IgnoreClasses) do
- if (a_ClsName:match(name)) then
- return true;
- end
- end
- return false;
- end
-
- -- Returns true if the function is to be ignored
- local function IsFunctionIgnored(a_ClassName, a_FnName)
- if (a_Desc.IgnoreFunctions == nil) then
- return false;
- end
- if (((a_Desc.Classes[a_ClassName] or {}).Functions or {})[a_FnName] ~= nil) then
- -- The function is documented, don't ignore
- return false;
- end
- local FnName = a_ClassName .. "." .. a_FnName;
- for _, name in ipairs(a_Desc.IgnoreFunctions) do
- if (FnName:match(name)) then
- return true;
- end
- end
- return false;
- end
-
- -- Returns true if the constant (specified by its fully qualified name) is to be ignored
- local function IsConstantIgnored(a_CnName)
- if (a_Desc.IgnoreConstants == nil) then
- return false;
- end;
- for _, name in ipairs(a_Desc.IgnoreConstants) do
- if (a_CnName:match(name)) then
- return true;
- end
- end
- return false;
- end
-
- -- Returns true if the member variable (specified by its fully qualified name) is to be ignored
- local function IsVariableIgnored(a_VarName)
- if (a_Desc.IgnoreVariables == nil) then
- return false;
- end;
- for _, name in ipairs(a_Desc.IgnoreVariables) do
- if (a_VarName:match(name)) then
- return true;
- end
- end
- return false;
- end
-
- -- Remove ignored classes from a_API:
- local APICopy = {};
- for _, cls in ipairs(a_API) do
- if not(IsClassIgnored(cls.Name)) then
- table.insert(APICopy, cls);
- end
- end
- for i = 1, #a_API do
- a_API[i] = APICopy[i];
- end;
-
- -- Process the documentation for each class:
- for _, cls in ipairs(a_API) do
- -- Initialize default values for each class:
- cls.ConstantGroups = {};
- cls.NumConstantsInGroups = 0;
- cls.NumConstantsInGroupsForDescendants = 0;
-
- -- Rename special functions:
- for _, fn in ipairs(cls.Functions) do
- if (fn.Name == ".call") then
- fn.DocID = "constructor";
- fn.Name = "() (constructor)";
- elseif (fn.Name == ".add") then
- fn.DocID = "operator_plus";
- fn.Name = "operator +";
- elseif (fn.Name == ".div") then
- fn.DocID = "operator_div";
- fn.Name = "operator /";
- elseif (fn.Name == ".mul") then
- fn.DocID = "operator_mul";
- fn.Name = "operator *";
- elseif (fn.Name == ".sub") then
- fn.DocID = "operator_sub";
- fn.Name = "operator -";
- elseif (fn.Name == ".eq") then
- fn.DocID = "operator_eq";
- fn.Name = "operator ==";
- end
- end
-
- local APIDesc = a_Desc.Classes[cls.Name];
- if (APIDesc ~= nil) then
- APIDesc.IsExported = true;
- cls.Desc = APIDesc.Desc;
- cls.AdditionalInfo = APIDesc.AdditionalInfo;
-
- -- Process inheritance:
- if (APIDesc.Inherits ~= nil) then
- for _, icls in ipairs(a_API) do
- if (icls.Name == APIDesc.Inherits) then
- table.insert(icls.Descendants, cls);
- cls.Inherits = icls;
- end
- end
- end
-
- cls.UndocumentedFunctions = {}; -- This will contain names of all the functions that are not documented
- cls.UndocumentedConstants = {}; -- This will contain names of all the constants that are not documented
- cls.UndocumentedVariables = {}; -- This will contain names of all the variables that are not documented
-
- local DoxyFunctions = {}; -- This will contain all the API functions together with their documentation
-
- local function AddFunction(a_Name, a_Params, a_Returns, a_IsStatic, a_Notes)
- table.insert(DoxyFunctions, {Name = a_Name, Params = a_Params, Returns = a_Returns, IsStatic = a_IsStatic, Notes = a_Notes});
- end
-
- if (APIDesc.Functions ~= nil) then
- -- Assign function descriptions:
- for _, func in ipairs(cls.Functions) do
- local FnName = func.DocID or func.Name;
- local FnDesc = APIDesc.Functions[FnName];
- if (FnDesc == nil) then
- -- No description for this API function
- AddFunction(func.Name);
- if not(IsFunctionIgnored(cls.Name, FnName)) then
- table.insert(cls.UndocumentedFunctions, FnName);
- end
- else
- -- Description is available
- if (FnDesc[1] == nil) then
- -- Single function definition
- AddFunction(func.Name, FnDesc.Params, FnDesc.Returns, FnDesc.IsStatic, FnDesc.Notes);
- else
- -- Multiple function overloads
- for _, desc in ipairs(FnDesc) do
- AddFunction(func.Name, desc.Params, desc.Returns, desc.IsStatic, desc.Notes);
- end -- for k, desc - FnDesc[]
- end
- FnDesc.IsExported = true;
- end
- end -- for j, func
-
- -- Replace functions with their described and overload-expanded versions:
- cls.Functions = DoxyFunctions;
- else -- if (APIDesc.Functions ~= nil)
- for _, func in ipairs(cls.Functions) do
- local FnName = func.DocID or func.Name;
- if not(IsFunctionIgnored(cls.Name, FnName)) then
- table.insert(cls.UndocumentedFunctions, FnName);
- end
- end
- end -- if (APIDesc.Functions ~= nil)
-
- if (APIDesc.Constants ~= nil) then
- -- Assign constant descriptions:
- for _, cons in ipairs(cls.Constants) do
- local CnDesc = APIDesc.Constants[cons.Name];
- if (CnDesc == nil) then
- -- Not documented
- if not(IsConstantIgnored(cls.Name .. "." .. cons.Name)) then
- table.insert(cls.UndocumentedConstants, cons.Name);
- end
- else
- cons.Notes = CnDesc.Notes;
- CnDesc.IsExported = true;
- end
- end -- for j, cons
- else -- if (APIDesc.Constants ~= nil)
- for _, cons in ipairs(cls.Constants) do
- if not(IsConstantIgnored(cls.Name .. "." .. cons.Name)) then
- table.insert(cls.UndocumentedConstants, cons.Name);
- end
- end
- end -- else if (APIDesc.Constants ~= nil)
-
- -- Assign member variables' descriptions:
- if (APIDesc.Variables ~= nil) then
- for _, var in ipairs(cls.Variables) do
- local VarDesc = APIDesc.Variables[var.Name];
- if (VarDesc == nil) then
- -- Not documented
- if not(IsVariableIgnored(cls.Name .. "." .. var.Name)) then
- table.insert(cls.UndocumentedVariables, var.Name);
- end
- else
- -- Copy all documentation:
- for k, v in pairs(VarDesc) do
- var[k] = v
- end
- end
- end -- for j, var
- else -- if (APIDesc.Variables ~= nil)
- for _, var in ipairs(cls.Variables) do
- if not(IsVariableIgnored(cls.Name .. "." .. var.Name)) then
- table.insert(cls.UndocumentedVariables, var.Name);
- end
- end
- end -- else if (APIDesc.Variables ~= nil)
-
- if (APIDesc.ConstantGroups ~= nil) then
- -- Create links between the constants and the groups:
- local NumInGroups = 0;
- local NumInDescendantGroups = 0;
- for j, group in pairs(APIDesc.ConstantGroups) do
- group.Name = j;
- group.Constants = {};
- if (type(group.Include) == "string") then
- group.Include = { group.Include };
- end
- local NumInGroup = 0;
- for _, incl in ipairs(group.Include or {}) do
- for _, cons in ipairs(cls.Constants) do
- if ((cons.Group == nil) and cons.Name:match(incl)) then
- cons.Group = group;
- table.insert(group.Constants, cons);
- NumInGroup = NumInGroup + 1;
- end
- end -- for cidx - cls.Constants[]
- end -- for idx - group.Include[]
- NumInGroups = NumInGroups + NumInGroup;
- if (group.ShowInDescendants) then
- NumInDescendantGroups = NumInDescendantGroups + NumInGroup;
- end
-
- -- Sort the constants:
- table.sort(group.Constants,
- function(c1, c2)
- return (c1.Name < c2.Name);
- end
- );
- end -- for j - APIDesc.ConstantGroups[]
- cls.ConstantGroups = APIDesc.ConstantGroups;
- cls.NumConstantsInGroups = NumInGroups;
- cls.NumConstantsInGroupsForDescendants = NumInDescendantGroups;
-
- -- Remove grouped constants from the normal list:
- local NewConstants = {};
- for _, cons in ipairs(cls.Constants) do
- if (cons.Group == nil) then
- table.insert(NewConstants, cons);
- end
- end
- cls.Constants = NewConstants;
- end -- if (ConstantGroups ~= nil)
-
- else -- if (APIDesc ~= nil)
-
- -- Class is not documented at all, add all its members to Undocumented lists:
- cls.UndocumentedFunctions = {};
- cls.UndocumentedConstants = {};
- cls.UndocumentedVariables = {};
- cls.Variables = cls.Variables or {};
- g_Stats.NumUndocumentedClasses = g_Stats.NumUndocumentedClasses + 1;
- for _, func in ipairs(cls.Functions) do
- local FnName = func.DocID or func.Name;
- if not(IsFunctionIgnored(cls.Name, FnName)) then
- table.insert(cls.UndocumentedFunctions, FnName);
- end
- end -- for j, func - cls.Functions[]
- for _, cons in ipairs(cls.Constants) do
- if not(IsConstantIgnored(cls.Name .. "." .. cons.Name)) then
- table.insert(cls.UndocumentedConstants, cons.Name);
- end
- end -- for j, cons - cls.Constants[]
- for _, var in ipairs(cls.Variables) do
- if not(IsConstantIgnored(cls.Name .. "." .. var.Name)) then
- table.insert(cls.UndocumentedVariables, var.Name);
- end
- end -- for j, var - cls.Variables[]
- end -- else if (APIDesc ~= nil)
-
- -- Remove ignored functions:
- local NewFunctions = {};
- for _, fn in ipairs(cls.Functions) do
- if (not(IsFunctionIgnored(cls.Name, fn.Name))) then
- table.insert(NewFunctions, fn);
- end
- end -- for j, fn
- cls.Functions = NewFunctions;
-
- -- Sort the functions (they may have been renamed):
- table.sort(cls.Functions,
- function(f1, f2)
- return (f1.Name < f2.Name);
- end
- );
-
- -- Remove ignored constants:
- local NewConstants = {};
- for _, cn in ipairs(cls.Constants) do
- if (not(IsFunctionIgnored(cls.Name, cn.Name))) then
- table.insert(NewConstants, cn);
- end
- end -- for j, cn
- cls.Constants = NewConstants;
-
- -- Sort the constants:
- table.sort(cls.Constants,
- function(c1, c2)
- return (c1.Name < c2.Name);
- end
- );
-
- -- Remove ignored member variables:
- local NewVariables = {};
- for _, var in ipairs(cls.Variables) do
- if (not(IsVariableIgnored(cls.Name .. "." .. var.Name))) then
- table.insert(NewVariables, var);
- end
- end -- for j, var
- cls.Variables = NewVariables;
-
- -- Sort the member variables:
- table.sort(cls.Variables,
- function(v1, v2)
- return (v1.Name < v2.Name);
- end
- );
- end -- for i, cls
-
- -- Sort the descendants lists:
- for _, cls in ipairs(a_API) do
- table.sort(cls.Descendants,
- function(c1, c2)
- return (c1.Name < c2.Name);
- end
- );
- end -- for i, cls
-end
-
-
-
-
-
---- Fills the hooks in a_Hooks with their descriptions from a_Descs
--- a_Hooks is an array of hooks detected from current global environment
--- a_Descs is the description read from APIDesc.lua and Hooks files
-local function ReadHooks(a_Hooks, a_Descs)
- --[[
- a_Hooks = {
- { Name = "HOOK_1"},
- { Name = "HOOK_2"},
- ...
- };
- We want to add hook descriptions to each hook in this array
- --]]
- for _, hook in ipairs(a_Hooks) do
- local HookDesc = a_Descs.Hooks[hook.Name];
- if (HookDesc ~= nil) then
- for key, val in pairs(HookDesc) do
- hook[key] = val;
- end
- end
- end -- for i, hook - a_Hooks[]
- g_Stats.NumTotalHooks = #a_Hooks;
-end
-
-
-
-
-
---- Returns a HTML string describing the (parameter) type, linking to the type's documentation, if available
--- a_Type is the string containing the type (such as "cPlugin" or "number"), or nil
--- a_API is the complete API description (used for searching the classnames)
-local function LinkifyType(a_Type, a_API)
- -- Check params:
- assert(type(a_Type) == "string")
- assert(type(a_API) == "table")
-
- -- If the type is a known class, return a direct link to it:
- if (a_API[a_Type]) then
- return "" .. a_Type .. ""
- end
-
- -- If the type has a hash sign, it's a child enum of a class:
- local idxColon = a_Type:find("#")
- if (idxColon) then
- local classType = a_Type:sub(1, idxColon - 1)
- if (a_API[classType]) then
- local enumType = a_Type:sub(idxColon + 1)
- return "" .. enumType .. ""
- end
- end
-
- -- If the type is a ConstantGroup within the Globals, it's a global enum:
- if ((a_API.Globals.ConstantGroups or {})[a_Type]) then
- return "" .. a_Type .. ""
- end
-
- -- Unknown or built-in type, output just text:
- return a_Type
-end
-
-
-
-
-
---- Returns an HTML string describing all function parameters (or return values)
--- a_FnParams is an array-table or string description of the parameters
--- a_ClassName is the name of the class for which the function is being documented (for Linkification)
--- a_API is the complete API description (for cross-type linkification)
-local function CreateFunctionParamsDescription(a_FnParams, a_ClassName, a_API)
- local pt = type(a_FnParams)
- assert((pt == "string") or (pt == "table"))
- assert(type(a_ClassName) == "string")
- assert(type(a_API) == "table")
-
- -- If the params description is a string (old format), just linkify it:
- if (pt == "string") then
- return LinkifyString(a_FnParams, a_ClassName)
- end
-
- -- If the params description is an empty table, give no description at all:
- if not(a_FnParams[1]) then
- return ""
- end
-
- -- The params description is a table, output the full desc:
- local res = {"
"}
- local idx = 2
- for _, param in ipairs(a_FnParams) do
- res[idx] = "
"
- return table.concat(res)
-end
-
-
-
-
-
---- Writes an HTML file containing the class API description for the given class
--- a_ClassAPI is the API description of the class to output
--- a_ClassMenu is the HTML string containing the code for the menu sidebar
--- a_API is the complete API (for cross-type linkification)
-local function WriteHtmlClass(a_ClassAPI, a_ClassMenu, a_API)
- -- Check params:
- assert(type(a_ClassAPI) == "table")
- assert(type(a_ClassMenu) == "string")
- assert(type(a_API) == "table")
-
- local cf, err = io.open("API/" .. a_ClassAPI.Name .. ".html", "w");
- if (cf == nil) then
- LOGINFO("Cannot write HTML API for class " .. a_ClassAPI.Name .. ": " .. err)
- return;
- end
-
- -- Writes a table containing all functions in the specified list, with an optional "inherited from" header when a_InheritedName is valid
- local function WriteFunctions(a_Functions, a_InheritedName)
- if not(a_Functions[1]) then
- -- No functions to write
- return;
- end
-
- if (a_InheritedName) then
- cf:write("
Functions inherited from ", a_InheritedName, "
\n");
- end
- cf:write("
\n
Name
Parameters
Return value
Notes
\n");
- -- Store all function names, to create unique anchor names for all functions
- local TableOverloadedFunctions = {}
- for _, func in ipairs(a_Functions) do
- local StaticClause = ""
- if (func.IsStatic) then
- StaticClause = "(STATIC) "
- end
- -- Increase number by one
- TableOverloadedFunctions[func.Name] = (TableOverloadedFunctions[func.Name] or 0) + 1
- -- Add the anchor names as a title
- cf:write("
", func.Name, "
\n");
- cf:write("
", CreateFunctionParamsDescription(func.Params or {}, a_InheritedName or a_ClassAPI.Name, a_API), "
\n");
- cf:write("
", CreateFunctionParamsDescription(func.Returns or {}, a_InheritedName or a_ClassAPI.Name, a_API), "
\n");
- cf:write("
", StaticClause .. LinkifyString(func.Notes or "(undocumented)", (a_InheritedName or a_ClassAPI.Name)), "
\n");
- end
- cf:write("
\n");
- end
-
- local function WriteConstantTable(a_Constants, a_Source)
- cf:write("
\n
Name
Value
Notes
\n");
- for _, cons in ipairs(a_Constants) do
- cf:write("
", cons.Name, "
\n");
- cf:write("
", cons.Value, "
\n");
- cf:write("
", LinkifyString(cons.Notes or "", a_Source), "
\n");
- end
- cf:write("
\n\n");
- end
-
- local function WriteConstants(a_Constants, a_ConstantGroups, a_NumConstantGroups, a_InheritedName)
- if ((#a_Constants == 0) and (a_NumConstantGroups == 0)) then
- return;
- end
-
- local Source = a_ClassAPI.Name
- if (a_InheritedName ~= nil) then
- cf:write("
Constants inherited from ", a_InheritedName, "
\n");
- Source = a_InheritedName;
- end
-
- if (#a_Constants > 0) then
- WriteConstantTable(a_Constants, Source);
- end
-
- for _, group in pairs(a_ConstantGroups) do
- if ((a_InheritedName == nil) or group.ShowInDescendants) then
- cf:write("
");
- end
- end
- end
-
- local function WriteVariables(a_Variables, a_InheritedName)
- if (#a_Variables == 0) then
- return;
- end
-
- if (a_InheritedName ~= nil) then
- cf:write("
Member variables inherited from ", a_InheritedName, "
\n");
- end
-
- cf:write("
Name
Type
Notes
\n");
- for _, var in ipairs(a_Variables) do
- cf:write("
", var.Name, "
\n");
- cf:write("
", LinkifyString(var.Type or "(undocumented)", a_InheritedName or a_ClassAPI.Name), "
\n");
- cf:write("
", LinkifyString(var.Notes or "", a_InheritedName or a_ClassAPI.Name), "
\n
\n");
- end
- cf:write("
\n\n");
- end
-
- local function WriteDescendants(a_Descendants)
- if (#a_Descendants == 0) then
- return;
- end
- cf:write("
");
- for _, desc in ipairs(a_Descendants) do
- cf:write("
\n");
- WriteVariables(a_ClassAPI.Variables, nil);
- g_Stats.NumTotalVariables = g_Stats.NumTotalVariables + #a_ClassAPI.Variables;
- for _, cls in ipairs(InheritanceChain) do
- WriteVariables(cls.Variables, cls.Name);
- end;
- end
-
- -- Write the functions, including the inherited ones:
- if (HasFunctions) then
- cf:write("
\n");
- WriteFunctions(a_ClassAPI.Functions, nil);
- g_Stats.NumTotalFunctions = g_Stats.NumTotalFunctions + #a_ClassAPI.Functions;
- for _, cls in ipairs(InheritanceChain) do
- WriteFunctions(cls.Functions, cls.Name);
- end
- end
-
- -- Write the additional infos:
- if (a_ClassAPI.AdditionalInfo ~= nil) then
- for i, additional in ipairs(a_ClassAPI.AdditionalInfo) do
- cf:write("
\n");
- cf:write(LinkifyString(additional.Contents, ClassName));
- end
- end
-
- cf:write([[
]])
- cf:write(GetHtmlTimestamp())
- cf:write([[
-
-
-
- ]])
- cf:write([[]])
- cf:close()
-end
-
-
-
-
-
---- Writes all classes into HTML output file as links in a sorted bullet list, as well as the individual class HTML files
--- f is the output file
--- a_API is the API detected from current environment enriched with descriptions
--- a_ClassMenu is the HTML code for the menu on the left that is constant for all class pages
-local function WriteClasses(f, a_API, a_ClassMenu)
- f:write([[
-
\n");
- WriteHtmlClass(cls, a_ClassMenu, a_API);
- end
- f:write([[
-
-
- ]]);
-end
-
-
-
-
-
---- Writes a list of undocumented objects into a file
-local function ListUndocumentedObjects(API, UndocumentedHooks)
- local f = io.open("API/_undocumented.lua", "w");
- if (f ~= nil) then
- f:write("\n-- This is the list of undocumented API objects, automatically generated by APIDump\n\n");
- f:write("return\n{\n\tClasses =\n\t{\n");
- for _, cls in ipairs(API) do
- local HasFunctions = ((cls.UndocumentedFunctions ~= nil) and (#cls.UndocumentedFunctions > 0));
- local HasConstants = ((cls.UndocumentedConstants ~= nil) and (#cls.UndocumentedConstants > 0));
- local HasVariables = ((cls.UndocumentedVariables ~= nil) and (#cls.UndocumentedVariables > 0));
- g_Stats.NumUndocumentedFunctions = g_Stats.NumUndocumentedFunctions + #cls.UndocumentedFunctions;
- g_Stats.NumUndocumentedConstants = g_Stats.NumUndocumentedConstants + #cls.UndocumentedConstants;
- g_Stats.NumUndocumentedVariables = g_Stats.NumUndocumentedVariables + #cls.UndocumentedVariables;
- if (HasFunctions or HasConstants or HasVariables) then
- f:write("\t\t" .. cls.Name .. " =\n\t\t{\n");
- if ((cls.Desc == nil) or (cls.Desc == "")) then
- f:write("\t\t\tDesc = \"\",\n");
- end
- end
-
- if (HasFunctions) then
- f:write("\t\t\tFunctions =\n\t\t\t{\n");
- table.sort(cls.UndocumentedFunctions);
- for _, fn in ipairs(cls.UndocumentedFunctions) do
- f:write("\t\t\t\t" .. fn .. " = { Params = \"\", Return = \"\", Notes = \"\" },\n");
- end -- for j, fn - cls.UndocumentedFunctions[]
- f:write("\t\t\t},\n\n");
- end
-
- if (HasConstants) then
- f:write("\t\t\tConstants =\n\t\t\t{\n");
- table.sort(cls.UndocumentedConstants);
- for _, cn in ipairs(cls.UndocumentedConstants) do
- f:write("\t\t\t\t" .. cn .. " = { Notes = \"\" },\n");
- end -- for j, fn - cls.UndocumentedConstants[]
- f:write("\t\t\t},\n\n");
- end
-
- if (HasVariables) then
- f:write("\t\t\tVariables =\n\t\t\t{\n");
- table.sort(cls.UndocumentedVariables);
- for _, vn in ipairs(cls.UndocumentedVariables) do
- f:write("\t\t\t\t" .. vn .. " = { Type = \"\", Notes = \"\" },\n");
- end -- for j, fn - cls.UndocumentedVariables[]
- f:write("\t\t\t},\n\n");
- end
-
- if (HasFunctions or HasConstants or HasVariables) then
- f:write("\t\t},\n\n");
- end
- end -- for i, cls - API[]
- f:write("\t},\n");
-
- if (#UndocumentedHooks > 0) then
- f:write("\n\tHooks =\n\t{\n");
- for i, hook in ipairs(UndocumentedHooks) do
- if (i > 1) then
- f:write("\n");
- end
- f:write("\t\t" .. hook .. " =\n\t\t{\n");
- f:write("\t\t\tCalledWhen = \"\",\n");
- f:write("\t\t\tDefaultFnName = \"On\", -- also used as pagename\n");
- f:write("\t\t\tDesc = [[\n\t\t\t\t\n\t\t\t]],\n");
- f:write("\t\t\tParams =\n\t\t\t{\n");
- f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
- f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
- f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
- f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
- f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
- f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
- f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
- f:write("\t\t\t\t{ Name = \"\", Type = \"\", Notes = \"\" },\n");
- f:write("\t\t\t},\n");
- f:write("\t\t\tReturns = [[\n\t\t\t\t\n\t\t\t]],\n");
- f:write("\t\t}, -- " .. hook .. "\n");
- end
- f:write("\t},\n");
- end
- f:write("}\n\n\n\n");
- f:close();
- end
- g_Stats.NumUndocumentedHooks = #UndocumentedHooks;
-end
-
-
-
-
-
---- Lists the API objects that are documented but not available in the API:
-local function ListUnexportedObjects(a_APIDesc)
- f = io.open("API/_unexported-documented.txt", "w");
- if (f ~= nil) then
- for clsname, cls in pairs(a_APIDesc.Classes) do
- if not(cls.IsExported) then
- -- The whole class is not exported
- f:write("class\t" .. clsname .. "\n");
- else
- if (cls.Functions ~= nil) then
- for fnname, fnapi in pairs(cls.Functions) do
- if not(fnapi.IsExported) then
- f:write("func\t" .. clsname .. "." .. fnname .. "\n");
- end
- end -- for j, fn - cls.Functions[]
- end
- if (cls.Constants ~= nil) then
- for cnname, cnapi in pairs(cls.Constants) do
- if not(cnapi.IsExported) then
- f:write("const\t" .. clsname .. "." .. cnname .. "\n");
- end
- end -- for j, fn - cls.Functions[]
- end
- end
- end -- for i, cls - a_APIDesc.Classes[]
- f:close();
- end
-end
-
-
-
-
-
-local function ListMissingPages()
- local MissingPages = {};
- local NumLinks = 0;
- for PageName, Referrers in pairs(g_TrackedPages) do
- NumLinks = NumLinks + 1;
- if not(cFile:IsFile("API/" .. PageName .. ".html")) then
- table.insert(MissingPages, {Name = PageName, Refs = Referrers} );
- end
- end;
- g_Stats.NumTrackedLinks = NumLinks;
- g_TrackedPages = {};
-
- if (#MissingPages == 0) then
- -- No missing pages, congratulations!
- return;
- end
-
- -- Sort the pages by name:
- table.sort(MissingPages,
- function (Page1, Page2)
- return (Page1.Name < Page2.Name);
- end
- );
-
- -- Output the pages:
- local f, err = io.open("API/_missingPages.txt", "w");
- if (f == nil) then
- LOGWARNING("Cannot open _missingPages.txt for writing: '" .. err .. "'. There are " .. #MissingPages .. " pages missing.");
- return;
- end
- for _, pg in ipairs(MissingPages) do
- f:write(pg.Name .. ":\n");
- -- Sort and output the referrers:
- table.sort(pg.Refs);
- f:write("\t" .. table.concat(pg.Refs, "\n\t"));
- f:write("\n\n");
- end
- f:close();
- g_Stats.NumInvalidLinks = #MissingPages;
-end
-
-
-
-
-
---- Writes the documentation statistics (in g_Stats) into the given HTML file
-local function WriteStats(f)
- local function ExportMeter(a_Percent)
- local Color;
- if (a_Percent > 99) then
- Color = "green";
- elseif (a_Percent > 50) then
- Color = "orange";
- else
- Color = "red";
- end
-
- local meter = {
- "\n",
- "
There are ]], g_Stats.NumTrackedLinks, " internal links, ", g_Stats.NumInvalidLinks, " of them are invalid.
"
- );
-end
-
-
-
-
-
-local function DumpAPIHtml(a_API, a_Descs)
- LOG("Dumping all available functions and constants to API subfolder...");
-
- -- Create the output folder
- if not(cFile:IsFolder("API")) then
- cFile:CreateFolder("API");
- end
-
- LOG("Copying static files..");
- cFile:CreateFolder("API/Static");
- local localFolder = g_Plugin:GetLocalFolder();
- for _, fnam in ipairs(cFile:GetFolderContents(localFolder .. "/Static")) do
- cFile:Delete("API/Static/" .. fnam);
- cFile:Copy(localFolder .. "/Static/" .. fnam, "API/Static/" .. fnam);
- end
-
- -- Extract hook constants:
- local Hooks = {};
- local UndocumentedHooks = {};
- for name, obj in pairs(cPluginManager) do
- if (
- (type(obj) == "number") and
- name:match("HOOK_.*") and
- (name ~= "HOOK_MAX") and
- (name ~= "HOOK_NUM_HOOKS")
- ) then
- table.insert(Hooks, { Name = name });
- end
- end
- table.sort(Hooks,
- function(Hook1, Hook2)
- return (Hook1.Name < Hook2.Name);
- end
- );
- ReadHooks(Hooks, a_Descs);
-
- -- Create a "class index" file, write each class as a link to that file,
- -- then dump class contents into class-specific file
- LOG("Writing HTML files...");
- local f, err = io.open("API/index.html", "w");
- if (f == nil) then
- LOGINFO("Cannot output HTML API: " .. err);
- return;
- end
-
- -- Create a class navigation menu that will be inserted into each class file for faster navigation (#403)
- local ClassMenuTab = {};
- for _, cls in ipairs(a_API) do
- table.insert(ClassMenuTab, "");
- table.insert(ClassMenuTab, cls.Name);
- table.insert(ClassMenuTab, " ");
- end
- local ClassMenu = table.concat(ClassMenuTab, "");
-
- -- Create a hook navigation menu that will be inserted into each hook file for faster navigation(#403)
- local HookNavTab = {};
- for _, hook in ipairs(Hooks) do
- table.insert(HookNavTab, "");
- table.insert(HookNavTab, (hook.Name:gsub("^HOOK_", ""))); -- remove the "HOOK_" part of the name
- table.insert(HookNavTab, " ");
- end
- local HookNav = table.concat(HookNavTab, "");
-
- -- Write the HTML file:
- f:write([[
-
-
- Cuberite API - Index
-
-
-
-
-
-
Cuberite API - Index
-
-
-
The API reference is divided into the following sections:
-
- ]]);
-
- WriteArticles(f, a_Descs);
- WriteClasses(f, a_API, ClassMenu);
- WriteHooks(f, Hooks, UndocumentedHooks, HookNav);
-
- -- Copy the static files to the output folder:
- local StaticFiles =
- {
- "main.css",
- "piwik.js",
- "prettify.js",
- "prettify.css",
- "lang-lua.js",
- };
- for _, fnam in ipairs(StaticFiles) do
- cFile:Delete("API/" .. fnam);
- cFile:Copy(g_Plugin:GetLocalFolder() .. "/" .. fnam, "API/" .. fnam);
- end
-
- -- List the documentation problems:
- LOG("Listing leftovers...");
- ListUndocumentedObjects(a_API, UndocumentedHooks);
- ListUnexportedObjects(a_Descs);
- ListMissingPages();
-
- WriteStats(f);
-
- f:write([[
]])
- f:write(GetHtmlTimestamp())
- f:write([[
-
-
-
- ]])
- f:write([[]])
- f:close()
-
- LOG("API subfolder written");
-end
-
-
-
-
-
---- Returns the string with extra tabs and CR/LFs removed
-local function CleanUpDescription(a_Desc)
- -- Get rid of indent and newlines, normalize whitespace:
- local res = a_Desc:gsub("[\n\t]", "")
- res = a_Desc:gsub("%s%s+", " ")
-
- -- Replace paragraph marks with newlines:
- res = res:gsub("
", "\n")
- res = res:gsub("
", "")
-
- -- Replace list items with dashes:
- res = res:gsub("?ul>", "")
- res = res:gsub("
", "\n - ")
- res = res:gsub("
", "")
-
- return res
-end
-
-
-
-
-
---- Writes a list of methods into the specified file in ZBS format
-local function WriteZBSMethods(f, a_Methods)
- for _, func in ipairs(a_Methods or {}) do
- f:write("\t\t\t[\"", func.Name, "\"] =\n")
- f:write("\t\t\t{\n")
- f:write("\t\t\t\ttype = \"method\",\n")
- -- No way to indicate multiple signatures to ZBS, so don't output any params at all
- if ((func.Notes ~= nil) and (func.Notes ~= "")) then
- f:write("\t\t\t\tdescription = [[", CleanUpDescription(func.Notes or ""), " ]],\n")
- end
- f:write("\t\t\t},\n")
- end
-end
-
-
-
-
-
---- Writes a list of constants into the specified file in ZBS format
-local function WriteZBSConstants(f, a_Constants)
- for _, cons in ipairs(a_Constants or {}) do
- f:write("\t\t\t[\"", cons.Name, "\"] =\n")
- f:write("\t\t\t{\n")
- f:write("\t\t\t\ttype = \"value\",\n")
- if ((cons.Desc ~= nil) and (cons.Desc ~= "")) then
- f:write("\t\t\t\tdescription = [[", CleanUpDescription(cons.Desc or ""), " ]],\n")
- end
- f:write("\t\t\t},\n")
- end
-end
-
-
-
-
-
---- Writes one Cuberite class definition into the specified file in ZBS format
-local function WriteZBSClass(f, a_Class)
- assert(type(a_Class) == "table")
-
- -- Write class header:
- f:write("\t", a_Class.Name, " =\n\t{\n")
- f:write("\t\ttype = \"class\",\n")
- f:write("\t\tdescription = [[", CleanUpDescription(a_Class.Desc or ""), " ]],\n")
- f:write("\t\tchilds =\n")
- f:write("\t\t{\n")
-
- -- Export methods and constants:
- WriteZBSMethods(f, a_Class.Functions)
- WriteZBSConstants(f, a_Class.Constants)
-
- -- Finish the class definition:
- f:write("\t\t},\n")
- f:write("\t},\n\n")
-end
-
-
-
-
-
---- Dumps the entire API table into a file in the ZBS format
-local function DumpAPIZBS(a_API)
- LOG("Dumping ZBS API description...")
- local f, err = io.open("cuberite_api.lua", "w")
- if (f == nil) then
- LOG("Cannot open cuberite_api.lua for writing, ZBS API will not be dumped. " .. err)
- return
- end
-
- -- Write the file header:
- f:write("-- This is a Cuberite API file automatically generated by the APIDump plugin\n")
- f:write("-- Note that any manual changes will be overwritten by the next dump\n\n")
- f:write("return {\n")
-
- -- Export each class except Globals, store those aside:
- local Globals
- for _, cls in ipairs(a_API) do
- if (cls.Name ~= "Globals") then
- WriteZBSClass(f, cls)
- else
- Globals = cls
- end
- end
-
- -- Export the globals:
- if (Globals) then
- WriteZBSMethods(f, Globals.Functions)
- WriteZBSConstants(f, Globals.Constants)
- end
-
- -- Finish the file:
- f:write("}\n")
- f:close()
- LOG("ZBS API dumped...")
-end
-
-
-
-
-
---- Returns true if a_Descendant is declared to be a (possibly indirect) descendant of a_Base
-local function IsDeclaredDescendant(a_DescendantName, a_BaseName, a_API)
- -- Check params:
- assert(type(a_DescendantName) == "string")
- assert(type(a_BaseName) == "string")
- assert(type(a_API) == "table")
- if not(a_API[a_BaseName]) then
- return false
- end
- assert(type(a_API[a_BaseName]) == "table", "Not a class name: " .. a_BaseName)
- assert(type(a_API[a_BaseName].Descendants) == "table")
-
- -- Check direct inheritance:
- for _, desc in ipairs(a_API[a_BaseName].Descendants) do
- if (desc.Name == a_DescendantName) then
- return true
- end
- end -- for desc - a_BaseName's descendants
-
- -- Check indirect inheritance:
- for _, desc in ipairs(a_API[a_BaseName].Descendants) do
- if (IsDeclaredDescendant(a_DescendantName, desc.Name, a_API)) then
- return true
- end
- end -- for desc - a_BaseName's descendants
-
- return false
-end
-
-
-
-
-
---- Checks the specified class' inheritance
--- Reports any problems as new items in the a_Report table
-local function CheckClassInheritance(a_Class, a_API, a_Report)
- -- Check params:
- assert(type(a_Class) == "table")
- assert(type(a_API) == "table")
- assert(type(a_Report) == "table")
-
- -- Check that the declared descendants are really descendants:
- local registry = debug.getregistry()
- for _, desc in ipairs(a_Class.Descendants or {}) do
- local isParent = false
- local parents = registry["tolua_super"][_G[desc.Name]]
- if not(parents[a_Class.Name]) then
- table.insert(a_Report, desc.Name .. " is not a descendant of " .. a_Class.Name)
- end
- end -- for desc - a_Class.Descendants[]
-
- -- Check that all inheritance is listed for the class:
- local parents = registry["tolua_super"][_G[a_Class.Name]] -- map of "classname" -> true for each class that a_Class inherits
- for clsName, isParent in pairs(parents or {}) do
- if ((clsName ~= "") and not(clsName:match("const .*"))) then
- if not(IsDeclaredDescendant(a_Class.Name, clsName, a_API)) then
- table.insert(a_Report, a_Class.Name .. " inherits from " .. clsName .. " but this isn't documented")
- end
- end
- end
-end
-
-
-
-
-
---- Checks each class's declared inheritance versus the actual inheritance
-local function CheckAPIDescendants(a_API)
- -- Check each class:
- local report = {}
- for _, cls in ipairs(a_API) do
- if (cls.Name ~= "Globals") then
- CheckClassInheritance(cls, a_API, report)
- end
- end
-
- -- If there's anything to report, output it to a file:
- if (report[1] ~= nil) then
- LOG("There are inheritance errors in the API description:")
- for _, msg in ipairs(report) do
- LOG(" " .. msg)
- end
-
- local f, err = io.open("API/_inheritance_errors.txt", "w")
- if (f == nil) then
- LOG("Cannot report inheritance problems to a file: " .. tostring(err))
- return
- end
- f:write(table.concat(report, "\n"))
- f:close()
- end
-end
-
-
-
-
-
---- Prepares the API and Globals tables containing the documentation
--- Returns the API and Globals desc table, containing the Classes and Hooks subtables with descriptions,
--- and the apiDesc table containing the descriptions only in their original format.
-local function PrepareApi()
- -- Load the API descriptions from the Classes and Hooks subfolders:
- -- This needs to be done each time the command is invoked because the export modifies the tables' contents
- local apiDesc = dofile(g_PluginFolder .. "/APIDesc.lua")
- apiDesc.Classes = apiDesc.Classes or {}
- apiDesc.Hooks = apiDesc.Hooks or {}
- LoadAPIFiles("/Classes/", apiDesc.Classes)
- LoadAPIFiles("/Hooks/", apiDesc.Hooks)
-
- -- Reset the stats:
- g_TrackedPages = {}; -- List of tracked pages, to be checked later whether they exist. Each item is an array of referring pagenames.
- g_Stats = -- Statistics about the documentation
- {
- NumTotalClasses = 0,
- NumUndocumentedClasses = 0,
- NumTotalFunctions = 0,
- NumUndocumentedFunctions = 0,
- NumTotalConstants = 0,
- NumUndocumentedConstants = 0,
- NumTotalVariables = 0,
- NumUndocumentedVariables = 0,
- NumTotalHooks = 0,
- NumUndocumentedHooks = 0,
- NumTrackedLinks = 0,
- NumInvalidLinks = 0,
- }
-
- -- Create the API tables:
- local API, Globals = CreateAPITables();
-
- -- Sort the classes by name:
- table.sort(API,
- function (c1, c2)
- return (string.lower(c1.Name) < string.lower(c2.Name));
- end
- );
- g_Stats.NumTotalClasses = #API;
-
- -- Add Globals into the API:
- Globals.Name = "Globals";
- table.insert(API, Globals);
- API.Globals = Globals
-
- -- Read in the descriptions:
- LOG("Reading descriptions...");
- ReadDescriptions(API, apiDesc);
-
- return API, Globals, apiDesc
-end
-
-
-
-
-
-local function DumpApi()
- LOG("Dumping the API...")
-
- -- Match the currently exported API with the available documentation:
- local API, Globals, descs = PrepareApi()
-
- -- Check that the API lists the inheritance properly, report any problems to a file:
- CheckAPIDescendants(API)
-
- -- Dump all available API objects in HTML format into a subfolder:
- DumpAPIHtml(API, descs);
-
- -- Dump all available API objects in format used by ZeroBraneStudio API descriptions:
- DumpAPIZBS(API)
-
- LOG("APIDump finished");
- return true
-end
-
-
-
-
-
-local function HandleWebAdminDump(a_Request)
- if (a_Request.PostParams["Dump"] ~= nil) then
- DumpApi()
- end
- return
- [[
-
Pressing the button will generate the API dump on the server. Note that this can take some time.
-
- ]]
-end
-
-
-
-
-
-local function HandleCmdApi(a_Split)
- DumpApi()
- return true
-end
-
-
-
-
-
-local function HandleCmdApiShow(a_Split, a_EntireCmd)
- os.execute("API" .. cFile:GetPathSeparator() .. "index.html")
- return true, "Launching the browser to show the API docs..."
-end
-
-
-
-
-
-local function HandleCmdApiCheck(a_Split, a_EntireCmd)
- -- Download the official API stats on undocumented stuff:
- -- (We need a blocking downloader, which is impossible with the current cNetwork API)
- assert(os.execute("wget -O official_undocumented.lua http://apidocs.cuberite.org/_undocumented.lua"))
- local OfficialStats = cFile:ReadWholeFile("official_undocumented.lua")
- if (OfficialStats == "") then
- return true, "Cannot load official stats"
- end
-
- -- Load the API stats as a Lua file, process into usable dictionary:
- -- The _undocumented.lua file format has changed from "g_APIDesc = {}" to "return {}"
- -- To support both versions, we execute the function in a sandbox and check both its return value and the sandbox globals
- local Loaded, Msg = loadstring(OfficialStats)
- if not(Loaded) then
- return true, "Cannot load official stats: " .. (Msg or "")
- end
- local sandbox = {}
- setfenv(Loaded, sandbox)
- local IsSuccess, OfficialUndocumented = pcall(Loaded)
- if not(IsSuccess) then
- return true, "Cannot parse official stats: " .. tostring(OfficialUndocumented or "")
- end
- local Parsed = {}
- for clsK, clsV in pairs((sandbox.g_APIDesc or OfficialUndocumented).Classes) do -- Check return value OR sandbox global, whichever is present
- local cls =
- {
- Desc = not(clsV.Desc), -- set to true if the Desc was not documented in the official docs
- Functions = {},
- Constants = {}
- }
- for funK, _ in pairs(clsV.Functions or {}) do
- cls.Functions[funK] = true
- end
- for conK, _ in pairs(clsV.Constants or {}) do
- cls.Constants[conK] = true
- end
- Parsed[clsK] = cls
- end
-
- -- Get the current API's undocumented stats:
- local API = PrepareApi()
-
- -- Compare the two sets of undocumented stats, list anything extra in current:
- local res = {}
- local ins = table.insert
- for _, cls in ipairs(API) do
- local ParsedOfficial = Parsed[cls.Name] or {}
- if (not(cls.Desc) and ParsedOfficial.Desc) then
- ins(res, cls.Name .. ".Desc")
- end
- local ParsedOfficialFns = ParsedOfficial.Functions or {}
- for _, funK in ipairs(cls.UndocumentedFunctions or {}) do
- if not(ParsedOfficialFns[funK]) then
- ins(res, cls.Name .. "." .. funK .. " (function)")
- end
- end
- local ParsedOfficialCons = ParsedOfficial.Constants or {}
- for _, conK in ipairs(cls.UndocumentedConstants or {}) do
- if not(ParsedOfficialCons[conK]) then
- ins(res, cls.Name .. "." .. conK .. " (constant)")
- end
- end
- end
- table.sort(res)
-
- -- Bail out if no items found:
- if not(res[1]) then
- return true, "No new undocumented functions"
- end
-
- -- Save any found items to a file:
- local f = io.open("NewlyUndocumented.lua", "w")
- f:write(table.concat(res, "\n"))
- f:write("\n")
- f:close()
-
- return true, "Newly undocumented items: " .. #res .. "\n" .. table.concat(res, "\n")
-end
-
-
-
-
-
-function Initialize(Plugin)
- g_Plugin = Plugin;
- g_PluginFolder = Plugin:GetLocalFolder();
-
- LOG("Initialising " .. Plugin:GetName() .. " v." .. Plugin:GetVersion())
-
- -- Bind a console command to dump the API:
- cPluginManager:BindConsoleCommand("api", HandleCmdApi, "Dumps the Lua API docs into the API/ subfolder")
- cPluginManager:BindConsoleCommand("apicheck", HandleCmdApiCheck, "Checks the Lua API documentation stats against the official stats")
- cPluginManager:BindConsoleCommand("apishow", HandleCmdApiShow, "Runs the default browser to show the API docs")
-
- -- Add a WebAdmin tab that has a Dump button
- g_Plugin:AddWebTab("APIDump", HandleWebAdminDump)
-
- return true
-end
diff --git a/world/Plugins/APIDump/piwik.js b/world/Plugins/APIDump/piwik.js
deleted file mode 100644
index 4cc288e8..00000000
--- a/world/Plugins/APIDump/piwik.js
+++ /dev/null
@@ -1,6572 +0,0 @@
-/*!
- * Piwik - free/libre analytics platform
- *
- * JavaScript tracking client
- *
- * @link http://piwik.org
- * @source https://github.com/piwik/piwik/blob/master/js/piwik.js
- * @license http://piwik.org/free-software/bsd/ BSD-3 Clause (also in js/LICENSE.txt)
- * @license magnet:?xt=urn:btih:c80d50af7d3db9be66a4d0a86db0286e4fd33292&dn=bsd-3-clause.txt BSD-3-Clause
- */
-// NOTE: if you change this above Piwik comment block, you must also change `$byteStart` in js/tracker.php
-
-// Refer to README.md for build instructions when minifying this file for distribution.
-
-/*
- * Browser [In]Compatibility
- * - minimum required ECMAScript: ECMA-262, edition 3
- *
- * Incompatible with these (and earlier) versions of:
- * - IE4 - try..catch and for..in introduced in IE5
- * - IE5 - named anonymous functions, array.push, encodeURIComponent, decodeURIComponent, and getElementsByTagName introduced in IE5.5
- * - Firefox 1.0 and Netscape 8.x - FF1.5 adds array.indexOf, among other things
- * - Mozilla 1.7 and Netscape 6.x-7.x
- * - Netscape 4.8
- * - Opera 6 - Error object (and Presto) introduced in Opera 7
- * - Opera 7
- */
-
-/*global JSON2:true */
-
-if (typeof JSON2 !== 'object' && typeof window.JSON === 'object' && window.JSON.stringify && window.JSON.parse) {
- JSON2 = window.JSON;
-} else {
- (function () {
- // we make sure to not break any site that uses JSON3 as well as we do not know if they run it in conflict mode
- // or not.
- var exports = {};
-
- // Create a JSON object only if one does not already exist. We create the
- // methods in a closure to avoid creating global variables.
-
- /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
- (function () {
- // Detect the `define` function exposed by asynchronous module loaders. The
- // strict `define` check is necessary for compatibility with `r.js`.
- var isLoader = typeof define === "function" && define.amd;
-
- // A set of types used to distinguish objects from primitives.
- var objectTypes = {
- "function": true,
- "object": true
- };
-
- // Detect the `exports` object exposed by CommonJS implementations.
- var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
-
- // Use the `global` object exposed by Node (including Browserify via
- // `insert-module-globals`), Narwhal, and Ringo as the default context,
- // and the `window` object in browsers. Rhino exports a `global` function
- // instead.
- var root = objectTypes[typeof window] && window || this,
- freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
-
- if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
- root = freeGlobal;
- }
-
- // Public: Initializes JSON 3 using the given `context` object, attaching the
- // `stringify` and `parse` functions to the specified `exports` object.
- function runInContext(context, exports) {
- context || (context = root["Object"]());
- exports || (exports = root["Object"]());
-
- // Native constructor aliases.
- var Number = context["Number"] || root["Number"],
- String = context["String"] || root["String"],
- Object = context["Object"] || root["Object"],
- Date = context["Date"] || root["Date"],
- SyntaxError = context["SyntaxError"] || root["SyntaxError"],
- TypeError = context["TypeError"] || root["TypeError"],
- Math = context["Math"] || root["Math"],
- nativeJSON = context["JSON"] || root["JSON"];
-
- // Delegate to the native `stringify` and `parse` implementations.
- if (typeof nativeJSON == "object" && nativeJSON) {
- exports.stringify = nativeJSON.stringify;
- exports.parse = nativeJSON.parse;
- }
-
- // Convenience aliases.
- var objectProto = Object.prototype,
- getClass = objectProto.toString,
- isProperty, forEach, undef;
-
- // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
- var isExtended = new Date(-3509827334573292);
- try {
- // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
- // results for certain dates in Opera >= 10.53.
- isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
- // Safari < 2.0.2 stores the internal millisecond time value correctly,
- // but clips the values returned by the date methods to the range of
- // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
- isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
- } catch (exception) {}
-
- // Internal: Determines whether the native `JSON.stringify` and `parse`
- // implementations are spec-compliant. Based on work by Ken Snyder.
- function has(name) {
- if (has[name] !== undef) {
- // Return cached feature test result.
- return has[name];
- }
- var isSupported;
- if (name == "bug-string-char-index") {
- // IE <= 7 doesn't support accessing string characters using square
- // bracket notation. IE 8 only supports this for primitives.
- isSupported = "a"[0] != "a";
- } else if (name == "json") {
- // Indicates whether both `JSON.stringify` and `JSON.parse` are
- // supported.
- isSupported = has("json-stringify") && has("json-parse");
- } else {
- var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
- // Test `JSON.stringify`.
- if (name == "json-stringify") {
- var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
- if (stringifySupported) {
- // A test function object with a custom `toJSON` method.
- (value = function () {
- return 1;
- }).toJSON = value;
- try {
- stringifySupported =
- // Firefox 3.1b1 and b2 serialize string, number, and boolean
- // primitives as object literals.
- stringify(0) === "0" &&
- // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
- // literals.
- stringify(new Number()) === "0" &&
- stringify(new String()) == '""' &&
- // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
- // does not define a canonical JSON representation (this applies to
- // objects with `toJSON` properties as well, *unless* they are nested
- // within an object or array).
- stringify(getClass) === undef &&
- // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
- // FF 3.1b3 pass this test.
- stringify(undef) === undef &&
- // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
- // respectively, if the value is omitted entirely.
- stringify() === undef &&
- // FF 3.1b1, 2 throw an error if the given value is not a number,
- // string, array, object, Boolean, or `null` literal. This applies to
- // objects with custom `toJSON` methods as well, unless they are nested
- // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
- // methods entirely.
- stringify(value) === "1" &&
- stringify([value]) == "[1]" &&
- // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
- // `"[null]"`.
- stringify([undef]) == "[null]" &&
- // YUI 3.0.0b1 fails to serialize `null` literals.
- stringify(null) == "null" &&
- // FF 3.1b1, 2 halts serialization if an array contains a function:
- // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
- // elides non-JSON values from objects and arrays, unless they
- // define custom `toJSON` methods.
- stringify([undef, getClass, null]) == "[null,null,null]" &&
- // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
- // where character escape codes are expected (e.g., `\b` => `\u0008`).
- stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
- // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
- stringify(null, value) === "1" &&
- stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
- // JSON 2, Prototype <= 1.7, and older SpiderwebKit builds incorrectly
- // serialize extended years.
- stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
- // The milliseconds are optional in ES 5, but required in 5.1.
- stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
- // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
- // four-digit years instead of six-digit years. Credits: @Yaffle.
- stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
- // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
- // values less than 1000. Credits: @Yaffle.
- stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
- } catch (exception) {
- stringifySupported = false;
- }
- }
- isSupported = stringifySupported;
- }
- // Test `JSON.parse`.
- if (name == "json-parse") {
- var parse = exports.parse;
- if (typeof parse == "function") {
- try {
- // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
- // Conforming implementations should also coerce the initial argument to
- // a string prior to parsing.
- if (parse("0") === 0 && !parse(false)) {
- // Simple parsing test.
- value = parse(serialized);
- var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
- if (parseSupported) {
- try {
- // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
- parseSupported = !parse('"\t"');
- } catch (exception) {}
- if (parseSupported) {
- try {
- // FF 4.0 and 4.0.1 allow leading `+` signs and leading
- // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
- // certain octal literals.
- parseSupported = parse("01") !== 1;
- } catch (exception) {}
- }
- if (parseSupported) {
- try {
- // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
- // points. These environments, along with FF 3.1b1 and 2,
- // also allow trailing commas in JSON objects and arrays.
- parseSupported = parse("1.") !== 1;
- } catch (exception) {}
- }
- }
- }
- } catch (exception) {
- parseSupported = false;
- }
- }
- isSupported = parseSupported;
- }
- }
- return has[name] = !!isSupported;
- }
-
- if (!has("json")) {
- // Common `[[Class]]` name aliases.
- var functionClass = "[object Function]",
- dateClass = "[object Date]",
- numberClass = "[object Number]",
- stringClass = "[object String]",
- arrayClass = "[object Array]",
- booleanClass = "[object Boolean]";
-
- // Detect incomplete support for accessing string characters by index.
- var charIndexBuggy = has("bug-string-char-index");
-
- // Define additional utility methods if the `Date` methods are buggy.
- if (!isExtended) {
- var floor = Math.floor;
- // A mapping between the months of the year and the number of days between
- // January 1st and the first of the respective month.
- var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
- // Internal: Calculates the number of days between the Unix epoch and the
- // first day of the given month.
- var getDay = function (year, month) {
- return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
- };
- }
-
- // Internal: Determines if a property is a direct property of the given
- // object. Delegates to the native `Object#hasOwnProperty` method.
- if (!(isProperty = objectProto.hasOwnProperty)) {
- isProperty = function (property) {
- var members = {}, constructor;
- if ((members.__proto__ = null, members.__proto__ = {
- // The *proto* property cannot be set multiple times in recent
- // versions of Firefox and SeaMonkey.
- "toString": 1
- }, members).toString != getClass) {
- // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
- // supports the mutable *proto* property.
- isProperty = function (property) {
- // Capture and break the object's prototype chain (see section 8.6.2
- // of the ES 5.1 spec). The parenthesized expression prevents an
- // unsafe transformation by the Closure Compiler.
- var original = this.__proto__, result = property in (this.__proto__ = null, this);
- // Restore the original prototype chain.
- this.__proto__ = original;
- return result;
- };
- } else {
- // Capture a reference to the top-level `Object` constructor.
- constructor = members.constructor;
- // Use the `constructor` property to simulate `Object#hasOwnProperty` in
- // other environments.
- isProperty = function (property) {
- var parent = (this.constructor || constructor).prototype;
- return property in this && !(property in parent && this[property] === parent[property]);
- };
- }
- members = null;
- return isProperty.call(this, property);
- };
- }
-
- // Internal: Normalizes the `for...in` iteration algorithm across
- // environments. Each enumerated key is yielded to a `callback` function.
- forEach = function (object, callback) {
- var size = 0, Properties, members, property;
-
- // Tests for bugs in the current environment's `for...in` algorithm. The
- // `valueOf` property inherits the non-enumerable flag from
- // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
- (Properties = function () {
- this.valueOf = 0;
- }).prototype.valueOf = 0;
-
- // Iterate over a new instance of the `Properties` class.
- members = new Properties();
- for (property in members) {
- // Ignore all properties inherited from `Object.prototype`.
- if (isProperty.call(members, property)) {
- size++;
- }
- }
- Properties = members = null;
-
- // Normalize the iteration algorithm.
- if (!size) {
- // A list of non-enumerable properties inherited from `Object.prototype`.
- members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
- // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
- // properties.
- forEach = function (object, callback) {
- var isFunction = getClass.call(object) == functionClass, property, length;
- var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
- for (property in object) {
- // Gecko <= 1.0 enumerates the `prototype` property of functions under
- // certain conditions; IE does not.
- if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
- callback(property);
- }
- }
- // Manually invoke the callback for each non-enumerable property.
- for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
- };
- } else if (size == 2) {
- // Safari <= 2.0.4 enumerates shadowed properties twice.
- forEach = function (object, callback) {
- // Create a set of iterated properties.
- var members = {}, isFunction = getClass.call(object) == functionClass, property;
- for (property in object) {
- // Store each property name to prevent double enumeration. The
- // `prototype` property of functions is not enumerated due to cross-
- // environment inconsistencies.
- if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
- callback(property);
- }
- }
- };
- } else {
- // No bugs detected; use the standard `for...in` algorithm.
- forEach = function (object, callback) {
- var isFunction = getClass.call(object) == functionClass, property, isConstructor;
- for (property in object) {
- if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
- callback(property);
- }
- }
- // Manually invoke the callback for the `constructor` property due to
- // cross-environment inconsistencies.
- if (isConstructor || isProperty.call(object, (property = "constructor"))) {
- callback(property);
- }
- };
- }
- return forEach(object, callback);
- };
-
- // Public: Serializes a JavaScript `value` as a JSON string. The optional
- // `filter` argument may specify either a function that alters how object and
- // array members are serialized, or an array of strings and numbers that
- // indicates which properties should be serialized. The optional `width`
- // argument may be either a string or number that specifies the indentation
- // level of the output.
- if (!has("json-stringify")) {
- // Internal: A map of control characters and their escaped equivalents.
- var Escapes = {
- 92: "\\\\",
- 34: '\\"',
- 8: "\\b",
- 12: "\\f",
- 10: "\\n",
- 13: "\\r",
- 9: "\\t"
- };
-
- // Internal: Converts `value` into a zero-padded string such that its
- // length is at least equal to `width`. The `width` must be <= 6.
- var leadingZeroes = "000000";
- var toPaddedString = function (width, value) {
- // The `|| 0` expression is necessary to work around a bug in
- // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
- return (leadingZeroes + (value || 0)).slice(-width);
- };
-
- // Internal: Double-quotes a string `value`, replacing all ASCII control
- // characters (characters with code unit values between 0 and 31) with
- // their escaped equivalents. This is an implementation of the
- // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
- var unicodePrefix = "\\u00";
- var quote = function (value) {
- var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
- var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
- for (; index < length; index++) {
- var charCode = value.charCodeAt(index);
- // If the character is a control character, append its Unicode or
- // shorthand escape sequence; otherwise, append the character as-is.
- switch (charCode) {
- case 8: case 9: case 10: case 12: case 13: case 34: case 92:
- result += Escapes[charCode];
- break;
- default:
- if (charCode < 32) {
- result += unicodePrefix + toPaddedString(2, charCode.toString(16));
- break;
- }
- result += useCharIndex ? symbols[index] : value.charAt(index);
- }
- }
- return result + '"';
- };
-
- // Internal: Recursively serializes an object. Implements the
- // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
- var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
- var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
- try {
- // Necessary for host object support.
- value = object[property];
- } catch (exception) {}
- if (typeof value == "object" && value) {
- className = getClass.call(value);
- if (className == dateClass && !isProperty.call(value, "toJSON")) {
- if (value > -1 / 0 && value < 1 / 0) {
- // Dates are serialized according to the `Date#toJSON` method
- // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
- // for the ISO 8601 date time string format.
- if (getDay) {
- // Manually compute the year, month, date, hours, minutes,
- // seconds, and milliseconds if the `getUTC*` methods are
- // buggy. Adapted from @Yaffle's `date-shim` project.
- date = floor(value / 864e5);
- for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
- for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
- date = 1 + date - getDay(year, month);
- // The `time` value specifies the time within the day (see ES
- // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
- // to compute `A modulo B`, as the `%` operator does not
- // correspond to the `modulo` operation for negative numbers.
- time = (value % 864e5 + 864e5) % 864e5;
- // The hours, minutes, seconds, and milliseconds are obtained by
- // decomposing the time within the day. See section 15.9.1.10.
- hours = floor(time / 36e5) % 24;
- minutes = floor(time / 6e4) % 60;
- seconds = floor(time / 1e3) % 60;
- milliseconds = time % 1e3;
- } else {
- year = value.getUTCFullYear();
- month = value.getUTCMonth();
- date = value.getUTCDate();
- hours = value.getUTCHours();
- minutes = value.getUTCMinutes();
- seconds = value.getUTCSeconds();
- milliseconds = value.getUTCMilliseconds();
- }
- // Serialize extended years correctly.
- value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
- "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
- // Months, dates, hours, minutes, and seconds should have two
- // digits; milliseconds should have three.
- "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
- // Milliseconds are optional in ES 5.0, but required in 5.1.
- "." + toPaddedString(3, milliseconds) + "Z";
- } else {
- value = null;
- }
- } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
- // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
- // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
- // ignores all `toJSON` methods on these objects unless they are
- // defined directly on an instance.
- value = value.toJSON(property);
- }
- }
- if (callback) {
- // If a replacement function was provided, call it to obtain the value
- // for serialization.
- value = callback.call(object, property, value);
- }
- if (value === null) {
- return "null";
- }
- className = getClass.call(value);
- if (className == booleanClass) {
- // Booleans are represented literally.
- return "" + value;
- } else if (className == numberClass) {
- // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
- // `"null"`.
- return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
- } else if (className == stringClass) {
- // Strings are double-quoted and escaped.
- return quote("" + value);
- }
- // Recursively serialize objects and arrays.
- if (typeof value == "object") {
- // Check for cyclic structures. This is a linear search; performance
- // is inversely proportional to the number of unique nested objects.
- for (length = stack.length; length--;) {
- if (stack[length] === value) {
- // Cyclic structures cannot be serialized by `JSON.stringify`.
- throw TypeError();
- }
- }
- // Add the object to the stack of traversed objects.
- stack.push(value);
- results = [];
- // Save the current indentation level and indent one additional level.
- prefix = indentation;
- indentation += whitespace;
- if (className == arrayClass) {
- // Recursively serialize array elements.
- for (index = 0, length = value.length; index < length; index++) {
- element = serialize(index, value, callback, properties, whitespace, indentation, stack);
- results.push(element === undef ? "null" : element);
- }
- result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
- } else {
- // Recursively serialize object members. Members are selected from
- // either a user-specified list of property names, or the object
- // itself.
- forEach(properties || value, function (property) {
- var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
- if (element !== undef) {
- // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
- // is not the empty string, let `member` {quote(property) + ":"}
- // be the concatenation of `member` and the `space` character."
- // The "`space` character" refers to the literal space
- // character, not the `space` {width} argument provided to
- // `JSON.stringify`.
- results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
- }
- });
- result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
- }
- // Remove the object from the traversed object stack.
- stack.pop();
- return result;
- }
- };
-
- // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
- exports.stringify = function (source, filter, width) {
- var whitespace, callback, properties, className;
- if (objectTypes[typeof filter] && filter) {
- if ((className = getClass.call(filter)) == functionClass) {
- callback = filter;
- } else if (className == arrayClass) {
- // Convert the property names array into a makeshift set.
- properties = {};
- for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
- }
- }
- if (width) {
- if ((className = getClass.call(width)) == numberClass) {
- // Convert the `width` to an integer and create a string containing
- // `width` number of space characters.
- if ((width -= width % 1) > 0) {
- for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
- }
- } else if (className == stringClass) {
- whitespace = width.length <= 10 ? width : width.slice(0, 10);
- }
- }
- // Opera <= 7.54u2 discards the values associated with empty string keys
- // (`""`) only if they are used directly within an object member list
- // (e.g., `!("" in { "": 1})`).
- return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
- };
- }
-
- // Public: Parses a JSON source string.
- if (!has("json-parse")) {
- var fromCharCode = String.fromCharCode;
-
- // Internal: A map of escaped control characters and their unescaped
- // equivalents.
- var Unescapes = {
- 92: "\\",
- 34: '"',
- 47: "/",
- 98: "\b",
- 116: "\t",
- 110: "\n",
- 102: "\f",
- 114: "\r"
- };
-
- // Internal: Stores the parser state.
- var Index, Source;
-
- // Internal: Resets the parser state and throws a `SyntaxError`.
- var abort = function () {
- Index = Source = null;
- throw SyntaxError();
- };
-
- // Internal: Returns the next token, or `"$"` if the parser has reached
- // the end of the source string. A token may be a string, number, `null`
- // literal, or Boolean literal.
- var lex = function () {
- var source = Source, length = source.length, value, begin, position, isSigned, charCode;
- while (Index < length) {
- charCode = source.charCodeAt(Index);
- switch (charCode) {
- case 9: case 10: case 13: case 32:
- // Skip whitespace tokens, including tabs, carriage returns, line
- // feeds, and space characters.
- Index++;
- break;
- case 123: case 125: case 91: case 93: case 58: case 44:
- // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
- // the current position.
- value = charIndexBuggy ? source.charAt(Index) : source[Index];
- Index++;
- return value;
- case 34:
- // `"` delimits a JSON string; advance to the next character and
- // begin parsing the string. String tokens are prefixed with the
- // sentinel `@` character to distinguish them from punctuators and
- // end-of-string tokens.
- for (value = "@", Index++; Index < length;) {
- charCode = source.charCodeAt(Index);
- if (charCode < 32) {
- // Unescaped ASCII control characters (those with a code unit
- // less than the space character) are not permitted.
- abort();
- } else if (charCode == 92) {
- // A reverse solidus (`\`) marks the beginning of an escaped
- // control character (including `"`, `\`, and `/`) or Unicode
- // escape sequence.
- charCode = source.charCodeAt(++Index);
- switch (charCode) {
- case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
- // Revive escaped control characters.
- value += Unescapes[charCode];
- Index++;
- break;
- case 117:
- // `\u` marks the beginning of a Unicode escape sequence.
- // Advance to the first character and validate the
- // four-digit code point.
- begin = ++Index;
- for (position = Index + 4; Index < position; Index++) {
- charCode = source.charCodeAt(Index);
- // A valid sequence comprises four hexdigits (case-
- // insensitive) that form a single hexadecimal value.
- if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
- // Invalid Unicode escape sequence.
- abort();
- }
- }
- // Revive the escaped character.
- value += fromCharCode("0x" + source.slice(begin, Index));
- break;
- default:
- // Invalid escape sequence.
- abort();
- }
- } else {
- if (charCode == 34) {
- // An unescaped double-quote character marks the end of the
- // string.
- break;
- }
- charCode = source.charCodeAt(Index);
- begin = Index;
- // Optimize for the common case where a string is valid.
- while (charCode >= 32 && charCode != 92 && charCode != 34) {
- charCode = source.charCodeAt(++Index);
- }
- // Append the string as-is.
- value += source.slice(begin, Index);
- }
- }
- if (source.charCodeAt(Index) == 34) {
- // Advance to the next character and return the revived string.
- Index++;
- return value;
- }
- // Unterminated string.
- abort();
- default:
- // Parse numbers and literals.
- begin = Index;
- // Advance past the negative sign, if one is specified.
- if (charCode == 45) {
- isSigned = true;
- charCode = source.charCodeAt(++Index);
- }
- // Parse an integer or floating-point value.
- if (charCode >= 48 && charCode <= 57) {
- // Leading zeroes are interpreted as octal literals.
- if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
- // Illegal octal literal.
- abort();
- }
- isSigned = false;
- // Parse the integer component.
- for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
- // Floats cannot contain a leading decimal point; however, this
- // case is already accounted for by the parser.
- if (source.charCodeAt(Index) == 46) {
- position = ++Index;
- // Parse the decimal component.
- for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
- if (position == Index) {
- // Illegal trailing decimal.
- abort();
- }
- Index = position;
- }
- // Parse exponents. The `e` denoting the exponent is
- // case-insensitive.
- charCode = source.charCodeAt(Index);
- if (charCode == 101 || charCode == 69) {
- charCode = source.charCodeAt(++Index);
- // Skip past the sign following the exponent, if one is
- // specified.
- if (charCode == 43 || charCode == 45) {
- Index++;
- }
- // Parse the exponential component.
- for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
- if (position == Index) {
- // Illegal empty exponent.
- abort();
- }
- Index = position;
- }
- // Coerce the parsed value to a JavaScript number.
- return +source.slice(begin, Index);
- }
- // A negative sign may only precede numbers.
- if (isSigned) {
- abort();
- }
- // `true`, `false`, and `null` literals.
- if (source.slice(Index, Index + 4) == "true") {
- Index += 4;
- return true;
- } else if (source.slice(Index, Index + 5) == "false") {
- Index += 5;
- return false;
- } else if (source.slice(Index, Index + 4) == "null") {
- Index += 4;
- return null;
- }
- // Unrecognized token.
- abort();
- }
- }
- // Return the sentinel `$` character if the parser has reached the end
- // of the source string.
- return "$";
- };
-
- // Internal: Parses a JSON `value` token.
- var get = function (value) {
- var results, hasMembers;
- if (value == "$") {
- // Unexpected end of input.
- abort();
- }
- if (typeof value == "string") {
- if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
- // Remove the sentinel `@` character.
- return value.slice(1);
- }
- // Parse object and array literals.
- if (value == "[") {
- // Parses a JSON array, returning a new JavaScript array.
- results = [];
- for (;; hasMembers || (hasMembers = true)) {
- value = lex();
- // A closing square bracket marks the end of the array literal.
- if (value == "]") {
- break;
- }
- // If the array literal contains elements, the current token
- // should be a comma separating the previous element from the
- // next.
- if (hasMembers) {
- if (value == ",") {
- value = lex();
- if (value == "]") {
- // Unexpected trailing `,` in array literal.
- abort();
- }
- } else {
- // A `,` must separate each array element.
- abort();
- }
- }
- // Elisions and leading commas are not permitted.
- if (value == ",") {
- abort();
- }
- results.push(get(value));
- }
- return results;
- } else if (value == "{") {
- // Parses a JSON object, returning a new JavaScript object.
- results = {};
- for (;; hasMembers || (hasMembers = true)) {
- value = lex();
- // A closing curly brace marks the end of the object literal.
- if (value == "}") {
- break;
- }
- // If the object literal contains members, the current token
- // should be a comma separator.
- if (hasMembers) {
- if (value == ",") {
- value = lex();
- if (value == "}") {
- // Unexpected trailing `,` in object literal.
- abort();
- }
- } else {
- // A `,` must separate each object member.
- abort();
- }
- }
- // Leading commas are not permitted, object property names must be
- // double-quoted strings, and a `:` must separate each property
- // name and value.
- if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
- abort();
- }
- results[value.slice(1)] = get(lex());
- }
- return results;
- }
- // Unexpected token encountered.
- abort();
- }
- return value;
- };
-
- // Internal: Updates a traversed object member.
- var update = function (source, property, callback) {
- var element = walk(source, property, callback);
- if (element === undef) {
- delete source[property];
- } else {
- source[property] = element;
- }
- };
-
- // Internal: Recursively traverses a parsed JSON object, invoking the
- // `callback` function for each value. This is an implementation of the
- // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
- var walk = function (source, property, callback) {
- var value = source[property], length;
- if (typeof value == "object" && value) {
- // `forEach` can't be used to traverse an array in Opera <= 8.54
- // because its `Object#hasOwnProperty` implementation returns `false`
- // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
- if (getClass.call(value) == arrayClass) {
- for (length = value.length; length--;) {
- update(value, length, callback);
- }
- } else {
- forEach(value, function (property) {
- update(value, property, callback);
- });
- }
- }
- return callback.call(source, property, value);
- };
-
- // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
- exports.parse = function (source, callback) {
- var result, value;
- Index = 0;
- Source = "" + source;
- result = get(lex());
- // If a JSON string contains multiple tokens, it is invalid.
- if (lex() != "$") {
- abort();
- }
- // Reset the parser state.
- Index = Source = null;
- return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
- };
- }
- }
-
- exports["runInContext"] = runInContext;
- return exports;
- }
-
- if (freeExports && !isLoader) {
- // Export for CommonJS environments.
- runInContext(root, freeExports);
- } else {
- // Export for spiderweb browsers and JavaScript engines.
- var nativeJSON = root.JSON,
- previousJSON = root["JSON3"],
- isRestored = false;
-
- var JSON3 = runInContext(root, (root["JSON3"] = {
- // Public: Restores the original value of the global `JSON` object and
- // returns a reference to the `JSON3` object.
- "noConflict": function () {
- if (!isRestored) {
- isRestored = true;
- root.JSON = nativeJSON;
- root["JSON3"] = previousJSON;
- nativeJSON = previousJSON = null;
- }
- return JSON3;
- }
- }));
-
- root.JSON = {
- "parse": JSON3.parse,
- "stringify": JSON3.stringify
- };
- }
-
- // Export for asynchronous module loaders.
- if (isLoader) {
- define(function () {
- return JSON3;
- });
- }
- }).call(this);
- /************************************************************
- * end JSON
- ************************************************************/
-
- JSON2 = exports;
-
- })();
-}
-
-/* startjslint */
-/*jslint browser:true, plusplus:true, vars:true, nomen:true, evil:true, regexp: false, bitwise: true, white: true */
-/*global JSON2 */
-/*global window */
-/*global unescape */
-/*global ActiveXObject */
-/*members encodeURIComponent, decodeURIComponent, getElementsByTagName,
- shift, unshift, piwikAsyncInit,
- createElement, appendChild, characterSet, charset, all,
- addEventListener, attachEvent, removeEventListener, detachEvent, disableCookies,
- cookie, domain, readyState, documentElement, doScroll, title, text,
- location, top, onerror, document, referrer, parent, links, href, protocol, name, GearsFactory,
- performance, mozPerformance, msPerformance, spiderwebkitPerformance, timing, requestStart,
- responseEnd, event, which, button, srcElement, type, target,
- parentNode, tagName, hostname, className,
- userAgent, cookieEnabled, platform, mimeTypes, enabledPlugin, javaEnabled,
- XMLHttpRequest, ActiveXObject, open, setRequestHeader, onreadystatechange, send, readyState, status,
- getTime, getTimeAlias, setTime, toGMTString, getHours, getMinutes, getSeconds,
- toLowerCase, toUpperCase, charAt, indexOf, lastIndexOf, split, slice,
- onload, src,
- min, round, random,
- exec,
- res, width, height, devicePixelRatio,
- pdf, qt, realp, wma, dir, fla, java, gears, ag,
- hook, getHook, getVisitorId, getVisitorInfo, setUserId, getUserId, setSiteId, getSiteId, setTrackerUrl, getTrackerUrl, appendToTrackingUrl, getRequest, addPlugin,
- getAttributionInfo, getAttributionCampaignName, getAttributionCampaignKeyword,
- getAttributionReferrerTimestamp, getAttributionReferrerUrl,
- setCustomData, getCustomData,
- setCustomRequestProcessing,
- setCustomVariable, getCustomVariable, deleteCustomVariable, storeCustomVariablesInCookie, setCustomDimension, getCustomDimension,
- deleteCustomDimension, setDownloadExtensions, addDownloadExtensions, removeDownloadExtensions,
- setDomains, setIgnoreClasses, setRequestMethod, setRequestContentType,
- setReferrerUrl, setCustomUrl, setAPIUrl, setDocumentTitle,
- setDownloadClasses, setLinkClasses,
- setCampaignNameKey, setCampaignKeywordKey,
- discardHashTag,
- setCookieNamePrefix, setCookieDomain, setCookiePath, setVisitorIdCookie,
- setVisitorCookieTimeout, setSessionCookieTimeout, setReferralCookieTimeout,
- setConversionAttributionFirstReferrer,
- disablePerformanceTracking, setGenerationTimeMs,
- doNotTrack, setDoNotTrack, msDoNotTrack, getValuesFromVisitorIdCookie,
- addListener, enableLinkTracking, enableJSErrorTracking, setLinkTrackingTimer,
- enableHeartBeatTimer, disableHeartBeatTimer, killFrame, redirectFile, setCountPreRendered,
- trackGoal, trackLink, trackPageView, trackSiteSearch, trackEvent,
- setEcommerceView, addEcommerceItem, trackEcommerceOrder, trackEcommerceCartUpdate,
- deleteCookie, deleteCookies, offsetTop, offsetLeft, offsetHeight, offsetWidth, nodeType, defaultView,
- innerHTML, scrollLeft, scrollTop, currentStyle, getComputedStyle, querySelectorAll, splice,
- getAttribute, hasAttribute, attributes, nodeName, findContentNodes, findContentNodes, findContentNodesWithinNode,
- findPieceNode, findTargetNodeNoDefault, findTargetNode, findContentPiece, children, hasNodeCssClass,
- getAttributeValueFromNode, hasNodeAttributeWithValue, hasNodeAttribute, findNodesByTagName, findMultiple,
- makeNodesUnique, concat, find, htmlCollectionToArray, offsetParent, value, nodeValue, findNodesHavingAttribute,
- findFirstNodeHavingAttribute, findFirstNodeHavingAttributeWithValue, getElementsByClassName,
- findNodesHavingCssClass, findFirstNodeHavingClass, isLinkElement, findParentContentNode, removeDomainIfIsInLink,
- findContentName, findMediaUrlInNode, toAbsoluteUrl, findContentTarget, getLocation, origin, host, isSameDomain,
- search, trim, getBoundingClientRect, bottom, right, left, innerWidth, innerHeight, clientWidth, clientHeight,
- isOrWasNodeInViewport, isNodeVisible, buildInteractionRequestParams, buildImpressionRequestParams,
- shouldIgnoreInteraction, setHrefAttribute, setAttribute, buildContentBlock, collectContent, setLocation,
- CONTENT_ATTR, CONTENT_CLASS, CONTENT_NAME_ATTR, CONTENT_PIECE_ATTR, CONTENT_PIECE_CLASS,
- CONTENT_TARGET_ATTR, CONTENT_TARGET_CLASS, CONTENT_IGNOREINTERACTION_ATTR, CONTENT_IGNOREINTERACTION_CLASS,
- trackCallbackOnLoad, trackCallbackOnReady, buildContentImpressionsRequests, wasContentImpressionAlreadyTracked,
- getQuery, getContent, getContentImpressionsRequestsFromNodes, buildContentInteractionTrackingRedirectUrl,
- buildContentInteractionRequestNode, buildContentInteractionRequest, buildContentImpressionRequest,
- appendContentInteractionToRequestIfPossible, setupInteractionsTracking, trackContentImpressionClickInteraction,
- internalIsNodeVisible, clearTrackedContentImpressions, getTrackerUrl, trackAllContentImpressions,
- getTrackedContentImpressions, getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet,
- contentInteractionTrackingSetupDone, contains, match, pathname, piece, trackContentInteractionNode,
- trackContentInteractionNode, trackContentImpressionsWithinNode, trackContentImpression,
- enableTrackOnlyVisibleContent, trackContentInteraction, clearEnableTrackOnlyVisibleContent, logAllContentBlocksOnPage,
- trackVisibleContentImpressions, isTrackOnlyVisibleContentEnabled, port, isUrlToCurrentDomain,
- isNodeAuthorizedToTriggerInteraction, replaceHrefIfInternalLink, getConfigDownloadExtensions, disableLinkTracking,
- substr, setAnyAttribute, wasContentTargetAttrReplaced, max, abs, childNodes, compareDocumentPosition, body,
- getConfigVisitorCookieTimeout, getRemainingVisitorCookieTimeout, getDomains, getConfigCookiePath,
- newVisitor, uuid, createTs, visitCount, currentVisitTs, lastVisitTs, lastEcommerceOrderTs,
- "", "\b", "\t", "\n", "\f", "\r", "\"", "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
- getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace,
- sort, slice, stringify, test, toJSON, toString, valueOf, objectToJSON
- */
-/*global _paq:true */
-/*members push */
-/*global Piwik:true */
-/*members addPlugin, getTracker, getAsyncTracker */
-/*global Piwik_Overlay_Client */
-/*global AnalyticsTracker:true */
-/*members initialize */
-/*global define */
-/*members amd */
-/*global console:true */
-/*members error */
-/*members log */
-
-// asynchronous tracker (or proxy)
-if (typeof _paq !== 'object') {
- _paq = [];
-}
-
-// Piwik singleton and namespace
-if (typeof Piwik !== 'object') {
- Piwik = (function () {
- 'use strict';
-
- /************************************************************
- * Private data
- ************************************************************/
-
- var expireDateTime,
-
- /* plugins */
- plugins = {},
-
- /* alias frequently used globals for added minification */
- documentAlias = document,
- navigatorAlias = navigator,
- screenAlias = screen,
- windowAlias = window,
-
- /* performance timing */
- performanceAlias = windowAlias.performance || windowAlias.mozPerformance || windowAlias.msPerformance || windowAlias.spiderwebkitPerformance,
-
- /* DOM Ready */
- hasLoaded = false,
- registeredOnLoadHandlers = [],
-
- /* encode */
- encodeWrapper = windowAlias.encodeURIComponent,
-
- /* decode */
- decodeWrapper = windowAlias.decodeURIComponent,
-
- /* urldecode */
- urldecode = unescape,
-
- /* asynchronous tracker */
- asyncTracker,
-
- /* iterator */
- iterator,
-
- /* local Piwik */
- Piwik;
-
- /************************************************************
- * Private methods
- ************************************************************/
-
- /**
- * See https://github.com/piwik/piwik/issues/8413
- * To prevent Javascript Error: Uncaught URIError: URI malformed when encoding is not UTF-8. Use this method
- * instead of decodeWrapper if a text could contain any non UTF-8 encoded characters eg
- * a URL like http://apache.piwik/test.html?%F6%E4%FC or a link like
- * (encoded iso-8859-1 URL)
- */
- function safeDecodeWrapper(url)
- {
- try {
- return decodeWrapper(url);
- } catch (e) {
- return unescape(url);
- }
- }
-
- /*
- * Is property defined?
- */
- function isDefined(property) {
- // workaround https://github.com/douglascrockford/JSLint/commit/24f63ada2f9d7ad65afc90e6d949f631935c2480
- var propertyType = typeof property;
-
- return propertyType !== 'undefined';
- }
-
- /*
- * Is property a function?
- */
- function isFunction(property) {
- return typeof property === 'function';
- }
-
- /*
- * Is property an object?
- *
- * @return bool Returns true if property is null, an Object, or subclass of Object (i.e., an instanceof String, Date, etc.)
- */
- function isObject(property) {
- return typeof property === 'object';
- }
-
- /*
- * Is property a string?
- */
- function isString(property) {
- return typeof property === 'string' || property instanceof String;
- }
-
- function isObjectEmpty(property)
- {
- if (!property) {
- return true;
- }
-
- var i;
- var isEmpty = true;
- for (i in property) {
- if (Object.prototype.hasOwnProperty.call(property, i)) {
- isEmpty = false;
- }
- }
-
- return isEmpty;
- }
-
- /*
- * apply wrapper
- *
- * @param array parameterArray An array comprising either:
- * [ 'methodName', optional_parameters ]
- * or:
- * [ functionObject, optional_parameters ]
- */
- function apply() {
- var i, f, parameterArray;
-
- for (i = 0; i < arguments.length; i += 1) {
- parameterArray = arguments[i];
- f = parameterArray.shift();
-
- if (isString(f)) {
- asyncTracker[f].apply(asyncTracker, parameterArray);
- } else {
- f.apply(asyncTracker, parameterArray);
- }
- }
- }
-
- /*
- * Cross-browser helper function to add event handler
- */
- function addEventListener(element, eventType, eventHandler, useCapture) {
- if (element.addEventListener) {
- element.addEventListener(eventType, eventHandler, useCapture);
-
- return true;
- }
-
- if (element.attachEvent) {
- return element.attachEvent('on' + eventType, eventHandler);
- }
-
- element['on' + eventType] = eventHandler;
- }
-
- /*
- * Call plugin hook methods
- */
- function executePluginMethod(methodName, callback) {
- var result = '',
- i,
- pluginMethod;
-
- for (i in plugins) {
- if (Object.prototype.hasOwnProperty.call(plugins, i)) {
- pluginMethod = plugins[i][methodName];
-
- if (isFunction(pluginMethod)) {
- result += pluginMethod(callback);
- }
- }
- }
-
- return result;
- }
-
- /*
- * Handle beforeunload event
- *
- * Subject to Safari's "Runaway JavaScript Timer" and
- * Chrome V8 extension that terminates JS that exhibits
- * "slow unload", i.e., calling getTime() > 1000 times
- */
- function beforeUnloadHandler() {
- var now;
-
- executePluginMethod('unload');
-
- /*
- * Delay/pause (blocks UI)
- */
- if (expireDateTime) {
- // the things we do for backwards compatibility...
- // in ECMA-262 5th ed., we could simply use:
- // while (Date.now() < expireDateTime) { }
- do {
- now = new Date();
- } while (now.getTimeAlias() < expireDateTime);
- }
- }
-
- /*
- * Handler for onload event
- */
- function loadHandler() {
- var i;
-
- if (!hasLoaded) {
- hasLoaded = true;
- executePluginMethod('load');
- for (i = 0; i < registeredOnLoadHandlers.length; i++) {
- registeredOnLoadHandlers[i]();
- }
- }
-
- return true;
- }
-
- /*
- * Add onload or DOM ready handler
- */
- function addReadyListener() {
- var _timer;
-
- if (documentAlias.addEventListener) {
- addEventListener(documentAlias, 'DOMContentLoaded', function ready() {
- documentAlias.removeEventListener('DOMContentLoaded', ready, false);
- loadHandler();
- });
- } else if (documentAlias.attachEvent) {
- documentAlias.attachEvent('onreadystatechange', function ready() {
- if (documentAlias.readyState === 'complete') {
- documentAlias.detachEvent('onreadystatechange', ready);
- loadHandler();
- }
- });
-
- if (documentAlias.documentElement.doScroll && windowAlias === windowAlias.top) {
- (function ready() {
- if (!hasLoaded) {
- try {
- documentAlias.documentElement.doScroll('left');
- } catch (error) {
- setTimeout(ready, 0);
-
- return;
- }
- loadHandler();
- }
- }());
- }
- }
-
- // sniff for older SpiderwebKit versions
- if ((new RegExp('SpiderwebKit')).test(navigatorAlias.userAgent)) {
- _timer = setInterval(function () {
- if (hasLoaded || /loaded|complete/.test(documentAlias.readyState)) {
- clearInterval(_timer);
- loadHandler();
- }
- }, 10);
- }
-
- // fallback
- addEventListener(windowAlias, 'load', loadHandler, false);
- }
-
- /*
- * Load JavaScript file (asynchronously)
- */
- function loadScript(src, onLoad) {
- var script = documentAlias.createElement('script');
-
- script.type = 'text/javascript';
- script.src = src;
-
- if (script.readyState) {
- script.onreadystatechange = function () {
- var state = this.readyState;
-
- if (state === 'loaded' || state === 'complete') {
- script.onreadystatechange = null;
- onLoad();
- }
- };
- } else {
- script.onload = onLoad;
- }
-
- documentAlias.getElementsByTagName('head')[0].appendChild(script);
- }
-
- /*
- * Get page referrer
- */
- function getReferrer() {
- var referrer = '';
-
- try {
- referrer = windowAlias.top.document.referrer;
- } catch (e) {
- if (windowAlias.parent) {
- try {
- referrer = windowAlias.parent.document.referrer;
- } catch (e2) {
- referrer = '';
- }
- }
- }
-
- if (referrer === '') {
- referrer = documentAlias.referrer;
- }
-
- return referrer;
- }
-
- /*
- * Extract scheme/protocol from URL
- */
- function getProtocolScheme(url) {
- var e = new RegExp('^([a-z]+):'),
- matches = e.exec(url);
-
- return matches ? matches[1] : null;
- }
-
- /*
- * Extract hostname from URL
- */
- function getHostName(url) {
- // scheme : // [username [: password] @] hostame [: port] [/ [path] [? query] [# fragment]]
- var e = new RegExp('^(?:(?:https?|ftp):)/*(?:[^@]+@)?([^:/#]+)'),
- matches = e.exec(url);
-
- return matches ? matches[1] : url;
- }
-
- /*
- * Extract parameter from URL
- */
- function getParameter(url, name) {
- var regexSearch = "[\\?]" + name + "=([^]*)";
- var regex = new RegExp(regexSearch);
- var results = regex.exec(url);
- return results ? decodeWrapper(results[1]) : '';
- }
-
- /*
- * UTF-8 encoding
- */
- function utf8_encode(argString) {
- return unescape(encodeWrapper(argString));
- }
-
- /************************************************************
- * sha1
- * - based on sha1 from http://phpjs.org/functions/sha1:512 (MIT / GPL v2)
- ************************************************************/
-
- function sha1(str) {
- // + original by: Spiderwebtoolkit.info (http://www.spiderwebtoolkit.info/)
- // + namespaced by: Michael White (http://getsprink.com)
- // + input by: Brett Zamir (http://brett-zamir.me)
- // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + jslinted by: Anthon Pang (http://piwik.org)
-
- var
- rotate_left = function (n, s) {
- return (n << s) | (n >>> (32 - s));
- },
-
- cvt_hex = function (val) {
- var strout = '',
- i,
- v;
-
- for (i = 7; i >= 0; i--) {
- v = (val >>> (i * 4)) & 0x0f;
- strout += v.toString(16);
- }
-
- return strout;
- },
-
- blockstart,
- i,
- j,
- W = [],
- H0 = 0x67452301,
- H1 = 0xEFCDAB89,
- H2 = 0x98BADCFE,
- H3 = 0x10325476,
- H4 = 0xC3D2E1F0,
- A,
- B,
- C,
- D,
- E,
- temp,
- str_len,
- word_array = [];
-
- str = utf8_encode(str);
- str_len = str.length;
-
- for (i = 0; i < str_len - 3; i += 4) {
- j = str.charCodeAt(i) << 24 | str.charCodeAt(i + 1) << 16 |
- str.charCodeAt(i + 2) << 8 | str.charCodeAt(i + 3);
- word_array.push(j);
- }
-
- switch (str_len & 3) {
- case 0:
- i = 0x080000000;
- break;
- case 1:
- i = str.charCodeAt(str_len - 1) << 24 | 0x0800000;
- break;
- case 2:
- i = str.charCodeAt(str_len - 2) << 24 | str.charCodeAt(str_len - 1) << 16 | 0x08000;
- break;
- case 3:
- i = str.charCodeAt(str_len - 3) << 24 | str.charCodeAt(str_len - 2) << 16 | str.charCodeAt(str_len - 1) << 8 | 0x80;
- break;
- }
-
- word_array.push(i);
-
- while ((word_array.length & 15) !== 14) {
- word_array.push(0);
- }
-
- word_array.push(str_len >>> 29);
- word_array.push((str_len << 3) & 0x0ffffffff);
-
- for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {
- for (i = 0; i < 16; i++) {
- W[i] = word_array[blockstart + i];
- }
-
- for (i = 16; i <= 79; i++) {
- W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
- }
-
- A = H0;
- B = H1;
- C = H2;
- D = H3;
- E = H4;
-
- for (i = 0; i <= 19; i++) {
- temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
- E = D;
- D = C;
- C = rotate_left(B, 30);
- B = A;
- A = temp;
- }
-
- for (i = 20; i <= 39; i++) {
- temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
- E = D;
- D = C;
- C = rotate_left(B, 30);
- B = A;
- A = temp;
- }
-
- for (i = 40; i <= 59; i++) {
- temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
- E = D;
- D = C;
- C = rotate_left(B, 30);
- B = A;
- A = temp;
- }
-
- for (i = 60; i <= 79; i++) {
- temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
- E = D;
- D = C;
- C = rotate_left(B, 30);
- B = A;
- A = temp;
- }
-
- H0 = (H0 + A) & 0x0ffffffff;
- H1 = (H1 + B) & 0x0ffffffff;
- H2 = (H2 + C) & 0x0ffffffff;
- H3 = (H3 + D) & 0x0ffffffff;
- H4 = (H4 + E) & 0x0ffffffff;
- }
-
- temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
-
- return temp.toLowerCase();
- }
-
- /************************************************************
- * end sha1
- ************************************************************/
-
- /*
- * Fix-up URL when page rendered from search engine cache or translated page
- */
- function urlFixup(hostName, href, referrer) {
- if (!hostName) {
- hostName = '';
- }
-
- if (!href) {
- href = '';
- }
-
- if (hostName === 'translate.googleusercontent.com') { // Google
- if (referrer === '') {
- referrer = href;
- }
-
- href = getParameter(href, 'u');
- hostName = getHostName(href);
- } else if (hostName === 'cc.bingj.com' || // Bing
- hostName === 'spiderwebcache.googleusercontent.com' || // Google
- hostName.slice(0, 5) === '74.6.') { // Yahoo (via Inktomi 74.6.0.0/16)
- href = documentAlias.links[0].href;
- hostName = getHostName(href);
- }
-
- return [hostName, href, referrer];
- }
-
- /*
- * Fix-up domain
- */
- function domainFixup(domain) {
- var dl = domain.length;
-
- // remove trailing '.'
- if (domain.charAt(--dl) === '.') {
- domain = domain.slice(0, dl);
- }
-
- // remove leading '*'
- if (domain.slice(0, 2) === '*.') {
- domain = domain.slice(1);
- }
-
- if (domain.indexOf('/') !== -1) {
- domain = domain.substr(0, domain.indexOf('/'));
- }
-
- return domain;
- }
-
- /*
- * Title fixup
- */
- function titleFixup(title) {
- title = title && title.text ? title.text : title;
-
- if (!isString(title)) {
- var tmp = documentAlias.getElementsByTagName('title');
-
- if (tmp && isDefined(tmp[0])) {
- title = tmp[0].text;
- }
- }
-
- return title;
- }
-
- function getChildrenFromNode(node)
- {
- if (!node) {
- return [];
- }
-
- if (!isDefined(node.children) && isDefined(node.childNodes)) {
- return node.children;
- }
-
- if (isDefined(node.children)) {
- return node.children;
- }
-
- return [];
- }
-
- function containsNodeElement(node, containedNode)
- {
- if (!node || !containedNode) {
- return false;
- }
-
- if (node.contains) {
- return node.contains(containedNode);
- }
-
- if (node === containedNode) {
- return true;
- }
-
- if (node.compareDocumentPosition) {
- return !!(node.compareDocumentPosition(containedNode) & 16);
- }
-
- return false;
- }
-
- // Polyfill for IndexOf for IE6-IE8
- function indexOfArray(theArray, searchElement)
- {
- if (theArray && theArray.indexOf) {
- return theArray.indexOf(searchElement);
- }
-
- // 1. Let O be the result of calling ToObject passing
- // the this value as the argument.
- if (!isDefined(theArray) || theArray === null) {
- return -1;
- }
-
- if (!theArray.length) {
- return -1;
- }
-
- var len = theArray.length;
-
- if (len === 0) {
- return -1;
- }
-
- var k = 0;
-
- // 9. Repeat, while k < len
- while (k < len) {
- // a. Let Pk be ToString(k).
- // This is implicit for LHS operands of the in operator
- // b. Let kPresent be the result of calling the
- // HasProperty internal method of O with argument Pk.
- // This step can be combined with c
- // c. If kPresent is true, then
- // i. Let elementK be the result of calling the Get
- // internal method of O with the argument ToString(k).
- // ii. Let same be the result of applying the
- // Strict Equality Comparison Algorithm to
- // searchElement and elementK.
- // iii. If same is true, return k.
- if (theArray[k] === searchElement) {
- return k;
- }
- k++;
- }
- return -1;
- }
-
- /************************************************************
- * Element Visiblility
- ************************************************************/
-
- /**
- * Author: Jason Farrell
- * Author URI: http://useallfive.com/
- *
- * Description: Checks if a DOM element is truly visible.
- * Package URL: https://github.com/UseAllFive/true-visibility
- * License: MIT (https://github.com/UseAllFive/true-visibility/blob/master/LICENSE.txt)
- */
- function isVisible(node) {
-
- if (!node) {
- return false;
- }
-
- //-- Cross browser method to get style properties:
- function _getStyle(el, property) {
- if (windowAlias.getComputedStyle) {
- return documentAlias.defaultView.getComputedStyle(el,null)[property];
- }
- if (el.currentStyle) {
- return el.currentStyle[property];
- }
- }
-
- function _elementInDocument(element) {
- element = element.parentNode;
-
- while (element) {
- if (element === documentAlias) {
- return true;
- }
- element = element.parentNode;
- }
- return false;
- }
-
- /**
- * Checks if a DOM element is visible. Takes into
- * consideration its parents and overflow.
- *
- * @param (el) the DOM element to check if is visible
- *
- * These params are optional that are sent in recursively,
- * you typically won't use these:
- *
- * @param (t) Top corner position number
- * @param (r) Right corner position number
- * @param (b) Bottom corner position number
- * @param (l) Left corner position number
- * @param (w) Element width number
- * @param (h) Element height number
- */
- function _isVisible(el, t, r, b, l, w, h) {
- var p = el.parentNode,
- VISIBLE_PADDING = 1; // has to be visible at least one px of the element
-
- if (!_elementInDocument(el)) {
- return false;
- }
-
- //-- Return true for document node
- if (9 === p.nodeType) {
- return true;
- }
-
- //-- Return false if our element is invisible
- if (
- '0' === _getStyle(el, 'opacity') ||
- 'none' === _getStyle(el, 'display') ||
- 'hidden' === _getStyle(el, 'visibility')
- ) {
- return false;
- }
-
- if (!isDefined(t) ||
- !isDefined(r) ||
- !isDefined(b) ||
- !isDefined(l) ||
- !isDefined(w) ||
- !isDefined(h)) {
- t = el.offsetTop;
- l = el.offsetLeft;
- b = t + el.offsetHeight;
- r = l + el.offsetWidth;
- w = el.offsetWidth;
- h = el.offsetHeight;
- }
-
- if (node === el && (0 === h || 0 === w) && 'hidden' === _getStyle(el, 'overflow')) {
- return false;
- }
-
- //-- If we have a parent, let's continue:
- if (p) {
- //-- Check if the parent can hide its children.
- if (('hidden' === _getStyle(p, 'overflow') || 'scroll' === _getStyle(p, 'overflow'))) {
- //-- Only check if the offset is different for the parent
- if (
- //-- If the target element is to the right of the parent elm
- l + VISIBLE_PADDING > p.offsetWidth + p.scrollLeft ||
- //-- If the target element is to the left of the parent elm
- l + w - VISIBLE_PADDING < p.scrollLeft ||
- //-- If the target element is under the parent elm
- t + VISIBLE_PADDING > p.offsetHeight + p.scrollTop ||
- //-- If the target element is above the parent elm
- t + h - VISIBLE_PADDING < p.scrollTop
- ) {
- //-- Our target element is out of bounds:
- return false;
- }
- }
- //-- Add the offset parent's left/top coords to our element's offset:
- if (el.offsetParent === p) {
- l += p.offsetLeft;
- t += p.offsetTop;
- }
- //-- Let's recursively check upwards:
- return _isVisible(p, t, r, b, l, w, h);
- }
- return true;
- }
-
- return _isVisible(node);
- }
-
- /************************************************************
- * Query
- ************************************************************/
-
- var query = {
- htmlCollectionToArray: function (foundNodes)
- {
- var nodes = [], index;
-
- if (!foundNodes || !foundNodes.length) {
- return nodes;
- }
-
- for (index = 0; index < foundNodes.length; index++) {
- nodes.push(foundNodes[index]);
- }
-
- return nodes;
- },
- find: function (selector)
- {
- // we use querySelectorAll only on document, not on nodes because of its unexpected behavior. See for
- // instance http://stackoverflow.com/questions/11503534/jquery-vs-document-queryselectorall and
- // http://jsfiddle.net/QdMc5/ and http://ejohn.org/blog/thoughts-on-queryselectorall
- if (!document.querySelectorAll || !selector) {
- return []; // we do not support all browsers
- }
-
- var foundNodes = document.querySelectorAll(selector);
-
- return this.htmlCollectionToArray(foundNodes);
- },
- findMultiple: function (selectors)
- {
- if (!selectors || !selectors.length) {
- return [];
- }
-
- var index, foundNodes;
- var nodes = [];
- for (index = 0; index < selectors.length; index++) {
- foundNodes = this.find(selectors[index]);
- nodes = nodes.concat(foundNodes);
- }
-
- nodes = this.makeNodesUnique(nodes);
-
- return nodes;
- },
- findNodesByTagName: function (node, tagName)
- {
- if (!node || !tagName || !node.getElementsByTagName) {
- return [];
- }
-
- var foundNodes = node.getElementsByTagName(tagName);
-
- return this.htmlCollectionToArray(foundNodes);
- },
- makeNodesUnique: function (nodes)
- {
- var copy = [].concat(nodes);
- nodes.sort(function(n1, n2){
- if (n1 === n2) {
- return 0;
- }
-
- var index1 = indexOfArray(copy, n1);
- var index2 = indexOfArray(copy, n2);
-
- if (index1 === index2) {
- return 0;
- }
-
- return index1 > index2 ? -1 : 1;
- });
-
- if (nodes.length <= 1) {
- return nodes;
- }
-
- var index = 0;
- var numDuplicates = 0;
- var duplicates = [];
- var node;
-
- node = nodes[index++];
-
- while (node) {
- if (node === nodes[index]) {
- numDuplicates = duplicates.push(index);
- }
-
- node = nodes[index++] || null;
- }
-
- while (numDuplicates--) {
- nodes.splice(duplicates[numDuplicates], 1);
- }
-
- return nodes;
- },
- getAttributeValueFromNode: function (node, attributeName)
- {
- if (!this.hasNodeAttribute(node, attributeName)) {
- return;
- }
-
- if (node && node.getAttribute) {
- return node.getAttribute(attributeName);
- }
-
- if (!node || !node.attributes) {
- return;
- }
-
- var typeOfAttr = (typeof node.attributes[attributeName]);
- if ('undefined' === typeOfAttr) {
- return;
- }
-
- if (node.attributes[attributeName].value) {
- return node.attributes[attributeName].value; // nodeValue is deprecated ie Chrome
- }
-
- if (node.attributes[attributeName].nodeValue) {
- return node.attributes[attributeName].nodeValue;
- }
-
- var index;
- var attrs = node.attributes;
-
- if (!attrs) {
- return;
- }
-
- for (index = 0; index < attrs.length; index++) {
- if (attrs[index].nodeName === attributeName) {
- return attrs[index].nodeValue;
- }
- }
-
- return null;
- },
- hasNodeAttributeWithValue: function (node, attributeName)
- {
- var value = this.getAttributeValueFromNode(node, attributeName);
-
- return !!value;
- },
- hasNodeAttribute: function (node, attributeName)
- {
- if (node && node.hasAttribute) {
- return node.hasAttribute(attributeName);
- }
-
- if (node && node.attributes) {
- var typeOfAttr = (typeof node.attributes[attributeName]);
- return 'undefined' !== typeOfAttr;
- }
-
- return false;
- },
- hasNodeCssClass: function (node, klassName)
- {
- if (node && klassName && node.className) {
- var classes = typeof node.className === "string" ? node.className.split(' ') : [];
- if (-1 !== indexOfArray(classes, klassName)) {
- return true;
- }
- }
-
- return false;
- },
- findNodesHavingAttribute: function (nodeToSearch, attributeName, nodes)
- {
- if (!nodes) {
- nodes = [];
- }
-
- if (!nodeToSearch || !attributeName) {
- return nodes;
- }
-
- var children = getChildrenFromNode(nodeToSearch);
-
- if (!children || !children.length) {
- return nodes;
- }
-
- var index, child;
- for (index = 0; index < children.length; index++) {
- child = children[index];
- if (this.hasNodeAttribute(child, attributeName)) {
- nodes.push(child);
- }
-
- nodes = this.findNodesHavingAttribute(child, attributeName, nodes);
- }
-
- return nodes;
- },
- findFirstNodeHavingAttribute: function (node, attributeName)
- {
- if (!node || !attributeName) {
- return;
- }
-
- if (this.hasNodeAttribute(node, attributeName)) {
- return node;
- }
-
- var nodes = this.findNodesHavingAttribute(node, attributeName);
-
- if (nodes && nodes.length) {
- return nodes[0];
- }
- },
- findFirstNodeHavingAttributeWithValue: function (node, attributeName)
- {
- if (!node || !attributeName) {
- return;
- }
-
- if (this.hasNodeAttributeWithValue(node, attributeName)) {
- return node;
- }
-
- var nodes = this.findNodesHavingAttribute(node, attributeName);
-
- if (!nodes || !nodes.length) {
- return;
- }
-
- var index;
- for (index = 0; index < nodes.length; index++) {
- if (this.getAttributeValueFromNode(nodes[index], attributeName)) {
- return nodes[index];
- }
- }
- },
- findNodesHavingCssClass: function (nodeToSearch, className, nodes)
- {
- if (!nodes) {
- nodes = [];
- }
-
- if (!nodeToSearch || !className) {
- return nodes;
- }
-
- if (nodeToSearch.getElementsByClassName) {
- var foundNodes = nodeToSearch.getElementsByClassName(className);
- return this.htmlCollectionToArray(foundNodes);
- }
-
- var children = getChildrenFromNode(nodeToSearch);
-
- if (!children || !children.length) {
- return [];
- }
-
- var index, child;
- for (index = 0; index < children.length; index++) {
- child = children[index];
- if (this.hasNodeCssClass(child, className)) {
- nodes.push(child);
- }
-
- nodes = this.findNodesHavingCssClass(child, className, nodes);
- }
-
- return nodes;
- },
- findFirstNodeHavingClass: function (node, className)
- {
- if (!node || !className) {
- return;
- }
-
- if (this.hasNodeCssClass(node, className)) {
- return node;
- }
-
- var nodes = this.findNodesHavingCssClass(node, className);
-
- if (nodes && nodes.length) {
- return nodes[0];
- }
- },
- isLinkElement: function (node)
- {
- if (!node) {
- return false;
- }
-
- var elementName = String(node.nodeName).toLowerCase();
- var linkElementNames = ['a', 'area'];
- var pos = indexOfArray(linkElementNames, elementName);
-
- return pos !== -1;
- },
- setAnyAttribute: function (node, attrName, attrValue)
- {
- if (!node || !attrName) {
- return;
- }
-
- if (node.setAttribute) {
- node.setAttribute(attrName, attrValue);
- } else {
- node[attrName] = attrValue;
- }
- }
- };
-
- /************************************************************
- * Content Tracking
- ************************************************************/
-
- var content = {
- CONTENT_ATTR: 'data-track-content',
- CONTENT_CLASS: 'piwikTrackContent',
- CONTENT_NAME_ATTR: 'data-content-name',
- CONTENT_PIECE_ATTR: 'data-content-piece',
- CONTENT_PIECE_CLASS: 'piwikContentPiece',
- CONTENT_TARGET_ATTR: 'data-content-target',
- CONTENT_TARGET_CLASS: 'piwikContentTarget',
- CONTENT_IGNOREINTERACTION_ATTR: 'data-content-ignoreinteraction',
- CONTENT_IGNOREINTERACTION_CLASS: 'piwikContentIgnoreInteraction',
- location: undefined,
-
- findContentNodes: function ()
- {
-
- var cssSelector = '.' + this.CONTENT_CLASS;
- var attrSelector = '[' + this.CONTENT_ATTR + ']';
- var contentNodes = query.findMultiple([cssSelector, attrSelector]);
-
- return contentNodes;
- },
- findContentNodesWithinNode: function (node)
- {
- if (!node) {
- return [];
- }
-
- // NOTE: we do not use query.findMultiple here as querySelectorAll would most likely not deliver the result we want
-
- var nodes1 = query.findNodesHavingCssClass(node, this.CONTENT_CLASS);
- var nodes2 = query.findNodesHavingAttribute(node, this.CONTENT_ATTR);
-
- if (nodes2 && nodes2.length) {
- var index;
- for (index = 0; index < nodes2.length; index++) {
- nodes1.push(nodes2[index]);
- }
- }
-
- if (query.hasNodeAttribute(node, this.CONTENT_ATTR)) {
- nodes1.push(node);
- } else if (query.hasNodeCssClass(node, this.CONTENT_CLASS)) {
- nodes1.push(node);
- }
-
- nodes1 = query.makeNodesUnique(nodes1);
-
- return nodes1;
- },
- findParentContentNode: function (anyNode)
- {
- if (!anyNode) {
- return;
- }
-
- var node = anyNode;
- var counter = 0;
-
- while (node && node !== documentAlias && node.parentNode) {
- if (query.hasNodeAttribute(node, this.CONTENT_ATTR)) {
- return node;
- }
- if (query.hasNodeCssClass(node, this.CONTENT_CLASS)) {
- return node;
- }
-
- node = node.parentNode;
-
- if (counter > 1000) {
- break; // prevent loop, should not happen anyway but better we do this
- }
- counter++;
- }
- },
- findPieceNode: function (node)
- {
- var contentPiece;
-
- contentPiece = query.findFirstNodeHavingAttribute(node, this.CONTENT_PIECE_ATTR);
-
- if (!contentPiece) {
- contentPiece = query.findFirstNodeHavingClass(node, this.CONTENT_PIECE_CLASS);
- }
-
- if (contentPiece) {
- return contentPiece;
- }
-
- return node;
- },
- findTargetNodeNoDefault: function (node)
- {
- if (!node) {
- return;
- }
-
- var target = query.findFirstNodeHavingAttributeWithValue(node, this.CONTENT_TARGET_ATTR);
- if (target) {
- return target;
- }
-
- target = query.findFirstNodeHavingAttribute(node, this.CONTENT_TARGET_ATTR);
- if (target) {
- return target;
- }
-
- target = query.findFirstNodeHavingClass(node, this.CONTENT_TARGET_CLASS);
- if (target) {
- return target;
- }
- },
- findTargetNode: function (node)
- {
- var target = this.findTargetNodeNoDefault(node);
- if (target) {
- return target;
- }
-
- return node;
- },
- findContentName: function (node)
- {
- if (!node) {
- return;
- }
-
- var nameNode = query.findFirstNodeHavingAttributeWithValue(node, this.CONTENT_NAME_ATTR);
-
- if (nameNode) {
- return query.getAttributeValueFromNode(nameNode, this.CONTENT_NAME_ATTR);
- }
-
- var contentPiece = this.findContentPiece(node);
- if (contentPiece) {
- return this.removeDomainIfIsInLink(contentPiece);
- }
-
- if (query.hasNodeAttributeWithValue(node, 'title')) {
- return query.getAttributeValueFromNode(node, 'title');
- }
-
- var clickUrlNode = this.findPieceNode(node);
-
- if (query.hasNodeAttributeWithValue(clickUrlNode, 'title')) {
- return query.getAttributeValueFromNode(clickUrlNode, 'title');
- }
-
- var targetNode = this.findTargetNode(node);
-
- if (query.hasNodeAttributeWithValue(targetNode, 'title')) {
- return query.getAttributeValueFromNode(targetNode, 'title');
- }
- },
- findContentPiece: function (node)
- {
- if (!node) {
- return;
- }
-
- var nameNode = query.findFirstNodeHavingAttributeWithValue(node, this.CONTENT_PIECE_ATTR);
-
- if (nameNode) {
- return query.getAttributeValueFromNode(nameNode, this.CONTENT_PIECE_ATTR);
- }
-
- var contentNode = this.findPieceNode(node);
-
- var media = this.findMediaUrlInNode(contentNode);
- if (media) {
- return this.toAbsoluteUrl(media);
- }
- },
- findContentTarget: function (node)
- {
- if (!node) {
- return;
- }
-
- var targetNode = this.findTargetNode(node);
-
- if (query.hasNodeAttributeWithValue(targetNode, this.CONTENT_TARGET_ATTR)) {
- return query.getAttributeValueFromNode(targetNode, this.CONTENT_TARGET_ATTR);
- }
-
- var href;
- if (query.hasNodeAttributeWithValue(targetNode, 'href')) {
- href = query.getAttributeValueFromNode(targetNode, 'href');
- return this.toAbsoluteUrl(href);
- }
-
- var contentNode = this.findPieceNode(node);
-
- if (query.hasNodeAttributeWithValue(contentNode, 'href')) {
- href = query.getAttributeValueFromNode(contentNode, 'href');
- return this.toAbsoluteUrl(href);
- }
- },
- isSameDomain: function (url)
- {
- if (!url || !url.indexOf) {
- return false;
- }
-
- if (0 === url.indexOf(this.getLocation().origin)) {
- return true;
- }
-
- var posHost = url.indexOf(this.getLocation().host);
- if (8 >= posHost && 0 <= posHost) {
- return true;
- }
-
- return false;
- },
- removeDomainIfIsInLink: function (text)
- {
- // we will only remove if domain === location.origin meaning is not an outlink
- var regexContainsProtocol = '^https?:\/\/[^\/]+';
- var regexReplaceDomain = '^.*\/\/[^\/]+';
-
- if (text &&
- text.search &&
- -1 !== text.search(new RegExp(regexContainsProtocol))
- && this.isSameDomain(text)) {
-
- text = text.replace(new RegExp(regexReplaceDomain), '');
- if (!text) {
- text = '/';
- }
- }
-
- return text;
- },
- findMediaUrlInNode: function (node)
- {
- if (!node) {
- return;
- }
-
- var mediaElements = ['img', 'embed', 'video', 'audio'];
- var elementName = node.nodeName.toLowerCase();
-
- if (-1 !== indexOfArray(mediaElements, elementName) &&
- query.findFirstNodeHavingAttributeWithValue(node, 'src')) {
-
- var sourceNode = query.findFirstNodeHavingAttributeWithValue(node, 'src');
-
- return query.getAttributeValueFromNode(sourceNode, 'src');
- }
-
- if (elementName === 'object' &&
- query.hasNodeAttributeWithValue(node, 'data')) {
-
- return query.getAttributeValueFromNode(node, 'data');
- }
-
- if (elementName === 'object') {
- var params = query.findNodesByTagName(node, 'param');
- if (params && params.length) {
- var index;
- for (index = 0; index < params.length; index++) {
- if ('movie' === query.getAttributeValueFromNode(params[index], 'name') &&
- query.hasNodeAttributeWithValue(params[index], 'value')) {
-
- return query.getAttributeValueFromNode(params[index], 'value');
- }
- }
- }
-
- var embed = query.findNodesByTagName(node, 'embed');
- if (embed && embed.length) {
- return this.findMediaUrlInNode(embed[0]);
- }
- }
- },
- trim: function (text)
- {
- if (text && String(text) === text) {
- return text.replace(/^\s+|\s+$/g, '');
- }
-
- return text;
- },
- isOrWasNodeInViewport: function (node)
- {
- if (!node || !node.getBoundingClientRect || node.nodeType !== 1) {
- return true;
- }
-
- var rect = node.getBoundingClientRect();
- var html = documentAlias.documentElement || {};
-
- var wasVisible = rect.top < 0;
- if (wasVisible && node.offsetTop) {
- wasVisible = (node.offsetTop + rect.height) > 0;
- }
-
- var docWidth = html.clientWidth; // The clientWidth attribute returns the viewport width excluding the size of a rendered scroll bar
-
- if (windowAlias.innerWidth && docWidth > windowAlias.innerWidth) {
- docWidth = windowAlias.innerWidth; // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar
- }
-
- var docHeight = html.clientHeight; // The clientWidth attribute returns the viewport width excluding the size of a rendered scroll bar
-
- if (windowAlias.innerHeight && docHeight > windowAlias.innerHeight) {
- docHeight = windowAlias.innerHeight; // The innerWidth attribute must return the viewport width including the size of a rendered scroll bar
- }
-
- return (
- (rect.bottom > 0 || wasVisible) &&
- rect.right > 0 &&
- rect.left < docWidth &&
- ((rect.top < docHeight) || wasVisible) // rect.top < 0 we assume user has seen all the ones that are above the current viewport
- );
- },
- isNodeVisible: function (node)
- {
- var isItVisible = isVisible(node);
- var isInViewport = this.isOrWasNodeInViewport(node);
- return isItVisible && isInViewport;
- },
- buildInteractionRequestParams: function (interaction, name, piece, target)
- {
- var params = '';
-
- if (interaction) {
- params += 'c_i='+ encodeWrapper(interaction);
- }
- if (name) {
- if (params) {
- params += '&';
- }
- params += 'c_n='+ encodeWrapper(name);
- }
- if (piece) {
- if (params) {
- params += '&';
- }
- params += 'c_p='+ encodeWrapper(piece);
- }
- if (target) {
- if (params) {
- params += '&';
- }
- params += 'c_t='+ encodeWrapper(target);
- }
-
- return params;
- },
- buildImpressionRequestParams: function (name, piece, target)
- {
- var params = 'c_n=' + encodeWrapper(name) +
- '&c_p=' + encodeWrapper(piece);
-
- if (target) {
- params += '&c_t=' + encodeWrapper(target);
- }
-
- return params;
- },
- buildContentBlock: function (node)
- {
- if (!node) {
- return;
- }
-
- var name = this.findContentName(node);
- var piece = this.findContentPiece(node);
- var target = this.findContentTarget(node);
-
- name = this.trim(name);
- piece = this.trim(piece);
- target = this.trim(target);
-
- return {
- name: name || 'Unknown',
- piece: piece || 'Unknown',
- target: target || ''
- };
- },
- collectContent: function (contentNodes)
- {
- if (!contentNodes || !contentNodes.length) {
- return [];
- }
-
- var contents = [];
-
- var index, contentBlock;
- for (index = 0; index < contentNodes.length; index++) {
- contentBlock = this.buildContentBlock(contentNodes[index]);
- if (isDefined(contentBlock)) {
- contents.push(contentBlock);
- }
- }
-
- return contents;
- },
- setLocation: function (location)
- {
- this.location = location;
- },
- getLocation: function ()
- {
- var locationAlias = this.location || windowAlias.location;
-
- if (!locationAlias.origin) {
- locationAlias.origin = locationAlias.protocol + "//" + locationAlias.hostname + (locationAlias.port ? ':' + locationAlias.port: '');
- }
-
- return locationAlias;
- },
- toAbsoluteUrl: function (url)
- {
- if ((!url || String(url) !== url) && url !== '') {
- // we only handle strings
- return url;
- }
-
- if ('' === url) {
- return this.getLocation().href;
- }
-
- // Eg //example.com/test.jpg
- if (url.search(/^\/\//) !== -1) {
- return this.getLocation().protocol + url;
- }
-
- // Eg http://example.com/test.jpg
- if (url.search(/:\/\//) !== -1) {
- return url;
- }
-
- // Eg #test.jpg
- if (0 === url.indexOf('#')) {
- return this.getLocation().origin + this.getLocation().pathname + url;
- }
-
- // Eg ?x=5
- if (0 === url.indexOf('?')) {
- return this.getLocation().origin + this.getLocation().pathname + url;
- }
-
- // Eg mailto:x@y.z tel:012345, ... market:... sms:..., javasript:... ecmascript: ... and many more
- if (0 === url.search('^[a-zA-Z]{2,11}:')) {
- return url;
- }
-
- // Eg /test.jpg
- if (url.search(/^\//) !== -1) {
- return this.getLocation().origin + url;
- }
-
- // Eg test.jpg
- var regexMatchDir = '(.*\/)';
- var base = this.getLocation().origin + this.getLocation().pathname.match(new RegExp(regexMatchDir))[0];
- return base + url;
- },
- isUrlToCurrentDomain: function (url) {
-
- var absoluteUrl = this.toAbsoluteUrl(url);
-
- if (!absoluteUrl) {
- return false;
- }
-
- var origin = this.getLocation().origin;
- if (origin === absoluteUrl) {
- return true;
- }
-
- if (0 === String(absoluteUrl).indexOf(origin)) {
- if (':' === String(absoluteUrl).substr(origin.length, 1)) {
- return false; // url has port whereas origin has not => different URL
- }
-
- return true;
- }
-
- return false;
- },
- setHrefAttribute: function (node, url)
- {
- if (!node || !url) {
- return;
- }
-
- query.setAnyAttribute(node, 'href', url);
- },
- shouldIgnoreInteraction: function (targetNode)
- {
- var hasAttr = query.hasNodeAttribute(targetNode, this.CONTENT_IGNOREINTERACTION_ATTR);
- var hasClass = query.hasNodeCssClass(targetNode, this.CONTENT_IGNOREINTERACTION_CLASS);
- return hasAttr || hasClass;
- }
- };
-
- /************************************************************
- * Page Overlay
- ************************************************************/
-
- function getPiwikUrlForOverlay(trackerUrl, apiUrl) {
- if (apiUrl) {
- return apiUrl;
- }
-
- if (trackerUrl.slice(-9) === 'piwik.php') {
- trackerUrl = trackerUrl.slice(0, trackerUrl.length - 9);
- }
-
- return trackerUrl;
- }
-
- /*
- * Check whether this is a page overlay session
- *
- * @return boolean
- *
- * {@internal side-effect: modifies window.name }}
- */
- function isOverlaySession(configTrackerSiteId) {
- var windowName = 'Piwik_Overlay';
-
- // check whether we were redirected from the piwik overlay plugin
- var referrerRegExp = new RegExp('index\\.php\\?module=Overlay&action=startOverlaySession'
- + '&idSite=([0-9]+)&period=([^&]+)&date=([^&]+)(&segment=.*)?$');
-
- var match = referrerRegExp.exec(documentAlias.referrer);
-
- if (match) {
- // check idsite
- var idsite = match[1];
-
- if (idsite !== String(configTrackerSiteId)) {
- return false;
- }
-
- // store overlay session info in window name
- var period = match[2],
- date = match[3],
- segment = match[4];
-
- if (!segment) {
- segment = '';
- } else if (segment.indexOf('&segment=') === 0) {
- segment = segment.substr('&segment='.length);
- }
-
- windowAlias.name = windowName + '###' + period + '###' + date + '###' + segment;
- }
-
- // retrieve and check data from window name
- var windowNameParts = windowAlias.name.split('###');
-
- return windowNameParts.length === 4 && windowNameParts[0] === windowName;
- }
-
- /*
- * Inject the script needed for page overlay
- */
- function injectOverlayScripts(configTrackerUrl, configApiUrl, configTrackerSiteId) {
- var windowNameParts = windowAlias.name.split('###'),
- period = windowNameParts[1],
- date = windowNameParts[2],
- segment = windowNameParts[3],
- piwikUrl = getPiwikUrlForOverlay(configTrackerUrl, configApiUrl);
-
- loadScript(
- piwikUrl + 'plugins/Overlay/client/client.js?v=1',
- function () {
- Piwik_Overlay_Client.initialize(piwikUrl, configTrackerSiteId, period, date, segment);
- }
- );
- }
-
- /************************************************************
- * End Page Overlay
- ************************************************************/
-
- /*
- * Piwik Tracker class
- *
- * trackerUrl and trackerSiteId are optional arguments to the constructor
- *
- * See: Tracker.setTrackerUrl() and Tracker.setSiteId()
- */
- function Tracker(trackerUrl, siteId) {
-
- /************************************************************
- * Private members
- ************************************************************/
-
- var
-/**/
- /*
- * registered test hooks
- */
- registeredHooks = {},
-/**/
-
- // Current URL and Referrer URL
- locationArray = urlFixup(documentAlias.domain, windowAlias.location.href, getReferrer()),
- domainAlias = domainFixup(locationArray[0]),
- locationHrefAlias = safeDecodeWrapper(locationArray[1]),
- configReferrerUrl = safeDecodeWrapper(locationArray[2]),
-
- enableJSErrorTracking = false,
-
- defaultRequestMethod = 'GET',
-
- // Request method (GET or POST)
- configRequestMethod = defaultRequestMethod,
-
- defaultRequestContentType = 'application/x-www-form-urlencoded; charset=UTF-8',
-
- // Request Content-Type header value; applicable when POST request method is used for submitting tracking events
- configRequestContentType = defaultRequestContentType,
-
- // Tracker URL
- configTrackerUrl = trackerUrl || '',
-
- // API URL (only set if it differs from the Tracker URL)
- configApiUrl = '',
-
- // This string is appended to the Tracker URL Request (eg. to send data that is not handled by the existing setters/getters)
- configAppendToTrackingUrl = '',
-
- // Site ID
- configTrackerSiteId = siteId || '',
-
- // User ID
- configUserId = '',
-
- // Visitor UUID
- visitorUUID = '',
-
- // Document URL
- configCustomUrl,
-
- // Document title
- configTitle = documentAlias.title,
-
- // Extensions to be treated as download links
- configDownloadExtensions = ['7z','aac','apk','arc','arj','asf','asx','avi','azw3','bin','csv','deb','dmg','doc','docx','epub','exe','flv','gif','gz','gzip','hqx','ibooks','jar','jpg','jpeg','js','mobi','mp2','mp3','mp4','mpg','mpeg','mov','movie','msi','msp','odb','odf','odg','ods','odt','ogg','ogv','pdf','phps','png','ppt','pptx','qt','qtm','ra','ram','rar','rpm','sea','sit','tar','tbz','tbz2','bz','bz2','tgz','torrent','txt','wav','wma','wmv','wpd','xls','xlsx','xml','z','zip'],
-
- // Hosts or alias(es) to not treat as outlinks
- configHostsAlias = [domainAlias],
-
- // HTML anchor element classes to not track
- configIgnoreClasses = [],
-
- // HTML anchor element classes to treat as downloads
- configDownloadClasses = [],
-
- // HTML anchor element classes to treat at outlinks
- configLinkClasses = [],
-
- // Maximum delay to wait for spiderweb bug image to be fetched (in milliseconds)
- configTrackerPause = 500,
-
- // Minimum visit time after initial page view (in milliseconds)
- configMinimumVisitTime,
-
- // Recurring heart beat after initial ping (in milliseconds)
- configHeartBeatDelay,
-
- // alias to circumvent circular function dependency (JSLint requires this)
- heartBeatPingIfActivityAlias,
-
- // Disallow hash tags in URL
- configDiscardHashTag,
-
- // Custom data
- configCustomData,
-
- // Campaign names
- configCampaignNameParameters = [ 'pk_campaign', 'piwik_campaign', 'utm_campaign', 'utm_source', 'utm_medium' ],
-
- // Campaign keywords
- configCampaignKeywordParameters = [ 'pk_kwd', 'piwik_kwd', 'utm_term' ],
-
- // First-party cookie name prefix
- configCookieNamePrefix = '_pk_',
-
- // First-party cookie domain
- // User agent defaults to origin hostname
- configCookieDomain,
-
- // First-party cookie path
- // Default is user agent defined.
- configCookiePath,
-
- // Cookies are disabled
- configCookiesDisabled = false,
-
- // Do Not Track
- configDoNotTrack,
-
- // Count sites which are pre-rendered
- configCountPreRendered,
-
- // Do we attribute the conversion to the first referrer or the most recent referrer?
- configConversionAttributionFirstReferrer,
-
- // Life of the visitor cookie (in milliseconds)
- configVisitorCookieTimeout = 33955200000, // 13 months (365 days + 28days)
-
- // Life of the session cookie (in milliseconds)
- configSessionCookieTimeout = 1800000, // 30 minutes
-
- // Life of the referral cookie (in milliseconds)
- configReferralCookieTimeout = 15768000000, // 6 months
-
- // Is performance tracking enabled
- configPerformanceTrackingEnabled = true,
-
- // Generation time set from the server
- configPerformanceGenerationTime = 0,
-
- // Whether Custom Variables scope "visit" should be stored in a cookie during the time of the visit
- configStoreCustomVariablesInCookie = false,
-
- // Custom Variables read from cookie, scope "visit"
- customVariables = false,
-
- configCustomRequestContentProcessing,
-
- // Custom Variables, scope "page"
- customVariablesPage = {},
-
- // Custom Variables, scope "event"
- customVariablesEvent = {},
-
- // Custom Dimensions (can be any scope)
- customDimensions = {},
-
- // Custom Variables names and values are each truncated before being sent in the request or recorded in the cookie
- customVariableMaximumLength = 200,
-
- // Ecommerce items
- ecommerceItems = {},
-
- // Browser features via client-side data collection
- browserFeatures = {},
-
- // Keeps track of previously tracked content impressions
- trackedContentImpressions = [],
- isTrackOnlyVisibleContentEnabled = false,
-
- // Guard to prevent empty visits see #6415. If there is a new visitor and the first 2 (or 3 or 4)
- // tracking requests are at nearly same time (eg trackPageView and trackContentImpression) 2 or more
- // visits will be created
- timeNextTrackingRequestCanBeExecutedImmediately = false,
-
- // Guard against installing the link tracker more than once per Tracker instance
- linkTrackingInstalled = false,
- linkTrackingEnabled = false,
-
- // Guard against installing the activity tracker more than once per Tracker instance
- heartBeatSetUp = false,
-
- // Timestamp of last tracker request sent to Piwik
- lastTrackerRequestTime = null,
-
- // Handle to the current heart beat timeout
- heartBeatTimeout,
-
- // Internal state of the pseudo click handler
- lastButton,
- lastTarget,
-
- // Hash function
- hash = sha1,
-
- // Domain hash value
- domainHash;
-
- /*
- * Set cookie value
- */
- function setCookie(cookieName, value, msToExpire, path, domain, secure) {
- if (configCookiesDisabled) {
- return;
- }
-
- var expiryDate;
-
- // relative time to expire in milliseconds
- if (msToExpire) {
- expiryDate = new Date();
- expiryDate.setTime(expiryDate.getTime() + msToExpire);
- }
-
- documentAlias.cookie = cookieName + '=' + encodeWrapper(value) +
- (msToExpire ? ';expires=' + expiryDate.toGMTString() : '') +
- ';path=' + (path || '/') +
- (domain ? ';domain=' + domain : '') +
- (secure ? ';secure' : '');
- }
-
- /*
- * Get cookie value
- */
- function getCookie(cookieName) {
- if (configCookiesDisabled) {
- return 0;
- }
-
- var cookiePattern = new RegExp('(^|;)[ ]*' + cookieName + '=([^;]*)'),
- cookieMatch = cookiePattern.exec(documentAlias.cookie);
-
- return cookieMatch ? decodeWrapper(cookieMatch[2]) : 0;
- }
-
- /*
- * Removes hash tag from the URL
- *
- * URLs are purified before being recorded in the cookie,
- * or before being sent as GET parameters
- */
- function purify(url) {
- var targetPattern;
-
- if (configDiscardHashTag) {
- targetPattern = new RegExp('#.*');
-
- return url.replace(targetPattern, '');
- }
-
- return url;
- }
-
- /*
- * Resolve relative reference
- *
- * Note: not as described in rfc3986 section 5.2
- */
- function resolveRelativeReference(baseUrl, url) {
- var protocol = getProtocolScheme(url),
- i;
-
- if (protocol) {
- return url;
- }
-
- if (url.slice(0, 1) === '/') {
- return getProtocolScheme(baseUrl) + '://' + getHostName(baseUrl) + url;
- }
-
- baseUrl = purify(baseUrl);
-
- i = baseUrl.indexOf('?');
- if (i >= 0) {
- baseUrl = baseUrl.slice(0, i);
- }
-
- i = baseUrl.lastIndexOf('/');
- if (i !== baseUrl.length - 1) {
- baseUrl = baseUrl.slice(0, i + 1);
- }
-
- return baseUrl + url;
- }
-
- function isSameHost (hostName, alias) {
- var offset;
-
- hostName = String(hostName).toLowerCase();
- alias = String(alias).toLowerCase();
-
- if (hostName === alias) {
- return true;
- }
-
- if (alias.slice(0, 1) === '.') {
- if (hostName === alias.slice(1)) {
- return true;
- }
-
- offset = hostName.length - alias.length;
-
- if ((offset > 0) && (hostName.slice(offset) === alias)) {
- return true;
- }
- }
-
- return false;
- }
-
- function stringEndsWith(str, suffix) {
- str = String(str);
- return str.indexOf(suffix, str.length - suffix.length) !== -1;
- }
-
- function removeCharactersFromEndOfString(str, numCharactersToRemove) {
- str = String(str);
- return str.substr(0, str.length - numCharactersToRemove);
- }
-
- /*
- * Extract pathname from URL. element.pathname is actually supported by pretty much all browsers including
- * IE6 apart from some rare very old ones
- */
- function getPathName(url) {
- var parser = document.createElement('a');
- if (url.indexOf('//') !== 0 && url.indexOf('http') !== 0) {
- url = 'http://' + url;
- }
-
- parser.href = content.toAbsoluteUrl(url);
- if (parser.pathname) {
- return parser.pathname;
- }
-
- return '';
- }
-
- function isSitePath (path, pathAlias)
- {
- var matchesAnyPath = (!pathAlias || pathAlias === '/');
-
- if (matchesAnyPath) {
- return true;
- }
-
- if (path === pathAlias) {
- return true;
- }
-
- if (!path) {
- return false;
- }
-
- pathAlias = String(pathAlias).toLowerCase();
- path = String(path).toLowerCase();
-
- // we need to append slashes so /foobarbaz won't match a site /foobar
- if (!stringEndsWith(path, '/')) {
- path += '/';
- }
-
- if (!stringEndsWith(pathAlias, '/')) {
- pathAlias += '/';
- }
-
- return path.indexOf(pathAlias) === 0;
- }
-
- function isSiteHostPath(host, path)
- {
- var i,
- alias,
- configAlias,
- aliasHost,
- aliasPath;
-
- for (i = 0; i < configHostsAlias.length; i++) {
- aliasHost = domainFixup(configHostsAlias[i]);
- aliasPath = getPathName(configHostsAlias[i]);
-
- if (isSameHost(host, aliasHost) && isSitePath(path, aliasPath)) {
- return true;
- }
- }
-
- return false;
- }
-
- /*
- * Is the host local? (i.e., not an outlink)
- */
- function isSiteHostName(hostName) {
-
- var i,
- alias,
- offset;
-
- for (i = 0; i < configHostsAlias.length; i++) {
- alias = domainFixup(configHostsAlias[i].toLowerCase());
-
- if (hostName === alias) {
- return true;
- }
-
- if (alias.slice(0, 1) === '.') {
- if (hostName === alias.slice(1)) {
- return true;
- }
-
- offset = hostName.length - alias.length;
-
- if ((offset > 0) && (hostName.slice(offset) === alias)) {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /*
- * Send image request to Piwik server using GET.
- * The infamous spiderweb bug (or beacon) is a transparent, single pixel (1x1) image
- */
- function getImage(request, callback) {
- var image = new Image(1, 1);
-
- image.onload = function () {
- iterator = 0; // To avoid JSLint warning of empty block
- if (typeof callback === 'function') { callback(); }
- };
- image.src = configTrackerUrl + (configTrackerUrl.indexOf('?') < 0 ? '?' : '&') + request;
- }
-
- /*
- * POST request to Piwik server using XMLHttpRequest.
- */
- function sendXmlHttpRequest(request, callback, fallbackToGet) {
- if (!isDefined(fallbackToGet) || null === fallbackToGet) {
- fallbackToGet = true;
- }
-
- try {
- // we use the progid Microsoft.XMLHTTP because
- // IE5.5 included MSXML 2.5; the progid MSXML2.XMLHTTP
- // is pinned to MSXML2.XMLHTTP.3.0
- var xhr = windowAlias.XMLHttpRequest
- ? new windowAlias.XMLHttpRequest()
- : windowAlias.ActiveXObject
- ? new ActiveXObject('Microsoft.XMLHTTP')
- : null;
-
- xhr.open('POST', configTrackerUrl, true);
-
- // fallback on error
- xhr.onreadystatechange = function () {
- if (this.readyState === 4 && !(this.status >= 200 && this.status < 300) && fallbackToGet) {
- getImage(request, callback);
- } else {
- if (typeof callback === 'function') { callback(); }
- }
- };
-
- xhr.setRequestHeader('Content-Type', configRequestContentType);
-
- xhr.send(request);
- } catch (e) {
- if (fallbackToGet) {
- // fallback
- getImage(request, callback);
- }
- }
- }
-
- function setExpireDateTime(delay) {
-
- var now = new Date();
- var time = now.getTime() + delay;
-
- if (!expireDateTime || time > expireDateTime) {
- expireDateTime = time;
- }
- }
-
- /*
- * Sets up the heart beat timeout.
- */
- function heartBeatUp(delay) {
- if (heartBeatTimeout
- || !configHeartBeatDelay
- ) {
- return;
- }
-
- heartBeatTimeout = setTimeout(function heartBeat() {
- heartBeatTimeout = null;
- if (heartBeatPingIfActivityAlias()) {
- return;
- }
-
- var now = new Date(),
- heartBeatDelay = configHeartBeatDelay - (now.getTime() - lastTrackerRequestTime);
- // sanity check
- heartBeatDelay = Math.min(configHeartBeatDelay, heartBeatDelay);
- heartBeatUp(heartBeatDelay);
- }, delay || configHeartBeatDelay);
- }
-
- /*
- * Removes the heart beat timeout.
- */
- function heartBeatDown() {
- if (!heartBeatTimeout) {
- return;
- }
-
- clearTimeout(heartBeatTimeout);
- heartBeatTimeout = null;
- }
-
- function heartBeatOnFocus() {
- // since it's possible for a user to come back to a tab after several hours or more, we try to send
- // a ping if the page is active. (after the ping is sent, the heart beat timeout will be set)
- if (heartBeatPingIfActivityAlias()) {
- return;
- }
-
- heartBeatUp();
- }
-
- function heartBeatOnBlur() {
- heartBeatDown();
- }
-
- /*
- * Setup event handlers and timeout for initial heart beat.
- */
- function setUpHeartBeat() {
- if (heartBeatSetUp
- || !configHeartBeatDelay
- ) {
- return;
- }
-
- heartBeatSetUp = true;
-
- addEventListener(windowAlias, 'focus', heartBeatOnFocus);
- addEventListener(windowAlias, 'blur', heartBeatOnBlur);
-
- heartBeatUp();
- }
-
- function makeSureThereIsAGapAfterFirstTrackingRequestToPreventMultipleVisitorCreation(callback)
- {
- var now = new Date();
- var timeNow = now.getTime();
-
- lastTrackerRequestTime = timeNow;
-
- if (timeNextTrackingRequestCanBeExecutedImmediately && timeNow < timeNextTrackingRequestCanBeExecutedImmediately) {
- // we are in the time frame shortly after the first request. we have to delay this request a bit to make sure
- // a visitor has been created meanwhile.
-
- var timeToWait = timeNextTrackingRequestCanBeExecutedImmediately - timeNow;
-
- setTimeout(callback, timeToWait);
- setExpireDateTime(timeToWait + 50); // set timeout is not necessarily executed at timeToWait so delay a bit more
- timeNextTrackingRequestCanBeExecutedImmediately += 50; // delay next tracking request by further 50ms to next execute them at same time
-
- return;
- }
-
- if (timeNextTrackingRequestCanBeExecutedImmediately === false) {
- // it is the first request, we want to execute this one directly and delay all the next one(s) within a delay.
- // All requests after this delay can be executed as usual again
- var delayInMs = 800;
- timeNextTrackingRequestCanBeExecutedImmediately = timeNow + delayInMs;
- }
-
- callback();
- }
-
- /*
- * Send request
- */
- function sendRequest(request, delay, callback) {
- if (!configDoNotTrack && request) {
- makeSureThereIsAGapAfterFirstTrackingRequestToPreventMultipleVisitorCreation(function () {
- if (configRequestMethod === 'POST') {
- sendXmlHttpRequest(request, callback);
- } else {
- getImage(request, callback);
- }
-
- setExpireDateTime(delay);
- });
- }
-
- if (!heartBeatSetUp) {
- setUpHeartBeat(); // setup window events too, but only once
- } else {
- heartBeatUp();
- }
- }
-
- function canSendBulkRequest(requests)
- {
- if (configDoNotTrack) {
- return false;
- }
-
- return (requests && requests.length);
- }
-
- /*
- * Send requests using bulk
- */
- function sendBulkRequest(requests, delay)
- {
- if (!canSendBulkRequest(requests)) {
- return;
- }
-
- var bulk = '{"requests":["?' + requests.join('","?') + '"]}';
-
- makeSureThereIsAGapAfterFirstTrackingRequestToPreventMultipleVisitorCreation(function () {
- sendXmlHttpRequest(bulk, null, false);
- setExpireDateTime(delay);
- });
- }
-
- /*
- * Get cookie name with prefix and domain hash
- */
- function getCookieName(baseName) {
- // NOTE: If the cookie name is changed, we must also update the PiwikTracker.php which
- // will attempt to discover first party cookies. eg. See the PHP Client method getVisitorId()
- return configCookieNamePrefix + baseName + '.' + configTrackerSiteId + '.' + domainHash;
- }
-
- /*
- * Does browser have cookies enabled (for this site)?
- */
- function hasCookies() {
- if (configCookiesDisabled) {
- return '0';
- }
-
- if (!isDefined(navigatorAlias.cookieEnabled)) {
- var testCookieName = getCookieName('testcookie');
- setCookie(testCookieName, '1');
-
- return getCookie(testCookieName) === '1' ? '1' : '0';
- }
-
- return navigatorAlias.cookieEnabled ? '1' : '0';
- }
-
- /*
- * Update domain hash
- */
- function updateDomainHash() {
- domainHash = hash((configCookieDomain || domainAlias) + (configCookiePath || '/')).slice(0, 4); // 4 hexits = 16 bits
- }
-
- /*
- * Inits the custom variables object
- */
- function getCustomVariablesFromCookie() {
- var cookieName = getCookieName('cvar'),
- cookie = getCookie(cookieName);
-
- if (cookie.length) {
- cookie = JSON2.parse(cookie);
-
- if (isObject(cookie)) {
- return cookie;
- }
- }
-
- return {};
- }
-
- /*
- * Lazy loads the custom variables from the cookie, only once during this page view
- */
- function loadCustomVariables() {
- if (customVariables === false) {
- customVariables = getCustomVariablesFromCookie();
- }
- }
-
- /*
- * Generate a pseudo-unique ID to fingerprint this user
- * 16 hexits = 64 bits
- * note: this isn't a RFC4122-compliant UUID
- */
- function generateRandomUuid() {
- return hash(
- (navigatorAlias.userAgent || '') +
- (navigatorAlias.platform || '') +
- JSON2.stringify(browserFeatures) +
- (new Date()).getTime() +
- Math.random()
- ).slice(0, 16);
- }
-
- /*
- * Load visitor ID cookie
- */
- function loadVisitorIdCookie() {
- var now = new Date(),
- nowTs = Math.round(now.getTime() / 1000),
- visitorIdCookieName = getCookieName('id'),
- id = getCookie(visitorIdCookieName),
- cookieValue,
- uuid;
-
- // Visitor ID cookie found
- if (id) {
- cookieValue = id.split('.');
-
- // returning visitor flag
- cookieValue.unshift('0');
-
- if(visitorUUID.length) {
- cookieValue[1] = visitorUUID;
- }
- return cookieValue;
- }
-
- if(visitorUUID.length) {
- uuid = visitorUUID;
- } else if ('0' === hasCookies()){
- uuid = '';
- } else {
- uuid = generateRandomUuid();
- }
-
- // No visitor ID cookie, let's create a new one
- cookieValue = [
- // new visitor
- '1',
-
- // uuid
- uuid,
-
- // creation timestamp - seconds since Unix epoch
- nowTs,
-
- // visitCount - 0 = no previous visit
- 0,
-
- // current visit timestamp
- nowTs,
-
- // last visit timestamp - blank = no previous visit
- '',
-
- // last ecommerce order timestamp
- ''
- ];
-
- return cookieValue;
- }
-
-
- /**
- * Loads the Visitor ID cookie and returns a named array of values
- */
- function getValuesFromVisitorIdCookie() {
- var cookieVisitorIdValue = loadVisitorIdCookie(),
- newVisitor = cookieVisitorIdValue[0],
- uuid = cookieVisitorIdValue[1],
- createTs = cookieVisitorIdValue[2],
- visitCount = cookieVisitorIdValue[3],
- currentVisitTs = cookieVisitorIdValue[4],
- lastVisitTs = cookieVisitorIdValue[5];
-
- // case migrating from pre-1.5 cookies
- if (!isDefined(cookieVisitorIdValue[6])) {
- cookieVisitorIdValue[6] = "";
- }
-
- var lastEcommerceOrderTs = cookieVisitorIdValue[6];
-
- return {
- newVisitor: newVisitor,
- uuid: uuid,
- createTs: createTs,
- visitCount: visitCount,
- currentVisitTs: currentVisitTs,
- lastVisitTs: lastVisitTs,
- lastEcommerceOrderTs: lastEcommerceOrderTs
- };
- }
-
-
- function getRemainingVisitorCookieTimeout() {
- var now = new Date(),
- nowTs = now.getTime(),
- cookieCreatedTs = getValuesFromVisitorIdCookie().createTs;
-
- var createTs = parseInt(cookieCreatedTs, 10);
- var originalTimeout = (createTs * 1000) + configVisitorCookieTimeout - nowTs;
- return originalTimeout;
- }
-
- /*
- * Sets the Visitor ID cookie
- */
- function setVisitorIdCookie(visitorIdCookieValues) {
-
- if(!configTrackerSiteId) {
- // when called before Site ID was set
- return;
- }
-
- var now = new Date(),
- nowTs = Math.round(now.getTime() / 1000);
-
- if(!isDefined(visitorIdCookieValues)) {
- visitorIdCookieValues = getValuesFromVisitorIdCookie();
- }
-
- var cookieValue = visitorIdCookieValues.uuid + '.' +
- visitorIdCookieValues.createTs + '.' +
- visitorIdCookieValues.visitCount + '.' +
- nowTs + '.' +
- visitorIdCookieValues.lastVisitTs + '.' +
- visitorIdCookieValues.lastEcommerceOrderTs;
-
- setCookie(getCookieName('id'), cookieValue, getRemainingVisitorCookieTimeout(), configCookiePath, configCookieDomain);
- }
-
- /*
- * Loads the referrer attribution information
- *
- * @returns array
- * 0: campaign name
- * 1: campaign keyword
- * 2: timestamp
- * 3: raw URL
- */
- function loadReferrerAttributionCookie() {
- // NOTE: if the format of the cookie changes,
- // we must also update JS tests, PHP tracker, System tests,
- // and notify other tracking clients (eg. Java) of the changes
- var cookie = getCookie(getCookieName('ref'));
-
- if (cookie.length) {
- try {
- cookie = JSON2.parse(cookie);
- if (isObject(cookie)) {
- return cookie;
- }
- } catch (ignore) {
- // Pre 1.3, this cookie was not JSON encoded
- }
- }
-
- return [
- '',
- '',
- 0,
- ''
- ];
- }
-
- function deleteCookie(cookieName, path, domain) {
- setCookie(cookieName, '', -86400, path, domain);
- }
-
- function isPossibleToSetCookieOnDomain(domainToTest)
- {
- var valueToSet = 'testvalue';
- setCookie('test', valueToSet, 10000, null, domainToTest);
-
- if (getCookie('test') === valueToSet) {
- deleteCookie('test', null, domainToTest);
-
- return true;
- }
-
- return false;
- }
-
- function deleteCookies() {
- var savedConfigCookiesDisabled = configCookiesDisabled;
-
- // Temporarily allow cookies just to delete the existing ones
- configCookiesDisabled = false;
-
- var cookiesToDelete = ['id', 'ses', 'cvar', 'ref'];
- var index, cookieName;
-
- for (index = 0; index < cookiesToDelete.length; index++) {
- cookieName = getCookieName(cookiesToDelete[index]);
- if (0 !== getCookie(cookieName)) {
- deleteCookie(cookieName, configCookiePath, configCookieDomain);
- }
- }
-
- configCookiesDisabled = savedConfigCookiesDisabled;
- }
-
- function setSiteId(siteId) {
- configTrackerSiteId = siteId;
- setVisitorIdCookie();
- }
-
- function sortObjectByKeys(value) {
- if (!value || !isObject(value)) {
- return;
- }
-
- // Object.keys(value) is not supported by all browsers, we get the keys manually
- var keys = [];
- var key;
-
- for (key in value) {
- if (Object.prototype.hasOwnProperty.call(value, key)) {
- keys.push(key);
- }
- }
-
- var normalized = {};
- keys.sort();
- var len = keys.length;
- var i;
-
- for (i = 0; i < len; i++) {
- normalized[keys[i]] = value[keys[i]];
- }
-
- return normalized;
- }
-
- /**
- * Creates the session cookie
- */
- function setSessionCookie() {
- setCookie(getCookieName('ses'), '*', configSessionCookieTimeout, configCookiePath, configCookieDomain);
- }
-
- /**
- * Returns the URL to call piwik.php,
- * with the standard parameters (plugins, resolution, url, referrer, etc.).
- * Sends the pageview and browser settings with every request in case of race conditions.
- */
- function getRequest(request, customData, pluginMethod, currentEcommerceOrderTs) {
- var i,
- now = new Date(),
- nowTs = Math.round(now.getTime() / 1000),
- referralTs,
- referralUrl,
- referralUrlMaxLength = 1024,
- currentReferrerHostName,
- originalReferrerHostName,
- customVariablesCopy = customVariables,
- cookieSessionName = getCookieName('ses'),
- cookieReferrerName = getCookieName('ref'),
- cookieCustomVariablesName = getCookieName('cvar'),
- cookieSessionValue = getCookie(cookieSessionName),
- attributionCookie = loadReferrerAttributionCookie(),
- currentUrl = configCustomUrl || locationHrefAlias,
- campaignNameDetected,
- campaignKeywordDetected;
-
- if (configCookiesDisabled) {
- deleteCookies();
- }
-
- if (configDoNotTrack) {
- return '';
- }
-
- var cookieVisitorIdValues = getValuesFromVisitorIdCookie();
- if (!isDefined(currentEcommerceOrderTs)) {
- currentEcommerceOrderTs = "";
- }
-
- // send charset if document charset is not utf-8. sometimes encoding
- // of urls will be the same as this and not utf-8, which will cause problems
- // do not send charset if it is utf8 since it's assumed by default in Piwik
- var charSet = documentAlias.characterSet || documentAlias.charset;
-
- if (!charSet || charSet.toLowerCase() === 'utf-8') {
- charSet = null;
- }
-
- campaignNameDetected = attributionCookie[0];
- campaignKeywordDetected = attributionCookie[1];
- referralTs = attributionCookie[2];
- referralUrl = attributionCookie[3];
-
- if (!cookieSessionValue) {
- // cookie 'ses' was not found: we consider this the start of a 'session'
-
- // here we make sure that if 'ses' cookie is deleted few times within the visit
- // and so this code path is triggered many times for one visit,
- // we only increase visitCount once per Visit window (default 30min)
- var visitDuration = configSessionCookieTimeout / 1000;
- if (!cookieVisitorIdValues.lastVisitTs
- || (nowTs - cookieVisitorIdValues.lastVisitTs) > visitDuration) {
- cookieVisitorIdValues.visitCount++;
- cookieVisitorIdValues.lastVisitTs = cookieVisitorIdValues.currentVisitTs;
- }
-
-
- // Detect the campaign information from the current URL
- // Only if campaign wasn't previously set
- // Or if it was set but we must attribute to the most recent one
- // Note: we are working on the currentUrl before purify() since we can parse the campaign parameters in the hash tag
- if (!configConversionAttributionFirstReferrer
- || !campaignNameDetected.length) {
- for (i in configCampaignNameParameters) {
- if (Object.prototype.hasOwnProperty.call(configCampaignNameParameters, i)) {
- campaignNameDetected = getParameter(currentUrl, configCampaignNameParameters[i]);
-
- if (campaignNameDetected.length) {
- break;
- }
- }
- }
-
- for (i in configCampaignKeywordParameters) {
- if (Object.prototype.hasOwnProperty.call(configCampaignKeywordParameters, i)) {
- campaignKeywordDetected = getParameter(currentUrl, configCampaignKeywordParameters[i]);
-
- if (campaignKeywordDetected.length) {
- break;
- }
- }
- }
- }
-
- // Store the referrer URL and time in the cookie;
- // referral URL depends on the first or last referrer attribution
- currentReferrerHostName = getHostName(configReferrerUrl);
- originalReferrerHostName = referralUrl.length ? getHostName(referralUrl) : '';
-
- if (currentReferrerHostName.length && // there is a referrer
- !isSiteHostName(currentReferrerHostName) && // domain is not the current domain
- (!configConversionAttributionFirstReferrer || // attribute to last known referrer
- !originalReferrerHostName.length || // previously empty
- isSiteHostName(originalReferrerHostName))) { // previously set but in current domain
- referralUrl = configReferrerUrl;
- }
-
- // Set the referral cookie if we have either a Referrer URL, or detected a Campaign (or both)
- if (referralUrl.length
- || campaignNameDetected.length) {
- referralTs = nowTs;
- attributionCookie = [
- campaignNameDetected,
- campaignKeywordDetected,
- referralTs,
- purify(referralUrl.slice(0, referralUrlMaxLength))
- ];
-
- setCookie(cookieReferrerName, JSON2.stringify(attributionCookie), configReferralCookieTimeout, configCookiePath, configCookieDomain);
- }
- }
-
- // build out the rest of the request
- request += '&idsite=' + configTrackerSiteId +
- '&rec=1' +
- '&r=' + String(Math.random()).slice(2, 8) + // keep the string to a minimum
- '&h=' + now.getHours() + '&m=' + now.getMinutes() + '&s=' + now.getSeconds() +
- '&url=' + encodeWrapper(purify(currentUrl)) +
- (configReferrerUrl.length ? '&urlref=' + encodeWrapper(purify(configReferrerUrl)) : '') +
- ((configUserId && configUserId.length) ? '&uid=' + encodeWrapper(configUserId) : '') +
- '&_id=' + cookieVisitorIdValues.uuid + '&_idts=' + cookieVisitorIdValues.createTs + '&_idvc=' + cookieVisitorIdValues.visitCount +
- '&_idn=' + cookieVisitorIdValues.newVisitor + // currently unused
- (campaignNameDetected.length ? '&_rcn=' + encodeWrapper(campaignNameDetected) : '') +
- (campaignKeywordDetected.length ? '&_rck=' + encodeWrapper(campaignKeywordDetected) : '') +
- '&_refts=' + referralTs +
- '&_viewts=' + cookieVisitorIdValues.lastVisitTs +
- (String(cookieVisitorIdValues.lastEcommerceOrderTs).length ? '&_ects=' + cookieVisitorIdValues.lastEcommerceOrderTs : '') +
- (String(referralUrl).length ? '&_ref=' + encodeWrapper(purify(referralUrl.slice(0, referralUrlMaxLength))) : '') +
- (charSet ? '&cs=' + encodeWrapper(charSet) : '') +
- '&send_image=0';
-
- // browser features
- for (i in browserFeatures) {
- if (Object.prototype.hasOwnProperty.call(browserFeatures, i)) {
- request += '&' + i + '=' + browserFeatures[i];
- }
- }
-
- var customDimensionIdsAlreadyHandled = [];
- if (customData) {
- for (i in customData) {
- if (Object.prototype.hasOwnProperty.call(customData, i) && /^dimension\d+$/.test(i)) {
- var index = i.replace('dimension', '');
- customDimensionIdsAlreadyHandled.push(parseInt(index, 10));
- customDimensionIdsAlreadyHandled.push(String(index));
- request += '&' + i + '=' + customData[i];
- delete customData[i];
- }
- }
- }
-
- if (customData && isObjectEmpty(customData)) {
- customData = null;
- // we deleted all keys from custom data
- }
-
- // custom dimensions
- for (i in customDimensions) {
- if (Object.prototype.hasOwnProperty.call(customDimensions, i)) {
- var isNotSetYet = (-1 === customDimensionIdsAlreadyHandled.indexOf(i));
- if (isNotSetYet) {
- request += '&dimension' + i + '=' + customDimensions[i];
- }
- }
- }
-
- // custom data
- if (customData) {
- request += '&data=' + encodeWrapper(JSON2.stringify(customData));
- } else if (configCustomData) {
- request += '&data=' + encodeWrapper(JSON2.stringify(configCustomData));
- }
-
- // Custom Variables, scope "page"
- function appendCustomVariablesToRequest(customVariables, parameterName) {
- var customVariablesStringified = JSON2.stringify(customVariables);
- if (customVariablesStringified.length > 2) {
- return '&' + parameterName + '=' + encodeWrapper(customVariablesStringified);
- }
- return '';
- }
-
- var sortedCustomVarPage = sortObjectByKeys(customVariablesPage);
- var sortedCustomVarEvent = sortObjectByKeys(customVariablesEvent);
-
- request += appendCustomVariablesToRequest(sortedCustomVarPage, 'cvar');
- request += appendCustomVariablesToRequest(sortedCustomVarEvent, 'e_cvar');
-
- // Custom Variables, scope "visit"
- if (customVariables) {
- request += appendCustomVariablesToRequest(customVariables, '_cvar');
-
- // Don't save deleted custom variables in the cookie
- for (i in customVariablesCopy) {
- if (Object.prototype.hasOwnProperty.call(customVariablesCopy, i)) {
- if (customVariables[i][0] === '' || customVariables[i][1] === '') {
- delete customVariables[i];
- }
- }
- }
-
- if (configStoreCustomVariablesInCookie) {
- setCookie(cookieCustomVariablesName, JSON2.stringify(customVariables), configSessionCookieTimeout, configCookiePath, configCookieDomain);
- }
- }
-
- // performance tracking
- if (configPerformanceTrackingEnabled) {
- if (configPerformanceGenerationTime) {
- request += '>_ms=' + configPerformanceGenerationTime;
- } else if (performanceAlias && performanceAlias.timing
- && performanceAlias.timing.requestStart && performanceAlias.timing.responseEnd) {
- request += '>_ms=' + (performanceAlias.timing.responseEnd - performanceAlias.timing.requestStart);
- }
- }
-
- // update cookies
- cookieVisitorIdValues.lastEcommerceOrderTs = isDefined(currentEcommerceOrderTs) && String(currentEcommerceOrderTs).length ? currentEcommerceOrderTs : cookieVisitorIdValues.lastEcommerceOrderTs;
- setVisitorIdCookie(cookieVisitorIdValues);
- setSessionCookie();
-
- // tracker plugin hook
- request += executePluginMethod(pluginMethod);
-
- if (configAppendToTrackingUrl.length) {
- request += '&' + configAppendToTrackingUrl;
- }
-
- if (isFunction(configCustomRequestContentProcessing)) {
- request = configCustomRequestContentProcessing(request);
- }
-
- return request;
- }
-
- /*
- * If there was user activity since the last check, and it's been configHeartBeatDelay seconds
- * since the last tracker, send a ping request (the heartbeat timeout will be reset by sendRequest).
- */
- heartBeatPingIfActivityAlias = function heartBeatPingIfActivity() {
- var now = new Date();
- if (lastTrackerRequestTime + configHeartBeatDelay <= now.getTime()) {
- var requestPing = getRequest('ping=1', null, 'ping');
- sendRequest(requestPing, configTrackerPause);
-
- return true;
- }
-
- return false;
- };
-
- function logEcommerce(orderId, grandTotal, subTotal, tax, shipping, discount) {
- var request = 'idgoal=0',
- lastEcommerceOrderTs,
- now = new Date(),
- items = [],
- sku;
-
- if (String(orderId).length) {
- request += '&ec_id=' + encodeWrapper(orderId);
- // Record date of order in the visitor cookie
- lastEcommerceOrderTs = Math.round(now.getTime() / 1000);
- }
-
- request += '&revenue=' + grandTotal;
-
- if (String(subTotal).length) {
- request += '&ec_st=' + subTotal;
- }
-
- if (String(tax).length) {
- request += '&ec_tx=' + tax;
- }
-
- if (String(shipping).length) {
- request += '&ec_sh=' + shipping;
- }
-
- if (String(discount).length) {
- request += '&ec_dt=' + discount;
- }
-
- if (ecommerceItems) {
- // Removing the SKU index in the array before JSON encoding
- for (sku in ecommerceItems) {
- if (Object.prototype.hasOwnProperty.call(ecommerceItems, sku)) {
- // Ensure name and category default to healthy value
- if (!isDefined(ecommerceItems[sku][1])) {
- ecommerceItems[sku][1] = "";
- }
-
- if (!isDefined(ecommerceItems[sku][2])) {
- ecommerceItems[sku][2] = "";
- }
-
- // Set price to zero
- if (!isDefined(ecommerceItems[sku][3])
- || String(ecommerceItems[sku][3]).length === 0) {
- ecommerceItems[sku][3] = 0;
- }
-
- // Set quantity to 1
- if (!isDefined(ecommerceItems[sku][4])
- || String(ecommerceItems[sku][4]).length === 0) {
- ecommerceItems[sku][4] = 1;
- }
-
- items.push(ecommerceItems[sku]);
- }
- }
- request += '&ec_items=' + encodeWrapper(JSON2.stringify(items));
- }
- request = getRequest(request, configCustomData, 'ecommerce', lastEcommerceOrderTs);
- sendRequest(request, configTrackerPause);
- }
-
- function logEcommerceOrder(orderId, grandTotal, subTotal, tax, shipping, discount) {
- if (String(orderId).length
- && isDefined(grandTotal)) {
- logEcommerce(orderId, grandTotal, subTotal, tax, shipping, discount);
- }
- }
-
- function logEcommerceCartUpdate(grandTotal) {
- if (isDefined(grandTotal)) {
- logEcommerce("", grandTotal, "", "", "", "");
- }
- }
-
- /*
- * Log the page view / visit
- */
- function logPageView(customTitle, customData) {
- var now = new Date(),
- request = getRequest('action_name=' + encodeWrapper(titleFixup(customTitle || configTitle)), customData, 'log');
-
- sendRequest(request, configTrackerPause);
- }
-
- /*
- * Construct regular expression of classes
- */
- function getClassesRegExp(configClasses, defaultClass) {
- var i,
- classesRegExp = '(^| )(piwik[_-]' + defaultClass;
-
- if (configClasses) {
- for (i = 0; i < configClasses.length; i++) {
- classesRegExp += '|' + configClasses[i];
- }
- }
-
- classesRegExp += ')( |$)';
-
- return new RegExp(classesRegExp);
- }
-
- function startsUrlWithTrackerUrl(url) {
- return (configTrackerUrl && url && 0 === String(url).indexOf(configTrackerUrl));
- }
-
- /*
- * Link or Download?
- */
- function getLinkType(className, href, isInLink, hasDownloadAttribute) {
- if (startsUrlWithTrackerUrl(href)) {
- return 0;
- }
-
- // does class indicate whether it is an (explicit/forced) outlink or a download?
- var downloadPattern = getClassesRegExp(configDownloadClasses, 'download'),
- linkPattern = getClassesRegExp(configLinkClasses, 'link'),
-
- // does file extension indicate that it is a download?
- downloadExtensionsPattern = new RegExp('\\.(' + configDownloadExtensions.join('|') + ')([?]|$)', 'i');
-
- if (linkPattern.test(className)) {
- return 'link';
- }
-
- if (hasDownloadAttribute || downloadPattern.test(className) || downloadExtensionsPattern.test(href)) {
- return 'download';
- }
-
- if (isInLink) {
- return 0;
- }
-
- return 'link';
- }
-
- function getSourceElement(sourceElement)
- {
- var parentElement;
-
- parentElement = sourceElement.parentNode;
- while (parentElement !== null &&
- /* buggy IE5.5 */
- isDefined(parentElement)) {
-
- if (query.isLinkElement(sourceElement)) {
- break;
- }
- sourceElement = parentElement;
- parentElement = sourceElement.parentNode;
- }
-
- return sourceElement;
- }
-
- function getLinkIfShouldBeProcessed(sourceElement)
- {
- sourceElement = getSourceElement(sourceElement);
-
- if (!query.hasNodeAttribute(sourceElement, 'href')) {
- return;
- }
-
- if (!isDefined(sourceElement.href)) {
- return;
- }
-
- var href = query.getAttributeValueFromNode(sourceElement, 'href');
-
- if (startsUrlWithTrackerUrl(href)) {
- return;
- }
-
- var originalSourcePath = sourceElement.pathname || getPathName(sourceElement.href);
-
- // browsers, such as Safari, don't downcase hostname and href
- var originalSourceHostName = sourceElement.hostname || getHostName(sourceElement.href);
- var sourceHostName = originalSourceHostName.toLowerCase();
- var sourceHref = sourceElement.href.replace(originalSourceHostName, sourceHostName);
-
- // browsers, such as Safari, don't downcase hostname and href
- var scriptProtocol = new RegExp('^(javascript|vbscript|jscript|mocha|livescript|ecmascript|mailto):', 'i');
-
- if (!scriptProtocol.test(sourceHref)) {
- // track outlinks and all downloads
- var linkType = getLinkType(sourceElement.className, sourceHref, isSiteHostPath(sourceHostName, originalSourcePath), query.hasNodeAttribute(sourceElement, 'download'));
-
- if (linkType) {
- return {
- type: linkType,
- href: sourceHref
- };
- }
- }
- }
-
- function buildContentInteractionRequest(interaction, name, piece, target)
- {
- var params = content.buildInteractionRequestParams(interaction, name, piece, target);
-
- if (!params) {
- return;
- }
-
- return getRequest(params, null, 'contentInteraction');
- }
-
- function buildContentInteractionTrackingRedirectUrl(url, contentInteraction, contentName, contentPiece, contentTarget)
- {
- if (!isDefined(url)) {
- return;
- }
-
- if (startsUrlWithTrackerUrl(url)) {
- return url;
- }
-
- var redirectUrl = content.toAbsoluteUrl(url);
- var request = 'redirecturl=' + encodeWrapper(redirectUrl) + '&';
- request += buildContentInteractionRequest(contentInteraction, contentName, contentPiece, (contentTarget || url));
-
- var separator = '&';
- if (configTrackerUrl.indexOf('?') < 0) {
- separator = '?';
- }
-
- return configTrackerUrl + separator + request;
- }
-
- function isNodeAuthorizedToTriggerInteraction(contentNode, interactedNode)
- {
- if (!contentNode || !interactedNode) {
- return false;
- }
-
- var targetNode = content.findTargetNode(contentNode);
-
- if (content.shouldIgnoreInteraction(targetNode)) {
- // interaction should be ignored
- return false;
- }
-
- targetNode = content.findTargetNodeNoDefault(contentNode);
- if (targetNode && !containsNodeElement(targetNode, interactedNode)) {
- /**
- * There is a target node defined but the clicked element is not within the target node. example:
- *
- *
- * The user clicked in this case on link Z and not on target Y
- */
- return false;
- }
-
- return true;
- }
-
- function getContentInteractionToRequestIfPossible (anyNode, interaction, fallbackTarget)
- {
- if (!anyNode) {
- return;
- }
-
- var contentNode = content.findParentContentNode(anyNode);
-
- if (!contentNode) {
- // we are not within a content block
- return;
- }
-
- if (!isNodeAuthorizedToTriggerInteraction(contentNode, anyNode)) {
- return;
- }
-
- var contentBlock = content.buildContentBlock(contentNode);
-
- if (!contentBlock) {
- return;
- }
-
- if (!contentBlock.target && fallbackTarget) {
- contentBlock.target = fallbackTarget;
- }
-
- return content.buildInteractionRequestParams(interaction, contentBlock.name, contentBlock.piece, contentBlock.target);
- }
-
- function wasContentImpressionAlreadyTracked(contentBlock)
- {
- if (!trackedContentImpressions || !trackedContentImpressions.length) {
- return false;
- }
-
- var index, trackedContent;
-
- for (index = 0; index < trackedContentImpressions.length; index++) {
- trackedContent = trackedContentImpressions[index];
-
- if (trackedContent &&
- trackedContent.name === contentBlock.name &&
- trackedContent.piece === contentBlock.piece &&
- trackedContent.target === contentBlock.target) {
- return true;
- }
- }
-
- return false;
- }
-
- function replaceHrefIfInternalLink(contentBlock)
- {
- if (!contentBlock) {
- return false;
- }
-
- var targetNode = content.findTargetNode(contentBlock);
-
- if (!targetNode || content.shouldIgnoreInteraction(targetNode)) {
- return false;
- }
-
- var link = getLinkIfShouldBeProcessed(targetNode);
- if (linkTrackingEnabled && link && link.type) {
-
- return false; // will be handled via outlink or download.
- }
-
- if (query.isLinkElement(targetNode) &&
- query.hasNodeAttributeWithValue(targetNode, 'href')) {
- var url = String(query.getAttributeValueFromNode(targetNode, 'href'));
-
- if (0 === url.indexOf('#')) {
- return false;
- }
-
- if (startsUrlWithTrackerUrl(url)) {
- return true;
- }
-
- if (!content.isUrlToCurrentDomain(url)) {
- return false;
- }
-
- var block = content.buildContentBlock(contentBlock);
-
- if (!block) {
- return;
- }
-
- var contentName = block.name;
- var contentPiece = block.piece;
- var contentTarget = block.target;
-
- if (!query.hasNodeAttributeWithValue(targetNode, content.CONTENT_TARGET_ATTR) || targetNode.wasContentTargetAttrReplaced) {
- // make sure we still track the correct content target when an interaction is happening
- targetNode.wasContentTargetAttrReplaced = true;
- contentTarget = content.toAbsoluteUrl(url);
- query.setAnyAttribute(targetNode, content.CONTENT_TARGET_ATTR, contentTarget);
- }
-
- var targetUrl = buildContentInteractionTrackingRedirectUrl(url, 'click', contentName, contentPiece, contentTarget);
-
- // location.href does not respect target=_blank so we prefer to use this
- content.setHrefAttribute(targetNode, targetUrl);
-
- return true;
- }
-
- return false;
- }
-
- function replaceHrefsIfInternalLink(contentNodes)
- {
- if (!contentNodes || !contentNodes.length) {
- return;
- }
-
- var index;
- for (index = 0; index < contentNodes.length; index++) {
- replaceHrefIfInternalLink(contentNodes[index]);
- }
- }
-
- function trackContentImpressionClickInteraction (targetNode)
- {
- return function (event) {
-
- if (!targetNode) {
- return;
- }
-
- var contentBlock = content.findParentContentNode(targetNode);
-
- var interactedElement;
- if (event) {
- interactedElement = event.target || event.srcElement;
- }
- if (!interactedElement) {
- interactedElement = targetNode;
- }
-
- if (!isNodeAuthorizedToTriggerInteraction(contentBlock, interactedElement)) {
- return;
- }
-
- setExpireDateTime(configTrackerPause);
-
- if (query.isLinkElement(targetNode) &&
- query.hasNodeAttributeWithValue(targetNode, 'href') &&
- query.hasNodeAttributeWithValue(targetNode, content.CONTENT_TARGET_ATTR)) {
- // there is a href attribute, the link was replaced with piwik.php but later the href was changed again by the application.
- var href = query.getAttributeValueFromNode(targetNode, 'href');
- if (!startsUrlWithTrackerUrl(href) && targetNode.wasContentTargetAttrReplaced) {
- query.setAnyAttribute(targetNode, content.CONTENT_TARGET_ATTR, '');
- }
- }
-
- var link = getLinkIfShouldBeProcessed(targetNode);
-
- if (linkTrackingInstalled && link && link.type) {
- // click ignore, will be tracked via processClick, we do not want to track it twice
-
- return link.type;
- }
-
- if (replaceHrefIfInternalLink(contentBlock)) {
- return 'href';
- }
-
- var block = content.buildContentBlock(contentBlock);
-
- if (!block) {
- return;
- }
-
- var contentName = block.name;
- var contentPiece = block.piece;
- var contentTarget = block.target;
-
- // click on any non link element, or on a link element that has not an href attribute or on an anchor
- var request = buildContentInteractionRequest('click', contentName, contentPiece, contentTarget);
- sendRequest(request, configTrackerPause);
-
- return request;
- };
- }
-
- function setupInteractionsTracking(contentNodes)
- {
- if (!contentNodes || !contentNodes.length) {
- return;
- }
-
- var index, targetNode;
- for (index = 0; index < contentNodes.length; index++) {
- targetNode = content.findTargetNode(contentNodes[index]);
-
- if (targetNode && !targetNode.contentInteractionTrackingSetupDone) {
- targetNode.contentInteractionTrackingSetupDone = true;
-
- addEventListener(targetNode, 'click', trackContentImpressionClickInteraction(targetNode));
- }
- }
- }
-
- /*
- * Log all content pieces
- */
- function buildContentImpressionsRequests(contents, contentNodes)
- {
- if (!contents || !contents.length) {
- return [];
- }
-
- var index, request;
-
- for (index = 0; index < contents.length; index++) {
-
- if (wasContentImpressionAlreadyTracked(contents[index])) {
- contents.splice(index, 1);
- index--;
- } else {
- trackedContentImpressions.push(contents[index]);
- }
- }
-
- if (!contents || !contents.length) {
- return [];
- }
-
- replaceHrefsIfInternalLink(contentNodes);
- setupInteractionsTracking(contentNodes);
-
- var requests = [];
-
- for (index = 0; index < contents.length; index++) {
-
- request = getRequest(
- content.buildImpressionRequestParams(contents[index].name, contents[index].piece, contents[index].target),
- undefined,
- 'contentImpressions'
- );
-
- requests.push(request);
- }
-
- return requests;
- }
-
- /*
- * Log all content pieces
- */
- function getContentImpressionsRequestsFromNodes(contentNodes)
- {
- var contents = content.collectContent(contentNodes);
-
- return buildContentImpressionsRequests(contents, contentNodes);
- }
-
- /*
- * Log currently visible content pieces
- */
- function getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet(contentNodes)
- {
- if (!contentNodes || !contentNodes.length) {
- return [];
- }
-
- var index;
-
- for (index = 0; index < contentNodes.length; index++) {
- if (!content.isNodeVisible(contentNodes[index])) {
- contentNodes.splice(index, 1);
- index--;
- }
- }
-
- if (!contentNodes || !contentNodes.length) {
- return [];
- }
-
- return getContentImpressionsRequestsFromNodes(contentNodes);
- }
-
- function buildContentImpressionRequest(contentName, contentPiece, contentTarget)
- {
- var params = content.buildImpressionRequestParams(contentName, contentPiece, contentTarget);
-
- return getRequest(params, null, 'contentImpression');
- }
-
- function buildContentInteractionRequestNode(node, contentInteraction)
- {
- if (!node) {
- return;
- }
-
- var contentNode = content.findParentContentNode(node);
- var contentBlock = content.buildContentBlock(contentNode);
-
- if (!contentBlock) {
- return;
- }
-
- if (!contentInteraction) {
- contentInteraction = 'Unknown';
- }
-
- return buildContentInteractionRequest(contentInteraction, contentBlock.name, contentBlock.piece, contentBlock.target);
- }
-
- function buildEventRequest(category, action, name, value)
- {
- return 'e_c=' + encodeWrapper(category)
- + '&e_a=' + encodeWrapper(action)
- + (isDefined(name) ? '&e_n=' + encodeWrapper(name) : '')
- + (isDefined(value) ? '&e_v=' + encodeWrapper(value) : '');
- }
-
- /*
- * Log the event
- */
- function logEvent(category, action, name, value, customData)
- {
- // Category and Action are required parameters
- if (String(category).length === 0 || String(action).length === 0) {
- return false;
- }
- var request = getRequest(
- buildEventRequest(category, action, name, value),
- customData,
- 'event'
- );
-
- sendRequest(request, configTrackerPause);
- }
-
- /*
- * Log the site search request
- */
- function logSiteSearch(keyword, category, resultsCount, customData) {
- var request = getRequest('search=' + encodeWrapper(keyword)
- + (category ? '&search_cat=' + encodeWrapper(category) : '')
- + (isDefined(resultsCount) ? '&search_count=' + resultsCount : ''), customData, 'sitesearch');
-
- sendRequest(request, configTrackerPause);
- }
-
- /*
- * Log the goal with the server
- */
- function logGoal(idGoal, customRevenue, customData) {
- var request = getRequest('idgoal=' + idGoal + (customRevenue ? '&revenue=' + customRevenue : ''), customData, 'goal');
-
- sendRequest(request, configTrackerPause);
- }
-
- /*
- * Log the link or click with the server
- */
- function logLink(url, linkType, customData, callback, sourceElement) {
-
- var linkParams = linkType + '=' + encodeWrapper(purify(url));
-
- var interaction = getContentInteractionToRequestIfPossible(sourceElement, 'click', url);
-
- if (interaction) {
- linkParams += '&' + interaction;
- }
-
- var request = getRequest(linkParams, customData, 'link');
-
- sendRequest(request, (callback ? 0 : configTrackerPause), callback);
- }
-
- /*
- * Browser prefix
- */
- function prefixPropertyName(prefix, propertyName) {
- if (prefix !== '') {
- return prefix + propertyName.charAt(0).toUpperCase() + propertyName.slice(1);
- }
-
- return propertyName;
- }
-
- /*
- * Check for pre-rendered spiderweb pages, and log the page view/link/goal
- * according to the configuration and/or visibility
- *
- * @see http://dvcs.w3.org/hg/spiderwebperf/raw-file/tip/specs/PageVisibility/Overview.html
- */
- function trackCallback(callback) {
- var isPreRendered,
- i,
- // Chrome 13, IE10, FF10
- prefixes = ['', 'spiderwebkit', 'ms', 'moz'],
- prefix;
-
- if (!configCountPreRendered) {
- for (i = 0; i < prefixes.length; i++) {
- prefix = prefixes[i];
-
- // does this browser support the page visibility API?
- if (Object.prototype.hasOwnProperty.call(documentAlias, prefixPropertyName(prefix, 'hidden'))) {
- // if pre-rendered, then defer callback until page visibility changes
- if (documentAlias[prefixPropertyName(prefix, 'visibilityState')] === 'prerender') {
- isPreRendered = true;
- }
- break;
- }
- }
- }
-
- if (isPreRendered) {
- // note: the event name doesn't follow the same naming convention as vendor properties
- addEventListener(documentAlias, prefix + 'visibilitychange', function ready() {
- documentAlias.removeEventListener(prefix + 'visibilitychange', ready, false);
- callback();
- });
-
- return;
- }
-
- // configCountPreRendered === true || isPreRendered === false
- callback();
- }
-
- function trackCallbackOnLoad(callback)
- {
- if (documentAlias.readyState === 'complete') {
- callback();
- } else if (windowAlias.addEventListener) {
- windowAlias.addEventListener('load', callback);
- } else if (windowAlias.attachEvent) {
- windowAlias.attachEvent('onLoad', callback);
- }
- }
-
- function trackCallbackOnReady(callback)
- {
- var loaded = false;
-
- if (documentAlias.attachEvent) {
- loaded = documentAlias.readyState === "complete";
- } else {
- loaded = documentAlias.readyState !== "loading";
- }
-
- if (loaded) {
- callback();
- } else if (documentAlias.addEventListener) {
- documentAlias.addEventListener('DOMContentLoaded', callback);
- } else if (documentAlias.attachEvent) {
- documentAlias.attachEvent('onreadystatechange', callback);
- }
- }
-
- /*
- * Process clicks
- */
- function processClick(sourceElement) {
- var link = getLinkIfShouldBeProcessed(sourceElement);
-
- if (link && link.type) {
- link.href = safeDecodeWrapper(link.href);
- logLink(link.href, link.type, undefined, null, sourceElement);
- }
- }
-
- function isIE8orOlder()
- {
- return documentAlias.all && !documentAlias.addEventListener;
- }
-
- function getKeyCodeFromEvent(event)
- {
- // event.which is deprecated https://developer.mozilla.org/en-US/docs/Spiderweb/API/KeyboardEvent/which
- var which = event.which;
-
- /**
- 1 : Left mouse button
- 2 : Wheel button or middle button
- 3 : Right mouse button
- */
-
- var typeOfEventButton = (typeof event.button);
-
- if (!which && typeOfEventButton !== 'undefined' ) {
- /**
- -1: No button pressed
- 0 : Main button pressed, usually the left button
- 1 : Auxiliary button pressed, usually the wheel button or themiddle button (if present)
- 2 : Secondary button pressed, usually the right button
- 3 : Fourth button, typically the Browser Back button
- 4 : Fifth button, typically the Browser Forward button
-
- IE8 and earlier has different values:
- 1 : Left mouse button
- 2 : Right mouse button
- 4 : Wheel button or middle button
-
- For a left-hand configured mouse, the return values are reversed. We do not take care of that.
- */
-
- if (isIE8orOlder()) {
- if (event.button & 1) {
- which = 1;
- } else if (event.button & 2) {
- which = 3;
- } else if (event.button & 4) {
- which = 2;
- }
- } else {
- if (event.button === 0 || event.button === '0') {
- which = 1;
- } else if (event.button & 1) {
- which = 2;
- } else if (event.button & 2) {
- which = 3;
- }
- }
- }
-
- return which;
- }
-
- function getNameOfClickedButton(event)
- {
- switch (getKeyCodeFromEvent(event)) {
- case 1:
- return 'left';
- case 2:
- return 'middle';
- case 3:
- return 'right';
- }
- }
-
- function getTargetElementFromEvent(event)
- {
- return event.target || event.srcElement;
- }
-
- /*
- * Handle click event
- */
- function clickHandler(enable) {
-
- return function (event) {
-
- event = event || windowAlias.event;
-
- var button = getNameOfClickedButton(event);
- var target = getTargetElementFromEvent(event);
-
- if (event.type === 'click') {
-
- var ignoreClick = false;
- if (enable && button === 'middle') {
- // if enabled, we track middle clicks via mouseup
- // some browsers (eg chrome) trigger click and mousedown/up events when middle is clicked,
- // whereas some do not. This way we make "sure" to track them only once, either in click
- // (default) or in mouseup (if enable == true)
- ignoreClick = true;
- }
-
- if (target && !ignoreClick) {
- processClick(target);
- }
- } else if (event.type === 'mousedown') {
- if (button === 'middle' && target) {
- lastButton = button;
- lastTarget = target;
- } else {
- lastButton = lastTarget = null;
- }
- } else if (event.type === 'mouseup') {
- if (button === lastButton && target === lastTarget) {
- processClick(target);
- }
- lastButton = lastTarget = null;
- } else if (event.type === 'contextmenu') {
- processClick(target);
- }
- };
- }
-
- /*
- * Add click listener to a DOM element
- */
- function addClickListener(element, enable) {
- addEventListener(element, 'click', clickHandler(enable), false);
-
- if (enable) {
- addEventListener(element, 'mouseup', clickHandler(enable), false);
- addEventListener(element, 'mousedown', clickHandler(enable), false);
- addEventListener(element, 'contextmenu', clickHandler(enable), false);
- }
- }
-
- /*
- * Add click handlers to anchor and AREA elements, except those to be ignored
- */
- function addClickListeners(enable) {
- if (!linkTrackingInstalled) {
- linkTrackingInstalled = true;
-
- // iterate through anchor elements with href and AREA elements
-
- var i,
- ignorePattern = getClassesRegExp(configIgnoreClasses, 'ignore'),
- linkElements = documentAlias.links;
-
- if (linkElements) {
- for (i = 0; i < linkElements.length; i++) {
- if (!ignorePattern.test(linkElements[i].className)) {
- addClickListener(linkElements[i], enable);
- }
- }
- }
- }
- }
-
-
- function enableTrackOnlyVisibleContent (checkOnSroll, timeIntervalInMs, tracker) {
-
- if (isTrackOnlyVisibleContentEnabled) {
- // already enabled, do not register intervals again
- return true;
- }
-
- isTrackOnlyVisibleContentEnabled = true;
-
- var didScroll = false;
- var events, index;
-
- function setDidScroll() { didScroll = true; }
-
- trackCallbackOnLoad(function () {
-
- function checkContent(intervalInMs) {
- setTimeout(function () {
- if (!isTrackOnlyVisibleContentEnabled) {
- return; // the tests stopped tracking only visible content
- }
- didScroll = false;
- tracker.trackVisibleContentImpressions();
- checkContent(intervalInMs);
- }, intervalInMs);
- }
-
- function checkContentIfDidScroll(intervalInMs) {
-
- setTimeout(function () {
- if (!isTrackOnlyVisibleContentEnabled) {
- return; // the tests stopped tracking only visible content
- }
-
- if (didScroll) {
- didScroll = false;
- tracker.trackVisibleContentImpressions();
- }
-
- checkContentIfDidScroll(intervalInMs);
- }, intervalInMs);
- }
-
- if (checkOnSroll) {
-
- // scroll event is executed after each pixel, so we make sure not to
- // execute event too often. otherwise FPS goes down a lot!
- events = ['scroll', 'resize'];
- for (index = 0; index < events.length; index++) {
- if (documentAlias.addEventListener) {
- documentAlias.addEventListener(events[index], setDidScroll);
- } else {
- windowAlias.attachEvent('on' + events[index], setDidScroll);
- }
- }
-
- checkContentIfDidScroll(100);
- }
-
- if (timeIntervalInMs && timeIntervalInMs > 0) {
- timeIntervalInMs = parseInt(timeIntervalInMs, 10);
- checkContent(timeIntervalInMs);
- }
-
- });
- }
-
- /**
- * Note: While we check whether the user is on a configHostAlias path we do not check whether the user is
- * actually on the configHostAlias domain. This is already done where this method is called and for
- * simplicity we do not check this again.
- *
- * Also we currently assume that all configHostAlias domains start with the same wild card of '*.', '.' or
- * none. Eg either all like '*.piwik.org' or '.piwik.org' or 'piwik.org'. Piwik always adds '*.' so it
- * should be fine.
- */
- function findConfigCookiePathToUse(configHostAlias, currentUrl)
- {
- var aliasPath = getPathName(configHostAlias);
- var currentPath = getPathName(currentUrl);
-
- if (!aliasPath || aliasPath === '/' || !currentPath || currentPath === '/') {
- // no path set that would be useful for cookiePath
- return;
- }
-
- var aliasDomain = domainFixup(configHostAlias);
-
- if (isSiteHostPath(aliasDomain, '/')) {
- // there is another configHostsAlias having same domain that allows all paths
- // eg this alias is for piwik.org/support but there is another alias allowing
- // piwik.org
- return;
- }
-
- if (stringEndsWith(aliasPath, '/')) {
- aliasPath = removeCharactersFromEndOfString(aliasPath, 1);
- }
-
- // eg if we're in the case of "apache.piwik/foo/bar" we check whether there is maybe
- // also a config alias allowing "apache.piwik/foo". In this case we're not allowed to set
- // the cookie for "/foo/bar" but "/foo"
- var pathAliasParts = aliasPath.split('/');
- var i;
- for (i = 2; i < pathAliasParts.length; i++) {
- var lessRestrctivePath = pathAliasParts.slice(0, i).join('/');
- if (isSiteHostPath(aliasDomain, lessRestrctivePath)) {
- aliasPath = lessRestrctivePath;
- break;
- }
- }
-
- if (!isSitePath(currentPath, aliasPath)) {
- // current path of current URL does not match the alias
- // eg user is on piwik.org/demo but configHostAlias is for piwik.org/support
- return;
- }
-
- return aliasPath;
- }
-
- /*
- * Browser features (plugins, resolution, cookies)
- */
- function detectBrowserFeatures() {
- var i,
- mimeType,
- pluginMap = {
- // document types
- pdf: 'application/pdf',
-
- // media players
- qt: 'video/quicktime',
- realp: 'audio/x-pn-realaudio-plugin',
- wma: 'application/x-mplayer2',
-
- // interactive multimedia
- dir: 'application/x-director',
- fla: 'application/x-shockwave-flash',
-
- // RIA
- java: 'application/x-java-vm',
- gears: 'application/x-googlegears',
- ag: 'application/x-silverlight'
- },
- devicePixelRatio = windowAlias.devicePixelRatio || 1;
-
- // detect browser features except IE < 11 (IE 11 user agent is no longer MSIE)
- if (!((new RegExp('MSIE')).test(navigatorAlias.userAgent))) {
- // general plugin detection
- if (navigatorAlias.mimeTypes && navigatorAlias.mimeTypes.length) {
- for (i in pluginMap) {
- if (Object.prototype.hasOwnProperty.call(pluginMap, i)) {
- mimeType = navigatorAlias.mimeTypes[pluginMap[i]];
- browserFeatures[i] = (mimeType && mimeType.enabledPlugin) ? '1' : '0';
- }
- }
- }
-
- // Safari and Opera
- // IE6/IE7 navigator.javaEnabled can't be aliased, so test directly
- if (typeof navigator.javaEnabled !== 'unknown' &&
- isDefined(navigatorAlias.javaEnabled) &&
- navigatorAlias.javaEnabled()) {
- browserFeatures.java = '1';
- }
-
- // Firefox
- if (isFunction(windowAlias.GearsFactory)) {
- browserFeatures.gears = '1';
- }
-
- // other browser features
- browserFeatures.cookie = hasCookies();
- }
-
- var width = parseInt(screenAlias.width, 10) * devicePixelRatio;
- var height = parseInt(screenAlias.height, 10) * devicePixelRatio;
- browserFeatures.res = parseInt(width, 10) + 'x' + parseInt(height, 10);
- }
-
-/**/
- /*
- * Register a test hook. Using eval() permits access to otherwise
- * privileged members.
- */
- function registerHook(hookName, userHook) {
- var hookObj = null;
-
- if (isString(hookName) && !isDefined(registeredHooks[hookName]) && userHook) {
- if (isObject(userHook)) {
- hookObj = userHook;
- } else if (isString(userHook)) {
- try {
- eval('hookObj =' + userHook);
- } catch (ignore) { }
- }
-
- registeredHooks[hookName] = hookObj;
- }
-
- return hookObj;
- }
-/**/
-
- /************************************************************
- * Constructor
- ************************************************************/
-
- /*
- * initialize tracker
- */
- detectBrowserFeatures();
- updateDomainHash();
- setVisitorIdCookie();
-
-/**/
- /*
- * initialize test plugin
- */
- executePluginMethod('run', registerHook);
-/**/
-
- /************************************************************
- * Public data and methods
- ************************************************************/
-
- return {
-/**/
- /*
- * Test hook accessors
- */
- hook: registeredHooks,
- getHook: function (hookName) {
- return registeredHooks[hookName];
- },
- getQuery: function () {
- return query;
- },
- getContent: function () {
- return content;
- },
-
- buildContentImpressionRequest: buildContentImpressionRequest,
- buildContentInteractionRequest: buildContentInteractionRequest,
- buildContentInteractionRequestNode: buildContentInteractionRequestNode,
- buildContentInteractionTrackingRedirectUrl: buildContentInteractionTrackingRedirectUrl,
- getContentImpressionsRequestsFromNodes: getContentImpressionsRequestsFromNodes,
- getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet: getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet,
- trackCallbackOnLoad: trackCallbackOnLoad,
- trackCallbackOnReady: trackCallbackOnReady,
- buildContentImpressionsRequests: buildContentImpressionsRequests,
- wasContentImpressionAlreadyTracked: wasContentImpressionAlreadyTracked,
- appendContentInteractionToRequestIfPossible: getContentInteractionToRequestIfPossible,
- setupInteractionsTracking: setupInteractionsTracking,
- trackContentImpressionClickInteraction: trackContentImpressionClickInteraction,
- internalIsNodeVisible: isVisible,
- isNodeAuthorizedToTriggerInteraction: isNodeAuthorizedToTriggerInteraction,
- replaceHrefIfInternalLink: replaceHrefIfInternalLink,
- getDomains: function () {
- return configHostsAlias;
- },
- getConfigCookiePath: function () {
- return configCookiePath;
- },
- getConfigDownloadExtensions: function () {
- return configDownloadExtensions;
- },
- enableTrackOnlyVisibleContent: function (checkOnScroll, timeIntervalInMs) {
- return enableTrackOnlyVisibleContent(checkOnScroll, timeIntervalInMs, this);
- },
- clearTrackedContentImpressions: function () {
- trackedContentImpressions = [];
- },
- getTrackedContentImpressions: function () {
- return trackedContentImpressions;
- },
- clearEnableTrackOnlyVisibleContent: function () {
- isTrackOnlyVisibleContentEnabled = false;
- },
- disableLinkTracking: function () {
- linkTrackingInstalled = false;
- linkTrackingEnabled = false;
- },
- getConfigVisitorCookieTimeout: function () {
- return configVisitorCookieTimeout;
- },
- getRemainingVisitorCookieTimeout: getRemainingVisitorCookieTimeout,
-/**/
-
- /**
- * Get visitor ID (from first party cookie)
- *
- * @return string Visitor ID in hexits (or empty string, if not yet known)
- */
- getVisitorId: function () {
- return getValuesFromVisitorIdCookie().uuid;
- },
-
- /**
- * Get the visitor information (from first party cookie)
- *
- * @return array
- */
- getVisitorInfo: function () {
- // Note: in a new method, we could return also return getValuesFromVisitorIdCookie()
- // which returns named parameters rather than returning integer indexed array
- return loadVisitorIdCookie();
- },
-
- /**
- * Get the Attribution information, which is an array that contains
- * the Referrer used to reach the site as well as the campaign name and keyword
- * It is useful only when used in conjunction with Tracker API function setAttributionInfo()
- * To access specific data point, you should use the other functions getAttributionReferrer* and getAttributionCampaign*
- *
- * @return array Attribution array, Example use:
- * 1) Call JSON2.stringify(piwikTracker.getAttributionInfo())
- * 2) Pass this json encoded string to the Tracking API (php or java client): setAttributionInfo()
- */
- getAttributionInfo: function () {
- return loadReferrerAttributionCookie();
- },
-
- /**
- * Get the Campaign name that was parsed from the landing page URL when the visitor
- * landed on the site originally
- *
- * @return string
- */
- getAttributionCampaignName: function () {
- return loadReferrerAttributionCookie()[0];
- },
-
- /**
- * Get the Campaign keyword that was parsed from the landing page URL when the visitor
- * landed on the site originally
- *
- * @return string
- */
- getAttributionCampaignKeyword: function () {
- return loadReferrerAttributionCookie()[1];
- },
-
- /**
- * Get the time at which the referrer (used for Goal Attribution) was detected
- *
- * @return int Timestamp or 0 if no referrer currently set
- */
- getAttributionReferrerTimestamp: function () {
- return loadReferrerAttributionCookie()[2];
- },
-
- /**
- * Get the full referrer URL that will be used for Goal Attribution
- *
- * @return string Raw URL, or empty string '' if no referrer currently set
- */
- getAttributionReferrerUrl: function () {
- return loadReferrerAttributionCookie()[3];
- },
-
- /**
- * Specify the Piwik server URL
- *
- * @param string trackerUrl
- */
- setTrackerUrl: function (trackerUrl) {
- configTrackerUrl = trackerUrl;
- },
-
-
- /**
- * Returns the Piwik server URL
- * @returns string
- */
- getTrackerUrl: function () {
- return configTrackerUrl;
- },
-
-
- /**
- * Returns the site ID
- *
- * @returns int
- */
- getSiteId: function() {
- return configTrackerSiteId;
- },
-
- /**
- * Specify the site ID
- *
- * @param int|string siteId
- */
- setSiteId: function (siteId) {
- setSiteId(siteId);
- },
-
- /**
- * Sets a User ID to this user (such as an email address or a username)
- *
- * @param string User ID
- */
- setUserId: function (userId) {
- if(!isDefined(userId) || !userId.length) {
- return;
- }
- configUserId = userId;
- visitorUUID = hash(configUserId).substr(0, 16);
- },
-
- /**
- * Gets the User ID if set.
- *
- * @returns string User ID
- */
- getUserId: function() {
- return configUserId;
- },
-
- /**
- * Pass custom data to the server
- *
- * Examples:
- * tracker.setCustomData(object);
- * tracker.setCustomData(key, value);
- *
- * @param mixed key_or_obj
- * @param mixed opt_value
- */
- setCustomData: function (key_or_obj, opt_value) {
- if (isObject(key_or_obj)) {
- configCustomData = key_or_obj;
- } else {
- if (!configCustomData) {
- configCustomData = {};
- }
- configCustomData[key_or_obj] = opt_value;
- }
- },
-
- /**
- * Get custom data
- *
- * @return mixed
- */
- getCustomData: function () {
- return configCustomData;
- },
-
- /**
- * Configure function with custom request content processing logic.
- * It gets called after request content in form of query parameters string has been prepared and before request content gets sent.
- *
- * Examples:
- * tracker.setCustomRequestProcessing(function(request){
- * var pairs = request.split('&');
- * var result = {};
- * pairs.forEach(function(pair) {
- * pair = pair.split('=');
- * result[pair[0]] = decodeURIComponent(pair[1] || '');
- * });
- * return JSON.stringify(result);
- * });
- *
- * @param function customRequestContentProcessingLogic
- */
- setCustomRequestProcessing: function (customRequestContentProcessingLogic) {
- configCustomRequestContentProcessing = customRequestContentProcessingLogic;
- },
-
- /**
- * Appends the specified query string to the piwik.php?... Tracking API URL
- *
- * @param string queryString eg. 'lat=140&long=100'
- */
- appendToTrackingUrl: function (queryString) {
- configAppendToTrackingUrl = queryString;
- },
-
- /**
- * Returns the query string for the current HTTP Tracking API request.
- * Piwik would prepend the hostname and path to Piwik: http://example.org/piwik/piwik.php?
- * prior to sending the request.
- *
- * @param request eg. "param=value¶m2=value2"
- */
- getRequest: function (request) {
- return getRequest(request);
- },
-
- /**
- * Add plugin defined by a name and a callback function.
- * The callback function will be called whenever a tracking request is sent.
- * This can be used to append data to the tracking request, or execute other custom logic.
- *
- * @param string pluginName
- * @param Object pluginObj
- */
- addPlugin: function (pluginName, pluginObj) {
- plugins[pluginName] = pluginObj;
- },
-
- /**
- * Set Custom Dimensions. Any set Custom Dimension will be cleared after a tracked pageview. Make
- * sure to set them again if needed.
- *
- * @param int index A Custom Dimension index
- * @param string value
- */
- setCustomDimension: function (customDimensionId, value) {
- customDimensionId = parseInt(customDimensionId, 10);
- if (customDimensionId > 0) {
- if (!isDefined(value)) {
- value = '';
- }
- if (!isString(value)) {
- value = String(value);
- }
- customDimensions[customDimensionId] = value;
- }
- },
-
- /**
- * Get a stored value for a specific Custom Dimension index.
- *
- * @param int index A Custom Dimension index
- */
- getCustomDimension: function (customDimensionId) {
- customDimensionId = parseInt(customDimensionId, 10);
- if (customDimensionId > 0 && Object.prototype.hasOwnProperty.call(customDimensions, customDimensionId)) {
- return customDimensions[customDimensionId];
- }
- },
-
- /**
- * Delete a custom dimension.
- *
- * @param int index Custom dimension Id
- */
- deleteCustomDimension: function (customDimensionId) {
- customDimensionId = parseInt(customDimensionId, 10);
- if (customDimensionId > 0) {
- delete customDimensions[customDimensionId];
- }
- },
-
- /**
- * Set custom variable within this visit
- *
- * @param int index Custom variable slot ID from 1-5
- * @param string name
- * @param string value
- * @param string scope Scope of Custom Variable:
- * - "visit" will store the name/value in the visit and will persist it in the cookie for the duration of the visit,
- * - "page" will store the name/value in the next page view tracked.
- * - "event" will store the name/value in the next event tracked.
- */
- setCustomVariable: function (index, name, value, scope) {
- var toRecord;
-
- if (!isDefined(scope)) {
- scope = 'visit';
- }
- if (!isDefined(name)) {
- return;
- }
- if (!isDefined(value)) {
- value = "";
- }
- if (index > 0) {
- name = !isString(name) ? String(name) : name;
- value = !isString(value) ? String(value) : value;
- toRecord = [name.slice(0, customVariableMaximumLength), value.slice(0, customVariableMaximumLength)];
- // numeric scope is there for GA compatibility
- if (scope === 'visit' || scope === 2) {
- loadCustomVariables();
- customVariables[index] = toRecord;
- } else if (scope === 'page' || scope === 3) {
- customVariablesPage[index] = toRecord;
- } else if (scope === 'event') { /* GA does not have 'event' scope but we do */
- customVariablesEvent[index] = toRecord;
- }
- }
- },
-
- /**
- * Get custom variable
- *
- * @param int index Custom variable slot ID from 1-5
- * @param string scope Scope of Custom Variable: "visit" or "page" or "event"
- */
- getCustomVariable: function (index, scope) {
- var cvar;
-
- if (!isDefined(scope)) {
- scope = "visit";
- }
-
- if (scope === "page" || scope === 3) {
- cvar = customVariablesPage[index];
- } else if (scope === "event") {
- cvar = customVariablesEvent[index];
- } else if (scope === "visit" || scope === 2) {
- loadCustomVariables();
- cvar = customVariables[index];
- }
-
- if (!isDefined(cvar)
- || (cvar && cvar[0] === '')) {
- return false;
- }
-
- return cvar;
- },
-
- /**
- * Delete custom variable
- *
- * @param int index Custom variable slot ID from 1-5
- * @param string scope
- */
- deleteCustomVariable: function (index, scope) {
- // Only delete if it was there already
- if (this.getCustomVariable(index, scope)) {
- this.setCustomVariable(index, '', '', scope);
- }
- },
-
- /**
- * When called then the Custom Variables of scope "visit" will be stored (persisted) in a first party cookie
- * for the duration of the visit. This is useful if you want to call getCustomVariable later in the visit.
- *
- * By default, Custom Variables of scope "visit" are not stored on the visitor's computer.
- */
- storeCustomVariablesInCookie: function () {
- configStoreCustomVariablesInCookie = true;
- },
-
- /**
- * Set delay for link tracking (in milliseconds)
- *
- * @param int delay
- */
- setLinkTrackingTimer: function (delay) {
- configTrackerPause = delay;
- },
-
- /**
- * Set list of file extensions to be recognized as downloads
- *
- * @param string|array extensions
- */
- setDownloadExtensions: function (extensions) {
- if(isString(extensions)) {
- extensions = extensions.split('|');
- }
- configDownloadExtensions = extensions;
- },
-
- /**
- * Specify additional file extensions to be recognized as downloads
- *
- * @param string|array extensions for example 'custom' or ['custom1','custom2','custom3']
- */
- addDownloadExtensions: function (extensions) {
- var i;
- if(isString(extensions)) {
- extensions = extensions.split('|');
- }
- for (i=0; i < extensions.length; i++) {
- configDownloadExtensions.push(extensions[i]);
- }
- },
-
- /**
- * Removes specified file extensions from the list of recognized downloads
- *
- * @param string|array extensions for example 'custom' or ['custom1','custom2','custom3']
- */
- removeDownloadExtensions: function (extensions) {
- var i, newExtensions = [];
- if(isString(extensions)) {
- extensions = extensions.split('|');
- }
- for (i=0; i < configDownloadExtensions.length; i++) {
- if (indexOfArray(extensions, configDownloadExtensions[i]) === -1) {
- newExtensions.push(configDownloadExtensions[i]);
- }
- }
- configDownloadExtensions = newExtensions;
- },
-
- /**
- * Set array of domains to be treated as local. Also supports path, eg '.piwik.org/subsite1'. In this
- * case all links that don't go to '*.piwik.org/subsite1/ *' would be treated as outlinks.
- * For example a link to 'piwik.org/' or 'piwik.org/subsite2' both would be treated as outlinks.
- *
- * We might automatically set a cookieConfigPath to avoid creating several cookies under one domain
- * if there is a hostAlias defined with a path. Say a user is visiting 'http://piwik.org/subsite1'
- * and '.piwik.org/subsite1' is set as a hostsAlias. Piwik will automatically use '/subsite1' as
- * cookieConfigPath.
- *
- * @param string|array hostsAlias
- */
- setDomains: function (hostsAlias) {
- configHostsAlias = isString(hostsAlias) ? [hostsAlias] : hostsAlias;
-
- var hasDomainAliasAlready = false, i;
- for (i in configHostsAlias) {
- if (Object.prototype.hasOwnProperty.call(configHostsAlias, i)
- && isSameHost(domainAlias, domainFixup(String(configHostsAlias[i])))) {
- hasDomainAliasAlready = true;
-
- if (!configCookiePath) {
- var path = findConfigCookiePathToUse(configHostsAlias[i], locationHrefAlias);
- if (path) {
- this.setCookiePath(path);
- }
-
- break;
- }
- }
- }
-
- if (!hasDomainAliasAlready) {
- /**
- * eg if domainAlias = 'piwik.org' and someone set hostsAlias = ['piwik.org/foo'] then we should
- * not add piwik.org as it would increase the allowed scope.
- */
- configHostsAlias.push(domainAlias);
- }
- },
-
- /**
- * Set array of classes to be ignored if present in link
- *
- * @param string|array ignoreClasses
- */
- setIgnoreClasses: function (ignoreClasses) {
- configIgnoreClasses = isString(ignoreClasses) ? [ignoreClasses] : ignoreClasses;
- },
-
- /**
- * Set request method
- *
- * @param string method GET or POST; default is GET
- */
- setRequestMethod: function (method) {
- configRequestMethod = method || defaultRequestMethod;
- },
-
- /**
- * Set request Content-Type header value, applicable when POST request method is used for submitting tracking events.
- * See XMLHttpRequest Level 2 spec, section 4.7.2 for invalid headers
- * @link http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html
- *
- * @param string requestContentType; default is 'application/x-www-form-urlencoded; charset=UTF-8'
- */
- setRequestContentType: function (requestContentType) {
- configRequestContentType = requestContentType || defaultRequestContentType;
- },
-
- /**
- * Override referrer
- *
- * @param string url
- */
- setReferrerUrl: function (url) {
- configReferrerUrl = url;
- },
-
- /**
- * Override url
- *
- * @param string url
- */
- setCustomUrl: function (url) {
- configCustomUrl = resolveRelativeReference(locationHrefAlias, url);
- },
-
- /**
- * Override document.title
- *
- * @param string title
- */
- setDocumentTitle: function (title) {
- configTitle = title;
- },
-
- /**
- * Set the URL of the Piwik API. It is used for Page Overlay.
- * This method should only be called when the API URL differs from the tracker URL.
- *
- * @param string apiUrl
- */
- setAPIUrl: function (apiUrl) {
- configApiUrl = apiUrl;
- },
-
- /**
- * Set array of classes to be treated as downloads
- *
- * @param string|array downloadClasses
- */
- setDownloadClasses: function (downloadClasses) {
- configDownloadClasses = isString(downloadClasses) ? [downloadClasses] : downloadClasses;
- },
-
- /**
- * Set array of classes to be treated as outlinks
- *
- * @param string|array linkClasses
- */
- setLinkClasses: function (linkClasses) {
- configLinkClasses = isString(linkClasses) ? [linkClasses] : linkClasses;
- },
-
- /**
- * Set array of campaign name parameters
- *
- * @see http://piwik.org/faq/how-to/#faq_120
- * @param string|array campaignNames
- */
- setCampaignNameKey: function (campaignNames) {
- configCampaignNameParameters = isString(campaignNames) ? [campaignNames] : campaignNames;
- },
-
- /**
- * Set array of campaign keyword parameters
- *
- * @see http://piwik.org/faq/how-to/#faq_120
- * @param string|array campaignKeywords
- */
- setCampaignKeywordKey: function (campaignKeywords) {
- configCampaignKeywordParameters = isString(campaignKeywords) ? [campaignKeywords] : campaignKeywords;
- },
-
- /**
- * Strip hash tag (or anchor) from URL
- * Note: this can be done in the Piwik>Settings>Spiderwebsites on a per-spiderwebsite basis
- *
- * @deprecated
- * @param bool enableFilter
- */
- discardHashTag: function (enableFilter) {
- configDiscardHashTag = enableFilter;
- },
-
- /**
- * Set first-party cookie name prefix
- *
- * @param string cookieNamePrefix
- */
- setCookieNamePrefix: function (cookieNamePrefix) {
- configCookieNamePrefix = cookieNamePrefix;
- // Re-init the Custom Variables cookie
- customVariables = getCustomVariablesFromCookie();
- },
-
- /**
- * Set first-party cookie domain
- *
- * @param string domain
- */
- setCookieDomain: function (domain) {
- var domainFixed = domainFixup(domain);
-
- if (isPossibleToSetCookieOnDomain(domainFixed)) {
- configCookieDomain = domainFixed;
- updateDomainHash();
- }
- },
-
- /**
- * Set first-party cookie path
- *
- * @param string domain
- */
- setCookiePath: function (path) {
- configCookiePath = path;
- updateDomainHash();
- },
-
- /**
- * Set visitor cookie timeout (in seconds)
- * Defaults to 13 months (timeout=33955200)
- *
- * @param int timeout
- */
- setVisitorCookieTimeout: function (timeout) {
- configVisitorCookieTimeout = timeout * 1000;
- },
-
- /**
- * Set session cookie timeout (in seconds).
- * Defaults to 30 minutes (timeout=1800000)
- *
- * @param int timeout
- */
- setSessionCookieTimeout: function (timeout) {
- configSessionCookieTimeout = timeout * 1000;
- },
-
- /**
- * Set referral cookie timeout (in seconds).
- * Defaults to 6 months (15768000000)
- *
- * @param int timeout
- */
- setReferralCookieTimeout: function (timeout) {
- configReferralCookieTimeout = timeout * 1000;
- },
-
- /**
- * Set conversion attribution to first referrer and campaign
- *
- * @param bool if true, use first referrer (and first campaign)
- * if false, use the last referrer (or campaign)
- */
- setConversionAttributionFirstReferrer: function (enable) {
- configConversionAttributionFirstReferrer = enable;
- },
-
- /**
- * Disables all cookies from being set
- *
- * Existing cookies will be deleted on the next call to track
- */
- disableCookies: function () {
- configCookiesDisabled = true;
- browserFeatures.cookie = '0';
-
- if (configTrackerSiteId) {
- deleteCookies();
- }
- },
-
- /**
- * One off cookies clearing. Useful to call this when you know for sure a new visitor is using the same browser,
- * it maybe helps to "reset" tracking cookies to prevent data reuse for different users.
- */
- deleteCookies: function () {
- deleteCookies();
- },
-
- /**
- * Handle do-not-track requests
- *
- * @param bool enable If true, don't track if user agent sends 'do-not-track' header
- */
- setDoNotTrack: function (enable) {
- var dnt = navigatorAlias.doNotTrack || navigatorAlias.msDoNotTrack;
- configDoNotTrack = enable && (dnt === 'yes' || dnt === '1');
-
- // do not track also disables cookies and deletes existing cookies
- if (configDoNotTrack) {
- this.disableCookies();
- }
- },
-
- /**
- * Add click listener to a specific link element.
- * When clicked, Piwik will log the click automatically.
- *
- * @param DOMElement element
- * @param bool enable If true, use pseudo click-handler (middle click + context menu)
- */
- addListener: function (element, enable) {
- addClickListener(element, enable);
- },
-
- /**
- * Install link tracker
- *
- * The default behaviour is to use actual click events. However, some browsers
- * (e.g., Firefox, Opera, and Konqueror) don't generate click events for the middle mouse button.
- *
- * To capture more "clicks", the pseudo click-handler uses mousedown + mouseup events.
- * This is not industry standard and is vulnerable to false positives (e.g., drag events).
- *
- * There is a Safari/Chrome/Spiderwebkit bug that prevents tracking requests from being sent
- * by either click handler. The workaround is to set a target attribute (which can't
- * be "_self", "_top", or "_parent").
- *
- * @see https://bugs.spiderwebkit.org/show_bug.cgi?id=54783
- *
- * @param bool enable If "true", use pseudo click-handler (treat middle click and open contextmenu as
- * left click). A right click (or any click that opens the context menu) on a link
- * will be tracked as clicked even if "Open in new tab" is not selected. If
- * "false" (default), nothing will be tracked on open context menu or middle click.
- * The context menu is usually opened to open a link / download in a new tab
- * therefore you can get more accurate results by treat it as a click but it can lead
- * to wrong click numbers.
- */
- enableLinkTracking: function (enable) {
- linkTrackingEnabled = true;
-
- if (hasLoaded) {
- // the load event has already fired, add the click listeners now
- addClickListeners(enable);
- } else {
- // defer until page has loaded
- registeredOnLoadHandlers.push(function () {
- addClickListeners(enable);
- });
- }
- },
-
- /**
- * Enable tracking of uncatched JavaScript errors
- *
- * If enabled, uncaught JavaScript Errors will be tracked as an event by defining a
- * window.onerror handler. If a window.onerror handler is already defined we will make
- * sure to call this previously registered error handler after tracking the error.
- *
- * By default we return false in the window.onerror handler to make sure the error still
- * appears in the browser's console etc. Note: Some older browsers might behave differently
- * so it could happen that an actual JavaScript error will be suppressed.
- * If a window.onerror handler was registered we will return the result of this handler.
- *
- * Make sure not to overwrite the window.onerror handler after enabling the JS error
- * tracking as the error tracking won't work otherwise. To capture all JS errors we
- * recommend to include the Piwik JavaScript tracker in the HTML as early as possible.
- * If possible directly in before loading any other JavaScript.
- */
- enableJSErrorTracking: function () {
- if (enableJSErrorTracking) {
- return;
- }
-
- enableJSErrorTracking = true;
- var onError = windowAlias.onerror;
-
- windowAlias.onerror = function (message, url, linenumber, column, error) {
- trackCallback(function () {
- var category = 'JavaScript Errors';
-
- var action = url + ':' + linenumber;
- if (column) {
- action += ':' + column;
- }
-
- logEvent(category, action, message);
- });
-
- if (onError) {
- return onError(message, url, linenumber, column, error);
- }
-
- return false;
- };
- },
-
- /**
- * Disable automatic performance tracking
- */
- disablePerformanceTracking: function () {
- configPerformanceTrackingEnabled = false;
- },
-
- /**
- * Set the server generation time.
- * If set, the browser's performance.timing API in not used anymore to determine the time.
- *
- * @param int generationTime
- */
- setGenerationTimeMs: function (generationTime) {
- configPerformanceGenerationTime = parseInt(generationTime, 10);
- },
-
- /**
- * Set heartbeat (in seconds)
- *
- * @param int heartBeatDelayInSeconds Defaults to 15. Cannot be lower than 1.
- */
- enableHeartBeatTimer: function (heartBeatDelayInSeconds) {
- heartBeatDelayInSeconds = Math.max(heartBeatDelayInSeconds, 1);
- configHeartBeatDelay = (heartBeatDelayInSeconds || 15) * 1000;
-
- // if a tracking request has already been sent, start the heart beat timeout
- if (lastTrackerRequestTime !== null) {
- setUpHeartBeat();
- }
- },
-
-/**/
- /**
- * Clear heartbeat.
- */
- disableHeartBeatTimer: function () {
- heartBeatDown();
- configHeartBeatDelay = null;
-
- window.removeEventListener('focus', heartBeatOnFocus);
- window.removeEventListener('blur', heartBeatOnBlur);
- },
-/**/
-
- /**
- * Frame buster
- */
- killFrame: function () {
- if (windowAlias.location !== windowAlias.top.location) {
- windowAlias.top.location = windowAlias.location;
- }
- },
-
- /**
- * Redirect if browsing offline (aka file: buster)
- *
- * @param string url Redirect to this URL
- */
- redirectFile: function (url) {
- if (windowAlias.location.protocol === 'file:') {
- windowAlias.location = url;
- }
- },
-
- /**
- * Count sites in pre-rendered state
- *
- * @param bool enable If true, track when in pre-rendered state
- */
- setCountPreRendered: function (enable) {
- configCountPreRendered = enable;
- },
-
- /**
- * Trigger a goal
- *
- * @param int|string idGoal
- * @param int|float customRevenue
- * @param mixed customData
- */
- trackGoal: function (idGoal, customRevenue, customData) {
- trackCallback(function () {
- logGoal(idGoal, customRevenue, customData);
- });
- },
-
- /**
- * Manually log a click from your own code
- *
- * @param string sourceUrl
- * @param string linkType
- * @param mixed customData
- * @param function callback
- */
- trackLink: function (sourceUrl, linkType, customData, callback) {
- trackCallback(function () {
- logLink(sourceUrl, linkType, customData, callback);
- });
- },
-
- /**
- * Log visit to this page
- *
- * @param string customTitle
- * @param mixed customData
- */
- trackPageView: function (customTitle, customData) {
- trackedContentImpressions = [];
-
- if (isOverlaySession(configTrackerSiteId)) {
- trackCallback(function () {
- injectOverlayScripts(configTrackerUrl, configApiUrl, configTrackerSiteId);
- });
- } else {
- trackCallback(function () {
- logPageView(customTitle, customData);
- });
- }
- },
-
- /**
- * Scans the entire DOM for all content blocks and tracks all impressions once the DOM ready event has
- * been triggered.
- *
- * If you only want to track visible content impressions have a look at `trackVisibleContentImpressions()`.
- * We do not track an impression of the same content block twice if you call this method multiple times
- * unless `trackPageView()` is called meanwhile. This is useful for single page applications.
- */
- trackAllContentImpressions: function () {
- if (isOverlaySession(configTrackerSiteId)) {
- return;
- }
-
- trackCallback(function () {
- trackCallbackOnReady(function () {
- // we have to wait till DOM ready
- var contentNodes = content.findContentNodes();
- var requests = getContentImpressionsRequestsFromNodes(contentNodes);
-
- sendBulkRequest(requests, configTrackerPause);
- });
- });
- },
-
- /**
- * Scans the entire DOM for all content blocks as soon as the page is loaded. It tracks an impression
- * only if a content block is actually visible. Meaning it is not hidden and the content is or was at
- * some point in the viewport.
- *
- * If you want to track all content blocks have a look at `trackAllContentImpressions()`.
- * We do not track an impression of the same content block twice if you call this method multiple times
- * unless `trackPageView()` is called meanwhile. This is useful for single page applications.
- *
- * Once you have called this method you can no longer change `checkOnScroll` or `timeIntervalInMs`.
- *
- * If you do want to only track visible content blocks but not want us to perform any automatic checks
- * as they can slow down your frames per second you can call `trackVisibleContentImpressions()` or
- * `trackContentImpressionsWithinNode()` manually at any time to rescan the entire DOM for newly
- * visible content blocks.
- * o Call `trackVisibleContentImpressions(false, 0)` to initially track only visible content impressions
- * o Call `trackVisibleContentImpressions()` at any time again to rescan the entire DOM for newly visible content blocks or
- * o Call `trackContentImpressionsWithinNode(node)` at any time to rescan only a part of the DOM for newly visible content blocks
- *
- * @param boolean [checkOnScroll=true] Optional, you can disable rescanning the entire DOM automatically
- * after each scroll event by passing the value `false`. If enabled,
- * we check whether a previously hidden content blocks became visible
- * after a scroll and if so track the impression.
- * Note: If a content block is placed within a scrollable element
- * (`overflow: scroll`), we can currently not detect when this block
- * becomes visible.
- * @param integer [timeIntervalInMs=750] Optional, you can define an interval to rescan the entire DOM
- * for new impressions every X milliseconds by passing
- * for instance `timeIntervalInMs=500` (rescan DOM every 500ms).
- * Rescanning the entire DOM and detecting the visible state of content
- * blocks can take a while depending on the browser and amount of content.
- * In case your frames per second goes down you might want to increase
- * this value or disable it by passing the value `0`.
- */
- trackVisibleContentImpressions: function (checkOnSroll, timeIntervalInMs) {
- if (isOverlaySession(configTrackerSiteId)) {
- return;
- }
-
- if (!isDefined(checkOnSroll)) {
- checkOnSroll = true;
- }
-
- if (!isDefined(timeIntervalInMs)) {
- timeIntervalInMs = 750;
- }
-
- enableTrackOnlyVisibleContent(checkOnSroll, timeIntervalInMs, this);
-
- trackCallback(function () {
- trackCallbackOnLoad(function () {
- // we have to wait till CSS parsed and applied
- var contentNodes = content.findContentNodes();
- var requests = getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet(contentNodes);
-
- sendBulkRequest(requests, configTrackerPause);
- });
- });
- },
-
- /**
- * Tracks a content impression using the specified values. You should not call this method too often
- * as each call causes an XHR tracking request and can slow down your site or your server.
- *
- * @param string contentName For instance "Ad Sale".
- * @param string [contentPiece='Unknown'] For instance a path to an image or the text of a text ad.
- * @param string [contentTarget] For instance the URL of a landing page.
- */
- trackContentImpression: function (contentName, contentPiece, contentTarget) {
- if (isOverlaySession(configTrackerSiteId)) {
- return;
- }
-
- if (!contentName) {
- return;
- }
-
- contentPiece = contentPiece || 'Unknown';
-
- trackCallback(function () {
- var request = buildContentImpressionRequest(contentName, contentPiece, contentTarget);
- sendRequest(request, configTrackerPause);
- });
- },
-
- /**
- * Scans the given DOM node and its children for content blocks and tracks an impression for them if
- * no impression was already tracked for it. If you have called `trackVisibleContentImpressions()`
- * upfront only visible content blocks will be tracked. You can use this method if you, for instance,
- * dynamically add an element using JavaScript to your DOM after we have tracked the initial impressions.
- *
- * @param Element domNode
- */
- trackContentImpressionsWithinNode: function (domNode) {
- if (isOverlaySession(configTrackerSiteId) || !domNode) {
- return;
- }
-
- trackCallback(function () {
- if (isTrackOnlyVisibleContentEnabled) {
- trackCallbackOnLoad(function () {
- // we have to wait till CSS parsed and applied
- var contentNodes = content.findContentNodesWithinNode(domNode);
-
- var requests = getCurrentlyVisibleContentImpressionsRequestsIfNotTrackedYet(contentNodes);
- sendBulkRequest(requests, configTrackerPause);
- });
- } else {
- trackCallbackOnReady(function () {
- // we have to wait till DOM ready
- var contentNodes = content.findContentNodesWithinNode(domNode);
-
- var requests = getContentImpressionsRequestsFromNodes(contentNodes);
- sendBulkRequest(requests, configTrackerPause);
- });
- }
- });
- },
-
- /**
- * Tracks a content interaction using the specified values. You should use this method only in conjunction
- * with `trackContentImpression()`. The specified `contentName` and `contentPiece` has to be exactly the
- * same as the ones that were used in `trackContentImpression()`. Otherwise the interaction will not count.
- *
- * @param string contentInteraction The type of interaction that happened. For instance 'click' or 'submit'.
- * @param string contentName The name of the content. For instance "Ad Sale".
- * @param string [contentPiece='Unknown'] The actual content. For instance a path to an image or the text of a text ad.
- * @param string [contentTarget] For instance the URL of a landing page.
- */
- trackContentInteraction: function (contentInteraction, contentName, contentPiece, contentTarget) {
- if (isOverlaySession(configTrackerSiteId)) {
- return;
- }
-
- if (!contentInteraction || !contentName) {
- return;
- }
-
- contentPiece = contentPiece || 'Unknown';
-
- trackCallback(function () {
- var request = buildContentInteractionRequest(contentInteraction, contentName, contentPiece, contentTarget);
- sendRequest(request, configTrackerPause);
- });
- },
-
- /**
- * Tracks an interaction with the given DOM node / content block.
- *
- * By default we track interactions on click but sometimes you might want to track interactions yourself.
- * For instance you might want to track an interaction manually on a double click or a form submit.
- * Make sure to disable the automatic interaction tracking in this case by specifying either the CSS
- * class `piwikContentIgnoreInteraction` or the attribute `data-content-ignoreinteraction`.
- *
- * @param Element domNode This element itself or any of its parent elements has to be a content block
- * element. Meaning one of those has to have a `piwikTrackContent` CSS class or
- * a `data-track-content` attribute.
- * @param string [contentInteraction='Unknown] The name of the interaction that happened. For instance
- * 'click', 'formSubmit', 'DblClick', ...
- */
- trackContentInteractionNode: function (domNode, contentInteraction) {
- if (isOverlaySession(configTrackerSiteId) || !domNode) {
- return;
- }
-
- trackCallback(function () {
- var request = buildContentInteractionRequestNode(domNode, contentInteraction);
- sendRequest(request, configTrackerPause);
- });
- },
-
- /**
- * Useful to debug content tracking. This method will log all detected content blocks to console
- * (if the browser supports the console). It will list the detected name, piece, and target of each
- * content block.
- */
- logAllContentBlocksOnPage: function () {
- var contentNodes = content.findContentNodes();
- var contents = content.collectContent(contentNodes);
-
- if (console !== undefined && console && console.log) {
- console.log(contents);
- }
- },
-
- /**
- * Records an event
- *
- * @param string category The Event Category (Videos, Music, Games...)
- * @param string action The Event's Action (Play, Pause, Duration, Add Playlist, Downloaded, Clicked...)
- * @param string name (optional) The Event's object Name (a particular Movie name, or Song name, or File name...)
- * @param float value (optional) The Event's value
- * @param mixed customData
- */
- trackEvent: function (category, action, name, value, customData) {
- trackCallback(function () {
- logEvent(category, action, name, value, customData);
- });
- },
-
- /**
- * Log special pageview: Internal search
- *
- * @param string keyword
- * @param string category
- * @param int resultsCount
- * @param mixed customData
- */
- trackSiteSearch: function (keyword, category, resultsCount, customData) {
- trackCallback(function () {
- logSiteSearch(keyword, category, resultsCount, customData);
- });
- },
-
- /**
- * Used to record that the current page view is an item (product) page view, or a Ecommerce Category page view.
- * This must be called before trackPageView() on the product/category page.
- * It will set 3 custom variables of scope "page" with the SKU, Name and Category for this page view.
- * Note: Custom Variables of scope "page" slots 3, 4 and 5 will be used.
- *
- * On a category page, you can set the parameter category, and set the other parameters to empty string or false
- *
- * Tracking Product/Category page views will allow Piwik to report on Product & Categories
- * conversion rates (Conversion rate = Ecommerce orders containing this product or category / Visits to the product or category)
- *
- * @param string sku Item's SKU code being viewed
- * @param string name Item's Name being viewed
- * @param string category Category page being viewed. On an Item's page, this is the item's category
- * @param float price Item's display price, not use in standard Piwik reports, but output in API product reports.
- */
- setEcommerceView: function (sku, name, category, price) {
- if (!isDefined(category) || !category.length) {
- category = "";
- } else if (category instanceof Array) {
- category = JSON2.stringify(category);
- }
-
- customVariablesPage[5] = ['_pkc', category];
-
- if (isDefined(price) && String(price).length) {
- customVariablesPage[2] = ['_pkp', price];
- }
-
- // On a category page, do not track Product name not defined
- if ((!isDefined(sku) || !sku.length)
- && (!isDefined(name) || !name.length)) {
- return;
- }
-
- if (isDefined(sku) && sku.length) {
- customVariablesPage[3] = ['_pks', sku];
- }
-
- if (!isDefined(name) || !name.length) {
- name = "";
- }
-
- customVariablesPage[4] = ['_pkn', name];
- },
-
- /**
- * Adds an item (product) that is in the current Cart or in the Ecommerce order.
- * This function is called for every item (product) in the Cart or the Order.
- * The only required parameter is sku.
- *
- * @param string sku (required) Item's SKU Code. This is the unique identifier for the product.
- * @param string name (optional) Item's name
- * @param string name (optional) Item's category, or array of up to 5 categories
- * @param float price (optional) Item's price. If not specified, will default to 0
- * @param float quantity (optional) Item's quantity. If not specified, will default to 1
- */
- addEcommerceItem: function (sku, name, category, price, quantity) {
- if (sku.length) {
- ecommerceItems[sku] = [ sku, name, category, price, quantity ];
- }
- },
-
- /**
- * Tracks an Ecommerce order.
- * If the Ecommerce order contains items (products), you must call first the addEcommerceItem() for each item in the order.
- * All revenues (grandTotal, subTotal, tax, shipping, discount) will be individually summed and reported in Piwik reports.
- * Parameters orderId and grandTotal are required. For others, you can set to false if you don't need to specify them.
- *
- * @param string|int orderId (required) Unique Order ID.
- * This will be used to count this order only once in the event the order page is reloaded several times.
- * orderId must be unique for each transaction, even on different days, or the transaction will not be recorded by Piwik.
- * @param float grandTotal (required) Grand Total revenue of the transaction (including tax, shipping, etc.)
- * @param float subTotal (optional) Sub total amount, typically the sum of items prices for all items in this order (before Tax and Shipping costs are applied)
- * @param float tax (optional) Tax amount for this order
- * @param float shipping (optional) Shipping amount for this order
- * @param float discount (optional) Discounted amount in this order
- */
- trackEcommerceOrder: function (orderId, grandTotal, subTotal, tax, shipping, discount) {
- logEcommerceOrder(orderId, grandTotal, subTotal, tax, shipping, discount);
- },
-
- /**
- * Tracks a Cart Update (add item, remove item, update item).
- * On every Cart update, you must call addEcommerceItem() for each item (product) in the cart, including the items that haven't been updated since the last cart update.
- * Then you can call this function with the Cart grandTotal (typically the sum of all items' prices)
- *
- * @param float grandTotal (required) Items (products) amount in the Cart
- */
- trackEcommerceCartUpdate: function (grandTotal) {
- logEcommerceCartUpdate(grandTotal);
- }
-
- };
- }
-
- /************************************************************
- * Proxy object
- * - this allows the caller to continue push()'ing to _paq
- * after the Tracker has been initialized and loaded
- ************************************************************/
-
- function TrackerProxy() {
- return {
- push: apply
- };
- }
-
- /**
- * Applies the given methods in the given order if they are present in paq.
- *
- * @param {Array} paq
- * @param {Array} methodsToApply an array containing method names in the order that they should be applied
- * eg ['setSiteId', 'setTrackerUrl']
- * @returns {Array} the modified paq array with the methods that were already applied set to undefined
- */
- function applyMethodsInOrder(paq, methodsToApply)
- {
- var appliedMethods = {};
- var index, iterator;
-
- for (index = 0; index < methodsToApply.length; index++) {
- var methodNameToApply = methodsToApply[index];
- appliedMethods[methodNameToApply] = 1;
-
- for (iterator = 0; iterator < paq.length; iterator++) {
- if (paq[iterator] && paq[iterator][0]) {
- var methodName = paq[iterator][0];
-
- if (methodNameToApply === methodName) {
- apply(paq[iterator]);
- delete paq[iterator];
-
- if (appliedMethods[methodName] > 1) {
- if (console !== undefined && console && console.error) {
- console.error('The method ' + methodName + ' is registered more than once in "paq" variable. Only the last call has an effect. Please have a look at the multiple Piwik trackers documentation: http://developer.piwik.org/guides/tracking-javascript-guide#multiple-piwik-trackers');
- }
- }
-
- appliedMethods[methodName]++;
- }
- }
- }
- }
-
- return paq;
- }
-
- /************************************************************
- * Constructor
- ************************************************************/
-
- // initialize the Piwik singleton
- addEventListener(windowAlias, 'beforeunload', beforeUnloadHandler, false);
- addReadyListener();
-
- Date.prototype.getTimeAlias = Date.prototype.getTime;
-
- asyncTracker = new Tracker();
-
- var applyFirst = ['disableCookies', 'setTrackerUrl', 'setAPIUrl', 'setCookiePath', 'setCookieDomain', 'setDomains', 'setUserId', 'setSiteId', 'enableLinkTracking'];
- _paq = applyMethodsInOrder(_paq, applyFirst);
-
- // apply the queue of actions
- for (iterator = 0; iterator < _paq.length; iterator++) {
- if (_paq[iterator]) {
- apply(_paq[iterator]);
- }
- }
-
- // replace initialization array with proxy object
- _paq = new TrackerProxy();
-
- /************************************************************
- * Public data and methods
- ************************************************************/
-
- Piwik = {
- /**
- * Add plugin
- *
- * @param string pluginName
- * @param Object pluginObj
- */
- addPlugin: function (pluginName, pluginObj) {
- plugins[pluginName] = pluginObj;
- },
-
- /**
- * Get Tracker (factory method)
- *
- * @param string piwikUrl
- * @param int|string siteId
- * @return Tracker
- */
- getTracker: function (piwikUrl, siteId) {
- if(!isDefined(siteId)) {
- siteId = this.getAsyncTracker().getSiteId();
- }
- if(!isDefined(piwikUrl)) {
- piwikUrl = this.getAsyncTracker().getTrackerUrl();
- }
- return new Tracker(piwikUrl, siteId);
- },
-
- /**
- * Get internal asynchronous tracker object
- *
- * @return Tracker
- */
- getAsyncTracker: function () {
- return asyncTracker;
- }
- };
-
- // Expose Piwik as an AMD module
- if (typeof define === 'function' && define.amd) {
- define('piwik', [], function () { return Piwik; });
- }
-
- return Piwik;
- }());
-}
-
-if (window && window.piwikAsyncInit) {
- window.piwikAsyncInit();
-}
-
-/*jslint sloppy: true */
-(function () {
- var jsTrackerType = (typeof AnalyticsTracker);
- if (jsTrackerType === 'undefined') {
- AnalyticsTracker = Piwik;
- }
-}());
-/*jslint sloppy: false */
-
-/************************************************************
- * Deprecated functionality below
- * Legacy piwik.js compatibility ftw
- ************************************************************/
-
-/*
- * Piwik globals
- *
- * var piwik_install_tracker, piwik_tracker_pause, piwik_download_extensions, piwik_hosts_alias, piwik_ignore_classes;
- */
-/*global piwik_log:true */
-/*global piwik_track:true */
-
-/**
- * Track page visit
- *
- * @param string documentTitle
- * @param int|string siteId
- * @param string piwikUrl
- * @param mixed customData
- */
-if (typeof piwik_log !== 'function') {
- piwik_log = function (documentTitle, siteId, piwikUrl, customData) {
- 'use strict';
-
- function getOption(optionName) {
- try {
- if (window['piwik_' + optionName]) {
- return window['piwik_' + optionName];
- }
- } catch (ignore) { }
-
- return; // undefined
- }
-
- // instantiate the tracker
- var option,
- piwikTracker = Piwik.getTracker(piwikUrl, siteId);
-
- // initialize tracker
- piwikTracker.setDocumentTitle(documentTitle);
- piwikTracker.setCustomData(customData);
-
- // handle Piwik globals
- option = getOption('tracker_pause');
-
- if (option) {
- piwikTracker.setLinkTrackingTimer(option);
- }
-
- option = getOption('download_extensions');
-
- if (option) {
- piwikTracker.setDownloadExtensions(option);
- }
-
- option = getOption('hosts_alias');
-
- if (option) {
- piwikTracker.setDomains(option);
- }
-
- option = getOption('ignore_classes');
-
- if (option) {
- piwikTracker.setIgnoreClasses(option);
- }
-
- // track this page view
- piwikTracker.trackPageView();
-
- // default is to install the link tracker
- if (getOption('install_tracker')) {
-
- /**
- * Track click manually (function is defined below)
- *
- * @param string sourceUrl
- * @param int|string siteId
- * @param string piwikUrl
- * @param string linkType
- */
- piwik_track = function (sourceUrl, siteId, piwikUrl, linkType) {
- piwikTracker.setSiteId(siteId);
- piwikTracker.setTrackerUrl(piwikUrl);
- piwikTracker.trackLink(sourceUrl, linkType);
- };
-
- // set-up link tracking
- piwikTracker.enableLinkTracking();
- }
- };
-}
-
-/*! @license-end */
diff --git a/world/Plugins/APIDump/prettify.css b/world/Plugins/APIDump/prettify.css
deleted file mode 100644
index d44b3a22..00000000
--- a/world/Plugins/APIDump/prettify.css
+++ /dev/null
@@ -1 +0,0 @@
-.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee}
\ No newline at end of file
diff --git a/world/Plugins/APIDump/prettify.js b/world/Plugins/APIDump/prettify.js
deleted file mode 100644
index 7b990496..00000000
--- a/world/Plugins/APIDump/prettify.js
+++ /dev/null
@@ -1,30 +0,0 @@
-!function(){var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
-(function(){function S(a){function d(e){var b=e.charCodeAt(0);if(b!==92)return b;var a=e.charAt(1);return(b=r[a])?b:"0"<=a&&a<="7"?parseInt(e.substring(1),8):a==="u"||a==="x"?parseInt(e.substring(2),16):e.charCodeAt(1)}function g(e){if(e<32)return(e<16?"\\x0":"\\x")+e.toString(16);e=String.fromCharCode(e);return e==="\\"||e==="-"||e==="]"||e==="^"?"\\"+e:e}function b(e){var b=e.substring(1,e.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),e=[],a=
-b[0]==="^",c=["["];a&&c.push("^");for(var a=a?1:0,f=b.length;a122||(l<65||h>90||e.push([Math.max(65,h)|32,Math.min(l,90)|32]),l<97||h>122||e.push([Math.max(97,h)&-33,Math.min(l,122)&-33]))}}e.sort(function(e,a){return e[0]-a[0]||a[1]-e[1]});b=[];f=[];for(a=0;ah[0]&&(h[1]+1>h[0]&&c.push("-"),c.push(g(h[1])));c.push("]");return c.join("")}function s(e){for(var a=e.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),c=a.length,d=[],f=0,h=0;f=2&&e==="["?a[f]=b(l):e!=="\\"&&(a[f]=l.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return a.join("")}for(var x=0,m=!1,j=!1,k=0,c=a.length;k=5&&"lang-"===w.substring(0,5))&&!(t&&typeof t[1]==="string"))f=!1,w="src";f||(r[z]=w)}h=c;c+=z.length;if(f){f=t[1];var l=z.indexOf(f),B=l+f.length;t[2]&&(B=z.length-t[2].length,l=B-f.length);w=w.substring(5);H(j+h,z.substring(0,l),g,k);H(j+h+l,f,I(w,f),k);H(j+h+B,z.substring(B),g,k)}else k.push(j+h,w)}a.g=k}var b={},s;(function(){for(var g=a.concat(d),j=[],k={},c=0,i=g.length;c=0;)b[n.charAt(e)]=r;r=r[1];n=""+r;k.hasOwnProperty(n)||(j.push(r),k[n]=q)}j.push(/[\S\s]/);s=S(j)})();var x=d.length;return g}function v(a){var d=[],g=[];a.tripleQuotedStrings?d.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?d.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
-q,"'\"`"]):d.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&g.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var b=a.hashComments;b&&(a.cStyleComments?(b>1?d.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):d.push(["com",/^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),g.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,q])):d.push(["com",
-/^#[^\n\r]*/,q,"#"]));a.cStyleComments&&(g.push(["com",/^\/\/[^\n\r]*/,q]),g.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));if(b=a.regexLiterals){var s=(b=b>1?"":"\n\r")?".":"[\\S\\s]";g.push(["lang-regex",RegExp("^(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<=?|>>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*("+("/(?=[^/*"+b+"])(?:[^/\\x5B\\x5C"+b+"]|\\x5C"+s+"|\\x5B(?:[^\\x5C\\x5D"+b+"]|\\x5C"+
-s+")*(?:\\x5D|$))+/")+")")])}(b=a.types)&&g.push(["typ",b]);b=(""+a.keywords).replace(/^ | $/g,"");b.length&&g.push(["kwd",RegExp("^(?:"+b.replace(/[\s,]+/g,"|")+")\\b"),q]);d.push(["pln",/^\s+/,q," \r\n\t\u00a0"]);b="^.[^\\s\\w.$@'\"`/\\\\]*";a.regexLiterals&&(b+="(?!s*/)");g.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,
-q],["pun",RegExp(b),q]);return C(d,g)}function J(a,d,g){function b(a){var c=a.nodeType;if(c==1&&!x.test(a.className))if("br"===a.nodeName)s(a),a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)b(a);else if((c==3||c==4)&&g){var d=a.nodeValue,i=d.match(m);if(i)c=d.substring(0,i.index),a.nodeValue=c,(d=d.substring(i.index+i[0].length))&&a.parentNode.insertBefore(j.createTextNode(d),a.nextSibling),s(a),c||a.parentNode.removeChild(a)}}function s(a){function b(a,c){var d=
-c?a.cloneNode(!1):a,e=a.parentNode;if(e){var e=b(e,1),g=a.nextSibling;e.appendChild(d);for(var i=g;i;i=g)g=i.nextSibling,e.appendChild(i)}return d}for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),d;(d=a.parentNode)&&d.nodeType===1;)a=d;c.push(a)}for(var x=/(?:^|\s)nocode(?:\s|$)/,m=/\r\n?|\n/,j=a.ownerDocument,k=j.createElement("li");a.firstChild;)k.appendChild(a.firstChild);for(var c=[k],i=0;i=0;){var b=d[g];F.hasOwnProperty(b)?D.console&&console.warn("cannot override language handler %s",b):F[b]=a}}function I(a,d){if(!a||!F.hasOwnProperty(a))a=/^\s*=l&&(b+=2);g>=B&&(r+=2)}}finally{if(f)f.style.display=h}}catch(u){D.console&&console.log(u&&u.stack||u)}}var D=window,y=["break,continue,do,else,for,if,return,while"],E=[[y,"auto,case,char,const,default,double,enum,extern,float,goto,inline,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"],
-"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],M=[E,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,delegate,dynamic_cast,explicit,export,friend,generic,late_check,mutable,namespace,nullptr,property,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],N=[E,"abstract,assert,boolean,byte,extends,final,finally,implements,import,instanceof,interface,null,native,package,strictfp,super,synchronized,throws,transient"],
-O=[N,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,internal,into,is,let,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var,virtual,where"],E=[E,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],P=[y,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],
-Q=[y,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],W=[y,"as,assert,const,copy,drop,enum,extern,fail,false,fn,impl,let,log,loop,match,mod,move,mut,priv,pub,pure,ref,self,static,struct,true,trait,type,unsafe,use"],y=[y,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],R=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/,
-V=/\S/,X=v({keywords:[M,O,E,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",P,Q,y],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),F={};p(X,["default-code"]);p(C([],[["pln",/^[^]+/],["dec",/^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",
-/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^
-]]
--- Array of {PluginName, FunctionName} tables
-local OnWebChatCallbacks = {}
-local ChatLogMessages = {}
-local WebCommands = {}
-local ltNormal = 1
-local ltInfo = 2
-local ltWarning = 3
-local ltError = 4
-
--- Adds Webchat callback, plugins can return true to
--- prevent message from appearing / being processed
--- by further callbacks
--- OnWebChat(Username, Message)
-function AddWebChatCallback(PluginName, FunctionName)
- for k, v in pairs(OnWebChatCallbacks) do
- if v[1] == PluginName and v[2] == FunctionName then
- return false
- end
- end
- table.insert(OnWebChatCallbacks, {PluginName, FunctionName})
- return true
-end
-
--- Removes webchat callback
-function RemoveWebChatCallback(PluginName, FunctionName)
- for i = #OnWebChatCallbacks, 0, -1 do
- if OnWebChatCallbacks[i][1] == PluginName and OnWebChatCallbacks[i][2] == FunctionName then
- table.remove(OnWebChatCallbacks, i)
- return true
- end
- end
- return false
-end
-
-
--- Checks the chatlogs to see if the size gets too big.
-function TrimWebChatIfNeeded()
- while( #ChatLogMessages > CHAT_HISTORY ) do
- table.remove( ChatLogMessages, 1 )
- end
-end
-
-
-
-
-
--- Adds a plain message to the chat log
--- The a_WebUserName parameter can be either a string(name) to send it to a certain webuser or nil to send it to every webuser.
-function WEBLOG(a_Message, a_WebUserName)
- LastMessageID = LastMessageID + 1
- table.insert(ChatLogMessages, {timestamp = os.date("[%Y-%m-%d %H:%M:%S]", os.time()), webuser = a_WebUserName, message = a_Message, id = LastMessageID, logtype = ltNormal})
- TrimWebChatIfNeeded()
-end
-
-
-
-
-
--- Adds a yellow-ish message to the chat log.
--- The a_WebUserName parameter can be either a string(name) to send it to a certain webuser or nil to send it to every webuser.
-function WEBLOGINFO(a_Message, a_WebUserName)
- LastMessageID = LastMessageID + 1
- table.insert(ChatLogMessages, {timestamp = os.date("[%Y-%m-%d %H:%M:%S]", os.time()), webuser = a_WebUserName, message = a_Message, id = LastMessageID, logtype = ltInfo})
- TrimWebChatIfNeeded()
-end
-
-
-
-
-
--- Adds a red message to the chat log
--- The a_WebUserName parameter can be either a string(name) to send it to a certain webuser or nil to send it to every webuser.
-function WEBLOGWARN(a_Message, a_WebUserName)
- LastMessageID = LastMessageID + 1
- table.insert(ChatLogMessages, {timestamp = os.date("[%Y-%m-%d %H:%M:%S]", os.time()), webuser = a_WebUserName, message = a_Message, id = LastMessageID, logtype = ltWarning})
- TrimWebChatIfNeeded()
-end
-
-
-
-
-
--- Adds a message with a red background to the chat log
--- The a_WebUserName parameter can be either a string(name) to send it to a certain webuser or nil to send it to every webuser.
-function WEBLOGERROR(a_Message, a_WebUserName)
- LastMessageID = LastMessageID + 1
- table.insert(ChatLogMessages, {timestamp = os.date("[%Y-%m-%d %H:%M:%S]", os.time()), webuser = a_WebUserName, message = a_Message, id = LastMessageID, logtype = ltError})
- TrimWebChatIfNeeded()
-end
-
-
-
-
-
--- This function allows other plugins to add new commands to the webadmin.
--- a_CommandString is the the way you call the command ("/help")
--- a_HelpString is the message that tells you what the command does ("Shows a list of all the possible commands")
--- a_PluginName is the name of the plugin binding the command ("Core")
--- a_CallbackName is the name if the function that will be called when the command is executed ("HandleWebHelpCommand")
-function BindWebCommand(a_CommandString, a_HelpString, a_PluginName, a_CallbackName)
- assert(type(a_CommandString) == 'string')
- assert(type(a_PluginName) == 'string')
- assert(type(a_CallbackName) == 'string')
-
- -- Check if the command is already bound. Return false with an error message if.
- for Idx, CommandInfo in ipairs(WebCommands) do
- if (CommandInfo.Command == a_CommandString) then
- return false, "That command is already bound to a plugin called \"" .. CommandInfo.PluginName .. "\"."
- end
- end
-
- -- Insert the command into the array and return true
- table.insert(WebCommands, {CommandString = a_CommandString, HelpString = a_HelpString, PluginName = a_PluginName, CallbackName = a_CallbackName})
- return true
-end
-
-
-
-
-
--- Used by the webadmin to use /help
-function HandleWebHelpCommand(a_User, a_Message)
- local Content = "Available Commands:"
- for Idx, CommandInfo in ipairs(WebCommands) do
- if (CommandInfo.HelpString ~= "") then
- Content = Content .. ' ' .. CommandInfo.CommandString .. ' - ' .. CommandInfo.HelpString
- end
- end
-
- WEBLOG(Content, a_User)
- return true
-end
-
-
-
-
-
--- Used by the webadmin to reload the server
-function HandleWebReloadCommand(a_User, a_Message)
- cPluginManager:Get():ReloadPlugins()
- WEBLOG("Reloading Plugins", a_User)
- return true
-end
-
-
-
-
-
--- Register some basic commands
-BindWebCommand("/help", "Shows a list of all the possible commands", "Core", "HandleWebHelpCommand")
-BindWebCommand("/reload", "Reloads all the plugins", "Core", "HandleWebReloadCommand")
-
-
-
-
-
--- Add a chatmessage from a player to the chatlog
-function OnChat(a_Player, a_Message)
- WEBLOG("[" .. a_Player:GetName() .. "]: " .. a_Message)
-end
-
-
-
-
-
---- Removes html tags
---- Creates a tag when http(s) links are send.
---- It does this by selecting all the characters between "http(s)://" and a space, and puts an anker tag around it.
-local function ParseMessage(a_Message)
- local function PlaceString(a_Url)
- return '' .. a_Url .. ''
- end
-
- a_Message = a_Message:gsub("<", "<"):gsub(">", ">"):gsub("=", "="):gsub('"', """):gsub("'", "'"):gsub("&", "&")
- a_Message = a_Message:gsub('http://[^%s]+', PlaceString):gsub('https://[^%s]+', PlaceString)
- return a_Message
-end
-
-
-
-
-
-function HandleRequest_Chat( Request )
- -- The webadmin asks if there are new messages.
- if( Request.PostParams["JustChat"] ~= nil ) then
- local LastIdx = tonumber(Request.PostParams["LastMessageID"] or 0) or 0
- local Content = ""
-
- -- Go through each message to see if they are older then the last message, and add them to the content
- for key, MessageInfo in pairs(ChatLogMessages) do
- if( MessageInfo.id > LastIdx ) then
- if (not MessageInfo.webuser or (MessageInfo.webuser == Request.Username)) then
- local Message = MessageInfo.timestamp .. ' ' .. ParseMessage(MessageInfo.message)
- if (MessageInfo.logtype == ltNormal) then
- Content = Content .. Message .. " "
- elseif (MessageInfo.logtype == ltInfo) then
- Content = Content .. '' .. Message .. ' '
- elseif (MessageInfo.logtype == ltWarning) then
- Content = Content .. '' .. Message .. ' '
- elseif (MessageInfo.logtype == ltError) then
- Content = Content .. '' .. Message .. ' '
- end
- end
- end
- end
- Content = Content .. "<>" .. LastMessageID .. "<>" .. LastIdx
- return Content
- end
-
- -- Check if the webuser send a chat message.
- if( Request.PostParams["ChatMessage"] ~= nil ) then
- local Split = StringSplit(Request.PostParams["ChatMessage"])
- local CommandExecuted = false
-
- -- Check if the message was actualy a command
- for Idx, CommandInfo in ipairs(WebCommands) do
- if (CommandInfo.CommandString == Split[1]) then
- -- cPluginManager:CallPlugin doesn't support calling yourself, so we have to check if the command is from the Core.
- if (CommandInfo.PluginName == "Core") then
- if (not _G[CommandInfo.CallbackName](Request.Username, Request.PostParams["ChatMessage"])) then
- WEBLOG("Something went wrong while calling \"" .. CommandInfo.CallbackName .. "\" From \"" .. CommandInfo.PluginName .. "\".", Request.Username)
- end
- else
- if (not cPluginManager:CallPlugin(CommandInfo.PluginName, CommandInfo.CallbackName, Request.Username, Request.PostParams["ChatMessage"])) then
- WEBLOG("Something went wrong while calling \"" .. CommandInfo.CallbackName .. "\" From \"" .. CommandInfo.PluginName .. "\".", Request.Username)
- end
- end
- return ""
- end
- end
-
- -- If the message starts with a '/' then the message is a command, but since it wasn't executed a few lines above the command didn't exist
- if (Request.PostParams["ChatMessage"]:sub(1, 1) == "/") then
- WEBLOG('Unknown Command "' .. Request.PostParams["ChatMessage"] .. '"', nil)
- return ""
- end
-
- -- Broadcast the message to the server
- for k, v in pairs(OnWebChatCallbacks) do
- if cPluginManager:CallPlugin(v[1], v[2], Request.Username, Request.PostParams["ChatMessage"]) then
- return ""
- end
- end
- cRoot:Get():BroadcastChat(cCompositeChat("[WEB] <" .. Request.Username .. "> " .. Request.PostParams["ChatMessage"]):UnderlineUrls())
-
- -- Add the message to the chatlog
- WEBLOG("[WEB] [" .. Request.Username .. "]: " .. Request.PostParams["ChatMessage"])
- return ""
- end
-
- local Content = JavaScript
- Content = Content .. [[
-
-
- ]]
- return Content
-end
diff --git a/world/Plugins/Core/web_manageserver.lua b/world/Plugins/Core/web_manageserver.lua
deleted file mode 100644
index 4b45739d..00000000
--- a/world/Plugins/Core/web_manageserver.lua
+++ /dev/null
@@ -1,36 +0,0 @@
-function HandleRequest_ManageServer( Request )
- local Content = ""
- if (Request.PostParams["RestartServer"] ~= nil) then
- cRoot:Get():QueueExecuteConsoleCommand("restart");
- elseif (Request.PostParams["ReloadServer"] ~= nil) then
- cRoot:Get():GetPluginManager():ReloadPlugins();
- elseif (Request.PostParams["StopServer"] ~= nil) then
- cRoot:Get():QueueExecuteConsoleCommand("stop");
- elseif (Request.PostParams["WorldSaveAllChunks"] ~= nil) then
- cRoot:Get():GetWorld(Request.PostParams["WorldSaveAllChunks"]):QueueSaveAllChunks();
- end
- Content = Content .. [[
-
Group name:
")
- ins(Page, GetFormButton("addgroup", "Create a new group", {}))
- ins(Page, "
")
-
- -- Display a table showing all groups currently known:
- ins(Page, "
Groups
Group name
Permissions
Restrictions
Actions
")
- local AllGroups = cRankManager:GetAllGroups()
- table.sort(AllGroups)
- for _, group in ipairs(AllGroups) do
- ins(Page, GetGroupRow(group))
- end
- ins(Page, "
")
-
- return con(Page)
-end
-
-
-
-
-
---- Handles the AddGroup form in the main page
--- Adds the group and redirects the user back to the group list
-local function ShowAddGroupPage(a_Request)
- -- Check params:
- local GroupName = a_Request.PostParams["GroupName"]
- if (GroupName == nil) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Add the group:
- cRankManager:AddGroup(GroupName)
-
- -- Redirect the user:
- return "
"
-end
-
-
-
-
-
---- Handles the AddPermission form in the Edit group page
--- Adds the permission to the group and redirects the user back to the permission list
-local function ShowAddPermissionPage(a_Request)
- -- Check params:
- local GroupName = a_Request.PostParams["GroupName"]
- local Permission = a_Request.PostParams["Permission"]
- if ((GroupName == nil) or (Permission == nil)) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Add the permission:
- cRankManager:AddPermissionToGroup(Permission, GroupName)
-
- -- Redirect the user:
- return
- "
"
-end
-
-
-
-
-
---- Handles the AddRestriction form in the Edit group page
--- Adds the restriction to the group and redirects the user back to the permission list
-local function ShowAddRestrictionPage(a_Request)
- -- Check params:
- local GroupName = a_Request.PostParams["GroupName"]
- local Restriction = a_Request.PostParams["Restriction"]
- if ((GroupName == nil) or (Restriction == nil)) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Add the permission:
- cRankManager:AddRestrictionToGroup(Restriction, GroupName)
-
- -- Redirect the user:
- return
- "
"
-end
-
-
-
-
-
---- Shows a confirmation page for deleting a group
-local function ShowConfirmDelGroupPage(a_Request)
- -- Check params:
- local GroupName = a_Request.PostParams["GroupName"]
- if (GroupName == nil) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Show the confirmation request:
- local Page =
- {
- "
Delete group
Are you sure you want to delete group ",
- GroupName,
- "? It will be removed from all the ranks that are using it.
"
- }
- return con(Page)
-end
-
-
-
-
-
---- Handles the DelGroup button in the ConfirmDelGroup page
--- Removes the group and redirects the user back to the group list
-local function ShowDelGroupPage(a_Request)
- -- Check params:
- local GroupName = a_Request.PostParams["GroupName"]
- if (GroupName == nil) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Remove the group:
- cRankManager:RemoveGroup(GroupName)
-
- -- Redirect the user:
- return
- "
"
-end
-
-
-
-
-
--- Handles the DelPermission form in the Edit permissions page
--- Removes the permission from the group and redirects the user back to the permission list
-local function ShowDelPermissionPage(a_Request)
- -- Check params:
- local GroupName = a_Request.PostParams["GroupName"]
- local Permission = a_Request.PostParams["Permission"]
- if ((GroupName == nil) or (Permission == nil)) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Add the permission:
- cRankManager:RemovePermissionFromGroup(Permission, GroupName)
-
- -- Redirect the user:
- return
- "
"
-end
-
-
-
-
-
--- Handles the DelRestriction form in the Edit group page
--- Removes the restriction from the group and redirects the user back to the Edit group page
-local function ShowDelRestrictionPage(a_Request)
- -- Check params:
- local GroupName = a_Request.PostParams["GroupName"]
- local Restriction = a_Request.PostParams["Restriction"]
- if ((GroupName == nil) or (Restriction == nil)) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Add the permission:
- cRankManager:RemoveRestrictionFromGroup(Restriction, GroupName)
-
- -- Redirect the user:
- return
- "
"
-end
-
-
-
-
-
---- Displays the Edit Group page for a single group, allowing the admin to edit permissions and restrictions
-local function ShowEditGroupPage(a_Request)
- -- Check params:
- local GroupName = a_Request.PostParams["GroupName"]
- if (GroupName == nil) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Add the header for adding permissions:
- local Page = {[[
-
")
- return con(Page)
-end
-
-
-
-
-
---- Handlers for the individual subpages in this tab
--- Each item maps a subpage name to a handler function that receives a HTTPRequest object and returns the HTML to return
-local g_SubpageHandlers =
-{
- [""] = ShowMainPermissionsPage,
- ["addgroup"] = ShowAddGroupPage,
- ["addpermission"] = ShowAddPermissionPage,
- ["addrestriction"] = ShowAddRestrictionPage,
- ["confirmdelgroup"] = ShowConfirmDelGroupPage,
- ["delgroup"] = ShowDelGroupPage,
- ["delpermission"] = ShowDelPermissionPage,
- ["delrestriction"] = ShowDelRestrictionPage,
- ["edit"] = ShowEditGroupPage,
-}
-
-
-
-
-
---- Handles the web request coming from MCS
--- Returns the entire tab's HTML contents, based on the player's request
-function HandleRequest_Permissions(a_Request)
- local Subpage = (a_Request.PostParams["subpage"] or "")
- local Handler = g_SubpageHandlers[Subpage]
- if (Handler == nil) then
- return HTMLError("An internal error has occurred, no handler for subpage " .. Subpage .. ".")
- end
-
- local PageContent = Handler(a_Request)
-
- --[[
- -- DEBUG: Save content to a file for debugging purposes:
- local f = io.open("permissions.html", "wb")
- if (f ~= nil) then
- f:write(PageContent)
- f:close()
- end
- --]]
-
- return PageContent
-end
-
-
-
-
-
diff --git a/world/Plugins/Core/web_playerranks.lua b/world/Plugins/Core/web_playerranks.lua
deleted file mode 100644
index c1152f13..00000000
--- a/world/Plugins/Core/web_playerranks.lua
+++ /dev/null
@@ -1,422 +0,0 @@
-
--- web_playerranks.lua
-
--- Implements the Player Ranks tab in the webadmin
-
-
-
-
-
---- Maximum number of players displayed on a single page.
-local PLAYERS_PER_PAGE = 20
-
-local ins = table.insert
-local con = table.concat
-
-
-
-
-
---- Updates the rank from the ingame player with this uuid
-local function UpdateIngamePlayer(a_PlayerUUID, a_Message)
- cRoot:Get():ForEachPlayer(
- function(a_Player)
- if (a_Player:GetUUID() == a_PlayerUUID) then
- if (a_Message ~= "") then
- a_Player:SendMessage(a_Message)
- end
- a_Player:LoadRank()
- end
- end
- )
-end
-
-
-
-
-
---- Returns the HTML contents of the rank list
-local function GetRankList(a_SelectedRank)
- local RankList = {}
- ins(RankList, "")
-
- return con(RankList)
-end
-
-
-
-
-
---- Returns the HTML contents of a single row in the Players table
-local function GetPlayerRow(a_PlayerUUID)
- -- Get the player name/rank:
- local PlayerName = cRankManager:GetPlayerName(a_PlayerUUID)
- local PlayerRank = cRankManager:GetPlayerRankName(a_PlayerUUID)
-
- -- First row: player name:
- local Row = {"
")
- ins(Row, GetFormButton("confirmdel", "Remove rank", {PlayerUUID = a_PlayerUUID, PlayerName = PlayerName}))
-
- -- Terminate the row and return the entire concatenated string:
- ins(Row, "
")
- return con(Row)
-end
-
-
-
-
-
---- Returns the HTML contents of the main Rankplayers page
-local function ShowMainPlayersPage(a_Request)
- -- Read the page number:
- local PageNumber = tonumber(a_Request.Params["PageNumber"])
- if (PageNumber == nil) then
- PageNumber = 1
- end
- local StartRow = (PageNumber - 1) * PLAYERS_PER_PAGE
- local EndRow = PageNumber * PLAYERS_PER_PAGE - 1
-
- -- Accumulator for the page data
- local PageText = {}
- ins(PageText, "
")
-
- -- Add a table describing each player:
- ins(PageText, "
Playername
Rank
Action
\n")
- local AllPlayers = cRankManager:GetAllPlayerUUIDs()
- for i = StartRow, EndRow, 1 do
- local PlayerUUID = AllPlayers[i + 1]
- if (PlayerUUID ~= nil) then
- ins(PageText, GetPlayerRow(PlayerUUID))
- end
- end
- ins(PageText, "
")
-
- -- Calculate the page num:
- local MaxPages = math.floor((#AllPlayers + PLAYERS_PER_PAGE - 1) / PLAYERS_PER_PAGE)
-
- -- Display the pages list:
- ins(PageText, "
")
-
- -- Return the entire concatenated string:
- return con(PageText)
-end
-
-
-
-
-
---- Returns the HTML contents of the player add page
-local function ShowAddPlayerPage(a_Request)
- return [[
-
Add Player
-
-
-
-
-
Player Name:
-
-
-
-
Player UUID (short):
-
-
- If you leave this empty, the server generates the uuid automaticly.
-
]]
-end
-
-
-
-
-
---- Processes the AddPlayer page's input, creating a new player and redirecting to the player rank list
-local function ShowAddPlayerProcessPage(a_Request)
- -- Check the received values:
- local PlayerName = a_Request.PostParams["PlayerName"]
- local PlayerUUID = a_Request.PostParams["PlayerUUID"]
- local RankName = a_Request.PostParams["RankName"]
- if ((PlayerName == nil) or (PlayerUUID == nil) or (RankName == nil) or (RankName == "")) then
- return HTMLError("Invalid request received, missing values.")
- end
-
- -- Check if playername is given
- if (PlayerName == "") then
- return [[
-
Add Player
-
Missing Playername or name is longer than 16 chars!
- ]]
- end
-
- -- Search the uuid (if uuid line is empty)
- if (PlayerUUID == "") then
- if (cRoot:Get():GetServer():ShouldAuthenticate()) then
- PlayerUUID = cMojangAPI:GetUUIDFromPlayerName(PlayerName, false)
- else
- PlayerUUID = cClientHandle:GenerateOfflineUUID(PlayerName)
- end
- end
-
- -- Check if the uuid is correct
- if ((PlayerUUID == "") or (string.len(PlayerUUID) ~= 32)) then
- if (a_Request.PostParams["PlayerUUID"] == "") then
- return [[
-
"
-end
-
-
-
-
---- Deletes the specified player and redirects back to list
-local function ShowDelPlayerPage(a_Request)
- -- Check the input:
- local PlayerUUID = a_Request.PostParams["PlayerUUID"]
- if (PlayerUUID == nil) then
- return HTMLError("Bad request")
- end
-
- -- Delete the player:
- cRankManager:RemovePlayerRank(PlayerUUID)
- UpdateIngamePlayer(PlayerUUID, "You were assigned the rank " .. cRankManager:GetDefaultRank() .. " by webadmin.")
-
- -- Redirect back to list:
- return "
Rank deleted. Return to list."
-end
-
-
-
-
-
---- Shows a confirmation page for deleting the specified player
-local function ShowConfirmDelPage(a_Request)
- -- Check the input:
- local PlayerUUID = a_Request.PostParams["PlayerUUID"]
- local PlayerName = a_Request.PostParams["PlayerName"]
- if ((PlayerUUID == nil) or (PlayerName == nil)) then
- return HTMLError("Bad request")
- end
-
- -- Show confirmation:
- return [[
-
Delete player
-
Are you sure you want to delete player ]] .. PlayerName .. [[?
- UUID: ]] .. PlayerUUID .. [[
- ]]
-end
-
-
-
-
-
---- Returns the HTML contents of the playerrank edit page.
-local function ShowEditPlayerRankPage(a_Request)
- -- Check the input:
- local PlayerUUID = a_Request.PostParams["PlayerUUID"]
- if ((PlayerUUID == nil) or (string.len(PlayerUUID) ~= 32)) then
- return HTMLError("Bad request")
- end
-
- -- Get player name:
- local PlayerName = cRankManager:GetPlayerName(PlayerUUID)
- local PlayerRank = cRankManager:GetPlayerRankName(PlayerUUID)
-
- return [[
-
Change rank from ]] .. PlayerName .. [[
-
-
-
-
-
-
UUID
-
]] .. PlayerUUID .. [[
-
-
-
Current Rank
-
]] .. PlayerRank .. [[
-
-
-
New Rank
-
]] .. GetRankList(PlayerRank) .. [[
-
-
-
-
-
-
-
- ]]
-end
-
-
-
-
-
---- Processes the edit rank page's input, change the rank and redirecting to the player rank list
-local function ShowEditPlayerRankProcessPage(a_Request)
- -- Check the input:
- local PlayerUUID = a_Request.PostParams["PlayerUUID"]
- local NewRank = a_Request.PostParams["RankName"]
- if ((PlayerUUID == nil) or (NewRank == nil) or (string.len(PlayerUUID) ~= 32) or (NewRank == "")) then
- return HTMLError("Bad request")
- end
-
- -- Get the player name:
- local PlayerName = cRankManager:GetPlayerName(PlayerUUID)
- if (PlayerName == "") then
- return [[
-
Can't change the rank because this user doesn't exists!
- ]]
- end
-
- -- Edit the rank:
- cRankManager:SetPlayerRank(PlayerUUID, PlayerName, NewRank)
- UpdateIngamePlayer(PlayerUUID, "You were assigned the rank " .. NewRank .. " by webadmin.")
- return "
The rank from player " .. PlayerName .. " was changed to " .. NewRank .. ". Return.
"
-end
-
-
-
-
-
---- Processes the clear of all player ranks
-local function ShowClearPlayersPage(a_Request)
- cRankManager:ClearPlayerRanks();
- LOGINFO("WebAdmin: A user cleared all player ranks")
-
- -- Update ingame players:
- cRoot:Get():ForEachPlayer(
- function(a_Player)
- a_Player:LoadRank()
- end
- )
-
- return "
- ]]
-end
-
-
-
-
-
---- Handlers for the individual subpages in this tab
--- Each item maps a subpage name to a handler function that receives a HTTPRequest object and returns the HTML to return
-local g_SubpageHandlers =
-{
- [""] = ShowMainPlayersPage,
- ["addplayer"] = ShowAddPlayerPage,
- ["addplayerproc"] = ShowAddPlayerProcessPage,
- ["delplayer"] = ShowDelPlayerPage,
- ["confirmdel"] = ShowConfirmDelPage,
- ["editplayer"] = ShowEditPlayerRankPage,
- ["editplayerproc"] = ShowEditPlayerRankProcessPage,
- ["clear"] = ShowClearPlayersPage,
- ["confirmclear"] = ShowConfirmClearPage,
-}
-
-
-
-
-
---- Handles the web request coming from MCS
--- Returns the entire tab's HTML contents, based on the player's request
-function HandleRequest_PlayerRanks(a_Request)
- local Subpage = (a_Request.PostParams["subpage"] or "")
- local Handler = g_SubpageHandlers[Subpage]
- if (Handler == nil) then
- return HTMLError("An internal error has occurred, no handler for subpage " .. Subpage .. ".")
- end
-
- local PageContent = Handler(a_Request)
- return PageContent
-end
diff --git a/world/Plugins/Core/web_players.lua b/world/Plugins/Core/web_players.lua
deleted file mode 100644
index b9efaf82..00000000
--- a/world/Plugins/Core/web_players.lua
+++ /dev/null
@@ -1,478 +0,0 @@
-
--- web_players.lua
-
--- Implements the Players tab in the webadmin
-
-
-
-
-
-local ins = table.insert
-local con = table.concat
-
-
-
-
-
---- Enumerates all players currently connected to the server
--- Returns an array-table in which each item has PlayerName, PlayerUUID and WorldName
-local function EnumAllPlayers()
- local res = {}
-
- -- Insert each player into the table:
- cRoot:Get():ForEachPlayer(
- function(a_Player)
- ins(res, {
- PlayerName = a_Player:GetName(),
- PlayerUUID = a_Player:GetUUID(),
- WorldName = a_Player:GetWorld():GetName(),
- EntityID = a_Player:GetUniqueID()
- })
- end
- )
-
- return res
-end
-
-
-
-
-
---- Returns the HTML for a single table row describing the specified player
--- a_Player is the player item, a table containing PlayerName, PlayerUUID, WorldName and EntityID, as
--- returned by EnumAllPlayers
-local function GetPlayerRow(a_Player)
- -- Check params:
- assert(type(a_Player) == "table")
- assert(type(a_Player.PlayerName) == "string")
- assert(type(a_Player.PlayerUUID) == "string")
- assert(type(a_Player.WorldName) == "string")
- assert(type(a_Player.EntityID) == "number")
-
- local Row = {"
")
- return con(Row)
-end
-
-
-
-
-
---- Displays the Position details table in the Player details page
-local function GetPositionDetails(a_PlayerIdent)
- -- Get the player info:
- local PlayerInfo = {}
- local World = cRoot:Get():GetWorld(a_PlayerIdent.WorldName)
- if (World == nil) then
- return HTMLError("Error querying player position details - no world.")
- end
- World:DoWithEntityByID(a_PlayerIdent.EntityID,
- function(a_Entity)
- if not(a_Entity:IsPlayer()) then
- return
- end
- local Player = tolua.cast(a_Entity, "cPlayer")
- PlayerInfo.Pos = Player:GetPosition()
- PlayerInfo.LastBedPos = Player:GetLastBedPos()
- PlayerInfo.Found = true
- -- TODO: Other info?
- end
- )
-
- -- If the player is not present (disconnected in the meantime), display no info:
- if not(PlayerInfo.Found) then
- return ""
- end
-
- -- Display the current world and coords:
- local Page =
- {
- "
"
-
- --[[
- -- TODO
- -- Add teleport control page:
- "
Teleport control
Spawn
",
- GetFormButton("teleportcoord", "Teleport to spawn", a_PlayerIdent)
- --]]
-}
-
- return con(Page)
-end
-
-
-
-
-
---- Displays the Rank details table in the Player details page
-local function GetRankDetails(a_PlayerIdent)
- -- Display the current rank and its permissions:
- local RankName = cWebAdmin:GetHTMLEscapedString(cRankManager:GetPlayerRankName(a_PlayerIdent.PlayerUUID))
- if (RankName == "") then
- RankName = cWebAdmin:GetHTMLEscapedString(cRankManager:GetDefaultRank())
- end
- local Permissions = cRankManager:GetPlayerPermissions(a_PlayerIdent.PlayerUUID)
- table.sort(Permissions)
- local Page =
- {
- "
Rank
Current rank
",
- RankName,
- "
Permissions
",
- con(Permissions, " "),
- "
",
- }
-
- -- Let the admin change the rank using a combobox:
- ins(Page, "
")
-
- return con(Page)
-end
-
-
-
-
-
---- Displays the main Players page
--- Contains a per-world tables of all the players connected to the server
-local function ShowMainPlayersPage(a_Request)
- -- Get all players:
- local AllPlayers = EnumAllPlayers()
-
- -- Get all worlds:
- local PerWorldPlayers = {} -- Contains a map: WorldName -> {Players}
- local WorldNames = {} -- Contains an array of world names
- cRoot:Get():ForEachWorld(
- function(a_World)
- local WorldName = a_World:GetName()
- PerWorldPlayers[WorldName] = {}
- ins(WorldNames, WorldName)
- end
- )
- table.sort(WorldNames)
-
- -- Translate the list into a per-world list:
- for _, player in ipairs(AllPlayers) do
- local PerWorld = PerWorldPlayers[player.WorldName]
- ins(PerWorld, player)
- end
-
- -- For each world, display a table of players:
- local Page = {}
- for _, worldname in ipairs(WorldNames) do
- ins(Page, "
")
- ins(Page, worldname)
- ins(Page, "
Player
Rank
Actions
")
- table.sort(PerWorldPlayers[worldname],
- function (a_Player1, a_Player2)
- return (a_Player1.PlayerName < a_Player2.PlayerName)
- end
- )
- for _, player in ipairs(PerWorldPlayers[worldname]) do
- ins(Page, GetPlayerRow(player))
- end
- ins(Page, "
Total players in world: ")
- ins(Page, tostring(#PerWorldPlayers[worldname]))
- ins(Page, "
")
- end
-
- return con(Page)
-end
-
-
-
-
-
---- Displays the player details page
-local function ShowDetailsPage(a_Request)
- -- Check params:
- local WorldName = a_Request.PostParams["WorldName"]
- local EntityID = a_Request.PostParams["EntityID"]
- local PlayerName = a_Request.PostParams["PlayerName"]
- local PlayerUUID = a_Request.PostParams["PlayerUUID"]
- if ((WorldName == nil) or (EntityID == nil) or (PlayerName == nil) or (PlayerUUID == nil)) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Stuff the parameters into a table:
- local PlayerIdent =
- {
- PlayerName = PlayerName,
- WorldName = WorldName,
- EntityID = EntityID,
- PlayerUUID = PlayerUUID,
- }
-
- -- Add the header:
- local Page =
- {
- "
",
- }
-
- -- Display the position details:
- ins(Page, GetPositionDetails(PlayerIdent))
-
- -- Display the rank details:
- ins(Page, GetRankDetails(PlayerIdent))
-
- return con(Page)
-end
-
-
-
-
-
---- Handles the KickPlayer button in the main page
--- Kicks the player and redirects the admin back to the player list
-local function ShowKickPlayerPage(a_Request)
- -- Check params:
- local WorldName = a_Request.PostParams["WorldName"]
- local EntityID = a_Request.PostParams["EntityID"]
- local PlayerName = a_Request.PostParams["PlayerName"]
- if ((WorldName == nil) or (EntityID == nil) or (PlayerName == nil)) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Get the world:
- local World = cRoot:Get():GetWorld(WorldName)
- if (World == nil) then
- return HTMLError("Bad request, no such world.")
- end
-
- -- Kick the player:
- World:DoWithEntityByID(EntityID,
- function(a_Entity)
- if (a_Entity:IsPlayer()) then
- local Client = tolua.cast(a_Entity, "cPlayer"):GetClientHandle()
- if (Client ~= nil) then
- Client:Kick(a_Request.PostParams["Reason"] or "Kicked from webadmin")
- else
- LOG("Client is nil")
- end
- end
- end
- )
-
- -- Redirect the admin back to the player list:
- return "
"
-end
-
-
-
-
-
---- Displays the SendPM subpage allowing the admin to send a PM to the player
-local function ShowSendPMPage(a_Request)
- -- Check params:
- local WorldName = a_Request.PostParams["WorldName"]
- local EntityID = a_Request.PostParams["EntityID"]
- local PlayerName = a_Request.PostParams["PlayerName"]
- if ((WorldName == nil) or (EntityID == nil) or (PlayerName == nil)) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Show the form for entering the message:
- local PlayerIdent =
- {
- PlayerName = PlayerName,
- WorldName = WorldName,
- EntityID = EntityID,
- }
- return table.concat({
- "
"
- })
-end
-
-
-
-
-
---- Handles the message form from the SendPM page
--- Sends the PM, redirects the admin back to the player list
-local function ShowSendPMProcPage(a_Request)
- -- Check params:
- local WorldName = a_Request.PostParams["WorldName"]
- local EntityID = a_Request.PostParams["EntityID"]
- local PlayerName = a_Request.PostParams["PlayerName"]
- local Msg = a_Request.PostParams["Msg"]
- if ((WorldName == nil) or (EntityID == nil) or (PlayerName == nil) or (Msg == nil)) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Send the PM:
- local World = cRoot:Get():GetWorld(WorldName)
- if (World ~= nil) then
- World:DoWithEntityByID(EntityID,
- function(a_Entity)
- if (a_Entity:IsPlayer()) then
- SendMessage(tolua.cast(a_Entity, "cPlayer"), Msg)
- end
- end
- )
- end
-
- -- Redirect the admin back to the player list:
- return "
"
-end
-
-
-
-
-
---- Processes the SetRank form in the player details page
--- Sets the player's rank and redirects the admin back to the player details page
-local function ShowSetRankPage(a_Request)
- -- Check params:
- local WorldName = a_Request.PostParams["WorldName"]
- local EntityID = a_Request.PostParams["EntityID"]
- local PlayerName = a_Request.PostParams["PlayerName"]
- local PlayerUUID = a_Request.PostParams["PlayerUUID"]
- local RankName = a_Request.PostParams["RankName"]
- if ((WorldName == nil) or (EntityID == nil) or (PlayerName == nil) or (PlayerUUID == nil) or (RankName == nil)) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Change the player's rank:
- cRankManager:SetPlayerRank(PlayerUUID, PlayerName, RankName)
-
- -- Update each in-game player:
- cRoot:Get():ForEachPlayer(
- function(a_CBPlayer)
- if (a_CBPlayer:GetName() == PlayerName) then
- a_CBPlayer:SendMessage("You were assigned the rank " .. RankName .. " by webadmin.")
- a_CBPlayer:LoadRank()
- end
- end
- )
-
- -- Redirect the admin back to the player list:
- return con({
- "
"
- })
-end
-
-
-
-
-
---- Handlers for the individual subpages in this tab
--- Each item maps a subpage name to a handler function that receives a HTTPRequest object and returns the HTML to return
-local g_SubpageHandlers =
-{
- [""] = ShowMainPlayersPage,
- ["details"] = ShowDetailsPage,
- ["kick"] = ShowKickPlayerPage,
- ["sendpm"] = ShowSendPMPage,
- ["sendpmproc"] = ShowSendPMProcPage,
- ["setrank"] = ShowSetRankPage,
-}
-
-
-
-
-
---- Handles the web request coming from MCS
--- Returns the entire tab's HTML contents, based on the player's request
-function HandleRequest_Players(a_Request)
- local Subpage = (a_Request.PostParams["subpage"] or "")
- local Handler = g_SubpageHandlers[Subpage]
- if (Handler == nil) then
- return HTMLError("An internal error has occurred, no handler for subpage " .. Subpage .. ".")
- end
-
- local PageContent = Handler(a_Request)
-
- --[[
- -- DEBUG: Save content to a file for debugging purposes:
- local f = io.open("players.html", "wb")
- if (f ~= nil) then
- f:write(PageContent)
- f:close()
- end
- --]]
-
- return PageContent
-end
-
-
-
-
diff --git a/world/Plugins/Core/web_plugins.lua b/world/Plugins/Core/web_plugins.lua
deleted file mode 100644
index b8fd4a6e..00000000
--- a/world/Plugins/Core/web_plugins.lua
+++ /dev/null
@@ -1,357 +0,0 @@
-
--- web_plugins.lua
-
--- Implements the Plugins web tab used to manage plugins on the server
-
---[[
-General info: The web handler loads the settings.ini file in its start, and reads the list of enabled
-plugins out of it. Then it processes any changes requested by the user through the buttons; it carries out
-those changes on the list of enabled plugins itself. Then it saves that list back to the settings.ini. The
-changes aren't applied until the user expliticly clicks on "reload", since some changes require more than
-single reloads of the page (such as enabling a plugin and moving it into place using the up / down buttons).
---]]
-
-
-
-
-
--- Stores whether the plugin list has changed and thus the server needs to reload plugins
--- Has to be defined outside so that it keeps its value across multiple calls to the handler.
-local g_NeedsReload = false
-
-
-
-
-
---- Returns an array of plugin names that are enabled, in their load order
-local function LoadEnabledPlugins(SettingsIni)
- local res = {};
- local IniKeyPlugins = SettingsIni:FindKey("Plugins")
- if (IniKeyPlugins == cIniFile.noID) then
- -- No [Plugins] key in the INI file
- return {}
- end
-
- -- Scan each value, remember each that is named "plugin"
- for idx = 0, SettingsIni:GetNumValues(IniKeyPlugins) - 1 do
- if (string.lower(SettingsIni:GetValueName(IniKeyPlugins, idx)) == "plugin") then
- table.insert(res, SettingsIni:GetValue(IniKeyPlugins, idx))
- end
- end
- return res
-end
-
-
-
-
-
---- Saves the list of enabled plugins into the ini file
--- Keeps all the other values in the ini file intact
-local function SaveEnabledPlugins(SettingsIni, EnabledPlugins)
- -- First remove all values named "plugin":
- local IniKeyPlugins = SettingsIni:FindKey("Plugins")
- if (IniKeyPlugins ~= cIniFile.noID) then
- for idx = SettingsIni:GetNumValues(IniKeyPlugins) - 1, 0, -1 do
- if (string.lower(SettingsIni:GetValueName(IniKeyPlugins, idx)) == "plugin") then
- SettingsIni:DeleteValueByID(IniKeyPlugins, idx)
- end
- end
- end
-
- -- Now add back the entire list of enabled plugins, in our order:
- for idx, name in ipairs(EnabledPlugins) do
- SettingsIni:AddValue("Plugins", "Plugin", name)
- end
-
- -- Save to file:
- SettingsIni:WriteFile("settings.ini")
-
- -- Mark the settings as changed:
- g_NeedsReload = true
-end
-
-
-
-
-
---- Returns the lists of Enabled and Disabled plugins
--- Each list's item is a table describing the plugin - has Name, Folder, Status and LoadError
--- a_EnabledPluginFolders is an array of strings read from settings.ini listing the enabled plugins in their load order
-local function GetPluginLists(a_EnabledPluginFolders)
- -- Convert a_EnabledPluginFolders into a map {Folder -> true}:
- local EnabledPluginFolderMap = {}
- for _, folder in ipairs(a_EnabledPluginFolders) do
- EnabledPluginFolderMap[folder] = true
- end
-
- -- Retrieve a map of all known plugins:
- local PM = cPluginManager:Get()
- PM:RefreshPluginList()
- local Plugins = {} -- map {PluginFolder -> plugin}
- PM:ForEachPlugin(
- function (a_CBPlugin)
- local plugin =
- {
- Name = a_CBPlugin:GetName(),
- Folder = a_CBPlugin:GetFolderName(),
- Status = a_CBPlugin:GetStatus(),
- LoadError = a_CBPlugin:GetLoadError()
- }
- Plugins[plugin.Folder] = plugin
- end
- )
-
- -- Process the information about enabled plugins:
- local EnabledPlugins = {}
- for _, plgFolder in ipairs(a_EnabledPluginFolders) do
- table.insert(EnabledPlugins, Plugins[plgFolder])
- end
-
- -- Pick up all the disabled plugins:
- local DisabledPlugins = {}
- for folder, plugin in pairs(Plugins) do
- if not(EnabledPluginFolderMap[folder]) then
- table.insert(DisabledPlugins, plugin)
- end
- end
-
- -- Sort the disabled plugin array:
- table.sort(DisabledPlugins,
- function (a_Plugin1, a_Plugin2)
- return (string.lower(a_Plugin1.Folder) < string.lower(a_Plugin2.Folder))
- end
- )
- -- Do NOT sort EnabledPlugins - we want them listed in their load order instead!
-
- return EnabledPlugins, DisabledPlugins
-end
-
-
-
-
-
---- Builds an HTML table containing the list of plugins
--- First the enabled plugins are listed in their load order. If any is manually unloaded or errored, it is marked as such.
--- Then an alpha-sorted list of the disabled plugins
-local function ListCurrentPlugins(a_EnabledPluginFolders)
- local EnabledPlugins, DisabledPlugins = GetPluginLists(a_EnabledPluginFolders)
-
- -- Output the EnabledPlugins table:
- local res = {}
- local ins = table.insert
- if (#EnabledPlugins > 0) then
- ins(res, [[
-
Enabled plugins
-
These plugins are enabled in the server settings:
-
- ]]
- );
- local Num = #EnabledPlugins
- for idx, plugin in pairs(EnabledPlugins) do
- -- Move and Disable buttons:
- ins(res, "
")
- if (idx == 1) then
- ins(res, [[
]])
- else
- ins(res, '
')
- end
- ins(res, [[
]])
- if (idx == Num) then
- ins(res, '
')
- else
- ins(res, '
')
- end
- ins(res, '
')
-
- -- Plugin name and, if different, folder:
- ins(res, "
")
- ins(res, plugin.Folder)
- if (plugin.Folder ~= plugin.Name) then
- ins(res, " (API name ")
- ins(res, plugin.Name)
- ins(res, ")")
- end
-
- -- Plugin status, if not psLoaded:
- ins(res, "
")
- if (plugin.Status == cPluginManager.psUnloaded) then
- ins(res, "(currently unloaded)")
- elseif (plugin.Status == cPluginManager.psNotFound) then
- ins(res, "(files missing on disk)")
- elseif (plugin.Status == cPluginManager.psError) then
- ins(res, "")
- if ((plugin.LoadError == nil) or (plugin.LoadError == "")) then
- ins(res, "Unknown load error")
- else
- ins(res, plugin.LoadError)
- end
- ins(res, "")
- end
- ins(res, "
")
- end
- ins(res, "
")
- end
-
- -- Output DisabledPlugins table:
- if (#DisabledPlugins > 0) then
- ins(res, [[
Disabled plugins
-
These plugins are installed, but are disabled in the configuration.
-
]]
- )
- for idx, plugin in ipairs(DisabledPlugins) do
- ins(res, '
')
- ins(res, plugin.Name)
- ins(res, "
")
- end
- ins(res, "
")
- end
-
- return table.concat(res, "")
-end
-
-
-
-
-
---- Disables the specified plugin
--- Saves the new set of enabled plugins into a_SettingsIni
--- Returns true if the plugin was disabled
-local function DisablePlugin(a_SettingsIni, a_PluginFolder, a_EnabledPlugins)
- for idx, name in ipairs(a_EnabledPlugins) do
- if (name == a_PluginFolder) then
- table.remove(a_EnabledPlugins, idx)
- SaveEnabledPlugins(a_SettingsIni, a_EnabledPlugins)
- return true
- end
- end
- return false
-end
-
-
-
-
-
---- Enables the specified plugin
--- Saves the new set of enabled plugins into SettingsIni
--- Returns true if the plugin was enabled (false if it was already enabled before)
-local function EnablePlugin(SettingsIni, PluginName, EnabledPlugins)
- for idx, name in ipairs(EnabledPlugins) do
- if (name == PluginName) then
- -- Plugin already enabled, ignore this call
- return false
- end
- end
- -- Add the plugin to the end of the list, save:
- table.insert(EnabledPlugins, PluginName)
- SaveEnabledPlugins(SettingsIni, EnabledPlugins)
- return true
-end
-
-
-
-
-
---- Moves the specified plugin up or down by the specified delta
--- Saves the new order into SettingsIni
--- Returns true if the plugin was moved, false if not (bad delta / not found)
-local function MovePlugin(SettingsIni, PluginName, IndexDelta, EnabledPlugins)
- for idx, name in ipairs(EnabledPlugins) do
- if (name == PluginName) then
- local DstIdx = idx + IndexDelta
- if ((DstIdx < 1) or (DstIdx > #EnabledPlugins)) then
- LOGWARNING("Core WebAdmin: Requesting moving the plugin " .. PluginName .. " to invalid index " .. DstIdx .. " (max idx " .. #EnabledPlugins .. "); ignoring.")
- return false
- end
- EnabledPlugins[idx], EnabledPlugins[DstIdx] = EnabledPlugins[DstIdx], EnabledPlugins[idx] -- swap the two - we're expecting ony +1 / -1 moves
- SaveEnabledPlugins(SettingsIni, EnabledPlugins)
- return true
- end
- end
-
- -- Plugin not found:
- return false
-end
-
-
-
-
-
---- Processes the actions specified by the request parameters
--- Modifies EnabledPlugins directly to reflect the action
--- Returns the notification text to be displayed at the top of the page
-local function ProcessRequestActions(SettingsIni, Request, EnabledPlugins)
- local PluginFolder = Request.PostParams["PluginFolder"]
- if (PluginFolder == nil) then
- -- PluginFolder was not provided, so there's no action to perform
- return
- end
-
- if (Request.PostParams["DisablePlugin"] ~= nil) then
- if (DisablePlugin(SettingsIni, PluginFolder, EnabledPlugins)) then
- return '
You disabled plugin: "' .. PluginFolder .. '"
'
- end
- elseif (Request.PostParams["EnablePlugin"] ~= nil) then
- if (EnablePlugin(SettingsIni, PluginFolder, EnabledPlugins)) then
- return '
You enabled plugin: "' .. PluginFolder .. '"
'
- end
- elseif (Request.PostParams["MoveUp"] ~= nil) then
- MovePlugin(SettingsIni, PluginFolder, -1, EnabledPlugins)
- elseif (Request.PostParams["MoveDown"] ~= nil) then
- MovePlugin(SettingsIni, PluginFolder, 1, EnabledPlugins)
- end
-end
-
-
-
-
-
-function HandleRequest_ManagePlugins(Request)
- local Content = ""
-
- if (Request.PostParams["reload"] ~= nil) then
- Content = Content .. ""
- Content = Content .. "
Reloading plugins... This can take a while depending on the plugins you're using.
"
- cRoot:Get():GetPluginManager():ReloadPlugins()
- return Content
- end
-
- local SettingsIni = cIniFile()
- SettingsIni:ReadFile("settings.ini")
-
- local EnabledPlugins = LoadEnabledPlugins(SettingsIni)
-
- local NotificationText = ProcessRequestActions(SettingsIni, Request, EnabledPlugins)
- Content = Content .. (NotificationText or "")
-
- if (g_NeedsReload) then
- Content = Content .. [[
-
-
- You need to reload the plugins in order for the changes to take effect.
-
-
")
-
- -- List all groups in the rank:
- local Groups = cRankManager:GetRankGroups(a_RankName)
- table.sort(Groups)
- local NumGroups = #Groups
- if (NumGroups <= MAX_GROUPS) then
- ins(Row, con(Groups, " "))
- else
- -- There are more than MAX_GROUPS groups, display a triple-dot at the end of the list:
- ins(Row, con(Groups, " ", 1, MAX_GROUPS))
- ins(Row, " ...")
- end
- ins(Row, "
")
- ins(Row, GetFormButton("confirmdel", "Delete rank", {RankName = a_RankName}))
-
- -- Terminate the row and return the entire concatenated string:
- ins(Row, "
")
- return con(Row)
-end
-
-
-
-
-
---- Returns the HTML contents of the main Ranks page
-local function ShowMainRanksPage(a_Request)
- -- Accumulator for the page data
- local Page = {}
-
- -- Add the rank control header:
- ins(Page, "
")
-
- -- Add a table describing each rank:
- ins(Page, "
Rank
Groups
Visuals
Action
\n")
- local AllRanks = cRankManager:GetAllRanks()
- table.sort(AllRanks)
- for _, rank in ipairs(AllRanks) do
- ins(Page, GetRankRow(rank))
- end
- ins(Page, "
")
-
- -- Return the entire concatenated string:
- return con(Page)
-end
-
-
-
-
-
---- Processes the AddGroup page, adding a new group to the specified rank and redirecting back to rank's group list
-local function ShowAddGroupPage(a_Request)
- -- Check params:
- local RankName = a_Request.PostParams["RankName"]
- local NewGroupName = a_Request.PostParams["NewGroupName"]
- if ((RankName == nil) or (NewGroupName == nil)) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Add the group:
- cRankManager:AddGroupToRank(NewGroupName, RankName);
-
- -- Redirect the player:
- return
- "
Group added. Return to list."
-end
-
-
-
-
-
---- Handles the AddRank subpage.
--- Displays the HTML form for adding a new rank, processes the input
-local function ShowAddRankPage(a_Request)
- -- Display the "Add rank" webpage:
- -- TODO: Improve the color code input
- return [[
-
-
-
-
-
Rank name:
-
-
-
Message prefix:
-
-
-
Message suffix:
-
-
-
Message name color:
-
-
-
-
-
-
- ]]
-end
-
-
-
-
-
---- Processes the AddRank page's input, creating a new rank and redirecting to the rank list
-local function ShowAddRankProcessPage(a_Request)
- -- Check the received values:
- local RankName = a_Request.PostParams["RankName"]
- local MsgPrefix = a_Request.PostParams["MsgPrefix"]
- local MsgSuffix = a_Request.PostParams["MsgSuffix"]
- local MsgNameColorCode = a_Request.PostParams["MsgNameColorCode"]
- if ((RankName == nil) or (MsgPrefix == nil) or (MsgSuffix == nil) or (MsgNameColorCode == nil)) then
- return HTMLError("Invalid request received, missing values.")
- end
-
- -- Add the new rank:
- cRankManager:AddRank(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode)
- return "
- ]]
-end
-
-
-
-
-
---- Deletes the specified rank and redirects back to list
-local function ShowDelPage(a_Request)
- -- Check the input:
- local RankName = a_Request.PostParams["RankName"]
- if (RankName == nil) then
- return HTMLError("Bad request")
- end
-
- -- Delete the rank:
- cRankManager:RemoveRank(RankName)
-
- -- Redirect back to list:
- return "
Rank deleted. Return to list."
-end
-
-
-
-
-
-
---- Changes the default rank and redirects back to the list
-local function ShowEditDefaultRankPage(a_Request)
- -- Check the input:
- local RankName = a_Request.PostParams["NewGroupName"]
- if ((RankName == nil) or (RankName == "")) then
- return HTMLError("Bad request")
- end
-
- -- Change the default rank:
- if (cRankManager:SetDefaultRank(RankName)) then
- return "
Default rank changed to " .. RankName .. "! Return to list
"
- end
-end
-
-
-
-
-
---- Displays a page with all the groups, lets user add and remove groups to a rank
-local function ShowEditGroupsPage(a_Request)
- -- Check the input:
- local RankName = a_Request.PostParams["RankName"]
- if (RankName == nil) then
- return HTMLError("Bad request")
- end
-
- -- Add header:
- local Page = {[[
-
Back to rank list.
-
Add a group
-
-
-
-
-
Group:
-
]] .. GetGroupList("") .. [[
-
-
-
-
-
-
-
")
-
- -- List all the groups in the rank:
- local Groups = cRankManager:GetRankGroups(RankName)
- table.sort(Groups)
- ins(Page, "
Groups in rank ")
- ins(Page, cWebAdmin:GetHTMLEscapedString(RankName))
- ins(Page, "
")
- ins(Page, "
Group
Action
")
- for _, Group in ipairs(Groups) do
- ins(Page, "
")
- ins(Page, Group)
- ins(Page, "
")
- ins(Page, "
")
- end
- ins(Page, "
")
-
- return con(Page)
-end
-
-
-
-
-
---- Displays a page with the rank's visuals, lets user edit them
-local function ShowEditVisualsPage(a_Request)
- -- Check params:
- local RankName = a_Request.PostParams["RankName"]
- if (RankName == nil) then
- return HTMLError("Bad request, missing parameters.")
- end
-
- -- Get the current visuals to fill in:
- local MsgPrefix, MsgSuffix, MsgNameColorCode = cRankManager:GetRankVisuals(RankName)
- if (MsgPrefix == nil) then
- return HTMLError("Bad request, no such rank.")
- end
-
- -- Insert the form for changing the values:
- local Page = {"
-
- WARNING: Any changes made here might require a server restart in order to be applied!
-
]]
-
- return Content
-end
-
-
-local function ShowWorldsSettings(Request)
- local Content = ""
- local InfoMsg = nil
- local bSaveIni = false
-
- local SettingsIni = cIniFile()
- if not(SettingsIni:ReadFile("settings.ini")) then
- InfoMsg = [[ERROR: Could not read settings.ini!]]
- end
-
- if (Request.PostParams["RemoveWorld"] ~= nil) then
- Content = Content .. Request.PostParams["RemoveWorld"]
- local WorldIdx = string.sub(Request.PostParams["RemoveWorld"], string.len("Remove "))
- local KeyIdx = SettingsIni:FindKey("Worlds")
- local WorldName = SettingsIni:GetValue(KeyIdx, WorldIdx)
- if (SettingsIni:DeleteValueByID(KeyIdx, WorldIdx) == true) then
- InfoMsg = "INFO: Successfully removed world " .. WorldName .. "! "
- bSaveIni = true
- end
- end
-
- if (Request.PostParams["AddWorld"] ~= nil) then
- if (Request.PostParams["WorldName"] ~= nil and Request.PostParams["WorldName"] ~= "") then
- SettingsIni:AddValue("Worlds", "World", Request.PostParams["WorldName"])
- InfoMsg = "INFO: Successfully added world " .. Request.PostParams["WorldName"] .. "! "
- bSaveIni = true
- end
- end
-
- if (Request.PostParams["worlds_submit"] ~= nil ) then
- if Request.PostParams["Worlds_DefaultWorld"] ~= nil then
- SettingsIni:SetValue("Worlds", "DefaultWorld", Request.PostParams["Worlds_DefaultWorld"], false )
- end
- if (Request.PostParams["Worlds_World"] ~= nil) then
- SettingsIni:AddValue("Worlds", "World", Request.PostParams["Worlds_World"])
- end
- bSaveIni = true
- end
-
- if (bSaveIni) then
- if (InfoMsg == nil) then InfoMsg = "" end
- if not(SettingsIni:WriteFile("settings.ini")) then
- InfoMsg = InfoMsg .. "ERROR: Could not write to settings.ini!"
- else
- InfoMsg = InfoMsg .. "INFO: Successfully saved changes to settings.ini"
- end
- end
-
- Content = Content .. "
]]
-
- Content = Content .. [[
- WARNING: Any changes made here might require a server restart in order to be applied!
- ]]
- return Content
-end
-
-
-
-
-
-function GetAdvancedWorldSettings(Request)
- local Content = ""
- local InfoMsg = nil
- local SettingsIni = cIniFile()
-
- if not(SettingsIni:ReadFile("settings.ini")) then
- InfoMsg = [[ERROR: Could not read settings.ini!]]
- end
-
- local WORLD;
- local SelectedWorld = g_SelectedWorld[Request.Username];
-
- if (not g_SelectedWorld[Request.Username]) then
- g_SelectedWorld[Request.Username] = cRoot:Get():GetDefaultWorld()
- SelectedWorld = g_SelectedWorld[Request.Username]
- WORLD = SelectedWorld:GetName()
- else
- WORLD = g_SelectedWorld[Request.Username]:GetName()
- end
-
- if (Request.PostParams["WorldName"] ~= nil) then -- World is selected!
- WORLD = Request.PostParams["WorldName"]
- g_SelectedWorld[Request.Username] = cRoot:Get():GetWorld(WORLD)
- SelectedWorld = g_SelectedWorld[Request.Username]
- end
-
- if (Request.PostParams['WorldIniContent'] ~= nil) then
- local File = io.open(SelectedWorld:GetIniFileName(), "w")
- File:write(Request.PostParams['WorldIniContent'])
- File:close()
- end
-
- Content = Content .. "
- ]]
-
- if (Request.Params["tab"] == "Worlds") then
- Content = Content .. ShowWorldsSettings(Request)
- elseif (Request.Params["tab"] == "World") then
- Content = Content .. ShowWorldSettings(Request)
- else
- Content = Content .. ShowGeneralSettings(Request) -- Default to general settings
- end
-
- return Content
-end
diff --git a/world/Plugins/Core/web_utils.lua b/world/Plugins/Core/web_utils.lua
deleted file mode 100644
index 6f5ecde7..00000000
--- a/world/Plugins/Core/web_utils.lua
+++ /dev/null
@@ -1,54 +0,0 @@
-
--- web_utils.lua
-
--- Implements various utility functions related to the webadmin pages
-
-
-
-
-
-local ins = table.insert
-local con = table.concat
-
-
-
-
-
---- Returns the HTML-formatted error message with the specified reason
-function HTMLError(a_Reason)
- return "" .. a_Reason .. ""
-end
-
-
-
-
-
---- Returns a HTML string representing a form's Submit button
--- The form has the subpage hidden field added, and any hidden values in the a_HiddenValues map
--- All keys are left as-is, all values are HTML-escaped
-function GetFormButton(a_SubpageName, a_ButtonText, a_HiddenValues)
- -- Check params:
- assert(type(a_SubpageName) == "string")
- assert(type(a_ButtonText) == "string")
- assert(type(a_HiddenValues or {}) == "table")
-
- local res = {"")
- for k, v in pairs(a_HiddenValues) do
- ins(res, "")
- end
-
- return con(res)
-end
-
-
-
-
-
diff --git a/world/Plugins/Core/web_weather.lua b/world/Plugins/Core/web_weather.lua
deleted file mode 100644
index 52ff4d89..00000000
--- a/world/Plugins/Core/web_weather.lua
+++ /dev/null
@@ -1,72 +0,0 @@
-local function AddWorldButtons(inName)
- result = "
"
- result = result .. ""
- result = result .. ""
- result = result .. ""
- result = result .. ""
- result = result .. ""
- result = result .. ""
- result = result .. ""
- result = result .. "
"
- return result
-end
-
-function HandleRequest_Weather(Request)
- if (Request.PostParams["WorldName"] ~= nil) then -- World is selected!
- workWorldName = Request.PostParams["WorldName"]
- workWorld = cRoot:Get():GetWorld(workWorldName)
- if( Request.PostParams["SetTime"] ~= nil ) then
- -- Times used replicate vanilla: http://minecraft.gamepedia.com/Day-night_cycle#Commands
- if (Request.PostParams["SetTime"] == "Dawn") then
- workWorld:SetTimeOfDay(0)
- LOG("Time set to dawn in " .. workWorldName)
- elseif (Request.PostParams["SetTime"] == "Day") then
- workWorld:SetTimeOfDay(1000)
- LOG("Time set to day in " .. workWorldName)
- elseif (Request.PostParams["SetTime"] == "Dusk") then
- workWorld:SetTimeOfDay(12000)
- LOG("Time set to dusk in " .. workWorldName)
- elseif (Request.PostParams["SetTime"] == "Night") then
- workWorld:SetTimeOfDay(14000)
- LOG("Time set to night in " .. workWorldName)
- elseif (Request.PostParams["SetTime"] == "Midnight") then
- workWorld:SetTimeOfDay(18000)
- LOG("Time set to midnight in " .. workWorldName)
- end
- end
-
- if (Request.PostParams["SetWeather"] ~= nil) then
- if (Request.PostParams["SetWeather"] == "Sun") then
- workWorld:SetWeather(wSunny)
- LOG("Weather changed to sun in " .. workWorldName)
- elseif (Request.PostParams["SetWeather"] == "Rain") then
- workWorld:SetWeather(wRain)
- LOG("Weather changed to rain in " .. workWorldName)
- elseif (Request.PostParams["SetWeather"] == "Storm") then
- workWorld:SetWeather(wStorm)
- LOG("Weather changed to storm in " .. workWorldName)
- end
- end
- end
-
- return GenerateContent()
-end
-
-function GenerateContent()
- local content = "
"
-
- return content
-end
diff --git a/world/Plugins/Core/web_whitelist.lua b/world/Plugins/Core/web_whitelist.lua
deleted file mode 100644
index 9fe53ea9..00000000
--- a/world/Plugins/Core/web_whitelist.lua
+++ /dev/null
@@ -1,180 +0,0 @@
-
--- web_whitelist.lua
-
--- Implements the webadmin page for handling whitelist
-
-
-
-
-
-local ins = table.insert
-local con = table.concat
-
-
-
-
-
---- Returns the HTML code for an action button specific for the specified player
--- a_Player should be the player's description, as returned by ListWhitelistedPlayers()
-local function getPlayerActionButton(a_Action, a_Caption, a_Player)
- -- Check params:
- assert(type(a_Action) == "string")
- assert(type(a_Caption) == "string")
- assert(type(a_Player) == "table")
-
- -- Put together the code for the form:
- local res = { "
")
- return con(res)
-end
-
-
-
-
-
---- Returns the table row for a single player
--- a_Player should be the player's description, as returned by ListWhitelistedPlayers()
-local function getPlayerRow(a_Player)
- -- Check the params:
- assert(type(a_Player) == "table")
-
- -- Put together the code for the entire row:
- local res = { "
")
- return con(res)
-end
-
-
-
-
-
---- Returns the list of whitelisted players
-local function showList(a_Request)
- -- Show the whitelist status - enabled or disabled:
- local res = { "
" }
- if (IsWhitelistEnabled()) then
- ins(res, "Whitelist is ENABLED
")
- else
- ins(res, "Whitelist is DISABLED
")
- end
- ins(res, "
")
-
- -- Add the form to whitelist players:
- ins(res, "
Add player to whitelist: ")
- ins(res, "
")
- ins(res, "
")
-
- -- Show the whitelisted players:
- local players = ListWhitelistedPlayers()
- if (players[1] == nil) then
- ins(res, "
There are no players in the whitelist.
")
- else
- ins(res, "
Name
Date whitelisted
Whitelisted by
Action
")
- for _, player in ipairs(players) do
- ins(res, getPlayerRow(player))
- end
- end
-
- return con(res)
-end
-
-
-
-
-
---- Processes the "addplayer" action, whitelisting the specified player and returning the player list
-local function showAddPlayer(a_Request)
- -- Check HTML params:
- local playerName = a_Request.PostParams["playername"] or ""
- if (playerName == "") then
- return HTMLError("Cannot add player, bad name") .. showList(a_Request)
- end
-
- -- Whitelist the player:
- AddPlayerToWhitelist(playerName, "")
-
- -- Redirect back to the whitelist:
- return showList(a_Request)
-end
-
-
-
-
-
---- Processes the "delplayer" action, unwhitelisting the specified player and returning the player list
-local function showDelPlayer(a_Request)
- -- Check HTML params:
- local playerName = a_Request.PostParams["playername"] or ""
- if (playerName == "") then
- return HTMLError("Cannot remove player, bad name") .. showList(a_Request)
- end
-
- -- Whitelist the player:
- RemovePlayerFromWhitelist(playerName)
-
- -- Redirect back to the whitelist:
- return showList(a_Request)
-end
-
-
-
-
-
---- Processes the "disable" action, disabling the whitelist and returning the player list
-local function showDisableWhitelist(a_Request)
- WhitelistDisable()
- return showList(a_Request)
-end
-
-
-
-
-
---- Processes the "disable" action, disabling the whitelist and returning the player list
-local function showEnableWhitelist(a_Request)
- WhitelistEnable()
- return showList(a_Request)
-end
-
-
-
-
-
---- The table of all actions supported by this web tab:
-local g_ActionHandlers =
-{
- [""] = showList,
- ["addplayer"] = showAddPlayer,
- ["delplayer"] = showDelPlayer,
- ["disable"] = showDisableWhitelist,
- ["enable"] = showEnableWhitelist,
-}
-
-
-
-
-
-function HandleRequest_WhiteList(a_Request)
- local action = a_Request.PostParams["action"] or ""
- local handler = g_ActionHandlers[action]
- if (handler == nil) then
- return HTMLError("Error in whitelist processing: no action handler found for action \"" .. action .. "\"")
- end
- return handler(a_Request)
-end
-
-
-
-
diff --git a/world/Plugins/Core/whitelist.lua b/world/Plugins/Core/whitelist.lua
deleted file mode 100644
index aa095a08..00000000
--- a/world/Plugins/Core/whitelist.lua
+++ /dev/null
@@ -1,551 +0,0 @@
-
--- whitelist.lua
-
--- Implements the whitelist-related commands, console commands, API and storage
-
-
-
-
-
---- The SQLite handle to the whitelist database:
-local WhitelistDB
-
---- Global flag whether whitelist is enabled:
-local g_IsWhitelistEnabled = false
-
-
-
-
-
---- Loads the config from the DB
--- If any value cannot be read, it is kept unchanged
-local function LoadConfig()
- -- Read the g_IsWhitelistEnabled value:
- WhitelistDB:ExecuteStatement(
- "SELECT Value FROM WhitelistConfig WHERE Name='isEnabled'",
- {},
- function (a_Val)
- g_IsWhitelistEnabled = (a_Val["Value"] == "true")
- end
- )
-end
-
-
-
-
-
---- Saves the current config into the DB
-local function SaveConfig()
- -- Remove the value, if it exists:
- WhitelistDB:ExecuteStatement(
- "DELETE FROM WhitelistConfig WHERE Name='isEnabled'", {}
- )
-
- -- Insert the current value:
- WhitelistDB:ExecuteStatement(
- "INSERT INTO WhitelistConfig(Name, Value) VALUES ('isEnabled', ?)",
- { tostring(g_IsWhitelistEnabled) }
- )
-end
-
-
-
-
-
---- API: Adds the specified player to the whitelist
--- Resolves the player UUID, if needed, but only through cache, not to block
--- Returns true on success, false and optional error message on failure
-function AddPlayerToWhitelist(a_PlayerName, a_WhitelistedBy)
- -- Check params:
- assert(type(a_PlayerName) == "string")
- assert(type(a_WhitelistedBy) == "string")
-
- -- Resolve the player name to OfflineUUID and possibly OnlineUUID (if server is in online mode):
- local UUID = ""
- if (cRoot:Get():GetServer():ShouldAuthenticate()) then
- UUID = cMojangAPI:GetUUIDFromPlayerName(a_PlayerName, true)
- -- If the UUID cannot be resolved, leave it as an empty string, it will be resolved on next startup / eventually
- end
- local OfflineUUID = cClientHandle:GenerateOfflineUUID(a_PlayerName)
-
- -- Insert into DB:
- return WhitelistDB:ExecuteStatement(
- "INSERT INTO WhitelistNames (Name, UUID, OfflineUUID, Timestamp, WhitelistedBy) VALUES (?, ?, ?, ?, ?)",
- {
- a_PlayerName, UUID, OfflineUUID,
- os.time(), a_WhitelistedBy,
- }
- )
-end
-
-
-
-
-
---- API: Checks if the player is whitelisted
--- Returns true if whitelisted, false if not
--- Uses UUID for the check, and the playername with an empty UUID for a secondary check
-function IsPlayerWhitelisted(a_PlayerUUID, a_PlayerName)
- -- Check params:
- assert(type(a_PlayerUUID) == "string")
- assert(type(a_PlayerName) == "string")
- local UUID = a_PlayerUUID
- if (UUID == "") then
- -- There is no UUID supplied for the player, do not search by the UUID by using a dummy impossible value:
- UUID = "DummyImpossibleValue"
- end
-
- -- Query the DB:
- local offlineUUID = cClientHandle:GenerateOfflineUUID(a_PlayerName)
- local isWhitelisted
- assert(WhitelistDB:ExecuteStatement(
- [[
- SELECT Name FROM WhitelistNames WHERE
- (UUID = ?) OR
- (OfflineUUID = ?) OR
- ((UUID = '') AND (Name = ?))
- ]],
- { UUID, offlineUUID, a_PlayerName },
- function (a_Row)
- isWhitelisted = true
- end
- ))
- return isWhitelisted
-end
-
-
-
-
-
---- API: Returns true if whitelist is enabled
-function IsWhitelistEnabled()
- return g_IsWhitelistEnabled
-end
-
-
-
-
-
---- Returns a sorted array-table of all whitelisted players' names
-function ListWhitelistedPlayerNames()
- local res = {}
- WhitelistDB:ExecuteStatement(
- "SELECT Name FROM WhitelistNames ORDER BY Name", {},
- function (a_Columns)
- table.insert(res, a_Columns["Name"])
- end
- )
- return res
-end
-
-
-
-
-
---- Returns an array-table of all whitelisted players, sorted by player name
--- Each item is a table with the Name, OnlineUUID, OfflineUUID, Date and WhitelistedBy values
-function ListWhitelistedPlayers()
- local res = {}
- WhitelistDB:ExecuteStatement(
- "SELECT * FROM WhitelistNames ORDER BY Name", {},
- function (a_Columns)
- table.insert(res, a_Columns)
- end
- )
- return res
-end
-
-
-
-
-
---- API: Removes the specified player from the whitelist
--- No action if the player is not whitelisted
--- Returns true on success, false and optional error message on failure
-function RemovePlayerFromWhitelist(a_PlayerName)
- -- Check params:
- assert(type(a_PlayerName) == "string")
-
- -- Remove from the DB:
- return WhitelistDB:ExecuteStatement(
- "DELETE FROM WhitelistNames WHERE Name = ?",
- { a_PlayerName }
- )
-end
-
-
-
-
-
---- API: Disables the whitelist
--- After this call, any player can connect to the server
-function WhitelistDisable()
- g_IsWhitelistEnabled = false
- SaveConfig()
-end
-
-
-
-
-
---- API: Enables the whitelist
--- After this call, only whitelisted players can connect to the server
-function WhitelistEnable()
- g_IsWhitelistEnabled = true
- SaveConfig()
-end
-
-
-
-
-
---- Resolves the UUIDs for players that don't have their UUIDs in the DB
--- This may happen when whitelisting a player who never connected to the server and thus is not yet cached in the UUID lookup
-local function ResolveUUIDs()
- -- If the server is offline, bail out:
- if not(cRoot:Get():GetServer():ShouldAuthenticate()) then
- return
- end
-
- -- Collect the names of players without their UUIDs:
- local NamesToResolve = {}
- WhitelistDB:ExecuteStatement(
- "SELECT Name From WhitelistNames WHERE UUID = ''", {},
- function (a_Columns)
- table.insert(NamesToResolve, a_Columns["PlayerName"])
- end
- )
- if (#NamesToResolve == 0) then
- return;
- end
-
- -- Resolve the names:
- LOGINFO("Core: Resolving player UUIDs in the whitelist from Mojang servers. This may take a while...")
- local ResolvedNames = cMojangAPI:GetUUIDsFromPlayerNames(NamesToResolve)
- LOGINFO("Core: Resolving finished.")
-
- -- Update the names in the DB:
- for name, uuid in pairs(ResolvedNames) do
- WhitelistDB:ExecuteStatement(
- "UPDATE WhitelistNames SET UUID = ? WHERE PlayerName = ?",
- { uuid, name }
- )
- end
-end
-
-
-
-
-
---- If whitelist is disabled, sends a message to the specified player (or console if nil)
-local function NotifyWhitelistStatus(a_Player)
- -- Nothing to notify if the whitelist is enabled:
- if (g_IsWhitelistEnabled) then
- return
- end
-
- -- Send the notification msg to player / console:
- if (a_Player == nil) then
- LOG("Note: Whitelist is disabled. Use the \"whitelist on\" command to enable.")
- else
- a_Player:SendMessageInfo("Note: Whitelist is disabled. Use the \"/whitelist on\" command to enable.")
- end
-end
-
-
-
-
-
---- If whitelist is empty, sends a notification to the specified player (or console if nil)
--- Assumes that the whitelist is enabled
-local function NotifyWhitelistEmpty(a_Player)
- -- Check if whitelist is empty:
- local numWhitelisted
- local isSuccess, msg = WhitelistDB:ExecuteStatement(
- "SELECT COUNT(*) AS c FROM WhitelistNames",
- {},
- function (a_Values)
- numWhitelisted = a_Values["c"]
- end
- )
- if (not (isSuccess) or (type(numWhitelisted) ~= "number") or (numWhitelisted > 0)) then
- return
- end
-
- -- Send the notification msg to player / console:
- if (a_Player == nil) then
- LOGINFO("Note: Whitelist is empty. No player can connect to the server now. Use the \"whitelist add\" command to add players to whitelist.")
- else
- a_Player:SendMessageInfo("Note: Whitelist is empty. No player can connect to the server now. Use the \"/whitelist add\" command to add players to whitelist.")
- end
-end
-
-
-
-
-
-function HandleWhitelistAddCommand(a_Split, a_Player)
- -- Check params:
- if (a_Split[3] == nil) then
- SendMessage(a_Player, "Usage: " .. a_Split[1] .. " add ")
- return true
- end
- local playerName = a_Split[3]
-
- -- Add the player to the whitelist:
- local isSuccess, msg = AddPlayerToWhitelist(playerName, a_Player:GetName());
- if not(isSuccess) then
- SendMessageFailure(a_Player, "Cannot whitelist " .. playerName .. ": " .. (msg or ""))
- return true
- end
-
- -- Notify success:
- LOGINFO(a_Player:GetName() .. " added " .. playerName .. " to whitelist.")
- SendMessageSuccess(a_Player, "Successfully added " .. playerName .. " to whitelist.")
- NotifyWhitelistStatus(a_Player)
- return true
-end
-
-
-
-
-
-function HandleWhitelistListCommand(a_Split, a_Player)
- if (IsWhitelistEnabled()) then
- a_Player:SendMessageSuccess("Whitelist is enabled")
- else
- a_Player:SendMessageSuccess("Whitelist is disabled")
- end
- local players = ListWhitelistedPlayerNames()
- table.sort(players)
- a_Player:SendMessageSuccess(table.concat(players, ", "))
- return true
-end
-
-
-
-
-
-function HandleWhitelistOffCommand(a_Split, a_Player)
- g_IsWhitelistEnabled = true
- SaveConfig()
- a_Player:SendMessageSuccess("Whitelist is disabled.")
- return true
-end
-
-
-
-
-
-function HandleWhitelistOnCommand(a_Split, a_Player)
- g_IsWhitelistEnabled = true
- SaveConfig()
- a_Player:SendMessageSuccess("Whitelist is enabled.")
- NotifyWhitelistEmpty(a_Player)
- return true
-end
-
-
-
-
-
-function HandleWhitelistRemoveCommand(a_Split, a_Player)
- -- Check params:
- if ((a_Split[3] == nil) or (a_Split[4] ~= nil)) then
- SendMessage(a_Player, "Usage: " .. a_Split[1] .. " remove ")
- return true
- end
- local playerName = a_Split[3]
-
- -- Remove the player from the whitelist:
- local isSuccess, msg = RemovePlayerFromWhitelist(playerName)
- if not(isSuccess) then
- SendMessageFailure(a_Player, "Cannot unwhitelist " .. playerName .. ": " .. (msg or ""))
- return true
- end
-
- -- Notify success:
- LOGINFO(a_Player:GetName() .. " removed " .. playerName .. " from whitelist.")
- SendMessageSuccess(a_Player, "Removed " .. playerName .. " from whitelist.")
- NotifyWhitelistStatus(a_Player)
- return true
-end
-
-
-
-
-
-function HandleConsoleWhitelistAdd(a_Split)
- -- Check params:
- if (a_Split[3] == nil) then
- return true, "Usage: " .. a_Split[1] .. " add "
- end
- local playerName = a_Split[3]
-
- -- Whitelist the player:
- local isSuccess, msg = AddPlayerToWhitelist(playerName, "")
- if not(isSuccess) then
- return true, "Cannot whitelist " .. playerName .. ": " .. (msg or "")
- end
-
- -- Notify success:
- NotifyWhitelistStatus()
- return true, "You added " .. playerName .. " to whitelist."
-end
-
-
-
-
-
-function HandleConsoleWhitelistList(a_Split)
- local status
- if (g_IsWhitelistEnabled) then
- status = "Whitelist is ENABLED.\n"
- else
- status = "Whitelist is DISABLED.\n"
- end
- local players = ListWhitelistedPlayerNames()
- if (players[1] == nil) then
- return true, status .. "The whitelist is empty."
- else
- return true, status .. "Whitelisted players: " .. table.concat(players, ", ")
- end
-end
-
-
-
-
-
-function HandleConsoleWhitelistOff(a_Split)
- WhitelistDisable()
- return true, "Whitelist is disabled"
-end
-
-
-
-
-
-function HandleConsoleWhitelistOn(a_Split)
- WhitelistEnable()
- NotifyWhitelistEmpty()
- return true, "Whitelist is enabled"
-end
-
-
-
-
-
-function HandleConsoleWhitelistRemove(a_Split)
- -- Check params:
- if ((a_Split[3] == nil) or (a_Split[4] ~= nil)) then
- return true, "Usage: " .. a_Split[1] .. " remove "
- end
- local playerName = a_Split[3]
-
- -- Unwhitelist the player:
- local isSuccess, msg = RemovePlayerFromWhitelist(playerName)
- if not(isSuccess) then
- return true, "Cannot unwhitelist " .. playerName .. ": " .. (msg or "")
- end
-
- -- Notify success:
- NotifyWhitelistStatus()
- return true, "You removed " .. playerName .. " from whitelist."
-end
-
-
-
-
-
---- Opens the whitelist DB and checks that all the tables have the needed structure
-local function InitializeDB()
- -- Open the DB:
- local ErrMsg
- WhitelistDB, ErrMsg = NewSQLiteDB("whitelist.sqlite")
- if not(WhitelistDB) then
- LOGWARNING("Cannot open the whitelist database, whitelist not available. SQLite: " .. (ErrMsg or ""))
- error(ErrMsg)
- end
-
- -- Define the needed structure:
- local nameListColumns =
- {
- "Name",
- "UUID",
- "OfflineUUID",
- "Timestamp",
- "WhitelistedBy",
- }
- local configColumns =
- {
- "Name TEXT PRIMARY KEY",
- "Value"
- }
-
- -- Check structure:
- if (
- not(WhitelistDB:CreateDBTable("WhitelistNames", nameListColumns)) or
- not(WhitelistDB:CreateDBTable("WhitelistConfig", configColumns))
- ) then
- LOGWARNING("Cannot initialize the whitelist database, whitelist not available.")
- error("Whitelist DB failure")
- end
-
- -- Load the config:
- LoadConfig()
-end
-
-
-
-
-
-
---- Callback for the HOOK_PLAYER_JOINED hook
--- Kicks the player if they are whitelisted by UUID or Name
--- Also sets the UUID for the player in the DB, if not present
-local function OnPlayerJoined(a_Player)
- local UUID = a_Player:GetUUID()
- local Name = a_Player:GetName()
-
- -- Update the UUID in the DB, if empty:
- assert(WhitelistDB:ExecuteStatement(
- "UPDATE WhitelistNames SET UUID = ? WHERE ((UUID = '') AND (Name = ?))",
- { UUID, Name }
- ))
-
- -- If whitelist is not enabled, bail out:
- if not(g_IsWhitelistEnabled) then
- return false
- end
-
- -- Kick if not whitelisted:
- local isWhitelisted = IsPlayerWhitelisted(UUID, Name)
- if not(isWhitelisted) then
- a_Player:GetClientHandle():Kick("You are not on the whitelist")
- return true
- end
-end
-
-
-
-
-
---- Init function to be called upon plugin startup
--- Opens the whitelist DB and refreshes the player names stored within
-function InitializeWhitelist()
- -- Initialize the Whitelist DB:
- InitializeDB()
- ResolveUUIDs()
-
- -- Make a note in the console if the whitelist is enabled and empty:
- if (g_IsWhitelistEnabled) then
- NotifyWhitelistEmpty()
- end
-
- -- Add a hook to filter out non-whitelisted players:
- cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_JOINED, OnPlayerJoined)
-end
-
-
-
-
diff --git a/world/Plugins/Core/worldlimiter.lua b/world/Plugins/Core/worldlimiter.lua
deleted file mode 100644
index 26883ffd..00000000
--- a/world/Plugins/Core/worldlimiter.lua
+++ /dev/null
@@ -1,58 +0,0 @@
-local WorldLimiter_Flag = false -- True when teleportation is about to occur, false otherwise
-local WorldLimiter_LastMessage = -100 -- The last time the player was sent a message about reaching the border
-function OnPlayerMoving(Player)
- if (WorldLimiter_Flag == true) then
- return
- end
-
- local LimitChunks = WorldsWorldLimit[Player:GetWorld():GetName()]
-
- -- The world probably was created by an external plugin. Let's load the settings.
- if not LimitChunks then
- LoadWorldSettings(Player:GetWorld())
- LimitChunks = WorldsWorldLimit[Player:GetWorld():GetName()]
- end
-
- if (LimitChunks > 0) then
- local World = Player:GetWorld()
- local Limit = LimitChunks * 16 - 1
- local SpawnX = math.floor(World:GetSpawnX())
- local SpawnZ = math.floor(World:GetSpawnZ())
- local X = math.floor(Player:GetPosX())
- local Z = math.floor(Player:GetPosZ())
- local NewX = X
- local NewZ = Z
-
- if (X > SpawnX + Limit) then
- NewX = SpawnX + Limit
- elseif (X < SpawnX - Limit) then
- NewX = SpawnX - Limit
- end
-
- if (Z > SpawnZ + Limit) then
- NewZ = SpawnZ + Limit
- elseif (Z < SpawnZ - Limit) then
- NewZ = SpawnZ - Limit
- end
-
- if (X ~= NewX) or (Z ~= NewZ) then
- WorldLimiter_Flag = true
-
- local UpTime = cRoot:Get():GetServerUpTime()
- if UpTime - WorldLimiter_LastMessage > 30 then
- WorldLimiter_LastMessage = UpTime
- Player:SendMessageInfo("You have reached the world border")
- end
-
- local UUID = Player:GetUUID()
- World:ScheduleTask(3, function(World)
- World:DoWithPlayerByUUID(UUID, function(Player)
- Player:TeleportToCoords(NewX, Player:GetPosY(), NewZ)
- WorldLimiter_Flag = false
- end)
- end)
- end
-
-
- end
-end
diff --git a/world/Plugins/Debuggers/Debuggers.lua b/world/Plugins/Debuggers/Debuggers.lua
deleted file mode 100644
index f405d95a..00000000
--- a/world/Plugins/Debuggers/Debuggers.lua
+++ /dev/null
@@ -1,2383 +0,0 @@
-
--- Global variables
-g_DropSpensersToActivate = {}; -- A list of dispensers and droppers (as {World, X, Y Z} quadruplets) that are to be activated every tick
-g_HungerReportTick = 10;
-g_ShowFoodStats = false; -- When true, each player's food stats are sent to them every 10 ticks
-
-
-
-
-
-
-function Initialize(a_Plugin)
- --[[
- -- Test multiple hook handlers:
- cPluginManager.AddHook(cPluginManager.HOOK_TICK, OnTick1);
- cPluginManager.AddHook(cPluginManager.HOOK_TICK, OnTick2);
- --]]
-
- local PM = cPluginManager;
- PM:AddHook(cPluginManager.HOOK_PLAYER_USING_BLOCK, OnPlayerUsingBlock);
- PM:AddHook(cPluginManager.HOOK_PLAYER_USING_ITEM, OnPlayerUsingItem);
- PM:AddHook(cPluginManager.HOOK_TAKE_DAMAGE, OnTakeDamage);
- PM:AddHook(cPluginManager.HOOK_TICK, OnTick);
- PM:AddHook(cPluginManager.HOOK_CHAT, OnChat);
- PM:AddHook(cPluginManager.HOOK_PLAYER_RIGHT_CLICKING_ENTITY, OnPlayerRightClickingEntity);
- PM:AddHook(cPluginManager.HOOK_WORLD_TICK, OnWorldTick);
- PM:AddHook(cPluginManager.HOOK_PLUGINS_LOADED, OnPluginsLoaded);
- PM:AddHook(cPluginManager.HOOK_PLAYER_JOINED, OnPlayerJoined);
- PM:AddHook(cPluginManager.HOOK_PROJECTILE_HIT_BLOCK, OnProjectileHitBlock);
- PM:AddHook(cPluginManager.HOOK_CHUNK_UNLOADING, OnChunkUnloading);
- PM:AddHook(cPluginManager.HOOK_WORLD_STARTED, OnWorldStarted);
- PM:AddHook(cPluginManager.HOOK_PROJECTILE_HIT_BLOCK, OnProjectileHitBlock);
-
- -- _X: Disabled WECUI manipulation:
- -- PM:AddHook(cPluginManager.HOOK_PLUGIN_MESSAGE, OnPluginMessage);
- -- _X: Disabled so that the normal operation doesn't interfere with anything
- -- PM:AddHook(cPluginManager.HOOK_CHUNK_GENERATED, OnChunkGenerated);
-
- -- Load the InfoReg shared library:
- dofile(cPluginManager:GetPluginsPath() .. "/InfoReg.lua")
-
- -- Bind all the commands:
- RegisterPluginInfoCommands();
-
- -- Bind all the console commands:
- RegisterPluginInfoConsoleCommands();
-
- a_Plugin:AddWebTab("Debuggers", HandleRequest_Debuggers)
- a_Plugin:AddWebTab("StressTest", HandleRequest_StressTest)
-
- -- Enable the following line for BlockArea / Generator interface testing:
- -- PluginManager:AddHook(Plugin, cPluginManager.HOOK_CHUNK_GENERATED);
-
- -- TestBlockAreas()
- -- TestSQLiteBindings()
- -- TestExpatBindings()
- TestPluginCalls()
-
- TestBlockAreasString()
- TestStringBase64()
- -- TestUUIDFromName()
- -- TestRankMgr()
- TestFileExt()
- -- TestFileLastMod()
- TestPluginInterface()
-
- local LastSelfMod = cFile:GetLastModificationTime(a_Plugin:GetLocalFolder() .. "/Debuggers.lua")
- LOG("Debuggers.lua last modified on " .. os.date("%Y-%m-%dT%H:%M:%S", LastSelfMod))
-
- --[[
- -- Test cCompositeChat usage in console-logging:
- LOGINFO(cCompositeChat("This is a simple message with some @2 color formatting @4 and http://links.to .")
- :AddSuggestCommandPart("(Suggested command)", "cmd")
- :AddRunCommandPart("(Run command)", "cmd")
- :SetMessageType(mtInfo)
- )
- --]]
-
- -- Test the crash in #1889:
- cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_RIGHT_CLICKING_ENTITY,
- function (a_CBPlayer, a_CBEntity)
- a_CBPlayer:GetWorld():DoWithEntityByID( -- This will crash the server in #1889
- a_CBEntity:GetUniqueID(),
- function(Entity)
- LOG("RightClicking an entity, crash #1889 fixed. Entity is a " .. tolua.type(Entity))
- end
- )
- end
- )
-
- return true
-end;
-
-
-
-
-
-function TestPluginInterface()
- cPluginManager:DoWithPlugin("Core",
- function (a_CBPlugin)
- if (a_CBPlugin:GetStatus() == cPluginManager.psLoaded) then
- LOG("Core plugin was found, version " .. a_CBPlugin:GetVersion())
- else
- LOG("Core plugin is not loaded")
- end
- end
- )
-
- cPluginManager:ForEachPlugin(
- function (a_CBPlugin)
- LOG("Plugin in " .. a_CBPlugin:GetFolderName() .. " has an API name of " .. a_CBPlugin:GetName() .. " and status " .. a_CBPlugin:GetStatus())
- end
- )
-end
-
-
-
-
-function TestFileExt()
- assert(cFile:ChangeFileExt("fileless_dir/", "new") == "fileless_dir/")
- assert(cFile:ChangeFileExt("fileless_dir/", ".new") == "fileless_dir/")
- assert(cFile:ChangeFileExt("pathless_file.ext", "new") == "pathless_file.new")
- assert(cFile:ChangeFileExt("pathless_file.ext", ".new") == "pathless_file.new")
- assert(cFile:ChangeFileExt("path/to/file.ext", "new") == "path/to/file.new")
- assert(cFile:ChangeFileExt("path/to/file.ext", ".new") == "path/to/file.new")
- assert(cFile:ChangeFileExt("path/to.dir/file", "new") == "path/to.dir/file.new")
- assert(cFile:ChangeFileExt("path/to.dir/file", ".new") == "path/to.dir/file.new")
- assert(cFile:ChangeFileExt("path/to.dir/file.ext", "new") == "path/to.dir/file.new")
- assert(cFile:ChangeFileExt("path/to.dir/file.ext", ".new") == "path/to.dir/file.new")
- assert(cFile:ChangeFileExt("path/to.dir/file.longext", "new") == "path/to.dir/file.new")
- assert(cFile:ChangeFileExt("path/to.dir/file.longext", ".new") == "path/to.dir/file.new")
- assert(cFile:ChangeFileExt("path/to.dir/file.", "new") == "path/to.dir/file.new")
- assert(cFile:ChangeFileExt("path/to.dir/file.", ".new") == "path/to.dir/file.new")
-end
-
-
-
-
-
-function TestFileLastMod()
- local f = assert(io.open("test.txt", "w"))
- f:write("test")
- f:close()
- local filetime = cFile:GetLastModificationTime("test.txt")
- local ostime = os.time()
- LOG("file time: " .. filetime .. ", OS time: " .. ostime .. ", difference: " .. ostime - filetime)
-end
-
-
-
-
-
-function TestPluginCalls()
- -- In order to test the inter-plugin communication, we're going to call Core's ReturnColorFromChar() function
- -- It is a rather simple function that doesn't need any tables as its params and returns a value, too
- -- Note the signature: function ReturnColorFromChar( Split, char ) ... return cChatColog.Gray ... end
- -- The Split parameter should be a table, but it is not used in that function anyway,
- -- so we can get away with passing nil to it.
-
- LOG("Debuggers: Calling NoSuchPlugin.FnName()...")
- cPluginManager:CallPlugin("NoSuchPlugin", "FnName", "SomeParam")
- LOG("Debuggers: Calling Core.NoSuchFunction()...")
- cPluginManager:CallPlugin("Core", "NoSuchFunction", "SomeParam")
- LOG("Debuggers: Calling Core.ReturnColorFromChar(..., \"8\")...")
- local Gray = cPluginManager:CallPlugin("Core", "ReturnColorFromChar", "split", "8")
- if (Gray ~= cChatColor.Gray) then
- LOGWARNING("Debuggers: Call failed, exp " .. cChatColor.Gray .. ", got " .. (Gray or ""))
- else
- LOG("Debuggers: Call succeeded")
- end
- LOG("Debuggers: Inter-plugin calls done.")
-end
-
-
-
-
-
-function TestBlockAreas()
- LOG("Testing block areas...");
-
- -- Debug block area merging:
- local BA1 = cBlockArea();
- local BA2 = cBlockArea();
- if (BA1:LoadFromSchematicFile("schematics/test.schematic")) then
- if (BA2:LoadFromSchematicFile("schematics/fountain.schematic")) then
- BA2:SetRelBlockType(0, 0, 0, E_BLOCK_LAPIS_BLOCK);
- BA2:SetRelBlockType(1, 0, 0, E_BLOCK_LAPIS_BLOCK);
- BA2:SetRelBlockType(2, 0, 0, E_BLOCK_LAPIS_BLOCK);
- BA1:Merge(BA2, 1, 10, 1, cBlockArea.msImprint);
- BA1:SaveToSchematicFile("schematics/merge.schematic");
- end
- else
- BA1:Create(16, 16, 16);
- end
-
- -- Debug block area cuboid filling:
- BA1:FillRelCuboid(2, 9, 2, 8, 2, 8, cBlockArea.baTypes, E_BLOCK_GOLD_BLOCK);
- BA1:RelLine(2, 2, 2, 9, 8, 8, cBlockArea.baTypes or cBlockArea.baMetas, E_BLOCK_SAPLING, E_META_SAPLING_BIRCH);
- BA1:SaveToSchematicFile("schematics/fillrel.schematic");
-
- -- Debug block area mirroring:
- if (BA1:LoadFromSchematicFile("schematics/lt.schematic")) then
- BA1:MirrorXYNoMeta();
- BA1:SaveToSchematicFile("schematics/lt_XY.schematic");
- BA1:MirrorXYNoMeta();
- BA1:SaveToSchematicFile("schematics/lt_XY2.schematic");
-
- BA1:MirrorXZNoMeta();
- BA1:SaveToSchematicFile("schematics/lt_XZ.schematic");
- BA1:MirrorXZNoMeta();
- BA1:SaveToSchematicFile("schematics/lt_XZ2.schematic");
-
- BA1:MirrorYZNoMeta();
- BA1:SaveToSchematicFile("schematics/lt_YZ.schematic");
- BA1:MirrorYZNoMeta();
- BA1:SaveToSchematicFile("schematics/lt_YZ2.schematic");
- end
-
- -- Debug block area rotation:
- if (BA1:LoadFromSchematicFile("schematics/rot.schematic")) then
- BA1:RotateCWNoMeta();
- BA1:SaveToSchematicFile("schematics/rot1.schematic");
- BA1:RotateCWNoMeta();
- BA1:SaveToSchematicFile("schematics/rot2.schematic");
- BA1:RotateCWNoMeta();
- BA1:SaveToSchematicFile("schematics/rot3.schematic");
- BA1:RotateCWNoMeta();
- BA1:SaveToSchematicFile("schematics/rot4.schematic");
- end
-
- -- Debug block area rotation:
- if (BA1:LoadFromSchematicFile("schematics/rotm.schematic")) then
- BA1:RotateCCW();
- BA1:SaveToSchematicFile("schematics/rotm1.schematic");
- BA1:RotateCCW();
- BA1:SaveToSchematicFile("schematics/rotm2.schematic");
- BA1:RotateCCW();
- BA1:SaveToSchematicFile("schematics/rotm3.schematic");
- BA1:RotateCCW();
- BA1:SaveToSchematicFile("schematics/rotm4.schematic");
- end
-
- -- Debug block area mirroring:
- if (BA1:LoadFromSchematicFile("schematics/ltm.schematic")) then
- BA1:MirrorXY();
- BA1:SaveToSchematicFile("schematics/ltm_XY.schematic");
- BA1:MirrorXY();
- BA1:SaveToSchematicFile("schematics/ltm_XY2.schematic");
-
- BA1:MirrorXZ();
- BA1:SaveToSchematicFile("schematics/ltm_XZ.schematic");
- BA1:MirrorXZ();
- BA1:SaveToSchematicFile("schematics/ltm_XZ2.schematic");
-
- BA1:MirrorYZ();
- BA1:SaveToSchematicFile("schematics/ltm_YZ.schematic");
- BA1:MirrorYZ();
- BA1:SaveToSchematicFile("schematics/ltm_YZ2.schematic");
- end
-
- LOG("Block areas test ended");
-end
-
-
-
-
-
-
-function TestBlockAreasString()
- -- Write one area to string, then to file:
- local BA1 = cBlockArea()
- BA1:Create(5, 5, 5, cBlockArea.baTypes + cBlockArea.baMetas)
- BA1:Fill(cBlockArea.baTypes, E_BLOCK_DIAMOND_BLOCK)
- BA1:FillRelCuboid(1, 3, 1, 3, 1, 3, cBlockArea.baTypes, E_BLOCK_GOLD_BLOCK)
- local Data = BA1:SaveToSchematicString()
- if ((type(Data) ~= "string") or (Data == "")) then
- LOG("Cannot save schematic to string")
- return
- end
- cFile:CreateFolder("schematics")
- local f = io.open("schematics/StringTest.schematic", "wb")
- f:write(Data)
- f:close()
-
- -- Load a second area from that file:
- local BA2 = cBlockArea()
- if not(BA2:LoadFromSchematicFile("schematics/StringTest.schematic")) then
- LOG("Cannot read schematic from string test file")
- return
- end
- BA2:Clear()
-
- -- Load another area from a string in that file:
- f = io.open("schematics/StringTest.schematic", "rb")
- Data = f:read("*all")
- if not(BA2:LoadFromSchematicString(Data)) then
- LOG("Cannot load schematic from string")
- end
-end
-
-
-
-
-
-function TestStringBase64()
- -- Create a binary string:
- local s = ""
- for i = 0, 255 do
- s = s .. string.char(i)
- end
-
- -- Roundtrip through Base64:
- local Base64 = Base64Encode(s)
- local UnBase64 = Base64Decode(Base64)
-
- assert(UnBase64 == s)
-end
-
-
-
-
-
-function TestUUIDFromName()
- LOG("Testing UUID-from-Name resolution...")
-
- -- Test by querying a few existing names, along with a non-existent one:
- local PlayerNames =
- {
- "xoft",
- "aloe_vera",
- "nonexistent_player",
- }
- -- WARNING: Blocking operation! DO NOT USE IN TICK THREAD!
- local UUIDs = cMojangAPI:GetUUIDsFromPlayerNames(PlayerNames)
-
- -- Log the results:
- for _, name in ipairs(PlayerNames) do
- local UUID = UUIDs[name]
- if (UUID == nil) then
- LOG(" UUID(" .. name .. ") not found.")
- else
- LOG(" UUID(" .. name .. ") = \"" .. UUID .. "\"")
- end
- end
-
- -- Test once more with the same players, valid-only. This should go directly from cache, so fast.
- LOG("Testing again with the same valid players...")
- local ValidPlayerNames =
- {
- "xoft",
- "aloe_vera",
- }
- UUIDs = cMojangAPI:GetUUIDsFromPlayerNames(ValidPlayerNames);
-
- -- Log the results:
- for _, name in ipairs(ValidPlayerNames) do
- local UUID = UUIDs[name]
- if (UUID == nil) then
- LOG(" UUID(" .. name .. ") not found.")
- else
- LOG(" UUID(" .. name .. ") = \"" .. UUID .. "\"")
- end
- end
-
- -- Test yet again, cache-only:
- LOG("Testing once more, cache only...")
- local PlayerNames3 =
- {
- "xoft",
- "aloe_vera",
- "notch", -- Valid player name, but not cached (most likely :)
- }
- UUIDs = cMojangAPI:GetUUIDsFromPlayerNames(PlayerNames3, true)
-
- -- Log the results:
- for _, name in ipairs(PlayerNames3) do
- local UUID = UUIDs[name]
- if (UUID == nil) then
- LOG(" UUID(" .. name .. ") not found.")
- else
- LOG(" UUID(" .. name .. ") = \"" .. UUID .. "\"")
- end
- end
-
- LOG("UUID-from-Name resolution tests finished.")
-
- LOG("Performing a Name-from-UUID test...")
- -- local NameToTest = "aloe_vera"
- local NameToTest = "xoft"
- local Name = cMojangAPI:GetPlayerNameFromUUID(UUIDs[NameToTest])
- LOG("Name(" .. UUIDs[NameToTest] .. ") = '" .. Name .. "', expected '" .. NameToTest .. "'.")
- LOG("Name-from-UUID test finished.")
-end
-
-
-
-
-
-function TestRankMgr()
- LOG("Testing the rank manager")
- cRankManager:AddRank("LuaRank")
- cRankManager:AddGroup("LuaTestGroup")
- cRankManager:AddGroupToRank("LuaTestGroup", "LuaRank")
- cRankManager:AddPermissionToGroup("luaperm", "LuaTestGroup")
-end
-
-
-
-
-
-function TestSQLiteBindings()
- LOG("Testing SQLite bindings...");
-
- -- Debug SQLite binding
- local TestDB, ErrCode, ErrMsg = sqlite3.open("test.sqlite");
- if (TestDB ~= nil) then
- local function ShowRow(UserData, NumCols, Values, Names)
- assert(UserData == 'UserData');
- LOG("New row");
- for i = 1, NumCols do
- LOG(" " .. Names[i] .. " = " .. Values[i]);
- end
- return 0;
- end
- local sql = [=[
- CREATE TABLE numbers(num1,num2,str);
- INSERT INTO numbers VALUES(1, 11, "ABC");
- INSERT INTO numbers VALUES(2, 22, "DEF");
- INSERT INTO numbers VALUES(3, 33, "UVW");
- INSERT INTO numbers VALUES(4, 44, "XYZ");
- SELECT * FROM numbers;
- ]=]
- local Res = TestDB:exec(sql, ShowRow, 'UserData');
- if (Res ~= sqlite3.OK) then
- LOG("TestDB:exec() failed: " .. Res .. " (" .. TestDB:errmsg() .. ")");
- end;
- TestDB:close();
- else
- -- This happens if for example SQLite cannot open the file (eg. a folder with the same name exists)
- LOG("SQLite3 failed to open DB! (" .. ErrCode .. ", " .. ErrMsg ..")");
- end
-
- LOG("SQLite bindings test ended");
-end
-
-
-
-
-
-function TestExpatBindings()
- LOG("Testing Expat bindings...");
-
- -- Debug LuaExpat bindings:
- local count = 0
- callbacks = {
- StartElement = function (parser, name)
- LOG("+ " .. string.rep(" ", count) .. name);
- count = count + 1;
- end,
- EndElement = function (parser, name)
- count = count - 1;
- LOG("- " .. string.rep(" ", count) .. name);
- end
- }
-
- local p = lxp.new(callbacks);
- p:parse("\nnext line\nanother line");
- p:parse("text\n");
- p:parse("\n");
- p:parse("more text");
- p:parse("");
- p:parse("\n");
- p:parse(); -- finishes the document
- p:close(); -- closes the parser
-
- LOG("Expat bindings test ended");
-end
-
-
-
-
-
-function OnUsingBlazeRod(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
- -- Magic rod of query: show block types and metas for both neighbors of the pointed face
- local Valid, Type, Meta = Player:GetWorld():GetBlockTypeMeta(BlockX, BlockY, BlockZ);
-
- if (Type == E_BLOCK_AIR) then
- Player:SendMessage(cChatColor.LightGray .. "Block {" .. BlockX .. ", " .. BlockY .. ", " .. BlockZ .. "}: air:" .. Meta);
- else
- local TempItem = cItem(Type, 1, Meta);
- Player:SendMessage(cChatColor.LightGray .. "Block {" .. BlockX .. ", " .. BlockY .. ", " .. BlockZ .. "}: " .. ItemToFullString(TempItem) .. " (" .. Type .. ":" .. Meta .. ")");
- end
-
- local X, Y, Z = AddFaceDirection(BlockX, BlockY, BlockZ, BlockFace);
- Valid, Type, Meta = Player:GetWorld():GetBlockTypeMeta(X, Y, Z);
- if (Type == E_BLOCK_AIR) then
- Player:SendMessage(cChatColor.LightGray .. "Block {" .. X .. ", " .. Y .. ", " .. Z .. "}: air:" .. Meta);
- else
- local TempItem = cItem(Type, 1, Meta);
- Player:SendMessage(cChatColor.LightGray .. "Block {" .. X .. ", " .. Y .. ", " .. Z .. "}: " .. ItemToFullString(TempItem) .. " (" .. Type .. ":" .. Meta .. ")");
- end
- return false;
-end
-
-
-
-
-
-function OnUsingDiamond(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
- -- Rclk with a diamond to test block area cropping and expanding
- local Area = cBlockArea();
- Area:Read(Player:GetWorld(),
- BlockX - 19, BlockX + 19,
- BlockY - 7, BlockY + 7,
- BlockZ - 19, BlockZ + 19
- );
-
- LOG("Size before cropping: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
- Area:DumpToRawFile("crop0.dat");
-
- Area:Crop(2, 3, 0, 0, 0, 0);
- LOG("Size after cropping 1: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
- Area:DumpToRawFile("crop1.dat");
-
- Area:Crop(2, 3, 0, 0, 0, 0);
- LOG("Size after cropping 2: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
- Area:DumpToRawFile("crop2.dat");
-
- Area:Expand(2, 3, 0, 0, 0, 0);
- LOG("Size after expanding 1: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
- Area:DumpToRawFile("expand1.dat");
-
- Area:Expand(3, 2, 1, 1, 0, 0);
- LOG("Size after expanding 2: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
- Area:DumpToRawFile("expand2.dat");
-
- Area:Crop(0, 0, 0, 0, 3, 2);
- LOG("Size after cropping 3: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
- Area:DumpToRawFile("crop3.dat");
-
- Area:Crop(0, 0, 3, 2, 0, 0);
- LOG("Size after cropping 4: " .. Area:GetSizeX() .. " x " .. Area:GetSizeY() .. " x " .. Area:GetSizeZ());
- Area:DumpToRawFile("crop4.dat");
-
- LOG("Crop test done");
- Player:SendMessage("Crop / expand test done.");
- return false;
-end
-
-
-
-
-
-function OnUsingEyeOfEnder(Player, BlockX, BlockY, BlockZ)
- -- Rclk with an eye of ender places a predefined schematic at the cursor
- local Area = cBlockArea();
- if not(Area:LoadFromSchematicFile("schematics/test.schematic")) then
- LOG("Loading failed");
- return false;
- end
- LOG("Schematic loaded, placing now.");
- Area:Write(Player:GetWorld(), BlockX, BlockY, BlockZ);
- LOG("Done.");
- return false;
-end
-
-
-
-
-
-function OnUsingEnderPearl(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
- -- Rclk with an ender pearl saves a predefined area around the cursor into a .schematic file. Also tests area copying
- local Area = cBlockArea();
- if not(Area:Read(Player:GetWorld(),
- BlockX - 8, BlockX + 8, BlockY - 8, BlockY + 8, BlockZ - 8, BlockZ + 8)
- ) then
- LOG("LUA: Area couldn't be read");
- return false;
- end
- LOG("LUA: Area read, copying now.");
- local Area2 = cBlockArea();
- Area2:CopyFrom(Area);
- LOG("LUA: Copied, now saving.");
- if not(Area2:SaveToSchematicFile("schematics/test.schematic")) then
- LOG("LUA: Cannot save schematic file.");
- return false;
- end
- LOG("LUA: Done.");
- return false;
-end
-
-
-
-
-
-function OnUsingRedstoneTorch(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
- -- Redstone torch activates a rapid dispenser / dropper discharge (at every tick):
- local BlockType = Player:GetWorld():GetBlock(BlockX, BlockY, BlockZ);
- if (BlockType == E_BLOCK_DISPENSER) then
- table.insert(g_DropSpensersToActivate, {World = Player:GetWorld(), x = BlockX, y = BlockY, z = BlockZ});
- Player:SendMessage("Dispenser at {" .. BlockX .. ", " .. BlockY .. ", " .. BlockZ .. "} discharging");
- return true;
- elseif (BlockType == E_BLOCK_DROPPER) then
- table.insert(g_DropSpensersToActivate, {World = Player:GetWorld(), x = BlockX, y = BlockY, z = BlockZ});
- Player:SendMessage("Dropper at {" .. BlockX .. ", " .. BlockY .. ", " .. BlockZ .. "} discharging");
- return true;
- else
- Player:SendMessage("Neither a dispenser nor a dropper at {" .. BlockX .. ", " .. BlockY .. ", " .. BlockZ .. "}: " .. BlockType);
- end
- return false;
-end
-
-
-
-
-
-function OnPlayerUsingItem(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
-
- -- dont check if the direction is in the air
- if (BlockFace == BLOCK_FACE_NONE) then
- return false
- end
-
- local HeldItem = Player:GetEquippedItem();
- local HeldItemType = HeldItem.m_ItemType;
-
- if (HeldItemType == E_ITEM_STICK) then
- -- Magic sTick of ticking: set the pointed block for ticking at the next tick
- Player:SendMessage(cChatColor.LightGray .. "Setting next block tick to {" .. BlockX .. ", " .. BlockY .. ", " .. BlockZ .. "}")
- Player:GetWorld():SetNextBlockTick(BlockX, BlockY, BlockZ);
- return true
- elseif (HeldItemType == E_ITEM_BLAZE_ROD) then
- return OnUsingBlazeRod(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ);
- elseif (HeldItemType == E_ITEM_DIAMOND) then
- return OnUsingDiamond(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ);
- elseif (HeldItemType == E_ITEM_EYE_OF_ENDER) then
- return OnUsingEyeOfEnder(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ);
- elseif (HeldItemType == E_ITEM_ENDER_PEARL) then
- return OnUsingEnderPearl(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ);
- end
- return false;
-end
-
-
-
-
-
-function OnPlayerUsingBlock(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ, BlockType, BlockMeta)
- -- dont check if the direction is in the air
- if (BlockFace == BLOCK_FACE_NONE) then
- return false
- end
-
- local HeldItem = Player:GetEquippedItem();
- local HeldItemType = HeldItem.m_ItemType;
-
- if (HeldItemType == E_BLOCK_REDSTONE_TORCH_ON) then
- return OnUsingRedstoneTorch(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ);
- end
-end
-
-
-
-
-
-function OnTakeDamage(Receiver, TDI)
- -- Receiver is cPawn
- -- TDI is TakeDamageInfo
-
- -- LOG(Receiver:GetClass() .. " was dealt " .. DamageTypeToString(TDI.DamageType) .. " damage: Raw " .. TDI.RawDamage .. ", Final " .. TDI.FinalDamage .. " (" .. (TDI.RawDamage - TDI.FinalDamage) .. " covered by armor)");
- return false;
-end
-
-
-
-
-
-function OnTick1()
- -- For testing multiple hook handlers per plugin
- LOGINFO("Tick1");
-end
-
-
-
-
-
-function OnTick2()
- -- For testing multiple hook handlers per plugin
- LOGINFO("Tick2");
-end
-
-
-
-
-
---- When set to a positive number, the following OnTick() will perform GC and decrease until 0 again
-GCOnTick = 0;
-
-
-
-
-
-function OnTick()
- -- Activate all dropspensers in the g_DropSpensersToActivate list:
- local ActivateDrSp = function(DropSpenser)
- if (DropSpenser:GetContents():GetFirstUsedSlot() == -1) then
- return true;
- end
- DropSpenser:Activate();
- return false;
- end
- -- Walk the list backwards, because we're removing some items
- local idx = #g_DropSpensersToActivate;
- for i = idx, 1, -1 do
- local DrSp = g_DropSpensersToActivate[i];
- if not(DrSp.World:DoWithDropSpenserAt(DrSp.x, DrSp.y, DrSp.z, ActivateDrSp)) then
- table.remove(g_DropSpensersToActivate, i);
- end
- end
-
-
- -- If GCOnTick > 0, do a garbage-collect and decrease by one
- if (GCOnTick > 0) then
- collectgarbage();
- GCOnTick = GCOnTick - 1;
- end
-
- return false;
-end
-
-
-
-
-
-function OnWorldTick(a_World, a_Dt)
- -- Report food stats, if switched on:
- local Tick = a_World:GetWorldAge();
- if (not(g_ShowFoodStats) or (math.mod(Tick, 10) ~= 0)) then
- return false;
- end
- a_World:ForEachPlayer(
- function(a_Player)
- a_Player:SendMessage(
- tostring(Tick / 10) ..
- " > FS: fl " .. a_Player:GetFoodLevel() ..
- "; sat " .. a_Player:GetFoodSaturationLevel() ..
- "; exh " .. a_Player:GetFoodExhaustionLevel()
- );
- end
- );
-end
-
-
-
-
-
-function OnChat(a_Player, a_Message)
- return false, "blabla " .. a_Message;
-end
-
-
-
-
-
-function OnPlayerRightClickingEntity(a_Player, a_Entity)
- LOG("Player " .. a_Player:GetName() .. " right-clicking entity ID " .. a_Entity:GetUniqueID() .. ", a " .. a_Entity:GetClass());
- return false;
-end
-
-
-
-
-
-function OnPluginsLoaded()
- LOG("All plugins loaded");
-end
-
-
-
-
-
-function OnChunkGenerated(a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc)
- -- Get the topmost block coord:
- local Height = a_ChunkDesc:GetHeight(0, 0);
-
- -- Create a sign there:
- a_ChunkDesc:SetBlockTypeMeta(0, Height + 1, 0, E_BLOCK_SIGN_POST, 0);
- local BlockEntity = a_ChunkDesc:GetBlockEntity(0, Height + 1, 0);
- if (BlockEntity ~= nil) then
- local SignEntity = tolua.cast(BlockEntity, "cSignEntity");
- SignEntity:SetLines("Chunk:", tonumber(a_ChunkX) .. ", " .. tonumber(a_ChunkZ), "", "(Debuggers)");
- end
-
- -- Update the heightmap:
- a_ChunkDesc:SetHeight(0, 0, Height + 1);
-end
-
-
-
-
-
--- Function "round" copied from http://lua-users.org/wiki/SimpleRound
-function round(num, idp)
- local mult = 10^(idp or 0)
- if num >= 0 then return math.floor(num * mult + 0.5) / mult
- else return math.ceil(num * mult - 0.5) / mult end
-end
-
-
-
-
-
-function HandleNickCmd(Split, Player)
- if (Split[2] == nil) then
- Player:SendMessage("Usage: /nick [CustomName]");
- return true;
- end
-
- Player:SetCustomName(Split[2]);
- Player:SendMessageSuccess("Custom name setted to " .. Player:GetCustomName() .. "!")
- return true
-end
-
-
-
-
-
-function HandleListEntitiesCmd(Split, Player)
- local NumEntities = 0;
-
- local ListEntity = function(Entity)
- if (Entity:IsDestroyed()) then
- -- The entity has already been destroyed, don't list it
- return false;
- end;
- local cls = Entity:GetClass();
- Player:SendMessage(" " .. Entity:GetUniqueID() .. ": " .. cls .. " {" .. round(Entity:GetPosX(), 2) .. ", " .. round(Entity:GetPosY(), 2) .. ", " .. round(Entity:GetPosZ(), 2) .."}");
- if (cls == "cPickup") then
- local Pickup = Entity;
- tolua.cast(Pickup, "cPickup");
- Player:SendMessage(" Age: " .. Pickup:GetAge() .. ", IsCollected: " .. tostring(Pickup:IsCollected()));
- end
- NumEntities = NumEntities + 1;
- end
-
- Player:SendMessage("Listing all entities...");
- Player:GetWorld():ForEachEntity(ListEntity);
- Player:SendMessage("List finished, " .. NumEntities .. " entities listed");
- return true;
-end
-
-
-
-
-
-function HandleKillEntitiesCmd(Split, Player)
- local NumEntities = 0;
-
- local KillEntity = function(Entity)
- -- kill everything except for players:
- if (Entity:GetEntityType() ~= cEntity.etPlayer) then
- Entity:Destroy();
- NumEntities = NumEntities + 1;
- end;
- end
-
- Player:SendMessage("Killing all entities...");
- Player:GetWorld():ForEachEntity(KillEntity);
- Player:SendMessage("Killed " .. NumEntities .. " entities.");
- return true;
-end
-
-
-
-
-
-function HandleWoolCmd(Split, Player)
- local Wool = cItem(E_BLOCK_WOOL, 1, E_META_WOOL_BLUE);
- Player:GetInventory():SetArmorSlot(0, Wool);
- Player:GetInventory():SetArmorSlot(1, Wool);
- Player:GetInventory():SetArmorSlot(2, Wool);
- Player:GetInventory():SetArmorSlot(3, Wool);
- Player:SendMessage("You have been bluewooled :)");
- return true;
-end
-
-
-
-
-
-function HandleTestWndCmd(a_Split, a_Player)
- local WindowType = cWindow.wtHopper;
- local WindowSizeX = 5;
- local WindowSizeY = 1;
- if (#a_Split == 4) then
- WindowType = tonumber(a_Split[2]);
- WindowSizeX = tonumber(a_Split[3]);
- WindowSizeY = tonumber(a_Split[4]);
- elseif (#a_Split ~= 1) then
- a_Player:SendMessage("Usage: /testwnd [WindowType WindowSizeX WindowSizeY]");
- return true;
- end
-
- -- Test out the OnClosing callback's ability to refuse to close the window
- local attempt = 1;
- local OnClosing = function(Window, Player, CanRefuse)
- Player:SendMessage("Window closing attempt #" .. attempt .. "; CanRefuse = " .. tostring(CanRefuse));
- attempt = attempt + 1;
- return CanRefuse and (attempt <= 3); -- refuse twice, then allow, unless CanRefuse is set to true
- end
-
- -- Log the slot changes
- local OnSlotChanged = function(Window, SlotNum)
- LOG("Window \"" .. Window:GetWindowTitle() .. "\" slot " .. SlotNum .. " changed.");
- end
-
- local Window = cLuaWindow(WindowType, WindowSizeX, WindowSizeY, "TestWnd");
- local Item2 = cItem(E_ITEM_DIAMOND_SWORD, 1, 0, "1=1");
- local Item3 = cItem(E_ITEM_DIAMOND_SHOVEL);
- Item3.m_Enchantments:SetLevel(cEnchantments.enchUnbreaking, 4);
- local Item4 = cItem(Item3); -- Copy
- Item4.m_Enchantments:SetLevel(cEnchantments.enchEfficiency, 3); -- Add enchantment
- Item4.m_Enchantments:SetLevel(cEnchantments.enchUnbreaking, 5); -- Overwrite existing level
- local Item5 = cItem(E_ITEM_DIAMOND_CHESTPLATE, 1, 0, "thorns=1;unbreaking=3");
- Window:SetSlot(a_Player, 0, cItem(E_ITEM_DIAMOND, 64));
- Window:SetSlot(a_Player, 1, Item2);
- Window:SetSlot(a_Player, 2, Item3);
- Window:SetSlot(a_Player, 3, Item4);
- Window:SetSlot(a_Player, 4, Item5);
- Window:SetOnClosing(OnClosing);
- Window:SetOnSlotChanged(OnSlotChanged);
-
- a_Player:OpenWindow(Window);
-
- -- To make sure that the object has the correct life-management in Lua,
- -- let's garbage-collect in the following few ticks
- GCOnTick = 10;
-
- return true;
-end
-
-
-
-
-
-function HandleGCCmd(a_Split, a_Player)
- collectgarbage();
- return true;
-end
-
-
-
-
-
-
-function HandleFastCmd(a_Split, a_Player)
- if (a_Player:GetNormalMaxSpeed() <= 0.11) then
- -- The player has normal speed, set double speed:
- a_Player:SetNormalMaxSpeed(0.2);
- a_Player:SendMessage("You are now fast");
- else
- -- The player has fast speed, set normal speed:
- a_Player:SetNormalMaxSpeed(0.1);
- a_Player:SendMessage("Back to normal speed");
- end
- return true;
-end
-
-
-
-
-
-function HandleDashCmd(a_Split, a_Player)
- if (a_Player:GetSprintingMaxSpeed() <= 0.14) then
- -- The player has normal sprinting speed, set double Sprintingspeed:
- a_Player:SetSprintingMaxSpeed(0.4);
- a_Player:SendMessage("You can now sprint very fast");
- else
- -- The player has fast sprinting speed, set normal sprinting speed:
- a_Player:SetSprintingMaxSpeed(0.13);
- a_Player:SendMessage("Back to normal sprinting");
- end
- return true;
-end;
-
-
-
-
-
-function HandleHungerCmd(a_Split, a_Player)
- a_Player:SendMessage("FoodLevel: " .. a_Player:GetFoodLevel());
- a_Player:SendMessage("FoodSaturationLevel: " .. a_Player:GetFoodSaturationLevel());
- a_Player:SendMessage("FoodTickTimer: " .. a_Player:GetFoodTickTimer());
- a_Player:SendMessage("FoodExhaustionLevel: " .. a_Player:GetFoodExhaustionLevel());
- a_Player:SendMessage("FoodPoisonedTicksRemaining: " .. a_Player:GetFoodPoisonedTicksRemaining());
- return true;
-end
-
-
-
-
-
-function HandlePoisonCmd(a_Split, a_Player)
- a_Player:FoodPoison(15 * 20);
- return true;
-end
-
-
-
-
-
-function HandleStarveCmd(a_Split, a_Player)
- a_Player:SetFoodLevel(0);
- a_Player:SendMessage("You are now starving");
- return true;
-end
-
-
-
-
-
-function HandleFoodLevelCmd(a_Split, a_Player)
- if (#a_Split ~= 2) then
- a_Player:SendMessage("Missing an argument: the food level to set");
- return true;
- end
-
- a_Player:SetFoodLevel(tonumber(a_Split[2]));
- a_Player:SetFoodSaturationLevel(5);
- a_Player:SetFoodExhaustionLevel(0);
- a_Player:SendMessage(
- "Food level set to " .. a_Player:GetFoodLevel() ..
- ", saturation reset to " .. a_Player:GetFoodSaturationLevel() ..
- " and exhaustion reset to " .. a_Player:GetFoodExhaustionLevel()
- );
- return true;
-end
-
-
-
-
-
-function HandleSpideyCmd(a_Split, a_Player)
- -- Place a line of cobwebs from the player's eyes until non-air block, in the line-of-sight of the player
- local World = a_Player:GetWorld();
-
- local Callbacks = {
- OnNextBlock = function(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta)
- if (a_BlockType ~= E_BLOCK_AIR) then
- -- abort the trace
- return true;
- end
- World:SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_COBWEB, 0);
- end
- };
-
- local EyePos = a_Player:GetEyePosition();
- local LookVector = a_Player:GetLookVector();
- LookVector:Normalize();
-
- -- Start cca 2 blocks away from the eyes
- local Start = EyePos + LookVector + LookVector;
- local End = EyePos + LookVector * 50;
-
- cLineBlockTracer.Trace(World, Callbacks, Start.x, Start.y, Start.z, End.x, End.y, End.z);
-
- return true;
-end
-
-
-
-
-
-function HandleEnchCmd(a_Split, a_Player)
- local Wnd = cLuaWindow(cWindow.wtEnchantment, 1, 1, "Ench");
- a_Player:OpenWindow(Wnd);
- Wnd:SetProperty(0, 10);
- Wnd:SetProperty(1, 15);
- Wnd:SetProperty(2, 25);
- return true;
-end
-
-
-
-
-
-function HandleFoodStatsCmd(a_Split, a_Player)
- g_ShowFoodStats = not(g_ShowFoodStats);
- return true;
-end
-
-
-
-
-
-function HandleArrowCmd(a_Split, a_Player)
- local World = a_Player:GetWorld();
- local Pos = a_Player:GetEyePosition();
- local Speed = a_Player:GetLookVector();
- Speed:Normalize();
- Pos = Pos + Speed;
-
- World:CreateProjectile(Pos.x, Pos.y, Pos.z, cProjectileEntity.pkArrow, a_Player, Speed * 10);
- return true;
-end
-
-
-
-
-
-function HandleFireballCmd(a_Split, a_Player)
- local World = a_Player:GetWorld();
- local Pos = a_Player:GetEyePosition();
- local Speed = a_Player:GetLookVector();
- Speed:Normalize();
- Pos = Pos + Speed * 2;
-
- World:CreateProjectile(Pos.x, Pos.y, Pos.z, cProjectileEntity.pkGhastFireball, a_Player, Speed * 10);
- return true;
-end
-
-
-
-
-function HandleAddExperience(a_Split, a_Player)
- a_Player:DeltaExperience(200);
-
- return true;
-end
-
-
-
-
-
-function HandleRemoveXp(a_Split, a_Player)
- a_Player:SetCurrentExperience(0);
-
- return true;
-end
-
-
-
-
-
-function HandleFill(a_Split, a_Player)
- local World = a_Player:GetWorld();
- local ChunkX = a_Player:GetChunkX();
- local ChunkZ = a_Player:GetChunkZ();
- World:ForEachBlockEntityInChunk(ChunkX, ChunkZ,
- function(a_BlockEntity)
- local BlockType = a_BlockEntity:GetBlockType();
- if (
- (BlockType == E_BLOCK_CHEST) or
- (BlockType == E_BLOCK_DISPENSER) or
- (BlockType == E_BLOCK_DROPPER) or
- (BlockType == E_BLOCK_FURNACE) or
- (BlockType == E_BLOCK_HOPPER)
- ) then
- -- This block entity has items (inherits from cBlockEntityWithItems), fill it:
- -- Note that we're not touching lit furnaces, don't wanna mess them up
- local EntityWithItems = tolua.cast(a_BlockEntity, "cBlockEntityWithItems");
- local ItemGrid = EntityWithItems:GetContents();
- local NumSlots = ItemGrid:GetNumSlots();
- local ItemToSet = cItem(E_ITEM_GOLD_NUGGET);
- for i = 0, NumSlots - 1 do
- if (ItemGrid:GetSlot(i):IsEmpty()) then
- ItemGrid:SetSlot(i, ItemToSet);
- end
- end
- end
- end
- );
- return true;
-end
-
-
-
-
-
-function HandleFurnaceRecipe(a_Split, a_Player)
- local HeldItem = a_Player:GetEquippedItem();
- local Out, NumTicks, In = cRoot:GetFurnaceRecipe(HeldItem);
- if (Out ~= nil) then
- a_Player:SendMessage(
- "Furnace turns " .. ItemToFullString(In) ..
- " to " .. ItemToFullString(Out) ..
- " in " .. NumTicks .. " ticks (" ..
- tostring(NumTicks / 20) .. " seconds)."
- );
- else
- a_Player:SendMessage("There is no furnace recipe that would smelt " .. ItemToString(HeldItem));
- end
- return true;
-end
-
-
-
-
-
-function HandleFurnaceFuel(a_Split, a_Player)
- local HeldItem = a_Player:GetEquippedItem();
- local NumTicks = cRoot:GetFurnaceFuelBurnTime(HeldItem);
- if (NumTicks > 0) then
- a_Player:SendMessage(
- ItemToFullString(HeldItem) .. " would power a furnace for " .. NumTicks ..
- " ticks (" .. tostring(NumTicks / 20) .. " seconds)."
- );
- else
- a_Player:SendMessage(ItemToString(HeldItem) .. " will not power furnaces.");
- end
- return true;
-end
-
-
-
-
-
-function HandleSched(a_Split, a_Player)
- local World = a_Player:GetWorld()
-
- -- Schedule a broadcast of a countdown message:
- for i = 1, 10 do
- World:ScheduleTask(i * 20,
- function(a_World)
- a_World:BroadcastChat("Countdown: " .. 11 - i)
- end
- )
- end
-
- -- Schedule a broadcast of the final message and a note to the originating player
- -- Note that we CANNOT use the a_Player in the callback - what if the player disconnected?
- -- Therefore we store the player's EntityID
- local PlayerID = a_Player:GetUniqueID()
- World:ScheduleTask(220,
- function(a_World)
- a_World:BroadcastChat("Countdown: BOOM")
- a_World:DoWithEntityByID(PlayerID,
- function(a_Entity)
- if (a_Entity:IsPlayer()) then
- -- Although unlikely, it is possible that this player is not the originating player
- -- However, I leave this as an excercise to you to fix this "bug"
- local Player = tolua.cast(a_Entity, "cPlayer")
- Player:SendMessage("Countdown finished")
- end
- end
- )
- end
- )
-
- return true
-end
-
-
-
-
-
-function HandleRMItem(a_Split, a_Player)
- -- Check params:
- if (a_Split[2] == nil) then
- a_Player:SendMessage("Usage: /rmitem [Count]")
- return true
- end
-
- -- Parse the item type:
- local Item = cItem()
- if (not StringToItem(a_Split[2], Item)) then
- a_Player:SendMessageFailure(a_Split[2] .. " isn't a valid item")
- return true
- end
-
- -- Parse the optional item count
- if (a_Split[3] ~= nil) then
- local Count = tonumber(a_Split[3])
- if (Count == nil) then
- a_Player:SendMessageFailure(a_Split[3] .. " isn't a valid number")
- return true
- end
-
- Item.m_ItemCount = Count
- end
-
- -- Remove the item:
- local NumRemovedItems = a_Player:GetInventory():RemoveItem(Item)
- a_Player:SendMessageSuccess("Removed " .. NumRemovedItems .. " Items!")
- return true
-end
-
-
-
-
-
-function HandleRequest_Debuggers(a_Request)
- local FolderContents = cFile:GetFolderContents("./");
- return "
The following objects have been returned by cFile:GetFolderContents():
The counter below should be reloading as fast as possible
0
"
-end
-
-
-
-
-
-function OnPluginMessage(a_Client, a_Channel, a_Message)
- LOGINFO("Received a plugin message from client " .. a_Client:GetUsername() .. ": channel '" .. a_Channel .. "', message '" .. a_Message .. "'");
-
- if (a_Channel == "REGISTER") then
- if (a_Message:find("WECUI")) then
- -- The client has WorldEditCUI mod installed, test the comm by sending a few WECUI messages:
- --[[
- WECUI messages have the following generic format:
- |
- If shape is p (cuboid selection), the params are sent individually for each corner click and have the following format:
- ||||
- point-index is 0 or 1 (lclk / rclk)
- volume is the 3D volume of the current cuboid selected (all three coords' deltas multiplied), including the edge blocks; -1 if N/A
- --]]
- -- Select a 51 * 51 * 51 block cuboid:
- a_Client:SendPluginMessage("WECUI", "p|0|50|50|50|-1");
- a_Client:SendPluginMessage("WECUI", "p|1|100|100|100|132651"); -- 132651 = 51 * 51 * 51
- end
- end
-end
-
-
-
-
-
-function HandleChunkStay(a_Split, a_Player)
- -- As an example of using ChunkStay, this call will load 3x3 chunks around the specified chunk coords,
- -- then build an obsidian pillar in the middle of each one.
- -- Once complete, the player will be teleported to the middle pillar
-
- if (#a_Split ~= 3) then
- a_Player:SendMessageInfo("Usage: /cs ")
- return true
- end
-
- local ChunkX = tonumber(a_Split[2])
- local ChunkZ = tonumber(a_Split[3])
- if ((ChunkX == nil) or (ChunkZ == nil)) then
- a_Player:SendMessageFailure("Invalid chunk coords.")
- return true
- end
-
- local World = a_Player:GetWorld()
- local PlayerID = a_Player:GetUniqueID()
- a_Player:SendMessageInfo("Loading chunks, stand by...");
-
- -- Set the wanted chunks:
- local Chunks = {}
- for z = -1, 1 do for x = -1, 1 do
- table.insert(Chunks, {ChunkX + x, ChunkZ + z})
- end end
-
- -- The function that is called when all chunks are available
- -- Will perform the actual action with all those chunks
- -- Note that the player needs to be referenced using their EntityID - in case they disconnect before the chunks load
- local OnAllChunksAvailable = function()
- LOGINFO("ChunkStay all chunks now available")
- -- Build something on the neighboring chunks, to verify:
- for z = -1, 1 do for x = -1, 1 do
- local BlockX = (ChunkX + x) * 16 + 8
- local BlockZ = (ChunkZ + z) * 16 + 8
- for y = 20, 80 do
- World:SetBlock(BlockX, y, BlockZ, E_BLOCK_OBSIDIAN, 0)
- end
- end end
-
- -- Teleport the player there for visual inspection:
- World:DoWithEntityByID(PlayerID,
- function (a_CallbackPlayer)
- a_CallbackPlayer:TeleportToCoords(ChunkX * 16 + 8, 85, ChunkZ * 16 + 8)
- a_CallbackPlayer:SendMessageSuccess("ChunkStay fully available")
- end
- )
- end
-
- -- This function will be called for each chunk that is made available
- -- Note that the player needs to be referenced using their EntityID - in case they disconnect before the chunks load
- local OnChunkAvailable = function(a_ChunkX, a_ChunkZ)
- LOGINFO("ChunkStay now has chunk [" .. a_ChunkX .. ", " .. a_ChunkZ .. "]")
- World:DoWithEntityByID(PlayerID,
- function (a_CallbackPlayer)
- a_CallbackPlayer:SendMessageInfo("ChunkStay now has chunk [" .. a_ChunkX .. ", " .. a_ChunkZ .. "]")
- end
- )
- end
-
- -- Process the ChunkStay:
- World:ChunkStay(Chunks, OnChunkAvailable, OnAllChunksAvailable)
- return true
-end
-
-
-
-
-
-function HandleCompo(a_Split, a_Player)
- -- Send one composite message to self:
- local msg = cCompositeChat()
- msg:AddTextPart("Hello! ", "b@e") -- bold yellow
- msg:AddUrlPart("Cuberite", "http://cuberite.org")
- msg:AddTextPart(" rules! ")
- msg:AddRunCommandPart("Set morning", "/time set 0")
- a_Player:SendMessage(msg)
-
- -- Broadcast another one to the world:
- local msg2 = cCompositeChat()
- msg2:AddSuggestCommandPart(a_Player:GetName(), "/tell " .. a_Player:GetName() .. " ")
- msg2:AddTextPart(" knows how to use cCompositeChat!");
- a_Player:GetWorld():BroadcastChat(msg2)
-
- return true
-end
-
-
-
-
-
-function HandleSetBiome(a_Split, a_Player)
- local Biome = biJungle
- local Size = 20
- local SplitSize = #a_Split
- if (SplitSize > 3) then
- a_Player:SendMessage("Too many parameters. Usage: " .. a_Split[1] .. " ")
- return true
- end
-
- if (SplitSize >= 2) then
- Biome = StringToBiome(a_Split[2])
- if (Biome == biInvalidBiome) then
- a_Player:SendMessage("Unknown biome: '" .. a_Split[2] .. "'. Command ignored.")
- return true
- end
- end
- if (SplitSize >= 3) then
- Size = tostring(a_Split[3])
- if (Size == nil) then
- a_Player:SendMessage("Unknown size: '" .. a_Split[3] .. "'. Command ignored.")
- return true
- end
- end
-
- local BlockX = math.floor(a_Player:GetPosX())
- local BlockZ = math.floor(a_Player:GetPosZ())
- a_Player:GetWorld():SetAreaBiome(BlockX - Size, BlockX + Size, BlockZ - Size, BlockZ + Size, Biome)
- a_Player:SendMessage(
- "Blocks {" .. (BlockX - Size) .. ", " .. (BlockZ - Size) ..
- "} - {" .. (BlockX + Size) .. ", " .. (BlockZ + Size) ..
- "} set to biome #" .. tostring(Biome) .. "."
- )
- return true
-end
-
-
-
-
-
-function HandleWESel(a_Split, a_Player)
- -- Check if the selection is a cuboid:
- local IsCuboid = cPluginManager:CallPlugin("WorldEdit", "IsPlayerSelectionCuboid")
- if (IsCuboid == nil) then
- a_Player:SendMessage(cCompositeChat():SetMessageType(mtFailure):AddTextPart("Cannot adjust selection, WorldEdit is not loaded"))
- return true
- elseif (IsCuboid == false) then
- a_Player:SendMessage(cCompositeChat():SetMessageType(mtFailure):AddTextPart("Cannot adjust selection, the selection is not a cuboid"))
- return true
- end
-
- -- Get the selection:
- local SelCuboid = cCuboid()
- local IsSuccess = cPluginManager:CallPlugin("WorldEdit", "GetPlayerCuboidSelection", a_Player, SelCuboid)
- if not(IsSuccess) then
- a_Player:SendMessage(cCompositeChat():SetMessageType(mtFailure):AddTextPart("Cannot adjust selection, WorldEdit reported failure while getting current selection"))
- return true
- end
-
- -- Adjust the selection:
- local NumBlocks = tonumber(a_Split[2] or "1") or 1
- SelCuboid:Expand(NumBlocks, NumBlocks, 0, 0, NumBlocks, NumBlocks)
-
- -- Set the selection:
- IsSuccess = cPluginManager:CallPlugin("WorldEdit", "SetPlayerCuboidSelection", a_Player, SelCuboid)
- if not(IsSuccess) then
- a_Player:SendMessage(cCompositeChat():SetMessageType(mtFailure):AddTextPart("Cannot adjust selection, WorldEdit reported failure while setting new selection"))
- return true
- end
- a_Player:SendMessage(cCompositeChat():SetMessageType(mtInformation):AddTextPart("Successfully adjusted the selection by " .. NumBlocks .. " block(s)"))
- return true
-end
-
-
-
-
-
-function OnPlayerJoined(a_Player)
- -- Test composite chat chaining:
- a_Player:SendMessage(cCompositeChat()
- :AddTextPart("Hello, ")
- :AddUrlPart(a_Player:GetName(), "http://cuberite.org", "u@2")
- :AddSuggestCommandPart(", and welcome.", "/help", "u")
- :AddRunCommandPart(" SetDay", "/time set 0")
- )
-end
-
-
-
-
-
-function OnProjectileHitBlock(a_Projectile, a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, a_BlockHitPos)
- -- Test projectile hooks by setting the blocks they hit on fire:
- local BlockX, BlockY, BlockZ = AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, a_BlockFace)
- local World = a_Projectile:GetWorld()
-
- World:SetBlock(BlockX, BlockY, BlockZ, E_BLOCK_FIRE, 0)
-end
-
-
-
-
-
-function OnChunkUnloading(a_World, a_ChunkX, a_ChunkZ)
- -- Do not let chunk [0, 0] unload, so that it continues ticking [cWorld:SetChunkAlwaysTicked() test]
- if ((a_ChunkX == 0) and (a_ChunkZ == 0)) then
- return true
- end
-end
-
-
-
-
-
-function OnWorldStarted(a_World)
- -- Make the chunk [0, 0] in every world keep ticking [cWorld:SetChunkAlwaysTicked() test]
- a_World:ChunkStay({{0, 0}}, nil,
- function()
- -- The chunk is loaded, make it always tick:
- a_World:SetChunkAlwaysTicked(0, 0, true)
- end
- )
-end
-
-
-
-
-
-function OnProjectileHitBlock(a_ProjectileEntity, a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, a_BlockHitPos)
- -- This simple test is for testing issue #1326 - simply declaring this hook would crash the server upon call
- LOG("Projectile hit block")
- LOG(" Projectile EntityID: " .. a_ProjectileEntity:GetUniqueID())
- LOG(" Block: {" .. a_BlockX .. ", " .. a_BlockY .. ", " .. a_BlockZ .. "}, face " .. a_BlockFace)
- LOG(" HitPos: {" .. a_BlockHitPos.x .. ", " .. a_BlockHitPos.y .. ", " .. a_BlockHitPos.z .. "}")
-end
-
-
-
-
-
-local PossibleItems =
-{
- cItem(E_ITEM_DIAMOND),
- cItem(E_ITEM_GOLD),
- cItem(E_ITEM_IRON),
- cItem(E_ITEM_DYE, 1, E_META_DYE_BLUE), -- Lapis lazuli
- cItem(E_ITEM_COAL),
-}
-
-
-
-
-
-function HandlePickups(a_Split, a_Player)
- local PlayerX = a_Player:GetPosX()
- local PlayerY = a_Player:GetPosY()
- local PlayerZ = a_Player:GetPosZ()
- local World = a_Player:GetWorld()
- local Range = 12
- for x = 0, Range do for z = 0, Range do
- local px = PlayerX + x - Range / 2
- local pz = PlayerZ + z - Range / 2
- local Items = cItems()
- Items:Add(PossibleItems[math.random(#PossibleItems)])
- World:SpawnItemPickups(Items, px, PlayerY, pz, 0)
- end end -- for z, for x
- return true
-end
-
-
-
-
-
-function HandlePlugMsg(a_Split, a_Player)
- local ch = a_Player:GetClientHandle()
- ch:SendPluginMessage("TestCh", "some\0string\1with\2funny\3chars")
- return true
-end
-
-
-
-
-
-function HandlePoof(a_Split, a_Player)
- local PlayerPos = Vector3d(a_Player:GetPosition()) -- Create a copy of the position
- PlayerPos.y = PlayerPos.y - 1
- local Box = cBoundingBox(PlayerPos, 4, 2)
- local NumEntities = 0
- a_Player:GetWorld():ForEachEntityInBox(Box,
- function (a_Entity)
- if not(a_Entity:IsPlayer()) then
- local AddSpeed = a_Entity:GetPosition() - PlayerPos -- Speed away from the player
- a_Entity:AddSpeed(AddSpeed * 32 / (AddSpeed:SqrLength() + 1)) -- The further away, the less speed to add
- NumEntities = NumEntities + 1
- end
- end
- )
- a_Player:SendMessage("Poof! (" .. NumEntities .. " entities)")
- return true
-end
-
-
-
-
-
--- List of hashing functions to test:
-local HashFunctions =
-{
- {"md5", md5 },
- {"cCryptoHash.md5", cCryptoHash.md5 },
- {"cCryptoHash.md5HexString", cCryptoHash.md5HexString },
- {"cCryptoHash.sha1", cCryptoHash.sha1 },
- {"cCryptoHash.sha1HexString", cCryptoHash.sha1HexString },
-}
-
--- List of strings to try hashing:
-local HashExamples =
-{
- "",
- "\0",
- "test",
-}
-
-function HandleConsoleHash(a_Split)
- for _, str in ipairs(HashExamples) do
- LOG("Hashing string \"" .. str .. "\":")
- for _, hash in ipairs(HashFunctions) do
- if not(hash[2]) then
- LOG("Hash function " .. hash[1] .. " doesn't exist in the API!")
- else
- LOG(hash[1] .. "() = " .. hash[2](str))
- end
- end -- for hash - HashFunctions[]
- end -- for str - HashExamples[]
- return true
-end
-
-
-
-
-
---- Monitors the state of the "inh" entity-spawning hook
--- if false, the hook is installed before the "inh" command processing
-local isInhHookInstalled = false
-
-function HandleConsoleInh(a_Split, a_FullCmd)
- -- Check the param:
- local kindStr = a_Split[2] or "pkArrow"
- local kind = cProjectileEntity[kindStr]
- if (kind == nil) then
- return true, "There's no projectile kind '" .. kindStr .. "'."
- end
-
- -- Get the world to test in:
- local world = cRoot:Get():GetDefaultWorld()
- if (world == nil) then
- return true, "Cannot test inheritance, no default world"
- end
-
- -- Install the hook, if needed:
- if not(isInhHookInstalled) then
- cPluginManager:AddHook(cPluginManager.HOOK_SPAWNING_ENTITY,
- function (a_CBWorld, a_CBEntity)
- LOG("New entity is spawning:")
- LOG(" Lua type: '" .. type(a_CBEntity) .. "'")
- LOG(" ToLua type: '" .. tolua.type(a_CBEntity) .. "'")
- LOG(" GetEntityType(): '" .. a_CBEntity:GetEntityType() .. "'")
- LOG(" GetClass(): '" .. a_CBEntity:GetClass() .. "'")
- end
- )
- isInhHookInstalled = true
- end
-
- -- Create the projectile:
- LOG("Creating a " .. kindStr .. " projectile in world " .. world:GetName() .. "...")
- local msg
- world:ChunkStay({{0, 0}},
- nil,
- function ()
- -- Create a projectile at {8, 100, 8}:
- local entityID = world:CreateProjectile(8, 100, 8, kind, nil, nil)
- if (entityID < 0) then
- msg = "Cannot test inheritance, projectile creation failed."
- return
- end
- LOG("Entity created, ID #" .. entityID)
-
- -- Call a function on the newly created entity:
- local hasExecutedCallback = false
- world:DoWithEntityByID(
- entityID,
- function (a_CBEntity)
- LOG("Projectile created and found using the DoWithEntityByID() callback")
- LOG("Lua type: '" .. type(a_CBEntity) .. "'")
- LOG("ToLua type: '" .. tolua.type(a_CBEntity) .. "'")
- LOG("GetEntityType(): '" .. a_CBEntity:GetEntityType() .. "'")
- LOG("GetClass(): '" .. a_CBEntity:GetClass() .. "'")
- hasExecutedCallback = true
- end
- )
- if not(hasExecutedCallback) then
- msg = "The callback failed to execute"
- return
- end
-
- msg = "Inheritance test finished"
- end
- )
-
- return true, msg
-end
-
-
-
-
-
-function HandleConsoleLoadChunk(a_Split)
- -- Check params:
- local numParams = #a_Split
- if (numParams ~= 3) and (numParams ~= 4) then
- return true, "Usage: " .. a_Split[1] .. " []"
- end
-
- -- Get the chunk coords:
- local chunkX = tonumber(a_Split[2])
- if (chunkX == nil) then
- return true, "Not a number: '" .. a_Split[2] .. "'"
- end
- local chunkZ = tonumber(a_Split[3])
- if (chunkZ == nil) then
- return true, "Not a number: '" .. a_Split[3] .. "'"
- end
-
- -- Get the world:
- local world
- if (a_Split[4] == nil) then
- world = cRoot:Get():GetDefaultWorld()
- else
- world = cRoot:Get():GetWorld(a_Split[4])
- if (world == nil) then
- return true, "There's no world named '" .. a_Split[4] .. "'."
- end
- end
-
- -- Queue a ChunkStay for the chunk, log a message when the chunk is loaded:
- world:ChunkStay({{chunkX, chunkZ}}, nil,
- function()
- LOG("Chunk [" .. chunkX .. ", " .. chunkZ .. "] is loaded")
- end
- )
- return true
-end
-
-
-
-
-
-function HandleConsolePrepareChunk(a_Split)
- -- Check params:
- local numParams = #a_Split
- if (numParams ~= 3) and (numParams ~= 4) then
- return true, "Usage: " .. a_Split[1] .. " []"
- end
-
- -- Get the chunk coords:
- local chunkX = tonumber(a_Split[2])
- if (chunkX == nil) then
- return true, "Not a number: '" .. a_Split[2] .. "'"
- end
- local chunkZ = tonumber(a_Split[3])
- if (chunkZ == nil) then
- return true, "Not a number: '" .. a_Split[3] .. "'"
- end
-
- -- Get the world:
- local world
- if (a_Split[4] == nil) then
- world = cRoot:Get():GetDefaultWorld()
- else
- world = cRoot:Get():GetWorld(a_Split[4])
- if (world == nil) then
- return true, "There's no world named '" .. a_Split[4] .. "'."
- end
- end
-
- -- Queue the chunk for preparing, log a message when prepared:
- world:PrepareChunk(chunkX, chunkZ,
- function(a_CBChunkX, a_CBChunkZ)
- LOG("Chunk [" .. chunkX .. ", " .. chunkZ .. "] has been prepared")
- end
- )
- return true
-end
-
-
-
-
-
-function HandleConsoleSchedule(a_Split)
- local prev = os.clock()
- LOG("Scheduling a task for 5 seconds in the future (current os.clock is " .. prev .. ")")
- cRoot:Get():GetDefaultWorld():ScheduleTask(5 * 20,
- function ()
- local current = os.clock()
- local diff = current - prev
- LOG("Scheduled function is called. Current os.clock is " .. current .. ", difference is " .. diff .. ")")
- end
- )
- return true, "Task scheduled"
-end
-
-
-
-
-
---- Returns the square of the distance from the specified point to the specified line
-local function SqDistPtFromLine(x, y, x1, y1, x2, y2)
- local dx = x - x1
- local dy = y - y1
- local px = x2 - x1
- local py = y2 - y1
- local ss = px * dx + py * dy
- local ds = px * px + py * py
-
- if (ss < 0) then
- -- Return sqdistance from point 1
- return dx * dx + dy * dy
- end
- if (ss > ds) then
- -- Return sqdistance from point 2
- return ((x2 - x) * (x2 - x) + (y2 - y) * (y2 - y))
- end
-
- -- Return sqdistance from the line
- if ((px * px + py * py) == 0) then
- return dx * dx + dy * dy
- else
- return (py * dx - px * dy) * (py * dx - px * dy) / (px * px + py * py)
- end
-end
-
-
-
-
-
-function HandleConsoleTestBbox(a_Split, a_EntireCmd)
- -- Test bbox intersection:
- local bbox1 = cBoundingBox(0, 5, 0, 5, 0, 5)
- local bbox2 = cBoundingBox(bbox1) -- Make a copy
- bbox2:Move(20, 20, 20)
- local bbox3 = cBoundingBox(bbox1) -- Make a copy
- bbox3:Move(2, 2, 2)
- local doesIntersect, intersection = bbox1:Intersect(bbox2)
- LOG("Bbox 2 intersection: " .. tostring(doesIntersect))
- LOG(" Intersection type: " .. type(intersection) .. " / " .. tolua.type(intersection))
- if (intersection) then
- LOG(" {" .. intersection:GetMinX() .. ", " .. intersection:GetMinY() .. ", " .. intersection:GetMinZ() .. "}")
- LOG(" {" .. intersection:GetMaxX() .. ", " .. intersection:GetMaxY() .. ", " .. intersection:GetMaxZ() .. "}")
- end
- doesIntersect, intersection = bbox1:Intersect(bbox3)
- LOG("Bbox 3 intersection: " .. tostring(doesIntersect))
- LOG(" Intersection type: " .. type(intersection) .. " / " .. tolua.type(intersection))
- if (intersection) then
- LOG(" {" .. intersection:GetMinX() .. ", " .. intersection:GetMinY() .. ", " .. intersection:GetMinZ() .. "}")
- LOG(" {" .. intersection:GetMaxX() .. ", " .. intersection:GetMaxY() .. ", " .. intersection:GetMaxZ() .. "}")
- end
-
- -- Test line intersection:
- local lines =
- {
- { Vector3d(5, 0, 5), Vector3d(5, 1, 5) },
- { Vector3d(0, 0, 0), Vector3d(0, 1, 0) },
- }
- for idx, line in ipairs(lines) do
- local doesIntersect, coeff, face = bbox2:CalcLineIntersection(line[1], line[2])
- LOG("Line " .. idx .. " intersection: " .. tostring(doesIntersect))
- LOG(" Coeff: " .. tostring(coeff))
- LOG(" Face: " .. tostring(face))
- local doesIntersect2, coeff2, face2 = cBoundingBox:CalcLineIntersection(bbox2:GetMin(), bbox2:GetMax(), line[1], line[2])
- assert(doesIntersect == doesIntersect2)
- assert(coeff == coeff2)
- assert(face == face2)
- end
-
- return true
-end
-
-
-
-
-
-function HandleConsoleTestCall(a_Split, a_EntireCmd)
- LOG("Testing inter-plugin calls")
- LOG("Note: These will fail if the Core plugin is not enabled")
-
- -- Test calling the HandleConsoleWeather handler:
- local pm = cPluginManager
- LOG("Calling Core's HandleConsoleWeather")
- local isSuccess = pm:CallPlugin("Core", "HandleConsoleWeather",
- {
- "/weather",
- "rain",
- }
- )
- if (type(isSuccess) == "boolean") then
- LOG("Success")
- else
- LOG("FAILED")
- end
-
- -- Test injecting some code:
- LOG("Injecting code into the Core plugin")
- isSuccess = pm:CallPlugin("Core", "dofile", pm:GetCurrentPlugin():GetLocalFolder() .. "/Inject.lua")
- if (type(isSuccess) == "boolean") then
- LOG("Success")
- else
- LOG("FAILED")
- end
-
- -- Test the full capabilities of the table-passing API, using the injected function:
- LOG("Calling injected code")
- isSuccess = pm:CallPlugin("Core", "injectedPrintParams",
- {
- "test",
- nil,
- {
- "test",
- "test"
- },
- [10] = "test",
- ["test"] = "test",
- [{"test"}] = "test",
- [true] = "test",
- }
- )
- if (type(isSuccess) == "boolean") then
- LOG("Success")
- else
- LOG("FAILED")
- end
-
- return true
-end
-
-
-
-
-
-function HandleConsoleTestJson(a_Split, a_EntireCmd)
- LOG("Testing Json parsing...")
- local t1 = cJson:Parse([[{"a": 1, "b": "2", "c": [3, "4", 5], "d": true }]])
- assert(t1.a == 1)
- assert(t1.b == "2")
- assert(t1.c[1] == 3)
- assert(t1.c[2] == "4")
- assert(t1.c[3] == 5)
- assert(t1.d == true)
- LOG("Json parsing example 1 successful")
-
- local t2, msg = cJson:Parse([[{"some": invalid, json}]])
- assert(t2 == nil)
- assert(type(msg) == "string")
- LOG("Json parsing an invalid string: Error message returned: " .. msg)
-
- LOG("Json parsing test succeeded")
-
- LOG("Testing Json serializing...")
- local s1 = cJson:Serialize({a = 1, b = "2", c = {3, "4", 5}, d = true}, {indentation = " "})
- LOG("Serialization result: " .. (s1 or ""))
- LOG("Json serializing test succeeded")
-
- return true
-end
-
-
-
-
-
-function HandleConsoleTestTracer(a_Split, a_EntireCmd)
- -- Check required params:
- if not(a_Split[7]) then
- return true, "Usage: " .. a_Split[1] .. " []"
- end
- local Coords = {}
- for i = 1, 6 do
- local v = tonumber(a_Split[i + 1])
- if not(v) then
- return true, "Parameter " .. (i + 1) .. " (" .. tostring(a_Split[i + 1]) .. ") not a number "
- end
- Coords[i] = v
- end
-
- -- Get the world in which to test:
- local World
- if (a_Split[8]) then
- World = cRoot:GetWorld(a_Split[2])
- else
- World = cRoot:Get():GetDefaultWorld()
- end
- if not(World) then
- return true, "No such world"
- end
-
- -- Define the callbacks to use for tracing:
- local Callbacks =
- {
- OnNextBlock = function(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_EntryFace)
- LOG(string.format("{%d, %d, %d}: %s", a_BlockX, a_BlockY, a_BlockZ, ItemToString(cItem(a_BlockType, 1, a_BlockMeta))))
- end,
- OnNextBlockNoData = function(a_BlockX, a_BlockY, a_BlockZ, a_EntryFace)
- LOG(string.format("{%d, %d, %d} (no data)", a_BlockX, a_BlockY, a_BlockZ))
- end,
- OnNoChunk = function()
- LOG("Chunk not loaded")
- end,
- OnNoMoreHits = function()
- LOG("Trace finished")
- end,
- OnOutOfWorld = function()
- LOG("Out of world")
- end,
- OnIntoWorld = function()
- LOG("Into world")
- end,
- }
-
- -- Approximate the chunks needed for the trace by iterating over all chunks and measuring their center's distance from the traced line
- local Chunks = {}
- local sx = math.floor(Coords[1] / 16)
- local sz = math.floor(Coords[3] / 16)
- local ex = math.floor(Coords[4] / 16)
- local ez = math.floor(Coords[6] / 16)
- local sgnx = (sx < ex) and 1 or -1
- local sgnz = (sz < ez) and 1 or -1
- for z = sz, ez, sgnz do
- local ChunkCenterZ = z * 16 + 8
- for x = sx, ex, sgnx do
- local ChunkCenterX = x * 16 + 8
- local sqdist = SqDistPtFromLine(ChunkCenterX, ChunkCenterZ, Coords[1], Coords[3], Coords[4], Coords[6])
- if (sqdist <= 128) then
- table.insert(Chunks, {x, z})
- end
- end
- end
-
- -- Load the chunks and do the trace once loaded:
- World:ChunkStay(Chunks,
- nil,
- function()
- cLineBlockTracer:Trace(World, Callbacks, Coords[1], Coords[2], Coords[3], Coords[4], Coords[5], Coords[6])
- end
- )
- return true
-end
-
-
-
-
-
-function HandleConsoleTestUrlClient(a_Split, a_EntireCmd)
- local url = a_Split[2] or "https://github.com"
- local isSuccess, msg = cUrlClient:Get(url,
- function (a_Body, a_SecondParam)
- if not(a_Body) then
- -- An error has occurred, a_SecondParam is the error message
- LOG("Error while retrieving URL \"" .. url .. "\": " .. (a_SecondParam or ""))
- return
- end
- -- Body received, a_SecondParam is the HTTP headers dictionary-table
- assert(type(a_Body) == "string")
- assert(type(a_SecondParam) == "table")
- LOG("URL body received, length is " .. string.len(a_Body) .. " bytes and there are these headers:")
- for k, v in pairs(a_SecondParam) do
- LOG(" \"" .. k .. "\": \"" .. v .. "\"")
- end
- LOG("(headers list finished)")
- end
- )
- if not(isSuccess) then
- LOG("cUrlClient request failed: " .. (msg or ""))
- end
- return true
-end
-
-
-
-
-
-function HandleConsoleTestUrlParser(a_Split, a_EntireCmd)
- LOG("Testing cUrlParser...")
- local UrlsToTest =
- {
- "invalid URL",
- "https://github.com",
- "ftp://anonymous:user@example.com@ftp.cuberite.org:9921/releases/2015/2015-12-25.zip",
- "ftp://anonymous:user:name:with:colons@example.com@ftp.cuberite.org:9921",
- "http://google.com/",
- "http://google.com/?q=cuberite",
- "http://google.com/search?q=cuberite",
- "http://google.com/some/search?q=cuberite#results",
- "http://google.com/?q=cuberite#results",
- "http://google.com/#results",
- "ftp://cuberite.org:9921/releases/2015/2015-12-25.zip",
- "mailto:support@cuberite.org",
- }
- for _, u in ipairs(UrlsToTest) do
- LOG("URL: " .. u)
- local scheme, username, password, host, port, path, query, fragment = cUrlParser:Parse(u)
- if not(scheme) then
- LOG(" Error: " .. (username or ""))
- else
- LOG(" Scheme = " .. scheme)
- LOG(" Username = " .. username)
- LOG(" Password = " .. password)
- LOG(" Host = " .. host)
- LOG(" Port = " .. port)
- LOG(" Path = " .. path)
- LOG(" Query = " .. query)
- LOG(" Fragment = " .. fragment)
- end
- end
- LOG("cUrlParser test complete")
- return true
-end
-
-
-
-
-
-function HandleConsoleUuid(a_Split, a_EntireCmd)
- -- Check params:
- local playerName = a_Split[2]
- if not(playerName) then
- return true, "Usage: uuid "
- end
-
- -- Query with cache:
- LOG("Player " .. playerName .. ":")
- local cachedUuid = cMojangAPI:GetUUIDFromPlayerName(playerName, true)
- if not(cachedUuid) then
- LOG(" - not in the UUID cache")
- else
- LOG(" - in the cache: \"" .. cachedUuid .. "\"")
- end
-
- -- Query online:
- local onlineUuid = cMojangAPI:GetUUIDFromPlayerName(playerName, false)
- if not(onlineUuid) then
- LOG(" - UUID not available online")
- else
- LOG(" - online: \"" .. onlineUuid .. "\"")
- end
-
- return true
-end
-
-
-
-
-
-function HandleConsoleBBox(a_Split)
- local bbox = cBoundingBox(0, 10, 0, 10, 0, 10)
- local v1 = Vector3d(1, 1, 1)
- local v2 = Vector3d(5, 5, 5)
- local v3 = Vector3d(11, 11, 11)
-
- if (bbox:IsInside(v1)) then
- LOG("v1 is inside bbox")
- else
- LOG("v1 is not inside bbox")
- end
-
- if (bbox:IsInside(v2)) then
- LOG("v2 is inside bbox")
- else
- LOG("v2 is not inside bbox")
- end
-
- if (bbox:IsInside(v3)) then
- LOG("v3 is inside bbox")
- else
- LOG("v3 is not inside bbox")
- end
-
- if (bbox:IsInside(v1, v2)) then
- LOG("v1*v2 is inside bbox")
- else
- LOG("v1*v2 is not inside bbox")
- end
-
- if (bbox:IsInside(v2, v1)) then
- LOG("v2*v1 is inside bbox")
- else
- LOG("v2*v1 is not inside bbox")
- end
-
- if (bbox:IsInside(v1, v3)) then
- LOG("v1*v3 is inside bbox")
- else
- LOG("v1*v3 is not inside bbox")
- end
-
- if (bbox:IsInside(v2, v3)) then
- LOG("v2*v3 is inside bbox")
- else
- LOG("v2*v3 is not inside bbox")
- end
-
- return true
-end
-
-
-
-
-
-function HandleConsoleDownload(a_Split)
- -- Check params:
- local url = a_Split[2]
- local fnam = a_Split[3]
- if (not(url) or not(fnam)) then
- return true, "Missing parameters. Usage: download "
- end
-
- local callbacks =
- {
- OnStatusLine = function (self, a_HttpVersion, a_Status, a_Rest)
- if (a_Status ~= 200) then
- LOG("Cannot download " .. url .. ", HTTP error code " .. a_Status)
- return
- end
-
- local f, err = io.open(fnam, "wb")
- if not(f) then
- LOG("Cannot download " .. url .. ", error opening the file " .. fnam .. ": " .. (err or ""))
- return
- end
- self.m_File = f
- end,
-
- OnBodyData = function (self, a_Data)
- if (self.m_File) then
- self.m_File:write(a_Data)
- end
- end,
-
- OnBodyFinished = function (self)
- if (self.m_File) then
- self.m_File:close()
- LOG("File " .. fnam .. " has been downloaded.")
- end
- end,
- }
-
- local isSuccess, msg = cUrlClient:Get(url, callbacks)
- if not(isSuccess) then
- LOG("Cannot start an URL download: " .. (msg or ""))
- return true
- end
- return true
-end
-
-
-
-
-
-function HandleBlkCmd(a_Split, a_Player)
- -- Gets info about the block the player is looking at.
- local World = a_Player:GetWorld();
-
- local Callbacks = {
- OnNextBlock = function(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta)
- if (a_BlockType ~= E_BLOCK_AIR) then
- a_Player:SendMessage("Block at " .. a_BlockX .. ", " .. a_BlockY .. ", " .. a_BlockZ .. " is " .. a_BlockType .. ":" .. a_BlockMeta)
- return true;
- end
- end
- };
-
- local EyePos = a_Player:GetEyePosition();
- local LookVector = a_Player:GetLookVector();
- LookVector:Normalize();
-
- local End = EyePos + LookVector * 50;
-
- cLineBlockTracer.Trace(World, Callbacks, EyePos.x, EyePos.y, EyePos.z, End.x, End.y, End.z);
-
- return true;
-end
-
-
-
-
-
-function HandleTeamsCmd(a_Split, a_Player)
- local Scoreboard = a_Player:GetWorld():GetScoreBoard()
-
- a_Player:SendMessage("Teams: " .. table.concat(Scoreboard:GetTeamNames(), ", "))
-
- return true
-end
-
-
-
-
-
diff --git a/world/Plugins/Debuggers/Info.lua b/world/Plugins/Debuggers/Info.lua
deleted file mode 100644
index 6c7eabbf..00000000
--- a/world/Plugins/Debuggers/Info.lua
+++ /dev/null
@@ -1,309 +0,0 @@
-
--- Info.lua
-
--- Implements the g_PluginInfo standard plugin description
-
-
-
-
-
-g_PluginInfo =
-{
- Name = "Debuggers",
- Version = "14",
- Date = "2014-12-11",
- Description = [[Contains code for testing and debugging the server. Should not be enabled on a production server!]],
-
- Commands =
- {
- ["/arr"] =
- {
- Permission = "debuggers",
- Handler = HandleArrowCmd,
- HelpString = "Creates an arrow going away from the player"
- },
- ["/compo"] =
- {
- Permission = "debuggers",
- Handler = HandleCompo,
- HelpString = "Tests the cCompositeChat bindings"
- },
- ["/cstay"] =
- {
- Permission = "debuggers",
- Handler = HandleChunkStay,
- HelpString = "Tests the ChunkStay Lua integration for the specified chunk coords"
- },
- ["/dash"] =
- {
- Permission = "debuggers",
- Handler = HandleDashCmd,
- HelpString = "Switches between fast and normal sprinting speed"
- },
- ["/ench"] =
- {
- Permission = "debuggers",
- Handler = HandleEnchCmd,
- HelpString = "Provides an instant dummy enchantment window"
- },
- ["/fast"] =
- {
- Permission = "debuggers",
- Handler = HandleFastCmd,
- HelpString = "Switches between fast and normal movement speed"
- },
- ["/fb"] =
- {
- Permission = "debuggers",
- Handler = HandleFireballCmd,
- HelpString = "Creates a ghast fireball as if shot by the player"
- },
- ["/ff"] =
- {
- Permission = "debuggers",
- Handler = HandleFurnaceFuel,
- HelpString = "Shows how long the currently held item would burn in a furnace"
- },
- ["/fill"] =
- {
- Permission = "debuggers",
- Handler = HandleFill,
- HelpString = "Fills all block entities in current chunk with junk"
- },
- ["/fl"] =
- {
- Permission = "debuggers",
- Handler = HandleFoodLevelCmd,
- HelpString = "Sets the food level to the given value"
- },
- ["/fr"] =
- {
- Permission = "debuggers",
- Handler = HandleFurnaceRecipe,
- HelpString = "Shows the furnace recipe for the currently held item"
- },
- ["/fs"] =
- {
- Permission = "debuggers",
- Handler = HandleFoodStatsCmd,
- HelpString = "Turns regular foodstats message on or off"
- },
- ["/gc"] =
- {
- Permission = "debuggers",
- Handler = HandleGCCmd,
- HelpString = "Activates the Lua garbage collector"
- },
- ["/hunger"] =
- {
- Permission = "debuggers",
- Handler = HandleHungerCmd,
- HelpString = "Lists the current hunger-related variables"
- },
- ["/ke"] =
- {
- Permission = "debuggers",
- Handler = HandleKillEntitiesCmd,
- HelpString = "Kills all the loaded entities"
- },
- ["/le"] =
- {
- Permission = "debuggers",
- Handler = HandleListEntitiesCmd,
- HelpString = "Shows a list of all the loaded entities"
- },
- ["/nick"] =
- {
- Permission = "debuggers",
- Handler = HandleNickCmd,
- HelpString = "Gives you a custom name",
- },
- ["/pickups"] =
- {
- Permission = "debuggers",
- Handler = HandlePickups,
- HelpString = "Spawns random pickups around you"
- },
- ["/plugmsg"] =
- {
- Permission = "debuggers",
- Handler = HandlePlugMsg,
- HelpString = "Sends a test plugin message to the client",
- },
- ["/poison"] =
- {
- Permission = "debuggers",
- Handler = HandlePoisonCmd,
- HelpString = "Sets food-poisoning for 15 seconds"
- },
- ["/poof"] =
- {
- Permission = "debuggers",
- Handler = HandlePoof,
- HelpString = "Nudges pickups close to you away from you"
- },
- ["/rmitem"] =
- {
- Permission = "debuggers",
- Handler = HandleRMItem,
- HelpString = "Remove the specified item from the inventory."
- },
- ["/sb"] =
- {
- Permission = "debuggers",
- Handler = HandleSetBiome,
- HelpString = "Sets the biome around you to the specified one"
- },
- ["/sched"] =
- {
- Permission = "debuggers",
- Handler = HandleSched,
- HelpString = "Schedules a simple countdown using cWorld:ScheduleTask()"
- },
- ["/spidey"] =
- {
- Permission = "debuggers",
- Handler = HandleSpideyCmd,
- HelpString = "Shoots a line of web blocks until it hits non-air"
- },
- ["/starve"] =
- {
- Permission = "debuggers",
- Handler = HandleStarveCmd,
- HelpString = "Sets the food level to zero"
- },
- ["/testwnd"] =
- {
- Permission = "debuggers",
- Handler = HandleTestWndCmd,
- HelpString = "Opens up a window using plugin API"
- },
- ["/wesel"] =
- {
- Permission = "debuggers",
- Handler = HandleWESel,
- HelpString = "Expands the current WE selection by 1 block in X/Z"
- },
- ["/wool"] =
- {
- Permission = "debuggers",
- Handler = HandleWoolCmd,
- HelpString = "Sets all your armor to blue wool"
- },
- ["/xpa"] =
- {
- Permission = "debuggers",
- Handler = HandleAddExperience,
- HelpString = "Adds 200 experience to the player"
- },
- ["/xpr"] =
- {
- Permission = "debuggers",
- Handler = HandleRemoveXp,
- HelpString = "Remove all xp"
- },
- ["/blk"] =
- {
- Permission = "debuggers",
- Handler = HandleBlkCmd,
- HelpString = "Gets info about the block you are looking at"
- },
- ["/teams"] =
- {
- Permission = "debuggers",
- Handler = HandleTeamsCmd,
- HelpString = "List the teams"
- },
- }, -- Commands
-
- ConsoleCommands =
- {
- ["bbox"] =
- {
- Handler = HandleConsoleBBox,
- HelpString = "Performs cBoundingBox API tests",
- },
-
- ["download"] =
- {
- Handler = HandleConsoleDownload,
- HelpString = "Downloads a file from a specified URL",
- },
-
- ["hash"] =
- {
- Handler = HandleConsoleHash,
- HelpString = "Tests the crypto hashing functions",
- },
-
- ["inh"] =
- {
- Handler = HandleConsoleInh,
- HelpString = "Tests the bindings of the cEntity inheritance",
- },
-
- ["loadchunk"] =
- {
- Handler = HandleConsoleLoadChunk,
- HelpString = "Loads the specified chunk into memory",
- },
-
- ["preparechunk"] =
- {
- Handler = HandleConsolePrepareChunk,
- HelpString = "Prepares the specified chunk completely (load / gen / light)",
- },
-
- ["sched"] =
- {
- Handler = HandleConsoleSchedule,
- HelpString = "Tests the world scheduling",
- },
-
- ["testbbox"] =
- {
- Handler = HandleConsoleTestBbox,
- HelpString = "Tests cBoundingBox API"
- },
-
- ["testcall"] =
- {
- Handler = HandleConsoleTestCall,
- HelpString = "Tests inter-plugin calls with various values"
- },
-
- ["testjson"] =
- {
- Handler = HandleConsoleTestJson,
- HelpString = "Tests the cJson parser and serializer",
- },
-
- ["testtracer"] =
- {
- Handler = HandleConsoleTestTracer,
- HelpString = "Tests the cLineBlockTracer",
- },
-
- ["testurlclient"] =
- {
- Handler = HandleConsoleTestUrlClient,
- HelpString = "Tests the cUrlClient",
- },
-
- ["testurlparser"] =
- {
- Handler = HandleConsoleTestUrlParser,
- HelpString = "Tests the cUrlParser",
- },
-
- ["uuid"] =
- {
- Handler = HandleConsoleUuid,
- HelpString = "Queries the cMojangAPI for a player's UUID",
- }
- }, -- ConsoleCommands
-} -- g_PluginInfo
-
-
-
-
diff --git a/world/Plugins/Debuggers/Inject.lua b/world/Plugins/Debuggers/Inject.lua
deleted file mode 100644
index d707f95e..00000000
--- a/world/Plugins/Debuggers/Inject.lua
+++ /dev/null
@@ -1,57 +0,0 @@
--- Inject.lua
-
--- This file gets injected into the Core plugin when testing the inter-plugin calls with the "testcall" command
--- However, since this is a .lua file, it also gets loaded into the Debuggers plugin, so we need to distinguish the two
-
-
-
-
-
---- Prints the specified table to the log, using the specified indent
--- Assumes there are no cycles in the table and all keys and values can be turned to strings
-local function printTable(a_Table, a_Indent)
- for k, v in pairs(a_Table) do
- LOG(a_Indent .. "k = " .. tostring(k))
- if (type(k) == "table") then
- printTable(k, a_Indent .. " ")
- end
- LOG(a_Indent .. "v = " .. tostring(v))
- if (type(v) == "table") then
- printTable(v, a_Indent .. " ")
- end
- end
-end
-
-
-
-
-
-local function printParams(...)
- LOG("printParams:")
- for idx, param in ipairs({...}) do
- LOG(" param" .. idx .. ": " .. tostring(param))
- if (type(param) == "table") then
- printTable(param, " ")
- end
- end
- LOG("done")
- return true
-end
-
-
-
-
-
-local pluginName = cPluginManager:Get():GetCurrentPlugin():GetName()
-if (pluginName ~= "Debuggers") then
- -- We're in the destination plugin
- LOG("Loaded Inject.lua into " .. pluginName)
- injectedPrintParams = printParams
- return true
-else
- -- We're in the Debuggers plugin, do nothing
-end
-
-
-
-
diff --git a/world/Plugins/DiamondMover/DiamondMover.lua b/world/Plugins/DiamondMover/DiamondMover.lua
deleted file mode 100644
index d3e70acf..00000000
--- a/world/Plugins/DiamondMover/DiamondMover.lua
+++ /dev/null
@@ -1,85 +0,0 @@
-
--- DiamondMover.lua
-
--- An example Lua plugin using the cBlockArea object
--- When a player rclks with a diamond in their hand, an area around the clicked block is moved in the direction the player is facing
-
-
-
-
-
--- Global variables
-MOVER_SIZE_X = 4;
-MOVER_SIZE_Y = 4;
-MOVER_SIZE_Z = 4;
-
-
-
-
-
-function Initialize(Plugin)
- Plugin:SetName("DiamondMover");
- Plugin:SetVersion(1);
-
- cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_USED_ITEM, OnPlayerUsedItem);
-
- LOG("Initialized " .. Plugin:GetName() .. " v." .. Plugin:GetVersion());
- return true;
-end
-
-
-
-
-
-function OnPlayerUsedItem(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ)
-
- -- Don't check if the direction is in the air
- if (BlockFace == -1) then
- return false;
- end;
-
- if (not Player:HasPermission("diamondmover.move")) then
- return false;
- end;
-
- -- Rclk with a diamond to push in the direction the player is facing
- if (Player:GetEquippedItem().m_ItemType == E_ITEM_DIAMOND) then
- local Area = cBlockArea();
- Area:Read(Player:GetWorld(),
- BlockX - MOVER_SIZE_X, BlockX + MOVER_SIZE_X,
- BlockY - MOVER_SIZE_Y, BlockY + MOVER_SIZE_Y,
- BlockZ - MOVER_SIZE_Z, BlockZ + MOVER_SIZE_Z
- );
-
- local PlayerPitch = Player:GetPitch();
- if (PlayerPitch < -70) then -- looking up
- BlockY = BlockY + 1;
- else
- if (PlayerPitch > 70) then -- looking down
- BlockY = BlockY - 1;
- else
- local PlayerRot = Player:GetYaw() + 180; -- Convert [-180, 180] into [0, 360] for simpler conditions
- if ((PlayerRot < 45) or (PlayerRot > 315)) then
- BlockZ = BlockZ - 1;
- else
- if (PlayerRot < 135) then
- BlockX = BlockX + 1;
- else
- if (PlayerRot < 225) then
- BlockZ = BlockZ + 1;
- else
- BlockX = BlockX - 1;
- end;
- end;
- end;
- end;
- end;
-
- Area:Write(Player:GetWorld(), BlockX - MOVER_SIZE_X, BlockY - MOVER_SIZE_Y, BlockZ - MOVER_SIZE_Z);
- return false;
- end
-end
-
-
-
-
diff --git a/world/Plugins/Docker/container.lua b/world/Plugins/Docker/container.lua
deleted file mode 100644
index 1eebffd0..00000000
--- a/world/Plugins/Docker/container.lua
+++ /dev/null
@@ -1,217 +0,0 @@
--- Container object is the representation of a Docker
--- container in the Minecraft world
-
--- constant variables
-CONTAINER_CREATED = 0
-CONTAINER_RUNNING = 1
-CONTAINER_STOPPED = 2
-
--- NewContainer returns a Container object,
--- representation of a Docker container in
--- the Minecraft world
-function NewContainer()
- c = {
- displayed = false,
- x = 0,
- z = 0,
- name="",
- id="",
- imageRepo="",
- imageTag="",
- running=false,
- init=Container.init,
- setInfos=Container.setInfos,
- destroy=Container.destroy,
- display=Container.display,
- updateMemSign=Container.updateMemSign,
- updateCPUSign=Container.updateCPUSign,
- addGround=Container.addGround
- }
- return c
-end
-
-Container = {displayed = false, x = 0, z = 0, name="",id="",imageRepo="",imageTag="",running=false}
-
--- Container:init sets Container's position
-function Container:init(x,z)
- self.x = x
- self.z = z
- self.displayed = false
-end
-
--- Container:setInfos sets Container's id, name, imageRepo,
--- image tag and running state
-function Container:setInfos(id,name,imageRepo,imageTag,running)
- self.id = id
- self.name = name
- self.imageRepo = imageRepo
- self.imageTag = imageTag
- self.running = running
-end
-
--- Container:destroy removes all blocks of the
--- container, it won't be visible on the map anymore
-function Container:destroy(running)
- local X = self.x+2
- local Y = GROUND_LEVEL+2
- local Z = self.z+2
- LOG("Exploding at X:" .. X .. " Y:" .. Y .. " Z:" .. Z)
- local World = cRoot:Get():GetDefaultWorld()
- World:BroadcastSoundEffect("random.explode", X, Y, Z, 1, 1)
- World:BroadcastParticleEffect("hugeexplosion",X, Y, Z, 0, 0, 0, 1, 1)
-
- -- if a block is removed before it's button/lever/sign, that object will drop
- -- and the player can collect it. Remove these first
-
- -- lever
- digBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+1)
- -- signs
- digBlock(UpdateQueue,self.x+3,GROUND_LEVEL+2,self.z-1)
- digBlock(UpdateQueue,self.x,GROUND_LEVEL+2,self.z-1)
- digBlock(UpdateQueue,self.x+1,GROUND_LEVEL+2,self.z-1)
- -- torch
- digBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+1)
- --button
- digBlock(UpdateQueue,self.x+2,GROUND_LEVEL+3,self.z+2)
-
- -- rest of the blocks
- for py = GROUND_LEVEL+1, GROUND_LEVEL+4
- do
- for px=self.x-1, self.x+4
- do
- for pz=self.z-1, self.z+5
- do
- digBlock(UpdateQueue,px,py,pz)
- end
- end
- end
-end
-
--- Container:display displays all Container's blocks
--- Blocks will be blue if the container is running,
--- orange otherwise.
-function Container:display(running)
-
- local metaPrimaryColor = E_META_WOOL_LIGHTBLUE
- local metaSecondaryColor = E_META_WOOL_BLUE
-
- if running == false
- then
- metaPrimaryColor = E_META_WOOL_ORANGE
- metaSecondaryColor = E_META_WOOL_RED
- end
-
- self.displayed = true
-
- for px=self.x, self.x+3
- do
- for pz=self.z, self.z+4
- do
- setBlock(UpdateQueue,px,GROUND_LEVEL + 1,pz,E_BLOCK_WOOL,metaPrimaryColor)
- end
- end
-
- for py = GROUND_LEVEL+2, GROUND_LEVEL+3
- do
- setBlock(UpdateQueue,self.x+1,py,self.z,E_BLOCK_WOOL,metaPrimaryColor)
-
- -- leave empty space for the door
- -- setBlock(UpdateQueue,self.x+2,py,self.z,E_BLOCK_WOOL,metaPrimaryColor)
-
- setBlock(UpdateQueue,self.x,py,self.z,E_BLOCK_WOOL,metaPrimaryColor)
- setBlock(UpdateQueue,self.x+3,py,self.z,E_BLOCK_WOOL,metaPrimaryColor)
-
- setBlock(UpdateQueue,self.x,py,self.z+1,E_BLOCK_WOOL,metaSecondaryColor)
- setBlock(UpdateQueue,self.x+3,py,self.z+1,E_BLOCK_WOOL,metaSecondaryColor)
-
- setBlock(UpdateQueue,self.x,py,self.z+2,E_BLOCK_WOOL,metaPrimaryColor)
- setBlock(UpdateQueue,self.x+3,py,self.z+2,E_BLOCK_WOOL,metaPrimaryColor)
-
- setBlock(UpdateQueue,self.x,py,self.z+3,E_BLOCK_WOOL,metaSecondaryColor)
- setBlock(UpdateQueue,self.x+3,py,self.z+3,E_BLOCK_WOOL,metaSecondaryColor)
-
- setBlock(UpdateQueue,self.x,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor)
- setBlock(UpdateQueue,self.x+3,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor)
-
- setBlock(UpdateQueue,self.x+1,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor)
- setBlock(UpdateQueue,self.x+2,py,self.z+4,E_BLOCK_WOOL,metaPrimaryColor)
- end
-
- -- torch
- setBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+3,E_BLOCK_TORCH,E_META_TORCH_ZP)
-
- -- start / stop lever
- setBlock(UpdateQueue,self.x+1,GROUND_LEVEL + 3,self.z + 2,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_XP)
- updateSign(UpdateQueue,self.x+1,GROUND_LEVEL + 3,self.z + 2,"","START/STOP","---->","",2)
-
-
- if running
- then
- setBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+1,E_BLOCK_LEVER,1)
- else
- setBlock(UpdateQueue,self.x+1,GROUND_LEVEL+3,self.z+1,E_BLOCK_LEVER,9)
- end
-
-
- -- remove button
-
- setBlock(UpdateQueue,self.x+2,GROUND_LEVEL + 3,self.z + 2,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_XM)
- updateSign(UpdateQueue,self.x+2,GROUND_LEVEL + 3,self.z + 2,"","REMOVE","---->","",2)
-
- setBlock(UpdateQueue,self.x+2,GROUND_LEVEL+3,self.z+3,E_BLOCK_STONE_BUTTON,E_BLOCK_BUTTON_XM)
-
-
- -- door
- -- Cuberite bug with Minecraft 1.8 apparently, doors are not displayed correctly
- -- setBlock(UpdateQueue,self.x+2,GROUND_LEVEL+2,self.z,E_BLOCK_WOODEN_DOOR,E_META_CHEST_FACING_ZM)
-
-
- for px=self.x, self.x+3
- do
- for pz=self.z, self.z+4
- do
- setBlock(UpdateQueue,px,GROUND_LEVEL + 4,pz,E_BLOCK_WOOL,metaPrimaryColor)
- end
- end
-
- setBlock(UpdateQueue,self.x+3,GROUND_LEVEL + 2,self.z - 1,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_ZM)
- updateSign(UpdateQueue,self.x+3,GROUND_LEVEL + 2,self.z - 1,string.sub(self.id,1,8),self.name,self.imageRepo,self.imageTag,2)
-
- -- Mem sign
- setBlock(UpdateQueue,self.x,GROUND_LEVEL + 2,self.z - 1,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_ZM)
-
- -- CPU sign
- setBlock(UpdateQueue,self.x+1,GROUND_LEVEL + 2,self.z - 1,E_BLOCK_WALLSIGN,E_META_CHEST_FACING_ZM)
-end
-
-
--- Container:updateMemSign updates the mem usage
--- value displayed on Container's sign
-function Container:updateMemSign(s)
- updateSign(UpdateQueue,self.x,GROUND_LEVEL + 2,self.z - 1,"Mem usage","",s,"")
-end
-
--- Container:updateCPUSign updates the mem usage
--- value displayed on Container's sign
-function Container:updateCPUSign(s)
- updateSign(UpdateQueue,self.x+1,GROUND_LEVEL + 2,self.z - 1,"CPU usage","",s,"")
-end
-
--- Container:addGround creates ground blocks
--- necessary to display the container
-function Container:addGround()
- local y = GROUND_LEVEL
-
- if GROUND_MIN_X > self.x - 2
- then
- OLD_GROUND_MIN_X = GROUND_MIN_X
- GROUND_MIN_X = self.x - 2
- for x= GROUND_MIN_X, OLD_GROUND_MIN_X
- do
- for z=GROUND_MIN_Z,GROUND_MAX_Z
- do
- setBlock(UpdateQueue,x,y,z,E_BLOCK_WOOL,E_META_WOOL_WHITE)
- end
- end
- end
-end
diff --git a/world/Plugins/Docker/docker.lua b/world/Plugins/Docker/docker.lua
deleted file mode 100644
index 261a6da3..00000000
--- a/world/Plugins/Docker/docker.lua
+++ /dev/null
@@ -1,320 +0,0 @@
-----------------------------------------
--- GLOBALS
-----------------------------------------
-
--- queue containing the updates that need to be applied to the minecraft world
-UpdateQueue = nil
--- array of container objects
-Containers = {}
---
-SignsToUpdate = {}
--- as a lua array cannot contain nil values, we store references to this object
--- in the "Containers" array to indicate that there is no container at an index
-EmptyContainerSpace = {}
-
-----------------------------------------
--- FUNCTIONS
-----------------------------------------
-
--- Tick is triggered by cPluginManager.HOOK_TICK
-function Tick(TimeDelta)
- UpdateQueue:update(MAX_BLOCK_UPDATE_PER_TICK)
-end
-
--- Plugin initialization
-function Initialize(Plugin)
- Plugin:SetName("Docker")
- Plugin:SetVersion(1)
-
- UpdateQueue = NewUpdateQueue()
-
- -- Hooks
-
- cPluginManager:AddHook(cPluginManager.HOOK_WORLD_STARTED, WorldStarted);
- cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_JOINED, PlayerJoined);
- cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_USING_BLOCK, PlayerUsingBlock);
- cPluginManager:AddHook(cPluginManager.HOOK_CHUNK_GENERATING, OnChunkGenerating);
- cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_FOOD_LEVEL_CHANGE, OnPlayerFoodLevelChange);
- cPluginManager:AddHook(cPluginManager.HOOK_TAKE_DAMAGE, OnTakeDamage);
- cPluginManager:AddHook(cPluginManager.HOOK_WEATHER_CHANGING, OnWeatherChanging);
- cPluginManager:AddHook(cPluginManager.HOOK_SERVER_PING, OnServerPing);
- cPluginManager:AddHook(cPluginManager.HOOK_TICK, Tick);
-
- -- Command Bindings
-
- cPluginManager.BindCommand("/docker", "*", DockerCommand, " - docker CLI commands")
-
- -- make all players admin
- cRankManager:SetDefaultRank("Admin")
-
- cNetwork:Connect("127.0.0.1",25566,TCP_CLIENT)
-
- LOG("Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion())
-
- return true
-end
-
--- updateStats update CPU and memory usage displayed
--- on container sign (container identified by id)
-function updateStats(id, mem, cpu)
- for i=1, table.getn(Containers)
- do
- if Containers[i] ~= EmptyContainerSpace and Containers[i].id == id
- then
- Containers[i]:updateMemSign(mem)
- Containers[i]:updateCPUSign(cpu)
- break
- end
- end
-end
-
--- getStartStopLeverContainer returns the container
--- id that corresponds to lever at x,y coordinates
-function getStartStopLeverContainer(x, z)
- for i=1, table.getn(Containers)
- do
- if Containers[i] ~= EmptyContainerSpace and x == Containers[i].x + 1 and z == Containers[i].z + 1
- then
- return Containers[i].id
- end
- end
- return ""
-end
-
--- getRemoveButtonContainer returns the container
--- id and state for the button at x,y coordinates
-function getRemoveButtonContainer(x, z)
- for i=1, table.getn(Containers)
- do
- if Containers[i] ~= EmptyContainerSpace and x == Containers[i].x + 2 and z == Containers[i].z + 3
- then
- return Containers[i].id, Containers[i].running
- end
- end
- return "", true
-end
-
--- destroyContainer looks for the first container having the given id,
--- removes it from the Minecraft world and from the 'Containers' array
-function destroyContainer(id)
- LOG("destroyContainer: " .. id)
- -- loop over the containers and remove the first having the given id
- for i=1, table.getn(Containers)
- do
- if Containers[i] ~= EmptyContainerSpace and Containers[i].id == id
- then
- -- remove the container from the world
- Containers[i]:destroy()
- -- if the container being removed is the last element of the array
- -- we reduce the size of the "Container" array, but if it is not,
- -- we store a reference to the "EmptyContainerSpace" object at the
- -- same index to indicate this is a free space now.
- -- We use a reference to this object because it is not possible to
- -- have 'nil' values in the middle of a lua array.
- if i == table.getn(Containers)
- then
- table.remove(Containers, i)
- -- we have removed the last element of the array. If the array
- -- has tailing empty container spaces, we remove them as well.
- while Containers[table.getn(Containers)] == EmptyContainerSpace
- do
- table.remove(Containers, table.getn(Containers))
- end
- else
- Containers[i] = EmptyContainerSpace
- end
- -- we removed the container, we can exit the loop
- break
- end
- end
-end
-
--- updateContainer accepts 3 different states: running, stopped, created
--- sometimes "start" events arrive before "create" ones
--- in this case, we just ignore the update
-function updateContainer(id,name,imageRepo,imageTag,state)
- LOG("Update container with ID: " .. id .. " state: " .. state)
-
- -- first pass, to see if the container is
- -- already displayed (maybe with another state)
- for i=1, table.getn(Containers)
- do
- -- if container found with same ID, we update it
- if Containers[i] ~= EmptyContainerSpace and Containers[i].id == id
- then
- Containers[i]:setInfos(id,name,imageRepo,imageTag,state == CONTAINER_RUNNING)
- Containers[i]:display(state == CONTAINER_RUNNING)
- LOG("found. updated. now return")
- return
- end
- end
-
- -- if container isn't already displayed, we see if there's an empty space
- -- in the world to display the container
- local x = CONTAINER_START_X
- local index = -1
-
- for i=1, table.getn(Containers)
- do
- -- use first empty location
- if Containers[i] == EmptyContainerSpace
- then
- LOG("Found empty location: Containers[" .. tostring(i) .. "]")
- index = i
- break
- end
- x = x + CONTAINER_OFFSET_X
- end
-
- local container = NewContainer()
- container:init(x,CONTAINER_START_Z)
- container:setInfos(id,name,imageRepo,imageTag,state == CONTAINER_RUNNING)
- container:addGround()
- container:display(state == CONTAINER_RUNNING)
-
- if index == -1
- then
- table.insert(Containers, container)
- else
- Containers[index] = container
- end
-end
-
---
-function WorldStarted(World)
- local y = GROUND_LEVEL
- -- just enough to fit one container
- -- then it should be dynamic
- for x = GROUND_MIN_X, GROUND_MAX_X
- do
- for z = GROUND_MIN_Z, GROUND_MAX_Z
- do
- setBlock(UpdateQueue,x,y,z,E_BLOCK_WOOL,E_META_WOOL_WHITE)
- end
- end
-end
-
---
-function PlayerJoined(Player)
- -- enable flying
- Player:SetCanFly(true)
- LOG("player joined")
-end
-
---
-function PlayerUsingBlock(Player, BlockX, BlockY, BlockZ, BlockFace, CursorX, CursorY, CursorZ, BlockType, BlockMeta)
- LOG("Using block: " .. tostring(BlockX) .. "," .. tostring(BlockY) .. "," .. tostring(BlockZ) .. " - " .. tostring(BlockType) .. " - " .. tostring(BlockMeta))
-
- -- lever: 1->OFF 9->ON (in that orientation)
- -- lever
- if BlockType == 69
- then
- local containerID = getStartStopLeverContainer(BlockX,BlockZ)
- LOG("Using lever associated with container ID: " .. containerID)
-
- if containerID ~= ""
- then
- -- stop
- if BlockMeta == 1
- then
- Player:SendMessage("docker stop " .. string.sub(containerID,1,8))
- SendTCPMessage("docker",{"stop",containerID},0)
- -- start
- else
- Player:SendMessage("docker start " .. string.sub(containerID,1,8))
- SendTCPMessage("docker",{"start",containerID},0)
- end
- else
- LOG("WARNING: no docker container ID attached to this lever")
- end
- end
-
- -- stone button
- if BlockType == 77
- then
- local containerID, running = getRemoveButtonContainer(BlockX,BlockZ)
-
- if running
- then
- Player:SendMessage("A running container can't be removed.")
- else
- Player:SendMessage("docker rm " .. string.sub(containerID,1,8))
- SendTCPMessage("docker",{"rm",containerID},0)
- end
- end
-end
-
-
-function OnChunkGenerating(World, ChunkX, ChunkZ, ChunkDesc)
- -- override the built-in chunk generator
- -- to have it generate empty chunks only
- ChunkDesc:SetUseDefaultBiomes(false)
- ChunkDesc:SetUseDefaultComposition(false)
- ChunkDesc:SetUseDefaultFinish(false)
- ChunkDesc:SetUseDefaultHeight(false)
- return true
-end
-
-
-function DockerCommand(Split, Player)
- if table.getn(Split) > 0
- then
-
- LOG("Split[1]: " .. Split[1])
-
- if Split[1] == "/docker"
- then
- if table.getn(Split) > 1
- then
- if Split[2] == "pull" or Split[2] == "create" or Split[2] == "run" or Split[2] == "stop" or Split[2] == "rm" or Split[2] == "rmi" or Split[2] == "start" or Split[2] == "kill"
- then
- -- force detach when running a container
- if Split[2] == "run"
- then
- table.insert(Split,3,"-d")
- end
- table.remove(Split,1)
- SendTCPMessage("docker",Split,0)
- end
- end
- end
- end
-
- return true
-end
-
-
-function OnPlayerFoodLevelChange(Player, NewFoodLevel)
- -- Don't allow the player to get hungry
- return true, Player, NewFoodLevel
-end
-
-function OnTakeDamage(Receiver, TDI)
- -- Don't allow the player to take falling or explosion damage
- if Receiver:GetClass() == 'cPlayer'
- then
- if TDI.DamageType == dtFall or TDI.DamageType == dtExplosion then
- return true, Receiver, TDI
- end
- end
- return false, Receiver, TDI
-end
-
-function OnServerPing(ClientHandle, ServerDescription, OnlinePlayers, MaxPlayers, Favicon)
- -- Change Server Description
- local serverDescription = "A Docker client for Minecraft"
- -- Change favicon
- if cFile:IsFile("/srv/logo.png") then
- local FaviconData = cFile:ReadWholeFile("/srv/logo.png")
- if (FaviconData ~= "") and (FaviconData ~= nil) then
- Favicon = Base64Encode(FaviconData)
- end
- end
- return false, serverDescription, OnlinePlayers, MaxPlayers, Favicon
-end
-
--- Make it sunny all the time!
-function OnWeatherChanging(World, Weather)
- return true, wSunny
-end
-
diff --git a/world/Plugins/Docker/log.lua b/world/Plugins/Docker/log.lua
deleted file mode 100644
index 788d387d..00000000
--- a/world/Plugins/Docker/log.lua
+++ /dev/null
@@ -1,19 +0,0 @@
-
--- Print contents of `tbl`, with indentation.
--- `indent` sets the initial level of indentation.
-function logTable (tbl, indent)
- if not indent then indent = 0 end
- for k, v in pairs(tbl) do
- formatting = string.rep(" ", indent) .. k .. ": "
- if type(v) == "table" then
- print(formatting)
- logTable(v, indent+1)
- elseif type(v) == 'boolean' then
- print(formatting .. tostring(v))
- elseif type(v) == 'function' then
- print(formatting .. '') -- TODO: display the function's name
- else
- print(formatting .. v)
- end
- end
-end
\ No newline at end of file
diff --git a/world/Plugins/Docker/tcpclient.lua b/world/Plugins/Docker/tcpclient.lua
deleted file mode 100644
index 8be0bf62..00000000
--- a/world/Plugins/Docker/tcpclient.lua
+++ /dev/null
@@ -1,133 +0,0 @@
-json = require "json"
-
-TCP_CONN = nil
-TCP_DATA = ""
-
-TCP_CLIENT = {
-
- OnConnected = function (TCPConn)
- -- The specified link has succeeded in connecting to the remote server.
- -- Only called if the link is being connected as a client (using cNetwork:Connect() )
- -- Not used for incoming server links
- -- All returned values are ignored
- LOG("tcp client connected")
- TCP_CONN = TCPConn
-
- -- list containers
- LOG("listing containers...")
- SendTCPMessage("info",{"containers"},0)
- end,
-
- OnError = function (TCPConn, ErrorCode, ErrorMsg)
- -- The specified error has occured on the link
- -- No other callback will be called for this link from now on
- -- For a client link being connected, this reports a connection error (destination unreachable etc.)
- -- It is an Undefined Behavior to send data to a_TCPLink in or after this callback
- -- All returned values are ignored
- LOG("tcp client OnError: " .. ErrorCode .. ": " .. ErrorMsg)
-
- -- retry to establish connection
- LOG("retry cNetwork:Connect")
- cNetwork:Connect("127.0.0.1",25566,TCP_CLIENT)
- end,
-
- OnReceivedData = function (TCPConn, Data)
- -- Data has been received on the link
- -- Will get called whenever there's new data on the link
- -- a_Data contains the raw received data, as a string
- -- All returned values are ignored
- -- LOG("TCP_CLIENT OnReceivedData")
-
- TCP_DATA = TCP_DATA .. Data
- local shiftLen = 0
-
- for message in string.gmatch(TCP_DATA, '([^\n]+\n)') do
- shiftLen = shiftLen + string.len(message)
- -- remove \n at the end
- message = string.sub(message,1,string.len(message)-1)
- ParseTCPMessage(message)
- end
-
- TCP_DATA = string.sub(TCP_DATA,shiftLen+1)
-
- end,
-
- OnRemoteClosed = function (TCPConn)
- -- The remote peer has closed the link
- -- The link is already closed, any data sent to it now will be lost
- -- No other callback will be called for this link from now on
- -- All returned values are ignored
- LOG("tcp client OnRemoteClosed")
-
- -- retry to establish connection
- LOG("retry cNetwork:Connect")
- cNetwork:Connect("127.0.0.1",25566,TCP_CLIENT)
- end,
-}
-
--- SendTCPMessage sends a message over global
--- tcp connection TCP_CONN. args and id are optional
--- id stands for the request id.
-function SendTCPMessage(cmd, args, id)
- if TCP_CONN == nil
- then
- LOG("can't send TCP message, TCP_CLIENT not connected")
- return
- end
- local v = {cmd=cmd, args=args, id=id}
- local msg = json.stringify(v) .. "\n"
- TCP_CONN:Send(msg)
-end
-
--- ParseTCPMessage parses a message received from
--- global tcp connection TCP_CONN
-function ParseTCPMessage(message)
- local m = json.parse(message)
- if m.cmd == "event" and table.getn(m.args) > 0 and m.args[1] == "containers"
- then
- handleContainerEvent(m.data)
- end
-end
-
--- handleContainerEvent handles a container
--- event TCP message.
-function handleContainerEvent(event)
-
- event.imageTag = event.imageTag or ""
- event.imageRepo = event.imageRepo or ""
- event.name = event.name or ""
-
- if event.action == "containerInfos"
- then
- local state = CONTAINER_STOPPED
- if event.running then
- state = CONTAINER_RUNNING
- end
- updateContainer(event.id,event.name,event.imageRepo,event.imageTag,state)
- end
-
- if event.action == "startContainer"
- then
- updateContainer(event.id,event.name,event.imageRepo,event.imageTag,CONTAINER_RUNNING)
- end
-
- if event.action == "createContainer"
- then
- updateContainer(event.id,event.name,event.imageRepo,event.imageTag,CONTAINER_CREATED)
- end
-
- if event.action == "stopContainer"
- then
- updateContainer(event.id,event.name,event.imageRepo,event.imageTag,CONTAINER_STOPPED)
- end
-
- if event.action == "destroyContainer"
- then
- destroyContainer(event.id)
- end
-
- if event.action == "stats"
- then
- updateStats(event.id,event.ram,event.cpu)
- end
-end
diff --git a/world/Plugins/Docker/update.lua b/world/Plugins/Docker/update.lua
deleted file mode 100644
index dc6c71ab..00000000
--- a/world/Plugins/Docker/update.lua
+++ /dev/null
@@ -1,122 +0,0 @@
--- UPDATE OPERATIONS
--- The following functions can be used to update blocks in the map.
--- There are 3 update types:
--- UPDATE_SET: set a block
--- UPDATE_DIG: remove a block
--- UPDATE_SIGN: update a sign
--- Update operations are queued.
--- An new update queue can be created using NewUpdateQueue()
-
-UPDATE_SET = 0
-UPDATE_DIG = 1
-UPDATE_SIGN = 2
-
-function NewUpdateQueue()
- queue = {first=nil, last=nil, current=nil}
-
- -- queue.newUpdate creates an update operation and
- -- inserts it in the queue or returns an error
- -- in case of UPDATE_SIGN, line 1 to 4 should
- -- be present in meta parameter.
- -- the delay is optional and will make sure that
- -- the update is not triggered before given amount
- -- of ticks (0 by default)
- function queue:newUpdate(updateType, x, y, z, blockID, meta, delay)
- if updateType ~= UPDATE_SET and updateType ~= UPDATE_DIG and updateType ~= UPDATE_SIGN
- then
- return NewError(1,"NewUpdate: wrong update type")
- end
-
- if delay == nil
- then
- delay = 0
- end
-
- update = {op=updateType,next=nil,x=x,y=y,z=z,blockID=blockID,meta=meta, delay=delay}
-
- -- update.exec executes update operation
- -- and returns an error if it fails
- function update:exec()
- if self.op == UPDATE_SET
- then
- cRoot:Get():GetDefaultWorld():SetBlock(self.x,self.y,self.z,self.blockID,self.meta)
- elseif self.op == UPDATE_DIG
- then
- cRoot:Get():GetDefaultWorld():DigBlock(self.x,self.y,self.z)
- elseif self.op == UPDATE_SIGN
- then
- cRoot:Get():GetDefaultWorld():SetSignLines(self.x,self.y,self.z,self.meta.line1,self.meta.line2,self.meta.line3,self.meta.line4)
- else
- return NewError(1,"update:exec: unknown update type: " .. tostring(self.op))
- end
- end
-
- if self.first == nil
- then
- self.first = update
- self.last = update
- else
- self.last.next = update
- self.last = update
- end
- end -- ends queue.newUpdate
-
- -- update triggers updates starting from
- -- the first one. It stops when the limit
- -- is reached, of if there are no more
- -- operations in the queue. It returns
- -- the amount of updates executed.
- -- When an update has a delay > 0, the delay
- -- is decremented, and the number of updates
- -- executed is not incremented.
- function queue:update(limit)
- n = 0
- self.current = self.first
-
- while n < limit and self.current ~= nil
- do
- if self.current.delay == 0
- then
- err = self.current:exec()
- if err ~= nil
- then
- LOG("queue:update error: " .. err.message)
- break
- end
-
- if self.current == self.first
- then
- self.first = self.current.next
- end
- n = n + 1
- else
- self.current.delay = self.current.delay - 1
- end
- self.current = self.current.next
- end
-
- return n
- end
-
- return queue
-end
-
--- setBlock adds an update in given queue to
--- set a block at x,y,z coordinates
-function setBlock(queue,x,y,z,blockID,meta)
- queue:newUpdate(UPDATE_SET, x, y, z, blockID, meta)
-end
-
--- setBlock adds an update in given queue to
--- remove a block at x,y,z coordinates
-function digBlock(queue,x,y,z)
- queue:newUpdate(UPDATE_DIG, x, y, z)
-end
-
--- setBlock adds an update in given queue to
--- update a sign at x,y,z coordinates with
--- 4 lines of text
-function updateSign(queue,x,y,z,line1,line2,line3,line4,delay)
- meta = {line1=line1,line2=line2,line3=line3,line4=line4}
- queue:newUpdate(UPDATE_SIGN, x, y, z, nil, meta, delay)
-end
\ No newline at end of file
diff --git a/world/Plugins/DumpInfo/Init.lua b/world/Plugins/DumpInfo/Init.lua
deleted file mode 100644
index 8b328c86..00000000
--- a/world/Plugins/DumpInfo/Init.lua
+++ /dev/null
@@ -1,52 +0,0 @@
-function Initialize(a_Plugin)
- a_Plugin:SetName("DumpInfo")
- a_Plugin:SetVersion(1)
-
- -- Check if the infodump file exists.
- if (not cFile:IsFile("Plugins/InfoDump.lua")) then
- LOGWARN("[DumpInfo] InfoDump.lua was not found.")
- return false
- end
-
- -- Add the webtab.
- a_Plugin:AddWebTab("DumpPlugin", HandleDumpPluginRequest)
- return true
-end
-
-
-
-
-
-function HandleDumpPluginRequest(a_Request)
- local Content = ""
-
- -- Check if it already was requested to dump a plugin.
- if (a_Request.PostParams["DumpInfo"] ~= nil) then
- local F = loadfile("Plugins/InfoDump.lua")
- F("Plugins/" .. a_Request.PostParams["DumpInfo"])
- end
-
- Content = Content .. [[
-
-
-
DumpInfo
-
]]
-
- -- Loop through each plugin that is found.
- cPluginManager:Get():ForEachPlugin(
- function(a_Plugin)
- -- Check if there is a file called 'Info.lua'
- if (cFile:IsFile("Plugins/" .. a_Plugin:GetName() .. "/Info.lua")) then
- Content = Content .. "\n
";
-
- return Content, SubTitle
-end
-
-
-
-
-
-function ShowPage(WebAdmin, TemplateRequest)
- SiteContent = {}
- local BaseURL = cWebAdmin:GetBaseURL(TemplateRequest.Request.Path)
- local Title = "Cuberite WebAdmin"
- local NumPlayers = cRoot:Get():GetServer():GetNumPlayers()
- local MemoryUsageKiB = cRoot:GetPhysicalRAMUsage()
- local NumChunks = cRoot:Get():GetTotalChunkCount()
- local PluginPage = cWebAdmin:GetPage(TemplateRequest.Request)
- local PageContent = PluginPage.Content
- local SubTitle = PluginPage.PluginFolder
- if (PluginPage.UrlPath ~= "") then
- SubTitle = PluginPage.PluginFolder .. " - " .. PluginPage.TabTitle
- end
- if (PageContent == "") then
- PageContent, SubTitle = GetDefaultPage()
- end
-
- --[[
- -- 2016-01-15 Mattes: This wasn't used anywhere in the code, no idea what it was supposed to do
- local reqParamsClass = ""
- for key, value in pairs(TemplateRequest.Request.Params) do
- reqParamsClass = reqParamsClass .. " param-" .. string.lower(string.gsub(key, "[^a-zA-Z0-9]+", "-") .. "-" .. string.gsub(value, "[^a-zA-Z0-9]+", "-"))
- end
- if (string.gsub(reqParamsClass, "%s", "") == "") then
- reqParamsClass = " no-param"
- end
- --]]
-
- Output([[
-
-
-
- ]] .. Title .. [[
-
-
-
-
-
-
- ]])
-
- -- Get all tabs:
- local perPluginTabs = {}
- for _, tab in ipairs(cWebAdmin:GetAllWebTabs()) do
- local pluginTabs = perPluginTabs[tab.PluginName] or {};
- perPluginTabs[tab.PluginName] = pluginTabs
- table.insert(pluginTabs, tab)
- end
-
- -- Sort by plugin:
- local pluginNames = {}
- for pluginName, pluginTabs in pairs(perPluginTabs) do
- table.insert(pluginNames, pluginName)
- end
- table.sort(pluginNames)
-
- -- Output by plugin, then alphabetically:
- for _, pluginName in ipairs(pluginNames) do
- local pluginTabs = perPluginTabs[pluginName]
- table.sort(pluginTabs,
- function(a_Tab1, a_Tab2)
- return ((a_Tab1.Title or "") < (a_Tab2.Title or ""))
- end
- )
-
- -- Translate the plugin name into the folder name (-> title)
- local pluginWebTitle = cPluginManager:Get():GetPluginFolderName(pluginName) or pluginName
- Output("