Compare commits

...

No commits in common. "82818210753be59daf2f72d7520e51465f160b81" and "f69c55704cb4225195ab11edb13906b57f64c2c0" have entirely different histories.

282 changed files with 225 additions and 33787 deletions

160
.gitignore vendored
View file

@ -1,160 +0,0 @@
# ignore any files that start with '.secret'
.secret.*
.state/
# Docker .env files are generated from a Gradle task
.env
.idea/
!.idea/icon.svg
node_modules/
*.hprof
# Created by https://www.toptal.com/developers/gitignore/api/windows,macos,linux,gradle,intellij,visualstudiocode,kotlin
# Edit at https://www.toptal.com/developers/gitignore?templates=windows,macos,linux,gradle,intellij,visualstudiocode,kotlin
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# File-based project format
*.iws
*.iml
*.ipr
out/
### Kotlin ###
# Compiled class file
*.class
# Log file
*.log
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Ignore all local history of files
.history
.ionide
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
### Gradle ###
.gradle
build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project
.gradletasknamecache
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties
### Gradle Patch ###
**/build/
# Eclipse Gradle plugin generated files
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath
# End of https://www.toptal.com/developers/gitignore/api/windows,macos,linux,gradle,intellij,visualstudiocode,kotlin

646
LICENSE
View file

@ -1,674 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Copyright © 2007 Free Software Foundation, Inc. <https://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 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
“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.
“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.
“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.
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.
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 “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.
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.
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.
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.
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 "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" 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 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.
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.
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.
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.
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.
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.
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 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.
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:
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.
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”.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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 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.
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.
"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).
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.
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.
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.
"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.
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:
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
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
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
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
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
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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" 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.
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.
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.
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 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
Kafkatorio
Copyright (C) 2026 lazzexus
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 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.
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 <https://www.gnu.org/licenses/>.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://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:
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
Kafkatorio Copyright (C) 2026 lazzexus
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.
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".
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
<https://www.gnu.org/licenses/>.
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 <https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
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 <https://www.gnu.org/philosophy/why-not-lgpl.html>.

View file

@ -1,67 +1,2 @@
[![Mod Portal](https://img.shields.io/badge/dynamic/json?label=Mod%20Portal&query=%24.releases%5B-1%3A%5D.version&url=https%3A%2F%2Fmods.factorio.com%2Fapi%2Fmods%2Fkafkatorio-events&style=flat-square&color=%23600401)](https://mods.factorio.com/mod/kafkatorio-events)
[![Factorio Version](https://img.shields.io/badge/dynamic/json?label=Factorio%20Version&query=%24.releases%5B-1%3A%5D.info_json.factorio_version&url=https%3A%2F%2Fmods.factorio.com%2Fapi%2Fmods%2Fkafkatorio-events&style=flat-square&color=%23d7cdf6)](https://mods.factorio.com/mod/kafkatorio-events)
# Kafkatorio
[Kafkatorio](https://github.com/adamko-dev/kafkatorio) is a platform used for creating
[Factorio](https://www.factorio.com/) mods that require communication with an external server.
Development is ongoing.
At present Kafkatorio is used to create a [live-view web map](https://factorio.adamko.dev), that
shows the current status of a Factorio server, and any connected players.
However, Kafkatorio can be used for more than this. It has the potential to export metrics, and
allow for inter-server communication.
Kafkatorio was created to explore the possibilities of using
[Apache Kafka](https://kafka.apache.org/) to process updates from a Factorio server.
### Running
[Instructions for running a Kafkatorio instance are available in the docs](./docs/guide.md).
### Overview
This is a brief overview of how Kafkatorio gathers data, processes it, and uses it to create the
live web-map.
Kafkatorio receives updates from a Factorio server, processes them, and exposes them over a REST
and WebSocket APIs.
1. The Kafkatorio game mod, [`events-mod`](./modules/events-mod), collects event data, de-bouncing
and grouping events, and converts them to JSON packets
2. `events-mod` prints the packets to the Factorio game server logs
3. The Factorio logs are forwarded to a Kafka cluster, either using
* [syslog](https://docs.docker.com/config/containers/logging/syslog/) (using Docker logging
plugin)
* or [Kafka Pipe](./modules/infra-kafka-pipe) (a script that reads the server logs and forwards
them to a Kafka topic)
4. The packets are consumed by [`events-server`](./modules/events-server), which processes the
packets using Kafka Streams, creating and hosting map tiles.
`events-server` serves the map tiles via a REST API, and produces WebSocket messages regarding
updates (for example, when a player's location has changed).
5. The `web-map` uses Leaflet/JS to display the map, using the tiles and WebSocket messages from
`events-server`
```mermaid
sequenceDiagram
Factorio multiplayer server->>events-mod: in-game events
Note over events-mod: converts events to packets
events-mod->>logs processor: packets logged to console
logs processor->>Kafka: publishes packets<br/>(Requires API key!)
Kafka->>events-server:
Note over events-server: Packets are processed
events-server->>web-map: Web map tiles (REST API)
events-server-)web-map: WebSocket updates<br/>(e.g. player movement)
```
## License
Because I care about sharing improvements, Kafkatorio is licensed under the
[**GNU General Public License v3.0**](https://choosealicense.com/licenses/gpl-3.0/).

View file

@ -1,57 +0,0 @@
import java.time.LocalDate
import kafkatorio.extensions.excludeGeneratedGradleDsl
import kafkatorio.extensions.initIdeProjectLogo
plugins {
idea
base
id("kafkatorio.conventions.base")
// `project-report`
// `build-dashboard`
}
group = "dev.adamko.kafkatorio"
version = "0.10.1"
val licenseFile: RegularFile by extra(layout.projectDirectory.file("LICENSE"))
val projectTokens: MapProperty<String, String> by extra {
objects.mapProperty<String, String>().apply {
put("project.version", provider { "${project.version}" })
put("rootProject.name", provider { rootProject.name })
put("date.year", provider { "${LocalDate.now().year}" })
put("author.email", "adam@adamko.dev")
}
}
idea {
module {
isDownloadSources = true
isDownloadJavadoc = true
excludeGeneratedGradleDsl(layout)
excludeDirs = excludeDirs + layout.files(
".idea",
"gradle/kotlin-js-store",
"gradle/wrapper",
)
}
}
tasks.wrapper {
gradleVersion = "7.6"
distributionType = Wrapper.DistributionType.BIN
}
val runKafkatorio by tasks.registering {
group = rootProject.name
dependsOn(
":modules:infra-factorio-client:processRestart",
":modules:infra-factorio-server:processRestart",
":modules:infra-kafka-pipe:dockerUp",
)
}
apply(from = "$projectDir/kt52647.gradle.kts")
initIdeProjectLogo()

View file

@ -1,119 +0,0 @@
import kafkatorio.conventions.overrideKotlinLanguageVersion
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("kafkatorio.conventions.kotlin-dsl")
id("kafkatorio.conventions.kotlin-serialization")
// idea
// `kotlin-dsl`
// kotlin("jvm") //version "1.7.20" // embeddedKotlinVersion
// kotlin("plugin.serialization") // version embeddedKotlinVersion
// kotlin("plugin.serialization") version "1.7.20"
}
//val gradleJvmTarget = "11"
//val gradleKotlinTarget = "1.6"
dependencies {
implementation(platform(libs.kotlin.bom))
implementation("org.jetbrains.kotlin:kotlin-serialization:${libs.versions.kotlin.get()}")
implementation("org.jetbrains.kotlin:kotlin-reflect:${libs.versions.kotlin.get()}")
implementation("org.jetbrains.kotlin:kotlin-compiler-embeddable:${libs.versions.kotlin.get()}")
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:${libs.versions.kotlin.get()}")
implementation(platform(libs.kotlinx.coroutines.bom))
implementation(libs.kotlinx.coroutines.core)
implementation(platform(libs.kotlinxSerialization.bom))
implementation(libs.kotlinxSerialization.core)
implementation(libs.kotlinxSerialization.json)
// implementation("com.charleskorn.kaml:kaml:0.37.0")
implementation("com.github.node-gradle:gradle-node-plugin:${libs.versions.gradleNodePlugin.get()}")
implementation(platform(libs.kotest.bom))
implementation("io.kotest:kotest-framework-multiplatform-plugin-gradle")
implementation("io.kvision:io.kvision.gradle.plugin:${libs.versions.kvision.get()}")
implementation("net.swiftzer.semver:semver:${libs.versions.semver.get()}")
implementation(platform(libs.okio.bom))
implementation(libs.okio.core)
implementation(gradleKotlinDsl())
implementation(libs.kotlinx.cli)
implementation(platform(libs.ktor.bom))
implementation(libs.ktorClient.auth)
implementation(libs.ktorClient.contentNegotiation)
implementation(libs.ktorClient.core)
implementation(libs.ktorClient.encoding)
implementation(libs.ktorClient.logging)
implementation(libs.ktorClient.cio)
implementation(libs.ktorClient.resources)
implementation(libs.ktorSerialization.kotlinxJson)
// https://github.com/avast/gradle-docker-compose-plugin
// implementation("com.avast.gradle:gradle-docker-compose-plugin:${Versions.gradleDockerComposePlugin}")
// https://github.com/gradle/gradle/issues/15383#issuecomment-779893192
// https://youtrack.jetbrains.com/issue/IDEA-262280#focus=Comments-27-5397040.0-0
// implementation(files(libs.javaClass.superclass.protectionDomain.codeSource.location))
}
//tasks.compileKotlin {
// kotlinOptions {
// // needed by IntelliJ? Even though below does the same?
// languageVersion = "1.6"
// }
//}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
// jvmTarget = gradleJvmTarget
// apiVersion = gradleKotlinTarget
// languageVersion = gradleKotlinTarget
}
kotlinOptions.freeCompilerArgs += listOf(
// "-Xcontext-receivers",
"-opt-in=kotlin.RequiresOptIn",
"-opt-in=kotlin.ExperimentalStdlibApi",
"-opt-in=kotlin.time.ExperimentalTime",
// "-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi",
"-opt-in=kotlinx.serialization.ExperimentalSerializationApi",
)
}
overrideKotlinLanguageVersion("1.6")
//afterEvaluate {
// tasks.withType<KotlinCompile>().configureEach {
// kotlinOptions {
// apiVersion = gradleKotlinTarget
// languageVersion = gradleKotlinTarget
// }
// }
//}
//kotlin {
// jvmToolchain {
// (this as JavaToolchainSpec).languageVersion.set(JavaLanguageVersion.of(gradleJvmTarget))
// }
//}
//
//kotlinDslPluginOptions {
// jvmTarget.set(gradleJvmTarget)
//}
//idea {
// module {
// isDownloadSources = true
// isDownloadJavadoc = true
// }
//}

View file

@ -1,84 +0,0 @@
@Suppress("UnstableApiUsage") // Central declaration of repositories is an incubating feature
dependencyResolutionManagement {
// https://github.com/gradle/gradle/issues/15754#issuecomment-763614651
// https://github.com/gradle/gradle/blob/09fcaacc9848f09aa584b4119be9271bee6916e6/build-logic/build-logic-base/settings-plugin/src/main/kotlin/gradlebuild.repositories.settings.gradle.kts#L68
// Cannot use 'FAIL_ON_PROJECT_REPOS' because
// - the 'gradle-guides-plugin' adds a repo (which it should not do)
// - the 'kotlin-gradle-plugin' adds a repo (and removes it afterwards) to download NodeJS
// repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
repositories {
myMavenLocal()
mavenCentral()
// maven("https://s01.oss.sonatype.org/content/repositories/snapshots/") {
// mavenContent { snapshotsOnly() }
// }
jitpack()
gradlePluginPortal()
// Declare the Node.js download repository
ivy("https://nodejs.org/dist/") {
name = "Node Distributions at $url"
patternLayout { artifact("v[revision]/[artifact](-v[revision]-[classifier]).[ext]") }
metadataSources { artifact() }
content { includeModule("org.nodejs", "node") }
}
ivy("https://github.com/yarnpkg/yarn/releases/download") {
name = "Yarn Distributions at $url"
patternLayout { artifact("v[revision]/[artifact](-v[revision]).[ext]") }
metadataSources { artifact() }
content { includeModule("com.yarnpkg", "yarn") }
}
maven("https://raw.githubusercontent.com/adamko-dev/kotka-streams/artifacts/m2") {
content { includeGroup("dev.adamko.kotka") }
}
maven("https://maven.pkg.jetbrains.space/public/p/kotlinx-html/maven") {
content { includeGroup("org.jetbrains.kotlinx") }
}
sonatypeSnapshot()
}
pluginManagement {
repositories {
myMavenLocal()
gradlePluginPortal()
mavenCentral()
jitpack()
sonatypeSnapshot()
}
}
}
fun RepositoryHandler.jitpack() {
maven("https://jitpack.io")
}
fun RepositoryHandler.myMavenLocal(enabled: Boolean = true) {
if (enabled) {
logger.lifecycle("Maven local is enabled")
mavenLocal {
content {
// includeGroup("dev.adamko")
// includeGroup("dev.adamko.kxtsgen")
includeGroup("io.kotest")
}
}
}
}
fun RepositoryHandler.sonatypeSnapshot() {
maven("https://oss.sonatype.org/content/repositories/snapshots") {
mavenContent {
snapshotsOnly()
includeGroup("io.kotest")
}
}
}

View file

@ -1,12 +0,0 @@
rootProject.name = "buildSrc"
apply(from = "./repositories.settings.gradle.kts")
@Suppress("UnstableApiUsage") // Central declaration of repositories is an incubating feature
dependencyResolutionManagement {
versionCatalogs {
create("libs") {
from(files("../gradle/libs.versions.toml"))
}
}
}

View file

@ -1,28 +0,0 @@
import org.gradle.api.Task
import org.gradle.api.artifacts.Configuration
import org.gradle.api.tasks.TaskCollection
// to be moved into gradle-plugins/builder-plugins...
fun Configuration.asProvider() {
isVisible = false
isCanBeResolved = false
isCanBeConsumed = true
}
fun Configuration.asConsumer() {
isVisible = false
isCanBeResolved = true
isCanBeConsumed = false
}
//
//fun Configuration.typescriptAttributes(objects: ObjectFactory): Configuration =
// attributes {
// attribute(Usage.USAGE_ATTRIBUTE, objects.named("dev.adamko.gradle.factorio.typescriptFiles"))
// }
fun <T : Task> TaskCollection<T>.withName(name: String): TaskCollection<T> =
matching { it.name == name }

View file

@ -1,52 +0,0 @@
# Running Kafkatorio
### Building the project
#### Requirements
* Docker
* Docker Compose
* Java 11
Kafkatorio uses [Gradle](https://docs.gradle.org/current/userguide/getting_started.html) to
build the project, and Docker Compose to create images.
* `./gradlew build` - build and test the project
* `./gradlew runKafkatorio` - run locally (if Docker is running, a Kafka instance will start)
* `./gradlew dockerComposeBuild` - build, test, and create Kafkatorio Docker images
### Server set up
> See [./kafkatorio-platform/docker-compose.yml](kafkatorio-platform/docker-compose.yml) for a
> complete example
1. Copy the [kafkatorio-platform](./kafkatorio-platform) directory to your computer
2. Rename
[`example.secret.kafkatorio-config.yml`](./kafkatorio-platform/example.secret.kafkatorio-config.yml)
to `.secret.kafkatorio-config.yml`
In it, define both
* a JWT secret password (a long alphanumeric string is best, you won't need to type this
password manually)
* a Factorio server, with a short-ID and a description.
3. Rename [`example.env`](./kafkatorio-platform/example.env) to `.env`
4. Create a JWT for your Factorio server, by going to https://jwt.io/
* In 'PAYLOAD: DATA', set `sub` to your Factorio server's short ID.
```json
{
"sub": "<your server short ID>",
"iat": ...
}
```
(`iat`, 'issued-at-time', should update automatically to be the current time.)
* Replace `your-256-bit-secret` with your JWT secret password
Copy the 'Encoded' token (it should start with `ey`).
In the `.env` file, set `KAFKATORIO_TOKEN` to equal the token.
5. In `kafkatorio-platform`, start the docker containers
```terminal
docker-compose up -d; docker-compose logs -f
```

View file

@ -1,130 +0,0 @@
# This configuration file is intended for use in KRaft mode, where
# Apache ZooKeeper is not present. See config/kraft/README.md for details.
############################# Server Basics #############################
# The role of this server. Setting this puts us in KRaft mode
process.roles=broker,controller
# The node id associated with this instance's roles
node.id=1
# The connect string for the controller quorum
controller.quorum.voters=1@localhost:9093
############################# Socket Server Settings #############################
# The address the socket server listens on. It will get the value returned from
# java.net.InetAddress.getCanonicalHostName() if not configured.
# FORMAT:
# listeners = listener_name://host_name:port
# EXAMPLE:
# listeners = PLAINTEXT://your.host.name:9092
#listeners=PLAINTEXT://:9092,CONTROLLER://:9093
#listeners=PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092,CONTROLLER://localhost:9093
listeners=PLAINTEXT://:29092,PLAINTEXT_HOST://:9092,CONTROLLER://:9093
inter.broker.listener.name=PLAINTEXT
#KAFKA_INTER_BROKER_LISTENER_NAME: "PLAINTEXT"
# Hostname and port the broker will advertise to producers and consumers. If not set,
# it uses the value for "listeners" if configured. Otherwise, it will use the value
# returned from java.net.InetAddress.getCanonicalHostName().
#advertised.listeners=PLAINTEXT://localhost:9092
advertised.listeners=PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
# Listener, host name, and port for the controller to advertise to the brokers. If
# this server is a controller, this listener must be configured.
controller.listener.names=CONTROLLER
# Maps listener names to security protocols, the default is for them to be the same. See the config documentation for more details
#listener.security.protocol.map=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL
listener.security.protocol.map=CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
# ,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL
# The number of threads that the server uses for receiving requests from the network and sending responses to the network
num.network.threads=3
# The number of threads that the server uses for processing requests, which may include disk I/O
num.io.threads=8
# The send buffer (SO_SNDBUF) used by the socket server
socket.send.buffer.bytes=102400
# The receive buffer (SO_RCVBUF) used by the socket server
socket.receive.buffer.bytes=102400
# The maximum size of a request that the socket server will accept (protection against OOM)
socket.request.max.bytes=104857600
############################# Log Basics #############################
# A comma separated list of directories under which to store log files
log.dirs=/tmp/kraft-combined-logs
# The default number of log partitions per topic. More partitions allow greater
# parallelism for consumption, but this will also result in more files across
# the brokers.
num.partitions=3
# The number of threads per data directory to be used for log recovery at startup and flushing at shutdown.
# This value is recommended to be increased for installations with data dirs located in RAID array.
num.recovery.threads.per.data.dir=1
############################# Internal Topic Settings #############################
# The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state"
# For anything other than development testing, a value greater than 1 is recommended to ensure availability such as 3.
offsets.topic.replication.factor=1
transaction.state.log.replication.factor=1
transaction.state.log.min.isr=1
############################# Log Flush Policy #############################
# Messages are immediately written to the filesystem but by default we only fsync() to sync
# the OS cache lazily. The following configurations control the flush of data to disk.
# There are a few important trade-offs here:
# 1. Durability: Unflushed data may be lost if you are not using replication.
# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush.
# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to excessive seeks.
# The settings below allow one to configure the flush policy to flush data after a period of time or
# every N messages (or both). This can be done globally and overridden on a per-topic basis.
# The number of messages to accept before forcing a flush of data to disk
#log.flush.interval.messages=10000
# The maximum amount of time a message can sit in a log before we force a flush
#log.flush.interval.ms=1000
############################# Log Retention Policy #############################
# The following configurations control the disposal of log segments. The policy can
# be set to delete segments after a period of time, or after a given size has accumulated.
# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens
# from the end of the log.
# The minimum age of a log file to be eligible for deletion due to age
log.retention.hours=168
# A size-based retention policy for logs. Segments are pruned from the log unless the remaining
# segments drop below log.retention.bytes. Functions independently of log.retention.hours.
#log.retention.bytes=1073741824
# The maximum size of a log segment file. When this size is reached a new log segment will be created.
log.segment.bytes=1073741824
# The interval at which log segments are checked to see if they can be deleted according
# to the retention policies
log.retention.check.interval.ms=300000
### Compression ###
#compression.type=snappy
#linger.ms=5
### record size ###
message.max.bytes=10485760
replica.fetch.max.bytes=10485760
#log.cleanup.policy=compact
#auto.create.topics.enable=false

View file

@ -1,140 +0,0 @@
version: "3.9"
services:
## Factorio game server that players will connect to
factorio-server:
image: factoriotools/factorio:${FACTORIO_VERSION}
container_name: "factorio-server"
restart: unless-stopped
profiles: [ "factorio", "kafkatorio" ]
networks:
- kafkatorio-infra-nw
ports:
- "34198:34197/udp" # factorio
- "27016:27015/tcp" # rcon
volumes:
- "./factorio-server:/factorio"
logging:
# set up syslog, so logs can be forwarded to Kafkatorio
driver: syslog
options:
syslog-address: ${SYSLOG_ADDRESS}
syslog-format: "rfc5424"
# set the tag to be a JWT, containing the server short-ID
tag: ${KAFKATORIO_TOKEN}
## Kafkatorio Web Map host
web-map:
image: ${REGISTRY_HOST}/dev.adamko.kafkatorio/web-map:${KAFKATORIO_VERSION}
container_name: web-map
profiles: [ "infra", "kafkatorio" ]
restart: unless-stopped
networks:
- kafkatorio-infra-nw
## Process Kafkatorio events
events-processors:
image: ${REGISTRY_HOST}/dev.adamko.kafkatorio/events-processors:${KAFKATORIO_VERSION}
container_name: events-processors
restart: unless-stopped
profiles: [ "infra", "kafkatorio" ]
environment:
KAFKA_BOOTSTRAP_SERVERS: "kafka:29092"
networks:
- kafkatorio-infra-nw
depends_on:
- infra-kafka
secrets:
- source: kafkatorio_config
target: /.secret.config.yml
## Receives packets from the Factorio Server, forwarded via Docker syslog-plugin
events-server-syslog:
image: ${REGISTRY_HOST}/dev.adamko.kafkatorio/events-server-syslog:${KAFKATORIO_VERSION}
container_name: events-server-syslog
restart: unless-stopped
profiles: [ "infra", "kafkatorio" ]
environment:
KAFKA_BOOTSTRAP_SERVERS: "kafka:29092"
SOCKET_SERVER_HOST: "0.0.0.0"
SOCKET_SERVER_PORT: "9002"
ports:
- "12035:9002" # syslog socket
networks:
- kafkatorio-infra-nw
depends_on:
- infra-kafka
- events-processors
secrets:
- source: kafkatorio_config
target: /.secret.config.yml
## Hosts map-tiles and forwards websocket messages to the web-map browsers
events-server-web:
image: ${REGISTRY_HOST}/dev.adamko.kafkatorio/events-server-web:${KAFKATORIO_VERSION}
container_name: events-server-web
restart: unless-stopped
profiles: [ "infra", "kafkatorio" ]
environment:
KAFKA_BOOTSTRAP_SERVERS: "kafka:29092"
WEB_SERVER_PORT: "80"
ports:
- "12080:80" # http and ws
networks:
- kafkatorio-infra-nw
depends_on:
- infra-kafka
- events-processors
secrets:
- source: kafkatorio_config
target: /.secret.config.yml
## An instance of Kafka
infra-kafka:
image: ${REGISTRY_HOST}/dev.adamko.kafkatorio/kafka-kraft:${KAFKATORIO_VERSION}
container_name: infra-kafka
restart: unless-stopped
profiles: [ "infra", "kafka" ]
networks:
kafkatorio-infra-nw:
aliases: [ kafka ]
volumes:
- "./config/kafka-server.properties:/kafka/server.properties"
ports:
# note: other Docker containers should use 29092
- "9092:9092"
- "9093:9093"
## web-based GUI for Kafka
infra-kafka-ui:
image: provectuslabs/kafka-ui:v0.4.0
container_name: infra-kafka-ui
restart: unless-stopped
profiles: [ "infra", "kafka" ]
networks:
- kafkatorio-infra-nw
ports:
- "18090:8080"
depends_on:
- infra-kafka
environment:
KAFKA_CLUSTERS_0_NAME: "${COMPOSE_PROJECT_NAME}"
KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: "kafka:29092"
secrets:
kafkatorio_config:
file: ./.secret.kafkatorio-config.yml
networks:
kafkatorio-infra-nw:
kafkatorio-game-nw:

View file

@ -1,10 +0,0 @@
# Docker Compose containers config
COMPOSE_PROJECT_NAME=Kafkatorio
KAFKATORIO_TOKEN=<jwt token>
KAFKATORIO_VERSION=0.9.15
REGISTRY_HOST=localhost
SYSLOG_ADDRESS=tcp://www.my-website.com:12345

View file

@ -1,10 +0,0 @@
# Kafkatorio server config
jwt-secret: "correct horse battery staple"
# Define the servers that have the Kafkatorio Mod installed.
kafkatorio-servers:
# The key is the short ID, used to uniquely identify a server (used in URLs).
# The value is a description.
short-id-123: "Name of server"
another-id-456: "Name of another server"

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

View file

@ -1,71 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
id="kafkatorio-logo"
version="1.1"
viewBox="0 0 132.29166 132.29167"
height="500"
width="500"
xmlns="http://www.w3.org/2000/svg">
<defs
id="defs887">
<linearGradient
id="linearGradient24276">
<stop
style="stop-color:#ffffff;stop-opacity:1;"
offset="0"
id="stop24274" />
</linearGradient>
</defs>
<g
id="layer4"
style="display:inline">
<g
id="g3104">
<rect
style="font-variation-settings:normal;display:inline;vector-effect:none;fill:#000000;fill-opacity:1;stroke:#000000;stroke-width:0.159004;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;paint-order:markers stroke fill;stop-color:#000000"
id="rect22651"
width="132.29167"
height="132.29167"
x="0.079501145"
y="0.079499409"
ry="15.697195" />
<rect
style="font-variation-settings:normal;display:inline;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:0.150548;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;paint-order:markers stroke fill;stop-color:#000000"
id="rect28806"
width="125.36403"
height="125.36403"
x="3.5433378"
y="3.5433209"
ry="14.875189" />
</g>
</g>
<g
id="g7215"
style="display:inline">
<g
id="g9039"
style="fill:#2f2f2f;fill-opacity:1;font-variation-settings:normal;opacity:1;vector-effect:none;stroke:none;stroke-width:0.277019;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;paint-order:markers stroke fill;stop-color:#000000;stop-opacity:1">
<path
id="path2906"
style="font-variation-settings:normal;display:inline;vector-effect:none;fill:#2f2f2f;fill-opacity:1;stroke:none;stroke-width:1.04700096;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;-inkscape-stroke:none;paint-order:markers stroke fill;stop-color:#000000;opacity:1;stop-opacity:1"
d="m 177.00391,116.69531 v 60.4961 c -9.73134,1.70815 -18.8058,5.33994 -26.82032,10.48437 l -14.75976,-10.16797 -0.20313,-0.16211 c -6.08162,3.89957 -11.43071,9.25469 -15.90234,15.69922 l -0.0918,-0.0586 10.08789,14.89453 c -5.31415,7.70625 -9.18803,16.4722 -11.23242,25.91992 l -17.80273,2.87891 -0.25977,0.0234 c -1.697347,7.02192 -1.858163,14.58862 -0.632811,22.33594 l -0.109375,0.0215 18.224606,3.92187 0.16993,-0.0703 c 1.70045,9.13524 5.14078,17.99127 10.29687,26.03125 l -0.17773,0.0801 -10.39063,14.75976 -0.16601,0.20313 c 3.83719,6.12056 9.1367,11.52408 15.53515,16.06055 l -0.0586,0.0918 15.53711,-10.29297 c 8.97962,6.16727 18.98443,10.09232 29.26367,11.80469 v 62.12305 h 24.35547 V 321.6172 c 15.62848,-2.64498 30.51426,-10.36344 41.98047,-23.02344 0.90915,-1.00382 1.78144,-2.02833 2.625,-3.06836 l 54.59765,35.54688 11.86133,-21.44336 -54.42383,-35.42969 c 0.0994,-0.27357 0.18488,-0.55315 0.28125,-0.82813 2.64834,-7.55642 4.17188,-15.63687 4.17188,-24.08593 0,-8.60478 -1.56797,-16.82976 -4.30469,-24.50586 L 311.125,187.99805 299.21289,166.60938 246.72656,203.40039 C 235.6081,189.60708 219.599,179.97686 201.35938,177.03711 v -60.07813 z m 12.68359,94.22852 c 21.15216,0 38.36133,17.20803 38.36133,38.36133 0,21.15216 -17.20917,38.35742 -38.36133,38.35742 -21.15326,0 -38.36133,-17.20526 -38.36133,-38.35742 0,-21.1533 17.20807,-38.36133 38.36133,-38.36133 z"
transform="scale(0.26458333)" />
<path
id="path7213"
style="color:#000000;fill:#2f2f2f;stroke:none;stroke-width:0.277019;-inkscape-stroke:none;paint-order:markers stroke fill;fill-opacity:1;font-variation-settings:normal;vector-effect:none;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;stop-color:#000000;stop-opacity:1"
d="m 50.128106,8.9533314 c -0.533535,0.00315 -1.076759,0.051081 -1.62419,0.1421101 l -0.145727,0.025321 0.02481,0.1028361 -0.582909,2.8101644 c -1.466601,0.297805 -2.828065,0.864653 -4.035414,1.644344 l -2.322857,-1.584916 -0.0031,0.0026 -0.06563,-0.105421 -0.117306,0.077 c -0.985745,0.638295 -1.849646,1.509846 -2.567802,2.5554 l -0.08268,0.123507 0.09147,0.05374 1.591636,2.325439 c -0.787769,1.197243 -1.362,2.542733 -1.673293,3.980124 l -2.732132,0.535885 v 0.0036 l -0.123508,-0.02791 -0.02687,0.136942 c -0.23695,1.15021 -0.221318,2.377698 0.01964,3.623035 l 0.02894,0.145727 0.103354,-0.0279 2.703711,0.486276 c 0.29917,1.469819 0.868,2.834569 1.651061,4.04368 l -1.603518,2.281516 10e-4,0.0015 -0.107487,0.0646 0.07441,0.118853 c 0.624089,0.994796 1.485112,1.870363 2.52026,2.60346 l 0.121441,0.08682 0.05633,-0.09353 2.395201,-1.5875 c 1.194732,0.782899 2.536923,1.353658 3.969785,1.662945 l 0.515731,2.771926 h 0.0031 l -0.02894,0.122989 0.138493,0.02946 c 1.147731,0.248642 2.373717,0.244102 3.621484,0.0155 l 0.147794,-0.02687 -0.02739,-0.104902 0.531749,-2.790529 c 1.458415,-0.301307 2.812471,-0.868637 4.013192,-1.646928 l 2.35748,1.592668 0.0021,-0.0021 0.06615,0.104902 0.117306,-0.07648 c 0.98248,-0.643308 1.842571,-1.521182 2.555401,-2.570385 l 0.0827,-0.123507 -0.093,-0.05374 -1.612312,-2.332675 c 0.757187,-1.157091 1.315212,-2.452105 1.629882,-3.833874 l 2.74763,-0.481624 v -0.0021 l 0.12144,0.02997 0.031,-0.136426 c 0.26059,-1.145077 0.27002,-2.373503 0.0548,-3.623551 l -0.0269,-0.147795 -0.10645,0.02635 -2.74609,-0.552938 c -0.28086,-1.447346 -0.823273,-2.797849 -1.576674,-4.00124 l 1.626254,-2.244307 -0.001,-10e-4 0.10749,-0.06304 -0.0724,-0.120923 c -0.609755,-1.003638 -1.457459,-1.891281 -2.482,-2.63912 l -0.120406,-0.08837 -0.05839,0.09405 -2.397786,1.539958 C 55.568068,12.999715 54.18603,12.395711 52.701598,12.070453 L 52.235993,9.323851 h -0.0031 l 0.03049,-0.1209228 -0.135911,-0.033073 C 51.484233,9.0195324 50.814086,8.9492834 50.128111,8.953331 Z m 0.09974,9.9937046 c 0.839637,0.01115 1.627074,0.243738 2.305286,0.643372 0,0 5.16e-4,0 5.16e-4,0 1.294561,0.762983 2.190752,2.13424 2.289265,3.734139 0.158403,2.572068 -1.795772,4.782211 -4.367176,4.942851 -0.0012,7.6e-5 -0.0029,4.41e-4 -0.0041,5.15e-4 -1.206166,0.07428 -2.332545,-0.315841 -3.20549,-1.015957 0,0 -5.16e-4,0 -5.16e-4,0 -0.116398,-0.09337 -0.227899,-0.19258 -0.334862,-0.296622 -0.106966,-0.104042 -0.209219,-0.213127 -0.305924,-0.327112 -0.62859,-0.740902 -1.031664,-1.684077 -1.096058,-2.72955 -0.02475,-0.401926 0.0023,-0.795244 0.07493,-1.173055 0,0 0,-5.17e-4 0,-5.17e-4 0.392531,-2.041 2.122953,-3.635537 4.294312,-3.769279 0.116091,-0.0072 0.233547,-0.0103 0.34985,-0.0088 z" />
<path
id="path7752"
style="color:#000000;fill:#2f2f2f;stroke:none;stroke-width:0.277019;-inkscape-stroke:none;paint-order:markers stroke fill;fill-opacity:1;font-variation-settings:normal;vector-effect:none;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;stop-color:#000000;stop-opacity:1"
d="m 90.621778,30.353755 c -0.514798,-0.140187 -1.050973,-0.23974 -1.602753,-0.298951 l -0.147177,-0.01471 -0.0037,0.105722 -1.315631,2.550671 c -1.492725,-0.106678 -2.956366,0.07403 -4.32866,0.501137 l -1.81235,-2.150119 -0.0037,0.0017 -0.03493,-0.119166 -0.133667,0.0427 c -1.120875,0.35036 -2.186969,0.958118 -3.159357,1.772608 l -0.11279,0.09679 0.07369,0.07631 0.909231,2.667259 c -1.080154,0.941935 -1.994383,2.083981 -2.679979,3.385116 l -2.775727,-0.216933 -9.66e-4,0.0035 -0.111488,-0.06003 -0.06263,0.124709 c -0.536916,1.044437 -0.851251,2.231098 -0.953315,3.495419 l -0.01123,0.148148 0.10705,8.58e-4 2.474053,1.193977 c -0.106226,1.49619 0.07551,2.963529 0.505389,4.338425 l -2.156945,1.767533 5.61e-4,0.0017 -0.12088,0.03339 0.03979,0.134462 c 0.334247,1.125782 0.928732,2.200289 1.729188,3.184277 l 0.09369,0.116224 0.07936,-0.07498 2.733353,-0.886526 c 0.940822,1.074788 2.080622,1.984787 3.377933,2.667236 l -0.247027,2.808653 0.003,8.32e-4 -0.06088,0.110712 0.125508,0.06554 c 1.038912,0.547514 2.22115,0.872132 3.484496,0.986751 l 0.149584,0.01378 0.0018,-0.108404 1.261079,-2.545484 c 1.485779,0.101107 2.942413,-0.08206 4.307947,-0.509589 l 1.843622,2.166877 0.0026,-0.0015 0.03557,0.118806 0.133527,-0.0422 c 1.119075,-0.356066 2.183196,-0.970938 3.151432,-1.790372 l 0.11281,-0.09678 -0.07517,-0.07673 -0.927207,-2.679778 c 1.039919,-0.911461 1.924991,-2.009232 2.598915,-3.255879 l 2.7761,0.273363 5.6e-4,-0.002 0.108943,0.06146 0.0665,-0.123103 c 0.55831,-1.033149 0.89704,-2.213988 1.02516,-3.475941 l 0.0138,-0.149593 -0.10962,-0.0032 -2.496993,-1.269566 c 0.117834,-1.469629 -0.04228,-2.916153 -0.44512,-4.27758 l 2.168863,-1.725588 -6.9e-4,-0.0012 0.12046,-0.03188 -0.0373,-0.135916 c -0.318073,-1.130453 -0.896487,-2.213019 -1.682769,-3.208363 l -0.09228,-0.117439 -0.08149,0.07493 -2.723085,0.840033 c -0.95337,-1.124284 -2.122634,-2.077002 -3.465338,-2.788675 l 0.288519,-2.770806 -0.003,-8.32e-4 0.06182,-0.108306 -0.122051,-0.06833 c -0.579308,-0.317422 -1.206024,-0.564927 -1.867925,-0.745108 z m -2.585711,9.653921 c 0.805849,0.236056 1.501989,0.67142 2.048085,1.238394 0,0 4.97e-4,1.38e-4 4.97e-4,1.38e-4 1.042334,1.082391 1.53768,2.643845 1.20325,4.211498 -0.537617,2.520237 -3.013205,4.124917 -5.533402,3.589634 -0.0012,-2.49e-4 -0.0029,-3.54e-4 -0.0041,-6.04e-4 -1.181859,-0.252117 -2.162236,-0.930191 -2.815289,-1.838882 0,0 -4.97e-4,-1.38e-4 -4.97e-4,-1.38e-4 -0.08707,-0.121181 -0.167861,-0.246673 -0.242982,-0.375602 -0.07512,-0.12893 -0.144353,-0.261454 -0.206923,-0.397209 -0.406715,-0.882408 -0.541906,-1.899153 -0.323387,-2.92356 0.08401,-0.393826 0.215618,-0.765459 0.386969,-1.109923 0,0 1.39e-4,-4.98e-4 1.39e-4,-4.98e-4 0.925832,-1.860805 3.020677,-2.932502 5.148284,-2.478658 0.113765,0.02422 0.227745,0.05275 0.33938,0.0854 z" />
<path
id="path7754"
style="color:#000000;fill:#2f2f2f;stroke:none;stroke-width:0.277019;-inkscape-stroke:none;paint-order:markers stroke fill;fill-opacity:1;font-variation-settings:normal;vector-effect:none;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;stop-color:#000000;stop-opacity:1"
d="m 82.977619,73.20863 c -0.511668,0.151213 -1.020175,0.34823 -1.520761,0.587771 l -0.132955,0.06481 0.0524,0.09189 0.2208,2.861479 c -1.326119,0.693552 -2.476491,1.616344 -3.419681,2.70078 l -2.671748,-0.877147 -0.0022,0.0033 -0.09234,-0.08303 -0.09129,0.10656 c -0.769595,0.887038 -1.357337,1.964297 -1.756728,3.168214 l -0.04511,0.141616 0.1028,0.02621 2.175057,1.791673 c -0.424118,1.368976 -0.601918,2.821033 -0.501599,4.288321 l -2.475679,1.273866 0.001,0.0035 -0.1264,0.0075 0.01225,0.139015 c 0.09195,1.170758 0.448,2.345575 1.025469,3.474936 l 0.06829,0.131949 0.09153,-0.05552 2.732367,-0.284053 c 0.695758,1.328832 1.621366,2.481809 2.70953,3.425755 l -0.906503,2.637202 0.0014,0.0012 -0.0853,0.09192 0.104502,0.0935 c 0.875906,0.782236 1.946293,1.384113 3.144364,1.800743 l 0.140781,0.0496 0.02812,-0.1055 1.859838,-2.190461 c 1.36521,0.420138 2.813135,0.595519 4.275513,0.494531 l 1.265561,2.51949 0.003,-8.5e-4 0.0064,0.12618 0.141243,-0.01 c 1.171623,-0.08 2.34808,-0.425 3.483208,-0.99128 l 0.134503,-0.0669 -0.05546,-0.0931 -0.26449,-2.828397 c 1.317283,-0.694642 2.460405,-1.615839 3.397617,-2.697089 l 2.707161,0.874974 0.0014,-0.0026 0.09269,0.0824 0.09143,-0.106061 c 0.765066,-0.890946 1.347391,-1.97322 1.740651,-3.179164 l 0.0451,-0.141621 -0.10427,-0.02579 -2.19693,-1.79288 c 0.405897,-1.321908 0.582153,-2.720975 0.500531,-4.135768 l 2.505639,-1.226046 -5.8e-4,-0.002 0.12498,-0.005 -0.008,-0.139676 c -0.0679,-1.172394 -0.40005,-2.355076 -0.9541,-3.496113 l -0.0669,-0.134503 -0.0949,0.05488 -2.791593,0.231788 c -0.671924,-1.312331 -1.568198,-2.458962 -2.62628,-3.405654 l 0.938681,-2.607775 -0.0012,-6.84e-4 0.08574,-0.09042 -0.103146,-0.09604 c -0.864594,-0.794713 -1.92554,-1.411888 -3.11752,-1.845631 l -0.140217,-0.05144 -0.02996,0.10657 -1.87553,2.145515 C 89.327899,75.584406 87.83246,75.38816 86.316104,75.488133 l -1.210374,-2.509104 -0.003,8.61e-4 -0.0043,-0.124634 -0.139749,0.006 c -0.659678,0.03431 -1.322958,0.153015 -1.980802,0.347491 z m 2.872405,9.572533 c 0.809678,-0.222569 1.630733,-0.217914 2.393276,-0.02244 0,0 4.95e-4,-1.43e-4 4.95e-4,-1.43e-4 1.455576,0.37327 2.697465,1.441547 3.236606,2.951085 0.866774,2.426795 -0.39641,5.092859 -2.821943,5.961597 -0.0011,4.06e-4 -0.0027,0.0013 -0.0038,0.0017 -1.138041,0.40647 -2.328463,0.344655 -3.361555,-0.08536 0,0 -4.95e-4,1.43e-4 -4.95e-4,1.43e-4 -0.137757,-0.05735 -0.272432,-0.121679 -0.40409,-0.191907 -0.131661,-0.07023 -0.260196,-0.146608 -0.384762,-0.229238 -0.80969,-0.537088 -1.45894,-1.331141 -1.811268,-2.317562 -0.135444,-0.379226 -0.218736,-0.764574 -0.253935,-1.14769 0,0 -1.44e-4,-4.96e-4 -1.44e-4,-4.96e-4 -0.189982,-2.069702 1.029295,-4.082231 3.078007,-4.813986 0.10952,-0.03917 0.22149,-0.07479 0.333632,-0.105655 z" />
<path
id="path7756"
style="color:#000000;fill:#2f2f2f;stroke:none;stroke-width:0.277019;-inkscape-stroke:none;paint-order:markers stroke fill;fill-opacity:1;font-variation-settings:normal;vector-effect:none;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;stop-color:#000000;stop-opacity:1"
d="m 50.246826,94.1604 c -0.533535,0.0031 -1.076759,0.05108 -1.62419,0.14211 l -0.145727,0.02532 0.02481,0.102836 -0.582909,2.810165 c -1.466601,0.297805 -2.828065,0.864653 -4.035414,1.644344 l -2.322857,-1.584916 -0.0031,0.0026 -0.06563,-0.105421 -0.117306,0.077 c -0.985745,0.638295 -1.849646,1.509846 -2.567802,2.5554 l -0.08268,0.123505 0.09147,0.0537 1.591636,2.32544 c -0.787769,1.19724 -1.362,2.54273 -1.673293,3.98012 l -2.732132,0.53589 v 0.004 l -0.123508,-0.0279 -0.02687,0.13694 c -0.23695,1.15021 -0.221318,2.3777 0.01964,3.62304 l 0.02894,0.14572 0.103354,-0.0279 2.703711,0.48628 c 0.29917,1.46982 0.868,2.83457 1.651061,4.04368 l -1.603518,2.28152 0.001,0.001 -0.107487,0.0646 0.07441,0.11885 c 0.624089,0.99479 1.485112,1.87036 2.52026,2.60346 l 0.121441,0.0868 0.05633,-0.0935 2.395201,-1.5875 c 1.194732,0.7829 2.536923,1.35366 3.969785,1.66294 l 0.515731,2.77193 h 0.0031 l -0.02894,0.12299 0.138493,0.0295 c 1.147731,0.24864 2.373717,0.2441 3.621484,0.0155 l 0.147794,-0.0269 -0.02739,-0.1049 0.531749,-2.79053 c 1.458415,-0.30131 2.812471,-0.86864 4.013192,-1.64693 l 2.35748,1.59267 0.0021,-0.002 0.06615,0.1049 0.117306,-0.0765 c 0.98248,-0.64331 1.842571,-1.52118 2.555401,-2.57039 l 0.0827,-0.1235 -0.093,-0.0537 -1.612312,-2.33268 c 0.757187,-1.15709 1.315212,-2.4521 1.629882,-3.83387 L 64.554,110.96448 v -0.002 l 0.12144,0.03 0.031,-0.13642 c 0.26059,-1.14508 0.27002,-2.3735 0.0548,-3.62355 l -0.0269,-0.1478 -0.10645,0.0263 -2.746088,-0.55294 c -0.28086,-1.44734 -0.823273,-2.79784 -1.576674,-4.00124 l 1.626254,-2.2443 -10e-4,-10e-4 0.10749,-0.063 -0.0724,-0.12093 c -0.609755,-1.00363 -1.457459,-1.891273 -2.482,-2.639112 l -0.120406,-0.08837 -0.05839,0.09405 -2.397786,1.539958 c -1.220102,-0.827343 -2.60214,-1.431347 -4.086572,-1.756605 l -0.465605,-2.746602 h -0.0031 l 0.03049,-0.120923 -0.135911,-0.03307 c -0.643239,-0.150323 -1.313386,-0.220572 -1.999361,-0.216524 z m 0.09974,9.9937 c 0.839637,0.0112 1.627074,0.24374 2.305286,0.64337 0,0 5.16e-4,0 5.16e-4,0 1.294561,0.76299 2.190752,2.13424 2.289265,3.73414 0.158403,2.57207 -1.795772,4.78221 -4.367176,4.94285 -0.0012,8e-5 -0.0029,4.4e-4 -0.0041,5.2e-4 -1.206166,0.0743 -2.332545,-0.31584 -3.20549,-1.01596 0,0 -5.16e-4,0 -5.16e-4,0 -0.116398,-0.0934 -0.227899,-0.19258 -0.334862,-0.29662 -0.106966,-0.10404 -0.209219,-0.21313 -0.305924,-0.32711 -0.62859,-0.7409 -1.031664,-1.68408 -1.096058,-2.72955 -0.02475,-0.40193 0.0023,-0.79525 0.07493,-1.17306 0,0 0,-5.1e-4 0,-5.1e-4 0.392531,-2.041 2.122953,-3.63554 4.294312,-3.76928 0.116091,-0.007 0.233547,-0.0103 0.34985,-0.009 z" />
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 16 KiB

View file

@ -1,43 +0,0 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("kafkatorio.conventions.kotlin-dsl")
}
dependencies {
implementation(platform(libs.kotlin.bom))
implementation("org.jetbrains.kotlin:kotlin-serialization")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-compiler-embeddable")
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:${libs.versions.kotlin.get()}")
implementation(platform(libs.kotlinx.coroutines.bom))
implementation(libs.kotlinx.coroutines.core)
implementation(platform(libs.kotlinxSerialization.bom))
implementation(libs.kotlinxSerialization.core)
implementation(libs.kotlinxSerialization.json)
implementation("com.github.node-gradle:gradle-node-plugin:${libs.versions.gradleNodePlugin.get()}")
implementation(platform(libs.kotest.bom))
implementation("io.kotest:kotest-framework-multiplatform-plugin-gradle")
implementation(libs.gradlePlugin.kvision)
implementation(libs.semver)
implementation(platform(libs.okio.bom))
implementation(libs.okio.core)
implementation(libs.kotlinx.cli)
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions.freeCompilerArgs += listOf(
"-opt-in=kotlin.ExperimentalStdlibApi",
"-opt-in=kotlin.time.ExperimentalTime",
"-opt-in=kotlinx.serialization.ExperimentalSerializationApi",
)
}

View file

@ -1,24 +0,0 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm")
}
val gradleJvmTarget = "11"
dependencies {
implementation(platform(kotlin("bom")))
implementation(gradleApi())
}
kotlin {
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(gradleJvmTarget))
}
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
jvmTarget = gradleJvmTarget
}
}

View file

@ -1,17 +0,0 @@
package kafkatorio.common
import org.gradle.api.artifacts.Configuration
fun Configuration.asProvider() {
isVisible = false
isCanBeResolved = false
isCanBeConsumed = true
}
fun Configuration.asConsumer() {
isVisible = false
isCanBeResolved = true
isCanBeConsumed = false
}

View file

@ -1,31 +0,0 @@
rootProject.name = "builder-plugins"
pluginManagement {
@Suppress("UnstableApiUsage")
includeBuild("../settings-plugins/")
}
plugins {
id("kafkatorio.conventions.settings.repositories")
}
dependencyResolutionManagement {
versionCatalogs {
create("libs") {
from(files("../../gradle/libs.versions.toml"))
}
}
}
include(
":modules:common-lib",
":modules:build-conventions",
":modules:docker-compose",
":modules:factorio-mod",
":modules:typescript-to-lua",
)
enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")

View file

@ -1,27 +0,0 @@
package kafkatorio.conventions
plugins {
base
idea
}
group = rootProject.group
version = rootProject.version
tasks.withType<WriteProperties>().configureEach {
encoding = Charsets.UTF_8.name()
comment = " Do not edit manually. This file was created with task '$name'"
}
tasks.withType<AbstractArchiveTask>().configureEach {
exclude(
"**/.secret.*",
"**/.env",
)
isPreserveFileTimestamps = false
isReproducibleFileOrder = true
}

View file

@ -1,37 +0,0 @@
package kafkatorio.conventions
import io.kvision.gradle.KVisionExtension
import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.findByType
import org.jetbrains.kotlin.gradle.targets.js.yarn.YarnRootExtension
object Versions {
const val node = "14.19.1"
}
/**
* `kotlin-js` adds a directory in the root-dir for the Yarn lock.
* That's a bit annoying. It's a little neater if it's in the
* gradle dir, next to the version-catalog.
*/
fun Project.relocateKotlinJsStore() {
afterEvaluate {
rootProject.extensions.configure<YarnRootExtension> {
lockFileDirectory = project.rootDir.resolve("gradle/kotlin-js-store")
}
}
// rootProject.plugins.withType(YarnPlugin::class) {
// rootProject.the<YarnRootExtension>().lockFileDirectory =
// project.rootDir.resolve("gradle/kotlin-js-store")
// }
// KVision tries to be clever too
project.extensions.findByType<KVisionExtension>()?.apply {
enableHiddenKotlinJsStore.set(false)
}
}

View file

@ -1,63 +0,0 @@
package kafkatorio.conventions.infra
//import kafkatorio.tasks.DockerEnvUpdateTask
//import kafkatorio.extensions.DOCKER_COMPOSE_TASK_GROUP
//import org.jetbrains.kotlin.util.parseSpaceSeparatedArgs
//
//plugins {
// base
// id("kafkatorio.conventions.infra.process-runner")
//}
//
//
//val dockerComposeProjectName: String by extra(rootProject.name)
//val dockerSrcDir: Directory by extra(layout.projectDirectory.dir("src"))
//
//
//val dockerUp by tasks.registering(Exec::class) {
// group = DOCKER_COMPOSE_TASK_GROUP
//
// dependsOn(tasks.assemble)
// logging.captureStandardOutput(LogLevel.LIFECYCLE)
//
// workingDir = dockerSrcDir.asFile
// commandLine = parseSpaceSeparatedArgs(""" docker-compose up -d """)
//}
//
//
//val dockerDown by tasks.registering(Exec::class) {
// group = DOCKER_COMPOSE_TASK_GROUP
//
// logging.captureStandardOutput(LogLevel.LIFECYCLE)
//
// workingDir = dockerSrcDir.asFile
// commandLine = parseSpaceSeparatedArgs(""" docker-compose down """)
//}
//
//
//val dockerRemove by tasks.registering(Exec::class) {
// group = DOCKER_COMPOSE_TASK_GROUP
//
// logging.captureStandardOutput(LogLevel.LIFECYCLE)
//
// workingDir = dockerSrcDir.asFile
// commandLine = parseSpaceSeparatedArgs(""" docker-compose rm --stop -v -f """)
//}
//
//
//tasks.matching { it.name == "processRun" }.configureEach { dependsOn(dockerUp, dockerEnvUpdate) }
//tasks.matching { it.name == "processKill" }.configureEach { dependsOn(dockerDown) }
//
//
//val dockerEnvUpdate by tasks.registering(DockerEnvUpdateTask::class) {
// dotEnvFile.set(dockerSrcDir.file(".env"))
//
// properties(
// "COMPOSE_PROJECT_NAME" to dockerComposeProjectName,
// "KAFKATORIO_VERSION" to project.version,
// "REGISTRY_HOST" to providers.gradleProperty("dockerContainerRegistryHost"),
// )
//}
//
//
//tasks.assemble { dependsOn(dockerEnvUpdate) }

View file

@ -1,25 +0,0 @@
package kafkatorio.conventions.infra
import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.registering
plugins {
id("kafkatorio.conventions.base")
}
val processRunnerTaskGroup: String by extra("processes")
val processRun by tasks.registering(Task::class) {
group = processRunnerTaskGroup
}
val processKill by tasks.registering(Task::class) {
group = processRunnerTaskGroup
}
val processRestart by tasks.registering {
group = processRunnerTaskGroup
dependsOn(processKill)
finalizedBy(processRun)
}

View file

@ -1,70 +0,0 @@
package kafkatorio.conventions.lang
//import dev.adamko.kafkatorio.Versions
import kafkatorio.conventions.relocateKotlinJsStore
//import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension
//import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootPlugin
//import org.jetbrains.kotlin.gradle.targets.js.npm.NpmProject
//import org.jetbrains.kotlin.gradle.targets.js.yarn.YarnRootExtension
//import org.jetbrains.kotlin.gradle.targets.js.npm.tasks.RootPackageJsonTask
plugins {
kotlin("js")
id("kafkatorio.conventions.base")
}
//dependencies {
// implementation(
// project.dependencies.platform(
// "org.jetbrains.kotlin-wrappers:kotlin-wrappers-bom:${Versions.kotlinWrappers}"
// )
// )
//}
//val rootPackageJson by rootProject.tasks.getting(RootPackageJsonTask::class)
//fun NpmTask.setNodeModulesPath(path: String): Unit =
// environment.put("NODE_PATH", path)
//
//fun NpmTask.setNodeModulesPath(folder: File): Unit =
// setNodeModulesPath(folder.normalize().absolutePath)
// https://github.com/node-gradle/gradle-node-plugin/issues/150
// https://github.com/lamba92/kotlingram/blob/master/examples/js-bot/build.gradle.kts
//val nodePath: Directory by extra {
// val file = rootPackageJson.rootPackageJson.parentFile.normalize()
// logger.info("Kotlin/JS NODE_PATH: $file")
// project.layout.dir(project.provider { file }).get()
//}
//val nodeModulesDir: Directory by extra {
// val file = nodePath.dir(NpmProject.NODE_MODULES)
// logger.info("Kotlin/JS NODE_MODULES: $file")
// file
//}
relocateKotlinJsStore()
//plugins.withType<NodeJsRootPlugin> {
// configure<NodeJsRootExtension> {
// nodeVersion = "16.0.0"
// }
//}
//afterEvaluate {
// rootProject.extensions.configure<NodeJsRootExtension> {
// // https://github.com/rjaros/kvision/issues/410
// versions.webpackCli.version = "4.10.0"
// versions.webpackDevServer.version = "4.9.2"
// }
//
// rootProject.extensions.configure<YarnRootExtension> {
// resolution("http-proxy-middleware", "^2.0.6")
// }
//}

View file

@ -1,66 +0,0 @@
package kafkatorio.conventions.lang
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("kafkatorio.conventions.base")
kotlin("jvm")
}
val projectKotlinTarget = "1.7"
val projectJvmTarget = "11"
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter")
testImplementation("io.kotest:kotest-runner-junit5")
testImplementation("io.kotest:kotest-assertions-core")
testImplementation("io.kotest:kotest-property")
testImplementation("io.kotest:kotest-assertions-json")
testImplementation("io.mockk:mockk")
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
jvmTarget = projectJvmTarget
apiVersion = projectKotlinTarget
languageVersion = projectKotlinTarget
}
kotlinOptions.freeCompilerArgs += listOf(
// "-Xcontext-receivers",
"-opt-in=kotlin.RequiresOptIn",
"-opt-in=kotlin.ExperimentalStdlibApi",
"-opt-in=kotlin.time.ExperimentalTime",
// "-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi",
// "-opt-in=kotlinx.serialization.ExperimentalSerializationApi",
)
}
tasks.compileTestKotlin {
kotlinOptions.freeCompilerArgs += "-opt-in=io.kotest.common.ExperimentalKotest"
}
kotlin {
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(projectJvmTarget))
}
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
}
plugins.withType<ApplicationPlugin>().configureEach {
project.extensions.getByType<JavaApplication>().apply {
applicationDefaultJvmArgs += listOf("-Dkotlinx.coroutines.debug")
}
}

View file

@ -1,37 +0,0 @@
package kafkatorio.conventions.lang
import kafkatorio.conventions.relocateKotlinJsStore
//import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootExtension
//import org.jetbrains.kotlin.gradle.targets.js.nodejs.NodeJsRootPlugin
//import org.jetbrains.kotlin.gradle.targets.js.yarn.YarnRootExtension
plugins {
id("kafkatorio.conventions.base")
// id("dev.adamko.kafkatorio.lang.node")
kotlin("multiplatform")
// id("io.kotest.multiplatform") // disabled because of https://github.com/kotest/kotest/issues/3141
}
relocateKotlinJsStore()
//plugins.withType<NodeJsRootPlugin> {
// configure<NodeJsRootExtension> {
// nodeVersion = "16.0.0"
// }
//}
//
//
//afterEvaluate {
// rootProject.extensions.configure<NodeJsRootExtension> {
// // https://github.com/rjaros/kvision/issues/410
// versions.webpackCli.version = "4.10.0"
// versions.webpackDevServer.version = "4.9.2"
// }
//
// rootProject.extensions.configure<YarnRootExtension> {
// resolution("http-proxy-middleware", "^2.0.6")
// }
//}

View file

@ -1,64 +0,0 @@
package kafkatorio.conventions.lang
import com.github.gradle.node.npm.task.NpmInstallTask
import kafkatorio.conventions.Versions
import kafkatorio.tasks.UpdatePackageJson
import kotlinx.serialization.json.put
plugins {
id("com.github.node-gradle.node")
id("kafkatorio.conventions.base")
}
node {
download.set(true)
version.set(Versions.node)
distBaseUrl.set(null as String?) // set by dependencyResolutionManagement
}
val projectVersion: Provider<String> = providers.provider { "${project.version}" }
val updatePackageJson by tasks.registering(UpdatePackageJson::class) {
// group = NodePlugin.NODE_GROUP
// description = "Read the package.json file and update the version and name, based on the project."
inputs.property("projectVersion", projectVersion)
// propertiesToCheck.put("version", projectVersion)
updateExpectedJson {
put("version", projectVersion.get())
}
// check to see if the properties are already up-to-date
// outputs.upToDateWhen(areJsonPropertiesUpToDate(packageJsonFile, propertiesToCheck))
// onlyIf(!areJsonPropertiesUpToDate(packageJsonFile, propertiesToCheck))
// doLast {
// val packageJsonContent = packageJsonFile.get().asFile.readText()
// val packageJson = jsonMapper.parseToJsonElement(packageJsonContent).jsonObject
//
// val newJsonProps = propertiesToCheck.get().mapValues { (_, newVal) -> JsonPrimitive(newVal) }
//
// val packageJsonUpdate = JsonObject(packageJson + newJsonProps)
// val packageJsonContentUpdated =
// jsonMapper
// .encodeToString(packageJsonUpdate)
// .suffixIfNot("\n")
//
// logger.debug(packageJsonContentUpdated)
//
// packageJsonFile.get().asFile.writer().useToRun {
// write(packageJsonContentUpdated)
// }
//
// }
}
tasks.assemble { dependsOn(updatePackageJson) }
tasks.withType<NpmInstallTask>().configureEach {
dependsOn(updatePackageJson)
}

View file

@ -1,118 +0,0 @@
package kafkatorio.extensions
import java.io.ByteArrayOutputStream
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.file.Directory
import org.gradle.api.file.ProjectLayout
import org.gradle.api.file.RelativePath
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.provider.Provider
import org.gradle.api.specs.NotSpec
import org.gradle.api.specs.Spec
import org.gradle.api.tasks.TaskProvider
import org.gradle.api.tasks.application.CreateStartScripts
import org.gradle.kotlin.dsl.register
import org.gradle.plugins.ide.idea.model.IdeaModule
import org.gradle.process.ExecSpec
import org.jetbrains.kotlin.gradle.targets.js.yarn.YarnRootExtension
import org.jetbrains.kotlin.gradle.targets.js.yarn.yarn
import org.jetbrains.kotlin.incremental.md5
operator fun <T> Spec<T>.not(): NotSpec<T> = NotSpec(this)
//fun isProcessRunning(process: String, ignoreCase: Boolean = true): Spec<Task> =
// Spec<Task> {
// ByteArrayOutputStream().use { outputStream ->
// project.exec {
// }
// outputStream.toString().contains(process, ignoreCase)
// }
// }
//
/** exclude generated Gradle code, so it doesn't clog up search results */
fun IdeaModule.excludeGeneratedGradleDsl(layout: ProjectLayout) {
val generatedSrcDirs = listOf(
"kotlin-dsl-accessors",
"kotlin-dsl-external-plugin-spec-builders",
"kotlin-dsl-plugins",
)
excludeDirs.addAll(
layout.projectDirectory.asFile.walk()
.filter { it.isDirectory }
.filter { it.parentFile.name in generatedSrcDirs }
.flatMap { file ->
file.walk().maxDepth(1).filter { it.isDirectory }.toList()
}
)
}
// https://stackoverflow.com/a/70317110/4161471
fun Project.execCapture(spec: ExecSpec.() -> Unit): String {
return ByteArrayOutputStream().use { outputStream ->
exec {
this.spec()
this.standardOutput = outputStream
}
val output = outputStream.toString().trim()
logger.lifecycle(output)
output
}
}
/** https://youtrack.jetbrains.com/issue/KT-50848 */
fun Project.yarn(configure: YarnRootExtension.() -> Unit) = with(yarn, configure)
fun Directory.filesChecksum(): Long = asFileTree
.files
.map { it.readBytes() + it.absolutePath.toByteArray() }
.fold(byteArrayOf()) { acc, bytes -> acc + bytes }
.md5()
/** Drop the first [count] directories from the path */
fun RelativePath.dropDirectories(count: Int): RelativePath =
RelativePath(true, *segments.drop(count).toTypedArray())
/** Drop the first directory from the path */
fun RelativePath.dropDirectory(): RelativePath =
dropDirectories(1)
/** https://github.com/gradle/gradle/issues/16543 */
fun Project.taskProvider(taskName: String): Provider<Task> = providers.provider {
taskName
}.flatMap {
tasks.named(it)
}
const val DOCKER_COMPOSE_TASK_GROUP = "docker-compose"
fun Project.registerStartScriptTask(
appName: String,
configureStartScripts: CreateStartScripts.() -> Unit = {},
): TaskProvider<CreateStartScripts> =
tasks.register<CreateStartScripts>("startScript$appName") {
val jarTask = tasks.getByName(JavaPlugin.JAR_TASK_NAME)
val runtimeClasspath = configurations.getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME)
dependsOn(jarTask)
dependsOn(runtimeClasspath)
applicationName = appName
outputDir = layout.buildDirectory.dir("scripts").get().asFile
classpath = jarTask.outputs.files + runtimeClasspath
configureStartScripts()
}

View file

@ -1,21 +0,0 @@
package kafkatorio.extensions
import org.gradle.api.Project
/** Sets a logo for project IDEs */
fun Project.initIdeProjectLogo() {
val logoSvg = rootProject.layout.projectDirectory.file("docs/media/img/kafkatorio-logo.svg")
val ideaDir = rootProject.layout.projectDirectory.dir(".idea")
if (
logoSvg.asFile.exists()
&& ideaDir.asFile.exists()
&& !ideaDir.file("icon.png").asFile.exists()
&& !ideaDir.file("icon.svg").asFile.exists()
) {
copy {
from(logoSvg) { rename { "icon.svg" } }
into(ideaDir)
}
}
}

View file

@ -1,37 +0,0 @@
package kafkatorio.tasks
import javax.inject.Inject
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileSystemOperations
import org.gradle.api.tasks.JavaExec
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import org.gradle.work.DisableCachingByDefault
@DisableCachingByDefault(because = "caching makes regenerating more difficult")
abstract class GenerateTypeScriptTask @Inject constructor(
private val fileOps: FileSystemOperations,
) : JavaExec() {
@get:OutputDirectory
abstract val output: DirectoryProperty
init {
group = "kt2ts"
}
@TaskAction
fun generate() {
fileOps.delete { delete(temporaryDir) }
temporaryDir.mkdirs()
super.exec()
fileOps.sync {
from(temporaryDir)
into(output)
include("**/*.ts")
}
}
}

View file

@ -1,59 +0,0 @@
package kafkatorio.tasks
import kafkatorio.tasks.UpdatePackageJson.Companion.foldParseToJsonObject
import kafkatorio.tasks.UpdatePackageJson.Companion.parseToJsonObject
import kotlinx.serialization.json.JsonObject
import org.gradle.api.Task
import org.gradle.api.internal.specs.ExplainingSpec
import org.gradle.api.logging.Logger
import org.gradle.api.logging.Logging
object JsonPropertiesUpToDateSpec : ExplainingSpec<Task> {
private val logger: Logger = Logging.getLogger(this::class.java)
override fun isSatisfiedBy(element: Task?): Boolean {
val reason = whyUnsatisfied(element)
if (reason != null) {
logger.lifecycle("JsonProperties not up to date:\n$reason")
}
return reason == null
}
// Returns a description explaining why the task is outdated,
// or null if the task is up to date
override fun whyUnsatisfied(task: Task?): String? {
require(task is UpdatePackageJson) { "$task is not a UpdatePackageJson task" }
val current = task.packageJsonFile.asFile.orNull?.parseToJsonObject()
?: return "no package.json file"
val updates = task.expectedJsonUpdates.orNull?.toList()?.foldParseToJsonObject()
?: return "no package.json updates"
val expected = JsonObject(current + updates)
if (current != expected) {
return (current.keys + expected.keys)
.asSequence()
.distinct()
.sorted()
.mapNotNull {
val currentVal = current[it]
val expectedVal = expected[it]
if (currentVal == expectedVal) {
null
} else {
"'$it' - expected:$expectedVal, actual:$currentVal"
}
}.joinToString(separator = "\n\t", prefix = "package.json is not up to date.\n\t")
}
return null
}
}

View file

@ -1,77 +0,0 @@
package kafkatorio.tasks
import kafkatorio.extensions.execCapture
import org.gradle.api.DefaultTask
import org.gradle.api.logging.LogLevel
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.TaskAction
import org.intellij.lang.annotations.Language
import org.jetbrains.kotlin.util.parseSpaceSeparatedArgs
abstract class KafkaConsumerGroupsTask : DefaultTask() {
@get:Input
val bootstrapServer: String = "localhost:9092"
@get:Input
val kafkaDockerContainerName: String = "kafka"
@get:Internal
protected val bootstrapArg = "--bootstrap-server $bootstrapServer"
abstract class ResetAll : KafkaConsumerGroupsTask() {
@get:Input
@Language("Shell Script")
val resetCommand: String =
"""
/kafka/bin/kafka-consumer-groups.sh --execute --reset-offsets --all-topics --to-earliest $bootstrapArg
""".trimIndent()
@TaskAction
fun reset() {
getAllGroups().forEach { group ->
logger.lifecycle("Resetting group $group\n---")
dockerExec("$resetCommand --group $group")
logger.lifecycle("---")
}
}
}
abstract class DeleteAll : KafkaConsumerGroupsTask() {
@get:Input
@Language("Shell Script")
val deleteCommand: String =
"""
/kafka/bin/kafka-consumer-groups.sh --delete $bootstrapArg
""".trimIndent()
@TaskAction
fun reset() {
val groups = getAllGroups().joinToString(" ") { group -> "--group $group" }
dockerExec("$deleteCommand $groups")
}
}
@Internal
protected fun getAllGroups(): List<String> = dockerExec(
"""
/kafka/bin/kafka-consumer-groups.sh --list $bootstrapArg
""".trimIndent()
).lines()
.filter { it.trim().isNotBlank() }
// fun reset(applicationId: String) = """
// /kafka/bin/kafka-streams-application-reset.sh --application-id $applicationId --force --to-earliest
// """.trimIndent()
protected fun dockerExec(
@Language("Shell Script")
cmd: String
): String = project.execCapture {
logging.captureStandardOutput(LogLevel.LIFECYCLE)
commandLine = parseSpaceSeparatedArgs(""" docker exec $kafkaDockerContainerName $cmd """)
}
}

View file

@ -1,39 +0,0 @@
package kafkatorio.tasks
import java.io.ByteArrayOutputStream
import org.gradle.api.Task
import org.gradle.api.internal.specs.ExplainingSpec
import org.gradle.api.tasks.Exec
import org.gradle.process.ExecOperations
/** Checks if a process is running. Windows only. */
class ProcessRunningSpec(
private val executor: ExecOperations,
private val process: String,
private val ignoreCase: Boolean = true,
) : ExplainingSpec<Task> {
override fun isSatisfiedBy(element: Task?): Boolean = whyUnsatisfied(element) == null
override fun whyUnsatisfied(element: Task?): String? {
return when (element) {
null -> "task is null"
!is Exec -> "task ${this::class.simpleName} is not ${Exec::class.simpleName}"
else -> {
return ByteArrayOutputStream().use { outputStream ->
executor.exec {
commandLine("tasklist") // Windows only for now...
standardOutput = outputStream
}
if (outputStream.toString().contains(process, ignoreCase)) {
null
} else {
"found $process in tasklist"
}
}
}
}
}
}

View file

@ -1,50 +0,0 @@
package kafkatorio.tasks
import com.github.gradle.node.npm.task.NpmTask
import javax.inject.Inject
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileSystemOperations
import org.gradle.api.plugins.BasePlugin
import org.gradle.api.tasks.*
import org.gradle.work.NormalizeLineEndings
import org.jetbrains.kotlin.util.parseSpaceSeparatedArgs
@CacheableTask
abstract class TypeScriptToLuaTask @Inject constructor(
private val fs: FileSystemOperations
) : NpmTask() {
@get:InputFiles
@get:SkipWhenEmpty
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:NormalizeLineEndings
@get:IgnoreEmptyDirectories
abstract val sourceFiles: ConfigurableFileCollection
@get:OutputDirectory
abstract val outputDirectory: DirectoryProperty
init {
super.setGroup(BasePlugin.BUILD_GROUP)
super.setDescription("Convert TypeScript To Lua")
super.execOverrides { standardOutput = System.out }
super.npmCommand.set(listOf("run", "build"))
super.ignoreExitValue.set(false)
super.args.set(parseSpaceSeparatedArgs("-- --outDir $temporaryDir"))
}
@TaskAction
fun tstl() {
fs.delete { delete(temporaryDir) }
temporaryDir.mkdirs()
super.exec()
fs.sync {
from(temporaryDir)
into(outputDirectory)
}
}
}

View file

@ -1,116 +0,0 @@
package kafkatorio.tasks
import com.github.gradle.node.NodePlugin
import kafkatorio.*
import java.io.File
import javax.inject.Inject
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonObjectBuilder
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.ProviderFactory
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.support.useToRun
import org.jetbrains.kotlin.util.suffixIfNot
@CacheableTask
abstract class UpdatePackageJson @Inject constructor(
private val providers: ProviderFactory,
) : DefaultTask(),
ProviderFactory by providers {
/** Cumulative updates - will be combined one by one, then applied to [packageJsonFile] */
@get:Input
internal abstract val expectedJsonUpdates: ListProperty<String>
@get:OutputFile
abstract val packageJsonFile: RegularFileProperty
init {
group = NodePlugin.NPM_GROUP
description = "Update package.json properties"
outputs.upToDateWhen(JsonPropertiesUpToDateSpec)
}
@TaskAction
fun exec() {
val packageJsonFile = packageJsonFile.asFile.get()
val expectedJsonUpdates: List<String> = expectedJsonUpdates.get().toList()
logger.lifecycle("updating package.json ${packageJsonFile.canonicalFile}")
val expectedJson = expectedJsonUpdates.fold(JsonObject(emptyMap())) { acc, update ->
val updateJson = jsonMapper.parseToJsonElement(update).jsonObject
JsonObject(acc + updateJson)
}
val updatedPackageJson = JsonObject(
packageJsonFile.parseToJsonObject() + expectedJson
)
val packageJsonContentFormatted =
jsonMapper
.encodeToString(updatedPackageJson)
// change empty arrays/objects, because `npm install` also formats package.json,
// but slightly differently to kxs.
.replace(": {\n }", ": {}")
.replace(": [\n ]", ": []")
.suffixIfNot("\n")
logger.info(packageJsonContentFormatted)
packageJsonFile.writer().useToRun {
write(packageJsonContentFormatted)
}
}
/** Update [expectedJson] by merging [updateJsonProvider] with the existing value. */
fun updateExpectedJson(
expectedJsonUpdate: JsonObjectBuilder.() -> Unit
) {
val expectedJsonUpdateProvider = provider {
buildJsonObject(expectedJsonUpdate).toString()
}
expectedJsonUpdates.add(expectedJsonUpdateProvider)
}
companion object {
private val jsonMapper = Json {
prettyPrint = true
prettyPrintIndent = " "
}
internal fun File.parseToJsonObject(): JsonObject =
jsonMapper.parseToJsonElement(readText()).jsonObject
internal fun Property<String>.parseToJsonObject(): JsonObject =
jsonMapper.parseToJsonElement(get()).jsonObject
internal fun List<String>.foldParseToJsonObject(): JsonObject =
fold(JsonObject(emptyMap())) { acc, update ->
val updateJson = jsonMapper.parseToJsonElement(update).jsonObject
JsonObject(acc + updateJson)
}
}
}

View file

@ -1,19 +0,0 @@
plugins {
id("kafkatorio.conventions.kotlin-dsl")
`java-gradle-plugin`
}
dependencies {
implementation(platform(libs.kotlin.bom))
implementation("org.jetbrains.kotlin:kotlin-compiler-embeddable:${libs.versions.kotlin.get()}")
}
gradlePlugin {
plugins {
create("geedeecee") {
id = "dev.adamko.geedeecee"
displayName = "geedeecee - Gradle Docker Compose"
implementationClass = "dev.adamko.geedeecee.GDCPlugin"
}
}
}

View file

@ -1,18 +0,0 @@
rootProject.name = "docker-compose"
pluginManagement {
@Suppress("UnstableApiUsage")
includeBuild("../settings-plugins/")
}
plugins {
id("kafkatorio.conventions.settings.repositories")
}
dependencyResolutionManagement {
versionCatalogs {
create("libs") {
from(files("../../gradle/libs.versions.toml"))
}
}
}

View file

@ -1,138 +0,0 @@
package dev.adamko.geedeecee
import dev.adamko.geedeecee.tasks.DockerContextFilesPreparation
import dev.adamko.geedeecee.tasks.DockerEnvUpdateTask
import dev.adamko.geedeecee.tasks.GDCCommandTask
import javax.inject.Inject
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.provider.Provider
import org.gradle.api.provider.ProviderFactory
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.create
import org.gradle.kotlin.dsl.getValue
import org.gradle.kotlin.dsl.provideDelegate
import org.gradle.kotlin.dsl.registering
import org.gradle.kotlin.dsl.withType
import org.gradle.language.base.plugins.LifecycleBasePlugin
import org.jetbrains.kotlin.util.parseSpaceSeparatedArgs
@Suppress("UnstableApiUsage")
abstract class GDCPlugin @Inject constructor(
private val providers: ProviderFactory,
) : Plugin<Project> {
override fun apply(target: Project) {
target.plugins.apply(LifecycleBasePlugin::class)
val gdcSettings = target.createSettings()
val dockerComposeEnvUpdate by target.tasks.registering(DockerEnvUpdateTask::class) {
dotEnvFile.set(gdcSettings.srcDir.file(".env"))
envProperties.putAll(gdcSettings.dotEnv)
// properties(
// "COMPOSE_PROJECT_NAME" to gdcSettings.composeProjectName,
// "KAFKATORIO_VERSION" to gdcSettings.composeProjectVersion,
// "REGISTRY_HOST" to providers.gradleProperty("dockerContainerRegistryHost"),
// )
}
val dockerContextPrepareFiles by target.tasks.registering(DockerContextFilesPreparation::class) {
into(gdcSettings.dockerBuildContextDir)
includeEmptyDirs = false
// dockerContextDir.set(gdcSettings.dockerBuildContextDir)
// copySpec.convention(target.copySpec())
// copySpec = Action { }
}
val dockerComposeUp by target.tasks.registering(GDCCommandTask::class) {
`docker-compose`("up -d")
}
val dockerComposeDown by target.tasks.registering(GDCCommandTask::class) {
`docker-compose`("down")
}
val dockerComposeStop by target.tasks.registering(GDCCommandTask::class) {
`docker-compose`("stop")
}
val dockerComposeBuild by target.tasks.registering(GDCCommandTask::class) {
`docker-compose`("build")
cacheable.set(true)
}
val dockerComposePush by target.tasks.registering(GDCCommandTask::class) {
dependsOn(dockerComposeBuild)
`docker-compose`("push")
}
val dockerComposeRemove by target.tasks.registering(GDCCommandTask::class) {
`docker-compose`("rm --stop -v -f")
}
dockerComposeUp.configure { dependsOn(dockerComposeBuild) }
dockerComposeRemove.configure { dependsOn(dockerComposeDown) }
// target.tasks.withType<DockerComposeExec>().configureEach {
// dependsOn(dockerComposeEnvUpdate)
// dockerIsActive.set(isDockerActive())
// stateFile.set(temporaryDir.resolve("docker-state.md5"))
// }
target.tasks.withType<GDCCommandTask>().configureEach {
dependsOn(dockerComposeEnvUpdate)
dependsOn(dockerContextPrepareFiles)
workingDir.convention(gdcSettings.srcDir)
dockerActive.set(gdcSettings.dockerActive)
stateFile.set(
gdcSettings.stateDir.file(workingDir.map { "dc_state${name.hashCode()}${it.asFile.hashCode()}.md5" })
)
}
val assembleTasks = target.tasks.matching { LifecycleBasePlugin.ASSEMBLE_TASK_NAME == it.name }
assembleTasks.configureEach {
dependsOn(dockerComposeEnvUpdate)
}
dockerComposeUp.configure {
dependsOn(assembleTasks)
}
}
private fun Project.createSettings(): GDCSettings =
extensions.create<GDCSettings>(GDC_EXTENSION_NAME).apply {
composeProjectName.convention(providers.provider { rootProject.name })
composeProjectVersion.convention(providers.provider { project.version.toString() })
containerRegistryHost.convention(providers.gradleProperty("dockerContainerRegistryHost"))
srcDir.convention(layout.projectDirectory.dir("docker"))
dockerBuildContextDir.convention(srcDir.dir("build"))
stateDir.convention(layout.buildDirectory.dir("geedeecee/state/"))
dotEnv.put("COMPOSE_PROJECT_NAME", composeProjectName)
dotEnv.put("APP_NAME", providers.provider { project.name })
dotEnv.put("APP_GROUP", providers.provider { project.group.toString() })
dotEnv.put("PROJECT_VERSION", composeProjectVersion)
dotEnv.put("KAFKATORIO_VERSION", composeProjectVersion)
dotEnv.put("REGISTRY_HOST", containerRegistryHost)
dockerActive.convention(isDockerActive())
}
private fun isDockerActive(): Provider<Boolean> =
providers.exec {
commandLine = parseSpaceSeparatedArgs("docker info")
isIgnoreExitValue = true
}.result.map {
it.exitValue == 0
}
companion object {
const val GDC_EXTENSION_NAME = "geedeecee"
const val GCD_TASK_GROUP = "docker-compose"
}
}

View file

@ -1,79 +0,0 @@
package dev.adamko.geedeecee
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.provider.MapProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Internal
interface GDCSettings {
@get:Input
val composeProjectName: Property<String>
@get:Input
val composeProjectVersion: Property<String>
@get:Input
val containerRegistryHost: Property<String>
@get:Internal
val srcDir: DirectoryProperty
@get:Input
val dotEnv: MapProperty<String, String>
@get:Input
val dockerActive: Property<Boolean>
@get:Input
val dockerBuildContextDir: DirectoryProperty
val stateDir: DirectoryProperty
// @Suppress("PropertyName", "FunctionName")
// abstract class DotEnv(
// private val dotEnv: MapProperty<String, String>,
// private val providers: ProviderFactory,
// ) {
// var COMPOSE_API_VERSION: Provider<String> by dotEnv
// fun COMPOSE_API_VERSION(value: () -> String) {
// COMPOSE_API_VERSION = providers.provider(value)
// }
// // var COMPOSE_CONVERT_WINDOWS_PATHS: String
//// var COMPOSE_FILE: String
//// var COMPOSE_HTTP_TIMEOUT: String
//// var COMPOSE_PROFILES: String
//// var COMPOSE_PROJECT_NAME: String
//// var COMPOSE_TLS_VERSION: String
//// var DOCKER_CERT_PATH: String
//// var DOCKER_HOST: String
//// var DOCKER_TLS_VERIFY: String
// fun setComposeApiVersion(composeApiVersion: String) {}
// fun setComposeConvertWindowsPaths(composeConvertWindowsPaths: String) {}
// fun setComposeFile(composeFile: String) {}
// fun setComposeHttpTimeout(composeHttpTimeout: String) {}
// fun setComposeProfiles(composeProfiles: String) {}
// fun setComposeProjectName(composeProjectName: String) {}
// fun setComposeTlsVersion(composeTlsVersion: String) {}
// fun setDockerCertPath(dockerCertPath: String) {}
// fun setDockerHost(dockerHost: String) {}
// fun setDockerTlsVerify(dockerTlsVerify: String) {}
// }
}
//
//private operator fun <PV : Provider<String>> MapProperty<String, String>.setValue(
// dotEnv: GDCSettings.DotEnv,
// property: KProperty<*>,
// v: PV
//) {
// put(property.name, v)
//}
//
//private operator fun MapProperty<String, String>.getValue(
// dotEnv: GDCSettings.DotEnv,
// property: KProperty<*>
//): Provider<String> {
// return getting(property.name)
//}

View file

@ -1,12 +0,0 @@
package dev.adamko.geedeecee.internal
import org.gradle.api.file.Directory
import org.jetbrains.kotlin.incremental.md5
// should be moved to common plugins lib
internal fun Directory.filesChecksum(): Long = asFileTree
.files
.map { it.readBytes() + it.absolutePath.toByteArray() }
.fold(byteArrayOf()) { acc, bytes -> acc + bytes }
.md5()

View file

@ -1,14 +0,0 @@
package dev.adamko.geedeecee.internal
import org.gradle.api.Task
import org.gradle.api.file.FileCopyDetails
import org.gradle.api.file.RelativePath
// move to common-lib
internal inline fun <reified T : Task> T.enabledIf(crossinline spec: (T) -> Boolean) {
onlyIf {
require(it is T)
spec(it)
}
}

View file

@ -1,56 +0,0 @@
package dev.adamko.geedeecee.tasks
import dev.adamko.geedeecee.GDCPlugin
import javax.inject.Inject
import org.gradle.api.tasks.Sync
// look into using 'build context' for up-to-date check
// https://stackoverflow.com/questions/38946683/how-to-test-dockerignore-file
// https://github.com/pwaller/docker-show-context
// https://snippets.khromov.se/see-which-files-are-included-in-your-docker-build-context/
//@CacheableTask
//@Suppress("UnstableApiUsage")
abstract class DockerContextFilesPreparation @Inject constructor(
// private val files: FileSystemOperations,
) : Sync() {
// @get:InputFiles
//// @get:SkipWhenEmpty
// @get:PathSensitive(PathSensitivity.RELATIVE)
// @get:NormalizeLineEndings
// abstract val dockerContextFiles: ConfigurableFileCollection
// @get:Input
// abstract val copySpec: Property<CopySpec>
//
// @get:OutputDirectory
// abstract val dockerContextDir: DirectoryProperty
init {
group = GDCPlugin.GCD_TASK_GROUP
}
// @TaskAction
// fun exec() {
// files.sync {
// from(dockerContextFiles, copySpec)
// into(dockerContextDir)
//// with(copySpec)
// }
// }
// /** @see [CopySpec.from] */
// override fun from(vararg sourcePaths: Any?): CopySpec =
// copySpec.from(sourcePaths)
//
// /** @see [CopySpec.from] */
// override fun from(sourcePath: Any, configureClosure: Closure<*>): CopySpec =
// copySpec.from(sourcePath, configureClosure)
//
// /** @see [CopySpec.from] */
// override fun from(sourcePath: Any, configureAction: Action<in CopySpec>): CopySpec =
// copySpec.from(sourcePath, configureAction)
}

View file

@ -1,101 +0,0 @@
package dev.adamko.geedeecee.tasks
import dev.adamko.geedeecee.GDCPlugin
import java.io.File
import java.nio.charset.Charset
import java.util.Properties
import javax.inject.Inject
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.MapProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
/**
* (Based on [org.gradle.api.tasks.WriteProperties], but updated to use [MapProperty])
*/
@CacheableTask
abstract class DockerEnvUpdateTask @Inject constructor(
) : DefaultTask() {
@get:Input
@get:Optional
abstract val envProperties: MapProperty<String, String>
@get:Input
@get:Optional
abstract val comment: Property<String>
@get:Input
@get:Optional
abstract val charset: Property<Charset>
@get:OutputFile
abstract val dotEnvFile: RegularFileProperty
init {
group = GDCPlugin.GCD_TASK_GROUP
}
@TaskAction
fun writeProperties() {
val dotEnvFile: File = dotEnvFile.get().asFile
val charset: Charset = charset.orNull ?: Charsets.UTF_8
val comment: String = comment.orNull
?: " Do not edit manually. This file was created with task '$name'"
val envProperties = envProperties.getOrElse(emptyMap())
dotEnvFile.writer(charset).use { writer ->
val properties = Properties()
properties.putAll(envProperties)
properties.store(writer, comment)
}
// make the file reproducible by sorting and filtering lines in the file
val lines = dotEnvFile.useLines(charset) { lines ->
lines
.filterNot { it.isBlank() }
.sorted()
.toList()
}
// first comment is our comment
// second comment is the auto generated timestamp - which we will filter out, so the file is reproducible
val parsedComment = lines.firstOrNull { it.isComment() } ?: ""
val parsedLines = lines.filterNot { it.isComment() }.joinToString(separator = "\n")
dotEnvFile.writeText(
charset = charset,
text = """
|$parsedComment
|
|$parsedLines
|
""".trimMargin()
)
}
fun envProperties(configure: MapProperty<String, String>.() -> Unit) {
envProperties.configure()
}
companion object {
@JvmName("putProvider")
fun <K : Any, V : Any> MapProperty<K, V>.put(entry: Pair<K, Provider<V>>) =
put(entry.first, entry.second)
@JvmName("putValue")
fun <K : Any, V : Any> MapProperty<K, V>.put(entry: Pair<K, V>) =
put(entry.first, entry.second)
private fun String.isComment(): Boolean = trim().startsWith('#')
}
}

View file

@ -1,90 +0,0 @@
package dev.adamko.geedeecee.tasks
import dev.adamko.geedeecee.GDCPlugin
import dev.adamko.geedeecee.internal.enabledIf
import dev.adamko.geedeecee.internal.filesChecksum
import javax.inject.Inject
import org.gradle.api.DefaultTask
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.logging.LogLevel
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.SkipWhenEmpty
import org.gradle.api.tasks.TaskAction
import org.gradle.process.ExecOperations
import org.gradle.work.NormalizeLineEndings
import org.jetbrains.kotlin.util.parseSpaceSeparatedArgs
// look into using 'build context' for up-to-date check
// https://stackoverflow.com/questions/38946683/how-to-test-dockerignore-file
// https://github.com/pwaller/docker-show-context
// https://snippets.khromov.se/see-which-files-are-included-in-your-docker-build-context/
// or parsing Dockerfile
// https://github.com/keilerkonzept/dockerfile-json
@Suppress("UnstableApiUsage") // NormalizeLineEndings
abstract class GDCCommandTask @Inject constructor(
private val executor: ExecOperations,
) : DefaultTask() {
@get:InputDirectory
@get:SkipWhenEmpty
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:NormalizeLineEndings
abstract val workingDir: DirectoryProperty
@get:Input
abstract val separatedArgs: ListProperty<String>
@get:Input
abstract val dockerActive: Property<Boolean>
@get:Input
@get:Optional
abstract val cacheable: Property<Boolean>
@get:OutputFile
abstract val stateFile: RegularFileProperty
init {
group = GDCPlugin.GCD_TASK_GROUP
description = "Run a docker-compose command."
enabledIf { it.dockerActive.getOrElse(false) }
logging.captureStandardOutput(LogLevel.LIFECYCLE)
}
@TaskAction
fun dockerCompose() {
val separatedArgs: List<String> = separatedArgs.get()
executor.exec {
environment("BUILDKIT_PROGRESS", "plain")
workingDir(this@GDCCommandTask.workingDir)
commandLine(separatedArgs)
}
if (cacheable.getOrElse(false)) {
val inputChecksum = workingDir.get().filesChecksum()
stateFile.get().asFile.writeText("$inputChecksum")
}
}
/** Set the `docker-compose` argument */
@Suppress("FunctionName")
fun `docker-compose`(args: String) {
separatedArgs.set(
parseSpaceSeparatedArgs("docker-compose $args")
)
}
}

View file

@ -1,64 +0,0 @@
import kafkatorio.conventions.overrideKotlinLanguageVersion
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("kafkatorio.conventions.kotlin-dsl")
id("kafkatorio.conventions.kotlin-serialization")
}
dependencies {
implementation(platform(libs.kotlin.bom))
implementation(platform(libs.kotlinx.coroutines.bom))
implementation(libs.kotlinx.coroutines.core)
implementation(platform(libs.kotlinxSerialization.bom))
implementation(libs.kotlinxSerialization.core)
implementation(libs.kotlinxSerialization.json)
implementation(platform(libs.okio.bom))
implementation(libs.okio.core)
implementation(libs.kotlinx.cli)
implementation(platform(libs.ktor.bom))
implementation(libs.ktorClient.auth)
implementation(libs.ktorClient.contentNegotiation)
implementation(libs.ktorClient.core)
implementation(libs.ktorClient.encoding)
implementation(libs.ktorClient.logging)
implementation(libs.ktorClient.cio)
implementation(libs.ktorClient.resources)
implementation(libs.ktorSerialization.kotlinxJson)
implementation("org.jetbrains.kotlin:kotlin-compiler-embeddable:${libs.versions.kotlin.get()}")
}
gradlePlugin {
plugins {
create("factorioMod") {
displayName = "Factorio Mod"
id = "dev.adamko.factorio-mod"
implementationClass = "dev.adamko.gradle.factorio.FactorioModPlugin"
}
}
plugins {
create("factorioModLibrary") {
displayName = "Factorio Mod Library"
id = "dev.adamko.factorio-mod-library"
implementationClass = "dev.adamko.gradle.factorio.FactorioModLibraryPlugin"
}
}
}
overrideKotlinLanguageVersion("1.7") // required for Kotlinx Serialization
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions.freeCompilerArgs += listOf(
"-opt-in=kotlin.RequiresOptIn",
"-opt-in=kotlin.ExperimentalStdlibApi",
"-opt-in=kotlin.time.ExperimentalTime",
"-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi",
)
}

View file

@ -1,20 +0,0 @@
@file:Suppress("UnstableApiUsage")
rootProject.name = "factorio-gradle"
pluginManagement {
@Suppress("UnstableApiUsage")
includeBuild("../settings-plugins/")
}
plugins {
id("kafkatorio.conventions.settings.repositories")
}
dependencyResolutionManagement {
versionCatalogs {
create("libs") {
from(files("../../gradle/libs.versions.toml"))
}
}
}

View file

@ -1,9 +0,0 @@
package dev.adamko.gradle.factorio
import org.gradle.api.NamedDomainObjectProvider
import org.gradle.api.artifacts.Configuration
internal data class FactorioModConfigurations(
val factorioMod: NamedDomainObjectProvider<Configuration>,
val factorioModProvider: NamedDomainObjectProvider<Configuration>,
)

View file

@ -1,48 +0,0 @@
package dev.adamko.gradle.factorio
import javax.inject.Inject
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.slf4j.LoggerFactory
/**
* Configure a [Project] to produce components that will be used in a Factorio mod, but no tasks
* that will create a Factorio mod.
*/
abstract class FactorioModLibraryPlugin @Inject constructor(
// private val objects: ObjectFactory,
// private val providers: ProviderFactory,
// private val layout: ProjectLayout,
// private val files: FileSystemOperations,
) : Plugin<Project> {
internal val logger = LoggerFactory.getLogger(this::class.java)
internal var factorioModConfigurations: FactorioModConfigurations? = null
private set
override fun apply(target: Project) {
factorioModConfigurations = target.createConfigurations()
}
private fun Project.createConfigurations(): FactorioModConfigurations {
return FactorioModConfigurations(
factorioMod = project.configurations.register(CONFIGURATION_NAME__FACTORIO_MOD) {
asConsumer()
factorioModAttributes(objects)
},
factorioModProvider = project.configurations.register(
CONFIGURATION_NAME__FACTORIO_MOD_PROVIDER
) {
asProvider()
factorioModAttributes(objects)
},
)
}
companion object {
const val CONFIGURATION_NAME__FACTORIO_MOD = "factorioMod"
const val CONFIGURATION_NAME__FACTORIO_MOD_PROVIDER = "factorioModProvider"
}
}

View file

@ -1,108 +0,0 @@
package dev.adamko.gradle.factorio
import dev.adamko.gradle.factorio.tasks.AssembleFactorioModContents
import dev.adamko.gradle.factorio.tasks.GenerateFactorioModInfoTask
import dev.adamko.gradle.factorio.tasks.LaunchFactorioClientTask
import dev.adamko.gradle.factorio.tasks.LocalPublishFactorioModTask
import dev.adamko.gradle.factorio.tasks.PackageFactorioModTask
import javax.inject.Inject
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.FileSystemOperations
import org.gradle.api.file.ProjectLayout
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.ProviderFactory
import org.gradle.api.tasks.TaskProvider
import org.gradle.kotlin.dsl.create
import org.gradle.kotlin.dsl.newInstance
import org.gradle.kotlin.dsl.register
import org.slf4j.LoggerFactory
abstract class FactorioModPlugin @Inject constructor(
private val objects: ObjectFactory,
private val providers: ProviderFactory,
private val layout: ProjectLayout,
private val files: FileSystemOperations,
) : Plugin<Project> {
internal val logger = LoggerFactory.getLogger(this::class.java)
override fun apply(target: Project) {
val settings = target.extensions.create<FactorioModSettings>(FACTORIO_GRADLE_EXTENSION_NAME)
val factorioModLibraryPlugin = objects.newInstance<FactorioModLibraryPlugin>()
factorioModLibraryPlugin.apply(target)
val factorioModConfigurations = factorioModLibraryPlugin.factorioModConfigurations
?: error("Could not create Factorio Mod Configurations")
val context = PluginContext(
target,
settings,
target.createTasks(),
factorioModConfigurations,
objects,
providers,
layout,
files,
)
context.configureModSettings()
context.configureTasks()
context.configureIdea()
// context.configureDistribution()
}
private fun Project.createTasks(): PluginContext.Tasks {
return PluginContext.Tasks(
launchFactorioClient = project.tasks.register<LaunchFactorioClientTask>("launchFactorioClient"),
assembleModContents = project.tasks.register<AssembleFactorioModContents>("assembleFactorioModContents"),
packageMod = project.tasks.register<PackageFactorioModTask>("packageFactorioMod"),
publishModToLocalClient = project.tasks.register<LocalPublishFactorioModTask>("publishFactorioModToLocalClient"),
generateModInfoJson = project.tasks.register<GenerateFactorioModInfoTask>("generateFactorioModInfoJson"),
)
}
internal class PluginContext(
val project: Project,
val settings: FactorioModSettings,
val tasks: Tasks,
val configurations: FactorioModConfigurations,
val objects: ObjectFactory,
val providers: ProviderFactory,
val layout: ProjectLayout,
val files: FileSystemOperations,
) {
internal val logger = LoggerFactory.getLogger(this::class.java)
data class Tasks(
val launchFactorioClient: TaskProvider<LaunchFactorioClientTask>,
val assembleModContents: TaskProvider<AssembleFactorioModContents>,
val packageMod: TaskProvider<PackageFactorioModTask>,
val publishModToLocalClient: TaskProvider<LocalPublishFactorioModTask>,
val generateModInfoJson: TaskProvider<GenerateFactorioModInfoTask>,
)
}
companion object {
const val FACTORIO_GRADLE_EXTENSION_NAME = "factorioMod"
const val CONFIGURATION_NAME__FACTORIO_MOD = "factorioMod"
const val CONFIGURATION_NAME__FACTORIO_MOD_PROVIDER = "factorioModProvider"
const val TASK_GROUP = "factorio mod"
/** Lifecycle task for publishing the mod locally */
const val PUBLISH_MOD_LOCAL_TASK_NAME = "publishModLocal"
const val PUBLISH_MOD_TASK_NAME = "publishMod"
}
}

View file

@ -1,69 +0,0 @@
package dev.adamko.gradle.factorio
import javax.inject.Inject
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.ProjectLayout
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.ProviderFactory
import org.gradle.kotlin.dsl.newInstance
abstract class FactorioModSettings @Inject constructor(
internal val objects: ObjectFactory,
internal val providers: ProviderFactory,
internal val layout: ProjectLayout,
) {
abstract val modName: Property<String>
abstract val modTitle: Property<String>
abstract val modDescription: Property<String>
abstract val modAuthor: Property<String>
abstract val modVersion: Property<String>
abstract val modDependencies: ListProperty<String>
// version of Factorio that the mod is compatible with (must only be "major.minor" - patch causes error)
abstract val factorioCompatibility: Property<String>
abstract val distributionZipName: Property<String>
val mainSources: FactorioModSourceSet.WithResources = objects.newInstance("Main")
val testSources: FactorioModSourceSet.WithResources = objects.newInstance("Test")
val generatedSources: FactorioModSourceSet = objects.newInstance("Generated")
// abstract val typescriptSrcDir: DirectoryProperty
// abstract val resourcesDir: DirectoryProperty
// abstract val modDataResourcesDir: DirectoryProperty
// abstract val generatedLuaSrcDir: DirectoryProperty
abstract val factorioServerDataDirectory: DirectoryProperty
val localDev: LocalDev = objects.newInstance()
fun localDev(configure: LocalDev.() -> Unit) {
localDev.configure()
}
interface LocalDev {
val currentOs: Property<OS>
val windowsSteamExe: Property<String>
val factorioSteamId: Property<String>
val serverConnectHost: Property<String>
val clientModsDirectory: RegularFileProperty
val macApplicationSupportDir: RegularFileProperty
val macFactorioApp: RegularFileProperty
/** Supported local dev OSes */
enum class OS { WINDOWS, MAC_OS, UNSUPPORTED }
}
}

View file

@ -1,38 +0,0 @@
package dev.adamko.gradle.factorio
import javax.inject.Inject
import org.gradle.api.Named
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.model.ObjectFactory
abstract class FactorioModSourceSet @Inject constructor(
private val named: String,
objects: ObjectFactory,
) : Named {
val typescript: SourceDirectorySet = objects
.sourceDirectorySet("ts${named}", "TypeScript $named source files")
.apply {
include("**/*.d.ts", "**/*.ts")
}
val lua: SourceDirectorySet = objects
.sourceDirectorySet("lua${named}", "Lua $named source files")
.apply {
include("**/*.lua")
}
override fun getName(): String = named
abstract class WithResources @Inject constructor(
type: String,
objects: ObjectFactory,
) : FactorioModSourceSet(type, objects) {
val resources: SourceDirectorySet = objects
.sourceDirectorySet("resources${type}", "$type resources")
.apply {
exclude("**/*.d.ts", "**/*.ts", "**/*.lua")
}
}
}

View file

@ -1,44 +0,0 @@
package dev.adamko.gradle.factorio
import org.gradle.api.artifacts.Configuration
import org.gradle.api.attributes.Bundling
import org.gradle.api.attributes.Bundling.BUNDLING_ATTRIBUTE
import org.gradle.api.attributes.Category
import org.gradle.api.attributes.Category.CATEGORY_ATTRIBUTE
import org.gradle.api.attributes.LibraryElements
import org.gradle.api.attributes.LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE
import org.gradle.api.attributes.Usage.USAGE_ATTRIBUTE
import org.gradle.api.model.ObjectFactory
import org.gradle.kotlin.dsl.named
fun Configuration.asProvider(visible: Boolean = false) {
isVisible = visible
isCanBeResolved = false
isCanBeConsumed = true
}
fun Configuration.asConsumer(visible: Boolean = false) {
isVisible = visible
isCanBeResolved = true
isCanBeConsumed = false
}
fun Configuration.factorioModAttributes(objects: ObjectFactory): Configuration =
attributes {
attribute(USAGE_ATTRIBUTE, objects.named("dev.adamko.factorio"))
attribute(CATEGORY_ATTRIBUTE, objects.named(Category.LIBRARY))
attribute(LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements.CLASSES_AND_RESOURCES))
attribute(BUNDLING_ATTRIBUTE, objects.named(Bundling.EMBEDDED))
}
fun Configuration.typescriptAttributes(objects: ObjectFactory): Configuration =
attributes {
attribute(USAGE_ATTRIBUTE, objects.named("dev.adamko.typescript"))
attribute(CATEGORY_ATTRIBUTE, objects.named(Category.LIBRARY))
attribute(LIBRARY_ELEMENTS_ATTRIBUTE, objects.named(LibraryElements.OBJECTS))
attribute(BUNDLING_ATTRIBUTE, objects.named(Bundling.EXTERNAL))
}

View file

@ -1,42 +0,0 @@
package dev.adamko.gradle.factorio
import org.gradle.api.distribution.DistributionContainer
import org.gradle.api.distribution.plugins.DistributionPlugin
import org.gradle.api.tasks.bundling.Zip
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.named
internal fun FactorioModPlugin.PluginContext.configureDistribution() {
project.plugins.apply(DistributionPlugin::class)
val distributions = project.extensions.getByType<DistributionContainer>()
distributions.named(DistributionPlugin.MAIN_DISTRIBUTION_NAME) {
distributionBaseName.set(settings.modName)
contents {
includeEmptyDirs = false
from(settings.mainSources.resources) {
include("**/**")
}
exclude {
// exclude empty files
it.file.run {
isFile && useLines { lines -> lines.all { line -> line.isBlank() } }
}
}
}
}
val distZipTask = project.tasks.named<Zip>("distZip")
configurations.factorioModProvider.configure {
outgoing.artifact(distZipTask.flatMap { it.archiveFile })
}
}

View file

@ -1,38 +0,0 @@
package dev.adamko.gradle.factorio
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.withType
import org.gradle.plugins.ide.idea.IdeaPlugin
import org.gradle.plugins.ide.idea.model.IdeaModel
//import org.gradle.plugins.ide.idea.model.Module as IdeaModule
internal fun FactorioModPlugin.PluginContext.configureIdea() {
project.plugins.withType<IdeaPlugin>().configureEach {
project.extensions.configure<IdeaModel> {
module {
// scopes["MAIN"] = mapOf("plus" to listOf(configurations.factorioMod.get()))
sourceDirs.plusAssign(settings.mainSources.typescript.srcDirs)
sourceDirs.plusAssign(settings.mainSources.lua.srcDirs)
sourceDirs.plusAssign(settings.generatedSources.lua.srcDirs)
testSources.from(settings.testSources.typescript)
testSources.from(settings.testSources.lua)
resourceDirs.plusAssign(settings.mainSources.resources.srcDirs)
testResources.from(settings.testSources.resources)
generatedSourceDirs.plusAssign(settings.generatedSources.lua.srcDirs)
generatedSourceDirs.plusAssign(settings.generatedSources.typescript.srcDirs)
// iml {
// whenMerged {
// require(this is IdeaModule)
//
// }
// }
}
}
}
}

View file

@ -1,99 +0,0 @@
package dev.adamko.gradle.factorio
import dev.adamko.gradle.factorio.FactorioModSettings.LocalDev.OS
import java.io.File
import org.gradle.api.internal.provider.Providers
import org.gradle.api.provider.ProviderFactory
internal fun FactorioModPlugin.PluginContext.configureModSettings() = with(settings) {
modName.convention(providers.provider { project.name })
modTitle.convention(modName)
modDescription.convention(providers.provider { project.description ?: "" })
modVersion.convention(providers.provider { project.version.toString() })
distributionZipName.convention(providers.zip(modName, modVersion) { name, version ->
"${name}_${version}.zip"
})
val srcBaseMain = layout.projectDirectory.dir("src/main")
mainSources.lua.srcDir(srcBaseMain.dir("lua"))
mainSources.typescript.srcDir(srcBaseMain.dir("typescript"))
mainSources.resources.srcDir(srcBaseMain.dir("resources"))
val srcBaseTest = layout.projectDirectory.dir("src/test")
testSources.lua.srcDir(srcBaseTest.dir("lua"))
testSources.typescript.srcDir(srcBaseTest.dir("typescript"))
testSources.resources.srcDir(srcBaseTest.dir("resources"))
val srcBaseGenerated = layout.buildDirectory.dir("generated-src").get()
generatedSources.lua.srcDir(srcBaseGenerated.dir("lua"))
generatedSources.typescript.srcDir(srcBaseGenerated.dir("typescript"))
mainSources.typescript.destinationDirectory.convention(srcBaseGenerated.dir("lua"))
configureLocalDev()
}
private fun FactorioModPlugin.PluginContext.configureLocalDev() = with(settings) {
val userHome = providers.systemProperty("user.home")
.map { home -> File(home) }
localDev {
currentOs.convention(providers.systemProperty("os.name").map { osName ->
val currentOS = osName.lowercase()
when {
"windows" in currentOS -> OS.WINDOWS
"mac" in currentOS -> OS.MAC_OS
else -> {
logger.warn("cannot select OS for Factorio local dev - '${osName}' is unsupported")
OS.UNSUPPORTED
}
}
})
windowsSteamExe.convention("""C:\Program Files (x86)\Steam\steam.exe""")
factorioSteamId.convention("427520")
// serverConnectHost.convention("localhost")
macApplicationSupportDir.convention(layout.file(userHome.map { home ->
home.resolve("""Library/Application Support/""")
}))
macFactorioApp.convention(layout.file(macApplicationSupportDir.map { appSupport ->
appSupport.asFile.resolve("""Steam/steamapps/common/Factorio/factorio.app/Contents/MacOS/factorio""")
}))
clientModsDirectory.convention(layout.file(
currentOs.flatMap { os ->
when (os) {
OS.WINDOWS -> userHome.map { home ->
home.resolve("""AppData/Roaming/Factorio/mods""")
}
OS.MAC_OS -> macApplicationSupportDir.map { appSupport ->
appSupport.asFile.resolve("""factorio/mods""")
}
OS.UNSUPPORTED -> {
logger.warn("cannot automatically determine Factorio client mod directory, $os is unsupported")
Providers.notDefined() // https://github.com/gradle/gradle/issues/12388
}
}
}
))
}
}
private fun ProviderFactory.factorioModProp(name: String) {
environmentVariable("FACTORIO_MOD_$name")
.orElse(gradleProperty("factorioMod_$name"))
}

View file

@ -1,137 +0,0 @@
package dev.adamko.gradle.factorio
import dev.adamko.gradle.factorio.tasks.AssembleFactorioModContents
import dev.adamko.gradle.factorio.tasks.GenerateFactorioModInfoTask
import dev.adamko.gradle.factorio.tasks.LaunchFactorioClientTask
import dev.adamko.gradle.factorio.tasks.LocalPublishFactorioModTask
import dev.adamko.gradle.factorio.tasks.PackageFactorioModTask
import org.gradle.kotlin.dsl.withType
internal fun FactorioModPlugin.PluginContext.configureTasks() {
tasks.launchFactorioClient.configure {
}
tasks.assembleModContents.configure {
modFiles.apply {
from(settings.mainSources.typescript.destinationDirectory)
from(tasks.generateModInfoJson)
from(settings.mainSources.resources)
}
}
tasks.packageMod.configure {
from(tasks.assembleModContents)
}
tasks.publishModToLocalClient.configure {
dependsOn(tasks.packageMod)
}
tasks.generateModInfoJson.configure {
}
project.tasks.withType<LocalPublishFactorioModTask>().configureEach {
description = "Copy the mod to the Factorio client"
group = FactorioModPlugin.TASK_GROUP
onlyIf {
require(it is LocalPublishFactorioModTask)
it.clientModDirectory.asFile.get().exists()
}
modFiles.from(
configurations.factorioMod.map {
it.incoming
.artifactView { lenient(true) }
.files
}
)
doLast {
logger.lifecycle("Published Factorio Mod to '${clientModDirectory.asFile.get()}'")
}
}
configureLaunchFactorioClientTasks()
project.tasks.withType<GenerateFactorioModInfoTask>().configureEach {
description = "Generate info.json (required for Factorio Mods)"
group = FactorioModPlugin.TASK_GROUP
modName.convention(settings.modName)
modTitle.convention(settings.modTitle)
modDescription.convention(settings.modDescription)
modAuthor.convention(settings.modAuthor)
modVersion.convention(settings.modVersion)
factorioCompatibility.convention(settings.factorioCompatibility)
modDependencies.convention(settings.modDependencies)
infoJson.convention(
layout.file(
providers.provider {
temporaryDir.resolve("info.json")
}
)
)
}
project.tasks.withType<AssembleFactorioModContents>().configureEach {
description = "Gather the mod files that will be packaged into the mod zip"
group = FactorioModPlugin.TASK_GROUP
modName.convention(settings.modName)
modVersion.convention(settings.modVersion)
destination.convention(layout.dir(providers.provider { temporaryDir }))
}
project.tasks.withType<PackageFactorioModTask>().configureEach {
description = "Package the Factorio mod"
group = FactorioModPlugin.TASK_GROUP
archiveFileName.convention(settings.distributionZipName)
includeEmptyDirs = false
exclude {
// exclude empty files
it.file.run {
isFile && useLines { lines -> lines.all { line -> line.isBlank() } }
}
}
}
project.tasks.withType<LocalPublishFactorioModTask>().configureEach {
description = "Launch local Factorio Steam game client"
group = FactorioModPlugin.TASK_GROUP
modFiles.from(project.tasks.withType<PackageFactorioModTask>())
clientModDirectory.convention(layout.dir(settings.localDev.clientModsDirectory.asFile))
}
}
private fun FactorioModPlugin.PluginContext.configureLaunchFactorioClientTasks() {
val localDev = settings.localDev
// // convert to local props -> try to comply with Gradle config cache
// val localDevCurrentOs = localDev.currentOs
// val localDevWindowsSteamExe = localDev.windowsSteamExe
// val localDevFactorioSteamId = localDev.factorioSteamId
// val localDevServerConnectHost = localDev.serverConnectHost
// val localDevClientModDirectory = localDev.clientModDirectory
// val localDevMacApplicationSupportDir = localDev.macApplicationSupportDir
// val localDevMacFactorioApp = localDev.macFactorioApp
project.tasks.withType<LaunchFactorioClientTask>().configureEach {
description = "Launch local Factorio Steam game client"
group = FactorioModPlugin.TASK_GROUP
currentOs.convention(localDev.currentOs)
windowsSteamExe.convention(localDev.windowsSteamExe)
factorioSteamId.convention(localDev.factorioSteamId)
serverConnectHost.convention(localDev.serverConnectHost)
clientModsPath.convention(localDev.clientModsDirectory.map { it.asFile.canonicalPath })
macFactorioApp.convention(localDev.macFactorioApp)
}
}

View file

@ -1,19 +0,0 @@
package dev.adamko.gradle.factorio.mod
// to be used in a NamedDomainObject container?
//import org.gradle.api.Named
//import org.gradle.api.provider.Property
//
//abstract class FactorioModProperties : Named {
//
// abstract val modName: Property<String>
// abstract val modTitle: Property<String>
// abstract val modDescription: Property<String>
// abstract val modVersion: Property<String>
//
// // version of Factorio that the mod is compatible with (must only be "major.minor" - patch causes error)
// abstract val factorioCompatibility: Property<String>
//
// abstract val distributionZipName: Property<String>
//}

View file

@ -1,139 +0,0 @@
package dev.adamko.gradle.factorio.mod_portal
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.request.forms.MultiPartFormDataContent
import io.ktor.client.request.forms.formData
import io.ktor.client.request.forms.submitForm
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.Headers
import io.ktor.http.HttpHeaders
import io.ktor.http.Parameters
import io.ktor.http.append
import io.ktor.http.isSuccess
import io.ktor.serialization.kotlinx.json.json
import java.io.File
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.Json
import org.gradle.api.internal.tasks.userinput.UserInputHandler
import org.gradle.kotlin.dsl.support.useToRun
import io.ktor.client.plugins.logging.Logger as KtorLogger
import io.ktor.client.plugins.logging.Logging as KtorLogging
import org.gradle.api.logging.Logger as GradleLogger
import org.gradle.api.logging.Logging as GradleLogging
class FactorioModPortalPublishClient(
private val userInputHandler: UserInputHandler,
private val distributionZip: File,
private val modName: String,
private val modVersion: String,
private val portalApiKey: String,
private val portalUploadEndpoint: String,
private val modPortalBaseURl: String,
) {
private val logger: GradleLogger = GradleLogging.getLogger(this::class.java)
private fun client() = HttpClient(CIO) {
install(KtorLogging) {
logger = object : KtorLogger {
override fun log(message: String) {
this@FactorioModPortalPublishClient.logger.debug(message)
}
}
level = LogLevel.ALL
}
install(ContentNegotiation) {
json(Json {
prettyPrint = false
isLenient = true
})
}
defaultRequest {
header(HttpHeaders.Authorization, "Bearer $portalApiKey")
port = 443
}
followRedirects = false
expectSuccess = false
}
fun uploadMod(): Unit = runBlocking {
client().useToRun {
val initUploadResponse = initUpload()
val enteredVersion = userInputHandler.askQuestion(
"""
|Are you sure you want to publish $modName:$modVersion?
|Enter the version number to confirm:
""".trimMargin(),
"",
)
val confirmed = enteredVersion.trim().equals(modVersion.trim(), ignoreCase = true)
if (confirmed) {
upload(initUploadResponse)
} else {
logger.lifecycle("aborting mod '$modName' upload")
}
}
}
private suspend fun HttpClient.initUpload(): InitUploadResponse.Success {
val response = submitForm(
url = portalUploadEndpoint,
formParameters = Parameters.build {
append("mod", modName)
}
)
// println(response)
val initUploadResponse: InitUploadResponse =
Json.decodeFromString(InitUploadResponse.serializer(), response.bodyAsText())
// println(initUploadResponse)
require(response.status.isSuccess()) { "init upload request failed" }
return when (initUploadResponse) {
is Failure -> error(initUploadResponse)
is InitUploadResponse.Success -> initUploadResponse
}
}
private suspend fun HttpClient.upload(initUploadResponse: InitUploadResponse.Success) {
val requestForm = formData {
append(
"file",
distributionZip.readBytes(),
Headers.build {
append(HttpHeaders.ContentType, ContentType.Application.Zip)
append(HttpHeaders.ContentDisposition, "filename=${distributionZip.name}")
}
)
}
val response = post(initUploadResponse.uploadUrl) {
setBody(MultiPartFormDataContent(requestForm))
}
val submitUploadResponse =
Json.decodeFromString(SubmitUploadResponse.serializer(), response.bodyAsText())
// logger(response)
// println(submitUploadResponse)
require(response.status.isSuccess() && submitUploadResponse is SubmitUploadResponse.Success) {
"upload request failed"
}
logger.lifecycle("Mod '$modName' uploaded successfully! ${modPortalBaseURl.removeSuffix("/")}/$modName")
}
}

View file

@ -1,111 +0,0 @@
package dev.adamko.gradle.factorio.mod_portal
import dev.adamko.gradle.factorio.FactorioModPlugin
import io.ktor.http.URLBuilder
import io.ktor.http.takeFrom
import javax.inject.Inject
import kotlinx.coroutines.runBlocking
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.internal.tasks.userinput.UserInputHandler
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.Property
import org.gradle.api.provider.ProviderFactory
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.property
import org.gradle.kotlin.dsl.support.get
abstract class FactorioModPublishTask @Inject constructor(
objects: ObjectFactory,
providers: ProviderFactory,
) : DefaultTask() {
@get:InputFile
abstract val distributionZip: RegularFileProperty
@get:Input
abstract val modName: Property<String>
@get:Input
abstract val modVersion: Property<String>
// @get:Input
// abstract val factorioVersion: Property<String>
/** Bearer API key */
@get:Input
val portalApiKey: Property<String> = objects.property<String>().convention(
providers.gradleProperty("FACTORIO_MOD_PORTAL_API_KEY")
)
@get:Input
val portalApiUrl: Property<String> = objects.property<String>()
.convention("https://mods.factorio.com/api/v2/")
/**
* Base URL for linking to a mod page in the portal
*
* Example `https://mods.factorio.com/mod/my-mod-name`
*/
@get:Input
val modPortalBaseURl: Property<String> = objects.property<String>()
.convention("https://mods.factorio.com/mod/")
@get:Input
val portalUploadEndpoint: Property<String> = objects.property<String>()
.convention("mods/releases/init_upload")
init {
group = FactorioModPlugin.TASK_GROUP
}
@TaskAction
fun deploy(): Unit = runBlocking {
val userInputHandler = services.get<UserInputHandler>()
val portalUploadEndpoint = URLBuilder(portalApiUrl.get())
.takeFrom(portalUploadEndpoint.get())
.buildString()
val client = FactorioModPortalPublishClient(
userInputHandler = userInputHandler,
distributionZip = distributionZip.get().asFile,
modName = modName.get(),
modVersion = modVersion.get(),
portalApiKey = portalApiKey.get(),
portalUploadEndpoint = portalUploadEndpoint,
modPortalBaseURl = modPortalBaseURl.get(),
)
client.uploadMod()
}
// private fun validateInfoJson() {
// val modVersion = modVersion.get()
// val factorioVersion = factorioVersion.get()
//
// val distributionZip = distributionZip.get().asFile.toOkioPath()
//
// val zipContents = FileSystem.SYSTEM.openZip(distributionZip)
//
// val infoJson = zipContents.read("info.json".toPath()) {
// generateSequence { readUtf8Line() }
// }.joinToString("\n")
//
// val info: FactorioModInfo = Json.decodeFromString(FactorioModInfo.serializer(), infoJson)
//
// require(info.version == modVersion) {
// "mod version mismatch, ${info.version} vs $modVersion "
// }
//
// require(info.factorioVersion == factorioVersion) {
// "Factorio version mismatch, ${info.factorioVersion} vs $factorioVersion "
// }
// }
}

View file

@ -1,88 +0,0 @@
package dev.adamko.gradle.factorio.mod_portal
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonContentPolymorphicSerializer
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.jsonObject
@Serializable(with = InitUploadResponse.Serializer::class)
sealed interface InitUploadResponse {
/**
* @param[uploadUrl] URL the mod zip file should be uploaded to
*/
@Serializable
data class Success(
@SerialName("upload_url")
val uploadUrl: String,
) : InitUploadResponse
object Serializer :
JsonContentPolymorphicSerializer<InitUploadResponse>(InitUploadResponse::class) {
override fun selectDeserializer(element: JsonElement) = when {
"upload_url" in element.jsonObject -> Success.serializer()
else -> Failure.serializer()
}
}
}
@Serializable(with = SubmitUploadResponse.Serializer::class)
sealed interface SubmitUploadResponse {
@Serializable
data class Success(
val success: Boolean
) : SubmitUploadResponse
object Serializer : JsonContentPolymorphicSerializer<SubmitUploadResponse>(
SubmitUploadResponse::class
) {
override fun selectDeserializer(element: JsonElement) = when {
"success" in element.jsonObject -> Success.serializer()
else -> Failure.serializer()
}
}
}
@Serializable
data class Failure(
val error: String? = null,
val message: String? = null,
) : InitUploadResponse, SubmitUploadResponse {
private val reason: String?
get() = reasons[error]
override fun toString() = "Failure(error=$error, message=$message, reason=$reason)"
companion object {
private val reasons: Map<String?, String> = mapOf(
//@formatter:off
"InvalidApiKey" to "Missing or invalid API key for the current endpoint",
"InvalidRequest" to "Invalid request",
"InternalError" to "Internal error, please try again later.",
"Forbidden" to "Insufficient permission for current endpoint",
"Unknown" to "Unknown error, please try again later",
"InvalidModRelease" to "Invalid release data in info.json",
"InvalidModUpload" to "Invalid mod data in zipfile",
"UnknownMod" to "Mod does not exist in mod portal",
//@formatter:on
)
}
}
@Serializable
data class FactorioModInfo(
val name: String,
val version: String,
val title: String,
val description: String,
val author: String,
@SerialName("factorio_version") val factorioVersion: String,
val dependencies: List<String>,
)

View file

@ -1,40 +0,0 @@
package dev.adamko.gradle.factorio.tasks
import javax.inject.Inject
import org.gradle.api.*
import org.gradle.api.file.*
import org.gradle.api.internal.file.*
import org.gradle.api.provider.Property
import org.gradle.api.tasks.*
abstract class AssembleFactorioModContents @Inject constructor(
private val files: FileSystemOperations,
) : DefaultTask() {
@get:Input
abstract val modName: Property<String>
@get:Input
abstract val modVersion: Property<String>
@get:InputFiles
@get:SkipWhenEmpty
@get:PathSensitive(PathSensitivity.NAME_ONLY)
@get:IgnoreEmptyDirectories
abstract val modFiles: ConfigurableFileCollection
@get:OutputDirectory
abstract val destination: DirectoryProperty
@TaskAction
fun assemble() {
val modName = modName.get()
val modVersion = modVersion.get()
val modDirectory = "${modName}_${modVersion}"
files.sync {
from(modFiles)
into(destination.dir(modDirectory))
}
}
}

View file

@ -1,132 +0,0 @@
package dev.adamko.gradle.factorio.tasks
import javax.inject.Inject
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
abstract class GenerateFactorioModInfoTask @Inject constructor(
) : DefaultTask() {
/**
* Mandatory field. The internal name of mod. The game accepts anything as a mod name, however the mod portal restricts mod names to only consist of alphanumeric characters, dashes and underscores. Note that the mod folder or mod zip file name has to contain the mod name, where the restrictions of the file system apply.
*
* The game accepts mod names with a maximum length of 100 characters. The mod portal only accepts mods with names that are longer than 3 characters and shorter than 50 characters.
*/
@get:Input
abstract val modName: Property<String>
/**
* Mandatory field. The display name of the mod, so it is not recommended to use someUgly_pRoGrAmMeR-name here. Can be overwritten with a locale entry in the mod-name category, using the internal mod name as the key.
*
* The game will reject a title field that is longer than 100 characters. However, this can be worked around by using the locale entry. The mod portal does not restrict mod title length.
*/
@get:Input
abstract val modTitle: Property<String>
/**
* Optional field. A short description of what your mod does. This is all that people get to see in-game. Can be overwritten with a locale entry in the mod-description category, using the internal mod name as the key.
*/
@get:Input
@get:Optional
abstract val modDescription: Property<String>
/**
* Optional field. Where the mod can be found on the internet. Note that the in-game mod browser shows the mod portal link additionally to this field. Please don't put "None" here, it makes the field on the mod portal website look ugly. Just leave the field empty if the mod doesn't have a website/forum thread/discord.
*/
@get:Input
@get:Optional
abstract val modHomepage: Property<String>
/**
* Mandatory field. The author of the mod. This field does not have restrictions, it can also be a list of authors etc. The mod portal ignores this field, it will simply display the uploader's name as the author.
*/
@get:Input
abstract val modAuthor: Property<String>
/**
* Mandatory field. Defines the version of the mod in the format `number.number.number` for `Major.Middle.Minor`, for example `0.6.4`. Each number can range from 0 to 65535.
*/
@get:Input
abstract val modVersion: Property<String>
/**
* Optional field in the format "major.minor". The Factorio version that this mod supports. This can only be one Factorio version, not multiple. However, it includes all .sub versions. While the field is optional, usually mods are developed for versions higher than the default 0.12, so the field has to be added anyway.
*
* Adding a sub part, e.g. "0.18.27" will make the mod portal reject the mod and the game act weirdly. That means this shouldn't be done; use only the major and minor components "major.minor", for example "1.0".
*
* Mods with the factorio_version "0.18" can also be loaded in 1.0 and the mod portal will return them when queried for factorio_version 1.0 mods.
*/
@get:Input
@get:Optional
abstract val factorioCompatibility: Property<String>
/**
* Optional field. Mods that this mod depends on or is incompatible with.
* If this mod depends on another, the other mod will load first, see Data-Lifecycle.
* An empty array allows get around the default and have no dependencies at all.
*
* Example:
*
* `"dependencies": ["mod-a", "? mod-c > 0.4.3", "! mod-g"]`
*
* Each dependency is a string that consists of up to three parts: `<prefix> internal-mod-name <equality-operator version>`, for example `? some-mod-everyone-loves >= 4.2.0`.
*
* The equality operator (`<`, `<=`, `=`, `>=` or `>`) combined with the version allows to define dependencies that require certain mod versions, but it is not required.
*
* Incompatibility does not support versions; if incompatibility is used, version is ignored.
*
* The possible prefixes are:
* * `!` for incompatibility
* * `?` for an optional dependency
* * `(?)` for a hidden optional dependency
* * `~` for a dependency that does not affect load order
* * no prefix for a hard requirement for the other mod.
*/
@get:Input
@get:Optional
abstract val modDependencies: ListProperty<String>
@get:OutputFile
abstract val infoJson: RegularFileProperty
@TaskAction
fun generate() {
val infoJsonObject = buildJsonObject {
put("name", modName.get())
put("title", modTitle.get())
put("version", modVersion.get())
put("author", modAuthor.get())
modDescription.orNull?.let { put("description", it) }
modHomepage.orNull?.let { put("homepage", it) }
factorioCompatibility.orNull?.let { put("factorio_version", it) }
modDependencies.orNull?.let {
putJsonArray("dependencies") { it.forEach(::add) }
}
}
val infoJsonContent = encoder.encodeToString(infoJsonObject)
.replace("[\n ]", "[]")
val infoJson = infoJson.get().asFile
infoJson.parentFile.mkdirs()
infoJson.writeText(infoJsonContent + "\n")
}
companion object {
@OptIn(ExperimentalSerializationApi::class)
private val encoder = Json {
prettyPrint = true
prettyPrintIndent = " "
}
}
}

View file

@ -1,95 +0,0 @@
package dev.adamko.gradle.factorio.tasks
import dev.adamko.gradle.factorio.FactorioModSettings
import javax.inject.Inject
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.TaskAction
import org.gradle.process.ExecOperations
import org.gradle.work.DisableCachingByDefault
import org.jetbrains.kotlin.util.parseSpaceSeparatedArgs
@DisableCachingByDefault(because = "Not a cacheable task")
abstract class LaunchFactorioClientTask @Inject constructor(
private val executor: ExecOperations
) : DefaultTask() {
@get:Input
abstract val currentOs: Property<FactorioModSettings.LocalDev.OS>
@get:Input
@get:Optional
abstract val windowsSteamExe: Property<String>
@get:Input
@get:Optional
abstract val factorioSteamId: Property<String>
@get:Input
@get:Optional
abstract val serverConnectHost: Property<String>
@get:Input
@get:Optional
abstract val clientModsPath: Property<String>
@get:InputFile
@get:Optional
abstract val macFactorioApp: RegularFileProperty
@get:Input
@get:Optional
abstract val launchFactorioCommand: Property<String>
@TaskAction
fun launch() {
val launchCommand =
launchFactorioCommand.orNull ?: when (currentOs.orNull) {
FactorioModSettings.LocalDev.OS.WINDOWS -> windowsCmd()
FactorioModSettings.LocalDev.OS.MAC_OS -> macOSCmd()
null, FactorioModSettings.LocalDev.OS.UNSUPPORTED -> error("no can do, unsupported OS")
}
logger.lifecycle("Launching Factorio client\n > $launchCommand")
executor.exec {
commandLine = parseSpaceSeparatedArgs(launchCommand)
}
}
private fun windowsCmd(): String {
val steamExe = windowsSteamExe.orNull ?: error("missing Steam exe")
val factorioId = factorioSteamId.orNull ?: error("missing Factorio Steam ID")
val modsDirFlag = clientModsPath.map { """--mod-directory "$it"""" }.getOrElse("")
val mpConnectFlag = serverConnectHost.map { "--mp-connect $it" }.getOrElse("")
// commandLine = parseSpaceSeparatedArgs(
//// """explorer "steam://rungameid/$factorioGameId// --mp-connect localhost/" """ // not working
//// """explorer "steam://run/$factorioGameId//--mp-connect localhost/" """ // works! But has annoying pop-up
// """ ${steamExe.asFile.orNull?.canonicalPath} -applaunch $factorioGameId --mp-connect localhost --mod-directory ${clientModsDirectory.asFile.orNull?.canonicalPath} """
// )
return """
$steamExe --applaunch $factorioId $modsDirFlag $mpConnectFlag
""".trimIndent()
}
private fun macOSCmd(): String {
// val factorioApp = macFactorioApp.orNull ?: error("missing Factorio app")
val modsDirFlag = "" //clientModsPath.map { """--mod-directory "$it"""" }.getOrElse("")
val mpConnectFlag = serverConnectHost.map { "-mp-connect $it" }.getOrElse("")
return """
/Applications/Steam.app/Contents/MacOS/steam_osx -applaunch 427520 $modsDirFlag $mpConnectFlag
""".trimIndent()
// return """
// open -a "$factorioApp" --args $modsDirFlag $mpConnectFlag
// """.trimIndent()
}
}

View file

@ -1,40 +0,0 @@
package dev.adamko.gradle.factorio.tasks
import javax.inject.Inject
import org.gradle.api.DefaultTask
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileSystemOperations
import org.gradle.api.tasks.IgnoreEmptyDirectories
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.SkipWhenEmpty
import org.gradle.api.tasks.TaskAction
abstract class LocalPublishFactorioModTask @Inject constructor(
private val files: FileSystemOperations,
) : DefaultTask() {
@get:OutputDirectory
abstract val clientModDirectory: DirectoryProperty
@get:InputFiles
@get:SkipWhenEmpty
@get:PathSensitive(PathSensitivity.NAME_ONLY)
@get:IgnoreEmptyDirectories
abstract val modFiles: ConfigurableFileCollection
@TaskAction
fun install() {
logger.lifecycle("Copying mod from ${modFiles.files} to ${clientModDirectory.asFile.get()}")
files.copy {
from(modFiles) {
include("*.zip")
}
into(clientModDirectory)
}
}
}

View file

@ -1,6 +0,0 @@
package dev.adamko.gradle.factorio.tasks
import org.gradle.api.tasks.bundling.Zip
abstract class PackageFactorioModTask : Zip()

View file

@ -1,43 +0,0 @@
import org.gradle.kotlin.dsl.support.expectedKotlinDslPluginsVersion
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
`kotlin-dsl`
}
val gradleJvmTarget = "11"
description = "Provide Gradle settings plugins, used to configure base Gradle behaviour"
dependencies {
// This project should only be providing simple plugins for configuring Gradle without
// dependencies. Try to avoid setting dependencies here, else the Gradle script classpath might
// get polluted and messy.
implementation("org.gradle.kotlin:gradle-kotlin-dsl-plugins:$expectedKotlinDslPluginsVersion")
implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:${libs.versions.kotlin.get()}")
// https://github.com/gradle/gradle/issues/22510
implementation("org.jetbrains.kotlin:kotlin-sam-with-receiver:${libs.versions.kotlin.get()}")
implementation(platform(libs.kotlin.bom))
implementation("org.jetbrains.kotlin:kotlin-serialization:${libs.versions.kotlin.get()}")
implementation(platform(libs.kotlinx.coroutines.bom))
}
kotlin {
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(gradleJvmTarget))
}
}
kotlinDslPluginOptions {
jvmTarget.set(gradleJvmTarget)
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
jvmTarget = gradleJvmTarget
}
}

View file

@ -1,25 +0,0 @@
rootProject.name = "settings-plugins"
@Suppress("UnstableApiUsage") // Central declaration of repositories is an incubating feature
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
repositories {
mavenCentral()
gradlePluginPortal()
}
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
}
}
versionCatalogs {
create("libs") {
from(files("../../gradle/libs.versions.toml"))
}
}
}

View file

@ -1,29 +0,0 @@
package kafkatorio.conventions
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.gradle.kotlin.kotlin-dsl")
}
val gradleJvmTarget = 11
//kotlin {
// jvmToolchain(gradleJvmTarget)
//}
kotlin {
jvmToolchain {
languageVersion.set(JavaLanguageVersion.of(gradleJvmTarget))
}
}
kotlinDslPluginOptions {
jvmTarget.set("$gradleJvmTarget")
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
jvmTarget = "$gradleJvmTarget"
}
}

View file

@ -1,8 +0,0 @@
package kafkatorio.conventions
plugins {
kotlin("plugin.serialization")
}
// No config required or available. This convention plugin is only required because Gradle gets
// confused about the version.

View file

@ -1,21 +0,0 @@
package kafkatorio.conventions
import org.gradle.api.Project
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import org.gradle.jvm.toolchain.JavaLanguageVersion
import org.gradle.jvm.toolchain.JavaToolchainSpec
import org.gradle.kotlin.dsl.plugins.dsl.*
import org.gradle.kotlin.dsl.withType
fun Project.overrideKotlinLanguageVersion(
gradleKotlinTarget: String = "1.6"
) {
afterEvaluate {
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
apiVersion = gradleKotlinTarget
languageVersion = gradleKotlinTarget
}
}
}
}

View file

@ -1,86 +0,0 @@
@file:Suppress("PackageDirectoryMismatch")
package org.gradle.kotlin.dsl
import org.gradle.api.artifacts.dsl.RepositoryHandler
fun RepositoryHandler.jitpack() {
maven("https://jitpack.io")
}
fun RepositoryHandler.myMavenLocal(enabled: Boolean = true) {
if (enabled) {
println("Maven local is enabled")
mavenLocal {
content {
// includeGroup("dev.adamko")
// includeGroup("dev.adamko.kxtsgen")
includeGroup("io.kotest")
}
}
}
}
fun RepositoryHandler.sonatypeSnapshot() {
maven("https://oss.sonatype.org/content/repositories/snapshots") {
mavenContent {
snapshotsOnly()
includeGroup("io.kotest")
}
}
maven("https://s01.oss.sonatype.org/content/repositories/snapshots/") {
mavenContent {
snapshotsOnly()
includeGroup("io.kotest")
}
}
}
fun RepositoryHandler.nodeDistributions() {
// Declare the Node.js download repository
ivy("https://nodejs.org/dist/") {
name = "Node Distributions at $url"
patternLayout { artifact("v[revision]/[artifact](-v[revision]-[classifier]).[ext]") }
metadataSources { artifact() }
content { includeModule("org.nodejs", "node") }
}
}
fun RepositoryHandler.yarnDistributions() {
ivy("https://github.com/yarnpkg/yarn/releases/download") {
name = "Yarn Distributions at $url"
patternLayout { artifact("v[revision]/[artifact](-v[revision]).[ext]") }
metadataSources { artifact() }
content { includeModule("com.yarnpkg", "yarn") }
}
}
// https://stackoverflow.com/a/34327202/4161471
// example: implementation("jmeter-gradle-plugin:jmeter-gradle-plugin:1.0.3@zip")
fun RepositoryHandler.gitHub() {
ivy("https://github.com/") {
patternLayout {
artifact("/[organisation]/[module]/archive/[revision].[ext]")
}
metadataSources { artifact() }
content {
includeGroup("jmeter-gradle-plugin")
}
}
}
fun RepositoryHandler.kotlinxHtml() {
maven("https://maven.pkg.jetbrains.space/public/p/kotlinx-html/maven") {
mavenContent {
includeGroup("org.jetbrains.kotlinx")
}
}
}

View file

@ -1,35 +0,0 @@
package kafkatorio.conventions.settings
@Suppress("UnstableApiUsage") // Central declaration of repositories is an incubating feature
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
repositories {
myMavenLocal()
mavenCentral()
jitpack()
gradlePluginPortal()
// Declare the Node.js download repository
nodeDistributions()
yarnDistributions()
maven("https://raw.githubusercontent.com/adamko-dev/kotka-streams/artifacts/m2") {
content { includeGroup("dev.adamko.kotka") }
}
kotlinxHtml()
sonatypeSnapshot()
}
pluginManagement {
repositories {
myMavenLocal()
gradlePluginPortal()
mavenCentral()
jitpack()
sonatypeSnapshot()
}
}
}

View file

@ -1,14 +0,0 @@
org.gradle.jvmargs=-Dfile.encoding=UTF-8 -Xmx4g
kotlin.mpp.stability.nowarn=true
#kotlin.mpp.enableGranularSourceSetsMetadata=true
#kotlin.native.enableDependencyPropagation=false
org.gradle.dependency.verification.console=verbose
org.gradle.caching=true
org.gradle.unsafe.configuration-cache=true
org.gradle.unsafe.configuration-cache-problems=warn
org.gradle.kotlin.dsl.precompiled.accessors.strict=true
org.gradle.parallel=true

File diff suppressed because it is too large Load diff

View file

@ -1,331 +0,0 @@
# @formatter:off
##########
[versions]
##########
## compilation ##
jvm = "11"
kotlin = "1.7.22"
## libs ##
camel-kafkaConnectors = "0.11.0"
http4k = "4.25.16.2"
kafka = "3.3.1" # https://kafka.apache.org/downloads
kvision = "5.18.1" # https://github.com/rjaros/kvision/releases
log4j2 = "2.17.2"
okio = "3.2.0" # https://search.maven.org/artifact/com.squareup.okio/okio
qosLogback = "1.2.11"
scrimage = "4.0.32" # https://github.com/sksamuel/scrimage/releases
semver = "1.2.0" # https://github.com/swiftzer/semver/releases
slf4j = "1.7.36"
kotlinx-serialization = "1.4.0" # https://github.com/Kotlin/kotlinx.serialization/releases
kxs-charleskornKaml = "0.44.0"
kxs-mamoeYamlkt = "0.12.0"
kxs-kxsTsGen = "0.2.1"
kotlinJsWrappers = "1.0.0-pre.456" # https://search.maven.org/artifact/org.jetbrains.kotlin-wrappers/kotlin-wrappers-bom
kotlinx-cli = "0.3.5" # https://github.com/Kotlin/kotlinx-cli/releases
kotlinx-coroutines = "1.6.4" # https://github.com/Kotlin/kotlinx.coroutines/releases
kotlinx-datetime = "0.4.0" # https://github.com/Kotlin/kotlinx-datetime/releases
kotlinx-html = "0.8.0" # https://github.com/Kotlin/kotlinx.html/releases
kotlinx-nodejs = "0.0.7"
kSvgDsl = "v2.2.0"
ktor = "2.1.3" # https://github.com/ktorio/ktor/releases
hoplite = "2.7.0" # https://github.com/sksamuel/hoplite/releases
simpleSyslogParser = "1.0.0" # https://search.maven.org/artifact/com.github.palindromicity/simple-syslog
kotkaStreams = "22.08.06"
marykRocksDb = "7.3.1-2" # https://search.maven.org/artifact/io.maryk.rocksdb/rocksdb-multiplatform
klogging = "0.4.9"
nimbusJoseJwt = "9.25.6" # https://search.maven.org/artifact/com.nimbusds/nimbus-jose-jwt
## npm ##
npm-luaTypes = "2.13.1" # https://www.npmjs.com/package/lua-types
npm-typescriptToLua = "1.11.1" # https://www.npmjs.com/package/typescript-to-lua
npm-typedFactorio = "1.11.0" # https://github.com/GlassBricks/typed-factorio/blob/main/Changelog.md https://www.npmjs.com/package/typed-factorio
npm-typescript = "4.9" # https://github.com/microsoft/TypeScript/releases
npm-bootswatch = "5.2.2" # https://www.jsdelivr.com/package/npm/bootswatch
## test ##
junit = "5.9.1" # https://github.com/junit-team/junit5/releases
kotest = "5.5.4" # https://github.com/kotest/kotest/releases
mockk = "1.13.3" # https://github.com/mockk/mockk/releases/
## infra ##
factorio = "1.1.72" # https://www.factorio.com/download
confluent-kafkaConnect = "7.0.1"
grafana = "8.5.0"
prometheus = "v2.34.0"
## gradle plugins ##
gradleNodePlugin = "3.5.0" # https://github.com/node-gradle/gradle-node-plugin/releases
#########
[plugins]
#########
kotlinJvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
kotlinJs = { id = "org.jetbrains.kotlin.js", version.ref = "kotlin" }
kotlinSerialization = { id = "org.jetbrains.kotlin.kotlin-serialization", version.ref = "kotlin" }
loggingCapabilities = { id = "dev.jacomet.logging-capabilities", version = "0.10.0" }
###########
[libraries]
###########
## kotlin ##
kotlin-bom = { group = "org.jetbrains.kotlin", name = "kotlin-bom", version.ref = "kotlin" }
kotlin-embeddableCompiler = { module = "org.jetbrains.kotlin:kotlin-compiler-embeddable" }
kotlinScripting-common = { group = "org.jetbrains.kotlin", name = "kotlin-scripting-common" }
kotlinScripting-jvm = { group = "org.jetbrains.kotlin", name = "kotlin-scripting-jvm" }
kotlinScripting-jvmHost = { group = "org.jetbrains.kotlin", name = "kotlin-scripting-jvm-host" }
kotlinScripting-dependencies = { group = "org.jetbrains.kotlin", name = "kotlin-scripting-dependencies" }
kotlinScripting-dependenciesMaven = { group = "org.jetbrains.kotlin", name = "kotlin-scripting-dependencies-maven" }
kotlinxSerialization-bom = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-bom", version.ref = "kotlinx-serialization" }
kotlinxSerialization-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-core" }
kotlinxSerialization-cbor = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-cbor" }
kotlinxSerialization-hocon = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-hocon" }
kotlinxSerialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json" }
kotlinxSerialization-properties = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-properties" }
kotlinxSerialization-protobuf = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-protobuf" }
kotlinxSerialization-jsonOkio = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json-okio" }
kotlinxSerialization-charleskornKaml = { group = "com.charleskorn.kaml", name = "kaml", version.ref = "kxs-charleskornKaml" }
kotlinxSerialization-mamoeYamlkt = { group = "net.mamoe.yamlkt", name = "yamlkt", version.ref = "kxs-mamoeYamlkt" }
#kxs-kxsTsGen = { group = "dev.adamko.kxstsgen", name = "kxs-ts-gen-core", version.ref = "kxs-kxsTsGen" }
kotlinxSerialization-kxsTsGen = { group = "com.github.adamko-dev.kotlinx-serialization-typescript-generator", name = "kxs-ts-gen-core", version.ref = "kxs-kxsTsGen" }
kotlinx-coroutines-bom = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-bom", version.ref = "kotlinx-coroutines" }
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core" }
kotlinx-coroutines-jdk8 = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8" }
kotlinx-html = { group = "org.jetbrains.kotlinx", name = "kotlinx-html", version.ref = "kotlinx-html" }
kotlinx-nodejs = { group = "org.jetbrains.kotlinx", name = "kotlinx-nodejs", version.ref = "kotlinx-nodejs" }
kotlinx-cli = { group = "org.jetbrains.kotlinx", name = "kotlinx-cli", version.ref = "kotlinx-cli" }
kotlinx-datetime = { group = "org.jetbrains.kotlinx", name = "kotlinx-datetime", version.ref = "kotlinx-datetime" }
kSvgDsl = { group = "com.github.nwillc", name = "ksvg", version.ref = "kSvgDsl" }
kotlin-jsWrappers-bom = { group = "org.jetbrains.kotlin-wrappers", name = "kotlin-wrappers-bom", version.ref = "kotlinJsWrappers" }
## http4k ##
http4k-bom = { group = "org.http4k", name = "http4k-bom", version.ref = "http4k" }
http4k-core = { group = "org.http4k", name = "http4k-core" }
http4k-contract = { group = "org.http4k", name = "http4k-contract" }
http4k-client-okhttp = { group = "org.http4k", name = "http4k-client-okhttp" }
http4k-client-ws = { group = "org.http4k", name = "http4k-client-websocket" }
http4k-server = { group = "org.http4k", name = "http4k-server-undertow" }
http4k-cloudnative = { group = "org.http4k", name = "http4k-cloudnative" }
#http4k-format-jackson-json = { group = "org.http4k", name = "http4k-format-jackson" }
#http4k-format-jackson-xml = { group = "org.http4k", name = "http4k-format-jackson-xml" }
#http4k-format-jackson-yaml = { group = "org.http4k", name = "http4k-format-jackson-yaml" }
http4k-format-kotlinx = { group = "org.http4k", name = "http4k-format-kotlinx-serialization" }
http4k-graphql = { group = "org.http4k", name = "http4k-graphql" }
## ktor ##
ktor-bom = { group = "io.ktor", name = "ktor-bom", version.ref = "ktor" }
ktorSerialization-kotlinxJson = { group = "io.ktor", name = "ktor-serialization-kotlinx-json" }
ktorClient-core = { group = "io.ktor", name = "ktor-client-core" }
ktorClient-auth = { group = "io.ktor", name = "ktor-client-auth" }
ktorClient-cio = { group = "io.ktor", name = "ktor-client-cio" }
ktorClient-contentNegotiation = { group = "io.ktor", name = "ktor-client-content-negotiation" }
ktorClient-encoding = { group = "io.ktor", name = "ktor-client-encoding" }
ktorClient-logging = { group = "io.ktor", name = "ktor-client-logging" }
ktorClient-resources = { group = "io.ktor", name = "ktor-client-resources" }
ktorClient-websockets = { group = "io.ktor", name = "ktor-client-websockets" }
ktorClient-testMock = { group = "io.ktor", name = "ktor-client-mock" }
ktorServer-core = { group = "io.ktor", name = "ktor-server-core" }
ktorServer-auth = { group = "io.ktor", name = "ktor-server-auth" }
ktorServer-authJwt = { group = "io.ktor", name = "ktor-server-auth-jwt" }
ktorServer-autoHeadResponse = { group = "io.ktor", name = "ktor-server-auto-head-response" }
ktorServer-cachingHeaders = { group = "io.ktor", name = "ktor-server-caching-headers" }
ktorServer-callId = { group = "io.ktor", name = "ktor-server-call-id" }
ktorServer-callLogging = { group = "io.ktor", name = "ktor-server-call-logging" }
ktorServer-compression = { group = "io.ktor", name = "ktor-server-compression" }
ktorServer-conditionalHeaders = { group = "io.ktor", name = "ktor-server-conditional-headers" }
ktorServer-contentNegotiaion = { group = "io.ktor", name = "ktor-server-content-negotiation" }
ktorServer-cors = { group = "io.ktor", name = "ktor-server-cors" }
ktorServer-dataConversion = { group = "io.ktor", name = "ktor-server-data-conversion" }
ktorServer-defaultHeaders = { group = "io.ktor", name = "ktor-server-default-headers" }
ktorServer-forwardedHeader = { group = "io.ktor", name = "ktor-server-forwarded-header" }
ktorServer-hsts = { group = "io.ktor", name = "ktor-server-hsts" }
ktorServer-httpRedirect = { group = "io.ktor", name = "ktor-server-http-redirect" }
ktorServer-netty = { group = "io.ktor", name = "ktor-server-netty" }
ktorServer-cio = { group = "io.ktor", name = "ktor-server-cio" }
ktorServer-partialContent = { group = "io.ktor", name = "ktor-server-partial-content" }
ktorServer-resources = { group = "io.ktor", name = "ktor-server-resources" }
ktorServer-sessions = { group = "io.ktor", name = "ktor-server-sessions" }
ktorServer-statusPages = { group = "io.ktor", name = "ktor-server-status-pages" }
ktorServer-websockets = { group = "io.ktor", name = "ktor-server-websockets" }
ktorServer-testHost = { group = "io.ktor", name = "ktor-server-test-host" }
ktorNetwork-core = { group = "io.ktor", name = "ktor-network" }
ktorNetwork-tls = { group = "io.ktor", name = "ktor-network-tls" }
### jackson ##
#jackson-bom = { group = " com.fasterxml.jackson.module", name = ":jackson-module-kotlin", version = "2.13.+" }
#jackson-kotlin = { group = " com.fasterxml.jackson.module", name = ":jackson-module-kotlin", version = "2.13.+" }
## logging ##
slf4j-api = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" }
kotlin-logging = { group = "io.github.microutils", name = "kotlin-logging-jvm", version = "2.1.21" }
logback-core = { group = "ch.qos.logback", name = "logback-core", version.ref = "qosLogback" }
logback-classic = { group = "ch.qos.logback", name = "logback-classic", version.ref = "qosLogback" }
logback-encoder = { group = "net.logstash.logback", name = "logstash-logback-encoder", version = "6.6" }
klogging = { group = "io.klogging", name = "klogging-jvm", version.ref = "klogging" }
## gcp ##
#gcp-bom = { group = "com.google.cloud", name = "libraries-bom", version = "23.1.0" }
#gcp-pubsub = { group = "com.google.cloud", name = "google-cloud-pubsub" }
#gcp-speech = { group = "com.google.cloud", name = "google-cloud-speech" }
## kafka ##
kafka-streams = { group = "org.apache.kafka", name = "kafka-streams", version.ref = "kafka" }
kafka-streamsTestUtils = { group = "org.apache.kafka", name = "kafka-streams-test-utils", version.ref = "kafka" }
# kafka helpers
#kotka = { group = "com.github.blueanvil", name = "kotka", version = "1.1.1" }
kafka-kotkaStreams = { group = "dev.adamko.kotka", name = "kotka-streams", version.ref = "kotkaStreams" }
marykRocksDb = { group = "io.maryk.rocksdb", name = "rocksdb-multiplatform", version.ref = "marykRocksDb" }
jsoup = { group = "org.jsoup", name = "jsoup", version = "1.14.3" }
skrapeit = { group = "it.skrape", name = "skrapeit", version = "1.2.0" }
scrimage-core = { group = "com.sksamuel.scrimage", name = "scrimage-core", version.ref = "scrimage" }
semver = { group = "net.swiftzer.semver", name = "semver", version.ref = "semver" }
## okio ##
okio-bom = { group = "com.squareup.okio", name = "okio-bom", version.ref = "okio" }
okio-core = { group = "com.squareup.okio", name = "okio" }
hoplite-core = { group = "com.sksamuel.hoplite", name = "hoplite-core", version.ref = "hoplite" }
hoplite-datetime = { group = "com.sksamuel.hoplite", name = "hoplite-datetime", version.ref = "hoplite" }
hoplite-yaml = { group = "com.sksamuel.hoplite", name = "hoplite-yaml", version.ref = "hoplite" }
simpleSyslogParser = { group = "com.github.palindromicity", name = "simple-syslog", version.ref = "simpleSyslogParser" }
nimbusJoseJwt = { group = "com.nimbusds", name = "nimbus-jose-jwt", version.ref = "nimbusJoseJwt" }
#############
### test ###
#############
mockk = { group = "io.mockk", name = "mockk", version.ref = "mockk" }
## junit ##
junit-bom = { group = "org.junit", name = "junit-bom", version.ref = "junit" }
junit-api = { group = "org.junit.jupiter", name = "junit-jupiter-api" } # version.ref = "junit" }
junit-engine = { group = "org.junit.jupiter", name = "junit-jupiter-engine" } # version.ref = "junit" }
junit-launcher = { group = "org.junit.platform", name = "junit-platform-launcher" } # version = "1.7.2" }
## kotest ##
kotest-bom = { module = "io.kotest:kotest-bom", version.ref = "kotest" }
kotest-core = { module = "io.kotest:kotest-assertions-core" }
kotest-datatest = { module = "io.kotest:kotest-framework-datatest" }
kotest-json = { module = "io.kotest:kotest-assertions-json" }
kotest-prop = { module = "io.kotest:kotest-property" }
kotest-frameworkEngine = { module = "io.kotest:kotest-framework-engine" }
kotest-runnerJunit5 = { module = "io.kotest:kotest-runner-junit5" }
kotestPlugin-embeddedCompiler = { group = "io.kotest", name = "kotest-framework-multiplatform-plugin-embeddable-compiler" }
kotestPlugin-multiplatform = { group = "io.kotest", name = "kotest-framework-multiplatform-plugin-gradle" }
## http4k ##
http4k-test-chaos = { group = "org.http4k", name = "http4k-testing-chaos", version.ref = "http4k" }
http4k-test-approval = { group = "org.http4k", name = "http4k-testing-approval", version.ref = "http4k" }
http4k-test-kotest = { group = "org.http4k", name = "http4k-testing-kotest", version.ref = "http4k" }
################
### plugins ###
################
gradlePlugin-kvision = { module = "io.kvision:io.kvision.gradle.plugin", version.ref = "kvision" }
#########
[bundles]
#########
logging = [
"slf4j-api",
"kotlin-logging",
"logback-core",
"logback-classic",
"logback-encoder",
]
#kt-testing = [
# "kotest-core",
# "kotest-datatest",
# "kotest-runner",
# "kotest-prop",
# "kotest-json",
# "mockk",
#]
junit-runtime = [
"junit-engine",
"junit-launcher",
]
kotlinScripting-def = [
"kotlinScripting-common",
"kotlinScripting-jvm",
"kotlinScripting-dependencies",
"kotlinScripting-dependenciesMaven",
]
kotlinScripting-host = [
"kotlinScripting-common",
"kotlinScripting-jvm",
"kotlinScripting-jvmHost",
]
hoplite = [
"hoplite-core",
"hoplite-yaml",
"hoplite-datetime",
]

Binary file not shown.

View file

@ -1,6 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

244
gradlew vendored
View file

@ -1,244 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
gradlew.bat vendored
View file

@ -1,92 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View file

@ -1,32 +0,0 @@
// git update-index --skip-worktree kt52647.gradle.kts
val projectsMustBeConfiguringBuster by tasks.registering {
val buildFile = layout.projectDirectory.file("kt52647.gradle.kts").asFile
doLast {
logger.warn("Applying 'Projects must be configuring' workaround - https://youtrack.jetbrains.com/issue/KT-52647")
val newLines = buildFile.readText().lines().joinToString("\n") { line ->
if (line.startsWith("// projects must be configuring buster")) {
"// projects must be configuring buster ${System.currentTimeMillis()}"
} else {
line
}
}
buildFile.writeText(newLines)
}
}
allprojects {
tasks
.matching { it.name != projectsMustBeConfiguringBuster.name }
.configureEach {
finalizedBy(projectsMustBeConfiguringBuster)
}
}
// projects must be configuring buster
// ^ this line will be edited by projectsMustBeConfiguringBuster

View file

@ -1,175 +0,0 @@
import kafkatorio.tasks.GenerateTypeScriptTask
import org.jetbrains.kotlin.gradle.plugin.KotlinCompilation
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinJvmCompilation
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import dev.adamko.gradle.factorio.typescriptAttributes
plugins {
id("kafkatorio.conventions.lang.kotlin-multiplatform")
id("dev.adamko.factorio-mod-library") // only needed for 'attributes' - need to split up the plugin?
kotlin("plugin.serialization")
distribution
}
description = "shared data structures and utilities"
kotlin {
js(IR) {
browser {}
// this is a library - don't set binaries.executable()
}
jvm {
val main by compilations.getting {
kotlinOptions {
jvmTarget = "11"
}
}
testRuns.configureEach {
executionTask.configure {
useJUnitPlatform()
}
}
}
sourceSets {
configureEach {
languageSettings.apply {
optIn("kotlin.ExperimentalStdlibApi")
optIn("kotlin.ExperimentalUnsignedTypes")
optIn("kotlin.RequiresOptIn")
optIn("kotlin.js.ExperimentalJsExport")
optIn("kotlin.time.ExperimentalTime")
optIn("kotlinx.coroutines.FlowPreview")
optIn("kotlinx.serialization.ExperimentalSerializationApi")
}
}
val commonMain by getting {
dependencies {
implementation(dependencies.platform(projects.modules.versionsPlatform))
implementation(libs.kotlinxSerialization.core)
implementation(libs.kotlinxSerialization.json)
api(libs.kotlinxSerialization.kxsTsGen)
implementation(libs.okio.core)
implementation(libs.kotlinx.coroutines.core)
}
}
val commonTest by getting {
dependencies {
implementation(dependencies.platform(projects.modules.versionsPlatform))
implementation(kotlin("test"))
implementation(libs.kotest.core)
implementation(libs.kotest.datatest)
implementation(libs.kotest.frameworkEngine)
implementation(libs.kotest.json)
implementation(libs.kotest.prop)
}
}
val jvmMain by getting {
dependencies {
implementation(dependencies.platform(projects.modules.versionsPlatform))
implementation(kotlin("reflect"))
}
}
val jvmTest by getting {
dependencies {
implementation(dependencies.platform(projects.modules.versionsPlatform))
implementation(libs.kotest.runnerJunit5)
}
}
val jsTest by getting {
dependencies { }
}
}
}
val kotlinJvmMainCompilation: NamedDomainObjectProvider<KotlinJvmCompilation> =
kotlin.jvm().compilations.named(KotlinCompilation.MAIN_COMPILATION_NAME)
val jvmJar: TaskProvider<Jar> = tasks.named<Jar>(kotlin.jvm().artifactsTaskName)
val kotlinMainRuntimeDependencies: Provider<FileCollection> =
kotlinJvmMainCompilation.map { it.runtimeDependencyFiles }
val kotlinMainCompileDependencies: Provider<FileCollection> =
kotlinJvmMainCompilation.map { it.compileDependencyFiles }
val kotlinMainCompileTask: Provider<KotlinCompile> =
kotlinJvmMainCompilation.map { it.compileKotlinTask }
val generateTypeScript by tasks.registering(GenerateTypeScriptTask::class) {
dependsOn(jvmJar)
// dependsOn(kotlinMainCompileTask)
// inputs.files(jvmJar.map { it.outputs.files })
// inputs.files(kotlinMainCompileTask.map { it.javaSources })
classpath(
jvmJar,
kotlinMainRuntimeDependencies,
// kotlinMainCompileTask.map { it.libraries }
// kotlinMainDependencies,
)
output.set(layout.buildDirectory.dir("generated/typescript"))
mainClass.set("dev.adamko.kafkatorio.schema.Kt2ts2Kt")
args(temporaryDir.canonicalPath)
}
val schemaTsDistributionName: Provider<String> = providers.provider {
"${rootProject.name}-${project.name}"
}
val generateTypeScriptOutputFiles: Provider<FileTree> =
generateTypeScript.map { it.outputs.files.asFileTree }
//val schemaTs by distributions.registering {
// distributionBaseName.set(schemaTsDistributionName)
// contents {
// from(generateTypeScriptOutputFiles)
// }
//}
//val schemaTsZipTask: TaskProvider<Zip> = tasks.named<Zip>("${schemaTs.name}DistZip")
//val schemaTsZipTaskArchiveFile: Provider<RegularFile> = schemaTsZipTask.flatMap { it.archiveFile }
val schemaTsZip by tasks.registering(Zip::class) {
group = "kt2ts"
archiveBaseName.set("schema-ts")
from(generateTypeScriptOutputFiles)
destinationDirectory.set(layout.buildDirectory.dir("distributions/kt2ts"))
}
val schemaTsZipTaskArchiveFile: Provider<RegularFile> = schemaTsZip.flatMap { it.archiveFile }
val typeScriptModelGenerated by configurations.creating<Configuration> {
asProvider()
typescriptAttributes(objects)
outgoing.artifact(schemaTsZipTaskArchiveFile)
// outgoing.artifact(schemaTsZipTaskArchiveFile)
}

View file

@ -1,79 +0,0 @@
package dev.adamko.kafkatorio.library
import kotlin.jvm.JvmInline
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.modules.SerializersModule
val jsonMapperKafkatorio = Json {
prettyPrint = true
prettyPrintIndent = " "
serializersModule = SerializersModule {
// contextual(List::class) { args -> FactorioListJsonSerializer(args[0]) }
}
}
/** @see LuaJsonListSerializer */
@Serializable(with = LuaJsonListSerializer::class)
@JvmInline
value class LuaJsonList<T>(private val list: List<T>) : List<T> by list
/**
* Factorio outputs **empty** lists `[]` as *empty* Json objects `{}`.
*
* When deserializing JSON, this serializer transforms any incoming empty objects to empty
* [array][JsonArray]s.
*/
class LuaJsonListSerializer<T>(
elementSerializer: KSerializer<T>
) : KSerializer<LuaJsonList<T>> {
private val listSerializer: KSerializer<List<T>> = ListSerializer(elementSerializer)
override val descriptor: SerialDescriptor =
SerialDescriptor("kafkatorio.LuaList", listSerializer.descriptor)
override fun deserialize(decoder: Decoder): LuaJsonList<T> = LuaJsonList(
when (decoder) {
is JsonDecoder -> deserializeJson(decoder)
else -> decoder.decodeSerializableValue(listSerializer)
}
)
private fun deserializeJson(decoder: JsonDecoder): List<T> =
when (val element = decoder.decodeJsonElement()) {
is JsonObject -> when {
element.entries.isEmpty() -> emptyList()
else -> deserializeError(
"expected empty Json object, but contained ${element.entries.size} entries ${element.entries}"
)
}
is JsonArray -> decoder.json.decodeFromJsonElement(listSerializer, element)
else -> deserializeError(
"expected empty Json object or a Json array, but was $element"
)
}
override fun serialize(encoder: Encoder, value: LuaJsonList<T>) {
encoder.encodeSerializableValue(listSerializer, value)
}
companion object {
private fun deserializeError(msg: String): Nothing = throw SerializationException(
"Error deserializing LuaList: $msg"
)
}
}

View file

@ -1,160 +0,0 @@
package dev.adamko.kafkatorio.library
import kotlinx.serialization.BinaryFormat
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.builtins.ByteArraySerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.AbstractDecoder
import kotlinx.serialization.encoding.AbstractEncoder
import kotlinx.serialization.encoding.CompositeDecoder
import kotlinx.serialization.encoding.CompositeEncoder
import kotlinx.serialization.modules.EmptySerializersModule
import kotlinx.serialization.modules.SerializersModule
import okio.Buffer
import okio.BufferedSink
import okio.BufferedSource
val kxsBinary: KxsBinary = KxsBinary()
/** [`https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/formats.md#efficient-binary-format`](https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/formats.md#efficient-binary-format) */
class KxsBinary(
override val serializersModule: SerializersModule = EmptySerializersModule()
) : BinaryFormat {
override fun <T> encodeToByteArray(serializer: SerializationStrategy<T>, value: T): ByteArray {
val output = Buffer()
val encoder = KxsDataOutputEncoder(output, serializersModule)
encoder.encodeSerializableValue(serializer, value)
return output.readByteArray()
}
override fun <T> decodeFromByteArray(
deserializer: DeserializationStrategy<T>,
bytes: ByteArray
): T {
val input = Buffer().write(bytes)
val decoder = KxsDataInputDecoder(input, serializersModule)
return decoder.decodeSerializableValue(deserializer)
}
}
private val byteArraySerializer = ByteArraySerializer()
class KxsDataOutputEncoder(
private val output: BufferedSink,
override val serializersModule: SerializersModule = EmptySerializersModule(),
) : AbstractEncoder() {
private operator fun BufferedSink.invoke(action: BufferedSink.() -> Unit): Unit = action()
override fun encodeBoolean(value: Boolean) = output { writeByte(if (value) 1 else 0) }
override fun encodeByte(value: Byte) = output { writeByte(value.toInt()) }
override fun encodeChar(value: Char) = output { writeUtf8CodePoint(value.code) }
override fun encodeDouble(value: Double) = output { writeLong(value.toRawBits()) }
override fun encodeEnum(enumDescriptor: SerialDescriptor, index: Int) = output { writeInt(index) }
override fun encodeFloat(value: Float) = output { writeInt(value.toRawBits()) }
override fun encodeInt(value: Int) = output { writeInt(value) }
override fun encodeLong(value: Long) = output { writeLong(value) }
override fun encodeShort(value: Short) = output { writeShort(value.toInt()) }
override fun encodeString(value: String) = output {
encodeCompactSize(value.length)
writeUtf8(value)
}
override fun beginCollection(
descriptor: SerialDescriptor,
collectionSize: Int
): CompositeEncoder {
encodeCompactSize(collectionSize)
return this
}
override fun encodeNull() = encodeBoolean(false)
override fun encodeNotNullMark() = encodeBoolean(true)
override fun <T> encodeSerializableValue(serializer: SerializationStrategy<T>, value: T) {
when (serializer.descriptor) {
byteArraySerializer.descriptor -> encodeByteArray(value as ByteArray)
else -> super.encodeSerializableValue(serializer, value)
}
}
private fun encodeByteArray(bytes: ByteArray) {
encodeCompactSize(bytes.size)
output.write(bytes)
}
private fun encodeCompactSize(value: Int) {
if (value < 0xff) {
output.writeByte(value)
} else {
output.writeByte(0xff)
output.writeInt(value)
}
}
}
class KxsDataInputDecoder(
private val input: BufferedSource,
override val serializersModule: SerializersModule = EmptySerializersModule(),
private var elementsCount: Int = 0,
) : AbstractDecoder() {
private var elementIndex = 0
override fun decodeBoolean(): Boolean = input.readByte().toInt() != 0
override fun decodeByte(): Byte = input.readByte()
override fun decodeChar(): Char = input.readUtf8CodePoint().toChar()
override fun decodeDouble(): Double = Double.fromBits(input.readLong())
override fun decodeEnum(enumDescriptor: SerialDescriptor): Int = input.readInt()
override fun decodeFloat(): Float = Float.fromBits(input.readInt())
override fun decodeInt(): Int = input.readInt()
override fun decodeLong(): Long = input.readLong()
override fun decodeShort(): Short = input.readShort()
override fun decodeString(): String {
val size = decodeCompactSize()
return input.readUtf8(size.toLong())
}
override fun decodeElementIndex(descriptor: SerialDescriptor): Int {
if (elementIndex == elementsCount) return CompositeDecoder.DECODE_DONE
return elementIndex++
}
override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder =
KxsDataInputDecoder(input, serializersModule, descriptor.elementsCount)
override fun decodeSequentially(): Boolean = true
override fun decodeCollectionSize(descriptor: SerialDescriptor): Int =
decodeCompactSize().also { elementsCount = it }
override fun decodeNotNullMark(): Boolean = decodeBoolean()
override fun <T> decodeSerializableValue(
deserializer: DeserializationStrategy<T>,
previousValue: T?
): T {
@Suppress("UNCHECKED_CAST")
return when (deserializer.descriptor) {
byteArraySerializer.descriptor -> decodeByteArray() as T
else -> super.decodeSerializableValue(deserializer, previousValue)
}
}
private fun decodeByteArray(): ByteArray {
val bytes = ByteArray(decodeCompactSize())
input.readFully(bytes)
return bytes
}
private fun decodeCompactSize(): Int {
val byte = input.readByte().toInt() and 0xff
if (byte < 0xff) return byte
return input.readInt()
}
}

View file

@ -1,103 +0,0 @@
package dev.adamko.kafkatorio.library
import dev.adamko.kafkatorio.schema.common.ChunkSize
import dev.adamko.kafkatorio.schema.common.MapChunkPosition
import dev.adamko.kafkatorio.schema.common.MapEntityPosition
import dev.adamko.kafkatorio.schema.common.MapTilePosition
import kotlin.math.floor
operator fun MapTilePosition.times(factor: Int): MapTilePosition =
MapTilePosition(x * factor, y * factor)
operator fun MapTilePosition.div(divisor: Int): MapTilePosition =
MapTilePosition(x / divisor, y / divisor)
operator fun MapTilePosition.plus(addend: Int): MapTilePosition =
MapTilePosition(x + addend, y + addend)
operator fun MapTilePosition.plus(addend: MapTilePosition): MapTilePosition =
MapTilePosition(x + addend.x, y + addend.y)
operator fun MapTilePosition.minus(subtrahend: MapTilePosition): MapTilePosition =
MapTilePosition(x - subtrahend.x, y - subtrahend.y)
/** Get the [MapChunkPosition] of the tile */
fun MapTilePosition.toMapChunkPosition(chunkSize: ChunkSize): MapChunkPosition =
MapChunkPosition(
x = floor(x.toDouble() / chunkSize.lengthInTiles.toDouble()).toInt(),
y = floor(y.toDouble() / chunkSize.lengthInTiles.toDouble()).toInt(),
chunkSize = chunkSize,
)
/** Get the [MapTilePosition] of the entity */
fun MapEntityPosition.toMapTilePosition(): MapTilePosition =
MapTilePosition(
x = floor(x).toInt(),
y = floor(y).toInt(),
)
/** Get the [MapChunkPosition] of the entity */
fun MapEntityPosition.toMapChunkPosition(chunkSize: ChunkSize): MapChunkPosition =
MapChunkPosition(
x = floor(x / chunkSize.lengthInTiles.toDouble()).toInt(),
y = floor(y / chunkSize.lengthInTiles.toDouble()).toInt(),
chunkSize = chunkSize,
)
fun MapChunkPosition.resize(chunkSize: ChunkSize): MapChunkPosition =
leftTopTile().toMapChunkPosition(chunkSize)
operator fun MapChunkPosition.times(factor: Int): MapChunkPosition =
copy(x = x * factor, y = y * factor)
operator fun MapChunkPosition.plus(addend: Int): MapChunkPosition =
copy(x = x + addend, y = y + addend)
operator fun MapChunkPosition.minus(subtrahend: Int): MapChunkPosition =
copy(x = x - subtrahend, y = y - subtrahend)
fun MapChunkPosition.leftTopTile(): MapTilePosition =
MapTilePosition(
x * chunkSize.lengthInTiles,
y * chunkSize.lengthInTiles,
)
fun MapChunkPosition.rightBottomTile(): MapTilePosition =
leftTopTile() + (chunkSize.lengthInTiles - 1)
/** Iterate over all possible [MapTilePosition]s in the chunk. */
fun MapChunkPosition.iterateTiles(): Iterator<MapTilePosition> {
val leftTop = leftTopTile()
val rightBottom = rightBottomTile()
return iterator {
(leftTop.x..rightBottom.x).forEach { x ->
(leftTop.y..rightBottom.y).forEach { y ->
yield(MapTilePosition(x, y))
}
}
}
}
//val MapChunkPosition.rightBottomTile: MapTilePosition
// get() = leftTopTile + (MAP_CHUNK_SIZE - 1)
//
//val MapChunkPosition.boundingBox: MapBoundingBox
// get() = MapBoundingBox(leftTopTile, rightBottomTile)

View file

@ -1,143 +0,0 @@
package dev.adamko.kafkatorio.schema.common
import dev.adamko.kxstsgen.core.experiments.TupleSerializer
import kotlin.math.roundToInt
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* Red, green, blue and alpha values, all in range `[0, 1]` or all in range `[0, 255]` if any
* value is > 1.
*
* All values here are optional. Colour channels default to `0`, the alpha channel defaults to `1`.
*/
@Serializable(with = Colour.Serializer::class)
@SerialName("kafkatorio.common.Colour")
data class Colour(
val red: Float = 0f,
val green: Float = 0f,
val blue: Float = 0f,
val alpha: Float = 1f,
) {
object Serializer : TupleSerializer<Colour>(
"Colour",
{
element(Colour::red)
element(Colour::green)
element(Colour::blue)
element(Colour::alpha)
}
) {
override fun tupleConstructor(elements: Iterator<*>): Colour {
return Colour(
elements.next() as Float,
elements.next() as Float,
elements.next() as Float,
elements.next() as Float,
)
}
}
}
/** Size-efficient version of [Colour] (`4*4` bytes vs `4*1` bytes) */
@Serializable
@SerialName("kafkatorio.common.ColourHex")
data class ColourHex(
val red: UByte = UByte.MIN_VALUE,
val green: UByte = UByte.MIN_VALUE,
val blue: UByte = UByte.MIN_VALUE,
val alpha: UByte = UByte.MAX_VALUE,
) {
companion object {
val TRANSPARENT = ColourHex(0u, 0u, 0u, 0u)
val WHITE = ColourHex(UByte.MAX_VALUE, UByte.MAX_VALUE, UByte.MAX_VALUE, UByte.MAX_VALUE)
}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/** True if any value is greater than 1, so the values are hexadecimal. */
fun Colour.isHexadecimal(): Boolean {
return red > 1f
|| green > 1f
|| blue > 1f
|| alpha > 1f
}
/** True if all values are between `[0..1]`. */
fun Colour.isPercentage(): Boolean = !isHexadecimal()
fun Colour.toHexString(includeAlpha: Boolean = false): String {
val hexConverter: Float.() -> String = when {
isHexadecimal() -> Float::hexadecimalToString
else -> Float::percentageToHexadecimalString
}
val length = if (includeAlpha) 9 else 7
return buildString(length) {
append('#')
append(red.hexConverter())
append(green.hexConverter())
append(blue.hexConverter())
if (includeAlpha) {
append(alpha.hexConverter())
}
}
}
fun Float.hexadecimalToString(): String =
roundToInt().toString(16).padStart(2, ' ')
fun Float.percentageToHexadecimalString(): String =
times(255).roundToInt().toString(16).padStart(2, ' ')
private val ubyteMaxFloat = UByte.MAX_VALUE.toFloat()
private val ubyteMinFloat = UByte.MIN_VALUE.toFloat()
private val ubyteRangeFloat = ubyteMinFloat..ubyteMaxFloat
private fun Float.toColourHex() = (this * ubyteMaxFloat)
.coerceIn(ubyteRangeFloat)
.toUInt()
.toUByte()
private fun Float.coerceToColourHex() = coerceIn(ubyteRangeFloat)
.toUInt()
.toUByte()
fun Colour.toHex(): ColourHex {
val converter: Float.() -> UByte = when {
isPercentage() -> Float::toColourHex
else -> Float::coerceToColourHex
}
return ColourHex(
red.converter(),
green.converter(),
blue.converter(),
alpha.converter(),
)
}
private fun UByte.toPercentileFloat() = (this.toFloat() / ubyteMaxFloat).coerceIn(0f..1f)
fun ColourHex.toPercentile(): Colour {
return Colour(
red.toPercentileFloat(),
green.toPercentileFloat(),
blue.toPercentileFloat(),
alpha.toPercentileFloat(),
)
}

View file

@ -1,276 +0,0 @@
package dev.adamko.kafkatorio.schema.common
import kotlin.jvm.JvmInline
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
// TODO change all booleans to be optional, and default to 'false' (also in events-mod)
@Serializable
@SerialName("kafkatorio.entity.FactorioEntityData")
sealed interface FactorioEntityData {
val protoId: PrototypeId
val position: MapEntityPosition
/** Non-specific entity data */
@Serializable
@SerialName("kafkatorio.entity.FactorioEntityDataStandard")
data class Standard(
override val protoId: PrototypeId,
override val position: MapEntityPosition,
val graphicsVariation: UByte? = null,
val health: Float? = null,
val isActive: Boolean = false,
val isRotatable: Boolean = false,
val lastUser: UInt? = null,
val status: Status? = null,
val unitNumber: UnitNumber? = null,
) : FactorioEntityData
@Serializable
@SerialName("kafkatorio.entity.FactorioEntityDataResource")
data class Resource(
override val protoId: PrototypeId,
override val position: MapEntityPosition,
val amount: UInt,
/** Count of initial resource units contained. `null` if resource is not infinite. */
val initialAmount: UInt? = null,
) : FactorioEntityData
/**
* [`https://lua-api.factorio.com/latest/defines.html#defines.entity_status`](https://lua-api.factorio.com/latest/defines.html#defines.entity_status)
*/
@Suppress("unused") // not directly used at the moment - maybe later
@Serializable
@SerialName("kafkatorio.entity.FactorioEntityData.FactorioEntityStatus")
enum class Status {
WORKING,
NORMAL,
NO_POWER,
LOW_POWER,
NO_FUEL,
DISABLED_BY_CONTROL_BEHAVIOR,
OPENED_BY_CIRCUIT_NETWORK,
CLOSED_BY_CIRCUIT_NETWORK,
DISABLED_BY_SCRIPT,
MARKED_FOR_DECONSTRUCTION,
/** Used by generators and solar panels. */
NOT_PLUGGED_IN_ELECTRIC_NETWORK,
/** Used by power switches. */
NETWORKS_CONNECTED,
/** Used by power switches. */
NETWORKS_DISCONNECTED,
/** Used by accumulators. */
CHARGING,
/** Used by accumulators. */
DISCHARGING,
/** Used by accumulators. */
FULLY_CHARGED,
/** Used by logistic containers. */
OUT_OF_LOGISTIC_NETWORK,
/** Used by assembling machines. */
NO_RECIPE,
/** Used by furnaces. */
NO_INGREDIENTS,
/** USED BY BOILERS, fluid turrets and fluid energy sources: Boiler has no fluid to work with. */
NO_INPUT_FLUID,
/** Used by labs. */
NO_RESEARCH_IN_PROGRESS,
/** Used by mining drills. */
NO_MINABLE_RESOURCES,
/** Used by boilers and fluid turrets: Boiler still has some fluid but is about to run out. */
LOW_INPUT_FLUID,
/** Used by crafting machines. */
FLUID_INGREDIENT_SHORTAGE,
/**
* Used by crafting machines, boilers, burner energy sources and reactors: Reactor/burner has
* full burnt result inventory, boiler has full output fluid box.
*/
FULL_OUTPUT,
/** Used by crafting machines. */
ITEM_INGREDIENT_SHORTAGE,
/** Used by mining drills when the mining fluid is missing. */
MISSING_REQUIRED_FLUID,
/** Used by labs. */
MISSING_SCIENCE_PACKS,
/** Used by inserters. */
WAITING_FOR_SOURCE_ITEMS,
/** Used by inserters and mining drills. */
WAITING_FOR_SPACE_IN_DESTINATION,
/** Used by the rocket silo. */
PREPARING_ROCKET_FOR_LAUNCH,
/** Used by the rocket silo. */
WAITING_TO_LAUNCH_ROCKET,
/** Used by the rocket silo. */
LAUNCHING_ROCKET,
/** Used by beacons. */
NO_MODULES_TO_TRANSMIT,
/** Used by roboports. */
RECHARGING_AFTER_POWER_OUTAGE,
/** Used by inserters targeting entity ghosts. */
WAITING_FOR_TARGET_TO_BE_BUILT,
/** Used by inserters targeting rails. */
WAITING_FOR_TRAIN,
/** Used by ammo turrets. */
NO_AMMO,
/** Used by heat energy sources. */
LOW_TEMPERATURE,
/** Used by constant combinators: Combinator is turned off via switch in GUI. */
DISABLED,
/** Used by lamps. */
TURNED_OFF_DURING_DAYTIME,
/** Used by rail signals. */
NOT_CONNECTED_TO_RAIL,
/** Used by rail signals. */
CANT_DIVIDE_SEGMENTS,
}
}
sealed interface FactorioEntityUpdateDictionary<T : Any>
: Iterable<Pair<MapEntityPosition, T>> {
val entitiesXY: Map<String, Map<String, T>>
operator fun get(position: MapEntityPosition): T? =
entitiesXY[position.x.toString()]?.get(position.y.toString())
override fun iterator(): Iterator<Pair<MapEntityPosition, T>> =
iterator {
val invalid = mutableListOf<String>()
entitiesXY.forEach { (xString, column) ->
val x = xString.toDoubleOrNull()
column.forEach { (yString, entity) ->
val y = yString.toDoubleOrNull()
if (x == null || y == null) {
invalid += "$xString/$yString"
} else {
yield(MapEntityPosition(x, y) to entity)
}
}
}
if (invalid.isNotEmpty()) {
println("WARNING FactorioEntityUpdateDictionary contained invalid x/y coords: ${invalid.joinToString()}")
}
}
@Serializable
@SerialName("kafkatorio.entity.FactorioEntityUpdateResourceAmountDictionary")
@JvmInline
value class ResourceAmounts(
override val entitiesXY: Map<String, Map<String, UInt>> = emptyMap()
) : FactorioEntityUpdateDictionary<UInt>
@Serializable
@SerialName("kafkatorio.entity.FactorioEntityUpdateEntityDictionary")
@JvmInline
value class Entity(
override val entitiesXY: Map<String, Map<String, FactorioEntityUpdateElement.Standard>>
) : FactorioEntityUpdateDictionary<FactorioEntityUpdateElement.Standard>
}
sealed interface FactorioEntityUpdateElement {
@Serializable
@SerialName("kafkatorio.entity.FactorioEntityUpdateElementStandard")
data class Standard(
val status: FactorioEntityData.Status? = null,
val unitNumber: UnitNumber? = null,
val graphicsVariation: UByte? = null,
val health: Float? = null,
val isActive: Boolean = false,
val isRotatable: Boolean = false,
val lastUser: UInt? = null,
) : FactorioEntityUpdateElement
}
/*
AssemblingMachine
Beam
Car
Character
CharacterCorpse
CraftingMachine
ElectricEnergyInterface
ElectricPole
EntityGhost
EntityWithHealth
EntityWithOwner
FlyingText
Furnace
Gate
Generator
Ghost
HeatInterface
HighlightBox
InfinityContainer
InfinityPipe
Inserter
ItemEntity
LandMine
LinkedBelt
Loader
Market
MiningDrill
ProgrammableSpeaker
Pump
Radar
Rail
RailChainSignal
RailSignal
Reactor
ResourceEntity
RocketSilo
SmokeWithTrigger
SpiderVehicle
Splitter
TrainStop
TransportBeltConnectable
TransportBeltToGround
Turret
Unit
Vehicle
*/

View file

@ -1,114 +0,0 @@
package dev.adamko.kafkatorio.schema.common
import kotlin.jvm.JvmInline
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName("kafkatorio.id.Tick")
@JvmInline
value class Tick(val value: UInt)
val UInt.tick
get() = Tick(this)
/**
* Unique ID associated with this surface
*
* See [`LuaSurface.index`](https://lua-api.factorio.com/latest/LuaSurface.html#LuaSurface.index)
*/
@Serializable
@SerialName("kafkatorio.id.SurfaceIndex")
@JvmInline
value class SurfaceIndex(private val id: UInt) {
override fun toString(): String = "$id"
}
@Serializable
@SerialName("kafkatorio.id.ForceIndex")
@JvmInline
value class ForceIndex(private val id: UInt) {
override fun toString(): String = "$id"
}
/** The player's index in `LuaGameScript::players` */
@Serializable
@SerialName("kafkatorio.id.PlayerIndex")
@JvmInline
value class PlayerIndex(private val id: UInt) {
override fun toString(): String = "$id"
}
/** > This is universally unique for every entity that has one, for the lifetime of a whole game. */
@Serializable
@SerialName("kafkatorio.id.UnitNumber")
@JvmInline
value class UnitNumber(private val id: UInt) {
override fun toString(): String = "$id"
}
@Serializable
@SerialName("kafkatorio.id.EventName")
@JvmInline
value class EventName(private val name: String) {
override fun toString(): String = name
}
interface EntityIdentifiers {
val unitNumber: UnitNumber?
/** The 'prototype type' and 'prototype name' of the entity. */
val protoId: PrototypeId
}
// instant of EntityIdentifiers, because kxs needs a concrete instance
@Serializable
@SerialName("kafkatorio.id.EntityIdentifiersData")
data class EntityIdentifiersData(
override val unitNumber: UnitNumber? = null,
override val protoId: PrototypeId,
) : EntityIdentifiers
/** Friendly identifier, used in URLs. Should be human-readable. */
@Serializable
@SerialName("kafkatorio.id.FactorioServerId")
@JvmInline
value class FactorioServerId(val id: String) : CharSequence by id {
init {
require(id.isNotBlank()) { "require FactorioServerId is not blank: '$id'" }
require(id.matches(validIdRegex)) { "require FactorioServerId matches $validIdRegex: '$id'" }
}
override fun toString(): String = id
companion object {
val validIdRegex = Regex("""^[a-zA-Z0-9\-_]+""" + "\$")
}
}
/** Short identifier, used in tokens. Might not be human-readable. */
@Serializable
@SerialName("kafkatorio.id.FactorioServerToken")
@JvmInline
value class FactorioServerToken(private val id: String) : CharSequence by id {
init {
require(id.isNotBlank()) { "require FactorioServerToken is not blank: '$id'" }
require(id.matches(FactorioServerId.validIdRegex)) { "require FactorioServerToken matches ${validIdRegex}: '$id'" }
}
override fun toString(): String = id
companion object {
val validIdRegex = Regex("^[a-zA-Z0-9]+\$")
}
}

View file

@ -1,82 +0,0 @@
package dev.adamko.kafkatorio.schema.common
import dev.adamko.kafkatorio.library.LuaJsonList
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName("kafkatorio.prototype.FactorioPrototype")
sealed interface FactorioPrototype {
val protoId: PrototypeId
@SerialName("kafkatorio.prototype.MapTile")
@Serializable
data class MapTile(
override val protoId: PrototypeId,
val mapColour: Colour,
val layer: UInt,
// @Contextual
val collisionMasks: LuaJsonList<String>,
val order: String,
/** Can the tile be mined for resources? */
val canBeMined: Boolean = false,
) : FactorioPrototype
/**
* @param[colour] The colour of the prototype, or `null` if the prototype doesn't have colour.
* @param[mapColour] The map colour used when charting this entity if a
* [friendly][mapColourFriend] or [enemy][mapColourEnemy] colour isn't defined or `null`.
* @param[mapColourFriend] The friendly map colour used when charting this entity.
* @param[mapColourEnemy] The enemy map colour used when charting this entity.
* @param[tileWidth] Tiling size. If odd, center is the center of the tiles. If even, it's on the tile border.
* @param[tileHeight] Tiling size. If odd, center is the center of the tiles. If even, it's on the tile border.
*/
@SerialName("kafkatorio.prototype.Entity")
@Serializable
data class Entity(
override val protoId: PrototypeId,
val group: ItemGroup,
val subgroup: ItemGroup,
val colour: Colour? = null,
val mapColour: Colour? = null,
val mapColourFriend: Colour? = null,
val mapColourEnemy: Colour? = null,
val maxHealth: Float,
val isBuilding: Boolean = false,
val isEntityWithOwner: Boolean = false,
val isMilitaryTarget: Boolean = false,
val miningProperties: MiningProperties? = null,
val collisionBox: MapBoundingBox? = null,
val tileWidth: Int? = null,
val tileHeight: Int? = null,
) : FactorioPrototype {
@Serializable
@SerialName("kafkatorio.prototype.EntityMiningProperties")
data class MiningProperties(
val canBeMined: Boolean = false,
// @Contextual
val products: LuaJsonList<MinedProduct>?,
)
@Serializable
@SerialName("kafkatorio.prototype.EntityItemGroup")
data class ItemGroup(
val name: String? = null,
val type: String? = null,
val parentName: String? = null,
)
}
}

View file

@ -1,123 +0,0 @@
package dev.adamko.kafkatorio.schema.common
import dev.adamko.kafkatorio.schema.common.MapTileDictionary.PrototypeKey
import kotlin.jvm.JvmInline
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
const val MAP_CHUNK_SIZE = 32
@Serializable
data class MapTile(
val x: Int,
val y: Int,
val protoId: PrototypeId,
)
/**
* 2D map of x/y tile positions and prototype-name, optimised for JSON size.
*
* [protos] is a one-to-one map between a prototype[PrototypeId] and [PrototypeKey].
*
* [PrototypeKey] is an arbitrary integer value, which maps to one [PrototypeId] only for a
* specific instance of [MapTileDictionary].
*
* @param[tilesXY] Map an X/Y coordinate to a [PrototypeKey].
*/
@Serializable
@SerialName("kafkatorio.packet.keyed.MapTileDictionary")
data class MapTileDictionary(
val tilesXY: Map<String, Map<String, PrototypeKey>>,
val protos: Map<PrototypeId, PrototypeKey>,
) {
private val protosIndexToId: Map<PrototypeKey, PrototypeId> by lazy {
protos.entries.associate { (name, key) -> key to name }
}
fun toMapTileList(): List<MapTile> = buildList {
tilesXY.forEach { (xString, row) ->
row.forEach { (yString, protoIndex) ->
val x = xString.toIntOrNull()
val y = yString.toIntOrNull()
val protoName = protosIndexToId[protoIndex]
if (x != null && y != null && protoName != null) {
add(MapTile(x, y, protoName))
} else if (protoName == null) {
println("warning: no prototype name found for index:$protoIndex. $protosIndexToId")
}
}
}
}
/** An arbitrary ID for a prototype in [MapTileDictionary.protos]. */
@Serializable
@JvmInline
value class PrototypeKey(private val index: Int) : Comparable<Int> by index
// companion object {
// fun MapTileDictionary?.isNullOrEmpty(): Boolean {
// return this == null || (tilesXY.isEmpty() && tilesXY.all { it.value.isEmpty() })
// }
// }
}
@Serializable
data class ServerMapChunkId(
val serverId: FactorioServerId,
val layer: ServerMapTileLayer,
val chunkPosition: MapChunkPosition,
val surfaceIndex: SurfaceIndex,
) {
val chunkSize: ChunkSize get() = chunkPosition.chunkSize
}
@Serializable
enum class ServerMapTileLayer(val dir: String) {
@SerialName("terrain")
TERRAIN("terrain"),
@SerialName("resource")
RESOURCE("resource"),
@SerialName("building")
BUILDING("building"),
}
/** `${serverDataDir}/servers/{serverId}/map/${layer}/s{surfaceIndex}/z{zoomLevel}/x{chunkX}/y{chunkY}.png` */
@Serializable
@JvmInline
value class ServerMapTilePngFilename(val value: String) {
constructor(id: ServerMapChunkId) : this(
serverId = id.serverId,
layer = id.layer,
surfaceIndex = id.surfaceIndex,
zoomLevel = id.chunkSize.zoomLevel,
chunkX = id.chunkPosition.x,
chunkY = id.chunkPosition.y,
)
constructor(
serverId: FactorioServerId,
layer: ServerMapTileLayer,
surfaceIndex: SurfaceIndex,
zoomLevel: Int,
chunkX: Int,
chunkY: Int,
) : this(
"servers/${serverId.id}" +
"/map" +
"/layers/${layer.dir}" +
"/s${surfaceIndex}" +
"/z${zoomLevel}" +
"/x${chunkX}" +
"/y${chunkY}" +
".png"
)
}

View file

@ -1,224 +0,0 @@
package dev.adamko.kafkatorio.schema.common
import dev.adamko.kafkatorio.library.leftTopTile
import dev.adamko.kafkatorio.library.rightBottomTile
import dev.adamko.kxstsgen.core.experiments.TupleSerializer
import kotlin.math.abs
import kotlin.math.ceil
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* The position of something that exists in-game (not conceptually, like a
* [chunk][MapChunkPosition])
*/
sealed interface MapPosition : Comparable<MapPosition> {
val x: Number
val y: Number
}
/**
* Coordinates of an [entity][FactorioEntityData.Standard] on a map.
*
* Positive y points south, positive x points east.
*
* A [MapEntityPosition] can be translated to a [MapChunkPosition] by dividing the `x`/`y` values
* by [32][MAP_CHUNK_SIZE].
*/
@Serializable(with = MapEntityPosition.Companion.Serializer::class)
data class MapEntityPosition(
override val x: Double,
override val y: Double,
) : MapPosition {
override fun compareTo(other: MapPosition): Int =
when (val resultX = x.compareTo(other.x.toDouble())) {
0 -> y.compareTo(other.y.toDouble())
else -> resultX
}
companion object {
object Serializer : TupleSerializer<MapEntityPosition>(
"MapEntityPosition",
{
element(MapEntityPosition::x)
element(MapEntityPosition::y)
}
) {
override fun tupleConstructor(elements: Iterator<*>): MapEntityPosition {
return MapEntityPosition(
elements.next() as Double,
elements.next() as Double,
)
}
}
}
}
/**
* Coordinates of a tile on a surface, where each `x`/`y` coordinate represents a different
* [MapTile].
*
* Positive y points south, positive x points east.
*
* It rounds any `x`/`y` down to whole numbers.
*/
@Serializable(with = MapTilePosition.Companion.Serializer::class)
data class MapTilePosition(
override val x: Int,
override val y: Int,
) : MapPosition {
override fun compareTo(other: MapPosition): Int =
when (val resultX = x.compareTo(other.x.toInt())) {
0 -> y.compareTo(other.y.toInt())
else -> resultX
}
companion object {
object Serializer : TupleSerializer<MapTilePosition>(
"MapTilePosition",
{
element(MapTilePosition::x)
element(MapTilePosition::y)
}
) {
override fun tupleConstructor(elements: Iterator<*>): MapTilePosition {
val x = requireNotNull(elements.next() as? Int)
val y = requireNotNull(elements.next() as? Int)
return MapTilePosition(x, y)
}
}
}
}
/**
* Coordinates of a chunk on a surface, where each `x`/`y` coordinate represents a different
* chunk.
*
* Positive y points south, positive x points east.
*
* A [MapChunkPosition] can be translated to a [MapEntityPosition] by multiplying the `x`/`y`
* values by [32][MAP_CHUNK_SIZE].
*/
@Serializable(with = MapChunkPosition.Companion.Serializer::class)
data class MapChunkPosition(
val x: Int,
val y: Int,
// Don't set a default for ChunkSize. It could default to 32, but it's clearer to make it explicit
// and avoid accidentally not setting it. Also, a default doesn't save much in serialization size.
val chunkSize: ChunkSize,
) {
val bounds: MapChunkPositionBounds by lazy {
MapChunkPositionBounds(this)
}
operator fun contains(tilePosition: MapTilePosition): Boolean = tilePosition in bounds
operator fun contains(entityPosition: MapEntityPosition): Boolean = entityPosition in bounds
companion object {
object Serializer : TupleSerializer<MapChunkPosition>(
"MapChunkPosition",
{
element(MapChunkPosition::x)
element(MapChunkPosition::y)
element(MapChunkPosition::chunkSize)
}
) {
override fun tupleConstructor(elements: Iterator<*>): MapChunkPosition {
return MapChunkPosition(
elements.next() as Int,
elements.next() as Int,
elements.next() as ChunkSize,
)
}
}
}
}
/**
* The bounds of a [MapChunkPosition], that may contain a [MapPosition].
*
* Because Factorio uses screen-coordinates, the lowest `x/y` coordinate is the [leftTop], and
* the highest is [rightBottomTile].
*/
@Serializable
data class MapChunkPositionBounds(
val leftTop: MapTilePosition,
val rightBottom: MapTilePosition,
val chunkSize: ChunkSize, // should be computable based on the tiles, but include it for completeness
) : ClosedRange<MapPosition> {
constructor(chunkPosition: MapChunkPosition) : this(
chunkPosition.leftTopTile(),
chunkPosition.rightBottomTile(),
chunkPosition.chunkSize,
)
override val start: MapTilePosition
get() = leftTop
override val endInclusive: MapTilePosition
get() = rightBottom
}
@Serializable
enum class ChunkSize(
val zoomLevel: Int,
) : Comparable<ChunkSize> {
CHUNK_512(-1),
CHUNK_256(0),
CHUNK_128(1),
CHUNK_064(2),
CHUNK_032(3),
;
/** 32, 64, 128, 256, or 512 */
val lengthInTiles: Int = 2f.pow(8 - zoomLevel).roundToInt()
init {
require(lengthInTiles > 0) { "tilesPerChunk $lengthInTiles must be positive" }
// 1000 & 0111 = 0000 => pow^2
// 1001 & 1000 = 1000 => !pow^2
require(lengthInTiles and (lengthInTiles - 1) == 0) {
"tilesPerChunk $lengthInTiles must be a power-of-two number"
}
}
companion object {
// cache values for better performance. KT-48872
val entries: Set<ChunkSize> = values().toSet()
val MAX: ChunkSize = entries.maxByOrNull { it.lengthInTiles }!!
val MIN: ChunkSize = entries.minByOrNull { it.lengthInTiles }!!
val STANDARD: ChunkSize = entries.first { it.zoomLevel == 0 }
}
}
@Serializable
@SerialName("kafkatorio.position.MapBoundingBox")
data class MapBoundingBox(
val leftTop: MapEntityPosition,
val rightBottom: MapEntityPosition,
) {
val width: Double get() = abs(leftTop.x - rightBottom.x)
val height: Double get() = abs(leftTop.y - rightBottom.y)
val tileWidth: Int get() = ceil(width).toInt()
val tileHeight: Int get() = ceil(height).toInt()
}

View file

@ -1,783 +0,0 @@
package dev.adamko.kafkatorio.schema.common
import kotlin.jvm.JvmInline
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* Both a [name] and [type] are required to unique identify a [prototype][FactorioPrototype].
*
* @property[name] The name of the prototype, which is unique per specific Prototype [type]
*/
@Serializable
@JvmInline
@SerialName("kafkatorio.id.PrototypeId")
value class PrototypeId private constructor(
private val typeNameConcat: String,
) {
val type: Type get() = Type(typeNameConcat.substringBefore(delim, ""))
val name: Name get() = Name(typeNameConcat.substringAfter(delim, ""))
operator fun component1(): Type = type
operator fun component2(): Name = name
constructor(
type: String,
name: String,
) : this("${type}${delim}${name}")
/** Denotes the class of the Prototype */
@Serializable
@JvmInline
@SerialName("kafkatorio.id.PrototypeIdType")
value class Type(private val id: String) {
override fun toString(): String = id
}
/** A specific implementation of a [type]. Unique per prototype 'super class' */
@Serializable
@JvmInline
@SerialName("kafkatorio.id.PrototypeIdName")
value class Name(private val name: String) {
override fun toString(): String = name
}
companion object {
private const val delim = '/'
}
}
/** Serialize a [PrototypeId] as an integer - more efficient storage */
@JvmInline
@Serializable
value class PrototypeHashCode private constructor(val code: Int) {
constructor(id: PrototypeId) : this(id.hashCode())
constructor(tile: FactorioPrototype) : this(tile.protoId)
}
//@Suppress("unused")
//enum class PrototypeTypeId(
// val id: String
//) {
// AmbientSound("ambient-sound"),
// Animation("animation"),
// EditorController("editor-controller"),
// Font("font"),
// GodController("god-controller"),
// MapGenPresets("map-gen-presets"),
// MapSettings("map-settings"),
// MouseCursor("mouse-cursor"),
// Sound("sound"),
// SpectatorController("spectator-controller"),
// Sprite("sprite"),
// TileEffect("tile-effect"),
// TipsAndTricksItemCategory("tips-and-tricks-item-category"),
// TriggerTargetType("trigger-target-type"),
// WindSound("wind-sound"),
// Achievement("achievement"),
// BuildEntityAchievement("build-entity-achievement"),
// CombatRobotCountAchievement("combat-robot-count"),
// ConstructWithRobotsAchievement("construct-with-robots-achievement"),
// DeconstructWithRobotsAchievement("deconstruct-with-robots-achievement"),
// DeliverByRobotsAchievement("deliver-by-robots-achievement"),
// DontBuildEntityAchievement("dont-build-entity-achievement"),
// DontCraftManuallyAchievement("dont-craft-manually-achievement"),
// DontUseEntityInEnergyProductionAchievement("dont-use-entity-in-energy-production-achievement"),
// FinishTheGameAchievement("finish-the-game-achievement"),
// GroupAttackAchievement("group-attack-achievement"),
// KillAchievement("kill-achievement"),
// PlayerDamagedAchievement("player-damaged-achievement"),
// ProduceAchievement("produce-achievement"),
// ProducePerHourAchievement("produce-per-hour-achievement"),
// ResearchAchievement("research-achievement"),
// TrainPathAchievement("train-path-achievement"),
// AmmoCategory("ammo-category"),
// AutoplaceControl("autoplace-control"),
// CustomInput("custom-input"),
// DamageType("damage-type"),
// Decorative("optimized-decorative"),
// Entity("<abstract>"),
// Arrow("arrow"),
// ArtilleryFlare("artillery-flare"),
// ArtilleryProjectile("artillery-projectile"),
// Beam("beam"),
// CharacterCorpse("character-corpse"),
// Cliff("cliff"),
// Corpse("corpse"),
// RailRemnants("rail-remnants"),
// DeconstructibleTileProxy("deconstructible-tile-proxy"),
// EntityGhost("entity-ghost"),
// /** for migration, cannot be used */
// EntityParticle("particle"),
// /** for migration, cannot be used */
// LeafParticle("leaf-particle"),
// EntityWithHealth("<abstract>"),
// EntityWithOwner("<abstract>"),
// Accumulator("accumulator"),
// ArtilleryTurret("artillery-turret"),
// Beacon("beacon"),
// Boiler("boiler"),
// BurnerGenerator("burner-generator"),
// Character("character"),
// Combinator("<abstract>"),
// ArithmeticCombinator("arithmetic-combinator"),
// DeciderCombinator("decider-combinator"),
// ConstantCombinator("constant-combinator"),
// Container("container"),
// LogisticContainer("logistic-container"),
// InfinityContainer("infinity-container"),
// CraftingMachine("<abstract>"),
// AssemblingMachine("assembling-machine"),
// RocketSilo("rocket-silo"),
// Furnace("furnace"),
// ElectricEnergyInterface("electric-energy-interface"),
// ElectricPole("electric-pole"),
// EnemySpawner("unit-spawner"),
// FlyingRobot("<abstract>"),
// CombatRobot("combat-robot"),
// RobotWithLogisticInterface("<abstract>"),
// ConstructionRobot("construction-robot"),
// LogisticRobot("logistic-robot"),
// Gate("gate"),
// Generator("generator"),
// HeatInterface("heat-interface"),
// HeatPipe("heat-pipe"),
// Inserter("inserter"),
// Lab("lab"),
// Lamp("lamp"),
// LandMine("land-mine"),
// LinkedContainer("linked-container"),
// Market("market"),
// MiningDrill("mining-drill"),
// OffshorePump("offshore-pump"),
// Pipe("pipe"),
// InfinityPipe("infinity-pipe"),
// PipeToGround("pipe-to-ground"),
// PlayerPort("player-port"),
// PowerSwitch("power-switch"),
// ProgrammableSpeaker("programmable-speaker"),
// Pump("pump"),
// Radar("radar"),
// Rail("<abstract>"),
// CurvedRail("curved-rail"),
// StraightRail("straight-rail"),
// RailSignalBase("<abstract>"),
// RailChainSignal("rail-chain-signal"),
// RailSignal("rail-signal"),
// Reactor("reactor"),
// Roboport("roboport"),
// SimpleEntityWithOwner("simple-entity-with-owner"),
// SimpleEntityWithForce("simple-entity-with-force"),
// SolarPanel("solar-panel"),
// StorageTank("storage-tank"),
// TrainStop("train-stop"),
// TransportBeltConnectable("<abstract>"),
// LinkedBelt("linked-belt"),
// Loader1x1("loader-1x1"),
// Loader1x2("loader"),
// Splitter("splitter"),
// TransportBelt("transport-belt"),
// UndergroundBelt("underground-belt"),
// Turret("turret"),
// AmmoTurret("ammo-turret"),
// ElectricTurret("electric-turret"),
// FluidTurret("fluid-turret"),
// Unit("unit"),
// Vehicle("<abstract>"),
// Car("car"),
// RollingStock("<abstract>"),
// ArtilleryWagon("artillery-wagon"),
// CargoWagon("cargo-wagon"),
// FluidWagon("fluid-wagon"),
// Locomotive("locomotive"),
// SpiderVehicle("spider-vehicle"),
// Wall("wall"),
// Fish("fish"),
// SimpleEntity("simple-entity"),
// SpiderLeg("spider-leg"),
// Tree("tree"),
// Explosion("explosion"),
// FlameThrowerExplosion("flame-thrower-explosion"),
// FireFlame("fire"),
// FluidStream("stream"),
// FlyingText("flying-text"),
// HighlightBoxEntity("highlight-box"),
// ItemEntity("item-entity"),
// ItemRequestProxy("item-request-proxy"),
// ParticleSource("particle-source"),
// Projectile("projectile"),
// ResourceEntity("resource"),
// RocketSiloRocket("rocket-silo-rocket"),
// RocketSiloRocketShadow("rocket-silo-rocket-shadow"),
// Smoke("<abstract>"),
// /** for migration, cannot be used */
// SimpleSmoke("smoke"),
// SmokeWithTrigger("smoke-with-trigger"),
// SpeechBubble("speech-bubble"),
// Sticker("sticker"),
// TileGhost("tile-ghost"),
// Equipment("<abstract>"),
// ActiveDefenseEquipment("active-defense-equipment"),
// BatteryEquipment("battery-equipment"),
// BeltImmunityEquipment("belt-immunity-equipment"),
// EnergyShieldEquipment("energy-shield-equipment"),
// GeneratorEquipment("generator-equipment"),
// MovementBonusEquipment("movement-bonus-equipment"),
// NightVisionEquipment("night-vision-equipment"),
// RoboportEquipment("roboport-equipment"),
// SolarPanelEquipment("solar-panel-equipment"),
// EquipmentCategory("equipment-category"),
// EquipmentGrid("equipment-grid"),
// Fluid("fluid"),
// FuelCategory("fuel-category"),
// GuiStyle("gui-style"),
// Item("item"),
// AmmoItem("ammo"),
// Capsule("capsule"),
// Gun("gun"),
// ItemWithEntityData("item-with-entity-data"),
// ItemWithLabel("item-with-label"),
// ItemWithInventory("item-with-inventory"),
// BlueprintBook("blueprint-book"),
// ItemWithTags("item-with-tags"),
// SelectionTool("selection-tool"),
// BlueprintItem("blueprint"),
// CopyPasteTool("copy-paste-tool"),
// DeconstructionItem("deconstruction-item"),
// UpgradeItem("upgrade-item"),
// Module("module"),
// RailPlanner("rail-planner"),
// SpidertronRemote("spidertron-remote"),
// Tool("tool"),
// Armor("armor"),
// /** for migration, cannot be used */
// MiningTool("mining-tool"),
// RepairTool("repair-tool"),
// ItemGroup("item-group"),
// ItemSubGroup("item-subgroup"),
// ModuleCategory("module-category"),
// NamedNoiseExpression("noise-expression"),
// NoiseLayer("noise-layer"),
// Particle("optimized-particle"),
// Recipe("recipe"),
// RecipeCategory("recipe-category"),
// ResourceCategory("resource-category"),
// Shortcut("shortcut"),
// Technology("technology"),
// Tile("tile"),
// TipsAndTricksItem("tips-and-tricks-item"),
// TrivialSmoke("trivial-smoke"),
// Tutorial("tutorial"),
// UtilityConstants("utility-constants"),
// UtilitySounds("utility-sounds"),
// UtilitySprites("utility-sprites"),
// VirtualSignal("virtual-signal"),
// ;
//
// fun named(protoName: String): PrototypeId = PrototypeId(this, protoName)
//
// companion object {
// val entries: Set<PrototypeTypeId> = values().toSet()
// }
//
//}
//@Suppress("unused")
//sealed class PrototypeType(
// val id: String
//) {
//
// object AmbientSound : PrototypeType("ambient-sound")
// object Animation : PrototypeType("animation")
// object EditorController : PrototypeType("editor-controller")
// object Font : PrototypeType("font")
// object GodController : PrototypeType("god-controller")
// object MapGenPresets : PrototypeType("map-gen-presets")
// object MapSettings : PrototypeType("map-settings")
// object MouseCursor : PrototypeType("mouse-cursor")
// object Sound : PrototypeType("sound")
// object SpectatorController : PrototypeType("spectator-controller")
// object Sprite : PrototypeType("sprite")
// object TileEffect : PrototypeType("tile-effect")
// object TipsAndTricksItemCategory : PrototypeType("tips-and-tricks-item-category")
// object TriggerTargetType : PrototypeType("trigger-target-type")
// object WindSound : PrototypeType("wind-sound")
//
//
// object Achievement : PrototypeType("achievement")
// object BuildEntityAchievement : PrototypeType("build-entity-achievement")
// object CombatRobotCountAchievement : PrototypeType("combat-robot-count")
// object ConstructWithRobotsAchievement : PrototypeType("construct-with-robots-achievement")
// object DeconstructWithRobotsAchievement : PrototypeType("deconstruct-with-robots-achievement")
// object DeliverByRobotsAchievement : PrototypeType("deliver-by-robots-achievement")
// object DontBuildEntityAchievement : PrototypeType("dont-build-entity-achievement")
// object DontCraftManuallyAchievement : PrototypeType("dont-craft-manually-achievement")
// object DontUseEntityInEnergyProductionAchievement : PrototypeType("dont-use-entity-in-energy-production-achievement")
//
//
// object FinishTheGameAchievement : PrototypeType("finish-the-game-achievement")
// object GroupAttackAchievement : PrototypeType("group-attack-achievement")
// object KillAchievement : PrototypeType("kill-achievement")
// object PlayerDamagedAchievement : PrototypeType("player-damaged-achievement")
// object ProduceAchievement : PrototypeType("produce-achievement")
// object ProducePerHourAchievement : PrototypeType("produce-per-hour-achievement")
// object ResearchAchievement : PrototypeType("research-achievement")
// object TrainPathAchievement : PrototypeType("train-path-achievement")
// object AmmoCategory : PrototypeType("ammo-category")
// object AutoplaceControl : PrototypeType("autoplace-control")
// object CustomInput : PrototypeType("custom-input")
// object DamageType : PrototypeType("damage-type")
// object Decorative : PrototypeType("optimized-decorative")
//
//
// object Entity : PrototypeType("stract>")
// object Arrow : PrototypeType("arrow")
// object ArtilleryFlare : PrototypeType("artillery-flare")
// object ArtilleryProjectile : PrototypeType("artillery-projectile")
// object Beam : PrototypeType("beam")
// object CharacterCorpse : PrototypeType("character-corpse")
// object Cliff : PrototypeType("cliff")
// object Corpse : PrototypeType("corpse")
// object RailRemnants : PrototypeType("rail-remnants")
// object DeconstructibleTileProxy : PrototypeType("deconstructible-tile-proxy")
// object EntityGhost : PrototypeType("entity-ghost")
// /** for migration, cannot be used */
// object EntityParticle : PrototypeType("particle")
// /** for migration, cannot be used */
// object LeafParticle : PrototypeType("leaf-particle")
//
//
// object EntityWithOwner : PrototypeType("stract>")
// object Accumulator : PrototypeType("accumulator")
// object ArtilleryTurret : PrototypeType("artillery-turret")
// object Beacon : PrototypeType("beacon")
// object Boiler : PrototypeType("boiler")
// object BurnerGenerator : PrototypeType("burner-generator")
// object Character : PrototypeType("character")
//
//
// object Combinator : PrototypeType("stract>")
// object ArithmeticCombinator : PrototypeType("arithmetic-combinator")
// object DeciderCombinator : PrototypeType("decider-combinator")
// object ConstantCombinator : PrototypeType("constant-combinator")
// object Container : PrototypeType("container")
// object LogisticContainer : PrototypeType("logistic-container")
// object InfinityContainer : PrototypeType("infinity-container")
//
//
// object CraftingMachine : PrototypeType("stract>")
// object AssemblingMachine : PrototypeType("assembling-machine")
// object RocketSilo : PrototypeType("rocket-silo")
// object Furnace : PrototypeType("furnace")
// object ElectricEnergyInterface : PrototypeType("electric-energy-interface")
// object ElectricPole : PrototypeType("electric-pole")
// object EnemySpawner : PrototypeType("unit-spawner")
//
//
// object FlyingRobot : PrototypeType("stract>")
// object CombatRobot : PrototypeType("combat-robot") , PrototypeAbstract.FlyingRobot
//
//
// object RobotWithLogisticInterface : PrototypeType("stract>")
// object ConstructionRobot : PrototypeType("construction-robot")
// object LogisticRobot : PrototypeType("logistic-robot")
// object Gate : PrototypeType("gate")
// object Generator : PrototypeType("generator")
// object HeatInterface : PrototypeType("heat-interface")
// object HeatPipe : PrototypeType("heat-pipe")
// object Inserter : PrototypeType("inserter")
// object Lab : PrototypeType("lab")
// object Lamp : PrototypeType("lamp")
// object LandMine : PrototypeType("land-mine")
// object LinkedContainer : PrototypeType("linked-container")
// object Market : PrototypeType("market")
// object MiningDrill : PrototypeType("mining-drill")
// object OffshorePump : PrototypeType("offshore-pump")
// object Pipe : PrototypeType("pipe")
// object InfinityPipe : PrototypeType("infinity-pipe")
// object PipeToGround : PrototypeType("pipe-to-ground")
// object PlayerPort : PrototypeType("player-port")
// object PowerSwitch : PrototypeType("power-switch")
// object ProgrammableSpeaker : PrototypeType("programmable-speaker")
// object Pump : PrototypeType("pump")
// object Radar : PrototypeType("radar")
//
// object CurvedRail : PrototypeType("curved-rail"), PrototypeAbstract.Rail
// object StraightRail : PrototypeType("straight-rail"), PrototypeAbstract.Rail
//
// object RailSignalBase : PrototypeType("stract>")
// object RailChainSignal : PrototypeType("rail-chain-signal")
// object RailSignal : PrototypeType("rail-signal")
// object Reactor : PrototypeType("reactor")
// object Roboport : PrototypeType("roboport")
// object SimpleEntityWithOwner : PrototypeType("simple-entity-with-owner")
// object SimpleEntityWithForce : PrototypeType("simple-entity-with-force")
// object SolarPanel : PrototypeType("solar-panel")
// object StorageTank : PrototypeType("storage-tank")
// object TrainStop : PrototypeType("train-stop")
//
//
// object TransportBeltConnectable : PrototypeType("stract>")
// object LinkedBelt : PrototypeType("linked-belt")
// object Loader1x1 : PrototypeType("loader-1x1")
// object Loader1x2 : PrototypeType("loader")
// object Splitter : PrototypeType("splitter")
// object TransportBelt : PrototypeType("transport-belt")
// object UndergroundBelt : PrototypeType("underground-belt")
// object Turret : PrototypeType("turret")
// object AmmoTurret : PrototypeType("ammo-turret")
// object ElectricTurret : PrototypeType("electric-turret")
// object FluidTurret : PrototypeType("fluid-turret")
// object Unit : PrototypeType("unit")
//
//
// object Car : PrototypeType("car>"), PrototypeAbstract.Vehicle
// object SpiderVehicle : PrototypeType("spider-vehicle"), PrototypeAbstract.Vehicle
//
//
// object ArtilleryWagon : PrototypeType("artillery-wagon"), PrototypeAbstract.RollingStock
// object CargoWagon : PrototypeType("cargo-wagon"), PrototypeAbstract.RollingStock
// object FluidWagon : PrototypeType("fluid-wagon"), PrototypeAbstract.RollingStock
// object Locomotive : PrototypeType("locomotive"), PrototypeAbstract.RollingStock
//
// object Wall : PrototypeType("wall")
//
//
// object Fish : PrototypeType("fish"), PrototypeAbstract.EntityWithHealth
// object SimpleEntity : PrototypeType("simple-entity"), PrototypeAbstract.EntityWithHealth
// object SpiderLeg : PrototypeType("spider-leg"), PrototypeAbstract.EntityWithHealth
// object Tree : PrototypeType("tree"), PrototypeAbstract.EntityWithHealth
//
//
// object Explosion : PrototypeType("explosion"),
// object FlameThrowerExplosion : PrototypeType("flame-thrower-explosion"),
// object FireFlame : PrototypeType("fire"),
// object FluidStream : PrototypeType("stream"),
// object FlyingText : PrototypeType("flying-text"),
// object HighlightBoxEntity : PrototypeType("highlight-box"),
// object ItemEntity : PrototypeType("item-entity"),
// object ItemRequestProxy : PrototypeType("item-request-proxy"),
// object ParticleSource : PrototypeType("particle-source"),
// object Projectile : PrototypeType("projectile"),
// object ResourceEntity : PrototypeType("resource"),
// object RocketSiloRocket : PrototypeType("rocket-silo-rocket"),
// object RocketSiloRocketShadow : PrototypeType("rocket-silo-rocket-shadow"),
//
// /** for migration, cannot be used */
// object SimpleSmoke : PrototypeType("smoke"), PrototypeAbstract.Smoke
// object SmokeWithTrigger : PrototypeType("smoke-with-trigger"), PrototypeAbstract.Smoke
// object SpeechBubble : PrototypeType("speech-bubble"), PrototypeAbstract.Smoke
// object Sticker : PrototypeType("sticker"), PrototypeAbstract.Smoke
// object TileGhost : PrototypeType("tile-ghost"), PrototypeAbstract.Smoke
//
// object Equipment : PrototypeType("abstract>")
// object ActiveDefenseEquipment : PrototypeType("active-defense-equipment")
// object BatteryEquipment : PrototypeType("battery-equipment")
// object BeltImmunityEquipment : PrototypeType("belt-immunity-equipment")
// object EnergyShieldEquipment : PrototypeType("energy-shield-equipment")
// object GeneratorEquipment : PrototypeType("generator-equipment")
// object MovementBonusEquipment : PrototypeType("movement-bonus-equipment")
// object NightVisionEquipment : PrototypeType("night-vision-equipment")
// object RoboportEquipment : PrototypeType("roboport-equipment")
// object SolarPanelEquipment : PrototypeType("solar-panel-equipment")
// object EquipmentCategory : PrototypeType("equipment-category")
// object EquipmentGrid : PrototypeType("equipment-grid")
// object Fluid : PrototypeType("fluid")
// object FuelCategory : PrototypeType("fuel-category")
// object GuiStyle : PrototypeType("gui-style")
// object Item : PrototypeType("item")
// object AmmoItem : PrototypeType("ammo")
// object Capsule : PrototypeType("capsule")
// object Gun : PrototypeType("gun")
// object ItemWithEntityData : PrototypeType("item-with-entity-data")
// object ItemWithLabel : PrototypeType("item-with-label")
// object ItemWithInventory : PrototypeType("item-with-inventory")
// object BlueprintBook : PrototypeType("blueprint-book")
// object ItemWithTags : PrototypeType("item-with-tags")
// object SelectionTool : PrototypeType("selection-tool")
// object BlueprintItem : PrototypeType("blueprint")
// object CopyPasteTool : PrototypeType("copy-paste-tool")
// object DeconstructionItem : PrototypeType("deconstruction-item")
// object UpgradeItem : PrototypeType("upgrade-item")
// object Module : PrototypeType("module")
// object RailPlanner : PrototypeType("rail-planner")
// object SpidertronRemote : PrototypeType("spidertron-remote")
// object Tool : PrototypeType("tool")
// object Armor : PrototypeType("armor")
// /** for migration, cannot be used */
// object MiningTool : PrototypeType("mining-tool")
// object RepairTool : PrototypeType("repair-tool")
// object ItemGroup : PrototypeType("item-group")
// object ItemSubGroup : PrototypeType("item-subgroup")
// object ModuleCategory : PrototypeType("module-category")
// object NamedNoiseExpression : PrototypeType("noise-expression")
// object NoiseLayer : PrototypeType("noise-layer")
// object Particle : PrototypeType("optimized-particle")
// object Recipe : PrototypeType("recipe")
// object RecipeCategory : PrototypeType("recipe-category")
// object ResourceCategory : PrototypeType("resource-category")
// object Shortcut : PrototypeType("shortcut")
// object Technology : PrototypeType("technology")
// object Tile : PrototypeType("tile")
// object TipsAndTricksItem : PrototypeType("tips-and-tricks-item")
// object TrivialSmoke : PrototypeType("trivial-smoke")
// object Tutorial : PrototypeType("tutorial")
// object UtilityConstants : PrototypeType("utility-constants")
// object UtilitySounds : PrototypeType("utility-sounds")
// object UtilitySprites : PrototypeType("utility-sprites")
// object VirtualSignal : PrototypeType("virtual-signal")
//
//}
//
//@Suppress("unused")
//sealed interface PrototypeAbstract {
// //@formatter:off
// sealed interface PrototypeBase : PrototypeAbstract
// sealed interface Entity : PrototypeAbstract
// sealed interface EntityWithHealth : Entity
//
// sealed interface EntityWithOwner : EntityWithHealth
//
// sealed interface Combinator : EntityWithOwner
// sealed interface CraftingMachine : EntityWithOwner
// sealed interface FlyingRobot : EntityWithOwner
//
// sealed interface RobotWithLogisticInterface : FlyingRobot
//
// sealed interface Rail : EntityWithOwner
//
// sealed interface RailSignalBase : EntityWithOwner
// sealed interface TransportBeltConnectable : EntityWithOwner
// sealed interface Vehicle : EntityWithOwner
// sealed interface RollingStock : Vehicle
// sealed interface Smoke : Entity
// sealed interface Equipment : PrototypeAbstract
// //@formatter:on
//}
/*
* [[Prototype/AmbientSound]] '''ambient-sound'''
* [[Prototype/Animation]] '''animation'''
* [[Prototype/EditorController]] '''editor-controller'''
* [[Prototype/Font]] '''font'''
* [[Prototype/GodController]] '''god-controller'''
* [[Prototype/MapGenPresets]] '''map-gen-presets'''
* [[Prototype/MapSettings]] '''map-settings'''
* [[Prototype/MouseCursor]] '''mouse-cursor'''
* [[Prototype/Sound]] '''sound'''
* [[Prototype/SpectatorController]] '''spectator-controller'''
* [[Prototype/Sprite]] '''sprite'''
* [[Prototype/TileEffect]] '''tile-effect'''
* [[Prototype/TipsAndTricksItemCategory]] '''tips-and-tricks-item-category'''
* [[Prototype/TriggerTargetType]] '''trigger-target-type'''
* [[Prototype/WindSound]] '''wind-sound'''
* [[PrototypeBase]] <abstract>
</div><div class="prototype-tree">
* [[Prototype/Achievement]] '''achievement'''
** [[Prototype/BuildEntityAchievement]] '''build-entity-achievement'''
** [[Prototype/CombatRobotCountAchievement]] '''combat-robot-count'''
** [[Prototype/ConstructWithRobotsAchievement]] '''construct-with-robots-achievement'''
** [[Prototype/DeconstructWithRobotsAchievement]] '''deconstruct-with-robots-achievement'''
** [[Prototype/DeliverByRobotsAchievement]] '''deliver-by-robots-achievement'''
** [[Prototype/DontBuildEntityAchievement]] '''dont-build-entity-achievement'''
** [[Prototype/DontCraftManuallyAchievement]] '''dont-craft-manually-achievement'''
** [[Prototype/DontUseEntityInEnergyProductionAchievement]] '''dont-use-entity-in-energy-production-achievement'''
** [[Prototype/FinishTheGameAchievement]] '''finish-the-game-achievement'''
** [[Prototype/GroupAttackAchievement]] '''group-attack-achievement'''
** [[Prototype/KillAchievement]] '''kill-achievement'''
** [[Prototype/PlayerDamagedAchievement]] '''player-damaged-achievement'''
** [[Prototype/ProduceAchievement]] '''produce-achievement'''
** [[Prototype/ProducePerHourAchievement]] '''produce-per-hour-achievement'''
** [[Prototype/ResearchAchievement]] '''research-achievement'''
** [[Prototype/TrainPathAchievement]] '''train-path-achievement'''
* [[Prototype/AmmoCategory]] '''ammo-category'''
* [[Prototype/AutoplaceControl]] '''autoplace-control'''
* [[Prototype/CustomInput]] '''custom-input'''
* [[Prototype/DamageType]] '''damage-type'''
* [[Prototype/Decorative]] '''optimized-decorative'''
* [[Prototype/Entity]] <abstract>
** [[Prototype/Arrow]] '''arrow'''
** [[Prototype/ArtilleryFlare]] '''artillery-flare'''
** [[Prototype/ArtilleryProjectile]] '''artillery-projectile'''
** [[Prototype/Beam]] '''beam'''
** [[Prototype/CharacterCorpse]] '''character-corpse'''
** [[Prototype/Cliff]] '''cliff'''
** [[Prototype/Corpse]] '''corpse'''
*** [[Prototype/RailRemnants]] '''rail-remnants'''
** [[Prototype/DeconstructibleTileProxy]] '''deconstructible-tile-proxy'''
** [[Prototype/EntityGhost]] '''entity-ghost'''
** [[Prototype/EntityParticle]] '''particle''' (for migration, cannot be used)
*** [[Prototype/LeafParticle]] '''leaf-particle''' (for migration, cannot be used)
** [[Prototype/EntityWithHealth]] <abstract>
*** [[Prototype/EntityWithOwner]] <abstract>
**** [[Prototype/Accumulator]] '''accumulator'''
**** [[Prototype/ArtilleryTurret]] '''artillery-turret'''
**** [[Prototype/Beacon]] '''beacon'''
**** [[Prototype/Boiler]] '''boiler'''
**** [[Prototype/BurnerGenerator]] '''burner-generator'''
**** [[Prototype/Character]] '''character'''
**** [[Prototype/Combinator]] <abstract>
***** [[Prototype/ArithmeticCombinator]] '''arithmetic-combinator'''
***** [[Prototype/DeciderCombinator]] '''decider-combinator'''
**** [[Prototype/ConstantCombinator]] '''constant-combinator'''
**** [[Prototype/Container]] '''container'''
***** [[Prototype/LogisticContainer]] '''logistic-container'''
****** [[Prototype/InfinityContainer]] '''infinity-container'''
**** [[Prototype/CraftingMachine]] <abstract>
***** [[Prototype/AssemblingMachine]] '''assembling-machine'''
****** [[Prototype/RocketSilo]] '''rocket-silo'''
***** [[Prototype/Furnace]] '''furnace'''
**** [[Prototype/ElectricEnergyInterface]] '''electric-energy-interface'''
**** [[Prototype/ElectricPole]] '''electric-pole'''
**** [[Prototype/EnemySpawner]] '''unit-spawner'''
**** [[Prototype/FlyingRobot]] <abstract>
***** [[Prototype/CombatRobot]] '''combat-robot'''
***** [[Prototype/RobotWithLogisticInterface]] <abstract>
****** [[Prototype/ConstructionRobot]] '''construction-robot'''
****** [[Prototype/LogisticRobot]] '''logistic-robot'''
**** [[Prototype/Gate]] '''gate'''
**** [[Prototype/Generator]] '''generator'''
**** [[Prototype/HeatInterface]] '''heat-interface'''
**** [[Prototype/HeatPipe]] '''heat-pipe'''
**** [[Prototype/Inserter]] '''inserter'''
**** [[Prototype/Lab]] '''lab'''
**** [[Prototype/Lamp]] '''lamp'''
**** [[Prototype/LandMine]] '''land-mine'''
**** [[Prototype/LinkedContainer]] '''linked-container'''
**** [[Prototype/Market]] '''market'''
**** [[Prototype/MiningDrill]] '''mining-drill'''
**** [[Prototype/OffshorePump]] '''offshore-pump'''
**** [[Prototype/Pipe]] '''pipe'''
***** [[Prototype/InfinityPipe]] '''infinity-pipe'''
**** [[Prototype/PipeToGround]] '''pipe-to-ground'''
**** [[Prototype/PlayerPort]] '''player-port'''
**** [[Prototype/PowerSwitch]] '''power-switch'''
**** [[Prototype/ProgrammableSpeaker]] '''programmable-speaker'''
**** [[Prototype/Pump]] '''pump'''
**** [[Prototype/Radar]] '''radar'''
**** [[Prototype/Rail]] <abstract>
***** [[Prototype/CurvedRail]] '''curved-rail'''
***** [[Prototype/StraightRail]] '''straight-rail'''
**** [[Prototype/RailSignalBase]] <abstract>
***** [[Prototype/RailChainSignal]] '''rail-chain-signal'''
***** [[Prototype/RailSignal]] '''rail-signal'''
**** [[Prototype/Reactor]] '''reactor'''
**** [[Prototype/Roboport]] '''roboport'''
**** [[Prototype/SimpleEntityWithOwner]] '''simple-entity-with-owner'''
***** [[Prototype/SimpleEntityWithForce]] '''simple-entity-with-force'''
**** [[Prototype/SolarPanel]] '''solar-panel'''
**** [[Prototype/StorageTank]] '''storage-tank'''
**** [[Prototype/TrainStop]] '''train-stop'''
**** [[Prototype/TransportBeltConnectable]] <abstract>
***** [[Prototype/LinkedBelt]] '''linked-belt'''
***** [[Prototype/Loader1x1]] '''loader-1x1'''
***** [[Prototype/Loader1x2]] '''loader'''
***** [[Prototype/Splitter]] '''splitter'''
***** [[Prototype/TransportBelt]] '''transport-belt'''
***** [[Prototype/UndergroundBelt]] '''underground-belt'''
**** [[Prototype/Turret]] '''turret'''
***** [[Prototype/AmmoTurret]] '''ammo-turret'''
***** [[Prototype/ElectricTurret]] '''electric-turret'''
***** [[Prototype/FluidTurret]] '''fluid-turret'''
**** [[Prototype/Unit]] '''unit'''
**** [[Prototype/Vehicle]] <abstract>
***** [[Prototype/Car]] '''car'''
***** [[Prototype/RollingStock]] <abstract>
****** [[Prototype/ArtilleryWagon]] '''artillery-wagon'''
****** [[Prototype/CargoWagon]] '''cargo-wagon'''
****** [[Prototype/FluidWagon]] '''fluid-wagon'''
****** [[Prototype/Locomotive]] '''locomotive'''
***** [[Prototype/SpiderVehicle]] '''spider-vehicle'''
**** [[Prototype/Wall]] '''wall'''
*** [[Prototype/Fish]] '''fish'''
*** [[Prototype/SimpleEntity]] '''simple-entity'''
*** [[Prototype/SpiderLeg]] '''spider-leg'''
*** [[Prototype/Tree]] '''tree'''
** [[Prototype/Explosion]] '''explosion'''
*** [[Prototype/FlameThrowerExplosion]] '''flame-thrower-explosion'''
** [[Prototype/FireFlame]] '''fire'''
** [[Prototype/FluidStream]] '''stream'''
** [[Prototype/FlyingText]] '''flying-text'''
** [[Prototype/HighlightBoxEntity]] '''highlight-box'''
** [[Prototype/ItemEntity]] '''item-entity'''
** [[Prototype/ItemRequestProxy]] '''item-request-proxy'''
** [[Prototype/ParticleSource]] '''particle-source'''
** [[Prototype/Projectile]] '''projectile'''
** [[Prototype/ResourceEntity]] '''resource'''
** [[Prototype/RocketSiloRocket]] '''rocket-silo-rocket'''
** [[Prototype/RocketSiloRocketShadow]] '''rocket-silo-rocket-shadow'''
** [[Prototype/Smoke]] <abstract>
*** [[Prototype/SimpleSmoke]] '''smoke''' (for migration, cannot be used)
*** [[Prototype/SmokeWithTrigger]] '''smoke-with-trigger'''
** [[Prototype/SpeechBubble]] '''speech-bubble'''
** [[Prototype/Sticker]] '''sticker'''
** [[Prototype/TileGhost]] '''tile-ghost'''
* [[Prototype/Equipment]] <abstract>
** [[Prototype/ActiveDefenseEquipment]] '''active-defense-equipment'''
** [[Prototype/BatteryEquipment]] '''battery-equipment'''
** [[Prototype/BeltImmunityEquipment]] '''belt-immunity-equipment'''
** [[Prototype/EnergyShieldEquipment]] '''energy-shield-equipment'''
** [[Prototype/GeneratorEquipment]] '''generator-equipment'''
** [[Prototype/MovementBonusEquipment]] '''movement-bonus-equipment'''
** [[Prototype/NightVisionEquipment]] '''night-vision-equipment'''
** [[Prototype/RoboportEquipment]] '''roboport-equipment'''
** [[Prototype/SolarPanelEquipment]] '''solar-panel-equipment'''
* [[Prototype/EquipmentCategory]] '''equipment-category'''
* [[Prototype/EquipmentGrid]] '''equipment-grid'''
* [[Prototype/Fluid]] '''fluid'''
* [[Prototype/FuelCategory]] '''fuel-category'''
* [[Prototype/GuiStyle]] '''gui-style'''
* [[Prototype/Item]] '''item'''
** [[Prototype/AmmoItem]] '''ammo'''
** [[Prototype/Capsule]] '''capsule'''
** [[Prototype/Gun]] '''gun'''
** [[Prototype/ItemWithEntityData]] '''item-with-entity-data'''
** [[Prototype/ItemWithLabel]] '''item-with-label'''
*** [[Prototype/ItemWithInventory]] '''item-with-inventory'''
**** [[Prototype/BlueprintBook]] '''blueprint-book'''
*** [[Prototype/ItemWithTags]] '''item-with-tags'''
*** [[Prototype/SelectionTool]] '''selection-tool'''
**** [[Prototype/BlueprintItem]] '''blueprint'''
**** [[Prototype/CopyPasteTool]] '''copy-paste-tool'''
**** [[Prototype/DeconstructionItem]] '''deconstruction-item'''
**** [[Prototype/UpgradeItem]] '''upgrade-item'''
** [[Prototype/Module]] '''module'''
** [[Prototype/RailPlanner]] '''rail-planner'''
** [[Prototype/SpidertronRemote]] '''spidertron-remote'''
** [[Prototype/Tool]] '''tool'''
*** [[Prototype/Armor]] '''armor'''
*** [[Prototype/MiningTool]] '''mining-tool''' (for migration, cannot be used)
*** [[Prototype/RepairTool]] '''repair-tool'''
* [[Prototype/ItemGroup]] '''item-group'''
* [[Prototype/ItemSubGroup]] '''item-subgroup'''
* [[Prototype/ModuleCategory]] '''module-category'''
* [[Prototype/NamedNoiseExpression]] '''noise-expression'''
* [[Prototype/NoiseLayer]] '''noise-layer'''
* [[Prototype/Particle]] '''optimized-particle'''
* [[Prototype/Recipe]] '''recipe'''
* [[Prototype/RecipeCategory]] '''recipe-category'''
* [[Prototype/ResourceCategory]] '''resource-category'''
* [[Prototype/Shortcut]] '''shortcut'''
* [[Prototype/Technology]] '''technology'''
* [[Prototype/Tile]] '''tile'''
* [[Prototype/TipsAndTricksItem]] '''tips-and-tricks-item'''
* [[Prototype/TrivialSmoke]] '''trivial-smoke'''
* [[Prototype/Tutorial]] '''tutorial'''
* [[Prototype/UtilityConstants]] '''utility-constants'''
* [[Prototype/UtilitySounds]] '''utility-sounds'''
* [[Prototype/UtilitySprites]] '''utility-sprites'''
* [[Prototype/VirtualSignal]] '''virtual-signal'''
*/

View file

@ -1,44 +0,0 @@
package dev.adamko.kafkatorio.schema.common
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName("kafkatorio.resource.MinedProduct")
sealed interface MinedProduct {
val resultProtoId: PrototypeId
//Amount of the item or fluid to give. If not specified, amount_min, amount_max and probability must all be specified.
val amount: Double?
//Minimal amount of the item or fluid to give. Has no effect when amount is specified.
//amount_min : Uint or double?,
//Maximum amount of the item or fluid to give. Has no effect when amount is specified.
//amount_max : Uint or double?,
//A value in range [0, 1]. Item or fluid is only given with this probability; otherwise no product is produced.
//probability : Double?,
//How much of this product is a catalyst.
//catalyst_amount : Uint or double?,
@Serializable
@SerialName("kafkatorio.resource.MinedProduct.MinedProductFluid")
data class Fluid(
override val amount: Double? = null,
override val resultProtoId: PrototypeId,
) : MinedProduct
@Serializable
@SerialName("kafkatorio.resource.MinedProduct.MinedProductItem")
data class Item(
override val amount: Double? = null,
override val resultProtoId: PrototypeId,
) : MinedProduct
}

View file

@ -1,13 +0,0 @@
package dev.adamko.kafkatorio.schema.common
import kotlin.jvm.JvmInline
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName("kafkatorio.common.MaskedValue")
@JvmInline
value class MaskedValue(val value: String) {
override fun toString(): String = "Secret(***)"
}

View file

@ -1,27 +0,0 @@
package dev.adamko.kafkatorio.schema.packets
import dev.adamko.kafkatorio.schema.common.ServerMapChunkId
import dev.adamko.kafkatorio.schema.common.ServerMapTilePngFilename
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
sealed class EventServerPacket {
@Serializable
@SerialName("kafkatorio.event-server-packet.Kafkatorio")
data class Kafkatorio(
val packet: KafkatorioPacket
) : EventServerPacket()
@Serializable
@SerialName("kafkatorio.event-server-packet.ChunkTileSaved")
data class ChunkTileSaved(
val chunkId: ServerMapChunkId,
val filename: ServerMapTilePngFilename,
) : EventServerPacket()
}

View file

@ -1,39 +0,0 @@
package dev.adamko.kafkatorio.schema.packets
import dev.adamko.kafkatorio.schema.common.Tick
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName("kafkatorio.packet.KafkatorioPacket")
data class KafkatorioPacket(
val modVersion: String,
val tick: Tick,
val data: KafkatorioPacketData,
)
@Serializable
@SerialName("kafkatorio.packet.KafkatorioPacketData")
sealed class KafkatorioPacketData
@Serializable
@SerialName("kafkatorio.packet.KafkatorioPacketData.Error")
data class KafkatorioPacketDataError(
val message: String? = null,
val rawValue: String? = null,
) : KafkatorioPacketData() {
constructor(
exception: Exception,
rawValue: String? = null
) : this(
message = """
$exception ${exception.message}
${exception.stackTraceToString()}
""".trimIndent(),
rawValue = rawValue,
)
}

View file

@ -1,81 +0,0 @@
package dev.adamko.kafkatorio.schema.packets
import dev.adamko.kafkatorio.library.LuaJsonList
import dev.adamko.kafkatorio.schema.common.FactorioPrototype
import dev.adamko.kafkatorio.schema.common.PlayerIndex
import dev.adamko.kafkatorio.schema.common.SurfaceIndex
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/** No key, no caching. Must be sent instantly. */
@Serializable
@SerialName("kafkatorio.packet.KafkatorioPacket")
sealed class KafkatorioInstantPacketData : KafkatorioPacketData()
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
@Serializable
@SerialName("kafkatorio.packet.instant.ConfigurationUpdate")
data class ConfigurationUpdate(
val factorioData: ConfigurationUpdateGameData,
// @Contextual
val allMods: LuaJsonList<ConfigurationUpdateModData>,
val modStartupSettingsChange: Boolean = false,
val migrationApplied: Boolean = false,
) : KafkatorioInstantPacketData() {
@Serializable
@SerialName("kafkatorio.packet.instant.ConfigurationUpdate.ConfigurationUpdateGameData")
data class ConfigurationUpdateGameData(
val oldVersion: String? = null,
val newVersion: String? = null,
)
@Serializable
@SerialName("kafkatorio.packet.instant.ConfigurationUpdate.ConfigurationUpdateModData")
data class ConfigurationUpdateModData(
val modName: String,
val currentVersion: String? = null,
val previousVersion: String? = null,
)
}
@Serializable
@SerialName("kafkatorio.packet.instant.ConsoleChatUpdate")
data class ConsoleChatUpdate(
val authorPlayerIndex: PlayerIndex?,
val content: String,
) : KafkatorioInstantPacketData()
@Serializable
@SerialName("kafkatorio.packet.instant.ConsoleCommandUpdate")
data class ConsoleCommandUpdate(
val authorPlayerIndex: PlayerIndex?,
val command: String,
val parameters: String,
) : KafkatorioInstantPacketData()
@Serializable
@SerialName("kafkatorio.packet.instant.PrototypesUpdate")
data class PrototypesUpdate(
// @Contextual
val prototypes: LuaJsonList<FactorioPrototype>,
) : KafkatorioInstantPacketData()
@Serializable
@SerialName("kafkatorio.packet.instant.SurfaceUpdate")
data class SurfaceUpdate(
val index: SurfaceIndex,
val daytime: Double,
val name: String,
) : KafkatorioInstantPacketData()
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */

View file

@ -1,221 +0,0 @@
package dev.adamko.kafkatorio.schema.packets
import dev.adamko.kafkatorio.library.LuaJsonList
import dev.adamko.kafkatorio.schema.common.Colour
import dev.adamko.kafkatorio.schema.common.EntityIdentifiers
import dev.adamko.kafkatorio.schema.common.EntityIdentifiersData
import dev.adamko.kafkatorio.schema.common.EventName
import dev.adamko.kafkatorio.schema.common.FactorioEntityData
import dev.adamko.kafkatorio.schema.common.FactorioEntityUpdateDictionary
import dev.adamko.kafkatorio.schema.common.FactorioEntityUpdateDictionary.ResourceAmounts
import dev.adamko.kafkatorio.schema.common.ForceIndex
import dev.adamko.kafkatorio.schema.common.MapChunkPosition
import dev.adamko.kafkatorio.schema.common.MapEntityPosition
import dev.adamko.kafkatorio.schema.common.MapTileDictionary
import dev.adamko.kafkatorio.schema.common.PlayerIndex
import dev.adamko.kafkatorio.schema.common.PrototypeId
import dev.adamko.kafkatorio.schema.common.SurfaceIndex
import dev.adamko.kafkatorio.schema.common.Tick
import dev.adamko.kafkatorio.schema.common.UnitNumber
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/** Has a key, so it can be debounced */
@Serializable
@SerialName("kafkatorio.packet.keyed.KafkatorioKeyedPacketData")
sealed class KafkatorioKeyedPacketData : KafkatorioPacketData() {
abstract val key: KafkatorioKeyedPacketKey
/** A list of all events that have been aggregated into this packet. */
// Maybe change to be Map<EventName, Tick>, where Tick is the most recent event?
// A complete event timeline isn't necessary. The most recent tick of an event is good enough, and requires less space.
abstract val events: Map<EventName, LuaJsonList<Tick>>?
}
@Serializable
@SerialName("kafkatorio.packet.keyed.KafkatorioKeyedPacketKey")
sealed class KafkatorioKeyedPacketKey
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
@Serializable
@SerialName("kafkatorio.packet.keyed.EntityUpdateKey")
data class EntityUpdateKey(
/** While normally optional, here a [unitNumber] is required for caching */
override val unitNumber: UnitNumber,
override val protoId: PrototypeId,
) : EntityIdentifiers, KafkatorioKeyedPacketKey()
@Serializable
@SerialName("kafkatorio.packet.keyed.EntityUpdate")
data class EntityUpdate(
override val key: EntityUpdateKey,
override val events: Map<EventName, LuaJsonList<Tick>>? = null,
val chunkPosition: MapEntityPosition? = null,
val graphicsVariation: UByte? = null,
val health: Float? = null,
val isActive: Boolean = false,
val isRotatable: Boolean = false,
val lastUser: UInt? = null,
val localisedDescription: String? = null,
val localisedName: String? = null,
) : KafkatorioKeyedPacketData()
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
@Serializable
@SerialName("kafkatorio.packet.keyed.MapChunkTileUpdateKey")
data class MapChunkTileUpdateKey(
// val index: PlayerIndex, // maybe add player/robot key, to allow metrics like 'player x mined y tiles'
val chunkPosition: MapChunkPosition,
val surfaceIndex: SurfaceIndex,
) : KafkatorioKeyedPacketKey()
@Serializable
@SerialName("kafkatorio.packet.keyed.MapChunkTileUpdate")
data class MapChunkTileUpdate(
override val key: MapChunkTileUpdateKey,
override val events: Map<EventName, LuaJsonList<Tick>>? = null,
val player: PlayerIndex? = null,
val robot: EntityIdentifiersData? = null,
val force: ForceIndex? = null,
/** updated tiles - might be partial and not all tiles in the chunk */
val tileDictionary: MapTileDictionary? = null,
val isDeleted: Boolean = false,
) : KafkatorioKeyedPacketData()
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
@Serializable
@SerialName("kafkatorio.packet.keyed.PlayerUpdateKey")
data class PlayerUpdateKey(
val index: PlayerIndex,
) : KafkatorioKeyedPacketKey()
@Serializable
@SerialName("kafkatorio.packet.keyed.PlayerUpdate")
data class PlayerUpdate(
override val key: PlayerUpdateKey,
override val events: Map<EventName, LuaJsonList<Tick>>? = null,
val characterUnitNumber: UnitNumber? = null,
val chatColour: Colour? = null,
val colour: Colour? = null,
val name: String? = null,
val afkTime: Tick? = null,
val ticksToRespawn: Tick? = null,
val forceIndex: ForceIndex? = null,
val isAdmin: Boolean = false,
val isConnected: Boolean = false,
val isShowOnMap: Boolean = false,
val isSpectator: Boolean = false,
val lastOnline: Tick? = null,
val onlineTime: Tick? = null,
val position: MapEntityPosition? = null,
val surfaceIndex: SurfaceIndex? = null,
val tag: String? = null,
val diedCause: EntityIdentifiersData? = null,
val bannedReason: String? = null,
val kickedReason: String? = null,
val disconnectReason: String? = null,
/** `true` when a player is removed (deleted) from the game */
val isRemoved: Boolean = false,
) : KafkatorioKeyedPacketData()
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
@Serializable
@SerialName("kafkatorio.packet.keyed.MapChunkEntityUpdateKey")
data class MapChunkEntityUpdateKey(
val protoId: PrototypeId,
val surfaceIndex: SurfaceIndex,
val chunkPosition: MapChunkPosition,
) : KafkatorioKeyedPacketKey()
@Serializable
@SerialName("kafkatorio.packet.keyed.MapChunkEntityUpdate")
data class MapChunkEntityUpdate(
override val key: MapChunkEntityUpdateKey,
override val events: Map<EventName, LuaJsonList<Tick>>? = null,
val entitiesXY: FactorioEntityUpdateDictionary.Entity,
) : KafkatorioKeyedPacketData() {
fun entities(): List<FactorioEntityData.Standard> =
entitiesXY.map { (position, entity) ->
FactorioEntityData.Standard(
protoId = key.protoId,
position = position,
status = entity.status,
unitNumber = entity.unitNumber,
graphicsVariation = entity.graphicsVariation,
health = entity.health,
isActive = entity.isActive,
isRotatable = entity.isRotatable,
lastUser = entity.lastUser
)
}
}
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
@Serializable
@SerialName("kafkatorio.packet.keyed.MapChunkResourceUpdateKey")
data class MapChunkResourceUpdateKey(
val protoId: PrototypeId,
val surfaceIndex: SurfaceIndex,
val chunkPosition: MapChunkPosition,
) : KafkatorioKeyedPacketKey()
@Serializable
@SerialName("kafkatorio.packet.keyed.MapChunkResourceUpdate")
data class MapChunkResourceUpdate(
override val key: MapChunkResourceUpdateKey,
override val events: Map<EventName, LuaJsonList<Tick>>? = null,
// Optimise JSON size by storing amounts separately.
val amounts: ResourceAmounts = ResourceAmounts(),
// Initial amount is only available for infinite resources, and infinite resources (oil) are more
// uncommon, so there are unlikely to be many per chunk
val initialAmounts: ResourceAmounts = ResourceAmounts(),
) : KafkatorioKeyedPacketData() {
fun resources(): List<FactorioEntityData.Resource> =
amounts.map { (position, amount) ->
FactorioEntityData.Resource(
protoId = key.protoId,
position = position,
amount = amount,
initialAmount = initialAmounts[position],
)
}
}
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */

View file

@ -1,77 +0,0 @@
package dev.adamko.kafkatorio.schema.common
import dev.adamko.kafkatorio.library.jsonMapperKafkatorio
import io.kotest.assertions.withClue
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.matchers.floats.shouldBeWithinPercentageOf
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.property.checkAll
import kotlinx.serialization.decodeFromString
class ColourHexTest : BehaviorSpec({
Given("colour json") {
//Language=JSON
val colourJson = """
[0.1, 0.4, 0.7, 0.6]
""".trimIndent()
val colour: Colour = jsonMapperKafkatorio.decodeFromString(colourJson)
Then("expect colour is decoded") {
colour shouldBe Colour(
0.1f,
0.4f,
0.7f,
0.6f,
)
}
Then("expect Colour can be converted to ColourHex and back") {
val colourHex = colour.toHex()
colourHex shouldBe ColourHex(
25u,
102u,
178u,
153u,
)
colourHex.toPercentile() should { back ->
withClue(back) {
val tolerance = 2.6 // 2.6%, because 255/100 = 2.55
withClue("red") { back.red.shouldBeWithinPercentageOf(0.1f, tolerance) }
withClue("green") { back.green.shouldBeWithinPercentageOf(0.4f, tolerance) }
withClue("blue") { back.blue.shouldBeWithinPercentageOf(0.7f, tolerance) }
withClue("alpha") { back.alpha.shouldBeWithinPercentageOf(0.6f, tolerance) }
}
}
}
}
Given("any colour json") {
Then("expect can always convert") {
checkAll<UByte, UByte, UByte, UByte> { r, g, b, a ->
//Language=JSON
val colourJson = """
[
${r.toFloat() / UByte.MAX_VALUE.toFloat()},
${g.toFloat() / UByte.MAX_VALUE.toFloat()},
${b.toFloat() / UByte.MAX_VALUE.toFloat()},
${a.toFloat() / UByte.MAX_VALUE.toFloat()}
]
""".trimIndent()
val colour: Colour = jsonMapperKafkatorio.decodeFromString(colourJson)
val colourHex = colour.toHex()
colourHex shouldBe ColourHex(r, g, b, a)
}
}
}
})

View file

@ -1,188 +0,0 @@
package dev.adamko.kafkatorio.schema.common
import dev.adamko.kafkatorio.library.kxsBinary
import io.kotest.assertions.asClue
import io.kotest.assertions.withClue
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldContainExactly
import io.kotest.matchers.ints.shouldBeExactly
import io.kotest.matchers.maps.shouldContainExactly
import io.kotest.matchers.shouldBe
import kotlinx.serialization.decodeFromByteArray
import kotlinx.serialization.encodeToByteArray
class MapChunkPositionBoundsTest : FunSpec({
context("create bounds") {
context("MapChunkPosition(0, 0)") {
context("chunk size 32") {
val chunkPos = MapChunkPosition(0, 0, ChunkSize.CHUNK_032)
test("leftTop should be 0,0") {
chunkPos.bounds.leftTop.asClue {
it.x shouldBeExactly 0
it.y shouldBeExactly 0
}
}
test("rightBottom should be 31,31") {
chunkPos.bounds.rightBottom.asClue {
it.x shouldBeExactly 31
it.y shouldBeExactly 31
}
}
}
}
context("chunk size 256") {
val chunkPos = MapChunkPosition(0, 0, ChunkSize.CHUNK_256)
test("leftTop should be 0,0") {
chunkPos.bounds.leftTop.asClue {
it.x shouldBeExactly 0
it.y shouldBeExactly 0
}
}
test("rightBottom should be 255,255") {
chunkPos.bounds.rightBottom.asClue {
it.x shouldBeExactly 255
it.y shouldBeExactly 255
}
}
}
}
context("MapChunkPosition(-10, -10)") {
context("chunk size 32") {
val chunkPos = MapChunkPosition(-10, -10, ChunkSize.CHUNK_032)
test("leftTop should be -320,-320") {
chunkPos.bounds.leftTop.asClue {
it.x shouldBeExactly -320
it.y shouldBeExactly -320
}
}
test("rightBottom should be -289,-289") {
chunkPos.bounds.rightBottom.asClue {
it.x shouldBeExactly -289
it.y shouldBeExactly -289
}
}
}
context("chunk size 256") {
val chunkPos = MapChunkPosition(-10, -10, ChunkSize.CHUNK_256)
test("leftTop should be -2560") {
chunkPos.bounds.leftTop.asClue {
it.x shouldBeExactly -2560
it.y shouldBeExactly -2560
}
}
test("rightBottom should be (-2560 + 255)") {
chunkPos.bounds.rightBottom.asClue {
it.x shouldBeExactly (-2560 + 255)
it.y shouldBeExactly (-2560 + 255)
}
}
}
}
context("encode MapTileDictionary") {
val actual = MapTileDictionary(
tilesXY = mapOf(
"-192" to mapOf("-65" to MapTileDictionary.PrototypeKey(2)),
"161" to mapOf(
"-96" to MapTileDictionary.PrototypeKey(1),
"-95" to MapTileDictionary.PrototypeKey(2),
"94" to MapTileDictionary.PrototypeKey(2),
"93" to MapTileDictionary.PrototypeKey(32),
),
// unknown prototype
"44" to mapOf("1" to MapTileDictionary.PrototypeKey(44)),
),
protos = mapOf(
PrototypeId("tile", "water") to MapTileDictionary.PrototypeKey(1),
PrototypeId("tile", "grass-4") to MapTileDictionary.PrototypeKey(2),
PrototypeId("tile", "grass-3") to MapTileDictionary.PrototypeKey(32),
PrototypeId("tile", "not-used") to MapTileDictionary.PrototypeKey(99),
)
)
test("binary round trip") {
val encoded: ByteArray = kxsBinary.encodeToByteArray(actual)
val decoded: MapTileDictionary = kxsBinary.decodeFromByteArray(encoded)
decoded.tilesXY shouldContainExactly actual.tilesXY
decoded.protos shouldContainExactly actual.protos
decoded.toMapTileList() shouldContainExactly actual.toMapTileList()
}
}
context("verify map chunk 'contains'") {
context("MapChunkPosition(1, 1)") {
val chunkPos = MapChunkPosition(1, 1, ChunkSize.CHUNK_032) // from 32,32 to 63,63
test("tile outside of chunk") {
val outerTilePos = MapTilePosition(1, 1)
withClue("$outerTilePos in ${chunkPos.bounds}") {
(outerTilePos in chunkPos) shouldBe false
}
}
test("tile inside of chunk") {
val innerTilePos = MapTilePosition(34, 33)
withClue("$innerTilePos in ${chunkPos.bounds}") {
(innerTilePos in chunkPos) shouldBe true
}
}
test("entity outside of chunk") {
val outerEntityPos = MapEntityPosition(1.0, 1.0)
withClue("$outerEntityPos in ${chunkPos.bounds}") {
(outerEntityPos !in chunkPos) shouldBe true
(outerEntityPos in chunkPos) shouldBe false
}
}
test("entity inside of chunk") {
val innerEntityPos = MapEntityPosition(34.0, 33.0)
withClue("$innerEntityPos in ${chunkPos.bounds}") {
(innerEntityPos !in chunkPos) shouldBe false
(innerEntityPos in chunkPos) shouldBe true
}
}
}
context(" MapChunkPosition(9, -5)") {
val chunkPos2 = MapChunkPosition(9, -5, ChunkSize.CHUNK_032)
test("tile inside of chunk") {
val innerTilePos = MapTilePosition(288, -160)
withClue("$innerTilePos in ${chunkPos2.bounds}") {
(innerTilePos in chunkPos2) shouldBe true
}
}
}
}
})

View file

@ -1,81 +0,0 @@
package dev.adamko.kafkatorio.schema.common
import io.kotest.core.spec.style.FunSpec
import io.kotest.datatest.withData
import io.kotest.matchers.shouldBe
import io.kotest.property.Arb
import io.kotest.property.arbitrary.arbitrary
import io.kotest.property.arbitrary.int
import io.kotest.property.checkAll
class MapChunkPositionTest : FunSpec({
context("check MapChunkPosition.contains()") {
context("MapChunkPosition(0, 0)") {
val chunkPos = MapChunkPosition(0, 0, ChunkSize.CHUNK_032)
test("should contain tiles from (0,0) to (31,31)") {
checkAll(mapTilePositionArb(0..31)) { tilePos ->
(tilePos in chunkPos) shouldBe true
}
}
test("should not contain tiles below (0,0)") {
checkAll(
mapTilePositionArb(-1000..-1)
) { tilePos ->
(tilePos in chunkPos) shouldBe false
}
}
test("should not contain tiles above (31,31)") {
checkAll(
mapTilePositionArb(32..100)
) { tilePos ->
(tilePos in chunkPos) shouldBe false
}
}
}
context("MapChunkPosition(-10, -10)") {
val chunkPos = MapChunkPosition(-10, -10, ChunkSize.CHUNK_032)
test("should contain tiles from (-320,-320) to (-289,-289)") {
checkAll(mapTilePositionArb(-320..-289)) { tilePos ->
(tilePos in chunkPos) shouldBe true
}
}
test("should not contain tiles below (-320,-320)") {
checkAll(
mapTilePositionArb(-400..-321)
) { tilePos ->
(tilePos in chunkPos) shouldBe false
}
}
test("should not contain tiles above (-289,-289)") {
checkAll(
mapTilePositionArb(-288..100)
) { tilePos ->
(tilePos in chunkPos) shouldBe false
}
}
}
}
}) {
companion object {
fun mapTilePositionArb(
range: IntRange = -1000..1000
) = arbitrary {
MapTilePosition(
Arb.int(range).bind(),
Arb.int(range).bind(),
)
}
}
}

Some files were not shown because too many files have changed in this diff Show more