diff options
author | Tycho Bickerstaff <work.tycho@gmail.com> | 2013-12-22 14:19:27 +0100 |
---|---|---|
committer | Tycho Bickerstaff <work.tycho@gmail.com> | 2013-12-22 14:19:27 +0100 |
commit | 94ca07cfbfe0016d70963c055c87fe14f8622a4d (patch) | |
tree | 28dc91dc948287f802d9628a2ea715e1d4e0be49 /MCServer/Plugins/APIDump | |
parent | Chunk is now warnings clean (diff) | |
parent | Update GETTING-STARTED.md (diff) | |
download | cuberite-94ca07cfbfe0016d70963c055c87fe14f8622a4d.tar cuberite-94ca07cfbfe0016d70963c055c87fe14f8622a4d.tar.gz cuberite-94ca07cfbfe0016d70963c055c87fe14f8622a4d.tar.bz2 cuberite-94ca07cfbfe0016d70963c055c87fe14f8622a4d.tar.lz cuberite-94ca07cfbfe0016d70963c055c87fe14f8622a4d.tar.xz cuberite-94ca07cfbfe0016d70963c055c87fe14f8622a4d.tar.zst cuberite-94ca07cfbfe0016d70963c055c87fe14f8622a4d.zip |
Diffstat (limited to 'MCServer/Plugins/APIDump')
-rw-r--r-- | MCServer/Plugins/APIDump/APIDesc.lua | 12 | ||||
-rw-r--r-- | MCServer/Plugins/APIDump/Hooks/OnPluginsLoaded.lua | 79 | ||||
-rw-r--r-- | MCServer/Plugins/APIDump/SettingUpDecoda.html | 49 | ||||
-rw-r--r-- | MCServer/Plugins/APIDump/Static/decoda_debug_settings.png | bin | 0 -> 6178 bytes | |||
-rw-r--r-- | MCServer/Plugins/APIDump/Static/decoda_logo.png | bin | 0 -> 2413 bytes | |||
-rw-r--r-- | MCServer/Plugins/APIDump/Static/decoda_workspace.png | bin | 0 -> 70644 bytes | |||
-rw-r--r-- | MCServer/Plugins/APIDump/WebWorldThreads.html | 101 | ||||
-rw-r--r-- | MCServer/Plugins/APIDump/Writing-a-MCServer-plugin.html | 263 | ||||
-rw-r--r-- | MCServer/Plugins/APIDump/main.css | 11 | ||||
-rw-r--r-- | MCServer/Plugins/APIDump/main_APIDump.lua | 228 |
10 files changed, 613 insertions, 130 deletions
diff --git a/MCServer/Plugins/APIDump/APIDesc.lua b/MCServer/Plugins/APIDump/APIDesc.lua index 5bc4a5f39..d388d15dd 100644 --- a/MCServer/Plugins/APIDump/APIDesc.lua +++ b/MCServer/Plugins/APIDump/APIDesc.lua @@ -1,4 +1,3 @@ - -- APIDesc.lua -- Contains the API objects' descriptions @@ -308,18 +307,15 @@ g_APIDesc = A wrapper class for constants representing colors or effects. ]], - Functions = - { - MakeColor = { Params = "ColorCodeConstant", Return = "string", Notes = "Creates the complete color-code-sequence from the color or effect constant" }, - }, + Functions = {}, Constants = { Black = { Notes = "" }, Blue = { Notes = "" }, Bold = { Notes = "" }, - Color = { Notes = "The first character of the color-code-sequence, §" }, + Color = { Notes = "The first character of the color-code-sequence, �" }, DarkPurple = { Notes = "" }, - Delimiter = { Notes = "The first character of the color-code-sequence, §" }, + Delimiter = { Notes = "The first character of the color-code-sequence, �" }, Gold = { Notes = "" }, Gray = { Notes = "" }, Green = { Notes = "" }, @@ -2764,6 +2760,8 @@ end ExtraPages = { -- No sorting is provided for these, they will be output in the same order as defined here + { FileName = "Writing-a-MCServer-plugin.html", Title = "Writing a MCServer plugin" }, + { FileName = "SettingUpDecoda.html", Title = "Setting up the Decoda Lua IDE" }, { FileName = "WebWorldThreads.html", Title = "Webserver vs World threads" }, } } ; diff --git a/MCServer/Plugins/APIDump/Hooks/OnPluginsLoaded.lua b/MCServer/Plugins/APIDump/Hooks/OnPluginsLoaded.lua new file mode 100644 index 000000000..0d5b7271e --- /dev/null +++ b/MCServer/Plugins/APIDump/Hooks/OnPluginsLoaded.lua @@ -0,0 +1,79 @@ +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/MCServer/Plugins/APIDump/SettingUpDecoda.html b/MCServer/Plugins/APIDump/SettingUpDecoda.html new file mode 100644 index 000000000..4ad827efe --- /dev/null +++ b/MCServer/Plugins/APIDump/SettingUpDecoda.html @@ -0,0 +1,49 @@ +<!DOCTYPE html> + +<html> + <head> + <title>MCServer - Setting up Decoda</title> + <link rel="stylesheet" type="text/css" href="main.css" /> + <link rel="stylesheet" type="text/css" href="prettify.css" /> + <script src="prettify.js"></script> + <script src="lang-lua.js"></script> + <meta charset="UTF-8"> + </head> + <body> + <div id="content"> + <h1>Setting up the Decoda IDE</h1> + <p> + This article will explain how to set up Decoda, an IDE for writing Lua code, so that you can develop MCServer plugins with the comfort of an IDE.</p> + + <h2><img src="Static/decoda_logo.png" /> About Decoda</h2> + + <p>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.</p> + <p>Here's a screenshot of a default Decoda window with the debugger stepping through the code (scaled down):<br /> + <img src="Static/decoda_workspace.png" /></p> + <p>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.</p> + <p>Decoda is open-source, the sources are on GitHub: <a href="https://github.com/unknownworlds/decoda">https://github.com/unknownworlds/decoda</a>. You can download a compiled binary from the creators' site, <a href="http://unknownworlds.com/decoda/">http://unknownworlds.com/decoda/</a>. + + <h2><img src="Static/decoda_logo.png" /> Project management</h2> + <p>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.</p> + <p>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:<br /> + <img src="Static/decoda_debug_settings.png" /></p> + <p>In the debugging section, fill in the full path to MCServer.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.</p> + + <h2><img src="Static/decoda_logo.png" /> Debugging</h2> + <p>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 MCServer under the debugger. The MCServer 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.</p> + <p>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 MCServer loads, so you can actually debug any of those faded files, too.</p> + <p>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), MCServer won't be fully running. You can fix the error and issue a "reload" command in MCServer console to reload the plugin code anew (MCServer doesn't detect changes in plugin code automatically).</p> + <p>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.</p> + + <h2><img src="Static/decoda_logo.png" /> Limitations</h2> + <p>So far everything seems wonderful. Unfortunately, it doesn't always go as easy. There are several limits to what Decoda can do:</p> + <ul> + <li>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.</li> + <li>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 MCServer; you need to stop the server and start again to reenable breakpoints.</li> + <li>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.</li> + <li>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.</li> + <li>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 <a href="http://jsimlo.sk/notepad/">TED Notepad</a>.</li> + </ul> + </div> + </body> +</html> diff --git a/MCServer/Plugins/APIDump/Static/decoda_debug_settings.png b/MCServer/Plugins/APIDump/Static/decoda_debug_settings.png Binary files differnew file mode 100644 index 000000000..462d517b4 --- /dev/null +++ b/MCServer/Plugins/APIDump/Static/decoda_debug_settings.png diff --git a/MCServer/Plugins/APIDump/Static/decoda_logo.png b/MCServer/Plugins/APIDump/Static/decoda_logo.png Binary files differnew file mode 100644 index 000000000..fb446b62c --- /dev/null +++ b/MCServer/Plugins/APIDump/Static/decoda_logo.png diff --git a/MCServer/Plugins/APIDump/Static/decoda_workspace.png b/MCServer/Plugins/APIDump/Static/decoda_workspace.png Binary files differnew file mode 100644 index 000000000..7e626dae9 --- /dev/null +++ b/MCServer/Plugins/APIDump/Static/decoda_workspace.png diff --git a/MCServer/Plugins/APIDump/WebWorldThreads.html b/MCServer/Plugins/APIDump/WebWorldThreads.html index 2f117ab7c..fc80a6178 100644 --- a/MCServer/Plugins/APIDump/WebWorldThreads.html +++ b/MCServer/Plugins/APIDump/WebWorldThreads.html @@ -6,64 +6,67 @@ <link rel="stylesheet" type="text/css" href="prettify.css" /> <script src="prettify.js"></script> <script src="lang-lua.js"></script> + <meta charset="UTF-8"> </head> <body> - <h1>Webserver vs World threads</h1> - <p> - This article will explain the threading issues that arise between the webserver and world threads are of concern to plugin authors.</p> - <p> - Generally, plugins that provide webadmin pages should be quite careful about their interactions. Most operations on MCServer objects requires synchronization, that MCServer 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.</p> - <p> - This locking can be a source of deadlocks for plugins that are not written carefully.</p> + <div id="content"> + <h1>Webserver vs World threads</h1> + <p> + This article will explain the threading issues that arise between the webserver and world threads are of concern to plugin authors.</p> + <p> + Generally, plugins that provide webadmin pages should be quite careful about their interactions. Most operations on MCServer objects requires synchronization, that MCServer 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.</p> + <p> + This locking can be a source of deadlocks for plugins that are not written carefully.</p> - <h2>Example scenario</h2> - <p>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.</p> - <p> - 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.</p> - <p> - 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.</p> + <h2>Example scenario</h2> + <p>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.</p> + <p> + 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.</p> + <p> + 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.</p> - <h2>How to avoid the deadlock</h2> - <p> - 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 <a href="cWorld.html">cWorld</a>: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.</p> - <p> - 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.</p> + <h2>How to avoid the deadlock</h2> + <p> + 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 <a href="cWorld.html">cWorld</a>: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.</p> + <p> + 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.</p> - <h2>What to avoid</h2> - <p> - Now that we know what the danger is and how to avoid it, how do we know if our code is susceptible?</p> - <p> - 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 <a href="cRoot.html">cRoot</a>: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.</p> + <h2>What to avoid</h2> + <p> + Now that we know what the danger is and how to avoid it, how do we know if our code is susceptible?</p> + <p> + 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 <a href="cRoot.html">cRoot</a>: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.</p> - <h2>Example</h2> - The Core has the facility to kick players using the web interface. It used the following code for the kicking (inside the webadmin handler): - <pre class="prettyprint lang-lua"> - 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) - </pre> - 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: - <pre class="prettyprint lang-lua"> - 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 + <h2>Example</h2> + The Core has the facility to kick players using the web interface. It used the following code for the kicking (inside the webadmin handler): + <pre class="prettyprint lang-lua"> + 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) + </pre> + 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: + <pre class="prettyprint lang-lua"> + 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 ) - end - ) - </pre> - <script> - prettyPrint(); - </script> + </pre> + <script> + prettyPrint(); + </script> + </div> </body> </html>
\ No newline at end of file diff --git a/MCServer/Plugins/APIDump/Writing-a-MCServer-plugin.html b/MCServer/Plugins/APIDump/Writing-a-MCServer-plugin.html new file mode 100644 index 000000000..50e39d533 --- /dev/null +++ b/MCServer/Plugins/APIDump/Writing-a-MCServer-plugin.html @@ -0,0 +1,263 @@ +<!DOCTYPE html> + +<html> + <head> + <title>MCS Plugin Tutorial</title> + <link rel="stylesheet" type="text/css" href="main.css" /> + <link rel="stylesheet" type="text/css" href="prettify.css" /> + <script src="prettify.js"></script> + <script src="lang-lua.js"></script> + <meta charset="UTF-8"> + </head> + <body> + <div id="content"> + <h1>Writing a MCServer plugin</h1> + <p> + 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. + </p> + <p> + Let us begin. In order to begin development, we must firstly obtain a compiled copy + of MCServer, and make sure that the Core plugin is within the Plugins folder, and activated. + Core handles much of the MCServer end-user experience and is a necessary component of + plugin development, as necessary plugin components depend on sone of its functions. + </p> + <p> + Next, we must obtain a copy of CoreMessaging.lua. This can be found + <a href="https://raw.github.com/mc-server/MCServer/master/MCServer/Plugins/MagicCarpet/coremessaging.lua">here.</a> + This is used to provide messaging support that is compliant with MCServer standards. + </p> + <h2>Creating the basic template</h2> + <p> + Plugins are written in Lua. Therefore, create a new Lua file. You can create as many files as you wish, with + any filename - MCServer bungs them all together at runtime, however, let us create a file called main.lua for now. + Format it like so: + </p> + <pre class="prettyprint lang-lua"> +local PLUGIN + +function Initialize(Plugin) + Plugin:SetName("DerpyPlugin") + Plugin:SetVersion(1) + + PLUGIN = Plugin + + -- Hooks + + local PluginManager = cPluginManager:Get() + -- Command bindings + + LOG("Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion()) + return true +end + +function OnDisable() + LOG(PLUGIN:GetName() .. " is shutting down...") +end + </pre> + <p> + Now for an explanation of the basics. + <ul> + <li><b>function Initialize</b> is called on plugin startup. It is the place where the plugin is set up.</li> + <li><b>Plugin:SetName</b> sets the name of the plugin.</li> + <li><b>Plugin:SetVersion</b> sets the revision number of the plugin. This must be an integer.</li> + <li><b>LOG</b> logs to console a message, in this case, it prints that the plugin was initialised.</li> + <li>The <b>PLUGIN</b> variable just stores this plugin's object, so GetName() can be called in OnDisable (as no Plugin parameter is passed there, contrary to Initialize).</li> + <li><b>function OnDisable</b> is called when the plugin is disabled, commonly when the server is shutting down. Perform cleanup and logging here.</li> + </ul> + Be sure to return true for this function, else MCS thinks you plugin had failed to initialise and prints a stacktrace with an error message. + </p> + + <h2>Registering hooks</h2> + <p> + Hooks are things that MCServer 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 <a href="index.html">the API documentation</a>. + </p> + <p> + 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. + </p> + <p> + To register a hook, insert the following code template into the "-- Hooks" area in the previous code example. + </p> + <pre class="prettyprint lang-lua"> +cPluginManager.AddHook(cPluginManager.HOOK_NAME_HERE, FunctionNameToBeCalled) + </pre> + <p> + What does this code do? + <ul> + <li><b>cPluginManager.AddHook</b> registers the hook. The hook name is the second parameter. See the previous API documentation link for a list of all hooks.</li> + </ul> + What about the third parameter, you ask? Well, it is the name of the function that MCServer calls when the hook fires. It is in this + function that you should handle or cancel the hook. + </p> + <p> + So in total, this is a working representation of what we have so far covered. + </p> + <pre class="prettyprint lang-lua"> +function Initialize(Plugin) + Plugin:SetName("DerpyPlugin") + Plugin:SetVersion(1) + + cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_MOVING, OnPlayerMoving) + + local PluginManager = cPluginManager:Get() + -- Command bindings + + 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 + </pre> + <p> + 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. + </p> + <h2>Binding a command</h2> + <h3>Format</h3> + <p> + So now we know how to hook into MCServer, 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: + </p> + <pre class="prettyprint lang-lua"> +-- ADD THIS IF COMMAND DOES NOT REQUIRE A PARAMETER (/explode) +PluginManager:BindCommand("/commandname", "permissionnode", FunctionToCall, " - Description of command") + +-- ADD THIS IF COMMAND DOES REQUIRE A PARAMETER (/explode Notch) +PluginManager:BindCommand("/commandname", "permissionnode", FunctionToCall, " ~ Description of command and parameter(s)") + </pre> + <p> + What does it do, and why are there two? + <ul> + <li><b>PluginManager:BindCommand</b> 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.</li> + </ul> + The command name is pretty self explanatory. The permission node is basically just a <b>string</b> 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. + </p> + <p> + 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. + </p> + <h3>Parameters</h3> + <p> + What parameters are in the function MCServer calls when the command is executed? A 'Split' array and a 'Player' object. + </p> + <h4>The Split Array</h4> + <p> + The Split array is an array of all text submitted to the server, including the actual command. MCServer 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:<br /><br /> +    /derp (Split[1])<br /> +    zubby (Split[2])<br /> +    explode (Split[3])<br /> + <br /> +    The total amount of parameters passed were: 3 (#Split) + </p> + <h4>The Player Object and sending them messages</h4> + <p> + 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 <i>do</i> we send a message to the client? + </p> + <p> + Remember that copy of CoreMessaging.lua that we downloaded earlier? Make sure that file is in your plugin folder, along with the main.lua file you are typing + your code in. Since MCS brings all the files together on JIT compile, we don't need to worry about requiring any files or such. Simply follow the below examples: + </p> + <pre class="prettyprint lang-lua"> +-- Format: §yellow[INFO] §white%text% (yellow [INFO], white text following it) +-- Use: Informational message, such as instructions for usage of a command +SendMessage(Player, "Usage: /explode [player]") + +-- Format: §green[INFO] §white%text% (green [INFO] etc.) +-- Use: Success message, like when a command executes successfully +SendMessageSuccess(Player, "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 +SendMessageFailure(Player, "Player Salted was not found") + </pre> + <p> + 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"). + </p> + <h2>Final example and conclusion</h2> + <p> + 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. + </p> + <pre class="prettyprint lang-lua"> +function Initialize(Plugin) + Plugin:SetName("DerpyPluginThatBlowsPeopleUp") + Plugin:SetVersion(9001) + + local PluginManager = cPluginManager:Get() + PluginManager: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 + SendMessage(Player, "Usage: /explode [playername]") + return true + end + + -- Create a callback ExplodePlayer with parameter Explodee, which MCS calls for every player on the server + local HasExploded = false + local ExplodePlayer = function(Explodee) + -- If the player we are currently at is the one we specified as the parameter + if (Explodee:GetName() == Split[2]) then + -- Create an explosion at the same position as they are; see <a href="cWorld.html">API docs</a> for further details of this function + Player:GetWorld():DoExplosionAt(Explodee:GetPosX(), Explodee:GetPosY(), Explodee:GetPosZ(), false, esPlugin) + SendMessageSuccess(Player, Split[2] .. " was successfully exploded") + HasExploded = true; + return true -- Signalize to MCS that we do not need to call this callback for any more players + end + end + + -- Tell MCS 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 + SendMessageFailure(Player, 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 + </pre> + <p> + Make sure to read the comments for a description of what everything does. Also be sure to return true for all <b>command</b> handlers, unless you want MCS 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, <a href="index.html">the API documentation</a> is your friend! + </p> + <p> + Happy coding ;) + </p> + + <script> + prettyPrint(); + </script> + </div> + </body> +</html> diff --git a/MCServer/Plugins/APIDump/main.css b/MCServer/Plugins/APIDump/main.css index 5cc603a3f..aa26bd186 100644 --- a/MCServer/Plugins/APIDump/main.css +++ b/MCServer/Plugins/APIDump/main.css @@ -30,6 +30,11 @@ 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 @@ -49,6 +54,12 @@ header font-family: Segoe UI Light, Helvetica; } +footer +{ + text-align: center; + font-family: Segoe UI Light, Helvetica; +} + #content { padding: 0px 25px 25px 25px; diff --git a/MCServer/Plugins/APIDump/main_APIDump.lua b/MCServer/Plugins/APIDump/main_APIDump.lua index e5c8b9c30..b3a95eb22 100644 --- a/MCServer/Plugins/APIDump/main_APIDump.lua +++ b/MCServer/Plugins/APIDump/main_APIDump.lua @@ -229,14 +229,100 @@ end +local function WriteArticles(f) + f:write([[ + <a name="articles"><h2>Articles</h2></a> + <p>The following articles provide various extra information on plugin development</p> + <ul> + ]]); + for i, extra in ipairs(g_APIDesc.ExtraPages) do + local SrcFileName = g_PluginFolder .. "/" .. extra.FileName; + if (cFile:Exists(SrcFileName)) then + local DstFileName = "API/" .. extra.FileName; + if (cFile:Exists(DstFileName)) then + cFile:Delete(DstFileName); + end + cFile:Copy(SrcFileName, DstFileName); + f:write("<li><a href=\"" .. extra.FileName .. "\">" .. extra.Title .. "</a></li>\n"); + else + f:write("<li>" .. extra.Title .. " <i>(file is missing)</i></li>\n"); + end + end + f:write("</ul><hr />"); +end + + + + + +local function WriteClasses(f, a_API, a_ClassMenu) + f:write([[ + <a name="classes"><h2>Class index</h2></a> + <p>The following classes are available in the MCServer Lua scripting language: + <ul> + ]]); + for i, cls in ipairs(a_API) do + f:write("<li><a href=\"", cls.Name, ".html\">", cls.Name, "</a></li>\n"); + WriteHtmlClass(cls, a_API, a_ClassMenu); + end + f:write([[ + </ul></p> + <hr /> + ]]); +end + + + + + +local function WriteHooks(f, a_Hooks, a_UndocumentedHooks, a_HookNav) + f:write([[ + <a name="hooks"><h2>Hooks</h2></a> + <p> + A plugin can register to be called whenever an "interesting event" occurs. It does so by calling + <a href="cPluginManager.html">cPluginManager</a>'s AddHook() function and implementing a callback + function to handle the event.</p> + <p> + 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 MCServer disables the default + behavior for the event). See each hook's details to see the exact behavior.</p> + <table> + <tr> + <th>Hook name</th> + <th>Called when</th> + </tr> + ]]); + for i, hook in ipairs(a_Hooks) do + if (hook.DefaultFnName == nil) then + -- The hook is not documented yet + f:write(" <tr>\n <td>" .. hook.Name .. "</td>\n <td><i>(No documentation yet)</i></td>\n </tr>\n"); + table.insert(a_UndocumentedHooks, hook.Name); + else + f:write(" <tr>\n <td><a href=\"" .. hook.DefaultFnName .. ".html\">" .. hook.Name .. "</a></td>\n <td>" .. LinkifyString(hook.CalledWhen, hook.Name) .. "</td>\n </tr>\n"); + WriteHtmlHook(hook, a_HookNav); + end + end + f:write([[ + </table> + <hr /> + ]]); +end + + + + + function DumpAPIHtml() LOG("Dumping all available functions and constants to API subfolder..."); - LOG("Moving static files.."); + LOG("Copying static files.."); cFile:CreateFolder("API/Static"); local localFolder = g_Plugin:GetLocalFolder(); - for k, v in cFile:GetFolderContents(localFolder .. "/Static") do - cFile:Copy(localFolder .. "/Static/" .. v, "API/Static/" .. v); + for idx, fnam in ipairs(cFile:GetFolderContents(localFolder .. "/Static")) do + cFile:Delete("API/Static/" .. fnam); + cFile:Copy(localFolder .. "/Static/" .. fnam, "API/Static/" .. fnam); end LOG("Creating API tables..."); @@ -293,7 +379,30 @@ function DumpAPIHtml() 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 idx, cls in ipairs(API) do + table.insert(ClassMenuTab, "<a href='"); + table.insert(ClassMenuTab, cls.Name); + table.insert(ClassMenuTab, ".html'>"); + table.insert(ClassMenuTab, cls.Name); + table.insert(ClassMenuTab, "</a><br />"); + 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 idx, hook in ipairs(Hooks) do + table.insert(HookNavTab, "<a href='"); + table.insert(HookNavTab, hook.DefaultFnName); + table.insert(HookNavTab, ".html'>"); + table.insert(HookNavTab, (hook.Name:gsub("^HOOK_", ""))); -- remove the "HOOK_" part of the name + table.insert(HookNavTab, "</a><br />"); + end + local HookNav = table.concat(HookNavTab, ""); + -- Write the HTML file: f:write([[<!DOCTYPE html> <html> <head> @@ -308,79 +417,30 @@ function DumpAPIHtml() </header> <p>The API reference is divided into the following sections:</p> <ul> + <li><a href="#articles">Articles</a></li> <li><a href="#classes">Class index</a></li> <li><a href="#hooks">Hooks</a></li> - <li><a href="#extra">Extra pages</a></li> <li><a href="#docstats">Documentation statistics</a></li> </ul> <hr /> - <a name="classes"><h2>Class index</h2></a> - <p>The following classes are available in the MCServer Lua scripting language: - <ul> - ]]); - for i, cls in ipairs(API) do - f:write("<li><a href=\"", cls.Name, ".html\">", cls.Name, "</a></li>\n"); - WriteHtmlClass(cls, API); - end - f:write([[ - </ul></p> - <hr /> - <a name="hooks"><h2>Hooks</h2></a> - <p> - A plugin can register to be called whenever an "interesting event" occurs. It does so by calling - <a href="cPluginManager.html">cPluginManager</a>'s AddHook() function and implementing a callback - function to handle the event.</p> - <p> - 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 MCServer disables the default - behavior for the event). See each hook's details to see the exact behavior.</p> - <table> - <tr> - <th>Hook name</th> - <th>Called when</th> - </tr> ]]); - for i, hook in ipairs(Hooks) do - if (hook.DefaultFnName == nil) then - -- The hook is not documented yet - f:write(" <tr>\n <td>" .. hook.Name .. "</td>\n <td><i>(No documentation yet)</i></td>\n </tr>\n"); - table.insert(UndocumentedHooks, hook.Name); - else - f:write(" <tr>\n <td><a href=\"" .. hook.DefaultFnName .. ".html\">" .. hook.Name .. "</a></td>\n <td>" .. LinkifyString(hook.CalledWhen, hook.Name) .. "</td>\n </tr>\n"); - WriteHtmlHook(hook); - end - end - f:write([[ </table> - <hr /> - <a name="extra"><h2>Extra pages</h2></a> - - <p>The following pages provide various extra information</p> - - <ul> -]]); - for i, extra in ipairs(g_APIDesc.ExtraPages) do - local SrcFileName = g_PluginFolder .. "/" .. extra.FileName; - if (cFile:Exists(SrcFileName)) then - local DstFileName = "API/" .. extra.FileName; - if (cFile:Exists(DstFileName)) then - cFile:Delete(DstFileName); - end - cFile:Copy(SrcFileName, DstFileName); - f:write(" <li><a href=\"" .. extra.FileName .. "\">" .. extra.Title .. "</a></li>\n"); - else - f:write(" <li>" .. extra.Title .. " <i>(file is missing)</i></li>\n"); - end + WriteArticles(f); + WriteClasses(f, API, ClassMenu); + WriteHooks(f, Hooks, UndocumentedHooks, HookNav); + + -- Copy the static files to the output folder: + local StaticFiles = + { + "main.css", + "prettify.js", + "prettify.css", + "lang-lua.js", + }; + for idx, fnam in ipairs(StaticFiles) do + cFile:Delete("API/" .. fnam); + cFile:Copy(g_Plugin:GetLocalFolder() .. "/" .. fnam, "API/" .. fnam); end - f:write("</ul>"); - - -- Copy the static files to the output folder (overwrite any existing): - cFile:Copy(g_Plugin:GetLocalFolder() .. "/main.css", "API/main.css"); - cFile:Copy(g_Plugin:GetLocalFolder() .. "/prettify.js", "API/prettify.js"); - cFile:Copy(g_Plugin:GetLocalFolder() .. "/prettify.css", "API/prettify.css"); - cFile:Copy(g_Plugin:GetLocalFolder() .. "/lang-lua.js", "API/lang-lua.js"); -- List the documentation problems: LOG("Listing leftovers..."); @@ -831,7 +891,7 @@ end -function WriteHtmlClass(a_ClassAPI, a_AllAPI) +function WriteHtmlClass(a_ClassAPI, a_AllAPI, a_ClassMenu) local cf, err = io.open("API/" .. a_ClassAPI.Name .. ".html", "w"); if (cf == nil) then return; @@ -946,7 +1006,17 @@ function WriteHtmlClass(a_ClassAPI, a_AllAPI) <h1>]], a_ClassAPI.Name, [[</h1> <hr /> </header> - <h1>Contents</h1> + <table><tr><td style="vertical-align: top;"> + Index:<br /> + <a href='index.html#articles'>Articles</a><br /> + <a href='index.html#classes'>Classes</a><br /> + <a href='index.html#hooks'>Hooks</a><br /> + <br /> + Quick navigation:<br /> + ]]); + cf:write(a_ClassMenu); + cf:write([[ + </td><td style="vertical-align: top;"><h1>Contents</h1> <p><ul> ]]); @@ -1044,7 +1114,7 @@ function WriteHtmlClass(a_ClassAPI, a_AllAPI) end end - cf:write([[</div><script>prettyPrint();</script></body></html>]]); + cf:write([[</td></tr></table></div><script>prettyPrint();</script></body></html>]]); cf:close(); end @@ -1052,7 +1122,7 @@ end -function WriteHtmlHook(a_Hook) +function WriteHtmlHook(a_Hook, a_HookNav) local fnam = "API/" .. a_Hook.DefaultFnName .. ".html"; local f, error = io.open(fnam, "w"); if (f == nil) then @@ -1075,7 +1145,17 @@ function WriteHtmlHook(a_Hook) <h1>]], a_Hook.Name, [[</h1> <hr /> </header> - <p> + <table><tr><td style="vertical-align: top;"> + Index:<br /> + <a href='index.html#articles'>Articles</a><br /> + <a href='index.html#classes'>Classes</a><br /> + <a href='index.html#hooks'>Hooks</a><br /> + <br /> + Quick navigation:<br /> + ]]); + f:write(a_HookNav); + f:write([[ + </td><td style="vertical-align: top;"><p> ]]); f:write(LinkifyString(a_Hook.Desc, HookName)); f:write("</p>\n<hr /><h1>Callback function</h1>\n<p>The default name for the callback function is "); @@ -1105,7 +1185,7 @@ function WriteHtmlHook(a_Hook) f:write("<p>", (example.Desc or "<i>missing Desc</i>"), "</p>\n"); f:write("<pre class=\"prettyprint lang-lua\">", (example.Code or "<i>missing Code</i>"), "\n</pre>\n\n"); end - f:write([[</div><script>prettyPrint();</script></body></html>]]); + f:write([[</td></tr></table></div><script>prettyPrint();</script></body></html>]]); f:close(); end |