mirror of
https://github.com/PHIDIAS0303/ExpCluster.git
synced 2025-12-26 19:15:23 +09:00
Add Clusterio Plugins
This commit is contained in:
91
.gitignore
vendored
91
.gitignore
vendored
@@ -1,88 +1,3 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
|
||||
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (http://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules
|
||||
jspm_packages
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# =========================
|
||||
# Operating System Files
|
||||
# =========================
|
||||
|
||||
# OSX
|
||||
# =========================
|
||||
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# IDE
|
||||
.vscode/settings.json
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
# Windows
|
||||
# =========================
|
||||
|
||||
# Windows image file caches
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
|
||||
# Folder config file
|
||||
Desktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
dist/
|
||||
node_modules/
|
||||
package-lock.json
|
||||
|
||||
31
.luacheckrc
31
.luacheckrc
@@ -70,14 +70,6 @@ do -- Assume Factorio Control Stage as Default
|
||||
}
|
||||
end
|
||||
|
||||
do -- RedMew and ExpGaming overrides
|
||||
globals = {
|
||||
'math', 'table',
|
||||
'print', 'require', 'unpack', 'inspect', 'loadstring', 'ServerCommands', 'Debug',
|
||||
'_C', '_DEBUG', '_CHEATS', '_DUMP_ENV', '_LIFECYCLE', '_STAGE',
|
||||
}
|
||||
end
|
||||
|
||||
do -- Set default prototype files
|
||||
files['**/data.lua'].std = STD_DATA
|
||||
files['**/data-updates.lua'].std = STD_DATA
|
||||
@@ -221,7 +213,7 @@ do -- Factorio STDs--
|
||||
fields = {
|
||||
"on_event", "on_nth_tick", "on_configuration_changed", "on_init", "on_load", "generate_event_name",
|
||||
"raise_event", "get_event_handler", "mod_name", "get_event_order",
|
||||
"is_game_in_debug_mode", "object_name", "set_event_filter", "get_event_filter",
|
||||
"is_game_in_debug_mode", "object_name", "set_event_filter", "get_event_filter", "register_metatable",
|
||||
active_mods = {read_only = true, other_fields = true},
|
||||
},
|
||||
other_fields = false,
|
||||
@@ -1026,21 +1018,6 @@ do -- Factorio Defines STDs--
|
||||
'northwest'
|
||||
}
|
||||
},
|
||||
disconnect_reason = {
|
||||
fields = {
|
||||
'quit',
|
||||
'dropped',
|
||||
'reconnect',
|
||||
'wrong_input',
|
||||
'desync_limit_reached',
|
||||
'cannot_keep_up',
|
||||
'afk',
|
||||
'kicked',
|
||||
'kicked_and_deleted',
|
||||
'banned',
|
||||
'switching_servers'
|
||||
}
|
||||
},
|
||||
distraction = {
|
||||
fields = {
|
||||
'by_enemy',
|
||||
@@ -1095,10 +1072,8 @@ do -- Factorio Defines STDs--
|
||||
'on_robot_built_entity',
|
||||
'on_robot_pre_mined',
|
||||
'on_robot_mined',
|
||||
'on_research_cancelled',
|
||||
'on_research_finished',
|
||||
'on_research_reversed',
|
||||
'on_research_started',
|
||||
'on_research_finished',
|
||||
'on_player_rotated_entity',
|
||||
'on_player_set_quickbar_slot',
|
||||
'on_marked_for_deconstruction',
|
||||
@@ -1231,7 +1206,7 @@ do -- Factorio Defines STDs--
|
||||
},
|
||||
flow_precision_index = {
|
||||
fields = {
|
||||
'five_seconds',
|
||||
'one_second',
|
||||
'one_minute',
|
||||
'ten_minutes',
|
||||
'one_hour',
|
||||
|
||||
3
.npmignore
Normal file
3
.npmignore
Normal file
@@ -0,0 +1,3 @@
|
||||
webpack.config.js
|
||||
dist/web/build
|
||||
dist/browser
|
||||
14
CONTRIBUTING.md
Normal file
14
CONTRIBUTING.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Contributing
|
||||
|
||||
All are welcome to make bug reports, feature requests, and pull requests for our scenario. We do not require you to have any coding knowledge to make bug reports and feature requests. If you have any questions ask us in our discord.
|
||||
|
||||
For developers wanting to add features please follow these guidelines:
|
||||
|
||||
- All lua code is documented using ldoc.
|
||||
- Changes should be made on your own fork and merged into `main` through a pull request.
|
||||
- Each pull request should be limited to one feature or a few bug fixes and link to the related issue page.
|
||||
- Pull requests are automatically linted and documentation checked.
|
||||
- Pull requests are manually reviewed to maintain code and language quality.
|
||||
- New features should have the branch names: `feature/feature-name`
|
||||
- Bug fixes should have the branch names: `fix/bug-name`
|
||||
- Commits should have meaningful messages.
|
||||
695
LICENSE
695
LICENSE
@@ -1,674 +1,21 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
Scenario for Facotorio multiplayer.
|
||||
Copyright (C) 2018 badgamernl
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
explosivegaming.nl Copyright (C) 2018 badgamernl
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Explosive Gaming
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
48
README.md
48
README.md
@@ -20,56 +20,36 @@
|
||||
<img src="https://discordapp.com/api/guilds/260843215836545025/widget.png?style=shield" alt="Discord">
|
||||
</a>
|
||||
</p>
|
||||
<h1 align="center">ExpGaming Scenario Repository</h2>
|
||||
<h1 align="center">ExpGaming Clusterio Repository</h2>
|
||||
|
||||
## Explosive Gaming
|
||||
|
||||
Explosive Gaming (often ExpGaming) is a server hosting community with a strong focus on [Factorio][factorio] and games with similar themes. We are best known for our weekly reset Factorio server with a vanilla+ scenario where we add new features and mechanics that are balanced with base game progression. Although our servers tend to attract the more experienced players, our servers are open to everyone. You can find us through our [website], [discord], or the public server list with the name ExpGaming.
|
||||
|
||||
## Use and Installation
|
||||
## Installation
|
||||
|
||||
1) Download our [git repository][experimental-dl] for the latest version. For a stable release you can download from our [stable branch][stable-dl]. See [releases](#releases) for other major releases.
|
||||
This is a plugin collection for [Clustorio](https://github.com/clusterio/clusterio) which provides all our scenario features.
|
||||
|
||||
2) Extract the downloaded zip file into your Factorio scenario directory:
|
||||
* Windows: `%appdata%\Factorio\scenarios`
|
||||
* Linux: `~/.factorio/scenarios`
|
||||
To use this plugin you must already have a clustorio instance running, see [here](https://github.com/clusterio/clusterio?tab=readme-ov-file#installation) for clustorio installation instructions.
|
||||
|
||||
3) Within the scenario you can find `./config/_file_loader.lua` which contains a list of all the modules which will be loaded by the scenario. Comment out (or delete) lines for features you do not want. Be aware modules may load other modules as dependencies even when removed from the list.
|
||||
This module is currently not published and therefore can not be installed via `npm`. Instead follow the steps for [building from source](#building-from-source)
|
||||
|
||||
4) More advanced users can adjust other configs files within `./config` but some files will require a basic understanding of lua.
|
||||
## Building from source
|
||||
|
||||
5) Once you have made your config changes: open Factorio, select either single or multiplayer, select (host) new game, and finally select our scenario which will be called `scenario-stable` or `scenario-dev` under user scenarios.
|
||||
|
||||
6) You will now be asked to generate your map and the scenario will load all selected modules. If any module does not load as expected please check `factorio-current.log` in your Factorio directory for errors and report them on our [issues page][issues].
|
||||
1) Create a `external_plugins` directory within your clustorio instance.
|
||||
2) Clone this repository into that directory: `git clone https://github.com/explosivegaming/ExpCluster`
|
||||
3) Install the package dev dependencies: `pnpm install`
|
||||
4) Add the plugins to your clustorio instance such as: `npx clustorioctl plugin add ./external_plugins/ExpCluster/exp_groups`
|
||||
|
||||
## Contributing
|
||||
|
||||
All are welcome to make bug reports, feature requests, and pull requests for our scenario. We do not require you to have any lua or coding knowledge to make bug reports and feature requests. If you have any questions ask us in our [discord].
|
||||
|
||||
For developers wanting to add features please follow these guidelines:
|
||||
|
||||
* All code is documented using ldoc, the end result can be found [here][docs].
|
||||
* Changes should be made on your own fork and merged into `dev` through a pull request.
|
||||
* Each pull request should be limited to one feature or a few bug fixes.
|
||||
* Pull requests are automatically checked for lint and documentation errors.
|
||||
* Pull requests are manually reviewed to maintain code and language quality.
|
||||
* New features should have the branch names: `feature/feature-name`
|
||||
* Bug fixes should have the branch names: `fix/bug-name`
|
||||
* Commits should have meaningful messages.
|
||||
|
||||
About our versioning and branch structure:
|
||||
|
||||
* Versions track changes to the stable branch and are managed by organisation members.
|
||||
* Versions to not track changes on the dev branch which may contain some critical bugs.
|
||||
* Other branches may exist for alternative version of our scenario, these are not versioned.
|
||||
* Major releases contain significant changes to core modules.
|
||||
* Minor releases contain many new features and bug fixes.
|
||||
* Patch releases are only used for critical bugs.
|
||||
See [Contributing](CONTRIBUTING.md) for how to make pull requests and issues.
|
||||
|
||||
## Releases
|
||||
|
||||
| Release* | Release Name | Factorio Version** |
|
||||
|---|---|---|
|
||||
| [6.4][s6.4] | Farewell Factorio 1.1 | [1.1.110][f1.1.110] |
|
||||
| [6.3][s6.3] | Feature Bundle 2: Electric Boogaloo | [1.1.101][f1.1.101] |
|
||||
| [6.2][s6.2] | Mega Feature Bundle | [1.1.32][f1.1.32] |
|
||||
| [6.1][s6.1] | External Data Overhaul | [1.0.0][f1.0.0] |
|
||||
@@ -95,6 +75,7 @@ About our versioning and branch structure:
|
||||
|
||||
\*\* Factorio versions show the version they were made for, often the minimum requirement to run the scenario.
|
||||
|
||||
[s6.4]: https://github.com/explosivegaming/scenario/releases/tag/6.4.0
|
||||
[s6.3]: https://github.com/explosivegaming/scenario/releases/tag/6.3.0
|
||||
[s6.2]: https://github.com/explosivegaming/scenario/releases/tag/6.2.0
|
||||
[s6.1]: https://github.com/explosivegaming/scenario/releases/tag/6.1.0
|
||||
@@ -116,6 +97,7 @@ About our versioning and branch structure:
|
||||
[s1.0]: https://github.com/explosivegaming/scenario/releases/tag/v1.0
|
||||
[s0.1]: https://github.com/explosivegaming/scenario/releases/tag/v0.1
|
||||
|
||||
[f1.1.110]: https://wiki.factorio.com/Version_history/1.1.0#1.1.110
|
||||
[f1.1.101]: https://wiki.factorio.com/Version_history/1.1.0#1.1.101
|
||||
[f1.1.32]: https://wiki.factorio.com/Version_history/1.1.0#1.1.32
|
||||
[f1.0.0]: https://wiki.factorio.com/Version_history/1.0.0#1.0.0
|
||||
@@ -138,7 +120,7 @@ About our versioning and branch structure:
|
||||
|
||||
## License
|
||||
|
||||
The Explosive Gaming codebase is licensed under the [GNU General Public License v3.0](LICENSE)
|
||||
The Explosive Gaming codebase is licensed under the [MIT](LICENSE)
|
||||
|
||||
[stable-dl]: https://github.com/explosivegaming/scenario/archive/master.zip
|
||||
[experimental-dl]: https://github.com/explosivegaming/scenario/archive/dev.zip
|
||||
|
||||
8
exp_commands/index.ts
Normal file
8
exp_commands/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
export const plugin: lib.PluginDeclaration = {
|
||||
name: "exp_commands",
|
||||
title: "exp_commands",
|
||||
description: "Example Description. Plugin. Change me in index.ts",
|
||||
instanceEntrypoint: "./dist/node/instance",
|
||||
};
|
||||
7
exp_commands/instance.ts
Normal file
7
exp_commands/instance.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { BaseInstancePlugin } from "@clusterio/host";
|
||||
|
||||
export class InstancePlugin extends BaseInstancePlugin {
|
||||
// This class is empty because an instance plugin must be defined for a module to be injected
|
||||
// This requirement may change in the future to allow for standalone modules
|
||||
}
|
||||
179
exp_commands/module/commands/data_types.lua
Normal file
179
exp_commands/module/commands/data_types.lua
Normal file
@@ -0,0 +1,179 @@
|
||||
--[[-- Command Module - Default data types
|
||||
The default data types that are available to all commands
|
||||
|
||||
@usage Adds parsers for:
|
||||
boolean
|
||||
string-options - options: array of strings
|
||||
string-key - map: table of string keys and any values
|
||||
string-max-length - maximum: number
|
||||
number
|
||||
integer
|
||||
number-range - minimum: number, maximum: number
|
||||
integer-range - minimum: number, maximum: number
|
||||
player
|
||||
player-online
|
||||
player-alive
|
||||
force
|
||||
surface
|
||||
color
|
||||
]]
|
||||
|
||||
local ExpUtil = require("modules/exp_util")
|
||||
local Commands = require("modules/exp_commands")
|
||||
local add, parse = Commands.add_data_type, Commands.parse_data_type
|
||||
local valid, invalid = Commands.status.success, Commands.status.invalid_input
|
||||
|
||||
--- A boolean value where true is one of: yes, y, true, 1
|
||||
add("boolean", function(input)
|
||||
input = input:lower()
|
||||
if input == "yes"
|
||||
or input == "y"
|
||||
or input == "true"
|
||||
or input == "1" then
|
||||
return valid(true)
|
||||
else
|
||||
return valid(false)
|
||||
end
|
||||
end)
|
||||
|
||||
--- A string, validation does nothing but it is a requirement
|
||||
add("string", function(input)
|
||||
return valid(input)
|
||||
end)
|
||||
|
||||
--- A string from a set of options, takes one argument which is an array of options
|
||||
add("string-options", function(input, _, options)
|
||||
local option = ExpUtil.auto_complete(options, input)
|
||||
if option == nil then
|
||||
return invalid{"exp-commands-parse.string-options", table.concat(options, ", ")}
|
||||
else
|
||||
return valid(option)
|
||||
end
|
||||
end)
|
||||
|
||||
--- A string which is the key of a table, takes one argument which is an map of string keys to values
|
||||
add("string-key", function(input, _, map)
|
||||
local option = ExpUtil.auto_complete(map, input, true)
|
||||
if option == nil then
|
||||
return invalid{"exp-commands-parse.string-options", table.concat(table.get_keys(map), ", ")}
|
||||
else
|
||||
return valid(option)
|
||||
end
|
||||
end)
|
||||
|
||||
--- A string with a maximum length, takes one argument which is the maximum length of a string
|
||||
add("string-max-length", function(input, _, maximum)
|
||||
if input:len() > maximum then
|
||||
return invalid{"exp-commands-parse.string-max-length", maximum}
|
||||
else
|
||||
return valid(input)
|
||||
end
|
||||
end)
|
||||
|
||||
--- A number
|
||||
add("number", function(input)
|
||||
local number = tonumber(input)
|
||||
if number == nil then
|
||||
return invalid{"exp-commands-parse.number"}
|
||||
else
|
||||
return valid(number)
|
||||
end
|
||||
end)
|
||||
|
||||
--- An integer, number which has been floored
|
||||
add("integer", function(input)
|
||||
local number = tonumber(input)
|
||||
if number == nil then
|
||||
return invalid{"exp-commands-parse.number"}
|
||||
else
|
||||
return valid(math.floor(number))
|
||||
end
|
||||
end)
|
||||
|
||||
--- A number in a given inclusive range
|
||||
add("number-range", function(input, _, minimum, maximum)
|
||||
local success, status, number = parse("number", input)
|
||||
if not success then
|
||||
return status, number
|
||||
elseif number < minimum or number > maximum then
|
||||
return invalid{"exp-commands-parse.number-range", minimum, maximum}
|
||||
else
|
||||
return valid(number)
|
||||
end
|
||||
end)
|
||||
|
||||
--- An integer in a given inclusive range
|
||||
add("integer-range", function(input, _, minimum, maximum)
|
||||
local success, status, number = parse("integer", input)
|
||||
if not success then
|
||||
return status, number
|
||||
elseif number < minimum or number > maximum then
|
||||
return invalid{"exp-commands-parse.number-range", minimum, maximum}
|
||||
else
|
||||
return valid(number)
|
||||
end
|
||||
end)
|
||||
|
||||
--- A player who has joined the game at least once
|
||||
add("player", function(input)
|
||||
local player = game.get_player(input)
|
||||
if player == nil then
|
||||
return invalid{"exp-commands-parse.player", input}
|
||||
else
|
||||
return valid(player)
|
||||
end
|
||||
end)
|
||||
|
||||
--- A player who is online
|
||||
add("player-online", function(input)
|
||||
local success, status, player = parse("player", input)
|
||||
if not success then
|
||||
return status, player
|
||||
elseif player.connected == false then
|
||||
return invalid{"exp-commands-parse.player-online"}
|
||||
else
|
||||
return valid(player)
|
||||
end
|
||||
end)
|
||||
|
||||
--- A player who is online and alive
|
||||
add("player-alive", function(input)
|
||||
local success, status, player = parse("player-online", input)
|
||||
if not success then
|
||||
return status, player
|
||||
elseif player.character == nil or player.character.health <= 0 then
|
||||
return invalid{"exp-commands-parse.player-alive"}
|
||||
else
|
||||
return valid(player)
|
||||
end
|
||||
end)
|
||||
|
||||
--- A force within the game
|
||||
add("force", function(input)
|
||||
local force = game.forces[input]
|
||||
if force == nil then
|
||||
return invalid{"exp-commands-parse.force"}
|
||||
else
|
||||
return valid(force)
|
||||
end
|
||||
end)
|
||||
|
||||
--- A surface within the game
|
||||
add("surface", function(input)
|
||||
local surface = game.surfaces[input]
|
||||
if surface == nil then
|
||||
return invalid{"exp-commands-parse.surface"}
|
||||
else
|
||||
return valid(surface)
|
||||
end
|
||||
end)
|
||||
|
||||
--- A name of a color from the predefined list, too many colours to use string-key
|
||||
add("color", function(input)
|
||||
local color = ExpUtil.auto_complete(Commands.color, input, true)
|
||||
if color == nil then
|
||||
return invalid{"exp-commands-parse.color"}
|
||||
else
|
||||
return valid(color)
|
||||
end
|
||||
end)
|
||||
81
exp_commands/module/commands/help.lua
Normal file
81
exp_commands/module/commands/help.lua
Normal file
@@ -0,0 +1,81 @@
|
||||
--[[-- Command Module - Help
|
||||
Game command to list and search all registered commands in a nice format
|
||||
@commands _system-ipc
|
||||
|
||||
@usage-- Get all messages related to banning a player
|
||||
/commands ban
|
||||
-- Get the second page of results
|
||||
/commands ban 2
|
||||
]]
|
||||
|
||||
local Global = require("modules/exp_util/global")
|
||||
local Commands = require("modules/exp_commands")
|
||||
|
||||
local PAGE_SIZE = 5
|
||||
|
||||
local search_cache = {}
|
||||
Global.register(search_cache, function(tbl)
|
||||
search_cache = tbl
|
||||
end)
|
||||
|
||||
--- Format commands into a strings across multiple pages
|
||||
local function format_as_pages(commands, page_size)
|
||||
local pages = { {} }
|
||||
local page_length = 0
|
||||
local current_page = 1
|
||||
local total = 0
|
||||
|
||||
for _, command in pairs(commands) do
|
||||
total = total + 1
|
||||
page_length = page_length + 1
|
||||
if page_length > page_size then
|
||||
current_page = current_page + 1
|
||||
pages[current_page] = {}
|
||||
page_length = 1
|
||||
end
|
||||
|
||||
local aliases = #command.aliases > 0 and {"exp-commands-help.aliases", table.concat(command.aliases, ", ")} or ""
|
||||
pages[current_page][page_length] = { "exp-commands-help.format", command.name, command.description, command.help, aliases }
|
||||
end
|
||||
|
||||
return pages, total
|
||||
end
|
||||
|
||||
Commands.new("commands", "List and search all commands for a keyword")
|
||||
:add_aliases{ "chelp", "helpp" }
|
||||
:argument("keyword", "string")
|
||||
:optional("page", "integer")
|
||||
:defaults{ page = 1 }
|
||||
:register(function(player, keyword, page)
|
||||
keyword = keyword:lower()
|
||||
local pages, found
|
||||
local cache = search_cache[player.index]
|
||||
if cache and cache.keyword == keyword then
|
||||
-- Cached value found, no search is needed
|
||||
pages = cache.pages
|
||||
found = cache.found
|
||||
else
|
||||
-- No cached value, so a search needs to be done
|
||||
local commands = Commands.search_for_player(keyword, player)
|
||||
pages, found = format_as_pages(commands, PAGE_SIZE)
|
||||
search_cache[player.index] = { keyword = keyword, pages = pages, found = found }
|
||||
end
|
||||
|
||||
-- Error if no pages found
|
||||
if found == 0 then
|
||||
return Commands.status.success{ "exp-commands-help.no-results" }
|
||||
end
|
||||
|
||||
local page_data = pages[page]
|
||||
if page_data == nil then
|
||||
-- Page number was out of range for this search
|
||||
return Commands.status.invalid_input{"exp-commands-help.out-of-range", page, #pages }
|
||||
end
|
||||
|
||||
-- Print selected page to the player
|
||||
Commands.print{ "exp-commands-help.header", keyword == '' and '<all>' or keyword }
|
||||
for _, command in pairs(page_data) do
|
||||
Commands.print(command)
|
||||
end
|
||||
return Commands.status.success{ "exp-commands-help.footer", found, page, #pages }
|
||||
end)
|
||||
25
exp_commands/module/commands/ipc.lua
Normal file
25
exp_commands/module/commands/ipc.lua
Normal file
@@ -0,0 +1,25 @@
|
||||
--[[-- Command Module - IPC
|
||||
System command which sends an object to the clustorio api, should be used for debugging / echo commands
|
||||
@commands _system-ipc
|
||||
|
||||
@usage-- Send a message on your custom channel, message is a json string
|
||||
/_ipc myChannel { "myProperty": "foo", "playerName": "Cooldude2606" }
|
||||
]]
|
||||
|
||||
local Commands = require("modules/exp_commands")
|
||||
local Clustorio = require("modules/clusterio/api")
|
||||
|
||||
Commands.new("_ipc", "Send an IPC message on the selected channel")
|
||||
:add_flags{ "system_only" }
|
||||
:enable_auto_concatenation()
|
||||
:argument("channel", "string")
|
||||
:argument("message", "string")
|
||||
:register(function(_, channel, message)
|
||||
local tbl = game.json_to_table(message)
|
||||
if tbl == nil then
|
||||
return Commands.status.invalid_input("Invalid json string")
|
||||
else
|
||||
Clustorio.send_json(channel, tbl)
|
||||
return Commands.status.success()
|
||||
end
|
||||
end)
|
||||
91
exp_commands/module/commands/permission_authorities.lua
Normal file
91
exp_commands/module/commands/permission_authorities.lua
Normal file
@@ -0,0 +1,91 @@
|
||||
--[[-- Command Module - Default permission authorities
|
||||
The default permission authorities controlled by the flags: admin_only, system_only, no_rcon, disabled
|
||||
|
||||
@usage-- Unlock system commands for debugging purposes
|
||||
/c require("modules/exp-commands").unlock_system_commands(game.player)
|
||||
|
||||
@usage-- Disable a command for all players because it is not functioning correctly
|
||||
/c require("modules/exp-commands").disable("my-command")
|
||||
]]
|
||||
|
||||
local Global = require("modules/exp_util/global")
|
||||
local Commands = require("modules/exp_commands")
|
||||
local add, allow, deny = Commands.add_permission_authority, Commands.status.success, Commands.status.unauthorised
|
||||
|
||||
local permission_authorities = {}
|
||||
|
||||
local system_players = {}
|
||||
local disabled_commands = {}
|
||||
Global.register({
|
||||
system_players,
|
||||
disabled_commands,
|
||||
}, function(tbl)
|
||||
system_players = tbl[1]
|
||||
disabled_commands = tbl[2]
|
||||
end)
|
||||
|
||||
--- Allow a player access to system commands, use for debug purposes only
|
||||
-- @tparam[opt] string player_name The name of the player to give access to, default is the current player
|
||||
function Commands.unlock_system_commands(player_name)
|
||||
system_players[player_name or game.player.name] = true
|
||||
end
|
||||
|
||||
--- Remove access from system commands for a player, use for debug purposes only
|
||||
-- @tparam[opt] string player_name The name of the player to give access to, default is the current player
|
||||
function Commands.lock_system_commands(player_name)
|
||||
system_players[player_name or game.player.name] = nil
|
||||
end
|
||||
|
||||
--- Get a list of all players who have system commands unlocked
|
||||
function Commands.get_system_command_players()
|
||||
return table.get_keys(system_players)
|
||||
end
|
||||
|
||||
--- Stops a command from be used by any one
|
||||
-- @tparam string command_name The name of the command to disable
|
||||
function Commands.disable(command_name)
|
||||
disabled_commands[command_name] = true
|
||||
end
|
||||
|
||||
--- Allows a command to be used again after disable was used
|
||||
-- @tparam string command_name The name of the command to enable
|
||||
function Commands.enable(command_name)
|
||||
disabled_commands[command_name] = nil
|
||||
end
|
||||
|
||||
--- Get a list of all players who have system commands unlocked
|
||||
function Commands.get_disabled_commands()
|
||||
return table.get_keys(disabled_commands)
|
||||
end
|
||||
|
||||
--- If a command has the flag "admin_only" then only admins can use the command#
|
||||
permission_authorities.admin_only =
|
||||
add(function(player, command)
|
||||
if command.flags.admin_only and not player.admin then
|
||||
return deny{"exp-commands-permissions.admin-only"}
|
||||
else
|
||||
return allow()
|
||||
end
|
||||
end)
|
||||
|
||||
--- If a command has the flag "system_only" then only rcon connections can use the command
|
||||
permission_authorities.system_only =
|
||||
add(function(player, command)
|
||||
if command.flags.system_only and not system_players[player.name] then
|
||||
return deny{"exp-commands-permissions.system-only"}
|
||||
else
|
||||
return allow()
|
||||
end
|
||||
end)
|
||||
|
||||
--- If Commands.disable was called then no one can use the command
|
||||
permission_authorities.disabled =
|
||||
add(function(_, command)
|
||||
if disabled_commands[command.name] then
|
||||
return deny{"exp-commands-permissions.disabled"}
|
||||
else
|
||||
return allow()
|
||||
end
|
||||
end)
|
||||
|
||||
return permission_authorities
|
||||
82
exp_commands/module/commands/rcon.lua
Normal file
82
exp_commands/module/commands/rcon.lua
Normal file
@@ -0,0 +1,82 @@
|
||||
--[[-- Command Module - Rcon
|
||||
System command which runs arbitrary code within a custom (not sandboxed) environment
|
||||
@commands _system-rcon
|
||||
|
||||
@usage-- Get the names of all online players, using rcon
|
||||
/_system-rcon local names = {}; for index, player in pairs(game.connected_player) do names[index] = player.name end; return names;
|
||||
|
||||
@usage-- Get the names of all online players, using clustorio ipcs
|
||||
/_system-rcon local names = {}; for index, player in pairs(game.connected_player) do names[index] = player.name end; ipc("online-players", names);
|
||||
]]
|
||||
|
||||
local ExpUtil = require("modules/exp_util")
|
||||
local Async = require("modules/exp_util/async")
|
||||
local Global = require("modules/exp_util/global")
|
||||
local Commands = require("modules/exp_commands")
|
||||
local Clustorio = require("modules/clusterio/api")
|
||||
|
||||
local rcon_env = {}
|
||||
local rcon_statics = {}
|
||||
local rcon_callbacks = {}
|
||||
setmetatable(rcon_statics, { __index = _G })
|
||||
setmetatable(rcon_env, { __index = rcon_statics })
|
||||
|
||||
--- Some common static values which can be added now
|
||||
rcon_statics.Async = Async
|
||||
rcon_statics.ExpUtil = ExpUtil
|
||||
rcon_statics.Commands = Commands
|
||||
rcon_statics.Clustorio = Clustorio
|
||||
rcon_statics.output = Commands.print
|
||||
rcon_statics.ipc = Clustorio.send_json
|
||||
|
||||
--- Some common callback values which are useful when a player uses the command
|
||||
function rcon_callbacks.player(player) return player end
|
||||
function rcon_callbacks.surface(player) return player and player.surface end
|
||||
function rcon_callbacks.force(player) return player and player.force end
|
||||
function rcon_callbacks.position(player) return player and player.position end
|
||||
function rcon_callbacks.entity(player) return player and player.selected end
|
||||
function rcon_callbacks.tile(player) return player and player.surface.get_tile(player.position) end
|
||||
|
||||
--- The rcon env is saved between command runs to prevent desyncs
|
||||
Global.register(rcon_env, function(tbl)
|
||||
rcon_env = setmetatable(tbl, { __index = rcon_statics })
|
||||
end)
|
||||
|
||||
--- Static values can be added to the rcon env which are not stored in global such as modules
|
||||
function Commands.add_rcon_static(name, value)
|
||||
ExpUtil.assert_not_runtime()
|
||||
rcon_statics[name] = value
|
||||
end
|
||||
|
||||
--- Callback values can be added to the rcon env, these are called on each invocation and should return one value
|
||||
function Commands.add_rcon_callback(name, callback)
|
||||
ExpUtil.assert_not_runtime()
|
||||
rcon_callbacks[name] = callback
|
||||
end
|
||||
|
||||
Commands.new("_rcon", "Execute arbitrary code within a custom environment")
|
||||
:add_flags{ "system_only" }
|
||||
:enable_auto_concatenation()
|
||||
:argument("invocation", "string")
|
||||
:register(function(player, invocation_string)
|
||||
-- Construct the environment the command will run within
|
||||
local env = setmetatable({}, { __index = rcon_env, __newindex = rcon_env })
|
||||
for name, callback in pairs(rcon_callbacks) do
|
||||
local _, rtn = pcall(callback, player.index > 0 and player or nil)
|
||||
rawset(env, name, rtn)
|
||||
end
|
||||
|
||||
-- Compile and run the invocation string
|
||||
local invocation, compile_error = load(invocation_string, "rcon-invocation", "t", env)
|
||||
if compile_error then
|
||||
return Commands.status.invalid_input(compile_error)
|
||||
else
|
||||
local success, rtn = xpcall(invocation, debug.traceback)
|
||||
if success == false then
|
||||
local err = rtn:gsub('%.%.%..-/temp/currently%-playing/', '')
|
||||
return Commands.status.error(err)
|
||||
else
|
||||
return Commands.status.success(rtn)
|
||||
end
|
||||
end
|
||||
end)
|
||||
25
exp_commands/module/commands/sudo.lua
Normal file
25
exp_commands/module/commands/sudo.lua
Normal file
@@ -0,0 +1,25 @@
|
||||
--[[-- Command Module - Sudo
|
||||
System command to execute a command as another player using their permissions (except for permissions group actions)
|
||||
@commands _system-sudo
|
||||
|
||||
@usage-- Run the example command as another player
|
||||
-- As Cooldude2606: /repeat 5
|
||||
/_system-sudo Cooldude2606 repeat 5
|
||||
]]
|
||||
|
||||
local Commands = require("modules/exp_commands")
|
||||
|
||||
Commands.new("_sudo", "Run a command as another player")
|
||||
:add_flags{ "system_only" }
|
||||
:enable_auto_concatenation()
|
||||
:argument("player", "player")
|
||||
:argument("command", "string-key", Commands.registered_commands)
|
||||
:argument("arguments", "string")
|
||||
:register(function(_, player, command, parameter)
|
||||
return Commands._event_handler{
|
||||
name = command.name,
|
||||
tick = game.tick,
|
||||
player_index = player.index,
|
||||
parameter = parameter
|
||||
}
|
||||
end)
|
||||
38
exp_commands/module/locale/en.cfg
Normal file
38
exp_commands/module/locale/en.cfg
Normal file
@@ -0,0 +1,38 @@
|
||||
color-tag=[color=__1__]__2__[/color]
|
||||
|
||||
[exp-commands]
|
||||
command-help=__1__ - __2__
|
||||
success=Command Complete.
|
||||
error=Command failed to run: __1__
|
||||
error-default=Please check you gave the correct arguments.
|
||||
unauthorized=Unauthorized: __1__
|
||||
unauthorized-default=Access is denied due to insufficient permissions.
|
||||
invalid-usage=Wrong number of arguments, usage: /__1__ __2__
|
||||
invalid-input=Invalid input: Please ensure everything is formated correctly.
|
||||
invalid-argument=Invalid argument "__1__"; __2__
|
||||
internal-error=Internal Error, Please contact an admin: __1__
|
||||
|
||||
[exp-commands-parse]
|
||||
string-options=Invalid Option, Must be one of: __1__
|
||||
string-max-length=Invalid Length, Max: __1__
|
||||
number=Invalid Number.
|
||||
number-range=Invalid Range, Min (inclusive): __1__, Max (inclusive): __2__
|
||||
player=Invalid Player Name, __1__ ,try using tab key to auto-complete the name
|
||||
player-online=Player is offline.
|
||||
player-alive=Player is dead.
|
||||
force=Invalid Force Name.
|
||||
surface=Invalid Surface Name.
|
||||
color=Invalid Color Name.
|
||||
|
||||
[exp-commands-permissions]
|
||||
admin-only=This command is for game admins only.
|
||||
system-only=This command can not be ran by players.
|
||||
disabled=This command is currently disabled.
|
||||
|
||||
[exp-commands-help]
|
||||
header=Help results for "__1__":
|
||||
footer=[__1__ results found: page __2__ of __3__]
|
||||
format=/__1__ __2__ - __3__ __4__
|
||||
aliases=Aliaies: __1__
|
||||
out-of-range=__1__ is an invalid page number. Last page: __2__
|
||||
no-results=No commands were found
|
||||
15
exp_commands/module/module.json
Normal file
15
exp_commands/module/module.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "exp_commands",
|
||||
"require": [
|
||||
"commands/data_types.lua",
|
||||
"commands/permission_authorities.lua",
|
||||
"commands/help.lua",
|
||||
"commands/rcon.lua",
|
||||
"commands/sudo.lua",
|
||||
"commands/ipc.lua"
|
||||
],
|
||||
"dependencies": {
|
||||
"clusterio": "*",
|
||||
"exp_util": "*"
|
||||
}
|
||||
}
|
||||
686
exp_commands/module/module_exports.lua
Normal file
686
exp_commands/module/module_exports.lua
Normal file
@@ -0,0 +1,686 @@
|
||||
--[[-- Core Module - Commands
|
||||
- Factorio command making module that makes commands with better parse and more modularity
|
||||
@core Commands
|
||||
@alias Commands
|
||||
|
||||
@usage-- Adding a permission authority
|
||||
-- You are only required to return a boolean, but by using the unauthorised status you can provide better feedback to the user
|
||||
Commands.add_permission_authority(function(player, command)
|
||||
if command.flags.admin_only and not player.admin then
|
||||
return Commands.status.unauthorised("This command requires in-game admin")
|
||||
end
|
||||
return Commands.status.success()
|
||||
end)
|
||||
|
||||
@usage-- Adding a data type
|
||||
-- You can not return nil from this function, doing so will raise an error, you must return a status
|
||||
Commands.add_data_type("integer", function(input, player)
|
||||
local number = tonumber(input)
|
||||
if number == nil then
|
||||
return Commands.status.invalid_input("Value must be a valid number")
|
||||
else
|
||||
return Commands.status.success(number)
|
||||
end
|
||||
end)
|
||||
|
||||
-- It is recommend to use exiting parsers within your own to simplify checks, but make sure to propagate failures
|
||||
Commands.add_data_type("integer-range", function(input, player, minimum, maximum)
|
||||
local success, status, integer = Commands.parse_data_type("integer", input, player)
|
||||
if not success then return status, number end
|
||||
|
||||
if integer < minimum or integer > maximum then
|
||||
return Commands.status.invalid_input(string.format("Integer must be in range: %d to %d", minimum, maximum))
|
||||
else
|
||||
return Commands.status.success(integer)
|
||||
end
|
||||
end)
|
||||
|
||||
@usage-- Adding a command
|
||||
Commands.new("repeat", "This is my new command, it will repeat a message a number of times")
|
||||
:add_flags{ "admin_only" } -- Using the permission authority above, this makes the command admin only
|
||||
:add_aliases{ "repeat-message" } -- You can add as many aliases as you want
|
||||
:enable_auto_concatenation() -- This allows the final argument to be any length
|
||||
:argument("count", "integer-range", 1, 10) -- Allow any value between 1 and 10
|
||||
:optional("message", "string") -- This is an optional argument
|
||||
:defaults{
|
||||
-- Defaults don't need to be functions, one is used here to demonstrate their use, remember player can be nil for the server
|
||||
message = function(player)
|
||||
return player and "Hello, "..player.name or "Hello, World!"
|
||||
end
|
||||
}
|
||||
:register(function(player, count, message)
|
||||
for i = 1, count do
|
||||
Commands.print("#"..i.." "..message)
|
||||
end
|
||||
end)
|
||||
|
||||
]]
|
||||
|
||||
local ExpUtil = require("modules/exp_util")
|
||||
local Color = require("modules/exp_util/include/color")
|
||||
|
||||
local Commands = {
|
||||
color = Color, -- A useful reference to the color utils to be used with command outputs
|
||||
_prototype = {}, -- Contains the methods for the command object
|
||||
registered_commands = {}, -- Stores a reference to all registered commands
|
||||
permission_authorities = {}, -- Stores a reference to all active permission authorities
|
||||
data_types = {}, -- Stores all input parsers and validators for different data types
|
||||
status = {}, -- Contains the different status values a command can return
|
||||
}
|
||||
|
||||
Commands._metatable = {
|
||||
__index = Commands._prototype,
|
||||
__class = "ExpCommand"
|
||||
}
|
||||
|
||||
Commands.player_server = setmetatable({
|
||||
index = 0,
|
||||
color = Color.white,
|
||||
chat_color = Color.white,
|
||||
name = "<server>",
|
||||
tag = "",
|
||||
connected = true,
|
||||
admin = true,
|
||||
afk_time = 0,
|
||||
online_time = 0,
|
||||
last_online = 0,
|
||||
spectator = true,
|
||||
show_on_map = false,
|
||||
valid = true,
|
||||
object_name = "LuaPlayer"
|
||||
}, {
|
||||
__index = function(_, key)
|
||||
if key == "__self" or type(key) == "number" then return nil end
|
||||
Commands.error("Command does not support rcon usage, requires reading player." .. key)
|
||||
error("Command does not support rcon usage, requires reading player." .. key)
|
||||
end,
|
||||
__newindex = function(_, key)
|
||||
Commands.error("Command does not support rcon usage, requires reading player." .. key)
|
||||
error("Command does not support rcon usage, requires setting player." .. key)
|
||||
end
|
||||
})
|
||||
|
||||
--- Status Returns.
|
||||
-- Return values used by command callbacks
|
||||
-- @section command-status
|
||||
|
||||
--- Used to signal success from a command, data type parser, or permission authority
|
||||
-- @tparam[opt] LocaleString|string msg An optional message to be included when a command completes (only has an effect in command callbacks)
|
||||
function Commands.status.success(msg)
|
||||
return Commands.status.success, msg or {'exp-commands.success'}
|
||||
end
|
||||
|
||||
--- Used to signal an error has occurred in a command, data type parser, or permission authority
|
||||
-- For data type parsers and permission authority, an error return will prevent the command from being executed
|
||||
-- @tparam[opt] LocaleString|string msg An optional error message to be included in the output, a generic message is used if not provided
|
||||
function Commands.status.error(msg)
|
||||
return Commands.status.error, {'exp-commands.error', msg or {'exp-commands.error-default'}}
|
||||
end
|
||||
|
||||
--- Used to signal the player is unauthorised to use a command, primarily used by permission authorities but can be used in a command callback
|
||||
-- For permission authorities, an error return will prevent the command from being executed
|
||||
-- @tparam[opt] LocaleString|string msg An optional error message to be included in the output, a generic message is used if not provided
|
||||
function Commands.status.unauthorised(msg)
|
||||
return Commands.status.unauthorised, msg or {'exp-commands.unauthorized', msg or {'exp-commands.unauthorized-default'}}
|
||||
end
|
||||
|
||||
--- Used to signal the player provided invalid input to an command, primarily used by data type parsers but can be used in a command callback
|
||||
-- For data type parsers, an error return will prevent the command from being executed
|
||||
-- @tparam[opt] LocaleString|string msg An optional error message to be included in the output, a generic message is used if not provided
|
||||
function Commands.status.invalid_input(msg)
|
||||
return Commands.status.invalid_input, msg or {'exp-commands.invalid-input'}
|
||||
end
|
||||
|
||||
--- Used to signal an internal error has occurred, this is reserved for internal use
|
||||
-- @tparam LocaleString|string msg A message detailing the error which has occurred, will be logged and outputted
|
||||
function Commands.status.internal_error(msg)
|
||||
return Commands.status.internal_error, {'exp-commands.internal-error', msg}
|
||||
end
|
||||
|
||||
local valid_command_status = {} -- Hashmap lookup for testing if a status is valid
|
||||
for name, status in pairs(Commands.status) do
|
||||
valid_command_status[status] = name
|
||||
end
|
||||
|
||||
--- Permission Authority.
|
||||
-- Functions that control who can use commands
|
||||
-- @section permission-authority
|
||||
|
||||
--- Add a permission authority, a permission authority is a function which provides access control for commands, multiple can be active at once
|
||||
-- When multiple are active, all authorities must give permission for the command to execute, if any deny access then the command is not ran
|
||||
-- @tparam function permission_authority The function to provide access control to commands, see module usage.
|
||||
-- @treturn function The function which was provided as the first argument
|
||||
function Commands.add_permission_authority(permission_authority)
|
||||
local next_index = #Commands.permission_authorities + 1
|
||||
Commands.permission_authorities[next_index] = permission_authority
|
||||
return permission_authority
|
||||
end
|
||||
|
||||
--- Remove a permission authority, must be the same function reference which was passed to add_permission_authority
|
||||
-- @tparam function permission_authority The access control function to remove as a permission authority
|
||||
function Commands.remove_permission_authority(permission_authority)
|
||||
local pms = Commands.permission_authorities
|
||||
for index, value in pairs(pms) do
|
||||
if value == permission_authority then
|
||||
local last = #pms
|
||||
pms[index] = pms[last]
|
||||
pms[last] = nil
|
||||
return
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Check if a player has permission to use a command, calling all permission authorities
|
||||
-- @tparam LuaPlayer player The player to test the permission of, nil represents the server and always returns true
|
||||
-- @tparam Command command The command the player is attempting to use
|
||||
-- @treturn boolean true if the player has permission to use the command
|
||||
-- @treturn LocaleString|string when permission is denied, this is the reason permission was denied
|
||||
function Commands.player_has_permission(player, command)
|
||||
if player == nil or player == Commands.player_server then return true end
|
||||
|
||||
for _, permission_authority in ipairs(Commands.permission_authorities) do
|
||||
local status, msg = permission_authority(player, command)
|
||||
if type(status) == "boolean" then
|
||||
if status == false then
|
||||
local _, rtn_msg = Commands.status.unauthorised(msg)
|
||||
return false, rtn_msg
|
||||
end
|
||||
elseif valid_command_status[status] then
|
||||
if status ~= Commands.status.success then
|
||||
return false, msg
|
||||
end
|
||||
else
|
||||
return false, "Permission authority returned unexpected value"
|
||||
end
|
||||
end
|
||||
|
||||
return true, nil
|
||||
end
|
||||
|
||||
--- Data Type Parsing.
|
||||
-- Functions that parse and validate player input
|
||||
-- @section input-parse-and-validation
|
||||
|
||||
--- Add a new input parser to the command library, this allows use of a data type without needing to pass the function directly
|
||||
-- @tparam string data_type The name of the data type the input parser reads in and validates
|
||||
-- @tparam function parser The function used to parse and validate the data type
|
||||
-- @treturn string The data type passed as the first argument
|
||||
function Commands.add_data_type(data_type, parser)
|
||||
if Commands.data_types[data_type] then
|
||||
error("Data type \""..tostring(data_type).."\" already has a parser registered", 2)
|
||||
end
|
||||
Commands.data_types[data_type] = parser
|
||||
return data_type
|
||||
end
|
||||
|
||||
--- Remove an input parser for a data type, must be the same string that was passed to add_input_parser
|
||||
-- @tparam string data_type The data type for which you want to remove the input parser of
|
||||
function Commands.remove_data_type(data_type)
|
||||
Commands.data_types[data_type] = nil
|
||||
end
|
||||
|
||||
--- Parse and validate an input string as a given data type
|
||||
-- @tparam string|function data_type The name of the data type parser to use to read and validate the input text
|
||||
-- @tparam string input The input string that will be read by the parser
|
||||
-- @param ... Any other arguments that the parser is expecting
|
||||
-- @treturn boolean true when the input was successfully parsed and validated to be the correct type
|
||||
-- @return When The error status for why parsing failed, otherwise it is the parsed value
|
||||
-- @return When first is false, this is the error message, otherwise this is the parsed value
|
||||
function Commands.parse_data_type(data_type, input, ...)
|
||||
local parser = Commands.data_types[data_type]
|
||||
if type(data_type) == "function" then
|
||||
parser = data_type
|
||||
elseif parser == nil then
|
||||
return false, Commands.status.internal_error, {"exp-commands.internal-error" , "Data type \""..tostring(data_type).."\" does not have a registered parser"}
|
||||
end
|
||||
|
||||
local status, parsed = parser(input, ...)
|
||||
if status == nil then
|
||||
return Commands.status.internal_error, {"exp-commands.internal-error" , "Parser for data type \""..tostring(data_type).."\" returned a nil value"}
|
||||
elseif valid_command_status[status] then
|
||||
if status ~= Commands.status.success then
|
||||
return false, status, parsed -- error_type, error_msg
|
||||
else
|
||||
return true, status, parsed -- success, parsed_data
|
||||
end
|
||||
else
|
||||
return true, Commands.status.success, status -- success, parsed_data
|
||||
end
|
||||
end
|
||||
|
||||
--- List and Search
|
||||
-- Functions used to list and search for commands
|
||||
-- @section list-and-search
|
||||
|
||||
--- Returns a list of all registered custom commands
|
||||
-- @treturn table An array of registered commands
|
||||
function Commands.list_all()
|
||||
return Commands.registered_commands
|
||||
end
|
||||
|
||||
--- Returns a list of all registered custom commands which the given player has permission to use
|
||||
-- @treturn table An array of registered commands
|
||||
function Commands.list_for_player(player)
|
||||
local rtn = {}
|
||||
|
||||
for name, command in pairs(Commands.registered_commands) do
|
||||
if Commands.player_has_permission(player, command) then
|
||||
rtn[name] = command
|
||||
end
|
||||
end
|
||||
|
||||
return rtn
|
||||
end
|
||||
|
||||
--- Searches all game commands and the provided custom commands for the given keyword
|
||||
local function search_commands(keyword, custom_commands)
|
||||
keyword = keyword:lower()
|
||||
local rtn = {}
|
||||
|
||||
-- Search all custom commands
|
||||
for name, command in pairs(custom_commands) do
|
||||
local search = string.format('%s %s %s', name, command.help, table.concat(command.aliases, ' '))
|
||||
if search:lower():match(keyword) then
|
||||
rtn[name] = command
|
||||
end
|
||||
end
|
||||
|
||||
-- Search all game commands
|
||||
for name, description in pairs(commands.game_commands) do
|
||||
local search = string.format('%s %s', name, description)
|
||||
if search:lower():match(keyword) then
|
||||
rtn[name] = {
|
||||
name = name,
|
||||
help = description,
|
||||
description = "",
|
||||
aliases = {}
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
return rtn
|
||||
end
|
||||
|
||||
--- Searches all custom commands and game commands for the given keyword
|
||||
-- @treturn table An array of registered commands
|
||||
function Commands.search_all(keyword)
|
||||
return search_commands(keyword, Commands.list_all())
|
||||
end
|
||||
|
||||
--- Searches custom commands allowed for this player and all game commands for the given keyword
|
||||
-- @treturn table An array of registered commands
|
||||
function Commands.search_for_player(keyword, player)
|
||||
return search_commands(keyword, Commands.list_for_player(player))
|
||||
end
|
||||
|
||||
--- Command Output
|
||||
-- Prints output to the player or rcon connection
|
||||
-- @section player-print
|
||||
|
||||
--- Set the color of a message using rich text chat
|
||||
-- @tparam string message The message to set the color of
|
||||
-- @tparam Color color The color that the message should be
|
||||
-- @treturn string The string which can be printed to game chat
|
||||
function Commands.set_chat_message_color(message, color)
|
||||
local color_tag = math.round(color.r, 3)..', '..math.round(color.g, 3)..', '..math.round(color.b, 3)
|
||||
return string.format('[color=%s]%s[/color]', color_tag, message)
|
||||
end
|
||||
|
||||
--- Set the color of a locale message using rich text chat
|
||||
-- @tparam LocaleString message The message to set the color of
|
||||
-- @tparam Color color The color that the message should be
|
||||
-- @treturn LocaleString The locale string which can be printed to game chat
|
||||
function Commands.set_locale_chat_message_color(message, color)
|
||||
local color_tag = math.round(color.r, 3)..', '..math.round(color.g, 3)..', '..math.round(color.b, 3)
|
||||
return {'color-tag', color_tag, message}
|
||||
end
|
||||
|
||||
--- Get a string representing the name of the given player in their chat colour
|
||||
-- @tparam LuaPlayer player The player to use the name and color of, nil represents the server
|
||||
-- @treturn string The players name formatted as a string in their chat color
|
||||
function Commands.format_player_name(player)
|
||||
local player_name = player and player.name or "<server>"
|
||||
local player_color = player and player.chat_color or Color.white
|
||||
local color_tag = math.round(player_color.r, 3)..', '..math.round(player_color.g, 3)..', '..math.round(player_color.b, 3)
|
||||
return string.format('[color=%s]%s[/color]', color_tag, player_name)
|
||||
end
|
||||
|
||||
--- Get a locale string representing the name of the given player in their chat colour
|
||||
-- @tparam LuaPlayer player The player to use the name and color of, nil represents the server
|
||||
-- @treturn LocaleString The players name formatted as a locale string in their chat color
|
||||
function Commands.format_locale_player_name(player)
|
||||
local player_name = player and player.name or "<server>"
|
||||
local player_color = player and player.chat_color or Color.white
|
||||
local color_tag = math.round(player_color.r, 3)..', '..math.round(player_color.g, 3)..', '..math.round(player_color.b, 3)
|
||||
return {'color-tag', color_tag, player_name}
|
||||
end
|
||||
|
||||
--- Print a message to the user of a command, accepts any value and will print in a readable and safe format
|
||||
-- @tparam any message The message / value to be printed
|
||||
-- @tparam[opt] Color color The color the message should be printed in
|
||||
-- @tparam[opt] string sound The sound path to be played when the message is printed
|
||||
function Commands.print(message, color, sound)
|
||||
local player = game.player
|
||||
if not player then
|
||||
rcon.print(ExpUtil.format_any(message))
|
||||
else
|
||||
local formatted = ExpUtil.format_any(message, nil, 20)
|
||||
player.print(formatted, color or Color.white)
|
||||
player.play_sound{ path = sound or 'utility/scenario_message' }
|
||||
end
|
||||
end
|
||||
|
||||
--- Print an error message to the user of a command, accepts any value and will print in a readable and safe format
|
||||
-- @tparam any message The message / value to be printed
|
||||
function Commands.error(message)
|
||||
return Commands.print(message, Color.orange_red, 'utility/wire_pickup')
|
||||
end
|
||||
|
||||
--- Command Prototype
|
||||
-- The prototype defination for command objects
|
||||
-- @section command-prototype
|
||||
|
||||
--- This is a default callback that should never be called
|
||||
local function default_command_callback()
|
||||
return Commands.status.internal_error('No callback registered')
|
||||
end
|
||||
|
||||
--- Returns a new command object, this will not register the command to the game
|
||||
-- @tparam string name The name of the command as it will be registered later
|
||||
-- @tparam string help The help message / description of the command
|
||||
-- @treturn Command A new command object which can be registered
|
||||
function Commands.new(name, help)
|
||||
ExpUtil.assert_argument_type(name, "string", 1, "name")
|
||||
ExpUtil.assert_argument_type(help, "string", 2, "help")
|
||||
if Commands.registered_commands[name] then
|
||||
error("Command is already defined at: "..Commands.registered_commands[name].defined_at, 2)
|
||||
end
|
||||
|
||||
return setmetatable({
|
||||
name = name,
|
||||
help = help,
|
||||
callback = default_command_callback,
|
||||
defined_at = ExpUtil.safe_file_path(2),
|
||||
auto_concat = false,
|
||||
min_arg_count = 0,
|
||||
max_arg_count = 0,
|
||||
flags = {}, -- stores flags that can be used by auth
|
||||
aliases = {}, -- stores aliases to this command
|
||||
arguments = {}, -- [{name: string, optional: boolean, default: any, data_type: function, parse_args: table}]
|
||||
}, Commands._metatable)
|
||||
end
|
||||
|
||||
--- Get the data type parser from a name, will raise an error if it doesnt exist
|
||||
local function get_parser(data_type)
|
||||
local rtn = Commands.data_types[data_type]
|
||||
if rtn == nil then
|
||||
error("Unknown data type: "..tostring(data_type), 3)
|
||||
end
|
||||
return data_type, rtn
|
||||
end
|
||||
|
||||
--- Add a new required argument to the command of the given data type
|
||||
-- @tparam string name The name of the argument being added
|
||||
-- @tparam string data_type The data type of this argument, must have previously been registered with add_data_type
|
||||
-- @treturn Command The command object to allow chaining method calls
|
||||
function Commands._prototype:argument(name, data_type, ...)
|
||||
if self.min_arg_count ~= self.max_arg_count then
|
||||
error("Can not have required arguments after optional arguments", 2)
|
||||
end
|
||||
self.min_arg_count = self.min_arg_count + 1
|
||||
self.max_arg_count = self.max_arg_count + 1
|
||||
self.arguments[#self.arguments + 1] = {
|
||||
name = name,
|
||||
optional = false,
|
||||
data_type = data_type,
|
||||
data_type_parser = get_parser(data_type),
|
||||
parse_args = {...}
|
||||
}
|
||||
return self
|
||||
end
|
||||
|
||||
--- Add a new optional argument to the command of the given data type
|
||||
-- @tparam string name The name of the argument being added
|
||||
-- @tparam string data_type The data type of this argument, must have previously been registered with add_data_type
|
||||
-- @treturn Command The command object to allow chaining method calls
|
||||
function Commands._prototype:optional(name, data_type, ...)
|
||||
self.max_arg_count = self.max_arg_count + 1
|
||||
self.arguments[#self.arguments + 1] = {
|
||||
name = name,
|
||||
optional = true,
|
||||
data_type = data_type,
|
||||
data_type_parser = get_parser(data_type),
|
||||
parse_args = {...}
|
||||
}
|
||||
return self
|
||||
end
|
||||
|
||||
--- Set the defaults for optional arguments, any not provided will have their value as nil
|
||||
-- @tparam table defaults A table who's keys are the argument names and values are the defaults or function which returns a default
|
||||
-- @treturn Command The command object to allow chaining method calls
|
||||
function Commands._prototype:defaults(defaults)
|
||||
local matched = {}
|
||||
for _, argument in ipairs(self.arguments) do
|
||||
if defaults[argument.name] then
|
||||
if not argument.optional then
|
||||
error("Attempting to set default value for required argument: " .. argument.name)
|
||||
end
|
||||
argument.default = defaults[argument.name]
|
||||
matched[argument.name] = true
|
||||
end
|
||||
end
|
||||
-- Check that there are no extra values in the table
|
||||
for name in pairs(defaults) do
|
||||
if not matched[name] then
|
||||
error("No argument with name: " .. name)
|
||||
end
|
||||
end
|
||||
return self
|
||||
end
|
||||
|
||||
--- Set the flags for the command, these can be accessed by permission authorities to check who should use a command
|
||||
-- @tparam table flags An array of string flags, or a table who's keys are the flag names and values are the flag values
|
||||
-- @treturn Command The command object to allow chaining method calls
|
||||
function Commands._prototype:add_flags(flags)
|
||||
for name, value in pairs(flags) do
|
||||
if type(name) == "number" then
|
||||
self.flags[value] = true
|
||||
else
|
||||
self.flags[name] = value
|
||||
end
|
||||
end
|
||||
return self
|
||||
end
|
||||
|
||||
--- Set the aliases for the command, these are alternative names that the command can be ran under
|
||||
-- @tparam table aliases An array of string names to use as aliases to this command
|
||||
-- @treturn Command The command object to allow chaining method calls
|
||||
function Commands._prototype:add_aliases(aliases)
|
||||
local start_index = #self.aliases
|
||||
for index, alias in ipairs(aliases) do
|
||||
self.aliases[start_index + index] = alias
|
||||
end
|
||||
return self
|
||||
end
|
||||
|
||||
--- Enable concatenation of all arguments after the last, this should be used for user provided reason text
|
||||
-- @treturn Command The command object to allow chaining method calls
|
||||
function Commands._prototype:enable_auto_concatenation()
|
||||
self.auto_concat = true
|
||||
return self
|
||||
end
|
||||
|
||||
--- Register the command to the game with the given callback, this must be the final step as the object becomes immutable afterwards
|
||||
-- @tparam function callback The function which is called to perform the command action
|
||||
function Commands._prototype:register(callback)
|
||||
Commands.registered_commands[self.name] = self
|
||||
self.callback = callback
|
||||
|
||||
-- Generates a description to be used
|
||||
local description = {}
|
||||
for index, argument in pairs(self.arguments) do
|
||||
if argument.optional then
|
||||
description[index] = "["..argument.name.."]"
|
||||
else
|
||||
description[index] = "<"..argument.name..">"
|
||||
end
|
||||
end
|
||||
self.description = table.concat(description, " ")
|
||||
|
||||
-- Callback which is called by the game engine
|
||||
local function command_callback(event)
|
||||
event.name = self.name
|
||||
local success, traceback = xpcall(Commands._event_handler, debug.traceback, event)
|
||||
if not success and not traceback:find("Command does not support rcon usage") then
|
||||
local _, msg = Commands.status.internal_error(event.tick)
|
||||
Commands.error(msg)
|
||||
log("Internal Command Error " .. event.tick .. "\n" .. traceback)
|
||||
end
|
||||
end
|
||||
|
||||
-- Registers the command under its own name
|
||||
local help = {'exp-commands.command-help', self.description, self.help}
|
||||
commands.add_command(self.name, help, command_callback)
|
||||
|
||||
-- Registers the command under its aliases
|
||||
for _, alias in ipairs(self.aliases) do
|
||||
commands.add_command(alias, help, command_callback)
|
||||
end
|
||||
end
|
||||
|
||||
--- Command Runner
|
||||
-- Used internally to run commands
|
||||
-- @section command-runner
|
||||
|
||||
--- Log that a command was attempted and its outcome (error / success)
|
||||
local function log_command(comment, command, player, args, detail)
|
||||
local player_name = player and player.name or '<Server>'
|
||||
ExpUtil.write_json('log/commands.log', {
|
||||
comment = comment,
|
||||
detail = detail,
|
||||
player_name = player_name,
|
||||
command_name = command.name,
|
||||
args = args
|
||||
})
|
||||
end
|
||||
|
||||
--- Extract the arguments from a string input string
|
||||
local function extract_arguments(raw_input, max_args, auto_concat)
|
||||
-- nil check when no input given
|
||||
if raw_input == nil then return {} end
|
||||
|
||||
-- Extract quoted arguments
|
||||
local quoted_arguments = {}
|
||||
local input_string = raw_input:gsub('"[^"]-"', function(word)
|
||||
local no_spaces = word:gsub('%s', '%%s')
|
||||
quoted_arguments[no_spaces] = word:sub(2, -2)
|
||||
return ' '..no_spaces..' '
|
||||
end)
|
||||
|
||||
-- Extract all arguments
|
||||
local index = 0
|
||||
local arguments = {}
|
||||
for word in input_string:gmatch('%S+') do
|
||||
index = index + 1
|
||||
if index > max_args then
|
||||
-- concat the word onto the last argument
|
||||
if auto_concat == false then
|
||||
return nil -- too many args, exit early
|
||||
elseif quoted_arguments[word] then
|
||||
arguments[max_args] = arguments[max_args]..' "'..quoted_arguments[word]..'"'
|
||||
else
|
||||
arguments[max_args] = arguments[max_args]..' '..word
|
||||
end
|
||||
else
|
||||
-- new argument to be added
|
||||
if quoted_arguments[word] then
|
||||
arguments[index] = quoted_arguments[word]
|
||||
else
|
||||
arguments[index] = word
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return arguments
|
||||
end
|
||||
|
||||
--- Internal event handler for the command event
|
||||
function Commands._event_handler(event)
|
||||
local command = Commands.registered_commands[event.name]
|
||||
if command == nil then
|
||||
error("Command not recognised: "..event.name)
|
||||
end
|
||||
|
||||
local player = nil -- nil represents the server until the command is called
|
||||
if event.player_index then
|
||||
player = game.get_player(event.player_index)
|
||||
end
|
||||
|
||||
-- Check if the player is allowed to use the command
|
||||
local allowed, failure_msg = Commands.player_has_permission(player, command)
|
||||
if not allowed then
|
||||
log_command("Command not allowed", command, player, event.parameter)
|
||||
return Commands.error(failure_msg)
|
||||
end
|
||||
|
||||
-- Check the edge case of parameter being nil
|
||||
if command.min_arg_count > 0 and event.parameter == nil then
|
||||
log_command("Too few arguments", command, player, event.parameter, { minimum = command.min_arg_count, maximum = command.max_arg_count })
|
||||
return Commands.error{'exp-commands.invalid-usage', command.name, command.description}
|
||||
end
|
||||
|
||||
-- Get the arguments for the command, returns nil if there are too many arguments
|
||||
local raw_arguments = extract_arguments(event.parameter, command.max_arg_count, command.auto_concat)
|
||||
if raw_arguments == nil then
|
||||
log_command("Too many arguments", command, player, event.parameter, { minimum = command.min_arg_count, maximum = command.max_arg_count })
|
||||
return Commands.error{'exp-commands.invalid-usage', command.name, command.description}
|
||||
end
|
||||
|
||||
-- Check the minimum number of arguments is fullfiled
|
||||
if #raw_arguments < command.min_arg_count then
|
||||
log_command("Too few arguments", command, player, event.parameter, { minimum = command.min_arg_count, maximum = command.max_arg_count })
|
||||
return Commands.error{'exp-commands.invalid-usage', command.name, command.description}
|
||||
end
|
||||
|
||||
-- Parse the arguments, optional arguments will attempt to use a default if provided
|
||||
local arguments = {}
|
||||
for index, argument in ipairs(command.arguments) do
|
||||
local input = raw_arguments[index]
|
||||
if input == nil then
|
||||
-- We know this is an optional argument because the mimimum count is satisfied
|
||||
assert(argument.optional == true, "Argument was required")
|
||||
if type(argument.default) == "function" then
|
||||
arguments[index] = argument.default(player)
|
||||
else
|
||||
arguments[index] = argument.default
|
||||
end
|
||||
else
|
||||
-- Parse the raw argument to get the correct data type
|
||||
local success, status, parsed = Commands.parse_data_type(argument.data_type_parser, input, player, table.unpack(argument.parse_args))
|
||||
if success == false then
|
||||
log_command("Input parse failed", command, player, event.parameter, { status = valid_command_status[status], index = index, argument = argument, reason = parsed })
|
||||
return Commands.error{'exp-commands.invalid-argument', argument.name, parsed}
|
||||
else
|
||||
arguments[index] = parsed
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- Run the command, dont need xpcall here because errors are caught in command_callback
|
||||
local status, status_msg = command.callback(player or Commands.player_server, table.unpack(arguments))
|
||||
if valid_command_status[status] then
|
||||
if status ~= Commands.status.success then
|
||||
log_command("Custom Error", command, player, event.parameter, status_msg)
|
||||
return Commands.error(status_msg)
|
||||
else
|
||||
log_command("Command Ran", command, player, event.parameter)
|
||||
return Commands.print(status_msg)
|
||||
end
|
||||
else
|
||||
log_command("Command Ran", command, player, event.parameter)
|
||||
local _, msg = Commands.status.success()
|
||||
return Commands.print(msg)
|
||||
end
|
||||
end
|
||||
|
||||
return Commands
|
||||
33
exp_commands/package.json
Normal file
33
exp_commands/package.json
Normal file
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "@explosivegaming/commands",
|
||||
"version": "0.0.1",
|
||||
"description": "Clusterio module for command handling",
|
||||
"author": "Cooldude2606 <https://github.com/Cooldude2606>",
|
||||
"license": "MIT",
|
||||
"repository": "explosivegaming/clustorio-exp-commands",
|
||||
"main": "dist/node/index.js",
|
||||
"scripts": {
|
||||
"prepare": "tsc --build"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@clusterio/lib": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@clusterio/lib": "workspace:*",
|
||||
"@types/node": "^20.14.9",
|
||||
"typescript": "^5.5.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sinclair/typebox": "^0.30.4"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"keywords": [
|
||||
"clusterio",
|
||||
"factorio"
|
||||
]
|
||||
}
|
||||
6
exp_commands/tsconfig.json
Normal file
6
exp_commands/tsconfig.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
8
exp_commands/tsconfig.node.json
Normal file
8
exp_commands/tsconfig.node.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.node.json",
|
||||
"references": [
|
||||
{ "path": "../../../packages/lib/tsconfig.node.json" },
|
||||
],
|
||||
"include": ["./**/*.ts"],
|
||||
"exclude": ["test/*", "./dist/*"],
|
||||
}
|
||||
32
exp_commands/webpack.config.js
Normal file
32
exp_commands/webpack.config.js
Normal file
@@ -0,0 +1,32 @@
|
||||
"use strict";
|
||||
const path = require("path");
|
||||
const webpack = require("webpack");
|
||||
const { merge } = require("webpack-merge");
|
||||
|
||||
const common = require("@clusterio/web_ui/webpack.common");
|
||||
|
||||
module.exports = (env = {}) => merge(common(env), {
|
||||
context: __dirname,
|
||||
entry: "./web/index.jsx",
|
||||
output: {
|
||||
path: path.resolve(__dirname, "dist", "web"),
|
||||
},
|
||||
plugins: [
|
||||
new webpack.container.ModuleFederationPlugin({
|
||||
name: "exp_commands",
|
||||
library: { type: "var", name: "plugin_exp_commands" },
|
||||
exposes: {
|
||||
"./info": "./dist/plugin/info.js",
|
||||
"./package.json": "./package.json",
|
||||
"./web": "./web/index.jsx",
|
||||
},
|
||||
shared: {
|
||||
"@clusterio/lib": { import: false },
|
||||
"@clusterio/web_ui": { import: false },
|
||||
"antd": { import: false },
|
||||
"react": { import: false },
|
||||
"react-dom": { import: false },
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
282
exp_groups/controller.ts
Normal file
282
exp_groups/controller.ts
Normal file
@@ -0,0 +1,282 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { BaseControllerPlugin, InstanceInfo } from "@clusterio/controller";
|
||||
|
||||
import {
|
||||
PermissionStrings, PermissionStringsUpdate,
|
||||
PermissionGroup, PermissionGroupUpdate,
|
||||
InstancePermissionGroups,
|
||||
PermissionInstanceId,
|
||||
PermissionGroupEditEvent,
|
||||
} from "./messages";
|
||||
|
||||
import path from "path";
|
||||
import fs from "fs-extra";
|
||||
|
||||
export class ControllerPlugin extends BaseControllerPlugin {
|
||||
static permissionGroupsPath = "exp_groups.json";
|
||||
static userGroupsPath = "exp_user_groups.json";
|
||||
|
||||
userToGroup: Map<lib.User["id"], PermissionGroup> = new Map(); // TODO this needs to be per instance
|
||||
permissionStrings!: Map<PermissionStrings["id"], PermissionStrings>;
|
||||
permissionGroups!: Map<InstancePermissionGroups["id"], InstancePermissionGroups>;
|
||||
|
||||
async init() {
|
||||
this.controller.handle(PermissionStringsUpdate, this.handlePermissionStringsUpdate.bind(this));
|
||||
this.controller.handle(PermissionGroupUpdate, this.handlePermissionGroupUpdate.bind(this));
|
||||
this.controller.handle(PermissionGroupEditEvent, this.handlePermissionGroupEditEvent.bind(this));
|
||||
this.controller.subscriptions.handle(PermissionStringsUpdate, this.handlePermissionStringsSubscription.bind(this));
|
||||
this.controller.subscriptions.handle(PermissionGroupUpdate, this.handlePermissionGroupSubscription.bind(this));
|
||||
this.controller.subscriptions.handle(PermissionGroupEditEvent);
|
||||
this.permissionStrings = new Map([["Global", new PermissionStrings("Global", new Set())]]);
|
||||
this.permissionGroups = new Map([["Global", new InstancePermissionGroups("Global")]]);
|
||||
await this.loadData();
|
||||
|
||||
// Add the default group if missing and add any missing cluster roles
|
||||
const clusterRoles = [...this.controller.userManager.roles.values()]
|
||||
for (const instanceGroups of this.permissionGroups.values()) {
|
||||
const groups = instanceGroups.groups;
|
||||
const instanceRoles = [...groups.values()].flatMap(group => [...group.roleIds.values()]);
|
||||
const missingRoles = clusterRoles.filter(role => instanceRoles.includes(role.id));
|
||||
const defaultGroup = groups.get("Default");
|
||||
if (defaultGroup) {
|
||||
for (const role of missingRoles) {
|
||||
defaultGroup.roleIds.add(role.id)
|
||||
}
|
||||
} else {
|
||||
groups.set("Default", new PermissionGroup(
|
||||
instanceGroups.instanceId,
|
||||
"Default",
|
||||
groups.size,
|
||||
new Set(missingRoles.map(role => role.id))
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async onControllerConfigFieldChanged(field: string, curr: unknown, prev: unknown) {
|
||||
if (field === "exp_groups.allow_role_inconsistency") {
|
||||
// Do something with this.userToGroup
|
||||
}
|
||||
}
|
||||
|
||||
async onInstanceConfigFieldChanged(instance: InstanceInfo, field: string, curr: unknown, prev: unknown) {
|
||||
this.logger.info(`controller::onInstanceConfigFieldChanged ${instance.id} ${field}`);
|
||||
if (field === "exp_groups.sync_permission_groups") {
|
||||
const updates = []
|
||||
const now = Date.now();
|
||||
if (curr) {
|
||||
// Global sync enabled, we dont need the instance config
|
||||
const instanceGroups = this.permissionGroups.get(instance.id);
|
||||
if (instanceGroups) {
|
||||
this.permissionGroups.delete(instance.id);
|
||||
for (const group of instanceGroups.groups.values()) {
|
||||
group.updatedAtMs = now;
|
||||
group.isDeleted = true;
|
||||
updates.push(group);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Global sync disabled, make a copy of the global config as a base
|
||||
const global = this.permissionGroups.get("Global")!;
|
||||
const oldInstanceGroups = this.permissionGroups.get(instance.id);
|
||||
const instanceGroups = new InstancePermissionGroups(
|
||||
instance.id, new Map([...global.groups.values()].map(group => [group.name, group.copy(instance.id)]))
|
||||
)
|
||||
this.permissionGroups.set(instance.id, instanceGroups);
|
||||
for (const group of instanceGroups.groups.values()) {
|
||||
group.updatedAtMs = now;
|
||||
updates.push(group);
|
||||
}
|
||||
// If it has an old config (unexpected) then deal with it
|
||||
if (oldInstanceGroups) {
|
||||
for (const group of oldInstanceGroups.groups.values()) {
|
||||
if (!instanceGroups.groups.has(group.name)) {
|
||||
group.updatedAtMs = now;
|
||||
group.isDeleted = true;
|
||||
updates.push(group);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Send the updates to all instances and controls
|
||||
if (updates.length) {
|
||||
this.controller.subscriptions.broadcast(new PermissionGroupUpdate(updates));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async loadPermissionGroups() {
|
||||
const file = path.resolve(this.controller.config.get("controller.database_directory"), ControllerPlugin.permissionGroupsPath);
|
||||
this.logger.verbose(`Loading ${file}`);
|
||||
try {
|
||||
const content = await fs.readFile(file, { encoding: "utf8" });
|
||||
for (const groupRaw of JSON.parse(content)) {
|
||||
const group = PermissionGroup.fromJSON(groupRaw);
|
||||
const instanceGroups = this.permissionGroups.get(group.instanceId);
|
||||
if (instanceGroups) {
|
||||
instanceGroups.groups.set(group.name, group);
|
||||
} else {
|
||||
this.permissionGroups.set(group.instanceId,
|
||||
new InstancePermissionGroups(group.instanceId, new Map([[group.name, group]]))
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
} catch (err: any) {
|
||||
if (err.code === "ENOENT") {
|
||||
this.logger.verbose("Creating new permission group database");
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async savePermissionGroups() {
|
||||
const file = path.resolve(this.controller.config.get("controller.database_directory"), ControllerPlugin.permissionGroupsPath);
|
||||
this.logger.verbose(`Writing ${file}`);
|
||||
await lib.safeOutputFile(file, JSON.stringify(
|
||||
[...this.permissionGroups.values()].flatMap(instanceGroups => [...instanceGroups.groups.values()])
|
||||
));
|
||||
}
|
||||
|
||||
async loadUserGroups() {
|
||||
if (!this.controller.config.get("exp_groups.allow_role_inconsistency")) return;
|
||||
const file = path.resolve(this.controller.config.get("controller.database_directory"), ControllerPlugin.userGroupsPath);
|
||||
this.logger.verbose(`Loading ${file}`);
|
||||
try {
|
||||
const content = await fs.readFile(file, { encoding: "utf8" });
|
||||
this.userToGroup = new Map(JSON.parse(content));
|
||||
|
||||
} catch (err: any) {
|
||||
if (err.code === "ENOENT") {
|
||||
this.logger.verbose("Creating new user group database");
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async saveUserGroups() {
|
||||
if (!this.controller.config.get("exp_groups.allow_role_inconsistency")) return;
|
||||
const file = path.resolve(this.controller.config.get("controller.database_directory"), ControllerPlugin.userGroupsPath);
|
||||
this.logger.verbose(`Writing ${file}`);
|
||||
await lib.safeOutputFile(file, JSON.stringify([...this.permissionGroups.entries()]));
|
||||
}
|
||||
|
||||
async loadData() {
|
||||
await Promise.all([
|
||||
this.loadPermissionGroups(),
|
||||
this.loadUserGroups(),
|
||||
])
|
||||
}
|
||||
|
||||
async onSaveData() {
|
||||
await Promise.all([
|
||||
this.savePermissionGroups(),
|
||||
this.saveUserGroups(),
|
||||
])
|
||||
}
|
||||
|
||||
addPermisisonGroup(instanceId: PermissionInstanceId, name: string, permissions = new Set<string>(), silent = false) {
|
||||
const instanceGroups = this.permissionGroups.get(instanceId);
|
||||
if (!instanceGroups) {
|
||||
throw new Error("Instance ID does not exist");
|
||||
}
|
||||
if (instanceGroups.groups.has(name)) {
|
||||
return instanceGroups.groups.get(name)!;
|
||||
}
|
||||
for (const group of instanceGroups.groups.values()) {
|
||||
group.order += 1;
|
||||
}
|
||||
const group = new PermissionGroup(instanceId, name, 0, new Set(), permissions, Date.now(), false);
|
||||
instanceGroups.groups.set(group.id, group);
|
||||
if (!silent) {
|
||||
this.controller.subscriptions.broadcast(new PermissionGroupUpdate([group]));
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
removePermissionGroup(instanceId: PermissionInstanceId, name: string, silent = false) {
|
||||
const instanceGroups = this.permissionGroups.get(instanceId);
|
||||
if (!instanceGroups) {
|
||||
throw new Error("Instance ID does not exist");
|
||||
}
|
||||
const group = instanceGroups.groups.get(name)
|
||||
if (!group) {
|
||||
return null;
|
||||
}
|
||||
for (const nextGroup of instanceGroups.groups.values()) {
|
||||
if (nextGroup.order > group.order) {
|
||||
nextGroup.order -= 1;
|
||||
}
|
||||
}
|
||||
instanceGroups.groups.delete(group.id);
|
||||
group.updatedAtMs = Date.now();
|
||||
group.isDeleted = true;
|
||||
if (!silent) {
|
||||
this.controller.subscriptions.broadcast(new PermissionGroupUpdate([group]));
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
async handlePermissionGroupEditEvent(event: PermissionGroupEditEvent) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
async handlePermissionStringsUpdate(event: PermissionStringsUpdate) {
|
||||
for (const update of event.updates) {
|
||||
const global = this.permissionStrings.get("Global")!
|
||||
this.permissionStrings.set(update.instanceId as number, update)
|
||||
global.updatedAtMs = Math.max(global.updatedAtMs, update.updatedAtMs)
|
||||
for (const permission of update.permissions) {
|
||||
global.permissions.add(permission)
|
||||
}
|
||||
// TODO maybe check if changes have happened rather than always pushing updates
|
||||
this.controller.subscriptions.broadcast(new PermissionStringsUpdate([global, update]))
|
||||
}
|
||||
}
|
||||
|
||||
async handlePermissionGroupUpdate(event: PermissionGroupUpdate) {
|
||||
const updates = [];
|
||||
for (const group of event.updates) {
|
||||
const groups = this.permissionGroups.get(group.instanceId);
|
||||
if (!groups) continue;
|
||||
const existingGroup = groups.groups.get(group.id);
|
||||
let update
|
||||
if (!existingGroup) {
|
||||
update = this.addPermisisonGroup(group.instanceId, group.name, group.permissions, true);
|
||||
} else if (group.isDeleted) {
|
||||
update = this.removePermissionGroup(group.instanceId, group.name, true);
|
||||
} else {
|
||||
existingGroup.permissions = group.permissions;
|
||||
existingGroup.updatedAtMs = Date.now();
|
||||
update = existingGroup;
|
||||
}
|
||||
if (update) updates.push(update);
|
||||
}
|
||||
this.controller.subscriptions.broadcast(new PermissionGroupUpdate(updates));
|
||||
}
|
||||
|
||||
async handlePermissionStringsSubscription(request: lib.SubscriptionRequest, src: lib.Address) {
|
||||
const updates = [ ...this.permissionStrings.values() ]
|
||||
.filter(
|
||||
value => value.updatedAtMs > request.lastRequestTimeMs,
|
||||
)
|
||||
return updates.length ? new PermissionStringsUpdate(updates) : null;
|
||||
}
|
||||
|
||||
async handlePermissionGroupSubscription(request: lib.SubscriptionRequest, src: lib.Address) {
|
||||
const updates = [ ...this.permissionGroups.values() ]
|
||||
.flatMap(instanceGroups => [...instanceGroups.groups.values()])
|
||||
.filter(
|
||||
value => value.updatedAtMs > request.lastRequestTimeMs,
|
||||
)
|
||||
if (src.type === lib.Address.instance) {
|
||||
const instanceUpdates = updates.filter(group => group.instanceId === src.id || group.instanceId === "Global");
|
||||
this.logger.info(JSON.stringify(updates))
|
||||
this.logger.info(JSON.stringify(instanceUpdates))
|
||||
return instanceUpdates.length ? new PermissionGroupUpdate(instanceUpdates) : null;
|
||||
}
|
||||
return updates.length ? new PermissionGroupUpdate(updates) : null;
|
||||
}
|
||||
}
|
||||
84
exp_groups/index.ts
Normal file
84
exp_groups/index.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
import * as Messages from "./messages";
|
||||
|
||||
lib.definePermission({
|
||||
name: "exp_groups.create_delete_groups",
|
||||
title: "Create and delete permission groups",
|
||||
description: "Create and delete permission groups.",
|
||||
});
|
||||
|
||||
lib.definePermission({
|
||||
name: "exp_groups.reorder_groups",
|
||||
title: "Reorder permission groups",
|
||||
description: "Reorder groups and link them to user roles.",
|
||||
});
|
||||
|
||||
lib.definePermission({
|
||||
name: "exp_groups.modify_permissions",
|
||||
title: "Modify permission groups",
|
||||
description: "Modify game permissions for groups.",
|
||||
});
|
||||
|
||||
lib.definePermission({
|
||||
name: "exp_groups.assign_players",
|
||||
title: "Change player group",
|
||||
description: "Change the permission group of a player",
|
||||
});
|
||||
|
||||
lib.definePermission({
|
||||
name: "exp_groups.list",
|
||||
title: "View permission groups",
|
||||
description: "View permission groups.",
|
||||
});
|
||||
|
||||
lib.definePermission({
|
||||
name: "exp_groups.list.subscribe",
|
||||
title: "Subscribe to permission group updates",
|
||||
description: "Subscribe to permission group updates.",
|
||||
});
|
||||
|
||||
declare module "@clusterio/lib" {
|
||||
export interface ControllerConfigFields {
|
||||
"exp_groups.allow_role_inconsistency": boolean;
|
||||
}
|
||||
export interface InstanceConfigFields {
|
||||
"exp_groups.sync_permission_groups": boolean;
|
||||
}
|
||||
}
|
||||
|
||||
export const plugin: lib.PluginDeclaration = {
|
||||
name: "exp_groups",
|
||||
title: "exp_groups",
|
||||
description: "Create, modify, and link factorio permission groups to clusterio user roles.",
|
||||
|
||||
controllerEntrypoint: "./dist/node/controller",
|
||||
controllerConfigFields: {
|
||||
"exp_groups.allow_role_inconsistency": {
|
||||
title: "Allow User Role Inconsistency",
|
||||
description: "When true, users can be assgined to any group regardless of their roles",
|
||||
type: "boolean",
|
||||
initialValue: false,
|
||||
},
|
||||
},
|
||||
|
||||
instanceEntrypoint: "./dist/node/instance",
|
||||
instanceConfigFields: {
|
||||
"exp_groups.sync_permission_groups": {
|
||||
title: "Sync Permission Groups",
|
||||
description: "When true, the instance cannot deviate from the global group settings and will be hidden from the sellection dropdown.",
|
||||
type: "boolean",
|
||||
initialValue: true,
|
||||
},
|
||||
},
|
||||
|
||||
messages: [
|
||||
Messages.PermissionGroupEditEvent,
|
||||
Messages.PermissionStringsUpdate,
|
||||
Messages.PermissionGroupUpdate,
|
||||
],
|
||||
|
||||
webEntrypoint: "./web",
|
||||
routes: [
|
||||
"/exp_groups",
|
||||
],
|
||||
};
|
||||
129
exp_groups/instance.ts
Normal file
129
exp_groups/instance.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { BaseInstancePlugin } from "@clusterio/host";
|
||||
import {
|
||||
PermissionGroup, PermissionGroupEditEvent, PermissionGroupEditType,
|
||||
PermissionGroupUpdate, PermissionInstanceId, PermissionStrings, PermissionStringsUpdate
|
||||
} from "./messages";
|
||||
|
||||
const rconBase = "/sc local Groups = package.loaded['modules/exp_groups/module_exports'];"
|
||||
|
||||
type EditIPC = {
|
||||
type: PermissionGroupEditType,
|
||||
changes: string[],
|
||||
group: string,
|
||||
};
|
||||
|
||||
type CreateIPC = {
|
||||
group: string,
|
||||
defiantion: [boolean, string[] | {}]
|
||||
}
|
||||
|
||||
type DeleteIPC = {
|
||||
group: string,
|
||||
}
|
||||
|
||||
export class InstancePlugin extends BaseInstancePlugin {
|
||||
permissions: Set<string> = new Set();
|
||||
permissionGroups = new lib.EventSubscriber(PermissionGroupUpdate, this.instance);
|
||||
permissionGroupUpdates = new lib.EventSubscriber(PermissionGroupEditEvent, this.instance);
|
||||
syncId: PermissionInstanceId = this.instance.config.get("exp_groups.sync_permission_groups") ? "Global" : this.instance.id;
|
||||
|
||||
async init() {
|
||||
this.instance.server.handle("exp_groups-permission_group_edit", this.handleEditIPC.bind(this));
|
||||
this.instance.server.handle("exp_groups-permission_group_create", this.handleCreateIPC.bind(this));
|
||||
this.instance.server.handle("exp_groups-permission_group_delete", this.handleDeleteIPC.bind(this));
|
||||
}
|
||||
|
||||
async onStart() {
|
||||
// Send the most recent version of the permission string
|
||||
const permissionsString = await this.sendRcon(rconBase + "rcon.print(Groups.get_actions_json())");
|
||||
this.permissions = new Set(JSON.parse(permissionsString));
|
||||
this.instance.sendTo("controller", new PermissionStringsUpdate([
|
||||
new PermissionStrings(this.instance.id, this.permissions, Date.now())
|
||||
]));
|
||||
|
||||
// Subscribe to get updates for permission groups
|
||||
this.permissionGroups.subscribe(this.onPermissionGroupsUpdate.bind(this));
|
||||
this.permissionGroupUpdates.subscribe(this.onPermissionGroupUpdate.bind(this));
|
||||
}
|
||||
|
||||
async onControllerConnectionEvent(event: any) {
|
||||
this.permissionGroups.handleConnectionEvent(event);
|
||||
}
|
||||
|
||||
async onInstanceConfigFieldChanged(field: string, curr: unknown, prev: unknown) {
|
||||
if (field === "exp_groups.sync_permission_groups") {
|
||||
this.syncId = curr ? "Global" : this.instance.id;
|
||||
const [snapshot, synced] = this.permissionGroups.getSnapshot();
|
||||
if (synced && this.instance.status !== "running") await this.syncPermissionGroups(snapshot.values());
|
||||
}
|
||||
}
|
||||
|
||||
async onPermissionGroupsUpdate(event: PermissionGroupUpdate | null, synced: boolean) {
|
||||
if (!synced || this.instance.status !== "running" || !event?.updates.length) return;
|
||||
await this.syncPermissionGroups(event.updates);
|
||||
}
|
||||
|
||||
async syncPermissionGroups(groups: Iterable<PermissionGroup>) {
|
||||
const updateCommands = [rconBase];
|
||||
for (const group of groups) {
|
||||
if (group.instanceId === this.syncId && group.updatedAtMs > (this.permissionGroups.values.get(group.id)?.updatedAtMs ?? 0)) {
|
||||
if (group.isDeleted) {
|
||||
updateCommands.push(`Groups.destroy_group('${group.name}')`);
|
||||
} else if (group.permissions.size < this.permissions.size / 2) {
|
||||
updateCommands.push(`Groups.get_or_create('${group.name}'):from_json('${JSON.stringify([false, [...this.permissions.values()]])}')`);
|
||||
} else {
|
||||
const inverted = [...this.permissions.values()].filter(permission => !group.permissions.has(permission));
|
||||
updateCommands.push(`Groups.get_or_create('${group.name}'):from_json('${JSON.stringify([true, inverted])}')`);
|
||||
}
|
||||
}
|
||||
}
|
||||
await this.sendRcon(updateCommands.join(";"), true);
|
||||
}
|
||||
|
||||
async onPermissionGroupUpdate(event: PermissionGroupEditEvent | null, synced: boolean) {
|
||||
if (!synced || this.instance.status !== "running" || !event) return;
|
||||
if (event.src.equals(lib.Address.fromShorthand({ instanceId: this.instance.id }))) return;
|
||||
const getCmd = `Groups.get_or_create('${event.group}')`;
|
||||
if (event.type === "add_permissions") {
|
||||
await this.sendRcon(rconBase + getCmd + `:allow_actions(Groups.json_to_actions('${JSON.stringify(event.changes)}'))`);
|
||||
} else if (event.type === "remove_permissions") {
|
||||
await this.sendRcon(rconBase + getCmd + `:disallow_actions(Groups.json_to_actions('${JSON.stringify(event.changes)}'))`);
|
||||
} else if (event.type === "assign_players") {
|
||||
await this.sendRcon(rconBase + getCmd + `:add_players(game.json_to_table('${JSON.stringify(event.changes)}'))`);
|
||||
}
|
||||
}
|
||||
|
||||
async handleEditIPC(event: EditIPC) {
|
||||
this.logger.info(JSON.stringify(event))
|
||||
this.instance.sendTo("controller", new PermissionGroupEditEvent(
|
||||
lib.Address.fromShorthand({ instanceId: this.instance.id }),
|
||||
event.type, event.group, event.changes
|
||||
))
|
||||
}
|
||||
|
||||
async handleCreateIPC(event: CreateIPC) {
|
||||
this.logger.info(JSON.stringify(event))
|
||||
if (!this.permissionGroups.synced) return;
|
||||
let [defaultAllow, permissionsRaw] = event.defiantion;
|
||||
if (!Array.isArray(permissionsRaw)) {
|
||||
permissionsRaw = [] // lua outputs {} for empty arrays
|
||||
}
|
||||
const permissions = [...this.permissions.values()]
|
||||
.filter(permission => defaultAllow !== (permissionsRaw as String[]).includes(permission));
|
||||
this.instance.sendTo("controller", new PermissionGroupUpdate([ new PermissionGroup(
|
||||
this.syncId, event.group, 0, new Set(), new Set(permissions)
|
||||
) ]));
|
||||
}
|
||||
|
||||
async handleDeleteIPC(event: DeleteIPC) {
|
||||
if (!this.permissionGroups.synced) return;
|
||||
const group = [...this.permissionGroups.values.values()]
|
||||
.find(group => group.instanceId === this.syncId && group.name === event.group);
|
||||
if (group) {
|
||||
group.updatedAtMs = Date.now();
|
||||
group.isDeleted = true;
|
||||
this.instance.sendTo("controller", new PermissionGroupUpdate([ group ]));
|
||||
}
|
||||
}
|
||||
}
|
||||
239
exp_groups/messages.ts
Normal file
239
exp_groups/messages.ts
Normal file
@@ -0,0 +1,239 @@
|
||||
import { User, InstanceDetails, IControllerUser, Link, MessageRequest, StringEnum, PermissionError, Address } from "@clusterio/lib";
|
||||
import { Type, Static } from "@sinclair/typebox";
|
||||
|
||||
export const PermissionInstanceIdSchema = Type.Union([InstanceDetails.jsonSchema.properties.id, Type.Literal("Global")])
|
||||
export type PermissionInstanceId = InstanceDetails["id"] | "Global"
|
||||
export type GamePermission = string; // todo: maybe enum this?
|
||||
|
||||
/**
|
||||
* Data class for permission groups
|
||||
*/
|
||||
export class PermissionGroup {
|
||||
constructor(
|
||||
public instanceId: PermissionInstanceId,
|
||||
public name: string,
|
||||
/** A lower order assumes a lower permission group */
|
||||
public order: number = 0,
|
||||
/** A role will use the highest order group it is apart of */
|
||||
public roleIds: User["roleIds"] = new Set(),
|
||||
public permissions: Set<GamePermission> = new Set(),
|
||||
public updatedAtMs: number = 0,
|
||||
public isDeleted: boolean = false,
|
||||
) {
|
||||
}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
instanceId: PermissionInstanceIdSchema,
|
||||
name: Type.String(),
|
||||
order: Type.Number(),
|
||||
roleIds: Type.Array(Type.Number()),
|
||||
permissions: Type.Array(Type.String()),
|
||||
updatedAtMs: Type.Optional(Type.Number()),
|
||||
isDeleted: Type.Optional(Type.Boolean()),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(
|
||||
json.instanceId,
|
||||
json.name,
|
||||
json.order,
|
||||
new Set(json.roleIds),
|
||||
new Set(json.permissions),
|
||||
json.updatedAtMs,
|
||||
json.isDeleted
|
||||
);
|
||||
}
|
||||
|
||||
toJSON(): Static<typeof PermissionGroup.jsonSchema> {
|
||||
return {
|
||||
instanceId: this.instanceId,
|
||||
name: this.name,
|
||||
order: this.order,
|
||||
roleIds: [...this.roleIds.values()],
|
||||
permissions: [...this.permissions.values()],
|
||||
updatedAtMs: this.updatedAtMs > 0 ? this.updatedAtMs : undefined,
|
||||
isDeleted: this.isDeleted ? this.isDeleted : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
get id() {
|
||||
return `${this.instanceId}:${this.name}`;
|
||||
}
|
||||
|
||||
copy(newInstanceId: PermissionInstanceId) {
|
||||
return new PermissionGroup(
|
||||
newInstanceId,
|
||||
this.name,
|
||||
this.order,
|
||||
new Set(this.roleIds),
|
||||
new Set(this.permissions),
|
||||
Date.now(),
|
||||
false
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export class InstancePermissionGroups {
|
||||
constructor(
|
||||
public instanceId: PermissionInstanceId,
|
||||
public groups: Map<PermissionGroup["name"], PermissionGroup> = new Map(),
|
||||
) {
|
||||
}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
instanceId: PermissionInstanceIdSchema,
|
||||
permissionsGroups: Type.Array(PermissionGroup.jsonSchema),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof InstancePermissionGroups.jsonSchema>) {
|
||||
return new InstancePermissionGroups(
|
||||
json.instanceId,
|
||||
new Map(json.permissionsGroups.map(group => [group.name, PermissionGroup.fromJSON(group)])),
|
||||
);
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
instanceId: this.instanceId,
|
||||
permissionsGroups: [...this.groups.values()],
|
||||
}
|
||||
}
|
||||
|
||||
getUserGroup(user: User) {
|
||||
const groups = [...user.roleIds.values()].map(roleId =>
|
||||
// There will always be one and only one group for each role
|
||||
[...this.groups.values()].find(group => group.roleIds.has(roleId))!
|
||||
);
|
||||
return groups.reduce((highest, group) => highest.order > group.order ? highest : group);
|
||||
}
|
||||
|
||||
get id() {
|
||||
return this.instanceId;
|
||||
}
|
||||
}
|
||||
|
||||
export class PermissionGroupUpdate {
|
||||
declare ["constructor"]: typeof PermissionGroupUpdate;
|
||||
static type = "event" as const;
|
||||
static src = ["controller", "instance"] as const;
|
||||
static dst = ["control", "instance", "controller"] as const;
|
||||
static plugin = "exp_groups" as const;
|
||||
static permission = "exp_groups.list.subscribe";
|
||||
|
||||
constructor(
|
||||
public updates: PermissionGroup[],
|
||||
) { }
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
"updates": Type.Array(PermissionGroup.jsonSchema),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(
|
||||
json.updates.map(update => PermissionGroup.fromJSON(update))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export type PermissionGroupEditType = "assign_players" | "add_permissions" | "remove_permissions";
|
||||
|
||||
export class PermissionGroupEditEvent {
|
||||
declare ["constructor"]: typeof PermissionGroupEditEvent;
|
||||
static type = "event" as const;
|
||||
static src = ["instance", "controller"] as const;
|
||||
static dst = ["control", "instance", "controller"] as const;
|
||||
static plugin = "exp_groups" as const;
|
||||
|
||||
static permission(user: IControllerUser, message: MessageRequest) {
|
||||
if (typeof message.data === "object" && message.data !== null) {
|
||||
const data = message.data as Static<typeof PermissionGroupEditEvent.jsonSchema>;
|
||||
if (data.type === "add_permissions" || data.type === "remove_permissions") {
|
||||
user.checkPermission("exp_groups.modify_permissions")
|
||||
} else if (data.type === "assign_players") {
|
||||
user.checkPermission("exp_groups.assign_players")
|
||||
} else {
|
||||
throw new PermissionError("Permission denied");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
constructor(
|
||||
public src: Address,
|
||||
public type: PermissionGroupEditType,
|
||||
public group: string,
|
||||
public changes: String[],
|
||||
) { }
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
"src": Address.jsonSchema,
|
||||
"type": StringEnum(["assign_players", "add_permissions", "remove_permissions"]),
|
||||
"group": Type.String(),
|
||||
"changes": Type.Array(Type.String()),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(Address.fromJSON(json.src), json.type, json.group, json.changes);
|
||||
}
|
||||
}
|
||||
|
||||
export class PermissionStrings {
|
||||
constructor(
|
||||
public instanceId: PermissionInstanceId,
|
||||
public permissions: Set<GamePermission>,
|
||||
public updatedAtMs: number = 0,
|
||||
public isDeleted: boolean = false,
|
||||
) {
|
||||
}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
instanceId: PermissionInstanceIdSchema,
|
||||
permissions: Type.Array(Type.String()),
|
||||
updatedAtMs: Type.Optional(Type.Number()),
|
||||
isDeleted: Type.Optional(Type.Boolean()),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof PermissionStrings.jsonSchema>) {
|
||||
return new PermissionStrings(
|
||||
json.instanceId,
|
||||
new Set(json.permissions),
|
||||
json.updatedAtMs,
|
||||
json.isDeleted
|
||||
);
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return {
|
||||
instanceId: this.instanceId,
|
||||
permissions: [...this.permissions.values()],
|
||||
updatedAtMs: this.updatedAtMs > 0 ? this.updatedAtMs : undefined,
|
||||
isDeleted: this.isDeleted ? this.isDeleted : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
get id() {
|
||||
return this.instanceId
|
||||
}
|
||||
}
|
||||
|
||||
export class PermissionStringsUpdate {
|
||||
declare ["constructor"]: typeof PermissionStringsUpdate;
|
||||
static type = "event" as const;
|
||||
static src = ["instance", "controller"] as const;
|
||||
static dst = ["controller", "control"] as const;
|
||||
static plugin = "exp_groups" as const;
|
||||
static permission = "exp_groups.list.subscribe";
|
||||
|
||||
constructor(
|
||||
public updates: PermissionStrings[],
|
||||
) { }
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
"updates": Type.Array(PermissionStrings.jsonSchema),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(
|
||||
json.updates.map(update => PermissionStrings.fromJSON(update))
|
||||
);
|
||||
}
|
||||
}
|
||||
125
exp_groups/module/control.lua
Normal file
125
exp_groups/module/control.lua
Normal file
@@ -0,0 +1,125 @@
|
||||
local clusterio_api = require("modules/clusterio/api")
|
||||
local Global = require("modules/exp_util/global")
|
||||
local Groups = require("modules/exp_groups")
|
||||
|
||||
local pending_updates = {}
|
||||
Global.register(pending_updates, function(tbl)
|
||||
pending_updates = tbl
|
||||
end)
|
||||
|
||||
local function on_permission_group_added(event)
|
||||
if not event.player_index then return end
|
||||
pending_updates[event.group.name] = {
|
||||
created = true,
|
||||
sync_all = true,
|
||||
tick = event.tick,
|
||||
permissions = {},
|
||||
players = {},
|
||||
}
|
||||
end
|
||||
|
||||
local function on_permission_group_deleted(event)
|
||||
if not event.player_index then return end
|
||||
local existing = pending_updates[event.group_name]
|
||||
pending_updates[event.group_name] = nil
|
||||
if not existing or not existing.created then
|
||||
clusterio_api.send_json("exp_groups-permission_group_delete", {
|
||||
group = event.group_name,
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
local function on_permission_group_edited(event)
|
||||
if not event.player_index then return end
|
||||
local pending = pending_updates[event.group.name]
|
||||
if not pending then
|
||||
pending = {
|
||||
tick = event.tick,
|
||||
permissions = {},
|
||||
players = {},
|
||||
}
|
||||
pending_updates[event.group.name] = pending
|
||||
end
|
||||
pending.tick = event.tick
|
||||
|
||||
if event.type == "add-permission" then
|
||||
if not pending.sync_all then
|
||||
pending.permissions[event.action] = true
|
||||
end
|
||||
elseif event.type == "remove-permission" then
|
||||
if not pending.sync_all then
|
||||
pending.permissions[event.action] = false
|
||||
end
|
||||
elseif event.type == "enable-all" then
|
||||
pending.sync_all = true
|
||||
elseif event.type == "disable-all" then
|
||||
pending.sync_all = true
|
||||
elseif event.type == "add-player" then
|
||||
local player = game.get_player(event.other_player_index) --- @cast player -nil
|
||||
pending.players[player.name] = true
|
||||
elseif event.type == "remove-player" then
|
||||
local player = game.get_player(event.other_player_index) --- @cast player -nil
|
||||
pending.players[player.name] = nil
|
||||
elseif event.type == "rename" then
|
||||
pending.created = true
|
||||
pending.sync_all = true
|
||||
local old = pending_updates[event.old_name]
|
||||
if old then pending.players = old.players end
|
||||
on_permission_group_deleted{
|
||||
tick = event.tick, player_index = event.player_index, group_name = event.old_name
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
local function send_updates()
|
||||
local tick = game.tick - 600 -- 10 Seconds
|
||||
local done = {}
|
||||
for group_name, pending in pairs(pending_updates) do
|
||||
if pending.tick < tick then
|
||||
done[group_name] = true
|
||||
if pending.sync_all then
|
||||
clusterio_api.send_json("exp_groups-permission_group_create", {
|
||||
group = group_name, defiantion = Groups.get_group(group_name):to_json(true)
|
||||
})
|
||||
else
|
||||
if next(pending.players) then
|
||||
clusterio_api.send_json("exp_groups-permission_group_edit", {
|
||||
type = "assign_players", group = group_name, changes = table.get_keys(pending.players)
|
||||
})
|
||||
end
|
||||
local add, remove = {}, {}
|
||||
for permission, state in pairs(pending.permissions) do
|
||||
if state then
|
||||
add[#add + 1] = permission
|
||||
else
|
||||
remove[#remove + 1] = permission
|
||||
end
|
||||
end
|
||||
if next(add) then
|
||||
clusterio_api.send_json("exp_groups-permission_group_edit", {
|
||||
type = "add_permissions", group = group_name, changes = Groups.actions_to_names(add)
|
||||
})
|
||||
end
|
||||
if next(remove) then
|
||||
clusterio_api.send_json("exp_groups-permission_group_edit", {
|
||||
type = "remove_permissions", group = group_name, changes = Groups.actions_to_names(remove)
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
for group_name in pairs(done) do
|
||||
pending_updates[group_name] = nil
|
||||
end
|
||||
end
|
||||
|
||||
return {
|
||||
events = {
|
||||
[defines.events.on_permission_group_added] = on_permission_group_added,
|
||||
[defines.events.on_permission_group_deleted] = on_permission_group_deleted,
|
||||
[defines.events.on_permission_group_edited] = on_permission_group_edited,
|
||||
},
|
||||
on_nth_tick = {
|
||||
[300] = send_updates,
|
||||
}
|
||||
}
|
||||
12
exp_groups/module/module.json
Normal file
12
exp_groups/module/module.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "exp_groups",
|
||||
"load": [
|
||||
"control.lua"
|
||||
],
|
||||
"require": [
|
||||
],
|
||||
"dependencies": {
|
||||
"clusterio": "*",
|
||||
"exp_util": "*"
|
||||
}
|
||||
}
|
||||
276
exp_groups/module/module_exports.lua
Normal file
276
exp_groups/module/module_exports.lua
Normal file
@@ -0,0 +1,276 @@
|
||||
local Async = require("modules/exp_util/async")
|
||||
|
||||
--- Top level module table, contains event handlers and public methods
|
||||
local Groups = {}
|
||||
|
||||
---@class ExpGroup
|
||||
---@field group LuaPermissionGroup The permission group for this group proxy
|
||||
Groups._prototype = {}
|
||||
|
||||
Groups._metatable = {
|
||||
__index = setmetatable(Groups._prototype, {
|
||||
__index = function(self, key)
|
||||
return self.group[key]
|
||||
end
|
||||
}),
|
||||
__class = "ExpGroup"
|
||||
}
|
||||
|
||||
local action_to_name = {}
|
||||
for name, action in pairs(defines.input_action) do
|
||||
action_to_name[action] = name
|
||||
end
|
||||
|
||||
--- Async Functions
|
||||
-- These are required to allow bypassing edit_permission_group
|
||||
|
||||
--- Add a player to a permission group, requires edit_permission_group
|
||||
---@param player LuaPlayer Player to add to the group
|
||||
---@param group LuaPermissionGroup Group to add the player to
|
||||
local function add_player_to_group(player, group)
|
||||
return group.add_player(player)
|
||||
end
|
||||
|
||||
--- Add a players to a permission group, requires edit_permission_group
|
||||
---@param players LuaPlayer[] Players to add to the group
|
||||
---@param group LuaPermissionGroup Group to add the players to
|
||||
local function add_players_to_group(players, group)
|
||||
local add_player = group.add_player
|
||||
if not add_player(players[1]) then
|
||||
return false
|
||||
end
|
||||
for i = 2, #players do
|
||||
add_player(players[i])
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- Async will bypass edit_permission_group but takes at least one tick
|
||||
local add_player_to_group_async = Async.register(add_player_to_group)
|
||||
local add_players_to_group_async = Async.register(add_players_to_group)
|
||||
|
||||
--- Static methods for gettings, creating and removing permission groups
|
||||
|
||||
--- Gets the permission group proxy with the given name or group ID.
|
||||
---@param group_name string|uint32 The name or id of the permission group
|
||||
function Groups.get_group(group_name)
|
||||
local group = game.permissions.get_group(group_name)
|
||||
if group == nil then return nil end
|
||||
return setmetatable({
|
||||
group = group
|
||||
}, Groups._metatable)
|
||||
end
|
||||
|
||||
--- Gets the permission group proxy for a players group
|
||||
---@param player LuaPlayer The player to get the group of
|
||||
function Groups.get_player_group(player)
|
||||
local group = player.permission_group
|
||||
if group == nil then return nil end
|
||||
return setmetatable({
|
||||
group = group
|
||||
}, Groups._metatable)
|
||||
end
|
||||
|
||||
--- Creates a new permission group, requires add_permission_group
|
||||
---@param group_name string Name of the group to create
|
||||
function Groups.new_group(group_name)
|
||||
local group = game.permissions.get_group(group_name)
|
||||
assert(group == nil, "Group already exists with name: " .. group_name)
|
||||
group = game.permissions.create_group(group_name)
|
||||
assert(group ~= nil, "Requires permission add_permission_group")
|
||||
return setmetatable({
|
||||
group = group
|
||||
}, Groups._metatable)
|
||||
end
|
||||
|
||||
--- Get or create a permisison group, must use the group name not the group id
|
||||
---@param group_name string Name of the group to create
|
||||
function Groups.get_or_create(group_name)
|
||||
local group = game.permissions.get_group(group_name)
|
||||
if group then
|
||||
return setmetatable({
|
||||
group = group
|
||||
}, Groups._metatable)
|
||||
else
|
||||
group = game.permissions.create_group(group_name)
|
||||
assert(group ~= nil, "Requires permission add_permission_group")
|
||||
return setmetatable({
|
||||
group = group
|
||||
}, Groups._metatable)
|
||||
end
|
||||
end
|
||||
|
||||
--- Destory a permission group, moves all players to default group
|
||||
---@param group_name string|uint32 The name or id of the permission group to destroy
|
||||
---@param move_to_name string|uint32? The name or id of the permission group to move players to
|
||||
function Groups.destroy_group(group_name, move_to_name)
|
||||
local group = game.permissions.get_group(group_name)
|
||||
if group == nil then return nil end
|
||||
|
||||
local players = group.players
|
||||
if #players > 0 then
|
||||
local move_to = game.permissions.get_group(move_to_name or "Default")
|
||||
for _, player in ipairs(players) do
|
||||
player.permission_group = move_to
|
||||
end
|
||||
end
|
||||
|
||||
local success = group.destroy()
|
||||
assert(success, "Requires permission delete_permission_group")
|
||||
end
|
||||
|
||||
--- Prototype methods for modifying and working with permission groups
|
||||
|
||||
--- Add a player to the permission group
|
||||
---@param player LuaPlayer The player to add to the group
|
||||
function Groups._prototype:add_player(player)
|
||||
return add_player_to_group(player, self.group) or add_player_to_group_async(player, self.group)
|
||||
end
|
||||
|
||||
--- Add players to the permission group
|
||||
---@param players LuaPlayer[] The player to add to the group
|
||||
function Groups._prototype:add_players(players)
|
||||
return add_players_to_group(players, self.group) or add_players_to_group_async(players, self.group)
|
||||
end
|
||||
|
||||
--- Move all players to another group
|
||||
---@param other_group ExpGroup The group to move players to, default is the Default group
|
||||
function Groups._prototype:move_players(other_group)
|
||||
return add_players_to_group(self.group.players, other_group.group) or add_players_to_group_async(self.group.players, other_group.group)
|
||||
end
|
||||
|
||||
--- Allow a set of actions for this group
|
||||
---@param actions defines.input_action[] Actions to allow
|
||||
function Groups._prototype:allow_actions(actions)
|
||||
local set_allow = self.group.set_allows_action
|
||||
for _, action in ipairs(actions) do
|
||||
set_allow(action, true)
|
||||
end
|
||||
return self
|
||||
end
|
||||
|
||||
--- Disallow a set of actions for this group
|
||||
---@param actions defines.input_action[] Actions to disallow
|
||||
function Groups._prototype:disallow_actions(actions)
|
||||
local set_allow = self.group.set_allows_action
|
||||
for _, action in ipairs(actions) do
|
||||
set_allow(action, false)
|
||||
end
|
||||
return self
|
||||
end
|
||||
|
||||
--- Reset the allowed state of all actions
|
||||
---@param allowed boolean? default true for allow all actions, false to disallow all actions
|
||||
function Groups._prototype:reset(allowed)
|
||||
local set_allow = self.group.set_allows_action
|
||||
if allowed == nil then allowed = true end
|
||||
for _, action in pairs(defines.input_action) do
|
||||
set_allow(action, allowed)
|
||||
end
|
||||
return self
|
||||
end
|
||||
|
||||
--- Returns if the group is allowed a given action
|
||||
---@param action string|defines.input_action Actions to test
|
||||
function Groups._prototype:allows(action)
|
||||
if type(action) == "string" then
|
||||
return self.group.allows_action(defines.input_action[action])
|
||||
end
|
||||
return self.group.allows_action(action)
|
||||
end
|
||||
|
||||
--- Print a message to all players in the group
|
||||
function Groups._prototype:print(...)
|
||||
for _, player in ipairs(self.group.players) do
|
||||
player.print(...)
|
||||
end
|
||||
end
|
||||
|
||||
--- Static and Prototype methods for use with IPC
|
||||
|
||||
--- Convert an array of strings into an array of action names
|
||||
---@param actions_names string[] An array of action names
|
||||
local function names_to_actions(actions_names)
|
||||
local actions, invalid, invalid_i = {}, {}, 1
|
||||
for i, action_name in ipairs(actions_names) do
|
||||
local action = defines.input_action[action_name]
|
||||
if action then
|
||||
actions[i] = action
|
||||
else
|
||||
invalid[invalid_i] = i
|
||||
invalid_i = invalid_i + 1
|
||||
end
|
||||
end
|
||||
|
||||
local last = #actions
|
||||
for _, i in ipairs(invalid) do
|
||||
actions[i] = actions[last]
|
||||
last = last - 1
|
||||
end
|
||||
|
||||
return actions
|
||||
end
|
||||
|
||||
--- Get the action names from the action numbers
|
||||
function Groups.actions_to_names(actions)
|
||||
local names = {}
|
||||
for i, action in ipairs(actions) do
|
||||
names[i] = action_to_name[action]
|
||||
end
|
||||
return names
|
||||
end
|
||||
|
||||
--- Get all input actions that are defined
|
||||
function Groups.get_actions_json()
|
||||
local rtn, rtn_i = {}, 1
|
||||
for name in pairs(defines.input_action) do
|
||||
rtn[rtn_i] = name
|
||||
rtn_i = rtn_i + 1
|
||||
end
|
||||
return game.table_to_json(rtn)
|
||||
end
|
||||
|
||||
--- Convert a json string array into an array of input actions
|
||||
---@param json string A json string representing a string array of actions
|
||||
function Groups.json_to_actions(json)
|
||||
local tbl = game.json_to_table(json)
|
||||
assert(tbl, "Invalid Json String")
|
||||
---@cast tbl string[]
|
||||
return names_to_actions(tbl)
|
||||
end
|
||||
|
||||
--- Returns the shortest defination of the allowed actions
|
||||
-- The first value of the return can be passed to :reset
|
||||
function Groups._prototype:to_json(raw)
|
||||
local allow, disallow = {}, {}
|
||||
local allow_i, disallow_i = 1, 1
|
||||
local allows = self.group.allows_action
|
||||
for name, action in pairs(defines.input_action) do
|
||||
if allows(action) then
|
||||
allow[allow_i] = name
|
||||
allow_i = allow_i + 1
|
||||
else
|
||||
disallow[disallow_i] = name
|
||||
disallow_i = disallow_i + 1
|
||||
end
|
||||
end
|
||||
|
||||
if allow_i >= disallow_i then
|
||||
return raw and {true, disallow} or game.table_to_json{ true, disallow }
|
||||
end
|
||||
return raw and {false, allow} or game.table_to_json{ false, allow }
|
||||
end
|
||||
|
||||
--- Restores this group to the state given in a json string
|
||||
---@param json string The json string to restore from
|
||||
function Groups._prototype:from_json(json)
|
||||
local tbl = game.json_to_table(json)
|
||||
assert(tbl and type(tbl[1]) == "boolean" and type(tbl[2]) == "table", "Invalid Json String")
|
||||
|
||||
if tbl[1] then
|
||||
return self:reset(true):disallow_actions(names_to_actions(tbl[2]))
|
||||
end
|
||||
return self:reset(false):allow_actions(names_to_actions(tbl[2]))
|
||||
end
|
||||
|
||||
return Groups
|
||||
40
exp_groups/package.json
Normal file
40
exp_groups/package.json
Normal file
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "exp_groups",
|
||||
"version": "0.1.0",
|
||||
"description": "Example Description. Package. Change me in package.json",
|
||||
"main": "dist/node/index.js",
|
||||
"scripts": {
|
||||
"prepare": "tsc --build && webpack-cli --env production"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@clusterio/lib": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@clusterio/lib": "workspace:*",
|
||||
"@clusterio/web_ui": "workspace:*",
|
||||
"@types/fs-extra": "^11.0.1",
|
||||
"@types/node": "^20.4.5",
|
||||
"@types/react": "^18.2.21",
|
||||
"antd": "^5.13.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"typescript": "^5.5.3",
|
||||
"webpack": "^5.88.2",
|
||||
"webpack-cli": "^5.1.4",
|
||||
"webpack-merge": "^5.9.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sinclair/typebox": "^0.30.4",
|
||||
"fs-extra": "^11.2.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"keywords": [
|
||||
"clusterio",
|
||||
"factorio"
|
||||
]
|
||||
}
|
||||
8
exp_groups/tsconfig.browser.json
Normal file
8
exp_groups/tsconfig.browser.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.browser.json",
|
||||
"references": [
|
||||
{ "path": "../../../packages/lib/tsconfig.browser.json" },
|
||||
{ "path": "../../../packages/web_ui/tsconfig.browser.json" },
|
||||
],
|
||||
"include": [ "web/**/*.tsx", "web/**/*.ts", "messages.ts", "package.json" ],
|
||||
}
|
||||
7
exp_groups/tsconfig.json
Normal file
7
exp_groups/tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.browser.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
8
exp_groups/tsconfig.node.json
Normal file
8
exp_groups/tsconfig.node.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.node.json",
|
||||
"references": [
|
||||
{ "path": "../../../packages/lib/tsconfig.node.json" },
|
||||
],
|
||||
"include": ["./**/*.ts"],
|
||||
"exclude": ["test/*", "./dist/*"],
|
||||
}
|
||||
129
exp_groups/web/components/groupTree.tsx
Normal file
129
exp_groups/web/components/groupTree.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Tree } from 'antd';
|
||||
import type { TreeDataNode, TreeProps } from 'antd';
|
||||
|
||||
const defaultData: TreeDataNode[] = [
|
||||
{
|
||||
title: "Group 1",
|
||||
key: "G-1",
|
||||
icon: false,
|
||||
children: [
|
||||
{
|
||||
title: "Role 1",
|
||||
key: "R-1"
|
||||
},
|
||||
{
|
||||
title: "Role 2",
|
||||
key: "R-2"
|
||||
},
|
||||
{
|
||||
title: "Role 3",
|
||||
key: "R-3"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
title: "Group 2",
|
||||
key: "G-2",
|
||||
icon: false,
|
||||
children: [
|
||||
{
|
||||
title: "Role 4",
|
||||
key: "R-4"
|
||||
},
|
||||
{
|
||||
title: "Role 5",
|
||||
key: "R-5"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
title: "Default",
|
||||
key: "G-3",
|
||||
icon: false,
|
||||
children: [
|
||||
{
|
||||
title: "Role 6",
|
||||
key: "R-6"
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
export function GroupTree() {
|
||||
const [gData, setGData] = useState(defaultData);
|
||||
|
||||
const onDrop: TreeProps['onDrop'] = (info) => {
|
||||
const dropKey = info.node.key;
|
||||
const dragKey = info.dragNode.key;
|
||||
const dropPos = info.node.pos.split('-');
|
||||
const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]); // the drop position relative to the drop node, inside 0, top -1, bottom 1
|
||||
|
||||
const findKey = (
|
||||
data: TreeDataNode[],
|
||||
key: React.Key,
|
||||
callback: (node: TreeDataNode, i: number, data: TreeDataNode[]) => void,
|
||||
) => {
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
if (data[i].key === key) {
|
||||
return callback(data[i], i, data);
|
||||
}
|
||||
if (data[i].children) {
|
||||
findKey(data[i].children!, key, callback);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const data = [...gData]
|
||||
|
||||
// Find dragObject
|
||||
let dragObj: TreeDataNode;
|
||||
findKey(data, dragKey, (item, index, arr) => {
|
||||
arr.splice(index, 1);
|
||||
dragObj = item;
|
||||
});
|
||||
|
||||
if (!info.dropToGap) {
|
||||
// Drop on the content
|
||||
findKey(data, dropKey, (item) => {
|
||||
item.children = item.children || [];
|
||||
// where to insert. New item was inserted to the start of the array in this example, but can be anywhere
|
||||
item.children.unshift(dragObj);
|
||||
});
|
||||
} else {
|
||||
let ar: TreeDataNode[] = [];
|
||||
let i: number;
|
||||
findKey(data, dropKey, (_item, index, arr) => {
|
||||
ar = arr;
|
||||
i = index;
|
||||
});
|
||||
if (dropPosition === -1) {
|
||||
// Drop on the top of the drop node
|
||||
ar.splice(i!, 0, dragObj!);
|
||||
} else {
|
||||
// Drop on the bottom of the drop node
|
||||
ar.splice(i! + 1, 0, dragObj!);
|
||||
}
|
||||
}
|
||||
|
||||
setGData(data)
|
||||
};
|
||||
|
||||
const allowDrop: TreeProps['allowDrop'] = ({dragNode, dropNode, dropPosition}) => {
|
||||
const dragType = (dragNode.key as string).charAt(0);
|
||||
const dropType = (dropNode.key as string).charAt(0);
|
||||
return dropType === dragType && dropPosition != 0 || dragType === "R" && dropType === "G" && dropPosition == 0
|
||||
}
|
||||
|
||||
return (
|
||||
<Tree
|
||||
className="draggable-tree"
|
||||
defaultExpandAll={true}
|
||||
draggable
|
||||
blockNode
|
||||
onDrop={onDrop}
|
||||
allowDrop={allowDrop}
|
||||
treeData={gData}
|
||||
/>
|
||||
);
|
||||
};
|
||||
82
exp_groups/web/index.tsx
Normal file
82
exp_groups/web/index.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import React, {
|
||||
useContext, useEffect, useState,
|
||||
useCallback, useSyncExternalStore,
|
||||
} from "react";
|
||||
|
||||
// import {
|
||||
//
|
||||
// } from "antd";
|
||||
|
||||
import {
|
||||
BaseWebPlugin, PageLayout, PageHeader, Control, ControlContext, notifyErrorHandler,
|
||||
useInstances,
|
||||
} from "@clusterio/web_ui";
|
||||
|
||||
import { PermissionGroupUpdate, PermissionInstanceId, PermissionStringsUpdate } from "../messages";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
import { GroupTree } from "./components/groupTree";
|
||||
|
||||
function MyTemplatePage() {
|
||||
const control = useContext(ControlContext);
|
||||
const plugin = control.plugins.get("exp_groups") as WebPlugin;
|
||||
const [permissionStrings, permissionStringsSynced] = plugin.usePermissionStrings();
|
||||
const [permissionGroups, permissionGroupsSynced] = plugin.usePermissionGroups();
|
||||
const [instances, instancesSync] = useInstances();
|
||||
|
||||
let [roles, setRoles] = useState<lib.Role[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
control.send(new lib.RoleListRequest()).then(newRoles => {
|
||||
setRoles(newRoles);
|
||||
}).catch(notifyErrorHandler("Error fetching role list"));
|
||||
}, []);
|
||||
|
||||
return <PageLayout nav={[{ name: "exp_groups" }]}>
|
||||
<PageHeader title="exp_groups" />
|
||||
Permission Strings: {String(permissionStringsSynced)} {JSON.stringify([...permissionStrings.values()])} <br/>
|
||||
Permission Groups: {String(permissionGroupsSynced)} {JSON.stringify([...permissionGroups.values()])} <br/>
|
||||
Instances: {String(instancesSync)} {JSON.stringify([...instances.values()].map(instance => [instance.id, instance.name]))} <br/>
|
||||
Roles: {JSON.stringify([...roles.values()].map(role => [role.id, role.name]))} <br/>
|
||||
<GroupTree/>
|
||||
</PageLayout>;
|
||||
}
|
||||
|
||||
export class WebPlugin extends BaseWebPlugin {
|
||||
permissionStrings = new lib.EventSubscriber(PermissionStringsUpdate, this.control);
|
||||
permissionGroups = new lib.EventSubscriber(PermissionGroupUpdate, this.control);
|
||||
|
||||
async init() {
|
||||
this.pages = [
|
||||
{
|
||||
path: "/exp_groups",
|
||||
sidebarName: "exp_groups",
|
||||
permission: "exp_groups.list",
|
||||
content: <MyTemplatePage/>,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
useInstancePermissionStrings(instanceId?: PermissionInstanceId) {
|
||||
const [permissionStrings, synced] = this.usePermissionStrings();
|
||||
return [instanceId !== undefined ? permissionStrings.get(instanceId) : undefined, synced] as const;
|
||||
}
|
||||
|
||||
usePermissionStrings() {
|
||||
const control = useContext(ControlContext);
|
||||
const subscribe = useCallback((callback: () => void) => this.permissionStrings.subscribe(callback), [control]);
|
||||
return useSyncExternalStore(subscribe, () => this.permissionStrings.getSnapshot());
|
||||
}
|
||||
|
||||
useInstancePermissionGroups(instanceId?: PermissionInstanceId) {
|
||||
const [permissionGroups, synced] = this.usePermissionGroups();
|
||||
return [instanceId !== undefined ? [...permissionGroups.values()].filter(group => group.instanceId === instanceId) : undefined, synced] as const;
|
||||
}
|
||||
|
||||
usePermissionGroups() {
|
||||
const control = useContext(ControlContext);
|
||||
const subscribe = useCallback((callback: () => void) => this.permissionGroups.subscribe(callback), [control]);
|
||||
return useSyncExternalStore(subscribe, () => this.permissionGroups.getSnapshot());
|
||||
}
|
||||
}
|
||||
32
exp_groups/webpack.config.js
Normal file
32
exp_groups/webpack.config.js
Normal file
@@ -0,0 +1,32 @@
|
||||
"use strict";
|
||||
const path = require("path");
|
||||
const webpack = require("webpack");
|
||||
const { merge } = require("webpack-merge");
|
||||
|
||||
const common = require("@clusterio/web_ui/webpack.common");
|
||||
|
||||
module.exports = (env = {}) => merge(common(env), {
|
||||
context: __dirname,
|
||||
entry: "./web/index.tsx",
|
||||
output: {
|
||||
path: path.resolve(__dirname, "dist", "web"),
|
||||
},
|
||||
plugins: [
|
||||
new webpack.container.ModuleFederationPlugin({
|
||||
name: "exp_groups",
|
||||
library: { type: "window", name: "plugin_exp_groups" },
|
||||
exposes: {
|
||||
"./": "./index.ts",
|
||||
"./package.json": "./package.json",
|
||||
"./web": "./web/index.tsx",
|
||||
},
|
||||
shared: {
|
||||
"@clusterio/lib": { import: false },
|
||||
"@clusterio/web_ui": { import: false },
|
||||
"antd": { import: false },
|
||||
"react": { import: false },
|
||||
"react-dom": { import: false },
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
8
exp_util/index.ts
Normal file
8
exp_util/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
export const plugin: lib.PluginDeclaration = {
|
||||
name: "exp_util",
|
||||
title: "ExpGaming Module Utilities",
|
||||
description: "Provides extensions and overrides of base Lua library functions, and provides utility modules for improved module compatibly",
|
||||
instanceEntrypoint: "./dist/node/instance",
|
||||
};
|
||||
7
exp_util/instance.ts
Normal file
7
exp_util/instance.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { BaseInstancePlugin } from "@clusterio/host";
|
||||
|
||||
export class InstancePlugin extends BaseInstancePlugin {
|
||||
// This class is empty because an instance plugin must be defined for a module to be injected
|
||||
// This requirement may change in the future to allow for standalone modules
|
||||
}
|
||||
326
exp_util/module/async.lua
Normal file
326
exp_util/module/async.lua
Normal file
@@ -0,0 +1,326 @@
|
||||
--[[-- Util Module - Async
|
||||
- Provides a method of spreading work across multiple ticks and running functions at a later time
|
||||
@core Async
|
||||
@alias Async
|
||||
|
||||
@usage-- Bypass permission groups
|
||||
-- This is a simple example, you should have some kind of validation to prevent security flaws
|
||||
local function setAdmin(player, state)
|
||||
player.admin = state
|
||||
end
|
||||
|
||||
local setAdminAsync = Async.register(setAdmin)
|
||||
setAdminAsync(game.players[1], true)
|
||||
|
||||
@usage-- Functions stored in global table
|
||||
-- This can be used to create run time configurable callbacks, although this is not recommended
|
||||
global.myCallback = Async.register(function()
|
||||
game.print("I got called!")
|
||||
end)
|
||||
|
||||
-- The function can be called just like any other function
|
||||
global.myCallback()
|
||||
|
||||
@usage-- Creating singleton tasks (best used with global data)
|
||||
-- This allows you to split large tasks across multiple ticks to prevent lag
|
||||
local myTask = Async.register(function(remainingWork)
|
||||
game.print("Working... " .. remainingWork)
|
||||
if remainingWork > 0 then
|
||||
return Async.status.continue(remainingWork - 1)
|
||||
end
|
||||
end)
|
||||
|
||||
myTask:start_task(10) -- Queues the task
|
||||
myTask:start_task(10) -- Does nothing, task is already running
|
||||
myTask:start_now(10) -- Ignores the already running instance and starts a second one
|
||||
|
||||
@usage-- Actions with variable delays
|
||||
-- on_nth_tick is great for consistent delays, but tasks allow for variable delays
|
||||
local linearBackoff = Async.register(function(startingDelay, remainingWork)
|
||||
game.print("Working... " .. remainingWork)
|
||||
if remainingWork > 0 then
|
||||
local newDelay = startingDelay + 1
|
||||
return Async.status.delay(newDelay, newDelay, remainingWork - 1)
|
||||
end
|
||||
end)
|
||||
|
||||
linearBackoff(1, 10)
|
||||
|
||||
@usage-- Getting return values
|
||||
-- you can capture the return values of an async function using the event
|
||||
local fillTableAsync = Async.register(function(tbl, val, remainingWork)
|
||||
table.insert(tbl, val)
|
||||
if remainingWork > 0 then
|
||||
return Async.status.continue(tbl, val, remainingWork - 1)
|
||||
else
|
||||
return Async.status.complete(tbl)
|
||||
end
|
||||
end)
|
||||
|
||||
local function on_function_complete(event)
|
||||
if event.async_id ~= fillTableAsync.id then return end
|
||||
local filledTable = table.unpack(event.return_values)
|
||||
game.print("Table has length of " .. #filledTable)
|
||||
end
|
||||
|
||||
fillTableAsync({}, "foo", 10) -- Puts 10 lots of foo into the table
|
||||
|
||||
]]
|
||||
|
||||
local Clustorio = require("modules/clusterio/api")
|
||||
local ExpUtil = require("modules.exp_util.common") --- @dep exp_util.common
|
||||
|
||||
local Async = {
|
||||
status = {}, -- Stores the allowed return types from a async function
|
||||
events = {}, -- Stores all event handlers for this module
|
||||
_prototype = {}, -- Prototype of the async function type
|
||||
_queue_pressure = {}, -- Stores the count of each function in the queue to avoid queue iteration during start_task
|
||||
_functions = {}, -- Stores a reference to all registered functions
|
||||
--- Raised when any async function has finished execution
|
||||
-- @event on_function_complete
|
||||
-- @tparam AsyncFunction async_id The function which finished execution, comparable to the return of register
|
||||
-- @tparam table return_values An array representing the values returned by the completed function
|
||||
on_function_complete = script.generate_event_name()
|
||||
}
|
||||
|
||||
Async._metatable = {
|
||||
__call = function(self, ...) Async._prototype.start_soon(self, ...) end,
|
||||
__index = Async._prototype,
|
||||
__class = "AsyncFunction"
|
||||
}
|
||||
|
||||
script.register_metatable("AsyncFunction", Async._metatable)
|
||||
|
||||
--- Globals
|
||||
local async_next -- Stores a queue of async functions to be executed on the next tick
|
||||
local async_queue -- Stores a queue of async functions to be executed on a later tick
|
||||
local on_tick_mutex = false -- It is not safe to modify the globals while this value is true
|
||||
|
||||
--- Insert an item into the priority queue
|
||||
local function add_to_queue(pending)
|
||||
local tick = pending.tick
|
||||
for index = #async_queue, 1, -1 do
|
||||
if async_queue[index].tick >= tick then
|
||||
async_queue[index + 1] = pending
|
||||
return
|
||||
else
|
||||
async_queue[index + 1] = async_queue[index]
|
||||
end
|
||||
end
|
||||
async_queue[1] = pending
|
||||
end
|
||||
|
||||
--- Static Methods.
|
||||
-- Static methods of the class
|
||||
-- @section async-static
|
||||
|
||||
--- Register a new async function
|
||||
-- @tparam function func The function which becomes the async function
|
||||
-- @treturn AsyncFunction The newly registered async function
|
||||
function Async.register(func)
|
||||
ExpUtil.assert_not_runtime()
|
||||
ExpUtil.assert_argument_type(func, "function", 1, "func")
|
||||
|
||||
local id = ExpUtil.get_function_name(func)
|
||||
Async._functions[id] = func
|
||||
Async._queue_pressure[id] = 0
|
||||
|
||||
return setmetatable({ id = id }, Async._metatable)
|
||||
end
|
||||
|
||||
--- Prototype Methods.
|
||||
-- Prototype methods of the class instances
|
||||
-- @section async-prototype
|
||||
|
||||
--- Run an async function on the next tick, this is the default and can be used to bypass permission groups
|
||||
-- @param ... The arguments to call the function with
|
||||
function Async._prototype:start_soon(...)
|
||||
assert(not on_tick_mutex, "Cannot queue new async call during execution of another")
|
||||
assert(Async._functions[self.id], "Async function is not registered")
|
||||
Async._queue_pressure[self.id] = Async._queue_pressure[self.id] + 1
|
||||
|
||||
async_next[#async_next + 1] = {
|
||||
id = self.id,
|
||||
args = {...}
|
||||
}
|
||||
end
|
||||
|
||||
--- Run an async function after the given number of ticks
|
||||
-- @tparam number ticks The number of ticks to call the function after
|
||||
-- @param ... The arguments to call the function with
|
||||
function Async._prototype:start_after(ticks, ...)
|
||||
ExpUtil.assert_argument_type(ticks, "number", 1, "ticks")
|
||||
assert(not on_tick_mutex, "Cannot queue new async call during execution of another")
|
||||
assert(Async._functions[self.id], "Async function is not registered")
|
||||
Async._queue_pressure[self.id] = Async._queue_pressure[self.id] + 1
|
||||
|
||||
add_to_queue({
|
||||
id = self.id,
|
||||
args = {...},
|
||||
tick = game.tick + ticks
|
||||
})
|
||||
end
|
||||
|
||||
--- Run an async function on the next tick if the function is not already queued, allows singleton task/thread behaviour
|
||||
-- @param ... The arguments to call the function with
|
||||
function Async._prototype:start_task(...)
|
||||
assert(not on_tick_mutex, "Cannot queue new async call during execution of another")
|
||||
assert(Async._functions[self.id], "Async function is not registered")
|
||||
if Async._queue_pressure[self.id] > 0 then return end
|
||||
self:start_soon(...)
|
||||
end
|
||||
|
||||
--- Run an async function on this tick, then queue it based on its return value
|
||||
-- @param ... The arguments to call the function with
|
||||
function Async._prototype:start_now(...)
|
||||
assert(not on_tick_mutex, "Cannot queue new async call during execution of another")
|
||||
assert(Async._functions[self.id], "Async function is not registered")
|
||||
local status, rtn1, rtn2 = Async._functions[self.id](...)
|
||||
if status == Async.status.continue then
|
||||
self:start_soon(table.unpack(rtn1))
|
||||
elseif status == Async.status.delay then
|
||||
self:start_after(rtn1, table.unpack(rtn2))
|
||||
elseif status == Async.status.complete or status == nil then
|
||||
-- The function has finished execution, raise the custom event
|
||||
script.raise_event(Async.on_function_complete, {
|
||||
event = Async.on_function_complete,
|
||||
tick = game.tick,
|
||||
async_id = self.id,
|
||||
returned = rtn1
|
||||
})
|
||||
else
|
||||
error("Async function " .. self.id .. " returned an invalid status: " .. table.inspect(status))
|
||||
end
|
||||
end
|
||||
|
||||
--- Status Returns.
|
||||
-- Return values used by async functions
|
||||
-- @section async-status
|
||||
|
||||
local empty_table = setmetatable({}, {
|
||||
__index = function() error("Field 'Returned' is Immutable") end
|
||||
}) -- File scope to allow for reuse
|
||||
|
||||
--- Default status, will raise on_function_complete
|
||||
-- @param ... The return value of the async call
|
||||
function Async.status.complete(...)
|
||||
if ... == nil then
|
||||
return Async.status.complete, empty_table
|
||||
end
|
||||
return Async.status.complete, {...}
|
||||
end
|
||||
|
||||
--- Will queue the function to be called again on the next tick using the new arguments
|
||||
-- @param ... The arguments to call the function with
|
||||
function Async.status.continue(...)
|
||||
if ... == nil then
|
||||
return Async.status.continue, empty_table
|
||||
end
|
||||
return Async.status.continue, {...}
|
||||
end
|
||||
|
||||
--- Will queue the function to be called again on a later tick using the new arguments
|
||||
-- @param ... The arguments to call the function with
|
||||
function Async.status.delay(ticks, ...)
|
||||
ExpUtil.assert_argument_type(ticks, "number", 1, "ticks")
|
||||
if ... == nil then
|
||||
return Async.status.continue, ticks, empty_table
|
||||
end
|
||||
return Async.status.delay, ticks, {...}
|
||||
end
|
||||
|
||||
--- Executes an async function and processes the return value
|
||||
local function exec(pending, tick, new_next, new_queue)
|
||||
local status, rtn1, rtn2 = Async._functions[pending.id](table.unpack(pending.args))
|
||||
if status == Async.status.continue then
|
||||
new_next[#new_next + 1] = pending
|
||||
pending.tick = nil
|
||||
pending.args = rtn1
|
||||
elseif status == Async.status.delay then
|
||||
new_queue[#new_queue + 1] = pending
|
||||
pending.tick = tick + rtn1
|
||||
pending.args = rtn2
|
||||
elseif status == Async.status.complete or status == nil then
|
||||
-- The function has finished execution, raise the custom event
|
||||
Async._queue_pressure[pending.id] = Async._queue_pressure[pending.id] - 1
|
||||
script.raise_event(Async.on_function_complete, {
|
||||
event = Async.on_function_complete,
|
||||
tick = tick,
|
||||
async_id = pending.id,
|
||||
returned = rtn1
|
||||
})
|
||||
else
|
||||
error("Async function " .. pending.id .. " returned an invalid status: " .. table.inspect(status))
|
||||
end
|
||||
end
|
||||
|
||||
local new_next, new_queue = {}, {} -- File scope to allow for reuse
|
||||
--- Each tick, run all next tick functions, then check if any in the queue need to be executed
|
||||
local function on_tick()
|
||||
if async_next == nil then return end
|
||||
local tick = game.tick
|
||||
|
||||
-- Execute all pending functions
|
||||
for index = 1, #async_next, 1 do
|
||||
exec(async_next[index], tick, new_next, new_queue)
|
||||
async_next[index] = nil
|
||||
end
|
||||
for index = #async_queue, 1, -1 do
|
||||
local pending = async_queue[index]
|
||||
if pending.tick > tick then
|
||||
break;
|
||||
end
|
||||
exec(pending, tick, new_next, new_queue)
|
||||
async_queue[index] = nil
|
||||
end
|
||||
|
||||
-- Queue any functions that did not complete
|
||||
for index = 1, #new_next, 1 do
|
||||
async_next[index] = new_next[index]
|
||||
new_next[index] = nil
|
||||
end
|
||||
for index = 1, #new_queue, 1 do
|
||||
add_to_queue(new_next[index])
|
||||
new_next[index] = nil
|
||||
end
|
||||
end
|
||||
|
||||
--- On load, check the queue status and update the pressure values
|
||||
local function on_load()
|
||||
if global.exp_async_next == nil then return end
|
||||
async_next = global.exp_async_next
|
||||
async_queue = global.exp_async_queue
|
||||
for _, pending in ipairs(async_next) do
|
||||
local count = Async._queue_pressure[pending.id]
|
||||
if count == nil then
|
||||
log("Warning: Pending async function missing after load: " .. pending.id)
|
||||
Async._functions[pending.id] = function() end -- NOP
|
||||
count = 0
|
||||
end
|
||||
Async._queue_pressure[pending.id] = count + 1
|
||||
end
|
||||
for _, pending in ipairs(async_queue) do
|
||||
local count = Async._queue_pressure[pending.id]
|
||||
if count == nil then
|
||||
log("Warning: Pending async function missing after load: " .. pending.id)
|
||||
Async._functions[pending.id] = function() end -- NOP
|
||||
count = 0
|
||||
end
|
||||
Async._queue_pressure[pending.id] = count + 1
|
||||
end
|
||||
end
|
||||
|
||||
--- On server startup initialise the global data
|
||||
local function on_server_startup()
|
||||
if global.exp_async_next == nil then
|
||||
global.exp_async_next = {}
|
||||
global.exp_async_queue = {}
|
||||
end
|
||||
on_load()
|
||||
end
|
||||
|
||||
Async.on_load = on_load
|
||||
Async.on_init = on_server_startup
|
||||
Async.events[defines.events.on_tick] = on_tick
|
||||
Async.events[Clustorio.events.on_server_startup] = on_server_startup
|
||||
return Async
|
||||
384
exp_util/module/common.lua
Normal file
384
exp_util/module/common.lua
Normal file
@@ -0,0 +1,384 @@
|
||||
--[[-- Util Module - Common
|
||||
- Adds some commonly used functions used in many modules
|
||||
@core Common
|
||||
@alias Common
|
||||
]]
|
||||
|
||||
local assert = assert
|
||||
--local getlocal = debug.getlocal
|
||||
--local getupvalue = debug.getupvalue
|
||||
local getinfo = debug.getinfo
|
||||
local traceback = debug.traceback
|
||||
local floor = math.floor
|
||||
local concat = table.concat
|
||||
|
||||
local Common = {
|
||||
--- A large mapping of colour rgb values by their common name
|
||||
color = require 'modules.exp_util.include.color'
|
||||
}
|
||||
|
||||
--- Raise an error if we are not in runtime
|
||||
function Common.assert_not_runtime()
|
||||
assert(package.lifecycle ~= package.lifecycle_stage.runtime, "Can not be called during runtime")
|
||||
end
|
||||
|
||||
--[[local assert_not_closure_fmt = "Can not be called with the closure %s at runtime"
|
||||
--- Raise an error if a function is a closure and we are in runtime
|
||||
-- @tparam function func The function to assert is not a closure if we are in runtime
|
||||
function Common.assert_not_closure(func)
|
||||
assert(package.lifecycle ~= package.lifecycle_stage.runtime, "Can not be called during runtime")
|
||||
local info = getinfo(2, "nu")
|
||||
for i = 1, info.nups do
|
||||
if getupvalue(func, i) ~= "_ENV" then
|
||||
error(assert_not_closure_fmt:format(info.name or "<anonymous>"))
|
||||
end
|
||||
end
|
||||
end]]
|
||||
|
||||
local assert_type_fmt = "%s expected to be of type %s but got %s"
|
||||
--- Raise an error if the type of a value is not as expected
|
||||
-- @param value The value to assert the type of
|
||||
-- @tparam string type_name The name of the type that value is expected to be
|
||||
-- @tparam[opt=Value] string value_name The name of the value being tested, this is included in the error message
|
||||
function Common.assert_type(value, type_name, value_name)
|
||||
if value == nil or type(value) ~= type_name then
|
||||
error(assert_type_fmt:format(value_name or "Value", type_name, type(value)), 2)
|
||||
end
|
||||
end
|
||||
|
||||
local assert_argument_fmt = "Bad argument #%d to %s; %s expected to be of type %s but got %s"
|
||||
--[[--- Raise an error if the type of any argument is not as expected, can be costly, for frequent callers see assert_argument_type
|
||||
-- @tparam string ... The type for each argument of the calling function
|
||||
function Common.assert_argument_types(...)
|
||||
local arg_types = {...}
|
||||
local info = getinfo(2, "nu")
|
||||
for arg_index = 1, info.nparams do
|
||||
local arg_name, arg_value = getlocal(2, arg_index)
|
||||
if arg_types[arg_index] and (arg_value == nil or type(arg_value) ~= arg_types[arg_index]) then
|
||||
error(assert_argument_fmt:format(arg_index, info.name or "<anonymous>", arg_name, arg_types[arg_index]), 2)
|
||||
end
|
||||
end
|
||||
end]]
|
||||
|
||||
--- Raise an error if the type of any argument is not as expected, more performant than assert_argument_types, but requires more manual input
|
||||
-- @param arg_value The argument to assert the type of
|
||||
-- @tparam string type_name The name of the type that value is expected to be
|
||||
-- @tparam number arg_index The index of the argument being tested, this is included in the error message
|
||||
-- @tparam[opt=Argument] string arg_name The name of the argument being tested, this is included in the error message
|
||||
function Common.assert_argument_type(arg_value, type_name, arg_index, arg_name)
|
||||
if arg_value == nil or type(arg_value) ~= type_name then
|
||||
local func_name = getinfo(2, "n").name or "<anonymous>"
|
||||
error(assert_argument_fmt:format(arg_index, func_name, arg_name or "Argument", type_name), 2)
|
||||
end
|
||||
end
|
||||
|
||||
--- Write a luu table to a file as a json string, note the defaults are different to game.write_file
|
||||
-- @tparam string path The path to write the json to
|
||||
-- @tparam table value The table to write to file
|
||||
-- @tparam[opt=false] boolean overwrite When true the json replaces the full contents of the file
|
||||
-- @tparam[opt=0] number player_index The player's machine to write on, -1 means all, 0 means host only
|
||||
function Common.write_json(path, tbl, overwrite, player_index)
|
||||
if player_index == -1 then
|
||||
return game.write_file(path, game.table_to_json(tbl).."\n", not overwrite)
|
||||
end
|
||||
return game.write_file(path, game.table_to_json(tbl).."\n", not overwrite, player_index or 0)
|
||||
end
|
||||
|
||||
--- Clear a file by replacing its contents with an empty string
|
||||
-- @tparam string path The path to clear the contents of
|
||||
-- @tparam[opt=0] number player_index The player's machine to write on, -1 means all, 0 means host only
|
||||
function Common.clear_file(path, player_index)
|
||||
if player_index == -1 then
|
||||
return game.write_file(path, "", false)
|
||||
end
|
||||
return game.write_file(path, "", false, player_index or 0)
|
||||
end
|
||||
|
||||
--- Same as require but will return nil if the module does not exist, all other errors will propagate to the caller
|
||||
-- @tparam string module_path The path to the module to require, same syntax as normal require
|
||||
-- @return The contents of the module, or nil if the module does not exist or did not return a value
|
||||
function Common.optional_require(module_path)
|
||||
local success, rtn = xpcall(require, traceback, module_path)
|
||||
if success then return rtn end
|
||||
if not rtn:find("not found; no such file", 0, true) then
|
||||
error(rtn, 2)
|
||||
end
|
||||
end
|
||||
|
||||
--- Returns a desync sale filepath for a given stack frame, default is the current file
|
||||
-- @tparam number level The level of the stack to get the file of, a value of 1 is the caller of this function
|
||||
-- @treturn string The relative filepath of the given stack frame
|
||||
function Common.safe_file_path(level)
|
||||
level = level or 1
|
||||
return getinfo(level+1, 'S').source:match('^.+/currently%-playing/(.+)$'):sub(1, -5)
|
||||
end
|
||||
|
||||
--- Returns the name of your module, this assumes your module is stored within /modules (which it is for clustorio)
|
||||
-- @tparam[opt=1] number level The level of the stack to get the module of, a value of 1 is the caller of this function
|
||||
-- @treturn string The name of the module at the given stack frame
|
||||
function Common.get_module_name(level)
|
||||
local file_within_module = getinfo((level or 1)+1, 'S').source:match('^.+/currently%-playing/modules/(.+)$'):sub(1, -5)
|
||||
local next_slash = file_within_module:find("/")
|
||||
if next_slash then
|
||||
return file_within_module:sub(1, next_slash-1)
|
||||
else
|
||||
return file_within_module
|
||||
end
|
||||
end
|
||||
|
||||
--- Returns the name of a function in a safe and consistent format
|
||||
-- @tparam number|function func The level of the stack to get the name of, a value of 1 is the caller of this function
|
||||
-- @tparam boolean raw When true there will not be any < > around the name
|
||||
-- @treturn string The name of the function at the given stack frame or provided as an argument
|
||||
function Common.get_function_name(func, raw)
|
||||
local debug_info = getinfo(func, "Sn")
|
||||
local safe_source = debug_info.source:match('^.+/currently%-playing/(.+)$')
|
||||
local file_name = safe_source and safe_source:sub(1, -5) or debug_info.source
|
||||
local func_name = debug_info.name or debug_info.linedefined
|
||||
if raw then return file_name .. ":" .. func_name end
|
||||
return "<" .. file_name .. ":" .. func_name .. ">"
|
||||
end
|
||||
|
||||
--- Attempt a simple autocomplete search from a set of options
|
||||
-- @tparam table options The table representing the possible options which can be selected
|
||||
-- @tparam string input The user input string which should be matched to an option
|
||||
-- @tparam[opt=false] boolean use_key When true the keys will be searched, when false the values will be searched
|
||||
-- @tparam[opt=false] boolean rtn_key When true the selected key will be returned, when false the selected value will be returned
|
||||
-- @return The selected key or value which first matches the input text
|
||||
function Common.auto_complete(options, input, use_key, rtn_key)
|
||||
input = input:lower()
|
||||
if use_key then
|
||||
for k, v in pairs(options) do
|
||||
if k:lower():find(input) then
|
||||
if rtn_key then return k else return v end
|
||||
end
|
||||
end
|
||||
else
|
||||
for k, v in pairs(options) do
|
||||
if v:lower():find(input) then
|
||||
if rtn_key then return k else return v end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Formats any value into a safe representation, useful with table.insert
|
||||
-- @param value The value to be formated
|
||||
-- @return The formated version of the value
|
||||
-- @return True if value is a locale string, nil otherwise
|
||||
function Common.safe_value(value)
|
||||
if type(value) == "table" or type(value) == "userdata" then
|
||||
if type(value.__self) == "userdata" or type(value) == "userdata" then
|
||||
local success, rtn = pcall(function() -- some userdata doesnt contain "valid"
|
||||
if value.valid then -- userdata
|
||||
return "<userdata:"..value.object_name..">"
|
||||
else -- invalid userdata
|
||||
return "<userdata:"..value.object_name..":invalid>"
|
||||
end
|
||||
end)
|
||||
return success and rtn or "<userdata:"..value.object_name..">"
|
||||
elseif type(value[1]) == "string" and string.find(value[1], ".+[.].+") and not string.find(value[1], "%s") then
|
||||
return value, true -- locale string
|
||||
elseif tostring(value) ~= "table" then
|
||||
return tostring(value) -- has __tostring metamethod
|
||||
else -- plain table
|
||||
return value
|
||||
end
|
||||
elseif type(value) == "function" then -- function
|
||||
return "<function:"..Common.get_function_name(value, true)..">"
|
||||
else -- not: table, userdata, or function
|
||||
return tostring(value)
|
||||
end
|
||||
end
|
||||
|
||||
--- Formats any value to be presented in a safe and human readable format
|
||||
-- @param value The value to be formated
|
||||
-- @param[opt] tableAsJson If table values should be returned as json
|
||||
-- @param[opt] maxLineCount If table newline count exceeds provided then it will be inlined
|
||||
-- @return The formated version of the value
|
||||
function Common.format_any(value, tableAsJson, maxLineCount)
|
||||
local formatted, is_locale_string = Common.safe_value(value)
|
||||
if type(formatted) == "table" and not is_locale_string then
|
||||
if tableAsJson then
|
||||
local success, rtn = pcall(game.table_to_json, value)
|
||||
if success then return rtn end
|
||||
end
|
||||
local rtn = table.inspect(value, {depth=5, indent=' ', newline='\n', process=Common.safe_value})
|
||||
if maxLineCount == nil or select(2, rtn:gsub("\n", "")) < maxLineCount then return rtn end
|
||||
return table.inspect(value, {depth=5, indent='', newline='', process=Common.safe_value})
|
||||
end
|
||||
return formatted
|
||||
end
|
||||
|
||||
--- Format a tick value into one of a selection of pre-defined formats (short, long, clock)
|
||||
-- @tparam number ticks The number of ticks which will be represented, can be any duration or time value
|
||||
-- @tparam string format The format to display, must be one of: short, long, clock
|
||||
-- @tparam[opt] table units A table selecting which units should be displayed, options are: days, hours, minutes, seconds
|
||||
-- @treturn string The ticks formatted into a string of the desired format
|
||||
function Common.format_time(ticks, format, units)
|
||||
units = units or { days = false, hours = true, minutes = true, seconds = false }
|
||||
local rtn_days, rtn_hours, rtn_minutes, rtn_seconds = "--", "--", "--", "--"
|
||||
|
||||
if ticks ~= nil then
|
||||
-- Calculate the values to be determine the display values
|
||||
local max_days, max_hours, max_minutes, max_seconds = ticks/5184000, ticks/216000, ticks/3600, ticks/60
|
||||
local days, hours = max_days, max_hours-floor(max_days)*24
|
||||
local minutes, seconds = max_minutes-floor(max_hours)*60, max_seconds-floor(max_minutes)*60
|
||||
|
||||
-- Calculate rhw units to be displayed
|
||||
rtn_days, rtn_hours, rtn_minutes, rtn_seconds = floor(days), floor(hours), floor(minutes), floor(seconds)
|
||||
if not units.days then rtn_hours = rtn_hours + rtn_days*24 end
|
||||
if not units.hours then rtn_minutes = rtn_minutes + rtn_hours*60 end
|
||||
if not units.minutes then rtn_seconds = rtn_seconds + rtn_minutes*60 end
|
||||
end
|
||||
|
||||
local rtn = {}
|
||||
if format == "clock" then
|
||||
-- Example 12:34:56 or --:--:--
|
||||
if units.days then rtn[#rtn+1] = rtn_days end
|
||||
if units.hours then rtn[#rtn+1] = rtn_hours end
|
||||
if units.minutes then rtn[#rtn+1] = rtn_minutes end
|
||||
if units.seconds then rtn[#rtn+1] = rtn_seconds end
|
||||
return concat(rtn, ":")
|
||||
elseif format == "short" then
|
||||
-- Example 12d 34h 56m or --d --h --m
|
||||
if units.days then rtn[#rtn+1] = rtn_days.."d" end
|
||||
if units.hours then rtn[#rtn+1] = rtn_hours.."h" end
|
||||
if units.minutes then rtn[#rtn+1] = rtn_minutes.."m" end
|
||||
if units.seconds then rtn[#rtn+1] = rtn_seconds.."s" end
|
||||
return concat(rtn, " ")
|
||||
else
|
||||
-- Example 12 days, 34 hours, and 56 minutes or -- days, -- hours, and -- minutes
|
||||
if units.days then rtn[#rtn+1] = rtn_days.." days" end
|
||||
if units.hours then rtn[#rtn+1] = rtn_hours.." hours" end
|
||||
if units.minutes then rtn[#rtn+1] = rtn_minutes.." minutes" end
|
||||
if units.seconds then rtn[#rtn+1] = rtn_seconds.." seconds" end
|
||||
rtn[#rtn] = "and "..rtn[#rtn]
|
||||
return concat(rtn, ", ")
|
||||
end
|
||||
end
|
||||
|
||||
--- Format a tick value into one of a selection of pre-defined formats (short, long, clock)
|
||||
-- @tparam number ticks The number of ticks which will be represented, can be any duration or time value
|
||||
-- @tparam string format The format to display, must be one of: short, long, clock
|
||||
-- @tparam[opt] table units A table selecting which units should be displayed, options are: days, hours, minutes, seconds
|
||||
-- @treturn LocaleString The ticks formatted into a LocaleString of the desired format
|
||||
function Common.format_locale_time(ticks, format, units)
|
||||
units = units or { days = false, hours = true, minutes = true, seconds = false }
|
||||
local rtn_days, rtn_hours, rtn_minutes, rtn_seconds = "--", "--", "--", "--"
|
||||
|
||||
if ticks ~= nil then
|
||||
-- Calculate the values to be determine the display values
|
||||
local max_days, max_hours, max_minutes, max_seconds = ticks/5184000, ticks/216000, ticks/3600, ticks/60
|
||||
local days, hours = max_days, max_hours-floor(max_days)*24
|
||||
local minutes, seconds = max_minutes-floor(max_hours)*60, max_seconds-floor(max_minutes)*60
|
||||
|
||||
-- Calculate rhw units to be displayed
|
||||
rtn_days, rtn_hours, rtn_minutes, rtn_seconds = floor(days), floor(hours), floor(minutes), floor(seconds)
|
||||
if not units.days then rtn_hours = rtn_hours + rtn_days*24 end
|
||||
if not units.hours then rtn_minutes = rtn_minutes + rtn_hours*60 end
|
||||
if not units.minutes then rtn_seconds = rtn_seconds + rtn_minutes*60 end
|
||||
end
|
||||
|
||||
local rtn = {}
|
||||
local join = ", "
|
||||
if format == "clock" then
|
||||
-- Example 12:34:56 or --:--:--
|
||||
if units.days then rtn[#rtn+1] = rtn_days end
|
||||
if units.hours then rtn[#rtn+1] = rtn_hours end
|
||||
if units.minutes then rtn[#rtn+1] = rtn_minutes end
|
||||
if units.seconds then rtn[#rtn+1] = rtn_seconds end
|
||||
join = { "colon" }
|
||||
elseif format == "short" then
|
||||
-- Example 12d 34h 56m or --d --h --m
|
||||
if units.days then rtn[#rtn+1] = {"?", {"time-symbol-days-short", rtn_days}, rtn_days.."d"} end
|
||||
if units.hours then rtn[#rtn+1] = {"time-symbol-hours-short", rtn_hours} end
|
||||
if units.minutes then rtn[#rtn+1] = {"time-symbol-minutes-short", rtn_minutes} end
|
||||
if units.seconds then rtn[#rtn+1] = {"time-symbol-seconds-short", rtn_seconds} end
|
||||
join = " "
|
||||
else
|
||||
-- Example 12 days, 34 hours, and 56 minutes or -- days, -- hours, and -- minutes
|
||||
if units.days then rtn[#rtn+1] = {"days", rtn_days} end
|
||||
if units.hours then rtn[#rtn+1] = {"hours", rtn_hours} end
|
||||
if units.minutes then rtn[#rtn+1] = {"minutes", rtn_minutes} end
|
||||
if units.seconds then rtn[#rtn+1] = {"seconds", rtn_seconds} end
|
||||
rtn[#rtn] = {"", { "and" }, " ", rtn[#rtn]}
|
||||
end
|
||||
|
||||
local joined = { "" }
|
||||
for k, v in ipairs(rtn) do
|
||||
joined[2*k] = v
|
||||
joined[2*k+1] = join
|
||||
end
|
||||
return joined
|
||||
end
|
||||
|
||||
--- Insert a copy of the given items into the found / created entities. If no entities are found then they will be created if possible.
|
||||
-- @tparam table items The items which are to be inserted into the entities, an array of LuaItemStack
|
||||
-- @tparam LuaSurface surface The surface which will be searched to find the entities
|
||||
-- @tparam table options A table of various optional options similar to find_entities_filtered
|
||||
-- position + radius or area can be used to define a search area on the surface
|
||||
-- type can be used to find all entities of a given type, such as a chest
|
||||
-- name can be used to further specify which entity to insert into, this field is required if entity creation is desired
|
||||
-- allow_creation is a boolean which when true will allow the function to create new entities in order to insert all items
|
||||
-- force is the force which new entities will be created to, the default is the neutral force
|
||||
-- @treturn LuaEntity the last entity that had items inserted into it
|
||||
function Common.insert_item_stacks(items, surface, options)
|
||||
local entities = surface.find_entities_filtered(options)
|
||||
local count, current, last_entity = #entities, 0, nil
|
||||
|
||||
for _, item in ipairs(items) do
|
||||
if item.valid_for_read then
|
||||
local inserted = false
|
||||
|
||||
-- Attempt to insert the items
|
||||
for i = 1, count do
|
||||
local entity = entities[((current+i-1)%count)+1]
|
||||
if entity.can_insert(item) then
|
||||
last_entity = entity
|
||||
current = current + 1
|
||||
entity.insert(item)
|
||||
inserted = true
|
||||
end
|
||||
end
|
||||
|
||||
-- If it was not inserted then a new entity is needed
|
||||
if not inserted then
|
||||
if not options.allow_creation then error("Unable to insert items into a valid entity, consider enabling allow_creation") end
|
||||
if options.name == nil then error("Name must be provided to allow creation of new entities") end
|
||||
|
||||
local position
|
||||
if options.position then
|
||||
position = surface.find_non_colliding_position(options.name, options.position, options.radius, 1, true)
|
||||
elseif options.area then
|
||||
position = surface.find_non_colliding_position_in_box(options.name, options.area, 1, true)
|
||||
else
|
||||
position = surface.find_non_colliding_position(options.name, {0,0}, 0, 1, true)
|
||||
end
|
||||
last_entity = surface.create_entity{name = options.name, position = position, force = options.force or "neutral"}
|
||||
|
||||
count = count + 1
|
||||
entities[count] = last_entity
|
||||
last_entity.insert(item)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return last_entity
|
||||
end
|
||||
|
||||
--- Move the given items into the found / created entities. If no entities are found then they will be created if possible.
|
||||
-- @tparam table items The items which are to be inserted into the entities, an array of LuaItemStack
|
||||
-- @tparam LuaSurface surface The surface which will be searched to find the entities
|
||||
-- @tparam table options A table of various optional options similar to find_entities_filtered
|
||||
-- position + radius or area can be used to define a search area on the surface
|
||||
-- type can be used to find all entities of a given type, such as a chest
|
||||
-- name can be used to further specify which entity to insert into, this field is required if entity creation is desired
|
||||
-- allow_creation is a boolean which when true will allow the function to create new entities in order to insert all items
|
||||
-- @treturn LuaEntity the last entity that had items inserted into it
|
||||
function Common.transfer_item_stacks(inventory, surface, options)
|
||||
Common.insert_item_stacks(inventory, surface, options)
|
||||
inventory.clear()
|
||||
end
|
||||
|
||||
return Common
|
||||
180
exp_util/module/floating_text.lua
Normal file
180
exp_util/module/floating_text.lua
Normal file
@@ -0,0 +1,180 @@
|
||||
--[[-- Util Module - FloatingText
|
||||
- Provides a method of creating floating text and tags in the world
|
||||
@core FloatingText
|
||||
@alias FloatingText
|
||||
|
||||
@usage-- Show player chat message in world
|
||||
local function on_console_chat(event)
|
||||
local player = game.get_player(event.player_index)
|
||||
FloatingText.print_as_player(player, event.message)
|
||||
end
|
||||
|
||||
@usage-- Show player tags above their characters
|
||||
local function on_player_respawned(event)
|
||||
local player = game.get_player(event.player_index)
|
||||
FloatingText.create_tag_as_player(player, player.tag)
|
||||
end
|
||||
|
||||
@usage-- Show placed an entity in alt mode
|
||||
local function on_built_entity(event)
|
||||
local entity = event.created_entity
|
||||
local player = game.get_player(event.player_index)
|
||||
FloatingText.create_tag_above_entity(entity, player.name, player.color, true)
|
||||
end
|
||||
|
||||
]]
|
||||
|
||||
local FloatingText = {}
|
||||
FloatingText.color = require("modules.exp_util.include.color")
|
||||
|
||||
--- Print Messages.
|
||||
-- Short lived messages that last at most a few seconds
|
||||
-- @section floating-text_print
|
||||
|
||||
--- Print floating text at the given position on the given surface
|
||||
-- @tparam LuaSurface surface The surface where the floating text will be created
|
||||
-- @tparam MapPosition position The position to create the floating text at
|
||||
-- @tparam string text The text which will be printed
|
||||
-- @tparam[opt=FloatingText.color.white] Color color The colour to print the text in
|
||||
-- @treturn LuaEntity The floating text entity which was created for the message
|
||||
function FloatingText.print(surface, position, text, color)
|
||||
return surface.create_entity{
|
||||
text = text,
|
||||
name = 'tutorial-flying-text',
|
||||
color = color or FloatingText.color.white,
|
||||
position = position
|
||||
}
|
||||
end
|
||||
|
||||
--- Print floating text above the given entity
|
||||
-- @tparam LuaEntity The entity to create the text above
|
||||
-- @tparam string text The text which will be printed
|
||||
-- @tparam[opt=FloatingText.color.white] Color color The colour to print the text in
|
||||
-- @treturn LuaEntity The floating text entity which was created for the message
|
||||
function FloatingText.print_above_entity(entity, text, color)
|
||||
local size_y = entity.bounding_box.left_top.y - entity.bounding_box.right_bottom.y
|
||||
return entity.surface.create_entity{
|
||||
text = text,
|
||||
name = 'tutorial-flying-text',
|
||||
color = color or FloatingText.color.white,
|
||||
position = {
|
||||
x = entity.position.x,
|
||||
y = entity.position.y - size_y * 0.25
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
--- Print floating text above the given player
|
||||
-- @tparam LuaPlayer The player to create the text above
|
||||
-- @tparam string text The text which will be printed
|
||||
-- @tparam[opt=FloatingText.color.white] Color color The colour to print the text in
|
||||
-- @treturn LuaEntity The floating text entity which was created for the message
|
||||
function FloatingText.print_above_player(player, text, color)
|
||||
return player.surface.create_entity{
|
||||
text = text,
|
||||
name = 'tutorial-flying-text',
|
||||
color = color or FloatingText.color.white,
|
||||
position = {
|
||||
x = player.position.x,
|
||||
y = player.position.y - 1.5
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
--- Print floating text above the given player in their chat color
|
||||
-- @tparam LuaPlayer The player to create the text above
|
||||
-- @tparam string text The text which will be printed
|
||||
-- @treturn LuaEntity The floating text entity which was created for the message
|
||||
function FloatingText.print_as_player(player, text)
|
||||
return player.surface.create_entity{
|
||||
text = text,
|
||||
name = 'tutorial-flying-text',
|
||||
color = player.chat_color,
|
||||
position = {
|
||||
x = player.position.x,
|
||||
y = player.position.y - 1.5
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
--- Tag Messages.
|
||||
-- Long lived messages that last until their are removed
|
||||
-- @section floating-text_tags
|
||||
|
||||
--- Create floating text at the given position on the given surface
|
||||
-- @tparam LuaSurface surface The surface where the floating text will be created
|
||||
-- @tparam MapPosition position The position to create the floating text at
|
||||
-- @tparam string text The text which will be printed
|
||||
-- @tparam[opt=FloatingText.color.white] Color color The colour to print the text in
|
||||
-- @tparam[opt=false] boolean alt_mode When true, the text will only appear when a player is in alt mode
|
||||
-- @treturn LuaEntity The floating text entity which was created for the message
|
||||
function FloatingText.create_tag(surface, position, text, color, alt_mode)
|
||||
return rendering.draw_text{
|
||||
text = text,
|
||||
surface = surface,
|
||||
color = color or FloatingText.color.white,
|
||||
only_in_alt_mode = alt_mode,
|
||||
target = position
|
||||
}
|
||||
end
|
||||
|
||||
--- Create floating text above the given entity
|
||||
-- @tparam LuaEntity The entity to create the text above
|
||||
-- @tparam string text The text which will be printed
|
||||
-- @tparam[opt=FloatingText.color.white] Color color The colour to print the text in
|
||||
-- @tparam[opt=false] boolean alt_mode When true, the text will only appear when a player is in alt mode
|
||||
-- @treturn LuaEntity The floating text entity which was created for the message
|
||||
function FloatingText.create_tag_above_entity(entity, text, color, alt_mode)
|
||||
return rendering.draw_text{
|
||||
text = text,
|
||||
surface = entity.surface,
|
||||
color = color or FloatingText.color.white,
|
||||
only_in_alt_mode = alt_mode,
|
||||
target = entity,
|
||||
target_offset = {
|
||||
x = 0,
|
||||
y = (entity.bounding_box.left_top.y - entity.bounding_box.right_bottom.y) * -0.25
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
--- Create floating text above the given player
|
||||
-- @tparam LuaPlayer The player to create the text above
|
||||
-- @tparam string text The text which will be printed
|
||||
-- @tparam[opt=FloatingText.color.white] Color color The colour to print the text in
|
||||
-- @tparam[opt=false] boolean alt_mode When true, the text will only appear when a player is in alt mode
|
||||
-- @treturn LuaEntity The floating text entity which was created for the message
|
||||
function FloatingText.create_tag_above_player(player, text, color, alt_mode)
|
||||
return rendering.draw_text{
|
||||
text = text,
|
||||
surface = player.surface,
|
||||
color = color or FloatingText.color.white,
|
||||
only_in_alt_mode = alt_mode,
|
||||
target = player.character,
|
||||
target_offset = {
|
||||
x = 0,
|
||||
y = -1.5
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
--- Create floating text above the given player in their character color
|
||||
-- @tparam LuaPlayer The player to create the text above
|
||||
-- @tparam string text The text which will be printed
|
||||
-- @tparam[opt=false] boolean alt_mode When true, the text will only appear when a player is in alt mode
|
||||
-- @treturn LuaEntity The floating text entity which was created for the message
|
||||
function FloatingText.create_tag_as_player(player, text, alt_mode)
|
||||
return rendering.draw_text{
|
||||
text = text,
|
||||
surface = player.surface,
|
||||
color = player.color,
|
||||
only_in_alt_mode = alt_mode,
|
||||
target = player.character,
|
||||
target_offset = {
|
||||
x = 0,
|
||||
y = -1.5
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
return FloatingText
|
||||
101
exp_util/module/global.lua
Normal file
101
exp_util/module/global.lua
Normal file
@@ -0,0 +1,101 @@
|
||||
--[[-- Util Module - Global
|
||||
- Provides a method of using global with the guarantee that keys will not conflict
|
||||
@core Global
|
||||
@alias Global
|
||||
|
||||
@usage--- Drop in boiler plate:
|
||||
-- Below is a drop in boiler plate which ensures your global access will not conflict with other modules
|
||||
local global = {}
|
||||
Global.register(global, function(tbl)
|
||||
global = tbl
|
||||
end)
|
||||
|
||||
@usage--- Registering new global tables:
|
||||
-- The boiler plate above is not recommend because it is not descriptive in its function
|
||||
-- Best practice is to list out all variables you are storing in global and their function
|
||||
local MyModule = {
|
||||
public_data = {} -- Stores data which other modules can access
|
||||
}
|
||||
|
||||
local private_data = {} -- Stores data which other modules cant access
|
||||
local more_private_data = {} -- Stores more data which other modules cant access
|
||||
-- You can not store a whole module in global because not all data types are serialisable
|
||||
Global.register({
|
||||
MyModule.public_data,
|
||||
private_data,
|
||||
more_private_data
|
||||
}, function(tbl)
|
||||
-- You can also use this callback to set metatable on class instances you have stored in global
|
||||
MyModule.public_data = tbl[1]
|
||||
private_data = tbl[2]
|
||||
more_private_data = tbl[3]
|
||||
end)
|
||||
|
||||
]]
|
||||
|
||||
local Clustorio = require("modules/clusterio/api")
|
||||
local ExpUtil = require("modules.exp_util.common")
|
||||
|
||||
local Global = {
|
||||
registered = {}, -- Map of all registered values and their initial values
|
||||
}
|
||||
|
||||
--- Register a new table to be stored in global, can only be called once per file, can not be called during runtime
|
||||
-- @tparam table tbl The initial value for the table you are registering, this should be a local variable
|
||||
-- @tparam function callback The callback used to replace local references and metatables
|
||||
function Global.register(tbl, callback)
|
||||
ExpUtil.assert_not_runtime()
|
||||
ExpUtil.assert_argument_type(tbl, "table", 1, "tbl")
|
||||
ExpUtil.assert_argument_type(callback, "function", 2, "callback")
|
||||
|
||||
local name = ExpUtil.safe_file_path(2)
|
||||
if Global.registered[name] then
|
||||
error("Global.register can only be called once per file", 2)
|
||||
end
|
||||
|
||||
Global.registered[name] = {
|
||||
init = tbl,
|
||||
callback = callback
|
||||
}
|
||||
end
|
||||
|
||||
--- Register a metatable which will be automatically restored during on_load
|
||||
-- @tparam string name The name of the metatable to register, must be unique within your module
|
||||
function Global.register_metatable(name, tbl)
|
||||
local module_name = ExpUtil.get_module_name(2)
|
||||
script.register_metatable(module_name.."."..name, tbl)
|
||||
end
|
||||
|
||||
--- Restore aliases on load, we do not need to initialise data during this event
|
||||
function Global.on_load()
|
||||
local globals = global.exp_global
|
||||
if globals == nil then return end
|
||||
for name, data in pairs(Global.registered) do
|
||||
if globals[name] ~= nil then
|
||||
data.callback(globals[name])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Event Handler, sets initial values if needed and calls all callbacks
|
||||
local function on_server_startup()
|
||||
local globals = global.exp_global
|
||||
if globals == nil then
|
||||
globals = {}
|
||||
global.exp_global = globals
|
||||
end
|
||||
|
||||
for name, data in pairs(Global.registered) do
|
||||
if globals[name] == nil then
|
||||
globals[name] = data.init
|
||||
end
|
||||
data.callback(globals[name])
|
||||
end
|
||||
end
|
||||
|
||||
Global.on_init = on_server_startup
|
||||
Global.events = {
|
||||
[Clustorio.events.on_server_startup] = on_server_startup
|
||||
}
|
||||
|
||||
return Global
|
||||
147
exp_util/module/include/color.lua
Normal file
147
exp_util/module/include/color.lua
Normal file
@@ -0,0 +1,147 @@
|
||||
-- source: https://www.rapidtables.com/web/color/RGB_Color.html
|
||||
return {
|
||||
maroon = {r = 128, g = 0, b = 0},
|
||||
dark_red = {r = 139, g = 0, b = 0},
|
||||
brown = {r = 165, g = 42, b = 42},
|
||||
firebrick = {r = 178, g = 34, b = 34},
|
||||
crimson = {r = 220, g = 20, b = 60},
|
||||
red = {r = 255, g = 0, b = 0},
|
||||
tomato = {r = 255, g = 99, b = 71},
|
||||
coral = {r = 255, g = 127, b = 80},
|
||||
indian_red = {r = 205, g = 92, b = 92},
|
||||
light_coral = {r = 240, g = 128, b = 128},
|
||||
dark_salmon = {r = 233, g = 150, b = 122},
|
||||
salmon = {r = 250, g = 128, b = 114},
|
||||
light_salmon = {r = 255, g = 160, b = 122},
|
||||
orange_red = {r = 255, g = 69, b = 0},
|
||||
dark_orange = {r = 255, g = 140, b = 0},
|
||||
orange = {r = 255, g = 165, b = 0},
|
||||
gold = {r = 255, g = 215, b = 0},
|
||||
dark_golden_rod = {r = 184, g = 134, b = 11},
|
||||
golden_rod = {r = 218, g = 165, b = 32},
|
||||
pale_golden_rod = {r = 238, g = 232, b = 170},
|
||||
dark_khaki = {r = 189, g = 183, b = 107},
|
||||
khaki = {r = 240, g = 230, b = 140},
|
||||
olive = {r = 128, g = 128, b = 0},
|
||||
yellow = {r = 255, g = 255, b = 0},
|
||||
yellow_green = {r = 154, g = 205, b = 50},
|
||||
dark_olive_green = {r = 85, g = 107, b = 47},
|
||||
olive_drab = {r = 107, g = 142, b = 35},
|
||||
lawn_green = {r = 124, g = 252, b = 0},
|
||||
chart_reuse = {r = 127, g = 255, b = 0},
|
||||
green_yellow = {r = 173, g = 255, b = 47},
|
||||
dark_green = {r = 0, g = 100, b = 0},
|
||||
green = {r = 0, g = 128, b = 0},
|
||||
forest_green = {r = 34, g = 139, b = 34},
|
||||
lime = {r = 0, g = 255, b = 0},
|
||||
lime_green = {r = 50, g = 205, b = 50},
|
||||
light_green = {r = 144, g = 238, b = 144},
|
||||
pale_green = {r = 152, g = 251, b = 152},
|
||||
dark_sea_green = {r = 143, g = 188, b = 143},
|
||||
medium_spring_green = {r = 0, g = 250, b = 154},
|
||||
spring_green = {r = 0, g = 255, b = 127},
|
||||
sea_green = {r = 46, g = 139, b = 87},
|
||||
medium_aqua_marine = {r = 102, g = 205, b = 170},
|
||||
medium_sea_green = {r = 60, g = 179, b = 113},
|
||||
light_sea_green = {r = 32, g = 178, b = 170},
|
||||
dark_slate_gray = {r = 47, g = 79, b = 79},
|
||||
teal = {r = 0, g = 128, b = 128},
|
||||
dark_cyan = {r = 0, g = 139, b = 139},
|
||||
aqua = {r = 0, g = 255, b = 255},
|
||||
cyan = {r = 0, g = 255, b = 255},
|
||||
light_cyan = {r = 224, g = 255, b = 255},
|
||||
dark_turquoise = {r = 0, g = 206, b = 209},
|
||||
turquoise = {r = 64, g = 224, b = 208},
|
||||
medium_turquoise = {r = 72, g = 209, b = 204},
|
||||
pale_turquoise = {r = 175, g = 238, b = 238},
|
||||
aqua_marine = {r = 127, g = 255, b = 212},
|
||||
powder_blue = {r = 176, g = 224, b = 230},
|
||||
cadet_blue = {r = 95, g = 158, b = 160},
|
||||
steel_blue = {r = 70, g = 130, b = 180},
|
||||
corn_flower_blue = {r = 100, g = 149, b = 237},
|
||||
deep_sky_blue = {r = 0, g = 191, b = 255},
|
||||
dodger_blue = {r = 30, g = 144, b = 255},
|
||||
light_blue = {r = 173, g = 216, b = 230},
|
||||
sky_blue = {r = 135, g = 206, b = 235},
|
||||
light_sky_blue = {r = 135, g = 206, b = 250},
|
||||
midnight_blue = {r = 25, g = 25, b = 112},
|
||||
navy = {r = 0, g = 0, b = 128},
|
||||
dark_blue = {r = 0, g = 0, b = 139},
|
||||
medium_blue = {r = 0, g = 0, b = 205},
|
||||
blue = {r = 0, g = 0, b = 255},
|
||||
royal_blue = {r = 65, g = 105, b = 225},
|
||||
blue_violet = {r = 138, g = 43, b = 226},
|
||||
indigo = {r = 75, g = 0, b = 130},
|
||||
dark_slate_blue = {r = 72, g = 61, b = 139},
|
||||
slate_blue = {r = 106, g = 90, b = 205},
|
||||
medium_slate_blue = {r = 123, g = 104, b = 238},
|
||||
medium_purple = {r = 147, g = 112, b = 219},
|
||||
dark_magenta = {r = 139, g = 0, b = 139},
|
||||
dark_violet = {r = 148, g = 0, b = 211},
|
||||
dark_orchid = {r = 153, g = 50, b = 204},
|
||||
medium_orchid = {r = 186, g = 85, b = 211},
|
||||
purple = {r = 128, g = 0, b = 128},
|
||||
thistle = {r = 216, g = 191, b = 216},
|
||||
plum = {r = 221, g = 160, b = 221},
|
||||
violet = {r = 238, g = 130, b = 238},
|
||||
magenta = {r = 255, g = 0, b = 255},
|
||||
fuchsia = {r = 255, g = 0, b = 255},
|
||||
orchid = {r = 218, g = 112, b = 214},
|
||||
medium_violet_red = {r = 199, g = 21, b = 133},
|
||||
pale_violet_red = {r = 219, g = 112, b = 147},
|
||||
deep_pink = {r = 255, g = 20, b = 147},
|
||||
hot_pink = {r = 255, g = 105, b = 180},
|
||||
light_pink = {r = 255, g = 182, b = 193},
|
||||
pink = {r = 255, g = 192, b = 203},
|
||||
antique_white = {r = 250, g = 235, b = 215},
|
||||
beige = {r = 245, g = 245, b = 220},
|
||||
bisque = {r = 255, g = 228, b = 196},
|
||||
blanched_almond = {r = 255, g = 235, b = 205},
|
||||
wheat = {r = 245, g = 222, b = 179},
|
||||
corn_silk = {r = 255, g = 248, b = 220},
|
||||
lemon_chiffon = {r = 255, g = 250, b = 205},
|
||||
light_golden_rod_yellow = {r = 250, g = 250, b = 210},
|
||||
light_yellow = {r = 255, g = 255, b = 224},
|
||||
saddle_brown = {r = 139, g = 69, b = 19},
|
||||
sienna = {r = 160, g = 82, b = 45},
|
||||
chocolate = {r = 210, g = 105, b = 30},
|
||||
peru = {r = 205, g = 133, b = 63},
|
||||
sandy_brown = {r = 244, g = 164, b = 96},
|
||||
burly_wood = {r = 222, g = 184, b = 135},
|
||||
tan = {r = 210, g = 180, b = 140},
|
||||
rosy_brown = {r = 188, g = 143, b = 143},
|
||||
moccasin = {r = 255, g = 228, b = 181},
|
||||
navajo_white = {r = 255, g = 222, b = 173},
|
||||
peach_puff = {r = 255, g = 218, b = 185},
|
||||
misty_rose = {r = 255, g = 228, b = 225},
|
||||
lavender_blush = {r = 255, g = 240, b = 245},
|
||||
linen = {r = 250, g = 240, b = 230},
|
||||
old_lace = {r = 253, g = 245, b = 230},
|
||||
papaya_whip = {r = 255, g = 239, b = 213},
|
||||
sea_shell = {r = 255, g = 245, b = 238},
|
||||
mint_cream = {r = 245, g = 255, b = 250},
|
||||
slate_gray = {r = 112, g = 128, b = 144},
|
||||
light_slate_gray = {r = 119, g = 136, b = 153},
|
||||
light_steel_blue = {r = 176, g = 196, b = 222},
|
||||
lavender = {r = 230, g = 230, b = 250},
|
||||
floral_white = {r = 255, g = 250, b = 240},
|
||||
alice_blue = {r = 240, g = 248, b = 255},
|
||||
ghost_white = {r = 248, g = 248, b = 255},
|
||||
honeydew = {r = 240, g = 255, b = 240},
|
||||
ivory = {r = 255, g = 255, b = 240},
|
||||
azure = {r = 240, g = 255, b = 255},
|
||||
snow = {r = 255, g = 250, b = 250},
|
||||
black = {r = 0, g = 0, b = 0},
|
||||
silver = {r = 192, g = 192, b = 192},
|
||||
dim_grey = {r = 105, g = 105, b = 105},
|
||||
grey = {r = 128, g = 128, b = 128},
|
||||
dark_grey = {r = 169, g = 169, b = 169},
|
||||
light_grey = {r = 211, g = 211, b = 211},
|
||||
gainsboro = {r = 220, g = 220, b = 220},
|
||||
white_smoke = {r = 245, g = 245, b = 245},
|
||||
white = {r = 255, g = 255, b = 255},
|
||||
success = {r = 0, g = 255, b = 0},
|
||||
warning = {r = 255, g = 255, b = 0},
|
||||
fail = {r = 255, g = 0, b = 0},
|
||||
info = {r = 255, g = 255, b = 255}
|
||||
}
|
||||
342
exp_util/module/include/inspect.lua
Normal file
342
exp_util/module/include/inspect.lua
Normal file
@@ -0,0 +1,342 @@
|
||||
local inspect = {
|
||||
_VERSION = 'inspect.lua 3.1.0',
|
||||
_URL = 'http://github.com/kikito/inspect.lua',
|
||||
_DESCRIPTION = 'human-readable representations of tables',
|
||||
_LICENSE = [[
|
||||
MIT LICENSE
|
||||
|
||||
Copyright (c) 2013 Enrique García Cota
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included
|
||||
in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
||||
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
]]
|
||||
}
|
||||
|
||||
local tostring = tostring
|
||||
|
||||
inspect.KEY = setmetatable({}, {__tostring = function() return 'inspect.KEY' end})
|
||||
inspect.METATABLE = setmetatable({}, {__tostring = function() return 'inspect.METATABLE' end})
|
||||
|
||||
-- Apostrophizes the string if it has quotes, but not aphostrophes
|
||||
-- Otherwise, it returns a regular quoted string
|
||||
local function smartQuote(str)
|
||||
if str:match('"') and not str:match("'") then
|
||||
return "'" .. str .. "'"
|
||||
end
|
||||
return '"' .. str:gsub('"', '\\"') .. '"'
|
||||
end
|
||||
|
||||
-- \a => '\\a', \0 => '\\0', 31 => '\31'
|
||||
local shortControlCharEscapes = {
|
||||
["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n",
|
||||
["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v"
|
||||
}
|
||||
local longControlCharEscapes = {} -- \a => nil, \0 => \000, 31 => \031
|
||||
for i=0, 31 do
|
||||
local ch = string.char(i)
|
||||
if not shortControlCharEscapes[ch] then
|
||||
shortControlCharEscapes[ch] = "\\"..i
|
||||
longControlCharEscapes[ch] = string.format("\\%03d", i)
|
||||
end
|
||||
end
|
||||
|
||||
local function escape(str)
|
||||
return (str:gsub("\\", "\\\\")
|
||||
:gsub("(%c)%f[0-9]", longControlCharEscapes)
|
||||
:gsub("%c", shortControlCharEscapes))
|
||||
end
|
||||
|
||||
local function isIdentifier(str)
|
||||
return type(str) == 'string' and str:match( "^[_%a][_%a%d]*$" )
|
||||
end
|
||||
|
||||
local function isSequenceKey(k, sequenceLength)
|
||||
return type(k) == 'number'
|
||||
and 1 <= k
|
||||
and k <= sequenceLength
|
||||
and math.floor(k) == k
|
||||
end
|
||||
|
||||
local defaultTypeOrders = {
|
||||
['number'] = 1, ['boolean'] = 2, ['string'] = 3, ['table'] = 4,
|
||||
['function'] = 5, ['userdata'] = 6, ['thread'] = 7
|
||||
}
|
||||
|
||||
local function sortKeys(a, b)
|
||||
local ta, tb = type(a), type(b)
|
||||
|
||||
-- strings and numbers are sorted numerically/alphabetically
|
||||
if ta == tb and (ta == 'string' or ta == 'number') then return a < b end
|
||||
|
||||
local dta, dtb = defaultTypeOrders[ta], defaultTypeOrders[tb]
|
||||
-- Two default types are compared according to the defaultTypeOrders table
|
||||
if dta and dtb then return defaultTypeOrders[ta] < defaultTypeOrders[tb]
|
||||
elseif dta then return true -- default types before custom ones
|
||||
elseif dtb then return false -- custom types after default ones
|
||||
end
|
||||
|
||||
-- custom types are sorted out alphabetically
|
||||
return ta < tb
|
||||
end
|
||||
|
||||
-- For implementation reasons, the behavior of rawlen & # is "undefined" when
|
||||
-- tables aren't pure sequences. So we implement our own # operator.
|
||||
local function getSequenceLength(t)
|
||||
local len = 1
|
||||
local v = rawget(t, len)
|
||||
while v ~= nil do
|
||||
len = len + 1
|
||||
v = rawget(t, len)
|
||||
end
|
||||
return len - 1
|
||||
end
|
||||
|
||||
local function getNonSequentialKeys(t)
|
||||
local keys = {}
|
||||
local sequenceLength = getSequenceLength(t)
|
||||
for k, _ in pairs(t) do
|
||||
if not isSequenceKey(k, sequenceLength) then table.insert(keys, k) end
|
||||
end
|
||||
table.sort(keys, sortKeys)
|
||||
return keys, sequenceLength
|
||||
end
|
||||
|
||||
local function getToStringResultSafely(t, mt)
|
||||
local __tostring = type(mt) == 'table' and rawget(mt, '__tostring')
|
||||
local str, ok
|
||||
if type(__tostring) == 'function' then
|
||||
ok, str = pcall(__tostring, t)
|
||||
str = ok and str or 'error: ' .. tostring(str)
|
||||
end
|
||||
if type(str) == 'string' and #str > 0 then return str end
|
||||
end
|
||||
|
||||
local function countTableAppearances(t, tableAppearances)
|
||||
tableAppearances = tableAppearances or {}
|
||||
|
||||
if type(t) == 'table' then
|
||||
if not tableAppearances[t] then
|
||||
tableAppearances[t] = 1
|
||||
for k, v in pairs(t) do
|
||||
countTableAppearances(k, tableAppearances)
|
||||
countTableAppearances(v, tableAppearances)
|
||||
end
|
||||
countTableAppearances(getmetatable(t), tableAppearances)
|
||||
else
|
||||
tableAppearances[t] = tableAppearances[t] + 1
|
||||
end
|
||||
end
|
||||
|
||||
return tableAppearances
|
||||
end
|
||||
|
||||
local copySequence = function(s)
|
||||
local copy, len = {}, #s
|
||||
for i=1, len do copy[i] = s[i] end
|
||||
return copy, len
|
||||
end
|
||||
|
||||
local function makePath(path, ...)
|
||||
local keys = {...}
|
||||
local newPath, len = copySequence(path)
|
||||
for i=1, #keys do
|
||||
newPath[len + i] = keys[i]
|
||||
end
|
||||
return newPath
|
||||
end
|
||||
|
||||
-- Cooldude2606: Modified this to respect the depth option
|
||||
local function processRecursive(process, item, path, visited, depth)
|
||||
|
||||
if item == nil then return nil end
|
||||
if visited[item] then return visited[item] end
|
||||
|
||||
local processed = process(item, path)
|
||||
if type(processed) == 'table' and (depth == nil or depth > 0) then
|
||||
local processedCopy = {}
|
||||
visited[item] = processedCopy
|
||||
local processedKey
|
||||
|
||||
for k, v in pairs(processed) do
|
||||
processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY), visited, depth and depth - 1)
|
||||
if processedKey ~= nil then
|
||||
processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey), visited, depth and depth - 1)
|
||||
end
|
||||
end
|
||||
|
||||
local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE), visited, depth and depth - 1)
|
||||
setmetatable(processedCopy, mt)
|
||||
processed = processedCopy
|
||||
end
|
||||
return processed
|
||||
end
|
||||
|
||||
|
||||
|
||||
-------------------------------------------------------------------
|
||||
|
||||
local Inspector = {}
|
||||
local Inspector_mt = {__index = Inspector}
|
||||
|
||||
function Inspector:puts(...)
|
||||
local args = {...}
|
||||
local buffer = self.buffer
|
||||
local len = #buffer
|
||||
for i=1, #args do
|
||||
len = len + 1
|
||||
buffer[len] = args[i]
|
||||
end
|
||||
end
|
||||
|
||||
function Inspector:down(f)
|
||||
self.level = self.level + 1
|
||||
f()
|
||||
self.level = self.level - 1
|
||||
end
|
||||
|
||||
function Inspector:tabify()
|
||||
self:puts(self.newline, string.rep(self.indent, self.level))
|
||||
end
|
||||
|
||||
function Inspector:alreadyVisited(v)
|
||||
return self.ids[v] ~= nil
|
||||
end
|
||||
|
||||
function Inspector:getId(v)
|
||||
local id = self.ids[v]
|
||||
if not id then
|
||||
local tv = type(v)
|
||||
id = (self.maxIds[tv] or 0) + 1
|
||||
self.maxIds[tv] = id
|
||||
self.ids[v] = id
|
||||
end
|
||||
return tostring(id)
|
||||
end
|
||||
|
||||
function Inspector:putKey(k)
|
||||
if isIdentifier(k) then return self:puts(k) end
|
||||
self:puts("[")
|
||||
self:putValue(k)
|
||||
self:puts("]")
|
||||
end
|
||||
|
||||
function Inspector:putTable(t)
|
||||
if t == inspect.KEY or t == inspect.METATABLE then
|
||||
self:puts(tostring(t))
|
||||
elseif self:alreadyVisited(t) then
|
||||
self:puts('<table ', self:getId(t), '>')
|
||||
elseif self.level >= self.depth then
|
||||
self:puts('{...}')
|
||||
else
|
||||
if self.tableAppearances[t] > 1 then self:puts('<', self:getId(t), '>') end
|
||||
|
||||
local nonSequentialKeys, sequenceLength = getNonSequentialKeys(t)
|
||||
local mt = getmetatable(t)
|
||||
local toStringResult = getToStringResultSafely(t, mt)
|
||||
|
||||
self:puts('{')
|
||||
self:down(function()
|
||||
if toStringResult then
|
||||
self:puts(' -- ', escape(toStringResult))
|
||||
if sequenceLength >= 1 then self:tabify() end
|
||||
end
|
||||
|
||||
local count = 0
|
||||
for i=1, sequenceLength do
|
||||
if count > 0 then self:puts(', ') end
|
||||
self:puts(' ')
|
||||
self:putValue(t[i])
|
||||
count = count + 1
|
||||
end
|
||||
|
||||
for _, k in ipairs(nonSequentialKeys) do
|
||||
if count > 0 then self:puts(', ') end
|
||||
self:tabify()
|
||||
self:putKey(k)
|
||||
self:puts(' = ')
|
||||
self:putValue(t[k])
|
||||
count = count + 1
|
||||
end
|
||||
|
||||
if mt then
|
||||
if count > 0 then self:puts(', ') end
|
||||
self:tabify()
|
||||
self:puts('<metatable> = ')
|
||||
self:putValue(mt)
|
||||
end
|
||||
end)
|
||||
|
||||
if #nonSequentialKeys > 0 or mt then -- result is multi-lined. Justify closing }
|
||||
self:tabify()
|
||||
elseif sequenceLength > 0 then -- array tables have one extra space before closing }
|
||||
self:puts(' ')
|
||||
end
|
||||
|
||||
self:puts('}')
|
||||
end
|
||||
end
|
||||
|
||||
function Inspector:putValue(v)
|
||||
local tv = type(v)
|
||||
|
||||
if tv == 'string' then
|
||||
self:puts(smartQuote(escape(v)))
|
||||
elseif tv == 'number' or tv == 'boolean' or tv == 'nil' or
|
||||
tv == 'cdata' or tv == 'ctype' then
|
||||
self:puts(tostring(v))
|
||||
elseif tv == 'table' then
|
||||
self:putTable(v)
|
||||
else
|
||||
self:puts('<', tv, ' ', self:getId(v), '>')
|
||||
end
|
||||
end
|
||||
|
||||
-------------------------------------------------------------------
|
||||
|
||||
function inspect.inspect(root, options)
|
||||
options = options or {}
|
||||
|
||||
local depth = options.depth or math.huge
|
||||
local newline = options.newline or '\n'
|
||||
local indent = options.indent or ' '
|
||||
local process = options.process
|
||||
|
||||
if process then
|
||||
root = processRecursive(process, root, {}, {})
|
||||
end
|
||||
|
||||
local inspector = setmetatable({
|
||||
depth = depth,
|
||||
level = 0,
|
||||
buffer = {},
|
||||
ids = {},
|
||||
maxIds = {},
|
||||
newline = newline,
|
||||
indent = indent,
|
||||
tableAppearances = countTableAppearances(root)
|
||||
}, Inspector_mt)
|
||||
|
||||
inspector:putValue(root)
|
||||
|
||||
return table.concat(inspector.buffer)
|
||||
end
|
||||
|
||||
setmetatable(inspect, { __call = function(_, ...) return inspect.inspect(...) end })
|
||||
|
||||
return inspect
|
||||
64
exp_util/module/include/math.lua
Normal file
64
exp_util/module/include/math.lua
Normal file
@@ -0,0 +1,64 @@
|
||||
--luacheck:ignore global math
|
||||
|
||||
local floor = math.floor
|
||||
local abs = math.abs
|
||||
|
||||
--- Constant value representing the square root of 2
|
||||
math.sqrt2 = math.sqrt(2)
|
||||
|
||||
--- Constant value representing the reciprocal of square root of 2
|
||||
math.inv_sqrt2 = 1 / math.sqrt2
|
||||
|
||||
--- Constant value representing the value of Tau aka 2*Pi
|
||||
math.tau = 2 * math.pi
|
||||
|
||||
--- Rounds a number to certain number of decimal places, does not work on significant figures
|
||||
-- @tparam number num The number to be rounded
|
||||
-- @tparam[opt=0] number idp The number of decimal places to round to
|
||||
-- @treturn number The input number rounded to the given number of decimal places
|
||||
math.round = function(num, idp)
|
||||
local mult = 10 ^ (idp or 0)
|
||||
return floor(num * mult + 0.5) / mult
|
||||
end
|
||||
|
||||
--- Clamp a number better a minimum and maximum value, preserves NaN (not the same as nil)
|
||||
-- @tparam number num The number to be clamped
|
||||
-- @tparam number min The lower bound of the accepted range
|
||||
-- @tparam number max The upper bound of the accepted range
|
||||
-- @treturn number The input number clamped to the given range
|
||||
math.clamp = function(num, min, max)
|
||||
if num < min then
|
||||
return min
|
||||
elseif num > max then
|
||||
return max
|
||||
else
|
||||
return num
|
||||
end
|
||||
end
|
||||
|
||||
--- Returns the slope / gradient of a line given two points on the line
|
||||
-- @tparam number x1 The X coordinate of the first point on the line
|
||||
-- @tparam number y1 The Y coordinate of the first point on the line
|
||||
-- @tparam number x2 The X coordinate of the second point on the line
|
||||
-- @tparam number y2 The Y coordinate of the second point on the line
|
||||
-- @treturn number The slope of the line
|
||||
math.slope = function(x1, y1, x2, y2)
|
||||
return abs((y2 - y1) / (x2 - x1))
|
||||
end
|
||||
|
||||
--- Returns the y-intercept of a line given ibe point on the line and its slope
|
||||
-- @tparam number x The X coordinate of point on the line
|
||||
-- @tparam number y The Y coordinate of point on the line
|
||||
-- @tparam number slope The slope / gradient of the line
|
||||
-- @treturn number The y-intercept of the line
|
||||
math.y_intercept = function(x, y, slope)
|
||||
return y - (slope * x)
|
||||
end
|
||||
|
||||
local deg_to_rad = math.tau / 360
|
||||
--- Returns the angle x (given in radians) in degrees
|
||||
math.degrees = function(x)
|
||||
return x * deg_to_rad
|
||||
end
|
||||
|
||||
return math
|
||||
33
exp_util/module/include/package.lua
Normal file
33
exp_util/module/include/package.lua
Normal file
@@ -0,0 +1,33 @@
|
||||
--luacheck:ignore global package
|
||||
|
||||
local Clustorio = require("modules/clusterio/api")
|
||||
|
||||
--- Enum values for the different lifecycle stages within a factorio module
|
||||
-- Info on the data lifecycle and how we use it: https://lua-api.factorio.com/latest/auxiliary/data-lifecycle.html
|
||||
-- We start in control stage and so values 1 thorough 3 are only present for completeness
|
||||
package.lifecycle_stage = {
|
||||
settings = 1,
|
||||
data = 2,
|
||||
migration = 3,
|
||||
control = 4,
|
||||
init = 5,
|
||||
load = 6,
|
||||
config_change = 7,
|
||||
runtime = 8
|
||||
}
|
||||
|
||||
--- Stores the current lifecycle stage we are in, compare values against package.lifecycle_stage
|
||||
package.lifecycle = package.lifecycle_stage.control
|
||||
|
||||
return setmetatable({
|
||||
on_init = function() package.lifecycle = package.lifecycle_stage.init end,
|
||||
on_load = function() package.lifecycle = package.lifecycle_stage.load end,
|
||||
on_configuration_changed = function() package.lifecycle = package.lifecycle_stage.config_change end,
|
||||
events = {
|
||||
-- TODO find a reliable way to set to runtime because currently it will desync if accessed before player joined
|
||||
[defines.events.on_player_joined_game] = function() package.lifecycle = package.lifecycle_stage.runtime end,
|
||||
[Clustorio.events.on_server_startup] = function() package.lifecycle = package.lifecycle_stage.runtime end,
|
||||
}
|
||||
}, {
|
||||
__index = package
|
||||
})
|
||||
23
exp_util/module/include/require.lua
Normal file
23
exp_util/module/include/require.lua
Normal file
@@ -0,0 +1,23 @@
|
||||
--luacheck:ignore global require
|
||||
|
||||
local package = require 'modules.exp_util.include.package'
|
||||
local loaded = package.loaded
|
||||
local _require = require
|
||||
|
||||
-- This replace function is used to avoid additional lines in stack traces during control stage
|
||||
local function replace()
|
||||
require = function(path)
|
||||
if package.lifecycle == package.lifecycle_stage.runtime then
|
||||
return loaded[path] or loaded[path:gsub(".", "/")] or error('Can only require files at runtime that have been required in the control stage.', 2)
|
||||
else
|
||||
return _require(path)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return setmetatable({
|
||||
on_init = replace,
|
||||
on_load = replace,
|
||||
}, {
|
||||
__call = _require
|
||||
})
|
||||
427
exp_util/module/include/table.lua
Normal file
427
exp_util/module/include/table.lua
Normal file
@@ -0,0 +1,427 @@
|
||||
--luacheck:ignore global table
|
||||
|
||||
local random = math.random
|
||||
local floor = math.floor
|
||||
local remove = table.remove
|
||||
local tonumber = tonumber
|
||||
local pairs = pairs
|
||||
local table_size = table_size
|
||||
|
||||
--- Adds all keys of the source table to destination table as a shallow copy
|
||||
-- @tparam table dst The table to insert into
|
||||
-- @tparam table src The table to insert from
|
||||
function table.merge(dst, src)
|
||||
local dst_len = #dst
|
||||
for k, v in pairs(src) do
|
||||
if tonumber(k) then
|
||||
dst_len = dst_len + 1
|
||||
dst[dst_len] = v
|
||||
else
|
||||
dst[k] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--[[-- Much faster method for inserting items into an array
|
||||
@tparam table tbl the table that will have the values added to it
|
||||
@tparam[opt] number start_index the index at which values will be added, nil means end of the array
|
||||
@tparam table values the new values that will be added to the table
|
||||
@treturn table the table that was passed as the first argument
|
||||
@usage-- Adding 1000 values into the middle of the array
|
||||
local tbl = {}
|
||||
local values = {}
|
||||
for i = 1, 1000 do tbl[i] = i values[i] = i end
|
||||
table.array_insert(tbl, 500, values) -- around 0.4ms
|
||||
]]
|
||||
function table.array_insert(tbl, start_index, values)
|
||||
if not values then
|
||||
values = start_index
|
||||
start_index = nil
|
||||
end
|
||||
|
||||
if start_index then
|
||||
local starting_length = #tbl
|
||||
local adding_length = #values
|
||||
local move_to = start_index+adding_length+1
|
||||
for offset = starting_length-start_index, 0, -1 do
|
||||
tbl[move_to+offset] = tbl[starting_length+offset]
|
||||
end
|
||||
start_index = start_index-1
|
||||
else
|
||||
start_index = #tbl
|
||||
end
|
||||
|
||||
for offset, item in ipairs(values) do
|
||||
tbl[start_index+offset] = item
|
||||
end
|
||||
|
||||
return tbl
|
||||
end
|
||||
|
||||
--[[-- Much faster method for inserting keys into a table
|
||||
@tparam table tbl the table that will have keys added to it
|
||||
@tparam[opt] number start_index the index at which values will be added, nil means end of the array, numbered indexs only
|
||||
@tparam table tbl2 the table that may contain both string and numbered keys
|
||||
@treturn table the table passed as the first argument
|
||||
@usage-- Merging two tables
|
||||
local tbl = {}
|
||||
local tbl2 = {}
|
||||
for i = 1, 100 do tbl[i] = i tbl['_'..i] = i tbl2[i] = i tbl2['__'..i] = i end
|
||||
table.table_insert(tbl, 50, tbl2)
|
||||
]]
|
||||
function table.table_insert(tbl, start_index, tbl2)
|
||||
if not tbl2 then
|
||||
tbl2 = start_index
|
||||
start_index = nil
|
||||
end
|
||||
|
||||
table.array_insert(tbl, start_index, tbl2)
|
||||
for key, value in pairs(tbl2) do
|
||||
if not tonumber(key) then
|
||||
tbl[key] = value
|
||||
end
|
||||
end
|
||||
|
||||
return tbl
|
||||
end
|
||||
|
||||
--- Searches an array to remove a specific element without an index
|
||||
-- @tparam table tbl The array to remove the element from
|
||||
-- @param element The element to search for
|
||||
function table.remove_element(tbl, element)
|
||||
for k, v in pairs(tbl) do
|
||||
if v == element then
|
||||
remove(tbl, k)
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Removes an item from an array in O(1) time. Does not guarantee the order of elements.
|
||||
-- @tparam table tbl The array to remove the element from
|
||||
-- @tparam number index Must be >= 0. The case where index > #tbl is handled.
|
||||
function table.remove_index(tbl, index)
|
||||
local count = #tbl
|
||||
if index > count then
|
||||
return
|
||||
end
|
||||
|
||||
tbl[index] = tbl[count]
|
||||
tbl[count] = nil
|
||||
end
|
||||
|
||||
--- Removes an item from an array in O(1) time. Does not guarantee the order of elements.
|
||||
-- @tparam table tbl The array to remove the element from
|
||||
-- @tparam number index Must be >= 0. The case where index > #tbl is handled.
|
||||
table.fast_remove = table.remove_index
|
||||
|
||||
--- Return the key which holds this element element
|
||||
-- @tparam table tbl The table to search
|
||||
-- @param element The element to find
|
||||
-- @return The key of the element or nil
|
||||
function table.get_key(tbl, element)
|
||||
for k, v in pairs(tbl) do
|
||||
if v == element then
|
||||
return k
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
--- Checks if the arrayed portion of a table contains an element
|
||||
-- @tparam table tbl The table to search
|
||||
-- @param element The element to find
|
||||
-- @treturn ?number The index of the element or nil
|
||||
function table.get_index(tbl, element)
|
||||
for i = 1, #tbl do
|
||||
if tbl[i] == element then
|
||||
return i
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
--- Checks if a table contains an element
|
||||
-- @tparam table tbl The table to search
|
||||
-- @param e The element to find
|
||||
-- @treturn boolean True if the element was found
|
||||
function table.contains(tbl, element)
|
||||
return table.get_key(tbl, element) and true or false
|
||||
end
|
||||
|
||||
--- Checks if the arrayed portion of a table contains an element
|
||||
-- @tparam table tbl The table to search
|
||||
-- @param e The element to find
|
||||
-- @treturn boolean True if the element was found
|
||||
function table.array_contains(tbl, element)
|
||||
return table.get_index(tbl, element) and true or false
|
||||
end
|
||||
|
||||
--[[-- Extracts certain keys from a table, similar to deconstruction in other languages
|
||||
@tparam table tbl table the which contains the keys
|
||||
@tparam string ... the names of the keys you want extracted
|
||||
@return the keys in the order given
|
||||
@usage -- Deconstruction of a required module
|
||||
local format_number, distance = table.deconstruct(require('util'), 'format_number', 'distance')
|
||||
]]
|
||||
function table.deconstruct(tbl, ...)
|
||||
local values = {}
|
||||
for _, key in pairs({...}) do
|
||||
table.insert(values, tbl[key])
|
||||
end
|
||||
return table.unpack(values)
|
||||
end
|
||||
|
||||
--- Chooses a random entry from a table, can only be used during runtime
|
||||
-- @tparam table tbl The table to select from
|
||||
-- @tparam[opt=false] boolean key When true the key will be returned rather than the value
|
||||
-- @return The selected element from the table
|
||||
function table.get_random(tbl, key)
|
||||
local target_index = random(1, table_size(tbl))
|
||||
local count = 1
|
||||
for k, v in pairs(tbl) do
|
||||
if target_index == count then
|
||||
if key then
|
||||
return k
|
||||
else
|
||||
return v
|
||||
end
|
||||
end
|
||||
count = count + 1
|
||||
end
|
||||
end
|
||||
|
||||
--- Chooses a random entry from a weighted table, can only be used during runtime
|
||||
-- @tparam table weighted_table The table of items and their weights
|
||||
-- @param[opt=1] item_key The index / key of items within each element
|
||||
-- @param[opt=2] weight_key The index / key of the weights within each element
|
||||
-- @return The selected element from the table
|
||||
function table.get_random_weighted(weighted_table, item_key, weight_index)
|
||||
local total_weight = 0
|
||||
item_key = item_key or 1
|
||||
weight_index = weight_index or 2
|
||||
|
||||
for _, w in pairs(weighted_table) do
|
||||
total_weight = total_weight + w[weight_index]
|
||||
end
|
||||
|
||||
local index = random() * total_weight
|
||||
local weight_sum = 0
|
||||
for _, w in pairs(weighted_table) do
|
||||
weight_sum = weight_sum + w[weight_index]
|
||||
if weight_sum >= index then
|
||||
return w[item_key]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Clears all existing entries in a table
|
||||
-- @tparam table tbl The table to clear
|
||||
-- @tparam[opt=false] boolean array When true only the array portion of the table is cleared
|
||||
function table.clear(t, array)
|
||||
if array then
|
||||
for i = 1, #t do
|
||||
t[i] = nil
|
||||
end
|
||||
else
|
||||
for i in pairs(t) do
|
||||
t[i] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Creates a fisher-yates shuffle of a sequential number-indexed table
|
||||
-- because this uses math.random, it cannot be used outside of events if no rng is supplied
|
||||
-- from: http://www.sdknews.com/cross-platform/corona/tutorial-how-to-shuffle-table-items
|
||||
-- @tparam table tbl The table to shuffle
|
||||
-- @tparam[opt=math.random] function rng The function to provide random numbers
|
||||
function table.shuffle(t, rng)
|
||||
local rand = rng or math.random
|
||||
local iterations = #t
|
||||
if iterations == 0 then
|
||||
error('Not a sequential table')
|
||||
return
|
||||
end
|
||||
local j
|
||||
|
||||
for i = iterations, 2, -1 do
|
||||
j = rand(i)
|
||||
t[i], t[j] = t[j], t[i]
|
||||
end
|
||||
end
|
||||
|
||||
--- Default table comparator sort function.
|
||||
-- @local
|
||||
-- @param x one comparator operand
|
||||
-- @param y the other comparator operand
|
||||
-- @return true if x logically comes before y in a list, false otherwise
|
||||
local function sortFunc(x, y) --sorts tables with mixed index types.
|
||||
local tx = type(x)
|
||||
local ty = type(y)
|
||||
if tx == ty then
|
||||
if type(x) == 'string' then
|
||||
return string.lower(x) < string.lower(y)
|
||||
else
|
||||
return x < y
|
||||
end
|
||||
elseif tx == 'number' then
|
||||
return true --only x is a number and goes first
|
||||
else
|
||||
return false --only y is a number and goes first
|
||||
end
|
||||
end
|
||||
|
||||
--- Returns a copy of all of the values in the table.
|
||||
-- @tparam table tbl the to copy the keys from, or an empty table if tbl is nil
|
||||
-- @tparam[opt] boolean sorted whether to sort the keys (slower) or keep the random order from pairs()
|
||||
-- @tparam[opt] boolean as_string whether to try and parse the values as strings, or leave them as their existing type
|
||||
-- @treturn array an array with a copy of all the values in the table
|
||||
function table.get_values(tbl, sorted, as_string)
|
||||
if not tbl then return {} end
|
||||
local valueset = {}
|
||||
local n = 0
|
||||
if as_string then --checking as_string /before/ looping is faster
|
||||
for _, v in pairs(tbl) do
|
||||
n = n + 1
|
||||
valueset[n] = tostring(v)
|
||||
end
|
||||
else
|
||||
for _, v in pairs(tbl) do
|
||||
n = n + 1
|
||||
valueset[n] = v
|
||||
end
|
||||
end
|
||||
if sorted then
|
||||
table.sort(valueset, sortFunc)
|
||||
end
|
||||
return valueset
|
||||
end
|
||||
|
||||
--- Returns a copy of all of the keys in the table.
|
||||
-- @tparam table tbl the to copy the keys from, or an empty table if tbl is nil
|
||||
-- @tparam[opt] boolean sorted whether to sort the keys (slower) or keep the random order from pairs()
|
||||
-- @tparam[opt] boolean as_string whether to try and parse the keys as strings, or leave them as their existing type
|
||||
-- @treturn array an array with a copy of all the keys in the table
|
||||
function table.get_keys(tbl, sorted, as_string)
|
||||
if not tbl then return {} end
|
||||
local keyset = {}
|
||||
local n = 0
|
||||
if as_string then --checking as_string /before/ looping is faster
|
||||
for k, _ in pairs(tbl) do
|
||||
n = n + 1
|
||||
keyset[n] = tostring(k)
|
||||
end
|
||||
else
|
||||
for k, _ in pairs(tbl) do
|
||||
n = n + 1
|
||||
keyset[n] = k
|
||||
end
|
||||
end
|
||||
if sorted then
|
||||
table.sort(keyset, sortFunc)
|
||||
end
|
||||
return keyset
|
||||
end
|
||||
|
||||
--- Returns the list is a sorted way that would be expected by people (this is by key)
|
||||
-- @tparam table tbl the table to be sorted
|
||||
-- @treturn table the sorted table
|
||||
function table.alphanum_sort(tbl)
|
||||
local o = table.get_keys(tbl)
|
||||
local function padnum(d) local dec, n = string.match(d, "(%.?)0*(.+)")
|
||||
return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n) end
|
||||
table.sort(o, function(a, b)
|
||||
return tostring(a):gsub("%.?%d+", padnum)..("%3d"):format(#b)
|
||||
< tostring(b):gsub("%.?%d+", padnum)..("%3d"):format(#a) end)
|
||||
local _tbl = {}
|
||||
for _, k in pairs(o) do _tbl[k] = tbl[k] end
|
||||
return _tbl
|
||||
end
|
||||
|
||||
--- Returns the list is a sorted way that would be expected by people (this is by key) (faster alternative than above)
|
||||
-- @tparam table tbl the table to be sorted
|
||||
-- @treturn table the sorted table
|
||||
function table.key_sort(tbl)
|
||||
local o = table.get_keys(tbl, true)
|
||||
local _tbl = {}
|
||||
for _, k in pairs(o) do _tbl[k] = tbl[k] end
|
||||
return _tbl
|
||||
end
|
||||
|
||||
--[[
|
||||
Returns the index where t[index] == target.
|
||||
If there is no such index, returns a negative value such that bit32.bnot(value) is
|
||||
the index that the value should be inserted to keep the list ordered.
|
||||
t must be a list in ascending order for the return value to be valid.
|
||||
|
||||
Usage example:
|
||||
local t = {1, 3,5, 7,9}
|
||||
local x = 5
|
||||
local index = table.binary_search(t, x)
|
||||
if index < 0 then
|
||||
game.print("value not found, smallest index where t[index] > x is: " .. bit32.bnot(index))
|
||||
else
|
||||
game.print("value found at index: " .. index)
|
||||
end
|
||||
]]
|
||||
function table.binary_search(t, target)
|
||||
--For some reason bit32.bnot doesn't return negative numbers so I'm using ~x = -1 - x instead.
|
||||
|
||||
local lower = 1
|
||||
local upper = #t
|
||||
|
||||
if upper == 0 then
|
||||
return -2 -- ~1
|
||||
end
|
||||
|
||||
repeat
|
||||
local mid = floor((lower + upper) * 0.5)
|
||||
local value = t[mid]
|
||||
if value == target then
|
||||
return mid
|
||||
elseif value < target then
|
||||
lower = mid + 1
|
||||
else
|
||||
upper = mid - 1
|
||||
end
|
||||
until lower > upper
|
||||
|
||||
return -1 - lower -- ~lower
|
||||
end
|
||||
|
||||
-- add table-related functions that exist in base factorio/util to the 'table' table
|
||||
require 'util'
|
||||
|
||||
--- Similar to serpent.block, returns a string with a pretty representation of a table.
|
||||
-- Notice: This method is not appropriate for saving/restoring tables. It is meant to be used by the programmer mainly while debugging a program.
|
||||
-- @tparam table root tTe table to serialize
|
||||
-- @tparam table options Options are depth, newline, indent, process
|
||||
-- depth sets the maximum depth that will be printed out. When the max depth is reached, inspect will stop parsing tables and just return {...}
|
||||
-- process is a function which allow altering the passed object before transforming it into a string.
|
||||
-- A typical way to use it would be to remove certain values so that they don't appear at all.
|
||||
-- return <string> the prettied table
|
||||
table.inspect = require 'modules.exp_util.include.inspect' --- @dep modules.exp_util.includes.inspect
|
||||
|
||||
--- Takes a table and returns the number of entries in the table. (Slower than #table, faster than iterating via pairs)
|
||||
table.size = table_size
|
||||
|
||||
--- Creates a deepcopy of a table. Metatables and LuaObjects inside the table are shallow copies.
|
||||
-- Shallow copies meaning it copies the reference to the object instead of the object itself.
|
||||
-- @tparam table object The object to copy
|
||||
-- @treturn table The copied object
|
||||
table.deep_copy = table.deepcopy -- added by util
|
||||
|
||||
--- Merges multiple tables. Tables later in the list will overwrite entries from tables earlier in the list.
|
||||
-- Ex. merge({{1, 2, 3}, {[2] = 0}, {[3] = 0}}) will return {1, 0, 0}
|
||||
-- @tparam table tables A table of tables to merge
|
||||
-- @treturn table The merged table
|
||||
table.deep_merge = util.merge
|
||||
|
||||
--- Determines if two tables are structurally equal.
|
||||
-- Notice: tables that are LuaObjects or contain LuaObjects won't be compared correctly, use == operator for LuaObjects
|
||||
-- @tparam table tbl1 The first table
|
||||
-- @tparam table tbl2 The second table
|
||||
-- @treturn boolean True if the tables are equal
|
||||
table.equals = table.compare -- added by util
|
||||
|
||||
return table
|
||||
1
exp_util/module/locale/en.cfg
Normal file
1
exp_util/module/locale/en.cfg
Normal file
@@ -0,0 +1 @@
|
||||
time-symbol-days-short=__1__d
|
||||
16
exp_util/module/module.json
Normal file
16
exp_util/module/module.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "exp_util",
|
||||
"load": [
|
||||
"include/package.lua",
|
||||
"include/require.lua",
|
||||
"global.lua",
|
||||
"async.lua"
|
||||
],
|
||||
"require": [
|
||||
"include/math.lua",
|
||||
"include/table.lua"
|
||||
],
|
||||
"dependencies": {
|
||||
"clusterio": "*"
|
||||
}
|
||||
}
|
||||
1
exp_util/module/module_exports.lua
Normal file
1
exp_util/module/module_exports.lua
Normal file
@@ -0,0 +1 @@
|
||||
return require("modules/exp_util/common")
|
||||
33
exp_util/package.json
Normal file
33
exp_util/package.json
Normal file
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "@explosivegaming/util",
|
||||
"version": "0.0.1",
|
||||
"description": "Clusterio module for Lua overrides and compatibility utils",
|
||||
"author": "Cooldude2606 <https://github.com/Cooldude2606>",
|
||||
"license": "MIT",
|
||||
"repository": "explosivegaming/clustorio-exp-util",
|
||||
"main": "dist/node/index.js",
|
||||
"scripts": {
|
||||
"prepare": "tsc --build"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@clusterio/lib": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@clusterio/lib": "workspace:*",
|
||||
"@types/node": "^20.14.9",
|
||||
"typescript": "^5.5.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sinclair/typebox": "^0.30.4"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"keywords": [
|
||||
"clusterio",
|
||||
"factorio"
|
||||
]
|
||||
}
|
||||
6
exp_util/tsconfig.json
Normal file
6
exp_util/tsconfig.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
11
exp_util/tsconfig.node.json
Normal file
11
exp_util/tsconfig.node.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.node.json",
|
||||
"references": [
|
||||
{ "path": "../../../packages/lib/tsconfig.node.json" },
|
||||
],
|
||||
"include": ["./**/*.ts"],
|
||||
"exclude": ["test/*", "./dist/*"],
|
||||
"compilerOptions": {
|
||||
"outDir": "dist/node",
|
||||
},
|
||||
}
|
||||
Reference in New Issue
Block a user