diff --git a/.gitignore b/.gitignore index c14c82f..897f9bd 100644 --- a/.gitignore +++ b/.gitignore @@ -26,5 +26,4 @@ logs/ todo.md # Локальные заметки -NOTICE.md todo.md diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +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: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + 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 +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fb78043 --- /dev/null +++ b/README.md @@ -0,0 +1,88 @@ +# Satura — авто-билдер для Minecraft (Fabric) + +Клиентский мод: выделяешь область — мод сам ходит/летает и строит заданную форму. +GUI-меню, команды `.pos1/.pos2/.sel/.build`, навигация через Baritone (Aethereal), +инкрементальный подсчёт прогресса, ремонтные проходы по дырам. + +| Что | Версия | +|---|---| +| Minecraft | 1.21.11 | +| Fabric Loader | 0.20.1 | +| Fabric API | 0.141.6+1.21.11 | +| Yarn mappings | 1.21.11+build.6 | +| Loom | 1.18.4 (нужна JVM 25 для запуска Gradle) | +| Java | 21 (target), 25 (JVM сборки) | + +## Сборка и запуск + +```bash +./gradlew build # jar в build/libs/satura-<версия>.jar +./gradlew check # тесты + checkstyle + pmd (гейт проекта) +./gradlew runClient # dev-запуск игры с модом +``` + +Gradle запускается на JVM 25: если дефолтная JVM другой версии, укажи её в +`gradle.properties` (`org.gradle.java.home`) или ключом `-Dorg.gradle.java.home=...`. +Для dev-запуска с Baritone положи `aethereal-1.21.11.jar` в `libs/`. + +## Использование + +### Клавиши (настраиваются в ванильных «Управлении», категория Satura) + +| Клавиша | Действие | +|---|---| +| Right Shift | открыть/закрыть меню билдера | +| P | макрос: пауза / продолжить текущий билд | + +### Команды (префикс `.`) + +| Команда | Действие | +|---|---| +| `.pos1` / `.pos2` | задать углы области по позиции ног | +| `.sel clear` | сбросить выделение | +| `.build start` / `pause` / `resume` / `stop` / `status` | управление стройкой | +| `.build block ` | блок (`stone`, `minecraft:glass` или `hand` — блок из руки) | +| `.build shape box\|checker\|walls` | форма застройки области | +| `.build layers 1..3` | слоёв за один проход колонны | +| `.build strategy ` | стратегия постановки (`band_stack`, `column_drop`) | +| `.build set <ключ> <знач>` | параметр стратегии (`delayMs`, `reach`, `hover`, `flySpeed`, `bandLayers`) | + +### GUI (Right Shift) + +Pos1/Pos2 — зафиксировать текущую позицию ног; Старт/Пауза/Продолжить/Стоп; +форма; слои; задержка установки; ID блока (Enter — применить). Внизу — живой +статус: этап, прогресс, блоков/с, дыры. Во время стройки тот же статус раз в +секунду дублируется над хотбаром. + +### Стратегии постановки + +- **BandStack** (дефолт) — за один визит колонны ставится 1–3 слоя снизу вверх. +- **ColumnDrop** — по одному слою за визит. +Обе летают над слоем и ставят в колонну под собой. Для серверов с жёстким +анти-читом используй меньший `delayMs` и без полёта (наземные стратегии — план +Фазы 9, S5/S6). + +Настройки хранятся в `config/satura/default.json` и применяются при старте. + +## Архитектура + +Слои зависимостей направлены строго вниз, циклы запрещены: + +``` +mixin → feature → interaction → core → util +gui → feature (только через фасад BuilderFeature) +``` + +- `core` — событие/команды/конфиг, ничего не знает о фичах; +- `feature/builder` — селекция, план (формы), скан (ColumnCache), движок, Baritone-мост; +- `interaction` — «руки»: постановка блоков (стратегии), инвентарь, движение; +- `gui` — экран и виджеты, общается с фичей только через фасад; +- `render` — GUI-рендер (rect/blur/outline/MSDF-текст) и рамка выделения в мире. + +Правила кода: максимум 250 строк на `.java`-файл, максимум 4 файла на пакет, +магические числа — в константы, гейт сборки — `./gradlew check` (Checkstyle + +PMD). Подробный план развития — `todo.md`. + +## Лицензия + +GPL-3.0-only, см. `LICENSE`. diff --git a/build.gradle.kts b/build.gradle.kts index 2a8ac87..3783f40 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -44,6 +44,7 @@ java { tasks.withType().configureEach { options.encoding = "UTF-8" options.release.set(21) + options.compilerArgs.addAll(listOf("-Xlint:all,-processing,-serial,-classfile", "-Werror")) } tasks.processResources { @@ -53,7 +54,7 @@ tasks.processResources { } } -// Правило проекта: файл максимум 200 строк — FileLength (severity=error валит check) +// Правило проекта: файл максимум 250 строк — FileLength (severity=error валит check) checkstyle { toolVersion = "10.21.2" configFile = rootProject.file("config/checkstyle/checkstyle.xml") @@ -74,3 +75,48 @@ tasks.test { tasks.named("pmdTest") { enabled = false } + +// Архитектура (правила 6 и 11): максимум 4 файла в папке, слои зависят только вниз +val maxFilesPerDir = 4 +val layerRules = mapOf( + "util" to setOf(), + "core" to setOf("util"), + "interaction" to setOf("core", "util"), + "render" to setOf("util"), + "feature" to setOf("core", "interaction", "render", "util"), + "gui" to setOf("core", "feature", "render", "util"), +) + +tasks.register("checkArchitecture") { + group = "verification" + description = "Лимит файлов в папке и направление зависимостей между слоями" + val srcRoot = layout.projectDirectory.dir("src/main/java/dev/loki/satura").asFile + val baselineFile = layout.projectDirectory.file("config/architecture/baseline.txt").asFile + doLast { + val errors = mutableListOf() + srcRoot.walkTopDown().filter { it.isDirectory }.forEach { dir -> + val count = dir.listFiles { f -> f.extension == "java" }?.size ?: 0 + if (count > maxFilesPerDir) { + errors += "${dir.relativeTo(srcRoot)}: $count файлов (максимум $maxFilesPerDir)" + } + } + val baseline = baselineFile.readLines().filter { it.isNotBlank() && !it.startsWith("#") }.toSet() + val importRe = Regex("^import (?:static )?dev\\.loki\\.satura\\.([a-z]+)") + srcRoot.walkTopDown().filter { it.extension == "java" }.forEach { file -> + val rel = file.relativeTo(srcRoot).invariantSeparatorsPath + val layer = rel.substringBefore('/') + val allowed = layerRules[layer] ?: return@forEach + file.readLines().mapNotNull { importRe.find(it)?.groupValues?.get(1) }.distinct() + .filter { it != layer && it !in allowed } + .filter { "$rel -> $it" !in baseline } + .forEach { errors += "$rel: слой '$layer' не может импортировать '$it'" } + } + if (errors.isNotEmpty()) { + throw GradleException("Нарушения архитектуры:\n" + errors.joinToString("\n") { " $it" }) + } + } +} + +tasks.named("check") { + dependsOn("checkArchitecture") +} diff --git a/config/architecture/baseline.txt b/config/architecture/baseline.txt new file mode 100644 index 0000000..0a97360 --- /dev/null +++ b/config/architecture/baseline.txt @@ -0,0 +1,7 @@ +# Известные нарушения слоёв (долг). Новые нарушения валят check; этот список только уменьшается. +# Формат: путь-к-файлу -> пакет, который импортируется +interaction/place/PlaceStrategy.java -> feature +interaction/place/option/CommonOptions.java -> feature +interaction/place/strategy/BandStack.java -> feature +interaction/place/strategy/ColumnDrop.java -> feature +interaction/place/strategy/ColumnPlacing.java -> feature diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index b39458a..c35f36f 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -3,41 +3,194 @@ "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" "https://checkstyle.org/dtds/configuration_1_3.dtd"> - + - + + - - + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml new file mode 100644 index 0000000..9219648 --- /dev/null +++ b/config/checkstyle/suppressions.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/config/pmd/pmd.xml b/config/pmd/pmd.xml index 4577da7..d3df49f 100644 --- a/config/pmd/pmd.xml +++ b/config/pmd/pmd.xml @@ -5,21 +5,69 @@ xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd"> - Satura base ruleset: errorprone + bestpractices + design (без шума) + Satura ruleset: errorprone, bestpractices, design, codestyle, performance, multithreading, security - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/dev/loki/satura/SaturaClient.java b/src/main/java/dev/loki/satura/SaturaClient.java index dfec8c1..8c92212 100644 --- a/src/main/java/dev/loki/satura/SaturaClient.java +++ b/src/main/java/dev/loki/satura/SaturaClient.java @@ -6,10 +6,12 @@ import dev.loki.satura.core.command.builtin.HelpCommand; import dev.loki.satura.core.config.ConfigStore; import dev.loki.satura.core.event.EventBus; import dev.loki.satura.feature.builder.BuilderFeature; +import dev.loki.satura.gui.BuilderUi; import dev.loki.satura.render.RenderDebug; import dev.loki.satura.render.Renderer; import dev.loki.satura.render.world.Marks; import dev.loki.satura.render.world.SelectionRenderer; +import dev.loki.satura.util.ActionBarOut; import dev.loki.satura.util.ChatOut; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; @@ -18,7 +20,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Точка входа клиента. Только сборка компонентов — вся логика в feature-пакетах. + * Client entry point. Only wires components together; all logic lives in the feature packages. */ public final class SaturaClient implements ClientModInitializer { @@ -39,6 +41,7 @@ public final class SaturaClient implements ClientModInitializer { RenderDebug.installIfEnabled(Renderer.shared()); new SelectionRenderer(() -> new Marks(builder.selection().pos1(), builder.selection().pos2()), SELECTION_SEE_THROUGH).register(); + new BuilderUi(builder, new ActionBarOut()).register(); LOG.info("[satura] client init"); } } diff --git a/src/main/java/dev/loki/satura/core/CoreServices.java b/src/main/java/dev/loki/satura/core/CoreServices.java index 5cd2256..571c10b 100644 --- a/src/main/java/dev/loki/satura/core/CoreServices.java +++ b/src/main/java/dev/loki/satura/core/CoreServices.java @@ -4,7 +4,7 @@ import dev.loki.satura.core.command.CommandRegistry; import dev.loki.satura.core.config.ConfigStore; import dev.loki.satura.core.event.EventBus; -/** Собранное ядро; доступ для миксинов (они не могут получить зависимости через конструктор). */ +/** Assembled core; exposed to mixins (they cannot receive dependencies through a constructor). */ public record CoreServices(EventBus events, CommandRegistry commands, ConfigStore config) { private static CoreServices current; @@ -13,7 +13,7 @@ public record CoreServices(EventBus events, CommandRegistry commands, ConfigStor current = services; } - /** Ядро или null, если мод ещё не инициализирован. */ + /** The core, or null if the mod is not initialized yet. */ public static CoreServices get() { return current; } diff --git a/src/main/java/dev/loki/satura/core/command/Command.java b/src/main/java/dev/loki/satura/core/command/Command.java index 2ab0ea7..b18fea6 100644 --- a/src/main/java/dev/loki/satura/core/command/Command.java +++ b/src/main/java/dev/loki/satura/core/command/Command.java @@ -3,7 +3,7 @@ package dev.loki.satura.core.command; import java.util.List; import java.util.function.Consumer; -/** Чат-команда с префиксом {@code .}. */ +/** Chat command with the {@code .} prefix. */ public interface Command { String name(); @@ -11,17 +11,17 @@ public interface Command { String description(); /** - * Выполнить команду. + * Execute the command. * - * @param args токены после имени - * @param reply куда писать ответ пользователю + * @param args tokens after the name + * @param reply where to write the reply for the user */ void execute(List args, Consumer reply); /** - * Кандидаты для последнего (редактируемого) токена. + * Candidates for the last (currently edited) token. * - * @param args токены после имени; последний — недописанный (может быть пустым) + * @param args tokens after the name; the last one is unfinished (may be empty) */ default List suggest(List args) { return List.of(); diff --git a/src/main/java/dev/loki/satura/core/command/CommandParser.java b/src/main/java/dev/loki/satura/core/command/CommandParser.java index 834286c..01780b6 100644 --- a/src/main/java/dev/loki/satura/core/command/CommandParser.java +++ b/src/main/java/dev/loki/satura/core/command/CommandParser.java @@ -3,7 +3,7 @@ package dev.loki.satura.core.command; import java.util.ArrayList; import java.util.List; -/** Разбиение строки на токены по пробелам; кавычки группируют; хвостовой пробел даёт пустой токен. */ +/** Splits a line into tokens by spaces; quotes group; a trailing space yields an empty token. */ final class CommandParser { private static final char QUOTE = '"'; diff --git a/src/main/java/dev/loki/satura/core/command/CommandRegistry.java b/src/main/java/dev/loki/satura/core/command/CommandRegistry.java index bbf7254..17e2e37 100644 --- a/src/main/java/dev/loki/satura/core/command/CommandRegistry.java +++ b/src/main/java/dev/loki/satura/core/command/CommandRegistry.java @@ -8,7 +8,7 @@ import java.util.Map; import java.util.TreeMap; import java.util.function.Consumer; -/** Реестр команд: регистрация, выполнение строки и подсказки. */ +/** Command registry: registration, line execution and suggestions. */ @SuppressWarnings({"PMD.LooseCoupling", "PMD.AvoidCatchingGenericException"}) public final class CommandRegistry { @@ -29,7 +29,7 @@ public final class CommandRegistry { return commands.values(); } - /** Выполняет строку без префикса, например {@code "help"}. */ + /** Executes a line without the prefix, e.g. {@code "help"}. */ public void execute(String line) { List tokens = CommandParser.tokenize(line.strip()); Command command = commands.get(tokens.get(0).toLowerCase(Locale.ROOT)); @@ -44,7 +44,7 @@ public final class CommandRegistry { } } - /** Подсказки для текста до курсора (с префиксом). */ + /** Suggestions for the text before the cursor (with the prefix). */ public List suggest(String toCursor) { String body = toCursor.startsWith(SuggestHelper.PREFIX) ? toCursor.substring(SuggestHelper.PREFIX.length()) : toCursor; diff --git a/src/main/java/dev/loki/satura/core/command/SuggestHelper.java b/src/main/java/dev/loki/satura/core/command/SuggestHelper.java index 7d48b4a..48d5fc5 100644 --- a/src/main/java/dev/loki/satura/core/command/SuggestHelper.java +++ b/src/main/java/dev/loki/satura/core/command/SuggestHelper.java @@ -3,7 +3,7 @@ package dev.loki.satura.core.command; import java.util.List; import java.util.Locale; -/** Фильтрация подсказок по префиксу и позиция начала редактируемого токена. */ +/** Suggestion filtering by prefix and the start position of the edited token. */ public final class SuggestHelper { public static final String PREFIX = "."; diff --git a/src/main/java/dev/loki/satura/core/command/builtin/HelpCommand.java b/src/main/java/dev/loki/satura/core/command/builtin/HelpCommand.java index 94f697e..228575e 100644 --- a/src/main/java/dev/loki/satura/core/command/builtin/HelpCommand.java +++ b/src/main/java/dev/loki/satura/core/command/builtin/HelpCommand.java @@ -6,7 +6,7 @@ import dev.loki.satura.core.command.SuggestHelper; import java.util.List; import java.util.function.Consumer; -/** {@code .help} — список зарегистрированных команд. */ +/** {@code .help} — list of registered commands. */ public final class HelpCommand implements Command { private final CommandRegistry registry; diff --git a/src/main/java/dev/loki/satura/core/config/ConfigStore.java b/src/main/java/dev/loki/satura/core/config/ConfigStore.java index 681fa31..9c2f6be 100644 --- a/src/main/java/dev/loki/satura/core/config/ConfigStore.java +++ b/src/main/java/dev/loki/satura/core/config/ConfigStore.java @@ -11,10 +11,14 @@ import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.stream.Stream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -/** Хранение профилей как json-файлов в каталоге (config/satura/). */ +/** Stores profiles as json files in a directory (config/satura/). */ +@SuppressWarnings("PMD.GuardLogStatement") public final class ConfigStore { + private static final Logger LOG = LoggerFactory.getLogger(ConfigStore.class); private static final String EXTENSION = ".json"; private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); @@ -41,6 +45,26 @@ public final class ConfigStore { } } + /** Loads the profile or an empty default; read errors never propagate to the caller. */ + @SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.CloseResource"}) + public Profile loadOrEmpty(final String name) { + try { + return load(name).orElse(Profile.empty(name)); + } catch (IOException | RuntimeException e) { + LOG.warn("[satura] profile {} not loaded: {}", name, e.toString()); + return Profile.empty(name); + } + } + + /** Saves the profile, swallowing I/O errors (for GUI/click handlers that cannot throw). */ + public void saveQuietly(final Profile profile) { + try { + save(profile); + } catch (IOException e) { + LOG.warn("[satura] profile {} not saved: {}", profile.name(), e.toString()); + } + } + public List list() throws IOException { if (!Files.isDirectory(dir)) { return List.of(); diff --git a/src/main/java/dev/loki/satura/core/config/Profile.java b/src/main/java/dev/loki/satura/core/config/Profile.java index bf7b84f..fe091d9 100644 --- a/src/main/java/dev/loki/satura/core/config/Profile.java +++ b/src/main/java/dev/loki/satura/core/config/Profile.java @@ -4,10 +4,10 @@ import java.util.HashMap; import java.util.Map; /** - * Иммутабельный профиль настроек. + * Immutable settings profile. * - * @param name имя профиля (имя файла) - * @param settings ключ → значение + * @param name profile name (file name) + * @param settings key → value */ @SuppressWarnings("PMD.LooseCoupling") public record Profile(String name, Map settings) { diff --git a/src/main/java/dev/loki/satura/core/event/Cancellable.java b/src/main/java/dev/loki/satura/core/event/Cancellable.java index bef2783..576bb34 100644 --- a/src/main/java/dev/loki/satura/core/event/Cancellable.java +++ b/src/main/java/dev/loki/satura/core/event/Cancellable.java @@ -1,6 +1,6 @@ package dev.loki.satura.core.event; -/** Событие, обработку которого можно отменить; после отмены цепочка слушателей прерывается. */ +/** An event whose handling can be cancelled; once cancelled, the listener chain is interrupted. */ public interface Cancellable extends Event { boolean isCancelled(); diff --git a/src/main/java/dev/loki/satura/core/event/Event.java b/src/main/java/dev/loki/satura/core/event/Event.java index 486e9cb..10f5e1c 100644 --- a/src/main/java/dev/loki/satura/core/event/Event.java +++ b/src/main/java/dev/loki/satura/core/event/Event.java @@ -1,5 +1,5 @@ package dev.loki.satura.core.event; -/** Маркер события. Тип события = его класс. */ +/** Event marker. The event type is its class. */ public interface Event { } diff --git a/src/main/java/dev/loki/satura/core/event/EventBus.java b/src/main/java/dev/loki/satura/core/event/EventBus.java index e16878f..32943ce 100644 --- a/src/main/java/dev/loki/satura/core/event/EventBus.java +++ b/src/main/java/dev/loki/satura/core/event/EventBus.java @@ -7,7 +7,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; -/** Шина событий: подписка с приоритетами, отписка, остановка цепочки на отменённом событии. */ +/** Event bus: prioritized subscription, unsubscription, chain stops on a cancelled event. */ @SuppressWarnings("PMD.LooseCoupling") public final class EventBus { diff --git a/src/main/java/dev/loki/satura/core/event/Listener.java b/src/main/java/dev/loki/satura/core/event/Listener.java index 1a6cfa3..a8d4313 100644 --- a/src/main/java/dev/loki/satura/core/event/Listener.java +++ b/src/main/java/dev/loki/satura/core/event/Listener.java @@ -3,12 +3,12 @@ package dev.loki.satura.core.event; import java.util.function.Consumer; /** - * Подписка на событие. Меньший priority вызывается раньше. + * Event subscription. A lower priority is called earlier. * - * @param type класс события - * @param priority порядок вызова - * @param handler обработчик - * @param тип события + * @param type event class + * @param priority call order + * @param handler handler + * @param event type */ public record Listener(Class type, int priority, Consumer handler) { diff --git a/src/main/java/dev/loki/satura/core/event/world/BlockChangeEvent.java b/src/main/java/dev/loki/satura/core/event/world/BlockChangeEvent.java index 7c2e0ce..f39038d 100644 --- a/src/main/java/dev/loki/satura/core/event/world/BlockChangeEvent.java +++ b/src/main/java/dev/loki/satura/core/event/world/BlockChangeEvent.java @@ -3,6 +3,6 @@ package dev.loki.satura.core.event.world; import dev.loki.satura.core.event.Event; import net.minecraft.util.math.BlockPos; -/** В клиентском мире изменился блок. */ +/** A block changed in the client world. */ public record BlockChangeEvent(BlockPos pos) implements Event { } diff --git a/src/main/java/dev/loki/satura/feature/builder/BuildSettings.java b/src/main/java/dev/loki/satura/feature/builder/BuildSettings.java index 12dd17c..a42e62a 100644 --- a/src/main/java/dev/loki/satura/feature/builder/BuildSettings.java +++ b/src/main/java/dev/loki/satura/feature/builder/BuildSettings.java @@ -13,11 +13,16 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; -/** Настройки билдера; читаются из {@link Profile} и в него же сериализуются. */ +/** Builder settings; read from and serialized back into a {@link Profile}. */ @SuppressWarnings({"PMD.LooseCoupling", "PMD.AvoidFieldNameMatchingMethodName"}) public final class BuildSettings { + /** Range and current value of a strategy parameter, for a GUI slider. */ + public record Range(double min, double max, double step, double value) { + } + static final String KEY_BLOCK = "block"; static final String KEY_SHAPE = "shape"; static final String KEY_LAYERS = "layers"; @@ -87,7 +92,7 @@ public final class BuildSettings { strategy = id; } - /** Слоёв за проход: значение опции стратегии bandLayers, если она её объявляет. */ + /** Layers per pass: the strategy's bandLayers option value, if it declares one. */ public int layers() { final PlaceStrategy s = strategy(); return s.options().contains(CommonOptions.BAND_LAYERS) @@ -105,6 +110,12 @@ public final class BuildSettings { return strategy().options().stream().map(Option::key).toList(); } + /** Range of a current-strategy parameter; empty if the strategy does not declare it. */ + public Optional optionRange(final String key) { + return strategy().options().stream().filter(o -> o.key().equals(key)).findFirst() + .map(o -> new Range(o.min(), o.max(), o.step(), strategy().values().get(o))); + } + public void setOption(final String key, final String value) { final double number; try { diff --git a/src/main/java/dev/loki/satura/feature/builder/BuilderFeature.java b/src/main/java/dev/loki/satura/feature/builder/BuilderFeature.java index 04b3bb3..b9a53bb 100644 --- a/src/main/java/dev/loki/satura/feature/builder/BuilderFeature.java +++ b/src/main/java/dev/loki/satura/feature/builder/BuilderFeature.java @@ -22,22 +22,17 @@ import dev.loki.satura.interaction.place.support.Cooldown; import dev.loki.satura.interaction.place.support.SupportFinder; import dev.loki.satura.util.ActionBarOut; import dev.loki.satura.util.ChatOut; -import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; import net.minecraft.client.MinecraftClient; import net.minecraft.util.math.BlockPos; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -/** Фасад фичи «авто-билдер»: единственная точка входа для GUI, команд и рендера. */ -@SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.GuardLogStatement"}) +/** Facade of the auto-builder feature: the single entry point for GUI, commands and rendering. */ +@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.LooseCoupling"}) public final class BuilderFeature implements BuildControl { - private static final Logger LOG = LoggerFactory.getLogger(BuilderFeature.class); - private final Selection current = new Selection(); private final BuildSettings settings; private final EngineAssembler assembler; @@ -56,7 +51,7 @@ public final class BuilderFeature implements BuildControl { commands.register(new BuildCommand(this)); } - /** Фасад на клиенте Minecraft; ходок «нет» (мост Baritone подключается через перегрузку). */ + /** Facade on the Minecraft client; no walker (the Baritone bridge is attached through an overload). */ public static BuilderFeature create(final CommandRegistry commands, final EventBus events, final ConfigStore store) { return create(commands, events, store, new NoWalker()); @@ -68,17 +63,16 @@ public final class BuilderFeature implements BuildControl { final MinecraftClient client = MinecraftClient.getInstance(); final BlockPlacer placer = new BlockPlacer(new SupportFinder(), new Cooldown()); final List strategies = List.of(new BandStack(placer), new ColumnDrop(placer)); - final Profile profile = load(store); return new BuilderFeature(commands, () -> client.player == null ? null : client.player.getBlockPos(), new EngineAssembler(client, events, walker, new ChatOut(), new ActionBarOut()), - new BuildSettings(profile, strategies), p -> save(store, p)); + new BuildSettings(store.loadOrEmpty(Profile.DEFAULT_NAME), strategies), store::saveQuietly); } public Selection selection() { return current; } - /** Вызывать каждый клиентский тик. */ + /** Call on every client tick. */ public void tick() { if (engine != null) { engine.tick(); @@ -119,6 +113,24 @@ public final class BuilderFeature implements BuildControl { return engine == null ? "IDLE" : engine.snapshot().describe(); } + /** Session stage, for GUI labels (the Pause/Resume button). */ + public Stage stage() { + return engine == null ? Stage.IDLE : engine.stage(); + } + + /** Settings for reading from the GUI; changes only via {@link BuildControl} methods. */ + public BuildSettings settings() { + return settings; + } + + /** Macro key: pause/resume the current build. */ + public String togglePause() { + if (engine == null) { + return "билд не запущен"; + } + return engine.stage() == Stage.PAUSED ? resume() : pause(); + } + @Override public String setBlock(final String id) { assembler.blocks().resolve(id); @@ -180,21 +192,4 @@ public final class BuilderFeature implements BuildControl { persist.accept(settings.toProfile(Profile.DEFAULT_NAME)); return message; } - - private static Profile load(final ConfigStore store) { - try { - return store.load(Profile.DEFAULT_NAME).orElse(Profile.empty(Profile.DEFAULT_NAME)); - } catch (IOException | RuntimeException e) { - LOG.warn("[satura] профиль не загружен: {}", e.toString()); - return Profile.empty(Profile.DEFAULT_NAME); - } - } - - private static void save(final ConfigStore store, final Profile profile) { - try { - store.save(profile); - } catch (IOException e) { - LOG.warn("[satura] профиль не сохранён: {}", e.toString()); - } - } } diff --git a/src/main/java/dev/loki/satura/feature/builder/EngineAssembler.java b/src/main/java/dev/loki/satura/feature/builder/EngineAssembler.java index b4ade9a..d972c9c 100644 --- a/src/main/java/dev/loki/satura/feature/builder/EngineAssembler.java +++ b/src/main/java/dev/loki/satura/feature/builder/EngineAssembler.java @@ -22,8 +22,8 @@ import java.util.random.RandomGenerator; import net.minecraft.block.Block; import net.minecraft.client.MinecraftClient; +/** Thin assembler of the engine from settings and the Minecraft client. */ @SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName") -/** Тонкий сборщик движка из настроек и клиента Minecraft. */ public final class EngineAssembler { private final MinecraftClient client; diff --git a/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneBridge.java b/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneBridge.java index d49ebd0..51bb84e 100644 --- a/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneBridge.java +++ b/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneBridge.java @@ -5,8 +5,9 @@ import net.fabricmc.loader.api.FabricLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** Мост к Baritone (Aethereal): только рефлексия, любая ошибка отключает мост одной записью в лог. */ -@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.AvoidCatchingGenericException", "PMD.GuardLogStatement"}) +/** Bridge to Baritone (Aethereal): reflection only; any error disables the bridge with a single log entry. */ +@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.AvoidCatchingGenericException", + "PMD.GuardLogStatement"}) public final class BaritoneBridge implements WalkerPort { static final String MOD_ID = "baritone-meteor"; diff --git a/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneLink.java b/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneLink.java index cc27fc9..991537a 100644 --- a/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneLink.java +++ b/src/main/java/dev/loki/satura/feature/builder/baritone/BaritoneLink.java @@ -5,7 +5,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; -/** Кэш рефлексивных дескрипторов Baritone API; создаётся один раз. */ +/** Cache of reflective Baritone API descriptors; created once. */ final class BaritoneLink { private static final String PKG = "baritone.api."; diff --git a/src/main/java/dev/loki/satura/feature/builder/baritone/WalkerPort.java b/src/main/java/dev/loki/satura/feature/builder/baritone/WalkerPort.java index 5ba9870..af02c05 100644 --- a/src/main/java/dev/loki/satura/feature/builder/baritone/WalkerPort.java +++ b/src/main/java/dev/loki/satura/feature/builder/baritone/WalkerPort.java @@ -1,9 +1,9 @@ package dev.loki.satura.feature.builder.baritone; -/** Порт перемещения: движок видит только его, а не Baritone. */ +/** Movement port: the engine sees only this, not Baritone. */ public interface WalkerPort { - /** Начать путь к точке (x, z); false — ходок недоступен или команда не принята. */ + /** Start a path to point (x, z); false if the walker is unavailable or the command was rejected. */ boolean walkTo(double x, double z); void cancel(); diff --git a/src/main/java/dev/loki/satura/feature/builder/commands/BuildCommand.java b/src/main/java/dev/loki/satura/feature/builder/commands/BuildCommand.java index 58eb341..51c510a 100644 --- a/src/main/java/dev/loki/satura/feature/builder/commands/BuildCommand.java +++ b/src/main/java/dev/loki/satura/feature/builder/commands/BuildCommand.java @@ -8,7 +8,7 @@ import java.util.Map; import java.util.function.Consumer; import java.util.stream.Collectors; -/** {@code .build} — диспетчер подкоманд. */ +/** {@code .build} — subcommand dispatcher. */ @SuppressWarnings("PMD.LooseCoupling") public final class BuildCommand implements Command { diff --git a/src/main/java/dev/loki/satura/feature/builder/commands/BuildControl.java b/src/main/java/dev/loki/satura/feature/builder/commands/BuildControl.java index c7e18b0..a127aa9 100644 --- a/src/main/java/dev/loki/satura/feature/builder/commands/BuildControl.java +++ b/src/main/java/dev/loki/satura/feature/builder/commands/BuildControl.java @@ -2,7 +2,7 @@ package dev.loki.satura.feature.builder.commands; import java.util.List; -/** Что команды {@code .build} умеют просить у фичи. Ошибки — исключения с текстом для пользователя. */ +/** What the {@code .build} commands can ask of the feature. Errors are exceptions with user-facing text. */ public interface BuildControl { String start(); diff --git a/src/main/java/dev/loki/satura/feature/builder/commands/BuildSubs.java b/src/main/java/dev/loki/satura/feature/builder/commands/BuildSubs.java index 890ca7d..e0cfec9 100644 --- a/src/main/java/dev/loki/satura/feature/builder/commands/BuildSubs.java +++ b/src/main/java/dev/loki/satura/feature/builder/commands/BuildSubs.java @@ -2,7 +2,7 @@ package dev.loki.satura.feature.builder.commands; import java.util.List; -/** Набор подкоманд {@code .build}, привязанных к {@link BuildControl}. */ +/** Set of {@code .build} subcommands bound to {@link BuildControl}. */ final class BuildSubs { private static final int SET_ARGS = 2; diff --git a/src/main/java/dev/loki/satura/feature/builder/commands/SubCommand.java b/src/main/java/dev/loki/satura/feature/builder/commands/SubCommand.java index 4dc615f..b482927 100644 --- a/src/main/java/dev/loki/satura/feature/builder/commands/SubCommand.java +++ b/src/main/java/dev/loki/satura/feature/builder/commands/SubCommand.java @@ -5,11 +5,11 @@ import java.util.function.Function; import java.util.function.Supplier; /** - * Подкоманда {@code .build }. + * Subcommand {@code .build }. * - * @param usage справка по аргументам - * @param options кандидаты для подсказки по токену номер index (после имени) - * @param run выполнить с аргументами после имени, вернуть ответ + * @param usage argument help text + * @param options suggestion candidates for the token at index (after the name) + * @param run execute with the arguments after the name, return the reply */ public record SubCommand(String name, String usage, Function> options, Function, String> run) { diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/BuildEngine.java b/src/main/java/dev/loki/satura/feature/builder/engine/BuildEngine.java index 191c732..24205ef 100644 --- a/src/main/java/dev/loki/satura/feature/builder/engine/BuildEngine.java +++ b/src/main/java/dev/loki/satura/feature/builder/engine/BuildEngine.java @@ -8,11 +8,11 @@ import dev.loki.satura.interaction.inventory.HotbarRefill; import dev.loki.satura.interaction.place.PlaceResult; import java.util.Optional; -@SuppressWarnings("PMD.CompareObjectsWithEquals") /** - * Тик билдера: planner → стратегия → пополнение хотбара. Паузы (экран, смерть, смена мира) - * снимаются сами, «нет блоков» — только вручную. Дыры чинятся ремонтными проходами. + * Builder tick: planner → strategy → hotbar refill. Pauses (screen, death, world change) + * lift on their own, "no blocks" only manually. Holes are fixed by repair passes. */ +@SuppressWarnings("PMD.CompareObjectsWithEquals") public final class BuildEngine { public static final int PROGRESS_INTERVAL_TICKS = 20; @@ -37,7 +37,7 @@ public final class BuildEngine { session.start(); } - /** Ручная пауза: авто-резюм не сработает. */ + /** Manual pause: auto-resume will not trigger. */ public void pause() { if (session.stage() == Stage.BUILD || session.stage() == Stage.PAUSED) { session.pause("пауза", false); diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/BuildSession.java b/src/main/java/dev/loki/satura/feature/builder/engine/BuildSession.java index 61b56c8..4504da8 100644 --- a/src/main/java/dev/loki/satura/feature/builder/engine/BuildSession.java +++ b/src/main/java/dev/loki/satura/feature/builder/engine/BuildSession.java @@ -5,17 +5,17 @@ import java.util.Locale; import java.util.Optional; import net.minecraft.util.math.BlockPos; +/** Session state: stage, pause reason, position, counters and statistics (progress comes from ColumnCache). */ @SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.NullAssignment"}) -/** Состояние сессии: этап, причина паузы, позиция, счётчики и статистика (прогресс — из ColumnCache). */ public final class BuildSession { private static final long MAX_STEP_MS = 250; private static final double MS_PER_SECOND = 1000.0; /** - * Снимок статистики. + * Statistics snapshot. * - * @param holes колонны, которые не удалось достроить + * @param holes columns that could not be completed */ public record Snapshot(Stage stage, String reason, int done, int total, double percent, int holes, int placed, int failed, double blocksPerSecond, Optional column) { @@ -80,7 +80,7 @@ public final class BuildSession { column = null; } - /** Учёт времени: считается только время в BUILD, паузы не входят. */ + /** Time accounting: only time in BUILD counts, pauses are excluded. */ public void advance(final long nowMs) { if (stage == Stage.BUILD && lastTickMs >= 0) { activeMs += Math.min(nowMs - lastTickMs, MAX_STEP_MS); diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/RepairTracker.java b/src/main/java/dev/loki/satura/feature/builder/engine/RepairTracker.java index 7dba333..b1f2f62 100644 --- a/src/main/java/dev/loki/satura/feature/builder/engine/RepairTracker.java +++ b/src/main/java/dev/loki/satura/feature/builder/engine/RepairTracker.java @@ -5,8 +5,8 @@ import java.util.HashSet; import java.util.Set; import net.minecraft.util.math.BlockPos; +/** Holes: columns that could not be completed; skipping, failure counters and repair passes. */ @SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName") -/** Дыры: колонны, которые не удалось достроить; пропуск, счётчики отказов и ремонтные проходы. */ public final class RepairTracker { public static final int MAX_FAILURES = 3; @@ -37,7 +37,7 @@ public final class RepairTracker { return passes; } - /** Сбрасывает счётчики, если сменилась колонна или прибавился прогресс. */ + /** Resets counters when the column changed or progress was made. */ public void observe(final BlockPos target, final int done) { if (!target.equals(column) || done != lastDone) { column = target; @@ -47,12 +47,12 @@ public final class RepairTracker { } } - /** Отказ стратегии; true — лимит исчерпан. */ + /** Strategy failure; true when the limit is exhausted. */ public boolean failure() { return ++failures >= MAX_FAILURES; } - /** Ожидание без прогресса; true — колонна зависла. */ + /** Waiting without progress; true when the column is stuck. */ public boolean stall() { return ++waits >= STALL_TICKS; } @@ -61,7 +61,7 @@ public final class RepairTracker { skipped.add(target.withY(0)); } - /** Ремонтный проход: вернуть пропущенные колонны в план; false — дыр нет или проходы кончились. */ + /** Repair pass: put skipped columns back into the plan; false when there are no holes or passes ran out. */ public boolean startRepair(final Planner planner) { if (skipped.isEmpty() || passes >= maxPasses) { return false; diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/Stage.java b/src/main/java/dev/loki/satura/feature/builder/engine/Stage.java index 62cf930..ad2bbff 100644 --- a/src/main/java/dev/loki/satura/feature/builder/engine/Stage.java +++ b/src/main/java/dev/loki/satura/feature/builder/engine/Stage.java @@ -1,6 +1,6 @@ package dev.loki.satura.feature.builder.engine; -/** Этап сессии. TRANSIT и SUPPLY — точки расширения (переход к области, вылазка за блоками). */ +/** Session stage. TRANSIT and SUPPLY are extension points (travel to the area, supply run). */ public enum Stage { IDLE, BUILD, diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/host/EngineDeps.java b/src/main/java/dev/loki/satura/feature/builder/engine/host/EngineDeps.java index b7881e9..e3de7a2 100644 --- a/src/main/java/dev/loki/satura/feature/builder/engine/host/EngineDeps.java +++ b/src/main/java/dev/loki/satura/feature/builder/engine/host/EngineDeps.java @@ -13,10 +13,10 @@ import dev.loki.satura.interaction.place.PlaceStrategy; import java.util.function.Consumer; /** - * Все зависимости движка (собираются снаружи, движок ничего не создаёт сам). + * All engine dependencies (assembled outside; the engine creates nothing itself). * - * @param chat сообщения пользователю - * @param bar строка прогресса (actionBar) + * @param chat messages to the user + * @param bar progress line (actionBar) */ @SuppressWarnings("PMD.ExcessiveParameterList") public record EngineDeps(Planner planner, ColumnCache cache, RepairTracker tracker, PlaceStrategy strategy, diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/host/GameState.java b/src/main/java/dev/loki/satura/feature/builder/engine/host/GameState.java index 693c0d4..7ebdc18 100644 --- a/src/main/java/dev/loki/satura/feature/builder/engine/host/GameState.java +++ b/src/main/java/dev/loki/satura/feature/builder/engine/host/GameState.java @@ -2,12 +2,12 @@ package dev.loki.satura.feature.builder.engine.host; import java.util.Optional; -/** Состояние игры, влияющее на работу движка; отделяет движок от клиента Minecraft. */ +/** Game state affecting the engine; decouples the engine from the Minecraft client. */ public interface GameState { - /** Причина, по которой строить сейчас нельзя (экран, смерть, нет мира); пусто — можно. */ + /** Reason why building is not possible now (screen, death, no world); empty when it is possible. */ Optional blockReason(); - /** Токен текущего мира: смена токена = смена мира. */ + /** Token of the current world: a token change means a world change. */ Object worldToken(); } diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftBlocks.java b/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftBlocks.java index f8b9e23..f6d8d11 100644 --- a/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftBlocks.java +++ b/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftBlocks.java @@ -8,7 +8,7 @@ import net.minecraft.item.BlockItem; import net.minecraft.registry.Registries; import net.minecraft.util.Identifier; -/** Поиск блоков: по ID из реестра или по предмету в основной руке. */ +/** Block lookup: by registry ID or by the item in the main hand. */ public final class MinecraftBlocks { public static final String HAND = "hand"; @@ -19,7 +19,7 @@ public final class MinecraftBlocks { this.client = client; } - /** Блок по ID ({@code stone} или {@code minecraft:stone}) либо из руки при {@link #HAND}. */ + /** Block by ID ({@code stone} or {@code minecraft:stone}) or from the hand for {@link #HAND}. */ public Block resolve(final String id) { if (HAND.equalsIgnoreCase(id)) { return fromHand(); diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftGameState.java b/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftGameState.java index fcd275c..5477dd9 100644 --- a/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftGameState.java +++ b/src/main/java/dev/loki/satura/feature/builder/engine/host/MinecraftGameState.java @@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.engine.host; import java.util.Optional; import net.minecraft.client.MinecraftClient; -/** Тонкий адаптер {@link GameState} к клиенту Minecraft. */ +/** Thin adapter of {@link GameState} to the Minecraft client. */ public final class MinecraftGameState implements GameState { private final MinecraftClient client; diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/walk/NoWalker.java b/src/main/java/dev/loki/satura/feature/builder/engine/walk/NoWalker.java index a5d8479..32e8b51 100644 --- a/src/main/java/dev/loki/satura/feature/builder/engine/walk/NoWalker.java +++ b/src/main/java/dev/loki/satura/feature/builder/engine/walk/NoWalker.java @@ -1,6 +1,6 @@ package dev.loki.satura.feature.builder.engine.walk; -/** Ходок «нет»: ничего не умеет. */ +/** Null walker: does nothing. */ public final class NoWalker implements Walker { @Override @@ -10,6 +10,6 @@ public final class NoWalker implements Walker { @Override public void cancel() { - // нечего отменять + // nothing to cancel } } diff --git a/src/main/java/dev/loki/satura/feature/builder/engine/walk/Walker.java b/src/main/java/dev/loki/satura/feature/builder/engine/walk/Walker.java index 8ee432c..1942ff8 100644 --- a/src/main/java/dev/loki/satura/feature/builder/engine/walk/Walker.java +++ b/src/main/java/dev/loki/satura/feature/builder/engine/walk/Walker.java @@ -1,9 +1,9 @@ package dev.loki.satura.feature.builder.engine.walk; -/** Ходок для наземных стратегий (S5/S6); мост к Baritone подключается позже. */ +/** Walker for ground strategies (S5/S6); the Baritone bridge is attached later. */ public interface Walker { - /** Начать путь к точке (x, z); false — ходок недоступен или команда не принята. */ + /** Start a path to point (x, z); false if the walker is unavailable or the command was rejected. */ boolean walkTo(double x, double z); void cancel(); diff --git a/src/main/java/dev/loki/satura/feature/builder/plan/ColumnTarget.java b/src/main/java/dev/loki/satura/feature/builder/plan/ColumnTarget.java index 33a26d6..c548764 100644 --- a/src/main/java/dev/loki/satura/feature/builder/plan/ColumnTarget.java +++ b/src/main/java/dev/loki/satura/feature/builder/plan/ColumnTarget.java @@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan; import java.util.List; import net.minecraft.util.math.BlockPos; -/** Колонна с ещё не построенными ячейками текущего Y-окна (по возрастанию Y). */ +/** Column with not yet built cells of the current Y window (ascending Y). */ public record ColumnTarget(BlockPos column, List cells) { public ColumnTarget { diff --git a/src/main/java/dev/loki/satura/feature/builder/plan/Planner.java b/src/main/java/dev/loki/satura/feature/builder/plan/Planner.java index f752e9d..4b6c5ba 100644 --- a/src/main/java/dev/loki/satura/feature/builder/plan/Planner.java +++ b/src/main/java/dev/loki/satura/feature/builder/plan/Planner.java @@ -8,7 +8,7 @@ import java.util.Optional; import java.util.function.Predicate; import net.minecraft.util.math.BlockPos; -/** Режет область на Y-окна и отдаёт следующую недостроенную колонну по змейке. */ +/** Slices the area into Y windows and returns the next unfinished column in snake order. */ public final class Planner { public static final int MIN_BAND_LAYERS = 1; @@ -31,7 +31,7 @@ public final class Planner { this.bandFloor = area.min().getY(); } - /** Следующая цель; окно сдвигается вверх, когда текущее достроено. Пусто = всё готово. */ + /** Next target; the window moves up once the current one is complete. Empty = all done. */ public Optional next() { final int top = area.max().getY(); while (bandFloor <= top) { @@ -47,12 +47,12 @@ public final class Planner { return Optional.empty(); } - /** Нижний Y текущего окна. */ + /** Lowest Y of the current window. */ public int bandStart() { return bandFloor; } - /** Вернуться к нижнему окну (для ремонтного прохода). */ + /** Go back to the lowest window (for a repair pass). */ public void reset() { bandFloor = area.min().getY(); } diff --git a/src/main/java/dev/loki/satura/feature/builder/plan/shape/BoxShape.java b/src/main/java/dev/loki/satura/feature/builder/plan/shape/BoxShape.java index 8ed5a26..c62608f 100644 --- a/src/main/java/dev/loki/satura/feature/builder/plan/shape/BoxShape.java +++ b/src/main/java/dev/loki/satura/feature/builder/plan/shape/BoxShape.java @@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan.shape; import dev.loki.satura.feature.builder.selection.Area; import net.minecraft.util.math.BlockPos; -/** Сплошной параллелепипед. */ +/** Solid cuboid. */ public final class BoxShape implements Shape { @Override diff --git a/src/main/java/dev/loki/satura/feature/builder/plan/shape/CheckerShape.java b/src/main/java/dev/loki/satura/feature/builder/plan/shape/CheckerShape.java index 30e0eab..ea5c4fb 100644 --- a/src/main/java/dev/loki/satura/feature/builder/plan/shape/CheckerShape.java +++ b/src/main/java/dev/loki/satura/feature/builder/plan/shape/CheckerShape.java @@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan.shape; import dev.loki.satura.feature.builder.selection.Area; import net.minecraft.util.math.BlockPos; -/** Шахматка: чётность x+z относительно угла min области. */ +/** Checkerboard: parity of x+z relative to the area's min corner. */ public final class CheckerShape implements Shape { @Override diff --git a/src/main/java/dev/loki/satura/feature/builder/plan/shape/Shape.java b/src/main/java/dev/loki/satura/feature/builder/plan/shape/Shape.java index b35a763..8299366 100644 --- a/src/main/java/dev/loki/satura/feature/builder/plan/shape/Shape.java +++ b/src/main/java/dev/loki/satura/feature/builder/plan/shape/Shape.java @@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan.shape; import dev.loki.satura.feature.builder.selection.Area; import net.minecraft.util.math.BlockPos; -/** Какие ячейки области нужно строить. */ +/** Which cells of the area must be built. */ public interface Shape { boolean includes(Area area, BlockPos pos); diff --git a/src/main/java/dev/loki/satura/feature/builder/plan/shape/WallsShape.java b/src/main/java/dev/loki/satura/feature/builder/plan/shape/WallsShape.java index 8d000b4..df45568 100644 --- a/src/main/java/dev/loki/satura/feature/builder/plan/shape/WallsShape.java +++ b/src/main/java/dev/loki/satura/feature/builder/plan/shape/WallsShape.java @@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan.shape; import dev.loki.satura.feature.builder.selection.Area; import net.minecraft.util.math.BlockPos; -/** Только внешний периметр (стены) по всей высоте. */ +/** Outer perimeter only (walls) over the full height. */ public final class WallsShape implements Shape { @Override diff --git a/src/main/java/dev/loki/satura/feature/builder/scan/BlockProbe.java b/src/main/java/dev/loki/satura/feature/builder/scan/BlockProbe.java index a12834a..0110ed9 100644 --- a/src/main/java/dev/loki/satura/feature/builder/scan/BlockProbe.java +++ b/src/main/java/dev/loki/satura/feature/builder/scan/BlockProbe.java @@ -2,7 +2,7 @@ package dev.loki.satura.feature.builder.scan; import net.minecraft.util.math.BlockPos; -/** Источник состояния блоков; отделяет подсчёт от клиента Minecraft. */ +/** Source of block states; decouples counting from the Minecraft client. */ public interface BlockProbe { boolean isFilled(BlockPos pos); diff --git a/src/main/java/dev/loki/satura/feature/builder/scan/ColumnCache.java b/src/main/java/dev/loki/satura/feature/builder/scan/ColumnCache.java index 0cdbe34..940f474 100644 --- a/src/main/java/dev/loki/satura/feature/builder/scan/ColumnCache.java +++ b/src/main/java/dev/loki/satura/feature/builder/scan/ColumnCache.java @@ -5,7 +5,7 @@ import dev.loki.satura.feature.builder.selection.Area; import java.util.Arrays; import net.minecraft.util.math.BlockPos; -/** Инкрементальные счётчики заполненности по колоннам области (вместо полного X*Y*Z-скана). */ +/** Incremental per-column fill counters of the area (instead of a full X*Y*Z scan). */ public final class ColumnCache { private static final double PERCENT_FULL = 100.0; @@ -28,7 +28,7 @@ public final class ColumnCache { fullRescan(); } - /** Полный пересчёт всей области. */ + /** Full recount of the whole area. */ public void fullRescan() { doneTotal = 0; requiredTotal = 0; @@ -39,7 +39,7 @@ public final class ColumnCache { } } - /** Пересчитывает только колонну изменённого блока; вне области — игнор. */ + /** Recounts only the column of the changed block; ignored outside the area. */ public void onBlockChanged(final BlockPos pos) { if (area.contains(pos)) { recount(pos.getX(), pos.getZ()); @@ -62,12 +62,12 @@ public final class ColumnCache { return requiredTotal - doneTotal; } - /** Построено клеток формы в колонне (x, z). */ + /** Shape cells already built in column (x, z). */ public int builtIn(final int x, final int z) { return built[index(x, z)]; } - /** Осталось построить в колонне (x, z). */ + /** Cells still to build in column (x, z). */ public int remainingIn(final int x, final int z) { final int i = index(x, z); return required[i] - built[i]; diff --git a/src/main/java/dev/loki/satura/feature/builder/scan/WorldBlockProbe.java b/src/main/java/dev/loki/satura/feature/builder/scan/WorldBlockProbe.java index a604b73..a8f1440 100644 --- a/src/main/java/dev/loki/satura/feature/builder/scan/WorldBlockProbe.java +++ b/src/main/java/dev/loki/satura/feature/builder/scan/WorldBlockProbe.java @@ -5,7 +5,7 @@ import net.minecraft.block.BlockState; import net.minecraft.client.world.ClientWorld; import net.minecraft.util.math.BlockPos; -/** Заполнено = не воздух и не заменяемое (трава, вода и т.п.). Мир берётся лениво. */ +/** Filled = not air and not replaceable (grass, water, etc.). The world is obtained lazily. */ @SuppressWarnings("PMD.CloseResource") public final class WorldBlockProbe implements BlockProbe { diff --git a/src/main/java/dev/loki/satura/feature/builder/selection/Area.java b/src/main/java/dev/loki/satura/feature/builder/selection/Area.java index 59dc8b5..0a92c06 100644 --- a/src/main/java/dev/loki/satura/feature/builder/selection/Area.java +++ b/src/main/java/dev/loki/satura/feature/builder/selection/Area.java @@ -4,7 +4,7 @@ import java.util.ArrayList; import java.util.List; import net.minecraft.util.math.BlockPos; -/** Прямоугольная область мира (границы включительно). */ +/** Rectangular world area (bounds inclusive). */ public record Area(BlockPos min, BlockPos max) { private static final int EVEN_DIVISOR = 2; @@ -18,9 +18,13 @@ public record Area(BlockPos min, BlockPos max) { } public boolean contains(BlockPos p) { - return p.getX() >= min.getX() && p.getX() <= max.getX() - && p.getY() >= min.getY() && p.getY() <= max.getY() - && p.getZ() >= min.getZ() && p.getZ() <= max.getZ(); + return within(p.getX(), min.getX(), max.getX()) + && within(p.getY(), min.getY(), max.getY()) + && within(p.getZ(), min.getZ(), max.getZ()); + } + + private static boolean within(int v, int lo, int hi) { + return v >= lo && v <= hi; } public long volume() { @@ -39,7 +43,7 @@ public record Area(BlockPos min, BlockPos max) { return max.getZ() - min.getZ() + 1; } - /** Колонны на y = min.y: ряды по z, чётные ряды по x вверх, нечётные вниз. */ + /** Columns at y = min.y: rows along z, even rows go up along x, odd rows go down. */ public List columns() { int sx = sizeX(); int sz = sizeZ(); diff --git a/src/main/java/dev/loki/satura/feature/builder/selection/PosCommand.java b/src/main/java/dev/loki/satura/feature/builder/selection/PosCommand.java index f73ebd8..0b17d7a 100644 --- a/src/main/java/dev/loki/satura/feature/builder/selection/PosCommand.java +++ b/src/main/java/dev/loki/satura/feature/builder/selection/PosCommand.java @@ -7,7 +7,7 @@ import java.util.function.Consumer; import java.util.function.Supplier; import net.minecraft.util.math.BlockPos; -/** {@code .pos1} / {@code .pos2} — запомнить позицию ног игрока. */ +/** {@code .pos1} / {@code .pos2} — remember the player's feet position. */ public final class PosCommand implements Command { private final String label; diff --git a/src/main/java/dev/loki/satura/feature/builder/selection/SelCommand.java b/src/main/java/dev/loki/satura/feature/builder/selection/SelCommand.java index 8e53654..dd781e2 100644 --- a/src/main/java/dev/loki/satura/feature/builder/selection/SelCommand.java +++ b/src/main/java/dev/loki/satura/feature/builder/selection/SelCommand.java @@ -4,7 +4,7 @@ import dev.loki.satura.core.command.Command; import java.util.List; import java.util.function.Consumer; -/** {@code .sel clear} — сбросить выделение. */ +/** {@code .sel clear} — reset the selection. */ public final class SelCommand implements Command { private static final String CLEAR = "clear"; diff --git a/src/main/java/dev/loki/satura/feature/builder/selection/Selection.java b/src/main/java/dev/loki/satura/feature/builder/selection/Selection.java index afeedc7..57ed751 100644 --- a/src/main/java/dev/loki/satura/feature/builder/selection/Selection.java +++ b/src/main/java/dev/loki/satura/feature/builder/selection/Selection.java @@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.selection; import java.util.Optional; import net.minecraft.util.math.BlockPos; -/** Две точки выделения; область существует, когда заданы обе. */ +/** Two selection points; the area exists once both are set. */ public final class Selection { private Optional first = Optional.empty(); diff --git a/src/main/java/dev/loki/satura/gui/BuilderUi.java b/src/main/java/dev/loki/satura/gui/BuilderUi.java new file mode 100644 index 0000000..f1978ef --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/BuilderUi.java @@ -0,0 +1,53 @@ +package dev.loki.satura.gui; + +import dev.loki.satura.feature.builder.BuilderFeature; +import dev.loki.satura.gui.screen.BuilderScreen; +import java.util.function.Consumer; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; +import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; +import net.minecraft.client.MinecraftClient; +import net.minecraft.client.option.KeyBinding; +import net.minecraft.util.Identifier; +import org.lwjgl.glfw.GLFW; + +/** + * Mod keys (Satura category, configurable in the vanilla Controls screen): + * Right Shift opens/closes the menu, the pause macro uses the key from the settings. + */ +public final class BuilderUi { + + private static final Identifier CATEGORY_ID = Identifier.of("satura", "main"); + private static final KeyBinding.Category CATEGORY = KeyBinding.Category.create(CATEGORY_ID); + private static final String KEY_MENU = "key.satura.open_menu"; + private static final String KEY_TOGGLE = "key.satura.toggle"; + + private final BuilderFeature builder; + private final Consumer bar; + private final KeyBinding openMenu; + private final KeyBinding toggleBuild; + + public BuilderUi(final BuilderFeature builder, final Consumer bar) { + this.builder = builder; + this.bar = bar; + this.openMenu = KeyBindingHelper.registerKeyBinding( + new KeyBinding(KEY_MENU, GLFW.GLFW_KEY_RIGHT_SHIFT, CATEGORY)); + this.toggleBuild = KeyBindingHelper.registerKeyBinding( + new KeyBinding(KEY_TOGGLE, GLFW.GLFW_KEY_P, CATEGORY)); + } + + /** Subscribes to client ticks; call once during initialization. */ + public void register() { + ClientTickEvents.END_CLIENT_TICK.register(this::tick); + } + + private void tick(final MinecraftClient client) { + while (openMenu.wasPressed()) { + if (client.currentScreen == null) { + client.setScreen(new BuilderScreen(builder, openMenu)); + } + } + while (toggleBuild.wasPressed()) { + bar.accept(builder.togglePause()); + } + } +} diff --git a/src/main/java/dev/loki/satura/gui/screen/BuilderScreen.java b/src/main/java/dev/loki/satura/gui/screen/BuilderScreen.java new file mode 100644 index 0000000..d9701da --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/screen/BuilderScreen.java @@ -0,0 +1,201 @@ +package dev.loki.satura.gui.screen; + +import dev.loki.satura.feature.builder.BuildSettings; +import dev.loki.satura.feature.builder.BuilderFeature; +import dev.loki.satura.feature.builder.engine.Stage; +import dev.loki.satura.feature.builder.plan.Planner; +import dev.loki.satura.gui.widget.CycleButton; +import dev.loki.satura.gui.widget.NumberSlider; +import dev.loki.satura.render.Renderer; +import dev.loki.satura.render.Theme; +import java.util.Optional; +import java.util.function.Supplier; +import net.minecraft.client.gui.DrawContext; +import net.minecraft.client.gui.screen.Screen; +import net.minecraft.client.gui.widget.ButtonWidget; +import net.minecraft.client.gui.widget.TextFieldWidget; +import net.minecraft.client.input.KeyInput; +import net.minecraft.client.option.KeyBinding; +import net.minecraft.text.Text; +import net.minecraft.util.math.BlockPos; + +/** Builder screen: selection, start/pause/stop, shape, layers, delay, block, status line. */ +@SuppressWarnings("PMD.AvoidCatchingGenericException") +public final class BuilderScreen extends Screen { + + private static final int FIXED_ROWS = 5; + private static final int NOTICE_TICKS = 100; + private static final int MAX_BLOCK_LEN = 64; + private static final int POS1 = 1; + private static final int POS2 = 2; + private static final String OPT_DELAY = "delayMs"; + private static final String LANG_POS1 = "satura.gui.pos1"; + private static final String LANG_POS2 = "satura.gui.pos2"; + private static final String LANG_PAUSE = "satura.gui.pause"; + private static final String LANG_RESUME = "satura.gui.resume"; + + private final BuilderFeature builder; + private final KeyBinding openMenu; + private Panel panel; + private ButtonWidget pos1Button; + private ButtonWidget pos2Button; + private ButtonWidget pauseButton; + private TextFieldWidget blockField; + private Text notice = Text.empty(); + private int noticeTicks; + + public BuilderScreen(final BuilderFeature builder, final KeyBinding openMenu) { + super(Text.translatable("satura.title")); + this.builder = builder; + this.openMenu = openMenu; + } + + @Override + protected void init() { + final Optional delay = builder.settings().optionRange(OPT_DELAY); + panel = new Panel(width, height, FIXED_ROWS + (delay.isPresent() ? 1 : 0)); + final int inner = panel.inner(); + final int left = panel.left(); + final int half = (inner - Panel.GAP) / 2; + final int third = (inner - Panel.GAP * 2) / 3; + int y = panel.top() + Panel.PAD + Panel.TITLE_H + Panel.GAP; + pos1Button = addDrawableChild(button(LANG_POS1, () -> capture(POS1), left, y, half)); + pos2Button = addDrawableChild(button(LANG_POS2, () -> capture(POS2), left + half + Panel.GAP, y, half)); + y += Panel.WIDGET_H + Panel.GAP; + addDrawableChild(button("satura.gui.start", () -> run(builder::start), left, y, third)); + pauseButton = addDrawableChild(button(LANG_PAUSE, + () -> run(() -> builder.stage() == Stage.PAUSED ? builder.resume() : builder.pause()), + left + third + Panel.GAP, y, third)); + addDrawableChild(button("satura.gui.stop", () -> run(builder::stop), + left + (third + Panel.GAP) * 2, y, third)); + y += Panel.WIDGET_H + Panel.GAP; + addDrawableChild(new CycleButton(left, y, inner, Panel.WIDGET_H, "satura.gui.shape", + builder.shapeIds(), builder.settings().shapeId(), id -> run(() -> builder.setShape(id)))); + y += Panel.WIDGET_H + Panel.GAP; + addDrawableChild(new NumberSlider(left, y, inner, Panel.WIDGET_H, + new NumberSlider.Spec(Planner.MIN_BAND_LAYERS, Planner.MAX_BAND_LAYERS, 1, + builder.settings().layers()), + v -> Text.translatable("satura.gui.layers", formatInt(v)), + v -> run(() -> builder.setLayers((int) Math.round(v))))); + y += Panel.WIDGET_H + Panel.GAP; + if (delay.isPresent()) { + final BuildSettings.Range r = delay.get(); + addDrawableChild(new NumberSlider(left, y, inner, Panel.WIDGET_H, + new NumberSlider.Spec(r.min(), r.max(), r.step(), r.value()), + v -> Text.translatable("satura.gui.delay", formatInt(v)), + v -> run(() -> builder.setOption(OPT_DELAY, formatInt(v))))); + y += Panel.WIDGET_H + Panel.GAP; + } + blockField = new TextFieldWidget(textRenderer, left, y, inner, Panel.WIDGET_H, + Text.translatable("satura.gui.block")); + blockField.setMaxLength(MAX_BLOCK_LEN); + blockField.setText(builder.settings().block()); + addSelectableChild(blockField); + } + + @Override + public void tick() { + if (noticeTicks > 0) { + noticeTicks--; + } + pos1Button.setMessage(posLabel(LANG_POS1, builder.selection().pos1())); + pos2Button.setMessage(posLabel(LANG_POS2, builder.selection().pos2())); + pauseButton.setMessage(Text.translatable( + builder.stage() == Stage.PAUSED ? LANG_RESUME : LANG_PAUSE)); + } + + @Override + public void render(final DrawContext context, final int mouseX, final int mouseY, final float delta) { + super.render(context, mouseX, mouseY, delta); + context.drawCenteredTextWithShadow(textRenderer, title, width / 2, + panel.top() + Panel.PAD, Theme.TEXT); + final String status = trim(builder.status()); + context.drawTextWithShadow(textRenderer, trim(notice.getString()), + panel.left(), panel.statusY(), Theme.ACCENT_HOVER); + context.drawTextWithShadow(textRenderer, status, + panel.left(), panel.statusY() + Panel.LINE_H, Theme.TEXT_MUTED); + } + + @Override + public void renderBackground(final DrawContext context, final int mouseX, final int mouseY, + final float delta) { + super.renderBackground(context, mouseX, mouseY, delta); + panel.paint(Renderer.shared()); + } + + @Override + public boolean keyPressed(final KeyInput input) { + if (openMenu.matchesKey(input)) { + close(); + return true; + } + if (blockField.isFocused() && input.isEnter()) { + commitBlock(); + return true; + } + return super.keyPressed(input); + } + + @Override + public void removed() { + commitBlock(); + super.removed(); + } + + @Override + public boolean shouldPause() { + return false; + } + + private void run(final Supplier action) { + try { + showNotice(action.get()); + } catch (RuntimeException e) { + showNotice(e.getMessage() == null ? "ошибка" : e.getMessage()); + } + } + + private void showNotice(final String text) { + notice = Text.literal(text); + noticeTicks = NOTICE_TICKS; + } + + private void commitBlock() { + final String id = blockField.getText().strip(); + if (!id.isEmpty() && !id.equals(builder.settings().block())) { + run(() -> builder.setBlock(id)); + } + } + + private void capture(final int which) { + if (client.player == null) { + showNotice("зайди в мир"); + return; + } + final BlockPos pos = client.player.getBlockPos(); + if (which == POS1) { + builder.selection().setPos1(pos); + } else { + builder.selection().setPos2(pos); + } + showNotice("Pos" + which + ": " + pos.toShortString()); + } + + private Text posLabel(final String key, final Optional pos) { + return Text.translatable(key, pos.map(BlockPos::toShortString).orElse("-")); + } + + private static String formatInt(final double value) { + return String.valueOf(Math.round(value)); + } + + private String trim(final String text) { + return textRenderer.trimToWidth(text, Panel.WIDTH - Panel.PAD * 2); + } + + private static ButtonWidget button(final String key, final Runnable action, + final int x, final int y, final int w) { + return ButtonWidget.builder(Text.translatable(key), b -> action.run()) + .dimensions(x, y, w, Panel.WIDGET_H).build(); + } +} diff --git a/src/main/java/dev/loki/satura/gui/screen/Panel.java b/src/main/java/dev/loki/satura/gui/screen/Panel.java new file mode 100644 index 0000000..a9459fb --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/screen/Panel.java @@ -0,0 +1,62 @@ +package dev.loki.satura.gui.screen; + +import dev.loki.satura.render.Renderer; +import dev.loki.satura.render.Theme; +import dev.loki.satura.render.geom.Bounds; + +/** Geometry and drawing of the screen's dark panel (blur, backdrop, outline). */ +final class Panel { + + static final int WIDTH = 240; + static final int PAD = 10; + static final int WIDGET_H = 20; + static final int GAP = 4; + static final int TITLE_H = 14; + static final int LINE_H = 11; + static final int STATUS_ROWS = 2; + private static final float BLUR_STRENGTH = 1.0f; + + private final int screenW; + private final int screenH; + private final int rows; + + Panel(final int screenW, final int screenH, final int rows) { + this.screenW = screenW; + this.screenH = screenH; + this.rows = rows; + } + + /** Left edge of the content (padding already applied). */ + int left() { + return (screenW - WIDTH) / 2 + PAD; + } + + int inner() { + return WIDTH - PAD * 2; + } + + int top() { + return (screenH - height()) / 2; + } + + int height() { + return PAD + TITLE_H + GAP + rows * (WIDGET_H + GAP) + GAP + STATUS_ROWS * LINE_H + PAD; + } + + /** Y of the first status line (at the bottom of the panel). */ + int statusY() { + return top() + height() - PAD - STATUS_ROWS * LINE_H; + } + + Bounds bounds() { + return new Bounds((screenW - WIDTH) / 2f, top(), WIDTH, height()); + } + + /** Draws the panel backdrop; called after the vanilla background, before the widgets. */ + void paint(final Renderer renderer) { + final Bounds b = bounds(); + renderer.blur(b, Theme.RADIUS, BLUR_STRENGTH); + renderer.rect(b, Theme.RADIUS, Theme.PANEL); + renderer.outline(b, Theme.RADIUS, Theme.BORDER_WIDTH, Theme.BORDER); + } +} diff --git a/src/main/java/dev/loki/satura/gui/widget/CycleButton.java b/src/main/java/dev/loki/satura/gui/widget/CycleButton.java new file mode 100644 index 0000000..4b39876 --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/widget/CycleButton.java @@ -0,0 +1,49 @@ +package dev.loki.satura.gui.widget; + +import java.util.List; +import java.util.function.Consumer; +import net.minecraft.client.gui.widget.ButtonWidget; +import net.minecraft.client.input.AbstractInput; + +/** + * Cycle button: a click steps through the values and hands the chosen one to the owner. + * The label is a translatable string with {@code %s} in place of the value. Rendering is vanilla + * (inherited from ButtonWidget.Text). + */ +public final class CycleButton extends ButtonWidget.Text { + + private final List values; + private final String labelKey; + private final Consumer onChange; + private int index; + + public CycleButton(final int x, final int y, final int width, final int height, + final String labelKey, final List values, + final String initial, final Consumer onChange) { + super(x, y, width, height, net.minecraft.text.Text.empty(), b -> { }, DEFAULT_NARRATION_SUPPLIER); + if (values.isEmpty()) { + throw new IllegalArgumentException("cycle without values: " + labelKey); + } + this.values = List.copyOf(values); + this.labelKey = labelKey; + this.onChange = onChange; + this.index = Math.max(0, this.values.indexOf(initial)); + refresh(); + } + + /** Currently selected value. */ + public String value() { + return values.get(index); + } + + @Override + public void onPress(final AbstractInput input) { + index = (index + 1) % values.size(); + refresh(); + onChange.accept(values.get(index)); + } + + private void refresh() { + setMessage(net.minecraft.text.Text.translatable(labelKey, values.get(index))); + } +} diff --git a/src/main/java/dev/loki/satura/gui/widget/NumberSlider.java b/src/main/java/dev/loki/satura/gui/widget/NumberSlider.java new file mode 100644 index 0000000..166db44 --- /dev/null +++ b/src/main/java/dev/loki/satura/gui/widget/NumberSlider.java @@ -0,0 +1,56 @@ +package dev.loki.satura.gui.widget; + +import java.util.function.Consumer; +import java.util.function.DoubleFunction; +import net.minecraft.client.gui.widget.SliderWidget; +import net.minecraft.text.Text; + +/** Number slider (int/float) with a step; range, label and receiver are set by the owner. */ +public final class NumberSlider extends SliderWidget { + + private static final double NO_STEP = 0.0; + + /** Slider range: bounds, step (0 = continuous) and the initial value. */ + public record Spec(double min, double max, double step, double initial) { + } + + private final double min; + private final double max; + private final double step; + private final DoubleFunction label; + private final Consumer onChange; + + public NumberSlider(final int x, final int y, final int width, final int height, final Spec spec, + final DoubleFunction label, final Consumer onChange) { + super(x, y, width, height, Text.empty(), normalized(spec.min(), spec.max(), spec.initial())); + this.min = spec.min(); + this.max = spec.max(); + this.step = spec.step(); + this.label = label; + this.onChange = onChange; + updateMessage(); + } + + /** Current value in range units (step applied). */ + public double current() { + final double raw = min + (max - min) * value; + return step == NO_STEP ? raw : Math.round(raw / step) * step; + } + + @Override + protected void updateMessage() { + setMessage(label.apply(current())); + } + + @Override + protected void applyValue() { + onChange.accept(current()); + } + + private static double normalized(final double min, final double max, final double value) { + if (max <= min) { + return 0.0; + } + return Math.clamp((value - min) / (max - min), 0.0, 1.0); + } +} diff --git a/src/main/java/dev/loki/satura/interaction/click/ClickConfig.java b/src/main/java/dev/loki/satura/interaction/click/ClickConfig.java index e2e1df8..7d35a1d 100644 --- a/src/main/java/dev/loki/satura/interaction/click/ClickConfig.java +++ b/src/main/java/dev/loki/satura/interaction/click/ClickConfig.java @@ -3,12 +3,12 @@ package dev.loki.satura.interaction.click; import java.util.random.RandomGenerator; /** - * Настройки темпа кликов по контейнерам. + * Pacing settings for container clicks. * - * @param minDelayMs базовая пауза между кликами - * @param jitter доля случайного разброса паузы (0.3 = плюс-минус 30%) - * @param confirmTimeoutMs сколько ждать подтверждения клика до повтора - * @param maxAttempts сколько раз кликнуть, прежде чем сдаться + * @param minDelayMs base pause between clicks + * @param jitter random spread share of the pause (0.3 = plus or minus 30%) + * @param confirmTimeoutMs how long to wait for click confirmation before retrying + * @param maxAttempts how many times to click before giving up */ public record ClickConfig(long minDelayMs, double jitter, long confirmTimeoutMs, int maxAttempts) { @@ -30,7 +30,7 @@ public record ClickConfig(long minDelayMs, double jitter, long confirmTimeoutMs, return new ClickConfig(delayMs, jitter, confirmTimeoutMs, maxAttempts); } - /** Следующая пауза: minDelayMs * (1 +- jitter), равномерно. */ + /** Next pause: minDelayMs * (1 +- jitter), uniformly distributed. */ public long nextDelay(RandomGenerator random) { double factor = 1 + jitter * (2 * random.nextDouble() - 1); return Math.round(minDelayMs * factor); diff --git a/src/main/java/dev/loki/satura/interaction/click/ClickScheduler.java b/src/main/java/dev/loki/satura/interaction/click/ClickScheduler.java index 31682db..313102f 100644 --- a/src/main/java/dev/loki/satura/interaction/click/ClickScheduler.java +++ b/src/main/java/dev/loki/satura/interaction/click/ClickScheduler.java @@ -5,8 +5,8 @@ import java.util.Deque; import java.util.random.RandomGenerator; /** - * Единая очередь контейнерных кликов: пауза с джиттером между кликами и подтверждение - * каждого клика по синхронизации слотов (таймаут, повтор). Тикается владельцем раз в тик. + * Single queue of container clicks: jittered pause between clicks and confirmation + * of every click via slot sync (timeout, retry). Ticked by the owner once per tick. */ public final class ClickScheduler { @@ -42,7 +42,7 @@ public final class ClickScheduler { return queue.size() + (current == null ? 0 : 1); } - /** Отложить следующий клик минимум на delayMs (пауза «человека» после открытия экрана). */ + /** Delay the next click by at least delayMs (a "human" pause after a screen opens). */ public void delayNext(long delayMs) { nextClickAt = Math.max(nextClickAt, clock.nowMillis() + delayMs); } diff --git a/src/main/java/dev/loki/satura/interaction/click/ClickTask.java b/src/main/java/dev/loki/satura/interaction/click/ClickTask.java index 730fed3..8634851 100644 --- a/src/main/java/dev/loki/satura/interaction/click/ClickTask.java +++ b/src/main/java/dev/loki/satura/interaction/click/ClickTask.java @@ -4,15 +4,15 @@ import java.util.function.BooleanSupplier; import java.util.function.Consumer; /** - * Один клик по контейнеру. + * A single container click. * - * @param click действие клика (вызов clickSlot) - * @param confirmed true, когда результат клика виден в слотах (синхронизация пришла) - * @param onDone итог задачи + * @param click click action (the clickSlot call) + * @param confirmed true when the click result is visible in the slots (sync arrived) + * @param onDone task outcome */ public record ClickTask(Runnable click, BooleanSupplier confirmed, Consumer onDone) { - /** Итог задачи. */ + /** Task outcome. */ public enum Outcome { CONFIRMED, FAILED } public static ClickTask of(Runnable click, BooleanSupplier confirmed) { diff --git a/src/main/java/dev/loki/satura/interaction/click/Clock.java b/src/main/java/dev/loki/satura/interaction/click/Clock.java index aa47d97..06f4f59 100644 --- a/src/main/java/dev/loki/satura/interaction/click/Clock.java +++ b/src/main/java/dev/loki/satura/interaction/click/Clock.java @@ -1,6 +1,6 @@ package dev.loki.satura.interaction.click; -/** Источник времени; подменяется в тестах. */ +/** Time source; replaced in tests. */ @FunctionalInterface public interface Clock { diff --git a/src/main/java/dev/loki/satura/interaction/inventory/HotbarRefill.java b/src/main/java/dev/loki/satura/interaction/inventory/HotbarRefill.java index 4cd846a..3ed1e1f 100644 --- a/src/main/java/dev/loki/satura/interaction/inventory/HotbarRefill.java +++ b/src/main/java/dev/loki/satura/interaction/inventory/HotbarRefill.java @@ -4,15 +4,15 @@ import dev.loki.satura.interaction.click.ClickScheduler; import dev.loki.satura.interaction.click.ClickTask; /** - * Пополнение хотбара: когда в выбранном слоте осталось не больше порога, самый полный стак - * из инвентаря меняется с пустеющим слотом хотбара (SWAP) через общий ClickScheduler. + * Hotbar refill: when the selected slot holds no more than the threshold, the fullest stack + * from the inventory is swapped with the emptying hotbar slot (SWAP) via the shared ClickScheduler. */ public final class HotbarRefill { - /** Порог: слот с таким или меньшим числом блоков считается пустым. */ + /** Threshold: a slot with this many blocks or fewer counts as empty. */ public static final int LOW = 2; - /** Состояние пополнения. */ + /** Refill state. */ public enum State { READY, REFILLING, EMPTY } private final InventoryView inventory; @@ -30,7 +30,7 @@ public final class HotbarRefill { this.planner = new RefillPlanner(low); } - /** Один тик логики; сам планировщик кликов тикает владелец. */ + /** One logic tick; the owner ticks the click scheduler itself. */ public State tick() { if (swapPending) { return State.REFILLING; diff --git a/src/main/java/dev/loki/satura/interaction/inventory/InventoryView.java b/src/main/java/dev/loki/satura/interaction/inventory/InventoryView.java index 77589cb..dbee407 100644 --- a/src/main/java/dev/loki/satura/interaction/inventory/InventoryView.java +++ b/src/main/java/dev/loki/satura/interaction/inventory/InventoryView.java @@ -1,18 +1,18 @@ package dev.loki.satura.interaction.inventory; -/** Вид на инвентарь игрока относительно целевого предмета. Слоты 0-8 хотбар, 9-35 инвентарь. */ +/** View of the player's inventory relative to the target item. Slots 0-8 hotbar, 9-35 inventory. */ public interface InventoryView { int SLOTS = 36; int HOTBAR_SIZE = 9; - /** Сколько целевых предметов в слоте (0, если слот пуст или там другое). */ + /** How many target items are in the slot (0 if empty or holds something else). */ int count(int slot); int selectedSlot(); void select(int slot); - /** Клик SWAP: стак из слота инвентаря src меняется местами со слотом хотбара hotbarSlot. */ + /** SWAP click: the stack from inventory slot src is swapped with hotbar slot hotbarSlot. */ void swapToHotbar(int src, int hotbarSlot); } diff --git a/src/main/java/dev/loki/satura/interaction/inventory/MinecraftInventoryView.java b/src/main/java/dev/loki/satura/interaction/inventory/MinecraftInventoryView.java index 3dd3538..7fa0d2a 100644 --- a/src/main/java/dev/loki/satura/interaction/inventory/MinecraftInventoryView.java +++ b/src/main/java/dev/loki/satura/interaction/inventory/MinecraftInventoryView.java @@ -7,7 +7,7 @@ import net.minecraft.item.BlockItem; import net.minecraft.item.ItemStack; import net.minecraft.screen.slot.SlotActionType; -/** Тонкий адаптер к клиенту Minecraft: инвентарь игрока относительно одного блока. */ +/** Thin adapter to the Minecraft client: the player's inventory relative to one block. */ public final class MinecraftInventoryView implements InventoryView { private final MinecraftClient client; diff --git a/src/main/java/dev/loki/satura/interaction/inventory/RefillPlanner.java b/src/main/java/dev/loki/satura/interaction/inventory/RefillPlanner.java index 6191f47..ba6d5d4 100644 --- a/src/main/java/dev/loki/satura/interaction/inventory/RefillPlanner.java +++ b/src/main/java/dev/loki/satura/interaction/inventory/RefillPlanner.java @@ -1,13 +1,13 @@ package dev.loki.satura.interaction.inventory; -/** Чистый выбор действия по заполненности слотов. */ +/** Pure action choice based on slot fill levels. */ public final class RefillPlanner { - /** Тип решения. */ + /** Decision type. */ public enum Kind { READY, SELECT, SWAP, EMPTY } /** - * Решение: SELECT - выбрать хотбар-слот from; SWAP - обменять from (инвентарь) на to (хотбар). + * Decision: SELECT - select hotbar slot from; SWAP - swap from (inventory) with to (hotbar). */ public record Decision(Kind kind, int from, int to) { diff --git a/src/main/java/dev/loki/satura/interaction/movement/Angles.java b/src/main/java/dev/loki/satura/interaction/movement/Angles.java index 8647dbd..1f547de 100644 --- a/src/main/java/dev/loki/satura/interaction/movement/Angles.java +++ b/src/main/java/dev/loki/satura/interaction/movement/Angles.java @@ -1,6 +1,6 @@ package dev.loki.satura.interaction.movement; -/** Чистая математика углов (градусы, система Minecraft). */ +/** Pure angle math (degrees, Minecraft convention). */ public final class Angles { private static final float FULL_TURN = 360f; @@ -33,7 +33,7 @@ public final class Angles { return Math.max(-limit, Math.min(limit, value)); } - /** Шаг от current к target не больше maxStep по кратчайшей дуге. */ + /** Step from current towards target of at most maxStep along the shortest arc. */ public static float approachYaw(float current, float target, float maxStep) { return current + clamp(wrap(target - current), maxStep); } diff --git a/src/main/java/dev/loki/satura/interaction/movement/LookController.java b/src/main/java/dev/loki/satura/interaction/movement/LookController.java index 9742665..6aaa860 100644 --- a/src/main/java/dev/loki/satura/interaction/movement/LookController.java +++ b/src/main/java/dev/loki/satura/interaction/movement/LookController.java @@ -2,7 +2,7 @@ package dev.loki.satura.interaction.movement; import dev.loki.satura.interaction.movement.io.PlayerPose; -/** Управление взглядом: плавный доворот с клампом °/тик и мгновенный взгляд вниз. */ +/** Look control: smooth turn clamped in degrees/tick and an instant look down. */ public final class LookController { public static final float MAX_YAW_STEP = 25f; @@ -16,7 +16,7 @@ public final class LookController { this.pose = pose; } - /** Доворот к точке за один тик; true, когда взгляд уже на цели. */ + /** Turn towards a point in one tick; true when already looking at the target. */ public boolean lookAtSmooth(double x, double y, double z) { double dx = x - pose.x(); double dz = z - pose.z(); @@ -34,7 +34,7 @@ public final class LookController { return false; } - /** Мгновенно смотреть строго вниз (для стратегий столбика/пола). */ + /** Instantly look straight down (for pillar/floor strategies). */ public void lookDown() { pose.setPitch(DOWN_PITCH); } diff --git a/src/main/java/dev/loki/satura/interaction/movement/MovementController.java b/src/main/java/dev/loki/satura/interaction/movement/MovementController.java index e8ea604..e2f36c2 100644 --- a/src/main/java/dev/loki/satura/interaction/movement/MovementController.java +++ b/src/main/java/dev/loki/satura/interaction/movement/MovementController.java @@ -3,7 +3,7 @@ package dev.loki.satura.interaction.movement; import dev.loki.satura.interaction.movement.io.KeyInput; import dev.loki.satura.interaction.movement.io.PlayerPose; -/** Ходьба к точке фейк-клавишами: кламп поворота, прыжок на препятствии, сайдстеп при застревании. */ +/** Walking to a point with fake keys: turn clamp, jump at obstacles, sidestep when stuck. */ public final class MovementController { public static final float MAX_TURN_STEP = 35f; @@ -42,7 +42,7 @@ public final class MovementController { keys.setJump(true); } - /** Один тик ходьбы к (x, z); true, когда дошли (клавиши отпущены). */ + /** One walking tick towards (x, z); true on arrival (keys released). */ public boolean walkTo(double x, double z) { double dx = x - pose.x(); double dz = z - pose.z(); diff --git a/src/main/java/dev/loki/satura/interaction/movement/io/KeyInput.java b/src/main/java/dev/loki/satura/interaction/movement/io/KeyInput.java index ae30e02..9427956 100644 --- a/src/main/java/dev/loki/satura/interaction/movement/io/KeyInput.java +++ b/src/main/java/dev/loki/satura/interaction/movement/io/KeyInput.java @@ -1,6 +1,6 @@ package dev.loki.satura.interaction.movement.io; -/** Фейковые клавиши движения. */ +/** Fake movement keys. */ public interface KeyInput { void setForward(boolean pressed); diff --git a/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftKeyInput.java b/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftKeyInput.java index 4648e68..ad5cbae 100644 --- a/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftKeyInput.java +++ b/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftKeyInput.java @@ -2,7 +2,7 @@ package dev.loki.satura.interaction.movement.io; import net.minecraft.client.MinecraftClient; -/** Адаптер клавиш к настройкам клиента Minecraft. */ +/** Adapter of keys to the Minecraft client options. */ public final class MinecraftKeyInput implements KeyInput { private final MinecraftClient client; diff --git a/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftPlayerPose.java b/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftPlayerPose.java index 3b35b0d..82e41ce 100644 --- a/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftPlayerPose.java +++ b/src/main/java/dev/loki/satura/interaction/movement/io/MinecraftPlayerPose.java @@ -3,7 +3,7 @@ package dev.loki.satura.interaction.movement.io; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayerEntity; -/** Адаптер позы к ClientPlayerEntity; без игрока (мир не загружен) работает как заглушка. */ +/** Adapter of the pose to ClientPlayerEntity; without a player (world not loaded) acts as a stub. */ public final class MinecraftPlayerPose implements PlayerPose { private final MinecraftClient client; diff --git a/src/main/java/dev/loki/satura/interaction/movement/io/PlayerPose.java b/src/main/java/dev/loki/satura/interaction/movement/io/PlayerPose.java index 5212441..410f10d 100644 --- a/src/main/java/dev/loki/satura/interaction/movement/io/PlayerPose.java +++ b/src/main/java/dev/loki/satura/interaction/movement/io/PlayerPose.java @@ -1,6 +1,6 @@ package dev.loki.satura.interaction.movement.io; -/** Положение и взгляд игрока (градусы по Minecraft: yaw 0 = юг, pitch + вниз). */ +/** Player position and look direction (Minecraft degrees: yaw 0 = south, positive pitch = down). */ public interface PlayerPose { double x(); diff --git a/src/main/java/dev/loki/satura/interaction/place/PlaceContext.java b/src/main/java/dev/loki/satura/interaction/place/PlaceContext.java index 7bedf56..f9e2bb8 100644 --- a/src/main/java/dev/loki/satura/interaction/place/PlaceContext.java +++ b/src/main/java/dev/loki/satura/interaction/place/PlaceContext.java @@ -4,29 +4,29 @@ import net.minecraft.util.hit.BlockHitResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; -/** Всё, чем стратегия касается игры. Узкий интерфейс, чтобы логику можно было тестировать фейком. */ +/** Everything a strategy touches in the game. A narrow interface so the logic can be tested with a fake. */ public interface PlaceContext { - /** Позиция ног игрока. */ + /** Player's feet position. */ Vec3d feetPos(); - /** Позиция глаз игрока. */ + /** Player's eye position. */ Vec3d eyePos(); - /** Годится ли блок как опора. */ + /** Whether the block is usable as a support. */ boolean isSolid(BlockPos pos); - /** Клик ПКМ по блоку; true - клиент принял действие. */ + /** Right-click on a block; true if the client accepted the action. */ boolean interact(BlockHitResult hit); void swing(); - /** Мгновенно взгляд строго вниз. */ + /** Instantly look straight down. */ void lookDown(); void setVelocity(double x, double y, double z); - /** Включить полёт, если он разрешён. */ + /** Enable flight if it is allowed. */ void enableFlight(); long nowMs(); diff --git a/src/main/java/dev/loki/satura/interaction/place/PlaceResult.java b/src/main/java/dev/loki/satura/interaction/place/PlaceResult.java index 6a496ff..92ec7b5 100644 --- a/src/main/java/dev/loki/satura/interaction/place/PlaceResult.java +++ b/src/main/java/dev/loki/satura/interaction/place/PlaceResult.java @@ -1,11 +1,11 @@ package dev.loki.satura.interaction.place; -/** Итог одного тика стратегии. */ +/** Outcome of a single strategy tick. */ public enum PlaceResult { - /** Блок поставлен в этом тике. */ + /** A block was placed this tick. */ PLACED, - /** Ничего не делали: летим, кулдаун, ждём ответ сервера. */ + /** Did nothing: flying, cooldown, waiting for the server reply. */ WAIT, - /** Цель сейчас не поставить (нет опоры / вне досягаемости): движок вправе пересчитать цель. */ + /** The target cannot be placed now (no support / out of reach): the engine may pick another target. */ FAILED } diff --git a/src/main/java/dev/loki/satura/interaction/place/PlaceStrategy.java b/src/main/java/dev/loki/satura/interaction/place/PlaceStrategy.java index 28a8e37..74475f5 100644 --- a/src/main/java/dev/loki/satura/interaction/place/PlaceStrategy.java +++ b/src/main/java/dev/loki/satura/interaction/place/PlaceStrategy.java @@ -5,19 +5,19 @@ import dev.loki.satura.interaction.place.option.Option; import dev.loki.satura.interaction.place.option.OptionValues; import java.util.List; -/** Способ ставить блоки в колонну. Движок вызывает {@link #tick} каждый тик, пока колонна не достроена. */ +/** A way to place blocks into a column. The engine calls {@link #tick} every tick until the column is complete. */ public interface PlaceStrategy { - /** Стабильный ключ для конфига. */ + /** Stable key for the config. */ String id(); - /** Название для GUI. */ + /** Display name for the GUI. */ String label(); - /** Объявление параметров; GUI рисует их генерично. */ + /** Parameter declarations; the GUI renders them generically. */ List