From 81dbd23e1d4250067baae067bb4776069997929c Mon Sep 17 00:00:00 2001 From: Mark Suckerberg Date: Tue, 14 Nov 2023 22:29:49 -0600 Subject: [PATCH] Adds VERB_REF and derivative (#74500) Apparently in (one) place in the codebase, we were still using stuff like `.verb/example_verb` for stuff like `INVOKE_ASYNC()` and `CALLBACK()`s, and I'm pretty sure this is one of those things that are being phased out in 515 (like we had to deal with in 4d6a8bc5371eb61f9adb7c4dd1b8c441d3ae9251), so let's give it the same treatment as we did `PROC_REF` in November 2022. In order to make this work, I created a generic backend of define macros, and then moved two things: `PROC_REF` and `VERB_REF` to just leverage that backend as needed. This was done just so we didn't have to copy-paste code in case we needed to update these macros in the future, let me know if I should approach this a different way. code don't break (or at least the compile-time assertions won't break) when we inevitably fully shift to 515. whoopie! Nothing players should be concerned about. --- .github/CONTRIBUTING.md | 662 +++++++++++++++------------- code/__byond_version_compat.dm | 32 +- code/modules/client/client_procs.dm | 2 +- 3 files changed, 381 insertions(+), 315 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 70f333da19f9..6dce107dd553 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -61,84 +61,37 @@ As mentioned before, you are expected to follow these specifications in order to As BYOND's Dream Maker (henceforth "DM") is an object-oriented language, code must be object-oriented when possible in order to be more flexible when adding content to it. If you don't know what "object-oriented" means, we highly recommend you do some light research to grasp the basics. -### All BYOND paths must contain the full path +### Avoid hacky code +Hacky code, such as adding specific checks, is highly discouraged and only allowed when there is ***no*** other option. (Protip: "I couldn't immediately think of a proper way so thus there must be no other option" is not gonna cut it here! If you can't think of anything else, say that outright and admit that you need help with it. Maintainers exist for exactly that reason.) -(i.e. absolute pathing) - -DM will allow you nest almost any type keyword into a block, such as: - -```DM -datum - datum1 - var - varname1 = 1 - varname2 - static - varname3 - varname4 - proc - proc1() - code - proc2() - code - - datum2 - varname1 = 0 - proc - proc3() - code - proc2() - ..() - code -``` - -The use of this is not allowed in this project as it makes finding definitions via full text searching next to impossible. The only exception is the variables of an object may be nested to the object, but must not nest further. - -The previous code made compliant: - -```DM -/datum/datum1 - var/varname1 - var/varname2 - var/static/varname3 - var/static/varname4 - -/datum/datum1/proc/proc1() - code -/datum/datum1/proc/proc2() - code -/datum/datum1/datum2 - varname1 = 0 -/datum/datum1/datum2/proc/proc3() - code -/datum/datum1/datum2/proc2() - ..() - code -``` - -### No overriding type safety checks +You can avoid hacky code by using object-oriented methodologies, such as overriding a function (called "procs" in DM) or sectioning code into functions and then overriding them as required. -The use of the : operator to override type safety checks is not allowed. You must cast the variable to the proper type. +### Develop Secure Code -### Type paths must begin with a / +* Player input must always be escaped safely, we recommend you use stripped_input in all cases where you would use input. Essentially, just always treat input from players as inherently malicious and design with that use case in mind -eg: `/datum/thing`, not `datum/thing` +* Calls to the database must be escaped properly - use sanitizeSQL to escape text based database entries from players or admins, and isnum() for number based database entries from players or admins. -### Paths must be in snake case +* All calls to topics must be checked for correctness. Topic href calls can be easily faked by clients, so you should ensure that the call is valid for the state the item is in. Do not rely on the UI code to provide only valid topic calls, because it won't. -eg: `/obj/handheld_tool`, not `/obj/handheldTool` +* Information that players could use to metagame (that is, to identify round information and/or antagonist type via information that would not be available to them in character) should be kept as administrator only. -### Improve code in any files you touch +* It is recommended as well you do not expose information about the players - even something as simple as the number of people who have readied up at the start of the round can and has been used to try to identify the round type. -If there is legacy code in a file you are modifying it is also your responsibility to bring the old code up to standards. In general this means that if you are expanding upon a proc that has single letter var names, improperly formatted var names, etc you should be modernizing that proc. **This does not mean you have to refactor the entirety of the file, although doing so would be appreciated.** +* Where you have code that can cause large-scale modification and *FUN*, make sure you start it out locked behind one of the default admin roles - use common sense to determine which role fits the level of damage a function could do. -### Type paths must be lowercase +### User Interfaces -eg: `/datum/thing/blue`, not `datum/thing/BLUE` or `datum/thing/Blue` +* All new player-facing user interfaces must use TGUI, unless they are critical user interfaces. +* All critical user interfaces must be usable with HTML or the interface.dmf, with tgui being *optional* for this UI. + * Examples of critical user interfaces are the chat box, the observe button, the stat panel, and the chat input. +* Documentation for TGUI can be found at: + * [tgui/README.md](../tgui/README.md) + * [tgui/tutorial-and-examples.md](../tgui/docs/tutorial-and-examples.md) -### Datum type paths must began with "datum" +### Dont override type safety checks -In DM, this is optional, but omitting it makes finding definitions harder. +The use of the : operator to override type safety checks is not allowed. You must cast the variable to the proper type. ### Do not use text/string based type paths @@ -152,387 +105,482 @@ var/path_type = /obj/item/baseball_bat var/path_type = "/obj/item/baseball_bat" ``` -### Use var/name format when declaring variables +### Other Notes -While DM allows other ways of declaring variables, this one should be used for consistency. +* Code should be modular where possible; if you are working on a new addition, then strongly consider putting it in its own file unless it makes sense to put it with similar ones (i.e. a new tool would go in the "tools.dm" file) -### Tabs, not spaces +* Bloated code may be necessary to add a certain feature, which means there has to be a judgement over whether the feature is worth having or not. You can help make this decision easier by making sure your code is modular. -You must use tabs to indent your code, NOT SPACES. +* You are expected to help maintain the code that you add, meaning that if there is a problem then you are likely to be approached in order to fix any issues, runtimes, or bugs. -### No hacky code +* Do not divide when you can easily convert it to multiplication. (ie `4/2` should be done as `4*0.5`) -Hacky code, such as adding specific checks, is highly discouraged and only allowed when there is **_no_** other option. (Protip: 'I couldn't immediately think of a proper way so thus there must be no other option' is not gonna cut it here! If you can't think of anything else, say that outright and admit that you need help with it. Maintainers exist for exactly that reason.) +* Separating single lines into more readable blocks is not banned, however you should use it only where it makes new information more accessible, or aids maintainability. We do not have a column limit, and mass conversions will not be received well. -You can avoid hacky code by using object-oriented methodologies, such as overriding a function (called "procs" in DM) or sectioning code into functions and then overriding them as required. +* If you used regex to replace code during development of your code, post the regex in your PR for the benefit of future developers and downstream users. -### No duplicated code +* Changes to the `/config` tree must be made in a way that allows for updating server deployments while preserving previous behaviour. This is due to the fact that the config tree is to be considered owned by the user and not necessarily updated alongside the remainder of the code. The code to preserve previous behaviour may be removed at some point in the future given the OK by maintainers. +* The dlls section of tgs3.json is not designed for dlls that are purely `call()()`ed since those handles are closed between world reboots. Only put in dlls that may have to exist between world reboots. + +## Structural +### No duplicated code (Don't repeat yourself) Copying code from one place to another may be suitable for small, short-time projects, but /tg/station is a long-term project and highly discourages this. Instead you can use object orientation, or simply placing repeated code in a function, to obey this specification easily. -### Document your code - -Our codebase uses an interpreter called SpacemanDMM which includes the helpful ability to provide tooltips and inform you of documentation for various procs and vars. You are required to document any code you add so that it is readable and understandable to the maintainers of the codebase and also to other contributors. -eg: - -```dm -/// This proc causes the object to do a thing to the target mob -/obj/proc/do_thing(mob/target) -``` +### Prefer `Initialize()` over `New()` for atoms -eg2: +Our game controller is pretty good at handling long operations and lag, but it can't control what happens when the map is loaded, which calls `New` for all atoms on the map. If you're creating a new atom, use the `Initialize` proc to do what you would normally do in `New`. This cuts down on the number of proc calls needed when the world is loaded. See here for details on `Initialize`: https://github.com/tgstation/tgstation/blob/34775d42a2db4e0f6734560baadcfcf5f5540910/code/game/atoms.dm#L166 +While we normally encourage (and in some cases, even require) bringing out of date code up to date when you make unrelated changes near the out of date code, that is not the case for `New` -> `Initialize` conversions. These systems are generally more dependent on parent and children procs so unrelated random conversions of existing things can cause bugs that take months to figure out. -```dm -/* This is a special proc that causes the target mob to instantly gib itself - * If the argument recurse_contents is passed a truthy value all mobs inside the contents are also gibbed - */ -/mob/proc/gib_recurse(recurse_contents=FALSE) - if(!recurse_contents) - gib() - return - for(var/mob/other in contents) - other.gib() - gib() -``` +### Files -### Use self-explanatory var names +* Because runtime errors do not give the full path, try to avoid having files with the same name across folders. -When adding any new vars to a type, they must be self-explanatory and concise. -eg:`var/ticks_to_explosion` instead of `var/tte` +* File names should not be mixed case, or contain spaces or any character that would require escaping in a uri. -### Asyncronous proc calls +* Files and path accessed and referenced by code above simply being #included should be strictly lowercase to avoid issues on filesystems where case matters. -If there is something that must be done via an asyncronous call, it is required that it be done using the INVOKE_ASYNC macro. +### RegisterSignal() -### Signal Handlers +#### PROC_REF Macros +When referencing procs in RegisterSignal, Callback and other procs you should use PROC_REF, TYPE_PROC_REF and GLOBAL_PROC_REF macros. +They ensure compilation fails if the reffered to procs change names or get removed. +The macro to be used depends on how the proc you're in relates to the proc you want to use: -If you are registering signal handlers onto a type, the signal handler must have the SIGNAL_HANDLER definition and cannot sleep. If there is code in your signal handler that requires use of the sleep proc you must have your signal hander handle it via an invoke async call. +PROC_REF if the proc you want to use is defined on the current proc type or any of it's ancestor types. +Example: +``` +/mob/proc/funny() + to_chat(world,"knock knock") -### Data caching +/mob/subtype/proc/very_funny() + to_chat(world,"who's there?") -Types and procs that need to create or load large amounts of data that (should) never change needs to be cached into a static var so that in the event the proc needs to load the data again instead of recreating the data it has a cache that it can pull from, this reduces overhead and memory usage. +/mob/subtype/proc/do_something() + // Proc on our own type + RegisterSignal(x, COMSIG_OTHER_FAKE, PROC_REF(very_funny)) + // Proc on ancestor type, /mob is parent type of /mob/subtype + RegisterSignal(x, COMSIG_FAKE, PROC_REF(funny)) +``` -### Startup/Runtime tradeoffs with lists and the "hidden" init proc +TYPE_PROC_REF if the proc you want to use is defined on a different unrelated type +Example: +``` +/obj/thing/proc/funny() + to_chat(world,"knock knock") -First, read the comments in [this BYOND thread](http://www.byond.com/forum/?post=2086980&page=2#comment19776775), starting where the link takes you. +/mob/subtype/proc/do_something() + var/obj/thing/x = new() + // we're referring to /obj/thing proc inside /mob/subtype proc + RegisterSignal(x, COMSIG_FAKE, TYPE_PROC_REF(/obj/thing, funny)) +``` -There are two key points here: +GLOBAL_PROC_REF if the proc you want to use is a global proc. +Example: +``` +/proc/funny() + to_chat(world,"knock knock") -1. Defining a list in the variable's definition calls a hidden proc - init. If you have to define a list at startup, do so in New() (or preferably Initialize()) and avoid the overhead of a second call (Init() and then New()) +/mob/subtype/proc/do_something() + addtimer(CALLBACK(GLOBAL_PROC, GLOBAL_PROC_REF(funny)), 100)) +``` -2. It also consumes more memory to the point where the list is actually required, even if the object in question may never use it! +Note that the same rules go for verbs too! We have VERB_REF() and TYPE_VERB_REF() as you need it in these same cases. GLOBAL_VERB_REF() isn't a thing however, as verbs are not global. -Remember: although this tradeoff makes sense in many cases, it doesn't cover them all. Think carefully about your addition before deciding if you need to use it. +#### Signal Handlers -### Prefer `Initialize()` over `New()` when possible +All procs that are registered to listen for signals using `RegisterSignal()` must contain at the start of the proc `SIGNAL_HANDLER` eg; +``` +/type/path/proc/signal_callback() + SIGNAL_HANDLER + // rest of the code +``` +This is to ensure that it is clear the proc handles signals and turns on a lint to ensure it does not sleep. -Our game controller is pretty good at handling long operations and lag, but it can't control what happens when the map is loaded, which calls `New` for all atoms on the map. If you're creating a new atom, use the `Initialize` proc to do what you would normally do in `New`. This cuts down on the number of proc calls needed when the world is loaded. See here for details on `Initialize`: https://github.com/tgstation/tgstation/blob/master/code/game/atoms.dm#L49 -While we normally encourage (and in some cases, even require) bringing out of date code up to date when you make unrelated changes near the out of date code, that is not the case for `New` -> `Initialize` conversions. These systems are generally more dependant on parent and children procs so unrelated random conversions of existing things can cause bugs that take months to figure out. +Any sleeping behaviour that you need to perform inside a `SIGNAL_HANDLER` proc must be called asynchronously (e.g. with `INVOKE_ASYNC()`) or be redone to work asynchronously. -### No magic numbers or strings +#### `override` -This means stuff like having a "mode" variable for an object set to "1" or "2" with no clear indicator of what that means. Make these #defines with a name that more clearly states what it's for. For instance: +Each atom can only register a signal on the same object once, or else you will get a runtime. Overriding signals is usually a bug, but if you are confident that it is not, you can silence this runtime with `override = TRUE`. -```DM -/datum/proc/do_the_thing(thing_to_do) - switch(thing_to_do) - if(1) - (...) - if(2) - (...) +```dm +RegisterSignal(fork, COMSIG_FORK_STAB, PROC_REF(on_fork_stab), override = TRUE) ``` -There's no indication of what "1" and "2" mean! Instead, you'd do something like this: +If you decide to do this, you should make it clear with a comment explaining why it is necessary. This helps us to understand that the signal override is not a bug, and may help us to remove it in the future if the assumptions change. -```DM -#define DO_THE_THING_REALLY_HARD 1 -#define DO_THE_THING_EFFICIENTLY 2 -/datum/proc/do_the_thing(thing_to_do) - switch(thing_to_do) - if(DO_THE_THING_REALLY_HARD) - (...) - if(DO_THE_THING_EFFICIENTLY) - (...) -``` +### Enforcing parent calling -This is clearer and enhances readability of your code! Get used to doing it! +When adding new signals to root level procs, eg; +``` +/atom/proc/setDir(newdir) + SHOULD_CALL_PARENT(TRUE) + SEND_SIGNAL(src, COMSIG_ATOM_DIR_CHANGE, dir, newdir) + dir = newdir +``` +The `SHOULD_CALL_PARENT(TRUE)` lint should be added to ensure that overrides/child procs call the parent chain and ensure the signal is sent. -### Control statements +### Avoid unnecessary type checks and obscuring nulls in lists -(if, while, for, etc) +Typecasting in `for` loops carries an implied `istype()` check that filters non-matching types, nulls included. The `as anything` key can be used to skip the check. -- All control statements must not contain code on the same line as the statement (`if (blah) return`) -- All control statements comparing a variable to a number should use the formula of `thing` `operator` `number`, not the reverse (eg: `if (count <= 10)` not `if (10 >= count)`) +If we know the list is supposed to only contain the desired type then we want to skip the check not only for the small optimization it offers, but also to catch any null entries that may creep into the list. -### Use early return +Nulls in lists tend to point to improperly-handled references, making hard deletes hard to debug. Generating a runtime in those cases is more often than not positive. -Do not enclose a proc in an if-block when returning on a condition is more feasible This is bad: - ```DM -/datum/datum1/proc/proc1() - if (thing1) - if (!thing2) - if (thing3 == 30) - do stuff +var/list/bag_of_atoms = list(new /obj, new /mob, new /atom, new /atom/movable, new /atom/movable) +var/highest_alpha = 0 +for(var/atom/thing in bag_of_atoms) + if(thing.alpha <= highest_alpha) + continue + highest_alpha = thing.alpha ``` This is good: - ```DM -/datum/datum1/proc/proc1() - if (!thing1) - return - if (thing2) - return - if (thing3 != 30) - return - do stuff +var/list/bag_of_atoms = list(new /obj, new /mob, new /atom, new /atom/movable, new /atom/movable) +var/highest_alpha = 0 +for(var/atom/thing as anything in bag_of_atoms) + if(thing.alpha <= highest_alpha) + continue + highest_alpha = thing.alpha ``` -This prevents nesting levels from getting deeper then they need to be. - -### Develop Secure Code - -- Player input must always be escaped safely, we recommend you use stripped_input in all cases where you would use input. Essentially, just always treat input from players as inherently malicious and design with that use case in mind - -- Calls to the database must be escaped properly - use sanitizeSQL to escape text based database entries from players or admins, and isnum() for number based database entries from players or admins. - -- All calls to topics must be checked for correctness. Topic href calls can be easily faked by clients, so you should ensure that the call is valid for the state the item is in. Do not rely on the UI code to provide only valid topic calls, because it won't. +### All `process` procs need to make use of delta-time and be frame independent -- Information that players could use to metagame (that is, to identify round information and/or antagonist type via information that would not be available to them in character) should be kept as administrator only. +In a lot of our older code, `process()` is frame dependent. Here's some example mob code: -- It is recommended as well you do not expose information about the players - even something as simple as the number of people who have readied up at the start of the round can and has been used to try to identify the round type. - -- Where you have code that can cause large-scale modification and _FUN_, make sure you start it out locked behind one of the default admin roles - use common sense to determine which role fits the level of damage a function could do. - -### Files - -- Because runtime errors do not give the full path, try to avoid having files with the same name across folders. - -- File names should not be mixed case, or contain spaces or any character that would require escaping in a uri. - -- Files and path accessed and referenced by code above simply being #included should be strictly lowercase to avoid issues on filesystems where case matters. - -### SQL +```DM +/mob/testmob + var/health = 100 + var/health_loss = 4 //We want to lose 2 health per second, so 4 per SSmobs process -- Do not use the shorthand sql insert format (where no column names are specified) because it unnecessarily breaks all queries on minor column changes and prevents using these tables for tracking outside related info such as in a connected site/forum. +/mob/testmob/process(delta_time) //SSmobs runs once every 2 seconds + health -= health_loss +``` -- All changes to the database's layout(schema) must be specified in the database changelog in SQL, as well as reflected in the schema files +As the mobs subsystem runs once every 2 seconds, the mob now loses 4 health every process, or 2 health per second. This is called frame dependent programming. -- Any time the schema is changed the `schema_revision` table and `DB_MAJOR_VERSION` or `DB_MINOR_VERSION` defines must be incremented. +Why is this an issue? If someone decides to make it so the mobs subsystem processes once every second (2 times as fast), your effects in process() will also be two times as fast. Resulting in 4 health loss per second rather than 2. -- Queries must never specify the database, be it in code, or in text files in the repo. +How do we solve this? By using delta-time. Delta-time is the amount of seconds you would theoretically have between 2 process() calls. In the case of the mobs subsystem, this would be 2 (As there is 2 seconds between every call in `process()`). Here is a new example using delta-time: -- Primary keys are inherently immutable and you must never do anything to change the primary key of a row or entity. This includes preserving auto increment numbers of rows when copying data to a table in a conversion script. No amount of bitching about gaps in ids or out of order ids will save you from this policy. +```DM +/mob/testmob + var/health = 100 + var/health_loss = 2 //Health loss every second -### Mapping Standards +/mob/testmob/process(delta_time) //SSmobs runs once every 2 seconds + health -= health_loss * delta_time +``` -- TGM Format & Map Merge +In the above example, we made our health_loss variable a per second value rather than per process. In the actual process() proc we then make use of deltatime. Because SSmobs runs once every 2 seconds. Delta_time would have a value of 2. This means that by doing health_loss * delta_time, you end up with the correct amount of health_loss per process, but if for some reason the SSmobs subsystem gets changed to be faster or slower in a PR, your health_loss variable will work the same. - - All new maps submitted to the repo through a pull request must be in TGM format (unless there is a valid reason present to have it in the default BYOND format.) This is done using the [Map Merge](https://github.com/tgstation/tgstation/wiki/Map-Merger) utility included in the repo to convert the file to TGM format. - - Likewise, you MUST run Map Merge prior to opening your PR when updating existing maps to minimize the change differences (even when using third party mapping programs such as FastDMM.) - - Failure to run Map Merge on a map after using third party mapping programs (such as FastDMM) greatly increases the risk of the map's key dictionary becoming corrupted by future edits after running map merge. Resolving the corruption issue involves rebuilding the map's key dictionary; id est rewriting all the keys contained within the map by reconverting it from BYOND to TGM format - which creates very large differences that ultimately delay the PR process and is extremely likely to cause merge conflicts with other pull requests. +For example, if SSmobs is set to run once every 4 seconds, it would call process once every 4 seconds and multiply your health_loss var by 4 before subtracting it. Ensuring that your code is frame independent. -- Variable Editing (Var-edits) - - While var-editing an item within the editor is perfectly fine, it is preferred that when you are changing the base behavior of an item (how it functions) that you make a new subtype of that item within the code, especially if you plan to use the item in multiple locations on the same map, or across multiple maps. This makes it easier to make corrections as needed to all instances of the item at one time as opposed to having to find each instance of it and change them all individually. - - Subtypes only intended to be used on away mission or ruin maps should be contained within an .dm file with a name corresponding to that map within `code\modules\awaymissions` or `code\modules\ruins` respectively. This is so in the event that the map is removed, that subtype will be removed at the same time as well to minimize leftover/unused data within the repo. - - Please attempt to clean out any dirty variables that may be contained within items you alter through var-editing. For example, due to how DM functions, changing the `pixel_x` variable from 23 to 0 will leave a dirty record in the map's code of `pixel_x = 0`. Likewise this can happen when changing an item's icon to something else and then back. This can lead to some issues where an item's icon has changed within the code, but becomes broken on the map due to it still attempting to use the old entry. - - Areas should not be var-edited on a map to change it's name or attributes. All areas of a single type and it's altered instances are considered the same area within the code, and editing their variables on a map can lead to issues with powernets and event subsystems which are difficult to debug. +## Optimization +### Startup/Runtime tradeoffs with lists and the "hidden" init proc -### User Interfaces +First, read the comments in [this BYOND thread](http://www.byond.com/forum/?post=2086980&page=2#comment19776775), starting where the link takes you. -- All new player-facing user interfaces must use TGUI. -- Raw HTML is permitted for admin and debug UIs. -- Documentation for TGUI can be found at: - - [tgui/README.md](../tgui/README.md) - - [tgui/tutorial-and-examples.md](../tgui/docs/tutorial-and-examples.md) +There are two key points here: -### Don't create code that hangs references +1) Defining a list in the variable's definition calls a hidden proc - init. If you have to define a list at startup, do so in New() (or preferably Initialize()) and avoid the overhead of a second call (Init() and then New()) -This is part of the larger issue of hard deletes, read this file for more info: [Guide to Harddels](HARDDEL_GUIDE.md)) +2) It also consumes more memory to the point where the list is actually required, even if the object in question may never use it! -### Other Notes +Remember: although this tradeoff makes sense in many cases, it doesn't cover them all. Think carefully about your addition before deciding if you need to use it. -- Code should be modular where possible; if you are working on a new addition, then strongly consider putting it in its own file unless it makes sense to put it with similar ones (i.e. a new tool would go in the "tools.dm" file) +### Icons are for image manipulation and defining an obj's `.icon` var, appearances are for everything else. -- Bloated code may be necessary to add a certain feature, which means there has to be a judgement over whether the feature is worth having or not. You can help make this decision easier by making sure your code is modular. +BYOND will allow you to use a raw icon file or even an icon datum for underlays, overlays, and what not (you can even use strings to refer to an icon state on the current icon). The issue is these get converted by BYOND to appearances on every overlay insert or removal involving them, and this process requires inserting the new appearance into the global list of appearances, and informing clients about them. -- You are expected to help maintain the code that you add, meaning that if there is a problem then you are likely to be approached in order to fix any issues, runtimes, or bugs. +Converting them yourself to appearances and storing this converted value will ensure this process only has to happen once for the lifetime of the round. Helper functions exist to do most of the work for you. -- Do not divide when you can easily convert it to multiplication. (ie `4/2` should be done as `4*0.5`) -- If you used regex to replace code during development of your code, post the regex in your PR for the benefit of future developers and downstream users. +Bad: +```dm +/obj/machine/update_overlays(blah) + if (stat & broken) + add_overlay(icon(broken_icon)) //this icon gets created, passed to byond, converted to an appearance, then deleted. + return + if (is_on) + add_overlay("on") //also bad, the converstion to an appearance still has to happen + else + add_overlay(iconstate2appearance(icon, "off")) //this might seem alright, but not storing the value just moves the repeated appearance generation to this proc rather then the core overlay management. It would only be acceptable (and to some degree perferred) if this overlay is only ever added once (like in init code) +``` -- Changes to the `/config` tree must be made in a way that allows for updating server deployments while preserving previous behaviour. This is due to the fact that the config tree is to be considered owned by the user and not necessarily updated alongside the remainder of the code. The code to preserve previous behaviour may be removed at some point in the future given the OK by maintainers. +Good: +```dm +/obj/machine/update_overlays(var/blah) + var/static/on_overlay + var/static/off_overlay + var/static/broken_overlay + if(isnull(on_overlay)) //static vars initialize with global variables, meaning src is null and this won't pass integration tests unless you check. + on_overlay = iconstate2appearance(icon, "on") + off_overlay = iconstate2appearance(icon, "off") + broken_overlay = icon2appearance(broken_icon) + if (stat & broken) + add_overlay(broken_overlay) + return + if (is_on) + add_overlay(on_overlay) + else + add_overlay(off_overlay) + ... +``` -- The dlls section of tgs3.json is not designed for dlls that are purely `call()()`ed since those handles are closed between world reboots. Only put in dlls that may have to exist between world reboots. +Note: images are appearances with extra steps, and don't incur the overhead in conversion. -#### Enforced not enforced -The following coding styles are not only not enforced at all, but are generally frowned upon to change for little to no reason: +### Do not abuse associated lists. -- English/British spelling on var/proc names - - Color/Colour - both are fine, but keep in mind that BYOND uses `color` as a base variable -- Spaces after control statements - - `if()` and `if ()` - nobody cares! +Associated lists that could instead be variables or statically defined number indexed lists will use more memory, as associated lists have a 24 bytes per item overhead (vs 8 for lists and most vars), and are slower to search compared to static/global variables and lists with known indexes. -### Operators -#### Spacing +Bad: +```dm +/obj/machine/update_overlays(var/blah) + var/static/our_overlays + if (isnull(our_overlays)) + our_overlays = list("on" = iconstate2appearance(overlay_icon, "on"), "off" = iconstate2appearance(overlay_icon, "off"), "broken" = iconstate2appearance(overlay_icon, "broken")) + if (stat & broken) + add_overlay(our_overlays["broken"]) + return + ... +``` -- Operators that should be separated by spaces - - Boolean and logic operators like &&, || <, >, ==, etc (but not !) - - Bitwise AND & - - Argument separator operators like , (and ; when used in a forloop) - - Assignment operators like = or += or the like -- Operators that should not be separated by spaces - - Bitwise OR | - - Access operators like . and : - - Parentheses () - - logical not ! +Good: +```dm +#define OUR_ON_OVERLAY 1 +#define OUR_OFF_OVERLAY 2 +#define OUR_BROKEN_OVERLAY 3 + +/obj/machine/update_overlays(var/blah) + var/static/our_overlays + if (isnull(our_overlays)) + our_overlays = list(iconstate2appearance(overlay_icon, "on"), iconstate2appearance(overlay_icon, "off"), iconstate2appearance(overlay_icon, "broken")) + if (stat & broken) + add_overlay(our_overlays[OUR_BROKEN_OVERLAY]) + return + ... -Math operators like +, -, /, \*, etc are up in the air, just choose which version looks more readable. +#undef OUR_ON_OVERLAY +#undef OUR_OFF_OVERLAY +#undef OUR_BROKEN_OVERLAY +``` +Storing these in a flat (non-associated) list saves on memory, and using defines to reference locations in the list saves CPU time searching the list. -#### Use +Also good: +```dm +/obj/machine/update_overlays(var/blah) + var/static/on_overlay + var/static/off_overlay + var/static/broken_overlay + if(isnull(on_overlay)) + on_overlay = iconstate2appearance(overlay_icon, "on") + off_overlay = iconstate2appearance(overlay_icon, "off") + broken_overlay = iconstate2appearance(overlay_icon, "broken") + if (stat & broken) + add_overlay(broken_overlay) + return + ... +``` +Proc variables, static variables, and global variables are resolved at compile time, so the above is equivalent to the second example, but is easier to read, and avoids the need to store a list. -- Bitwise AND - '&' - - Should be written as `bitfield & bitflag` NEVER `bitflag & bitfield`, both are valid, but the latter is confusing and nonstandard. -- Associated lists declarations must have their key value quoted if it's a string - - WRONG: list(a = "b") - - RIGHT: list("a" = "b") +Note: While there has historically been a strong impulse to use associated lists for caching of computed values, this is the easy way out and leaves a lot of hidden overhead. Please keep this in mind when designing core/root systems that are intended for use by other code/coders. It's normally better for consumers of such systems to handle their own caching using vars and number indexed lists, than for you to do it using associated lists. -### Dream Maker Quirks/Tricks +## Dream Maker Quirks/Tricks -Like all languages, Dream Maker has its quirks, some of them are beneficial to us, like these +Like all languages, Dream Maker has its quirks, some of them are beneficial to us, some are harmful. +### Loops #### In-To for-loops `for(var/i = 1, i <= some_value, i++)` is a fairly standard way to write an incremental for loop in most languages (especially those in the C family), but DM's `for(var/i in 1 to some_value)` syntax is oddly faster than its implementation of the former syntax; where possible, it's advised to use DM's syntax. (Note, the `to` keyword is inclusive, so it automatically defaults to replacing `<=`; if you want `<` then you should write it as `1 to some_value-1`). HOWEVER, if either `some_value` or `i` changes within the body of the for (underneath the `for(...)` header) or if you are looping over a list AND changing the length of the list then you can NOT use this type of for-loop! -### for(var/A in list) VS for(var/i in 1 to list.len) +#### `for(var/A in list)` versus `for(var/i in 1 to list.len)` The former is faster than the latter, as shown by the following profile results: https://file.house/zy7H.png Code used for the test in a readable format: https://pastebin.com/w50uERkG -#### Istypeless for loops +### Dot variable (`.`) -A name for a differing syntax for writing for-each style loops in DM. It's NOT DM's standard syntax, hence why this is considered a quirk. Take a look at this: +The `.` variable is present in all procs. It refers to the value returned by a proc. -```DM -var/list/bag_of_items = list(sword, apple, coinpouch, sword, sword) -var/obj/item/sword/best_sword -for(var/obj/item/sword/S in bag_of_items) - if(!best_sword || S.damage > best_sword.damage) - best_sword = S +```dm +/proc/return_six() + . = 3 + . *= 2 + +// ...is equivalent to... +/proc/return_six() + var/output = 3 + output *= 2 + return output ``` -The above is a simple proc for checking all swords in a container and returning the one with the highest damage, and it uses DM's standard syntax for a for-loop by specifying a type in the variable of the for's header that DM interprets as a type to filter by. It performs this filter using `istype()` (or some internal-magic similar to `istype()` - this is BYOND, after all). This is fine in its current state for `bag_of_items`, but if `bag_of_items` contained ONLY swords, or only SUBTYPES of swords, then the above is inefficient. For example: +At its best, it can make some very common patterns easy to use, and harder to mess up. However, at its worst, it can make it significantly harder to understand what a proc does. -```DM -var/list/bag_of_swords = list(sword, sword, sword, sword) -var/obj/item/sword/best_sword -for(var/obj/item/sword/S in bag_of_swords) - if(!best_sword || S.damage > best_sword.damage) - best_sword = S +```dm +/proc/complex_proc() + if (do_something()) + some_code() + if (do_something_else()) + . = TRUE // Uh oh, what's going on! + + // even + // more + // code + if (bad_condition()) + return // This actually will return something set from earlier! ``` -specifies a type for DM to filter by. +This sort of behavior can create some nasty to debug errors with things returning when you don't expect them to. Would you see `return` and it expect it to return a value, without reading all the code before it? Furthermore, a simple `return` statement cannot easily be checked by the LSP, meaning you can't easily check what is actually being returned. Basically, `return output` lets you go to where `output` is defined/set. `return` does not. -With the previous example that's perfectly fine, we only want swords, but here the bag only contains swords? Is DM still going to try to filter because we gave it a type to filter by? YES, and here comes the inefficiency. Wherever a list (or other container, such as an atom (in which case you're technically accessing their special contents list, but that's irrelevant)) contains datums of the same datatype or subtypes of the datatype you require for your loop's body, -you can circumvent DM's filtering and automatic `istype()` checks by writing the loop as such: +Even in simple cases, this can create some just generally hard to read code, seemingly in the pursuit of being clever. -```DM -var/list/bag_of_swords = list(sword, sword, sword, sword) -var/obj/item/sword/best_sword -for(var/s in bag_of_swords) - var/obj/item/sword/S = s - if(!best_sword || S.damage > best_sword.damage) - best_sword = S +```dm +/client/p_were(gender) + . = "was" + if (gender == PLURAL || gender == NEUTER) + . = "were" ``` -Of course, if the list contains data of a mixed type then the above optimisation is DANGEROUS, as it will blindly typecast all data in the list as the specified type, even if it isn't really that type, causing runtime errors. +Because of these problems, it is encouraged to prefer standard, explicit return statements. The above code would be best written as: -#### Dot variable +```dm +/client/p_were(gender) + if (gender == PLURAL || gender == NEUTER) + return "were" + else + return "was" +``` -Like other languages in the C family, DM has a `.` or "Dot" operator, used for accessing variables/members/functions of an object instance. -eg: +#### Exception: `. = ..()` -```DM -var/mob/living/carbon/human/H = YOU_THE_READER -H.gib() +As hinted at before, `. = ..()` is *extremely* common. This will call the parent function, and preserve its return type. Code like this: + +```dm +/obj/item/spoon/attack() + . = ..() + visible_message("Whack!") +``` + +...is completely accepted, and in fact, usually *prefered* over: + +```dm +/obj/item/spoon/attack() + var/output = ..() + visible_message("Whack!") + return output ``` -However, DM also has a dot variable, accessed just as `.` on its own, defaulting to a value of null. Now, what's special about the dot operator is that it is automatically returned (as in the `return` statement) at the end of a proc, provided the proc does not already manually return (`return count` for example.) Why is this special? +#### Exception: Runtime resilience -With `.` being everpresent in every proc, can we use it as a temporary variable? Of course we can! However, the `.` operator cannot replace a typecasted variable - it can hold data any other var in DM can, it just can't be accessed as one, although the `.` operator is compatible with a few operators that look weird but work perfectly fine, such as: `.++` for incrementing `.'s` value, or `.[1]` for accessing the first element of `.`, provided that it's a list. +One unique property of DM is the ability for procs to error, but for code to continue. For instance, the following: -## Globals versus static +```dm +/proc/uh_oh() + CRASH("oh no!") -DM has a var keyword, called global. This var keyword is for vars inside of types. For instance: +/proc/main() + to_chat(world, "1") + uh_oh() + to_chat(world, "2") +``` -```DM -mob - var - global - thing = TRUE +...would print both 1 *and* 2, which may be unexpected if you come from other languages. + +This is where `.` provides a new useful behavior--**a proc that runtimes will return `.`**. + +Meaning: + +```dm +/proc/uh_oh() + . = "woah!" + CRASH("oh no!") + +/proc/main() + to_chat(world, uh_oh()) ``` -This does NOT mean that you can access it everywhere like a global var. Instead, it means that that var will only exist once for all instances of its type, in this case that var will only exist once for all mobs - it's shared across everything in its type. (Much more like the keyword `static` in other languages like PHP/C++/C#/Java) +...will print `woah!`. -Isn't that confusing? +For this reason, it is acceptable for `.` to be used in places where consumers can reasonably continue in the event of a runtime. -There is also an undocumented keyword called `static` that has the same behaviour as global but more correctly describes BYOND's behaviour. Therefore, we always use static instead of global where we need it, as it reduces suprise when reading BYOND code. +If you are using `.` in this case (or for another case that might be acceptable, other than most uses of `. = ..()`), it is still prefered that you explicitly `return .` in order to prevent both editor issues and readability/error-prone issues. -## Pull Request Process +```dm +/proc/uh_oh() + . = "woah!" -There is no strict process when it comes to merging pull requests. Pull requests will sometimes take a while before they are looked at by a maintainer; the bigger the change, the more time it will take before they are accepted into the code. Every team member is a volunteer who is giving up their own time to help maintain and contribute, so please be courteous and respectful. Here are some helpful ways to make it easier for you and for the maintainers when making a pull request. + if (do_something()) + call_code() + if (!working_fine()) + return . // Instead of `return`, we explicitly `return .` -- Make sure your pull request complies to the requirements outlined here + if (some_fail_state()) + CRASH("youch!") -- You are going to be expected to document all your changes in the pull request. Failing to do so will mean delaying it as we will have to question why you made the change. On the other hand, you can speed up the process by making the pull request readable and easy to understand, with diagrams or before/after data. + return . // `return .` is used at the end, to signify it has been used +``` -- We ask that you use the changelog system to document your change, which prevents our players from being caught unaware by changes. +```dm +/obj/item/spoon/super_attack() + . = ..() + if (. == BIGGER_SUPER_ATTACK) + return BIGGER_SUPER_ATTACK // More readable than `.` + + // Due to how common it is, most uses of `. = ..()` do not need a trailing `return .` +``` -- If you are proposing multiple changes, which change many different aspects of the code, you are expected to section them off into different pull requests in order to make it easier to review them and to deny/accept the changes that are deemed acceptable. (This is called atomization, if someone asks you to do it.) +### The BYOND walk procs -- If your pull request rebalances something or adds a large new feature, it may be put up to vote. This vote will usually end 24 hours after it is announced. If the vote passes, the code has not been substantially changed since the vote began, and no maintainers have any pending requested changes, the pull request will likely be merged. If a maintainer deems it so, a controversial tag will be added to the PR, which then requires all votes to require a ratio of 1:2 of likes to dislikes to pass (subject to the topic of the PR), and the vote will go on for at least double the normal time. +BYOND has a few procs that move one atom towards/away from another, `walk()`, `walk_to()`, `walk_towards`, `walk_away()` and `walk_rand()`. -- Reverts of major features must be done three to four weeks (at minimum) after the PR that added it, unless said feature has a server-affecting exploit or error. Reverts of smaller features and rebalances must be done at minimum one week after. +The way they pull this off, while fine for the language itself, makes a mess of our master-controller, and can cause the whole game to slow down. Do not use them. -- Pull requests that are made as alternatives with few changes will be closed by maintainers. Use suggestions on the original pull request instead. +The following is a list of procs, and their safe replacements. -- If your pull request is accepted, the code you add no longer belongs exclusively to you but to everyone; everyone is free to work on it, but you are also free to support or object to any changes being made, which will likely hold more weight, as you're the one who added the feature. It is a shame this has to be explicitly said, but there have been cases where this would've saved some trouble. +* Removing something from the loop `walk(0)` -> `SSmove_manager.stop_looping()` +* Move in a direction `walk()` -> `SSmove_manager.move()` +* Move towards a thing, taking turf density into account`walk_to()` -> `SSmove_manager.move_to()` +* Move in a thing's direction, ignoring turf density `walk_towards()` -> `SSmove_manager.home_onto()` and `SSmove_manager.move_towards_legacy()`, check the documentation to see which you like better +* Move away from something, taking turf density into account `walk_away()` -> `SSmove_manager.move_away()` +* Move to a random place nearby. NOT random walk `walk_rand()` -> `SSmove_manager.move_rand()` is random walk, `SSmove_manager.move_to_rand()` is walk to a random place -- Please explain why you are submitting the pull request, and how you think your change will be beneficial to the game. Failure to do so will be grounds for rejecting the PR. +### BYOND hellspawn -- If your pull request is not finished make sure it is at least testable in a live environment, or at the very least mark it as a draft. Pull requests that do not at least meet this requirement will be closed. You may request a maintainer reopen the pull request when you're ready, or make a new one. +What follows is documentation of inconsistent or strange behavior found in our engine, BYOND. +It's listed here in the hope that it will prevent fruitless debugging in future. -- While we have no issue helping contributors (and especially new contributors) bring reasonably sized contributions up to standards via the pull request review process, larger contributions are expected to pass a higher bar of completeness and code quality _before_ you open a pull request. Maintainers may close such pull requests that are deemed to be substantially flawed. You should take some time to discuss with maintainers or other contributors on how to improve the changes. +#### Icon hell -## Porting features/sprites/sounds/tools from other codebases +Due to how they are internally represented as part of appearance, overlays and underlays which have an icon_state named the same as an icon_state on the parent object will use the parent's icon_state and look completely wrong. This has caused two bugs with underlay lighting whenever a turf had the icon_state of "transparent" or "dark" and their lighting objects also had those states - because when the lighting underlays were in those modes they would be rendered by the client to look like the icons the floor used. When adding something as an overlay or an underlay make sure it can't match icon_state names with whatever you're adding it to. -If you are porting features/tools from other codebases, you must give the original authors credit where it's due. Typically, crediting them in your pull request and the changelog is the recommended way of doing it. Take note of what license they use though, porting stuff from AGPLv3 and GPLv3 codebases are allowed. +## SQL -Regarding sprites & sounds, you must credit the artist and possibly the codebase. All /tg/station assets including icons and sound are under a [Creative Commons 3.0 BY-SA license](https://creativecommons.org/licenses/by-sa/3.0/) unless otherwise indicated. However if you are porting assets from GoonStation or usually any assets under the [Creative Commons 3.0 BY-NC-SA license](https://creativecommons.org/licenses/by-nc-sa/3.0/) are to go into the 'goon' folder of the /tg/station codebase. +* Do not use the shorthand sql insert format (where no column names are specified) because it unnecessarily breaks all queries on minor column changes and prevents using these tables for tracking outside related info such as in a connected site/forum. -## Banned content +* All changes to the database's layout(schema) must be specified in the database changelog in SQL, as well as reflected in the schema files -Do not add any of the following in a Pull Request or risk getting the PR closed: +* Any time the schema is changed the `schema_revision` table and `DB_MAJOR_VERSION` or `DB_MINOR_VERSION` defines must be incremented. -- National Socialist Party of Germany content, National Socialist Party of Germany related content, or National Socialist Party of Germany references -- Code where one line of code is split across mutiple lines (except for multiple, separate strings and comments; in those cases, existing longer lines must not be split up) -- Code adding, removing, or updating the availability of alien races/species/human mutants without prior approval. Pull requests attempting to add or remove features from said races/species/mutants require prior approval as well. -- Code which violates GitHub's [terms of service](https://github.com/site/terms). +* Queries must never specify the database, be it in code, or in text files in the repo. -Just because something isn't on this list doesn't mean that it's acceptable. Use common sense above all else. +* Primary keys are inherently immutable and you must never do anything to change the primary key of a row or entity. This includes preserving auto increment numbers of rows when copying data to a table in a conversion script. No amount of bitching about gaps in ids or out of order ids will save you from this policy. -## Line Endings +* The ttl for data from the database is 10 seconds. You must have a compelling reason to store and reuse data for longer then this. -All newly created, uploaded, or modified files in this codebase are required to be using the Unix Schema for line endings. That means the only acceptable line ending is '**\n**', not '**\r\n**' nor '**\r\r**' +* Do not write stored and transformed data to the database, instead, apply the transformation to the data in the database directly. + * ie: SELECTing a number from the database, doubling it, then updating the database with the doubled number. If the data in the database changed between step 1 and 3, you'll get an incorrect result. Instead, directly double it in the update query. `UPDATE table SET num = num*2` instead of `UPDATE table SET num = [num]`. + * if the transformation is user provided (such as allowing a user to edit a string), you should confirm the value being updated did not change in the database in the intervening time before writing the new user provided data by checking the old value with the current value in the database, and if it has changed, allow the user to decide what to do next. diff --git a/code/__byond_version_compat.dm b/code/__byond_version_compat.dm index 3325107cc7bb..c45df2db15c2 100644 --- a/code/__byond_version_compat.dm +++ b/code/__byond_version_compat.dm @@ -21,21 +21,39 @@ #define LIBCALL call_ext #endif -// So we want to have compile time guarantees these procs exist on local type, unfortunately 515 killed the .proc/procname syntax so we have to use nameof() +// So we want to have compile time guarantees these methods exist on local type, unfortunately 515 killed the .proc/procname and .verb/verbname syntax so we have to use nameof() +// For the record: GLOBAL_VERB_REF would be useless as verbs can't be global. + #if DM_VERSION < 515 -/// Call by name proc reference, checks if the proc exists on this type or as a global proc + +/// Call by name proc references, checks if the proc exists on either this type or as a global proc. #define PROC_REF(X) (.proc/##X) -/// Call by name proc reference, checks if the proc exists on given type or as a global proc +/// Call by name verb references, checks if the verb exists on either this type or as a global verb. +#define VERB_REF(X) (.verb/##X) + +/// Call by name proc reference, checks if the proc exists on either the given type or as a global proc #define TYPE_PROC_REF(TYPE, X) (##TYPE.proc/##X) -/// Call by name proc reference, checks if the proc is existing global proc +/// Call by name verb reference, checks if the verb exists on either the given type or as a global verb +#define TYPE_VERB_REF(TYPE, X) (##TYPE.verb/##X) + +/// Call by name proc reference, checks if the proc is an existing global proc #define GLOBAL_PROC_REF(X) (/proc/##X) + #else -/// Call by name proc reference, checks if the proc exists on this type or as a global proc + +/// Call by name proc references, checks if the proc exists on either this type or as a global proc. #define PROC_REF(X) (nameof(.proc/##X)) -/// Call by name proc reference, checks if the proc exists on given type or as a global proc +/// Call by name verb references, checks if the verb exists on either this type or as a global verb. +#define VERB_REF(X) (nameof(.verb/##X)) + +/// Call by name proc reference, checks if the proc exists on either the given type or as a global proc #define TYPE_PROC_REF(TYPE, X) (nameof(##TYPE.proc/##X)) -/// Call by name proc reference, checks if the proc is existing global proc +/// Call by name verb reference, checks if the verb exists on either the given type or as a global verb +#define TYPE_VERB_REF(TYPE, X) (nameof(##TYPE.verb/##X)) + +/// Call by name proc reference, checks if the proc is an existing global proc #define GLOBAL_PROC_REF(X) (/proc/##X) + #endif // I heard that this was fixed in 1609 (not public currently), but that could be wrong, so keep an eye on this diff --git a/code/modules/client/client_procs.dm b/code/modules/client/client_procs.dm index 334818c0e1f9..557960195e1c 100644 --- a/code/modules/client/client_procs.dm +++ b/code/modules/client/client_procs.dm @@ -1032,7 +1032,7 @@ GLOBAL_LIST_INIT(blacklisted_builds, list( var/mob/living/M = mob M.update_damage_hud() if (prefs.auto_fit_viewport) - addtimer(CALLBACK(src,.verb/fit_viewport,10)) //Delayed to avoid wingets from Login calls. + addtimer(CALLBACK(src, VERB_REF(fit_viewport), 1 SECONDS)) //Delayed to avoid wingets from Login calls. /client/proc/generate_clickcatcher() if(!void)