├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── index.html ├── package-lock.json ├── package.json ├── public └── favicon.ico ├── src ├── App.vue ├── assets │ └── logo.png ├── components │ ├── BlockNameDisplay.vue │ ├── CCRemoteController.vue │ ├── DiscordWidget.vue │ ├── FuelGauge.vue │ ├── GenericInventorySlot.vue │ ├── Inventory.vue │ ├── InventorySlot.vue │ ├── KeyboardBindings.vue │ ├── LuaTerminal.vue │ ├── MovementControl.vue │ ├── Scene.vue │ ├── TurtleInventory.vue │ └── TurtlePanel.vue ├── env.d.ts ├── main.ts ├── server │ ├── server.js │ └── utils │ │ ├── cmdLineInterface.js │ │ └── userManagement.js ├── store │ ├── useWorld.ts │ └── useWorldView.ts ├── turtlePrograms │ ├── miningTunnel2.lua │ ├── miningTunnel3.lua │ ├── placeNewTurtle.lua │ ├── randomExplore.lua │ ├── skynetExpander.lua │ ├── stairsToLava.lua │ ├── treeMiner.lua │ └── veinMiner.lua ├── types │ └── types.ts └── utils │ ├── BlockRenderStructure.ts │ └── DynamicInstancedMesh.ts ├── textures ├── blocks │ ├── minecraft │ │ └── .gitkeep │ └── someOtherModNamespace │ │ └── .gitkeep ├── items │ ├── minecraft │ │ └── .gitkeep │ └── someOtherModNamespace │ │ └── .gitkeep └── turtle │ ├── CCTurtle.glb │ ├── CCTurtle_happy.glb │ └── cross.glb ├── tsconfig.json ├── tsconfig.node.json ├── turtle ├── diskboot ├── location ├── rcTurtle.lua ├── setLocRot ├── startup └── tapi ├── utils ├── textureExtractor │ └── textureExtractor.js └── zipPackaged.js └── vite.config.ts /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | grab 14 | logs 15 | *.local 16 | 17 | # Editor directories and files 18 | .vscode/* 19 | !.vscode/extensions.json 20 | .idea 21 | .DS_Store 22 | *.suo 23 | *.ntvs* 24 | *.njsproj 25 | *.sln 26 | *.sw? 27 | 28 | # textures 29 | textures/blocks/*/* 30 | textures/items/*/* 31 | 32 | # saved state 33 | src/server/saved/* 34 | 35 | !/**/.gitkeep 36 | 37 | # packaged binary 38 | packaged 39 | packagedZip -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | # Change Log 3 | 4 | ## [1.2.1] 5 | 6 | ### Fixed 7 | 8 | - Added important comment to locations where you would put your ip/url/localhost 9 | 10 | ## [1.1.0] 11 | 12 | ### Fixed 13 | 14 | - Texture generation script now works again 15 | 16 | ## [1.0.2] 17 | 18 | ### Added 19 | 20 | - Included instructions how to use the vite dev server 21 | - Updated readme accordingly 22 | 23 | ## [1.0.1] 24 | 25 | ### Changed 26 | 27 | - Easier config for hosting on localhost & public ip 28 | - Updated readme accordingly 29 | 30 | ## [1.0.0] 31 | 32 | ### Changed 33 | 34 | - This version is released under AGPL 35 | 36 | ### Added 37 | 38 | - Link to github, displayed below the discord widget. 39 | 40 | ## [0.9.1] 41 | 42 | ### Fixed 43 | 44 | - Crash when starting server. 45 | 46 | ## [0.9.0] 47 | 48 | ### Added 49 | 50 | - Cute new favicon. 51 | - Discord widget in bottom right. 52 | - Keyboard shortcuts are now displayed in the buttons that have shortcuts. 53 | - Button with program to automatically place and install new turtle. 54 | - Simple server side user management. 55 | - Simple server cmd line interface. Currently supports 56 | - users : list all users sorted by recent activity 57 | - deleteTurtle : delete turtle from current state - use that to remove a turtle from the ui that is gone for good. 58 | - Better logging, now also to a log file. 59 | - Hijack the important turtle move functions. So turtle.up() can be used in the lua terminal in the ui without causing a position desync. 60 | 61 | ### Changed 62 | 63 | - This version is no longer released under AGPL. 64 | - Added "Turtle" prefix to turtle selector & added some padding. 65 | - Most of the UI now got a dark theme. 66 | - Because the stop buttom sometimes causes desyncs in now only clears the cmd queue to prevent that. 67 | - Commented out some of the buttons to control the turtle, as they contained old / unrelated programs. 68 | - The turtle texture was modified to show a little more emotion =). 69 | 70 | ## [0.8.0] 71 | 72 | ### Added 73 | 74 | - The turtle selector in the UI will now also display the turtle label. 75 | - Added a loading message for display while loading the state. 76 | - Added support for animated textures. 77 | - Added support for cross block model (e.g. in flowers). 78 | - Replace native turtle move methods with tapi equivalents to not lose track of turtles when accidentally using native methods. 79 | - Replace os.shutdown with empty function. 80 | 81 | ### Changed 82 | 83 | - After clicking one of the movement buttons, the return value will now be displayed at the bottom of the UI. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CCTurtleRemoteController 2 | A node server with user interface for remote controlling your computercraft turtles in your browser via the http api. 3 | 4 | TurtleController_2 5 | 6 | **Setup** 7 | 8 | 1. Clone this repo or download it as zip and extract it 9 | 2. Install Node.js including npm (https://nodejs.org/en/) or make sure you update the version you are using else it will likely cause some errors. 10 | 3. Run `npm install` in the root directory of the repo 11 | * if you are on linux and get this [error](https://github.com/exa-byte/CCTurtleRemoteController/issues/19): run `apt update && apt install -y build-essential libcairo2-dev libjpeg-dev libpango1.0-dev libgif-dev librsvg2-dev pkg-config` and retry `npm install` afterwards 12 | 5. Now you have 2 options, pick one of them: 13 | * setup port forwarding and replace every localhost in the code (in the server files, not the turtle!) with your public ip address 14 | * "turtle/startup" Line 2 15 | * "turtle/tapi" Line 6 16 | * allow http calls to localhost in your /serverconfig/computercraft-server.toml 17 | 6. Build the frontend using `npm run build` 18 | 7. If you don't want to see textured blocks and items in the ui you can skip this point, else run the command `npm run build-textures "" ""` (note: \ points to a minecraft jar **file** which is usually located under %appdata%\\.minecraft\versions\yourversion\yourversion.jar when using the default minecraft launcher, while \ points to a **directory**); in case any errors pop up, just restart the command until no errors pop up. The command will need to be executed 2 times without errors due to some bug. After completion, the ui will be able to display most blocks and items with default mc textures applied 19 | 8. Run the server: `npm run server` 20 | 9. You can now reach the ui from http://localhost/ or your public ip address if you chose the second option in step 4 21 | 10. Add any amount of turtles by running `wget run http://localhost/turtle/startup` or `wget run http:///turtle/startup` in the turtles command line and following the displayed instructions 22 | 11. You can now select a turtle id in the top left corner of the ui and press the `toggle follow` button to move the camera to it 23 | 12. The selected turtle can be controlled by the buttons on the interface or some basic keyboard shortcuts (wasdqe) 24 | 13. You can also directly input code to be executed on the turtle, however if you use the native move functions of the turtle, you will desync the turtle location - use the `tapi` library equivalents instead 25 | 26 | **Block and item textures** 27 | 28 | Extracting textures is now easier than ever: just go with step 7 in setup. 29 | The ui supports textured blocks and items. They are just not included here for license reasons. 30 | If you have additional textures that don't get extracted properly, you can manually add them into `textures/blocks/minecraft/`. 31 | Same goes for items which go into `textures/items/minecraft/`. 32 | If you add textures from mods, the textures must go into `textures/blocks/yourmodname/` and `textures/items/yourmodname/` respectively (yourmodname is the ingame block id prefix). 33 | 34 | **Random info** 35 | 36 | - you can double click a block and the selected turtle will try to move there with a very simple algorithm 37 | - hovering over a block will show its id in the top right corner along with its coordinates (i think i changed it to clicking for performance reasons) 38 | - you can click a chest to open a window displaying its contents, however interaction is not implemented yet 39 | - you can drag and drop between turtle inventory slots hold `ctrl` for moving a whole stack 40 | - the bar below the turtle inventory is the turtles fuel gauge and shows the number of blocks you can move with the current fuel level 41 | - unfortunately some minecraft block textures are not easily extractable and have to be handled with extra steps (e.g. chest, furnace, leaf blocks that are greyscale) 42 | - the turtles are controlled via a command queue, that means if you spam a button 10 times a second the turtle will not ignore the 9 times it is not able to perform that second but will execute them as fast as it can; the command queue can be cleared with the 'del' key (if you spammed it too much) 43 | - if you don't have a chunkloader you will have to stay in render distance of the turtle, else the currently running program will be stopped and cannot be easily continued (the turtle will restart and reconnect when you come into range again though) 44 | 45 | **Keyboard bindings** 46 | 47 | | Key | Action | 48 | |-----|----------------------------| 49 | | w | move forward | 50 | | s | move back | 51 | | q | move down | 52 | | e | move up | 53 | | a | turn left | 54 | | d | turn right | 55 | | del | stop (clear command queue) | 56 | 57 | **Modifying the user interface** 58 | 59 | - for development go to src/store/useWorld.ts line 5 and follow the instructions of the comment. 60 | - run ```npm run dev``` 61 | - the dev frontend is now available at http://localhost:3000/ and you get to tinker on the frontend with hot reloading. 62 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Skynet Origins 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ccturtleremotecontroller", 3 | "private": true, 4 | "version": "1.2.1", 5 | "bin": "src/server/server.js", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vue-tsc --noEmit && vite build", 9 | "preview": "vite preview", 10 | "server": "node src/server/server.js", 11 | "build-textures": "node utils/textureExtractor/textureExtractor.js", 12 | "pkg": "npm run build && pkg package.json && node utils/zipPackaged.js" 13 | }, 14 | "dependencies": { 15 | "camera-controls": "1.34.2", 16 | "compression": "1.7.4", 17 | "cors": "2.8.5", 18 | "express": "4.17.3", 19 | "http-terminator": "3.2.0", 20 | "math3d": "0.2.2", 21 | "pinia": "2.0.12", 22 | "simple-node-logger": "21.8.12", 23 | "three": "0.138.3", 24 | "vue": "3.2.25" 25 | }, 26 | "devDependencies": { 27 | "@types/three": "0.138.0", 28 | "@vitejs/plugin-vue": "2.2.0", 29 | "archiver": "^7.0.1", 30 | "minecraft-blocks-render": "1.1.1", 31 | "pkg": "^5.8.1", 32 | "typescript": "4.5.4", 33 | "unzipper": "0.10.11", 34 | "vite": "2.9.17", 35 | "vue-tsc": "0.29.8" 36 | }, 37 | "pkg": { 38 | "outputPath": "packaged" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exa-byte/CCTurtleRemoteController/cba45484f6b299ed9dd8abe6eac720a2d94b8eee/public/favicon.ico -------------------------------------------------------------------------------- /src/App.vue: -------------------------------------------------------------------------------- 1 | 8 | 9 | 13 | 14 | 37 | -------------------------------------------------------------------------------- /src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exa-byte/CCTurtleRemoteController/cba45484f6b299ed9dd8abe6eac720a2d94b8eee/src/assets/logo.png -------------------------------------------------------------------------------- /src/components/BlockNameDisplay.vue: -------------------------------------------------------------------------------- 1 | 14 | 15 | 28 | 29 | 40 | -------------------------------------------------------------------------------- /src/components/CCRemoteController.vue: -------------------------------------------------------------------------------- 1 | 27 | 28 | 48 | 49 | 132 | -------------------------------------------------------------------------------- /src/components/DiscordWidget.vue: -------------------------------------------------------------------------------- 1 | 16 | 17 | 45 | 46 | 63 | -------------------------------------------------------------------------------- /src/components/FuelGauge.vue: -------------------------------------------------------------------------------- 1 | 11 | 12 | 27 | 28 | 45 | -------------------------------------------------------------------------------- /src/components/GenericInventorySlot.vue: -------------------------------------------------------------------------------- 1 | 20 | 21 | 58 | 59 | 60 | 81 | -------------------------------------------------------------------------------- /src/components/Inventory.vue: -------------------------------------------------------------------------------- 1 | 15 | 16 | 30 | 31 | 55 | -------------------------------------------------------------------------------- /src/components/InventorySlot.vue: -------------------------------------------------------------------------------- 1 | 25 | 26 | 71 | 72 | 73 | 116 | -------------------------------------------------------------------------------- /src/components/KeyboardBindings.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 46 | -------------------------------------------------------------------------------- /src/components/LuaTerminal.vue: -------------------------------------------------------------------------------- 1 | 11 | 12 | 29 | 30 | 55 | -------------------------------------------------------------------------------- /src/components/MovementControl.vue: -------------------------------------------------------------------------------- 1 | 36 | 37 | 50 | 51 | 77 | -------------------------------------------------------------------------------- /src/components/Scene.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 342 | -------------------------------------------------------------------------------- /src/components/TurtleInventory.vue: -------------------------------------------------------------------------------- 1 | 21 | 22 | 38 | 39 | 58 | -------------------------------------------------------------------------------- /src/components/TurtlePanel.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 17 | 18 | 45 | -------------------------------------------------------------------------------- /src/env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | declare module '*.vue' { 4 | import type { DefineComponent } from 'vue' 5 | // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types 6 | const component: DefineComponent<{}, {}, any> 7 | export default component 8 | } 9 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { createApp } from 'vue' 2 | import App from './App.vue' 3 | import { createPinia } from 'pinia' 4 | 5 | createApp(App).use(createPinia()).mount('#app') 6 | -------------------------------------------------------------------------------- /src/server/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const cors = require('cors'); 3 | const compression = require('compression') 4 | const { Vector3 } = require('math3d'); 5 | const fs = require('fs'); 6 | const app = express(); 7 | const httpTerminator = require('http-terminator'); 8 | const simpleNodeLogger = require('simple-node-logger'); 9 | const UserManagement = require('./utils/userManagement.js'); 10 | const CommandLineInterface = require('./utils/cmdLineInterface.js'); 11 | 12 | const AUTOSAVE_INTERVAL_MIN = 1; 13 | const TRANSACTION_CACHE_COUNT = 10000; 14 | 15 | fs.mkdirSync('logs', { recursive: true }); 16 | const log = simpleNodeLogger.createSimpleLogger({ 17 | logFilePath: 'logs/server_log.log', 18 | timestampFormat: 'YYYY-MM-DD HH:mm:ss.SSS' 19 | }); 20 | 21 | app.use(cors({ 22 | origin: 'http://localhost:3000' 23 | })); 24 | app.use(express.json()); 25 | app.use(express.static('dist')); 26 | app.use('/turtle', express.static('turtle')); 27 | app.use('/textures', express.static('textures')); 28 | 29 | // API 30 | let state = { 31 | turtle: {}, 32 | world: { 33 | blocks: {}, 34 | }, 35 | lastTransactionId: 0, 36 | lastReadyTransactionId: 0, 37 | } 38 | let transactionCache = {} 39 | let commandResultCache = {} 40 | let cmds = {} 41 | let stopSignal = {} 42 | const userManagement = new UserManagement(); 43 | 44 | const cmdLineInterface = new CommandLineInterface(); 45 | cmdLineInterface.on('users', () => console.log(userManagement.getUserDataString())); 46 | cmdLineInterface.on('deleteTurtle', (id) => delete state.turtle[id]); 47 | 48 | 49 | try { 50 | let fs = require('fs'); 51 | state = JSON.parse(fs.readFileSync('./src/server/saved/saved_state.json', 'utf8')); 52 | state.lastTransactionId = 0; 53 | state.lastReadyTransactionId = 0; 54 | } 55 | catch { } 56 | 57 | // transaction has format : { id: number, blocks: { [locstring] : BlockState | null }} 58 | function applyTransaction(transaction, state, transactionCache) { 59 | for (const [locString, block] of Object.entries(transaction.blocks)) { 60 | if (block) state.world.blocks[locString] = block; 61 | else delete state.world.blocks[locString]; 62 | } 63 | for (const [id, turtleState] of Object.entries(transaction.turtles)) { 64 | state.turtle[id] = turtleState; 65 | } 66 | 67 | // cache transaction 68 | transactionCache[transaction.id] = transaction; 69 | // keep only last TRANSACTION_CACHE_COUNT transactions in cache 70 | if (transactionCache[transaction.id - TRANSACTION_CACHE_COUNT]) delete transactionCache[transaction.id - TRANSACTION_CACHE_COUNT] 71 | } 72 | 73 | function Vec3toString(vec) { 74 | return vec.x + "," + vec.y + "," + vec.z; 75 | } 76 | 77 | function extractState(turtleState, state) { 78 | let loc = new Vector3(turtleState.loc.x, turtleState.loc.y, turtleState.loc.z); 79 | let transaction = { 80 | id: ++state.lastTransactionId, 81 | blocks: {}, 82 | turtles: {}, 83 | } 84 | 85 | transaction.blocks[Vec3toString(loc.add(Vector3.up))] = (turtleState.view.top) ? turtleState.view.top : null; 86 | transaction.blocks[Vec3toString(loc.add(Vector3.down))] = (turtleState.view.bottom) ? turtleState.view.bottom : null; 87 | 88 | let locString; 89 | switch (turtleState.rot) { 90 | case 3: 91 | locString = Vec3toString(loc.add(Vector3.forward)); 92 | break; 93 | case 2: 94 | locString = Vec3toString(loc.add(Vector3.right)); 95 | break; 96 | case 1: 97 | locString = Vec3toString(loc.add(Vector3.back)); 98 | break; 99 | case 0: 100 | locString = Vec3toString(loc.add(Vector3.left)); 101 | break; 102 | default: 103 | log.warn(`error in extractBlockState: rot is invalid (${turtleState.rot})`); 104 | } 105 | transaction.blocks[locString] = (turtleState.view.front) ? turtleState.view.front : null; 106 | transaction.turtles[turtleState.id] = turtleState; 107 | state.lastReadyTransactionId++; 108 | return transaction; 109 | } 110 | 111 | app.use((req, res, next) => { 112 | // console.log('Time: ', new Date(Date.now())); 113 | // console.log(req.method + " " + req.originalUrl) 114 | userManagement.updateLastActive(req.ip); 115 | next(); 116 | }); 117 | 118 | app.get('/api/state', compression(), (req, res) => { 119 | res.send(state); 120 | }); 121 | 122 | app.post('/api/getStateUpdate', compression(), (req, res) => { 123 | const useOldStateUpdateMethod = false; // until the transaction-only update method works bug free, use the old method 124 | if (useOldStateUpdateMethod) { res.send({ state: state }); return; } 125 | // console.log(`${req.body.lastTransactionId} | ${state.lastReadyTransactionId} | ${state.lastTransactionId}`); 126 | // if no remote last transaction is given, send complete state 127 | if (!req.body.lastTransactionId == -1) { 128 | res.send({ state: state }); 129 | log.info(`/api/getStateUpdate : sent full state to ${req.ip}`); 130 | return; 131 | } 132 | // if frontend last transaction > server last transaction, send complete state 133 | if (req.body.lastTransactionId > state.lastReadyTransactionId) { 134 | res.send({ state: state }); 135 | log.info(`/api/getStateUpdate : sent full state to ${req.ip} (server has been restarted inbetween)`); 136 | return; 137 | } 138 | let newTransactionId = req.body.lastTransactionId + 1; 139 | let resJson = { transactions: {} } 140 | // if no further transactions happened since the remote last transaction return empty transaction obj 141 | if (newTransactionId > state.lastTransactionId) { res.send(resJson); return; } 142 | // if transactions are not cached, send complete state 143 | if (!transactionCache[newTransactionId]) { 144 | res.send({ state: state }); 145 | log.info(`/api/getStateUpdate : sent full state to ${req.ip} (transactions not cached)`); 146 | return; 147 | } 148 | // else fill transaction object with all new transactions and send 149 | for (let i = newTransactionId; i <= state.lastReadyTransactionId; i++) { 150 | resJson.transactions[transactionCache[i].id] = transactionCache[i]; 151 | } 152 | res.send(resJson); return; 153 | }); 154 | 155 | app.post('/api/state', (req, res) => { 156 | let s = req.body; 157 | applyTransaction(extractState(s, state), state, transactionCache); 158 | // console.log(s); 159 | res.sendStatus(200) 160 | }); 161 | 162 | app.post('/api/getCommand', (req, res) => { 163 | let s = req.body; 164 | // console.log(s); 165 | // console.log('/api/getCommand'); 166 | if (!cmds[s.id]) { 167 | res.send(); 168 | return; 169 | } 170 | res.send(cmds[s.id].shift()); 171 | }); 172 | 173 | app.post('/api/commandResult', (req, res) => { 174 | let turtleId = req.body.turtleId; 175 | if (!commandResultCache[turtleId]) commandResultCache[turtleId] = []; 176 | commandResultCache[turtleId].push(req.body.result); 177 | res.sendStatus(200) 178 | }); 179 | 180 | app.post('/api/getCommandResult', compression(), (req, res) => { 181 | let turtleId = req.body.turtleId; 182 | if (!commandResultCache[turtleId]) { 183 | res.send({}); 184 | return; 185 | } 186 | if (req.body.getOnlyLatest) { 187 | res.send({ turtleId, result: commandResultCache[turtleId].at(-1) }); 188 | return; 189 | } 190 | let startIndex = req.body.lastReceivedIndex ? req.body.lastReceivedIndex + 1 : 0; 191 | res.send({ turtleId, cmdResults: commandResultCache[turtleId].slice(startIndex) }) 192 | }); 193 | 194 | app.post('/api/setCommand', (req, res) => { 195 | let s = req.body; 196 | if (!cmds[s.id]) cmds[s.id] = [] 197 | cmds[s.id].push(s.cmd); 198 | log.info(`/api/setCommand id=${s.id} req.ip=${req.ip} <${s.cmd}>`); 199 | userManagement.users[req.ip].actionCount++; 200 | res.send({ response: "command set" }) 201 | }); 202 | 203 | app.post('/api/clearCommandQueue', (req, res) => { 204 | let s = req.body; 205 | clearCommandQueue(s.id, req.ip); 206 | res.send({ response: "command queue cleared" }) 207 | }); 208 | 209 | app.get('/api/turtleFileNames', (req, res) => { 210 | fs.readdirSync('turtle') 211 | res.send(fs.readdirSync('turtle')); 212 | }); 213 | 214 | app.post('/api/saveState', (req, res) => { 215 | saveStateToDisk(); 216 | res.sendStatus(200) 217 | }); 218 | 219 | app.post('/api/setStopSignal', (req, res) => { 220 | let json = req.body; 221 | if (isNaN(json.id)) { res.sendStatus(400); return; } 222 | // stopSignal[json.id] = true; 223 | clearCommandQueue(json.id, req.ip); 224 | log.info(`/api/setStopSignal id=${json.id} req.ip=${req.ip}`); 225 | userManagement.users[req.ip].actionCount++; 226 | res.sendStatus(200) 227 | }); 228 | 229 | app.post('/api/getStopSignal', (req, res) => { 230 | let json = req.body; 231 | if (isNaN(json.id)) { res.sendStatus(400); return; } 232 | res.send(stopSignal[json.id] ? true : false); 233 | delete stopSignal[json.id]; 234 | }); 235 | 236 | function clearCommandQueue(id, ip) { 237 | cmds[id] = []; 238 | log.info(`/api/clearCommandQueue id=${id} req.ip=${ip}`); 239 | userManagement.users[ip].actionCount++; 240 | } 241 | 242 | function saveStateToDisk() { 243 | fs.mkdirSync('./src/server/saved', { recursive: true }, (err) => { if (err) throw err; }); 244 | fs.writeFileSync('./src/server/saved/saved_state.json', JSON.stringify(state)); 245 | } 246 | 247 | function autoSave() { 248 | saveStateToDisk(); 249 | userManagement.save(); 250 | setTimeout(() => autoSave(), AUTOSAVE_INTERVAL_MIN * 60 * 1000); 251 | } 252 | 253 | const server = app.listen(80, () => log.info('Turtle remote controller server is listening on port 80.')); 254 | 255 | autoSave(); 256 | 257 | const terminator = httpTerminator.createHttpTerminator({ 258 | gracefulTerminationTimeout: 200, 259 | server, 260 | }); 261 | 262 | process.on('SIGINT', async () => { 263 | await terminator.terminate(); 264 | saveStateToDisk(); 265 | userManagement.save(); 266 | process.exit(0); 267 | }); -------------------------------------------------------------------------------- /src/server/utils/cmdLineInterface.js: -------------------------------------------------------------------------------- 1 | class CommandLineInterface { 2 | readInterface; 3 | commands; 4 | 5 | constructor() { 6 | this.commands = {}; 7 | this.readInterface = require('readline').createInterface({ 8 | input: process.stdin, 9 | output: process.stdout, 10 | }); 11 | 12 | this.readInterface.on('line', (line) => { 13 | const cmd = line.split(' ').at(0); 14 | const args = line.split(' ').slice(1) 15 | if (this.commands[cmd]) this.commands[cmd](...args); 16 | }); 17 | } 18 | 19 | on(name, callback) { 20 | this.commands[name] = callback; 21 | } 22 | } 23 | 24 | module.exports = CommandLineInterface; -------------------------------------------------------------------------------- /src/server/utils/userManagement.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | function getDateDiffString(date1, date2) { 4 | let diff = date1 - date2; 5 | const rtf1 = new Intl.RelativeTimeFormat('en', { style: 'narrow' }); 6 | 7 | const diff_sec = diff / 1000; 8 | 9 | // if diff is smaller than one minute output in seconds 10 | if (-diff_sec < 60) 11 | return rtf1.format(parseInt(diff_sec), 'second'); 12 | else if (-diff_sec < 60 * 60) 13 | return rtf1.format(parseInt(diff_sec / 60), 'minute'); 14 | else if (-diff_sec < 24 * 60 * 60) 15 | return rtf1.format(parseInt(diff_sec / 60 / 60), 'hour'); 16 | else 17 | return rtf1.format(parseInt(diff_sec / 60 / 60 / 24), 'day'); 18 | } 19 | 20 | class UserManagement { 21 | users = {} 22 | saveFile; 23 | 24 | constructor() { 25 | this.saveFile = "./src/server/saved/users.json"; 26 | this.load(); 27 | } 28 | 29 | _createUser(ip) { 30 | this.users[ip] = { 31 | actionCount: 0, 32 | }; 33 | } 34 | updateLastActive(ip) { 35 | if (!this.users[ip]) this._createUser(ip); 36 | this.users[ip].lastActive = Date.now(); 37 | } 38 | validateUsername(username) { 39 | // min of 3 characters, max of 16 40 | if (username.length < 3 || username.length > 16) return 'username length must be >= 3 and <= 16'; 41 | // allow only letters and numbers 42 | if (!/^[A-Za-z0-9]*$/.test(username)) return 'only a-Z and 0-9 characters allowed'; 43 | return true; 44 | } 45 | setUsername(ip, username) { 46 | // check for username allowed characters 47 | const result = this.validateUsername(username) 48 | if (result !== true) return result; 49 | 50 | // check if it already exists 51 | for (const [_, v] of Object.entries(this.users)) 52 | if (username === v.username) 53 | return 'username already taken'; 54 | 55 | this.users[ip].username = username; 56 | return true; 57 | } 58 | getUsername(ip) { 59 | if (!this.users[ip]) return false; 60 | return this.users[ip].username; 61 | } 62 | getUserDataList() { 63 | return this.users; 64 | } 65 | getUserDataString() { 66 | let list = [] 67 | for (const [ip, user] of Object.entries(this.users)) { 68 | let el = Object.assign({}, user); 69 | el.ip = ip; 70 | list.push(el) 71 | } 72 | list.sort((a, b) => (a.lastActive > b.lastActive) ? 1 : -1) 73 | let str = ""; 74 | for (const user of list) { 75 | const usernameStr = user.username ? `\t, username: ${user.username}` : ""; 76 | str += `{ '${user.ip}': { lastActive: ${getDateDiffString(user.lastActive, Date.now())}\t, actionCount: ${user.actionCount}${usernameStr} } }\n`; 77 | } 78 | return str; 79 | } 80 | save() { 81 | fs.mkdirSync('./src/server/saved', { recursive: true }, (err) => { if (err) throw err; }); 82 | fs.writeFileSync(this.saveFile, JSON.stringify(this.users)); 83 | } 84 | load() { 85 | try { 86 | this.users = JSON.parse(fs.readFileSync(this.saveFile, 'utf8')); 87 | } 88 | catch { } 89 | } 90 | } 91 | 92 | module.exports = UserManagement; -------------------------------------------------------------------------------- /src/store/useWorld.ts: -------------------------------------------------------------------------------- 1 | import { defineStore } from 'pinia' 2 | import { TurtleState, Block } from '../types/types'; 3 | import { useWorldViewStore } from './useWorldView'; 4 | 5 | // you have to set this to "http://localhost/" or "http:///" 6 | // (if you use public ip you also have to forward port 3000) if you want to develop using rpm run dev 7 | // after developing you can reset it to an empty string or this might cause you a headache if you switch from localhost to public ip hosting 8 | const url = "" 9 | 10 | export const useWorldStore = defineStore('world', { 11 | state: () => ({ 12 | turtles: {} as { [id: string]: TurtleState; }, 13 | blocks: {} as { [locString: string]: Block; }, 14 | commandResult: {} as { [id: string]: string; }, 15 | URL: `${url}`, 16 | apiURL: `${url}api/`, 17 | textureURL: `${url}textures/`, 18 | lastTransactionId: -1, 19 | isLoading: true, 20 | }), 21 | getters: { 22 | getTurtleIds(): number[] { 23 | return Object.keys(this.turtles).map(key => Number(key)); 24 | }, 25 | }, 26 | actions: { 27 | setTurtleStatus(remoteTurtleState: any) { 28 | 29 | for (let id in remoteTurtleState) { 30 | let turtleState = remoteTurtleState[id]; 31 | if (!this.turtles[id]) { 32 | const worldView = useWorldViewStore(); 33 | worldView.selectedTurtleId = parseInt(id); 34 | } 35 | this.turtles[id] = turtleState; 36 | this.turtles[id].modified = Date.now(); 37 | 38 | // replace 0s in inv with null 39 | for (let i = 0; i < turtleState.inv.length; i++) 40 | if (turtleState.inv[i] === 0) turtleState.inv[i] = undefined; 41 | } 42 | }, 43 | transactionRemoveBlock(locString: string) { 44 | const worldView = useWorldViewStore(); 45 | worldView.removeBlock(locString); 46 | delete this.blocks[locString]; 47 | }, 48 | transactionAddBlock(locString: string, block: Block) { 49 | const worldView = useWorldViewStore(); 50 | worldView.removeBlock(locString); 51 | this.blocks[locString] = block; 52 | worldView.addBlock(locString, block); 53 | }, 54 | transactionSetTurtleState(turtleState: any) { 55 | this.setTurtleStatus(turtleState); 56 | const worldView = useWorldViewStore(); 57 | for (const id of Object.keys(turtleState)) { 58 | worldView.updateTurtle(id); 59 | } 60 | }, 61 | applyTransactions(transactions: any) { 62 | let currTransactionId = this.lastTransactionId; 63 | const len = Object.keys(transactions).length 64 | for (let i = 0; i < len; i++) { 65 | currTransactionId++; 66 | const t = transactions[currTransactionId]; 67 | for (const [locString, block] of Object.entries(t.blocks)) { 68 | if (block) { 69 | this.transactionAddBlock(locString, block as Block); 70 | } 71 | else this.transactionRemoveBlock(locString); 72 | } 73 | this.transactionSetTurtleState(t.turtles); 74 | this.lastTransactionId = currTransactionId; 75 | } 76 | }, 77 | sendCommand(turtleId: number, cmd: string) { 78 | fetch(this.apiURL + "setCommand", { 79 | method: 'POST', 80 | mode: "cors", 81 | headers: { 82 | "Access-Control-Allow-Origin": "*", 83 | 'Content-Type': 'application/json', 84 | }, 85 | body: JSON.stringify({ id: turtleId, cmd: cmd }), 86 | }) 87 | .then((res) => res.json()) 88 | .then((data) => { 89 | console.log(data); 90 | }); 91 | }, 92 | sendStopSignal(turtleId: number) { 93 | fetch(this.apiURL + "setStopSignal", { 94 | method: 'POST', 95 | mode: "cors", 96 | headers: { 97 | "Access-Control-Allow-Origin": "*", 98 | 'Content-Type': 'application/json', 99 | }, 100 | body: JSON.stringify({ id: turtleId }), 101 | }) 102 | .then((res) => res.json()) 103 | .then((data) => { 104 | console.log(data); 105 | }); 106 | }, 107 | clearCommandQueue(turtleId: number) { 108 | fetch(this.apiURL + "clearCommandQueue", { 109 | method: 'POST', 110 | mode: "cors", 111 | headers: { 112 | "Access-Control-Allow-Origin": "*", 113 | 'Content-Type': 'application/json', 114 | }, 115 | body: JSON.stringify({ id: turtleId }), 116 | }) 117 | .then((res) => res.json()) 118 | .then((data) => { 119 | console.log(data); 120 | }); 121 | }, 122 | getBlockByObjPosition(pos: THREE.Vector3) { 123 | return this.blocks[pos.x + "," + pos.y + "," + pos.z]; 124 | }, 125 | }, 126 | }) -------------------------------------------------------------------------------- /src/store/useWorldView.ts: -------------------------------------------------------------------------------- 1 | import { defineStore } from 'pinia' 2 | import * as THREE from "three"; 3 | import { Block, Inventory } from '../types/types'; 4 | import { useWorldStore } from './useWorld'; 5 | 6 | const BIOME_TINT = 0x88C149; 7 | 8 | export const useWorldViewStore = defineStore('worldView', { 9 | state: () => ({ 10 | regenerateSceneFromBlocks: () => { }, 11 | render: () => { }, 12 | setCameraFocus: (target: THREE.Vector3) => { }, 13 | focusOnTurtle: (turtleId: number) => { }, 14 | addBlock: (locString: string, block: Block) => { }, 15 | removeBlock: (locString: string) => { }, 16 | updateTurtle: (turtleId: string) => { }, 17 | addAnimatedTexture: (texture: THREE.Texture) => { }, 18 | followedTurtle: { 19 | turtleId: -1 as number, 20 | lastPos: {} as { x: number, y: number, z: number } 21 | }, 22 | materials: {} as { [id: string]: THREE.MeshPhongMaterial; }, 23 | hoveredBlock: null as Block | null, 24 | hoveredBlockPos: null as THREE.Vector3 | null, 25 | gotoBlockPos: null as THREE.Vector3 | null, 26 | selectedTurtleId: -1 as number, 27 | turtles: {} as { [id: string]: THREE.Object3D; }, 28 | selectedInventory: null as Inventory | null, 29 | selectedInventorySize: 0 as number, 30 | blockTint: { 31 | "minecraft:water": 0x1e97f2, 32 | "minecraft:grass": BIOME_TINT, 33 | "minecraft:tall_grass": BIOME_TINT, 34 | "minecraft:grass_block": BIOME_TINT, 35 | "minecraft:acacia_leaves": BIOME_TINT, 36 | "minecraft:birch_leaves": 0x80a755, 37 | "minecraft:dark_oak_leaves": BIOME_TINT, 38 | "minecraft:jungle_leaves": BIOME_TINT, 39 | "minecraft:oak_leaves": BIOME_TINT, 40 | "minecraft:spruce_leaves": 0x619961, 41 | "minecraft:fern": BIOME_TINT, 42 | "minecraft:large_fern": BIOME_TINT, 43 | "minecraft:vine": BIOME_TINT, 44 | "minecraft:lily_pad": BIOME_TINT, 45 | "biomesoplenty:bush": BIOME_TINT, 46 | "biomesoplenty:clover": BIOME_TINT, 47 | "biomesoplenty:sprout": BIOME_TINT, 48 | "biomesoplenty:flowering_oak_leaves": BIOME_TINT, 49 | "biomesoplenty:mahogany_leaves": BIOME_TINT, 50 | "biomesoplenty:willow_leaves": BIOME_TINT, 51 | "biomesoplenty:willow_vine": BIOME_TINT, 52 | } as { [id: string]: number; }, 53 | geometryMap: { 54 | "biomesoplenty:bush": "cross", 55 | "biomesoplenty:toadstool": "cross", 56 | "biomesoplenty:reed": "cross", 57 | "biomesoplenty:clover": "cross", 58 | "biomesoplenty:goldenrod": "cross", 59 | "biomesoplenty:sprout": "cross", 60 | "biomesoplenty:mangrove_root": "cross", 61 | "biomesoplenty:spanish_moss": "cross", 62 | "biomesoplenty:cattail": "cross", 63 | "biomesoplenty:willow_vine": "cross", 64 | "biomesoplenty:glowshroom": "cross", 65 | "biomesoplenty:orange_cosmos": "cross", 66 | "biomesoplenty:pink_daffodil": "cross", 67 | "minecraft:cobweb": "cross", 68 | "minecraft:oak_sapling": "cross", 69 | "minecraft:brown_mushroom": "cross", 70 | "minecraft:red_mushroom": "cross", 71 | "minecraft:sugar_cane": "cross", 72 | "minecraft:dead_bush": "cross", 73 | "minecraft:fern": "cross", 74 | "minecraft:large_fern": "cross", 75 | "minecraft:grass": "cross", 76 | "minecraft:tall_grass": "cross", 77 | "minecraft:vine": "cross", 78 | "minecraft:dandelion": "cross", 79 | "minecraft:lilac": "cross", 80 | "minecraft:poppy": "cross", 81 | "minecraft:allium": "cross", 82 | "minecraft:rose": "cross", 83 | "minecraft:rose_bush": "cross", 84 | "minecraft:lily_of_the_valley": "cross", 85 | "minecraft:azure_bluet": "cross", 86 | "minecraft:blue_orchid": "cross", 87 | "minecraft:oxeye_daisy": "cross", 88 | "minecraft:white_tulip": "cross", 89 | "minecraft:sunflower": "cross", 90 | "minecraft:cornflower": "cross", 91 | "minecraft:peony": "cross", 92 | "quark:root": "cross", 93 | } as { [blockId: string]: string }, 94 | }), 95 | getters: { 96 | 97 | }, 98 | actions: { 99 | getBlockMaterial(id: string) { 100 | if (!this.materials[id]) { 101 | this.materials[id] = new THREE.MeshPhongMaterial({ 102 | color: Math.floor(Math.random() * 0xff00ff), 103 | }); 104 | const loader = new THREE.TextureLoader(); 105 | const world = useWorldStore(); 106 | loader.load( 107 | // resource URL 108 | world.textureURL + `blocks/${id.replace(':', '/')}.png`, 109 | 110 | // onLoad callback 111 | (texture) => { 112 | texture.minFilter = THREE.NearestFilter; 113 | texture.magFilter = THREE.NearestFilter; 114 | this.materials[id].map = texture; 115 | this.materials[id].color.setHex(0xffffff); 116 | const tint = this.blockTint[id]; 117 | if (tint) this.materials[id].color.setHex(tint); 118 | if (this.geometryMap[id] === "cross" || id.includes("leaves") || id.includes("sapling") || id.includes("kelp") || id.includes("seagrass")) 119 | this.materials[id].alphaTest = 1; 120 | if (this.geometryMap[id] === "cross" || id.includes("sapling") || id.includes("kelp") || id.includes("seagrass")) 121 | this.materials[id].side = THREE.DoubleSide; 122 | if (texture.image.width !== texture.image.height) 123 | this.addAnimatedTexture(texture); 124 | // this.materials[id].transparent = true; 125 | // this.materials[id].opacity = .5; 126 | this.materials[id].needsUpdate = true; 127 | }, 128 | 129 | // onProgress callback currently not supported 130 | undefined, 131 | 132 | // onError callback 133 | (err) => { 134 | console.log(`No block texture found for ${id}`); 135 | } 136 | ); 137 | } 138 | return this.materials[id]; 139 | }, 140 | followTurtle(turtleId: number) { 141 | if (turtleId === this.followedTurtle.turtleId) turtleId = -1; 142 | this.followedTurtle.turtleId = turtleId; 143 | if (turtleId === -1) return; 144 | const world = useWorldStore(); 145 | this.followedTurtle.lastPos = world.turtles[turtleId].loc; 146 | this.focusOnTurtle(turtleId); 147 | }, 148 | }, 149 | }) -------------------------------------------------------------------------------- /src/turtlePrograms/miningTunnel2.lua: -------------------------------------------------------------------------------- 1 | --- Given a block's data, returns true if it's a treasure 2 | -- @return Boolean of whether it's a treasure 3 | function isTreasure(block) 4 | return block.name:find('ore') 5 | end 6 | 7 | --- Calculate the destination coordinate from current pos, orientation, and desired turn 8 | -- This calculation is RELATIVE and doesn't correspond with Minecraft's F3 coordinates 9 | -- @param Table xyz Table of coordinates {x,y,z} of the starting point 10 | -- @param String orientation The cardinal direction you face at the starting point 11 | -- @param String direction The direction (e.g. left, right, up) you would turn and proceed into 12 | -- @return { {x, y, z}, orientation } of destination 13 | function calcDest(xyz, orientation, direction) 14 | local dest = { 15 | x = xyz['x'], 16 | y = xyz['y'], 17 | z = xyz['z'] 18 | } 19 | if direction == 'up' then 20 | dest['y'] = dest['y'] + 1 21 | elseif direction == 'down' then 22 | dest['y'] = dest['y'] - 1 23 | else 24 | local cardinals = { 25 | north = 0, 26 | west = 1, 27 | south = 2, 28 | east = 3 29 | } 30 | local cardinalsReverse = { 31 | [0] = 'north', 32 | 'west', 33 | 'south', 34 | 'east' 35 | } 36 | local leftTurns = { 37 | front = 0, 38 | left = 1, 39 | back = 2, 40 | right = 3 41 | } 42 | orientation = cardinalsReverse[(cardinals[orientation] + leftTurns[direction]) % 4] 43 | if orientation == 'north' then 44 | dest['z'] = dest['z'] + 1 45 | elseif orientation == 'south' then 46 | dest['z'] = dest['z'] - 1 47 | elseif orientation == 'east' then 48 | dest['x'] = dest['x'] + 1 49 | elseif orientation == 'west' then 50 | dest['x'] = dest['x'] - 1 51 | end 52 | end 53 | return {dest, orientation} 54 | end 55 | 56 | --- Test if a table of {x,y,z}s contains a certain {x,y,z} 57 | -- @param Table table table to search within 58 | -- @param Table xyz xyz to search for 59 | -- @return Boolean of whether the table has the xyz 60 | function contains(table, xyz) 61 | for _, v in ipairs(table) do 62 | if v['x'] == xyz['x'] and v['y'] == xyz['y'] and v['z'] == xyz['z'] then 63 | return true 64 | end 65 | end 66 | return false 67 | end 68 | 69 | --- Master function for mining a vein of treasures as if it were a graph 70 | -- with each block as a node and the directions you can travel from that block as edges 71 | -- When beginning to mine, assumes whatever orientation the turtle is facing as "north" 72 | -- and wherever it started mining as {0, 0, 0} xyz 73 | function mineVein() 74 | mineVeinHelper({ 75 | x = 0, 76 | y = 0, 77 | z = 0 78 | }, 'north', {}) 79 | end 80 | 81 | --- Recursive helper function for mining a vein of treasures (blocks) 82 | -- using the graph traversal method 83 | -- @param Table xyz Current location {x,y,z} of turtle 84 | -- @param String orientation Current orientation of turtle 85 | -- @param Table traversed Table of tables {x,y,z} of visited blocks 86 | function mineVeinHelper(xyz, orientation, traversed) 87 | for _, direction in ipairs({'up', 'down', 'front', 'back', 'left', 'right'}) do 88 | local destination, newOrientation = table.unpack(calcDest(xyz, orientation, direction)) 89 | if not contains(traversed, destination) then 90 | if direction ~= 'back' then 91 | table.insert(traversed, destination) 92 | end 93 | 94 | if direction == 'up' then 95 | local success, data = turtle.inspectUp() 96 | if success and isTreasure(data) then 97 | tapi.digUpRepeat() 98 | tapi.up() 99 | mineVeinHelper(destination, newOrientation, traversed); 100 | tapi.down() 101 | end 102 | elseif direction == 'down' then 103 | local success, data = turtle.inspectDown() 104 | if success and isTreasure(data) then 105 | tapi.digDownRepeat() 106 | tapi.down() 107 | mineVeinHelper(destination, newOrientation, traversed); 108 | tapi.up() 109 | end 110 | elseif direction == 'back' then 111 | local leftOrient = orientation 112 | for i = 1, 3 do 113 | local calculated = calcDest(xyz, leftOrient, 'left') 114 | local leftDest = calculated[1] 115 | leftOrient = calculated[2] 116 | tapi.left() 117 | table.insert(traversed, leftDest) 118 | local success, data = turtle.inspect() 119 | if success and isTreasure(data) then 120 | tapi.digRepeat() 121 | tapi.forward() 122 | mineVeinHelper(leftDest, leftOrient, traversed); 123 | tapi.back() 124 | end 125 | end 126 | tapi.left() 127 | else 128 | -- turn in the direction to inspect 129 | if direction == 'left' then 130 | tapi.left() 131 | elseif direction == 'right' then 132 | tapi.right() 133 | end 134 | -- inspect the block 135 | local success, data = turtle.inspect() 136 | if success and isTreasure(data) then 137 | tapi.digRepeat() 138 | tapi.forward() 139 | mineVeinHelper(destination, newOrientation, traversed); 140 | tapi.back() 141 | end 142 | -- unturn to face forwards again 143 | if direction == 'left' then 144 | tapi.right() 145 | elseif direction == 'right' then 146 | tapi.left() 147 | end 148 | end 149 | end 150 | end 151 | end 152 | 153 | local function miningOp(i) 154 | tapi.digRepeat() 155 | tapi.forward() 156 | mineVein() 157 | tapi.digUpRepeat() 158 | if tapi.selectItem("minecraft:cobblestone") or tapi.selectItem("quark:cobbled_deepslate") then 159 | tapi.placeDown() 160 | tapi.select(1) 161 | end 162 | if i % 12 == 0 then 163 | tapi.right(2) 164 | tapi.selectItem("minecraft:torch") 165 | tapi.place() 166 | tapi.right(2) 167 | tapi.select(1) 168 | end 169 | end 170 | 171 | for j = 1, 2 do 172 | for i = 0, 99 do 173 | miningOp(i) 174 | end 175 | tapi.right() 176 | for i = 0, 3 do 177 | miningOp(i) 178 | end 179 | tapi.right() 180 | end 181 | -------------------------------------------------------------------------------- /src/turtlePrograms/miningTunnel3.lua: -------------------------------------------------------------------------------- 1 | --- Given a block's data, returns true if it's a treasure 2 | -- @return Boolean of whether it's a treasure 3 | function isTreasure(block) 4 | return block.name:find('ore') 5 | end 6 | 7 | --- Calculate the destination coordinate from current pos, orientation, and desired turn 8 | -- This calculation is RELATIVE and doesn't correspond with Minecraft's F3 coordinates 9 | -- @param Table xyz Table of coordinates {x,y,z} of the starting point 10 | -- @param String orientation The cardinal direction you face at the starting point 11 | -- @param String direction The direction (e.g. left, right, up) you would turn and proceed into 12 | -- @return { {x, y, z}, orientation } of destination 13 | function calcDest(xyz, orientation, direction) 14 | local dest = { 15 | x = xyz['x'], 16 | y = xyz['y'], 17 | z = xyz['z'] 18 | } 19 | if direction == 'up' then 20 | dest['y'] = dest['y'] + 1 21 | elseif direction == 'down' then 22 | dest['y'] = dest['y'] - 1 23 | else 24 | local cardinals = { 25 | north = 0, 26 | west = 1, 27 | south = 2, 28 | east = 3 29 | } 30 | local cardinalsReverse = { 31 | [0] = 'north', 32 | 'west', 33 | 'south', 34 | 'east' 35 | } 36 | local leftTurns = { 37 | front = 0, 38 | left = 1, 39 | back = 2, 40 | right = 3 41 | } 42 | orientation = cardinalsReverse[(cardinals[orientation] + leftTurns[direction]) % 4] 43 | if orientation == 'north' then 44 | dest['z'] = dest['z'] + 1 45 | elseif orientation == 'south' then 46 | dest['z'] = dest['z'] - 1 47 | elseif orientation == 'east' then 48 | dest['x'] = dest['x'] + 1 49 | elseif orientation == 'west' then 50 | dest['x'] = dest['x'] - 1 51 | end 52 | end 53 | return {dest, orientation} 54 | end 55 | 56 | --- Test if a table of {x,y,z}s contains a certain {x,y,z} 57 | -- @param Table table table to search within 58 | -- @param Table xyz xyz to search for 59 | -- @return Boolean of whether the table has the xyz 60 | function contains(table, xyz) 61 | for _, v in ipairs(table) do 62 | if v['x'] == xyz['x'] and v['y'] == xyz['y'] and v['z'] == xyz['z'] then 63 | return true 64 | end 65 | end 66 | return false 67 | end 68 | 69 | --- Master function for mining a vein of treasures as if it were a graph 70 | -- with each block as a node and the directions you can travel from that block as edges 71 | -- When beginning to mine, assumes whatever orientation the turtle is facing as "north" 72 | -- and wherever it started mining as {0, 0, 0} xyz 73 | function mineVein() 74 | mineVeinHelper({ 75 | x = 0, 76 | y = 0, 77 | z = 0 78 | }, 'north', {}) 79 | end 80 | 81 | --- Recursive helper function for mining a vein of treasures (blocks) 82 | -- using the graph traversal method 83 | -- @param Table xyz Current location {x,y,z} of turtle 84 | -- @param String orientation Current orientation of turtle 85 | -- @param Table traversed Table of tables {x,y,z} of visited blocks 86 | function mineVeinHelper(xyz, orientation, traversed) 87 | for _, direction in ipairs({'up', 'down', 'front', 'back', 'left', 'right'}) do 88 | local destination, newOrientation = table.unpack(calcDest(xyz, orientation, direction)) 89 | if not contains(traversed, destination) then 90 | if direction ~= 'back' then 91 | table.insert(traversed, destination) 92 | end 93 | 94 | if direction == 'up' then 95 | local success, data = turtle.inspectUp() 96 | if success and isTreasure(data) then 97 | tapi.digUpRepeat() 98 | tapi.up() 99 | mineVeinHelper(destination, newOrientation, traversed); 100 | tapi.down() 101 | end 102 | elseif direction == 'down' then 103 | local success, data = turtle.inspectDown() 104 | if success and isTreasure(data) then 105 | tapi.digDownRepeat() 106 | tapi.down() 107 | mineVeinHelper(destination, newOrientation, traversed); 108 | tapi.up() 109 | end 110 | elseif direction == 'back' then 111 | local leftOrient = orientation 112 | for i = 1, 3 do 113 | local calculated = calcDest(xyz, leftOrient, 'left') 114 | local leftDest = calculated[1] 115 | leftOrient = calculated[2] 116 | tapi.left() 117 | table.insert(traversed, leftDest) 118 | local success, data = turtle.inspect() 119 | if success and isTreasure(data) then 120 | tapi.digRepeat() 121 | tapi.forward() 122 | mineVeinHelper(leftDest, leftOrient, traversed); 123 | tapi.back() 124 | end 125 | end 126 | tapi.left() 127 | else 128 | -- turn in the direction to inspect 129 | if direction == 'left' then 130 | tapi.left() 131 | elseif direction == 'right' then 132 | tapi.right() 133 | end 134 | -- inspect the block 135 | local success, data = turtle.inspect() 136 | if success and isTreasure(data) then 137 | tapi.digRepeat() 138 | tapi.forward() 139 | mineVeinHelper(destination, newOrientation, traversed); 140 | tapi.back() 141 | end 142 | -- unturn to face forwards again 143 | if direction == 'left' then 144 | tapi.right() 145 | elseif direction == 'right' then 146 | tapi.left() 147 | end 148 | end 149 | end 150 | end 151 | end 152 | 153 | local function miningOp(i) 154 | tapi.digRepeat() 155 | tapi.forward() 156 | mineVein() 157 | tapi.digUpRepeat() 158 | if tapi.selectItem("minecraft:cobblestone") or tapi.selectItem("quark:cobbled_deepslate") then 159 | tapi.placeDown() 160 | tapi.select(1) 161 | end 162 | if (i % 12 + 11) == 0 then 163 | tapi.right(2) 164 | tapi.selectItem("minecraft:torch") 165 | tapi.place() 166 | tapi.right(2) 167 | tapi.select(1) 168 | end 169 | end 170 | 171 | local function isInventoryEmpty() 172 | for i=1,16 do 173 | if turtle.getItemCount > 0 then return false end 174 | end 175 | return true 176 | end 177 | 178 | local function getChestFreeSlotCount(side) 179 | side = side or "front" 180 | local p = peripheral.wrap(side) 181 | if not p then return false end 182 | local slots = p.list() 183 | if not slots then return 0 end 184 | local freeSlots = 0 185 | for i,stack in pairs(slots) do 186 | if not stack then freeSlots = freeSlots + 1 end 187 | end 188 | return freeSlots 189 | end 190 | 191 | local function dropOresIntoChest() 192 | for i=1,16 do 193 | while getChestFreeSlotCount("front") == 0 do tapi.up() end 194 | local stack = turtle.getItemDetail(i) 195 | if stack and stack.name ~= "minecraft:torch" then 196 | tapi.select(i) 197 | tapi.drop() 198 | end 199 | end 200 | end 201 | 202 | local function dropCrapIntoChest() 203 | while not isInventoryEmpty() do 204 | for i=1,16 do 205 | while getChestFreeSlotCount("front") == 0 do tapi.up() end 206 | local stack = turtle.getItemDetail(i) 207 | print(stack and stack.name) 208 | if stack and ( 209 | stack.name:match("minecraft:cobblestone") or 210 | stack.name:match("projectred-exploration:marble") or 211 | stack.name:match("minecraft:gravel") or 212 | stack.name:match("minecraft:dirt") or 213 | stack.name:match("quark:smooth_basalt") or 214 | stack.name:match("quark:cobbled_deepslate") 215 | ) then 216 | tapi.select(i) 217 | tapi.drop() 218 | end 219 | end 220 | end 221 | end 222 | 223 | local function dropOffItems(i) 224 | local k = 0 225 | print("dropping off items") 226 | local old_pos = tapi.loc_internal 227 | local old_heading = tapi.loc_internal.h 228 | print(old_pos:tostring()) 229 | tapi.up(1, true) 230 | tapi.left(2) 231 | tapi.forward(i, true) 232 | tapi.right() 233 | local _, block 234 | repeat 235 | tapi.f(1, true) 236 | k = k + 1 237 | _, block = turtle.inspect() 238 | until block and block.name == "minecraft:cobblestone" 239 | tapi.left() 240 | tapi.down(1, true) 241 | tapi.forward(1, true) 242 | dropCrapIntoChest() 243 | tapi.right() 244 | tapi.forward(1, true) 245 | repeat tapi.down() until turtle.detectDown() 246 | tapi.right() 247 | tapi.forward(2, true) 248 | tapi.right() 249 | tapi.forward(1, true) 250 | tapi.left() 251 | dropOresIntoChest() 252 | tapi.right(2) 253 | tapi.forward(1, true) 254 | repeat tapi.down() until turtle.detectDown() 255 | tapi.left() 256 | tapi.forward(k, true) 257 | tapi.turnTo(old_heading) 258 | tapi.up(1, true) 259 | tapi.forward(i, true) 260 | tapi.down(1, true) 261 | end 262 | 263 | local function unloadIsNeeded() 264 | for i=1,16 do 265 | if turtle.getItemCount(i) == 0 then return false end 266 | end 267 | return true 268 | end 269 | 270 | local function unloadIfNeeded(i) 271 | if unloadIsNeeded() then dropOffItems(i) end 272 | end 273 | 274 | local start_pos = tapi.loc_internal; 275 | print("startPos="..start_pos:tostring()) 276 | local length = 250 277 | for i = 1, length do 278 | miningOp(i) 279 | unloadIfNeeded(i) 280 | end 281 | tapi.right(2) 282 | tapi.up(1, true) 283 | tapi.forward(length, true) 284 | tapi.down(1, true) 285 | tapi.right(2) 286 | dropOffItems(0) -------------------------------------------------------------------------------- /src/turtlePrograms/placeNewTurtle.lua: -------------------------------------------------------------------------------- 1 | local valid_turtle_ids = { 2 | "computercraft:turtle_normal", 3 | "computercraft:turtle_advanced" 4 | } 5 | 6 | local found = false 7 | for _,id in pairs(valid_turtle_ids) do 8 | if tapi.selectItem(id) then found = true; break end 9 | end 10 | if not found then return false end 11 | 12 | if not tapi.placeUp() then return false end 13 | 14 | local p = peripheral.wrap("top") 15 | if not p then return false end 16 | p.turnOn() 17 | 18 | -- TODO: use disk drive to automatically configure other turtle -------------------------------------------------------------------------------- /src/turtlePrograms/randomExplore.lua: -------------------------------------------------------------------------------- 1 | -- turtle.suck(25); 2 | -- turtle.refuel(); 3 | while true do 4 | while not tapi.down() do 5 | dir = math.random(1, 5) 6 | print(dir) 7 | if dir == 1 then tapi.forward() end 8 | if dir == 2 then tapi.left() end 9 | if dir == 3 then tapi.right() end 10 | if dir == 4 then 11 | while tapi.forward() do end 12 | tapi.up(); 13 | end 14 | if dir == 5 then 15 | while not tapi.forward() do 16 | local succ = tapi.up(); 17 | if not succ then break end 18 | end 19 | end 20 | end 21 | end -------------------------------------------------------------------------------- /src/turtlePrograms/skynetExpander.lua: -------------------------------------------------------------------------------- 1 | -- skynet expander 2 | 3 | -- check for enough materials 4 | if not (tapi.contains_items("computercraft:turtle_normal", 1) or tapi.contains_items("computercraft:turtle_normal", 1)) then 5 | return "need at least one turtle in inventory" end 6 | if not tapi.contains_items("computercraft:disk") then 7 | return "need at least one computercraft:disk in inventory" end 8 | if not tapi.contains_items("computercraft:disk_drive") then 9 | return "need at least one computercraft:disk_drive in inventory" end 10 | 11 | -- check space 12 | if not tapi.u(2) then return "need at least two free spaces above start position" end 13 | if not tapi.d(1) then return "something blocked the space below, try again" end 14 | 15 | -- place disk drive 16 | tapi.selectItem("computercraft:disk_drive") 17 | if not tapi.placeDown() then return "could not place down disk drive" end 18 | tapi.selectItem("computercraft:disk") 19 | if not tapi.dropDown() then return "could not drop down disk into disk drive" end 20 | 21 | -- copy relevant files onto floppy 22 | fs.delete("disk/_startup") 23 | fs.delete("disk/loc.sav") 24 | fs.delete("disk/startup") 25 | fs.copy("backup/startup", "disk/_startup") 26 | fs.copy("loc.sav", "disk/loc.sav") 27 | fs.copy("diskboot", "disk/startup") 28 | 29 | -- move up and place turtle 30 | if not tapi.u(1) then return "something blocked the space above, try again" end 31 | tapi.select(tapi.findItemFuzzy("turtle")) 32 | if not tapi.placeDown() then return "could not place down turtle" end 33 | 34 | -- turn turtle on 35 | local p 36 | while not p do p = peripheral.wrap("bottom") end 37 | p.turnOn() 38 | 39 | return true -------------------------------------------------------------------------------- /src/turtlePrograms/stairsToLava.lua: -------------------------------------------------------------------------------- 1 | local i = 0 2 | while true do 3 | tapi.digUp() 4 | tapi.digDown() 5 | tapi.down() 6 | if tapi.selectItem("minecraft:cobblestone") then 7 | tapi.placeDown() 8 | end 9 | tapi.dig() 10 | tapi.forward() 11 | 12 | -- place torch every 6 blocks 13 | if i % 6 == 0 then 14 | tapi.right(2) 15 | tapi.selectItem("minecraft:torch") 16 | tapi.place() 17 | tapi.right(2) 18 | end 19 | if tapi.getLoc().y == 13 then break end 20 | i = i + 1 21 | end -------------------------------------------------------------------------------- /src/turtlePrograms/treeMiner.lua: -------------------------------------------------------------------------------- 1 | --- Given a block's data, returns true if it's a treasure 2 | -- @return Boolean of whether it's a treasure 3 | function isTreasure(block) 4 | return block.name:find('log') or block.name:find('leaves') 5 | end 6 | 7 | --- Calculate the destination coordinate from current pos, orientation, and desired turn 8 | -- This calculation is RELATIVE and doesn't correspond with Minecraft's F3 coordinates 9 | -- @param Table xyz Table of coordinates {x,y,z} of the starting point 10 | -- @param String orientation The cardinal direction you face at the starting point 11 | -- @param String direction The direction (e.g. left, right, up) you would turn and proceed into 12 | -- @return { {x, y, z}, orientation } of destination 13 | function calcDest(xyz, orientation, direction) 14 | local dest = { 15 | x = xyz['x'], 16 | y = xyz['y'], 17 | z = xyz['z'] 18 | } 19 | if direction == 'up' then 20 | dest['y'] = dest['y'] + 1 21 | elseif direction == 'down' then 22 | dest['y'] = dest['y'] - 1 23 | else 24 | local cardinals = { 25 | north = 0, 26 | west = 1, 27 | south = 2, 28 | east = 3 29 | } 30 | local cardinalsReverse = { 31 | [0] = 'north', 32 | 'west', 33 | 'south', 34 | 'east' 35 | } 36 | local leftTurns = { 37 | front = 0, 38 | left = 1, 39 | back = 2, 40 | right = 3 41 | } 42 | orientation = cardinalsReverse[(cardinals[orientation] + leftTurns[direction]) % 4] 43 | if orientation == 'north' then 44 | dest['z'] = dest['z'] + 1 45 | elseif orientation == 'south' then 46 | dest['z'] = dest['z'] - 1 47 | elseif orientation == 'east' then 48 | dest['x'] = dest['x'] + 1 49 | elseif orientation == 'west' then 50 | dest['x'] = dest['x'] - 1 51 | end 52 | end 53 | return {dest, orientation} 54 | end 55 | 56 | --- Test if a table of {x,y,z}s contains a certain {x,y,z} 57 | -- @param Table table table to search within 58 | -- @param Table xyz xyz to search for 59 | -- @return Boolean of whether the table has the xyz 60 | function contains(table, xyz) 61 | for _, v in ipairs(table) do 62 | if v['x'] == xyz['x'] and v['y'] == xyz['y'] and v['z'] == xyz['z'] then 63 | return true 64 | end 65 | end 66 | return false 67 | end 68 | 69 | --- Master function for mining a vein of treasures as if it were a graph 70 | -- with each block as a node and the directions you can travel from that block as edges 71 | -- When beginning to mine, assumes whatever orientation the turtle is facing as "north" 72 | -- and wherever it started mining as {0, 0, 0} xyz 73 | function mineVein() 74 | mineVeinHelper({ 75 | x = 0, 76 | y = 0, 77 | z = 0 78 | }, 'north', {}) 79 | end 80 | 81 | --- Recursive helper function for mining a vein of treasures (blocks) 82 | -- using the graph traversal method 83 | -- @param Table xyz Current location {x,y,z} of turtle 84 | -- @param String orientation Current orientation of turtle 85 | -- @param Table traversed Table of tables {x,y,z} of visited blocks 86 | function mineVeinHelper(xyz, orientation, traversed) 87 | for _, direction in ipairs({'up', 'down', 'front', 'back', 'left', 'right'}) do 88 | local destination, newOrientation = table.unpack(calcDest(xyz, orientation, direction)) 89 | if not contains(traversed, destination) then 90 | if direction ~= 'back' then 91 | table.insert(traversed, destination) 92 | end 93 | 94 | if direction == 'up' then 95 | local success, data = turtle.inspectUp() 96 | if success and isTreasure(data) then 97 | tapi.digUp() 98 | tapi.up() 99 | mineVeinHelper(destination, newOrientation, traversed); 100 | tapi.down() 101 | end 102 | elseif direction == 'down' then 103 | local success, data = turtle.inspectDown() 104 | if success and isTreasure(data) then 105 | tapi.digDown() 106 | tapi.down() 107 | mineVeinHelper(destination, newOrientation, traversed); 108 | tapi.up() 109 | end 110 | elseif direction == 'back' then 111 | local leftOrient = orientation 112 | for i = 1, 3 do 113 | local calculated = calcDest(xyz, leftOrient, 'left') 114 | local leftDest = calculated[1] 115 | leftOrient = calculated[2] 116 | tapi.left() 117 | table.insert(traversed, leftDest) 118 | local success, data = turtle.inspect() 119 | if success and isTreasure(data) then 120 | tapi.dig() 121 | tapi.forward() 122 | mineVeinHelper(leftDest, leftOrient, traversed); 123 | tapi.back() 124 | end 125 | end 126 | tapi.left() 127 | else 128 | -- turn in the direction to inspect 129 | if direction == 'left' then 130 | tapi.left() 131 | elseif direction == 'right' then 132 | tapi.right() 133 | end 134 | -- inspect the block 135 | local success, data = turtle.inspect() 136 | if success and isTreasure(data) then 137 | tapi.dig() 138 | tapi.forward() 139 | mineVeinHelper(destination, newOrientation, traversed); 140 | tapi.back() 141 | end 142 | -- unturn to face forwards again 143 | if direction == 'left' then 144 | tapi.right() 145 | elseif direction == 'right' then 146 | tapi.left() 147 | end 148 | end 149 | end 150 | end 151 | end 152 | 153 | -- local found, block = turtle.inspect() 154 | -- if found and isTreasure(block) then 155 | mineVein() 156 | -- end 157 | -------------------------------------------------------------------------------- /src/turtlePrograms/veinMiner.lua: -------------------------------------------------------------------------------- 1 | --- Given a block's data, returns true if it's a treasure 2 | -- @return Boolean of whether it's a treasure 3 | function isTreasure(block) 4 | return block.name:find('ore') 5 | end 6 | 7 | --- Calculate the destination coordinate from current pos, orientation, and desired turn 8 | -- This calculation is RELATIVE and doesn't correspond with Minecraft's F3 coordinates 9 | -- @param Table xyz Table of coordinates {x,y,z} of the starting point 10 | -- @param String orientation The cardinal direction you face at the starting point 11 | -- @param String direction The direction (e.g. left, right, up) you would turn and proceed into 12 | -- @return { {x, y, z}, orientation } of destination 13 | function calcDest(xyz, orientation, direction) 14 | local dest = { 15 | x = xyz['x'], 16 | y = xyz['y'], 17 | z = xyz['z'] 18 | } 19 | if direction == 'up' then 20 | dest['y'] = dest['y'] + 1 21 | elseif direction == 'down' then 22 | dest['y'] = dest['y'] - 1 23 | else 24 | local cardinals = { 25 | north = 0, 26 | west = 1, 27 | south = 2, 28 | east = 3 29 | } 30 | local cardinalsReverse = { 31 | [0] = 'north', 32 | 'west', 33 | 'south', 34 | 'east' 35 | } 36 | local leftTurns = { 37 | front = 0, 38 | left = 1, 39 | back = 2, 40 | right = 3 41 | } 42 | orientation = cardinalsReverse[(cardinals[orientation] + leftTurns[direction]) % 4] 43 | if orientation == 'north' then 44 | dest['z'] = dest['z'] + 1 45 | elseif orientation == 'south' then 46 | dest['z'] = dest['z'] - 1 47 | elseif orientation == 'east' then 48 | dest['x'] = dest['x'] + 1 49 | elseif orientation == 'west' then 50 | dest['x'] = dest['x'] - 1 51 | end 52 | end 53 | return {dest, orientation} 54 | end 55 | 56 | --- Test if a table of {x,y,z}s contains a certain {x,y,z} 57 | -- @param Table table table to search within 58 | -- @param Table xyz xyz to search for 59 | -- @return Boolean of whether the table has the xyz 60 | function contains(table, xyz) 61 | for _, v in ipairs(table) do 62 | if v['x'] == xyz['x'] and v['y'] == xyz['y'] and v['z'] == xyz['z'] then 63 | return true 64 | end 65 | end 66 | return false 67 | end 68 | 69 | --- Master function for mining a vein of treasures as if it were a graph 70 | -- with each block as a node and the directions you can travel from that block as edges 71 | -- When beginning to mine, assumes whatever orientation the turtle is facing as "north" 72 | -- and wherever it started mining as {0, 0, 0} xyz 73 | function mineVein() 74 | mineVeinHelper({ 75 | x = 0, 76 | y = 0, 77 | z = 0 78 | }, 'north', {}) 79 | end 80 | 81 | --- Recursive helper function for mining a vein of treasures (blocks) 82 | -- using the graph traversal method 83 | -- @param Table xyz Current location {x,y,z} of turtle 84 | -- @param String orientation Current orientation of turtle 85 | -- @param Table traversed Table of tables {x,y,z} of visited blocks 86 | function mineVeinHelper(xyz, orientation, traversed) 87 | for _, direction in ipairs({'up', 'down', 'front', 'back', 'left', 'right'}) do 88 | local destination, newOrientation = table.unpack(calcDest(xyz, orientation, direction)) 89 | if not contains(traversed, destination) then 90 | if direction ~= 'back' then 91 | table.insert(traversed, destination) 92 | end 93 | 94 | if direction == 'up' then 95 | local success, data = turtle.inspectUp() 96 | if success and isTreasure(data) then 97 | tapi.digUp() 98 | tapi.up() 99 | mineVeinHelper(destination, newOrientation, traversed); 100 | tapi.down() 101 | end 102 | elseif direction == 'down' then 103 | local success, data = turtle.inspectDown() 104 | if success and isTreasure(data) then 105 | tapi.digDown() 106 | tapi.down() 107 | mineVeinHelper(destination, newOrientation, traversed); 108 | tapi.up() 109 | end 110 | elseif direction == 'back' then 111 | local leftOrient = orientation 112 | for i = 1, 3 do 113 | local calculated = calcDest(xyz, leftOrient, 'left') 114 | local leftDest = calculated[1] 115 | leftOrient = calculated[2] 116 | tapi.left() 117 | table.insert(traversed, leftDest) 118 | local success, data = turtle.inspect() 119 | if success and isTreasure(data) then 120 | tapi.dig() 121 | tapi.forward() 122 | mineVeinHelper(leftDest, leftOrient, traversed); 123 | tapi.back() 124 | end 125 | end 126 | tapi.left() 127 | else 128 | -- turn in the direction to inspect 129 | if direction == 'left' then 130 | tapi.left() 131 | elseif direction == 'right' then 132 | tapi.right() 133 | end 134 | -- inspect the block 135 | local success, data = turtle.inspect() 136 | if success and isTreasure(data) then 137 | tapi.dig() 138 | tapi.forward() 139 | mineVeinHelper(destination, newOrientation, traversed); 140 | tapi.back() 141 | end 142 | -- unturn to face forwards again 143 | if direction == 'left' then 144 | tapi.right() 145 | elseif direction == 'right' then 146 | tapi.left() 147 | end 148 | end 149 | end 150 | end 151 | end 152 | 153 | -- local found, block = turtle.inspect() 154 | -- if found and isTreasure(block) then 155 | mineVein() 156 | -- end 157 | -------------------------------------------------------------------------------- /src/types/types.ts: -------------------------------------------------------------------------------- 1 | interface TurtleState { 2 | id: number, 3 | label: "", 4 | loc: Vec, 5 | rot: number, 6 | inv: ItemStack[], 7 | selectedSlot: number, 8 | view: { 9 | front: 0, 10 | top: 0, 11 | bottom: 0 12 | }, 13 | fuelLevel: number, 14 | fuelLimit: number, 15 | modified?: number, 16 | } 17 | 18 | interface SimState { 19 | turtles: { [id: string]: TurtleState }, 20 | world: { [locString: string]: Block }, 21 | } 22 | 23 | interface Block { 24 | name: string, 25 | metadata: number, 26 | state?: Object, 27 | tags?: Object, 28 | inventory?: Inventory, 29 | inventorySize?: number, 30 | } 31 | 32 | interface ItemStack { 33 | count: number, 34 | name: string, 35 | damage?: number, 36 | } 37 | 38 | interface Item { 39 | name: string, 40 | damage: number, 41 | } 42 | 43 | type Vec = { 44 | x: number, 45 | y: number, 46 | z: number, 47 | } 48 | 49 | type Inventory = [{ name: string, count: number }] 50 | 51 | export { TurtleState, SimState, Block, ItemStack, Item, Vec, Inventory }; -------------------------------------------------------------------------------- /src/utils/BlockRenderStructure.ts: -------------------------------------------------------------------------------- 1 | import { BoxGeometry, BufferGeometry, Mesh, Object3D } from "three"; 2 | import { useWorldStore } from "../store/useWorld"; 3 | import { useWorldViewStore } from "../store/useWorldView"; 4 | import { Block } from "../types/types"; 5 | import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js"; 6 | import DynamicInstancedMesh from "./DynamicInstancedMesh"; 7 | 8 | class BlockRenderStructure { 9 | meshArray: DynamicInstancedMesh[]; 10 | blockToMeshIdxMap = {} as { [blockId: string]: number }; 11 | defaultInstanceCount = 16; 12 | boxGeometry: BoxGeometry; 13 | geometryCache = {} as { [geometryId: string]: BufferGeometry | Promise | null }; 14 | 15 | constructor(parentSceneObject: Object3D) { 16 | // console.log("New BlockRenderStructure created"); 17 | this.meshArray = parentSceneObject.children as DynamicInstancedMesh[]; 18 | this.boxGeometry = new BoxGeometry(); 19 | } 20 | addBlock(locString: string, block: Block) { 21 | if (!block || !locString) throw new Error(`Given block is ${block}`); 22 | const worldView = useWorldViewStore(); 23 | 24 | // create new mesh if none exists 25 | // console.log(`Old array: `); console.log(this.meshArray); 26 | let instMeshIdx = this.blockToMeshIdxMap[block.name]; 27 | if (instMeshIdx === undefined) { 28 | // console.log(`Creating mesh for new block type: ${block.name}`); 29 | let newMesh = new DynamicInstancedMesh(this.getBlockGeometry(block), worldView.getBlockMaterial(block.name)); 30 | instMeshIdx = this.meshArray.push(newMesh) - 1; 31 | this.blockToMeshIdxMap[block.name] = instMeshIdx; 32 | // console.log(`New array: `); console.log(this.meshArray); 33 | // console.log(`New blockToMeshIdxMap: `); console.log(this.blockToMeshIdxMap); 34 | } 35 | instMeshIdx = this.blockToMeshIdxMap[block.name]; 36 | let mesh = this.meshArray[instMeshIdx]; 37 | 38 | // recreate mesh if max instance count is reached 39 | if (mesh.count == mesh.maxInstanceCount) { 40 | const oldMesh = mesh; 41 | mesh = new DynamicInstancedMesh(oldMesh.geometry, worldView.getBlockMaterial(block.name), oldMesh.count * 2); 42 | mesh.setFromDynamicInstancedMesh(oldMesh); 43 | this.meshArray[instMeshIdx] = mesh; 44 | } 45 | 46 | // add block to mesh 47 | mesh.addBlock(locString, block); 48 | } 49 | removeBlock(locString: string) { 50 | const world = useWorldStore(); 51 | const block = world.blocks[locString]; 52 | if (!block) return; 53 | let instMeshIdx = this.blockToMeshIdxMap[block.name]; 54 | if (instMeshIdx === undefined) return; 55 | this.meshArray[instMeshIdx].removeBlock(locString); 56 | } 57 | getBlockGeometry(block: Block): BufferGeometry { 58 | const worldView = useWorldViewStore(); 59 | let geometryId = worldView.geometryMap[block.name]; 60 | if (!geometryId && (block.name.includes("sapling") || block.name.includes("kelp") || block.name.includes("seagrass") || block.name.includes("magrove_root"))) geometryId = "cross"; 61 | if (!geometryId) return this.boxGeometry; 62 | if (!this.geometryCache[geometryId]) { 63 | const loader = new GLTFLoader(); 64 | 65 | /* @ts-ignore */ 66 | const promise = loader.loadAsync(`textures/turtle/${geometryId}.glb`) 67 | .then( 68 | (gltf) => gltf.scene.traverse((child) => { 69 | /* @ts-ignore */ 70 | if (child.isMesh) { 71 | this.geometryCache[geometryId] = (child as Mesh).geometry; 72 | console.log("geometry request response:") 73 | console.log(this.geometryCache); 74 | } 75 | })) 76 | promise.catch((error) => { 77 | console.error(error); 78 | this.geometryCache[geometryId] = null; 79 | }); 80 | this.geometryCache[geometryId] = promise; 81 | } 82 | 83 | let geometryOrPromise: BufferGeometry | Promise | null = this.geometryCache[geometryId]; 84 | // in case a previous request for the resource failed just return a box geometry 85 | if (geometryOrPromise === null) return this.boxGeometry; 86 | /* @ts-ignore */ 87 | if (geometryOrPromise.catch) { 88 | // in case the geometry is already being requested, return box geom and change geom later 89 | console.log("geometry is being requested - returning box geometry") 90 | /* @ts-ignore */ 91 | geometryOrPromise.then(() => { 92 | const geometry = this.geometryCache[geometryId]; 93 | console.log("geometry request done") 94 | if (geometry) { 95 | console.log("geometry request successful - swapping mesh") 96 | this.meshArray[this.blockToMeshIdxMap[block.name]].geometry = geometry as BufferGeometry; 97 | } 98 | console.log(geometry) 99 | }); 100 | return this.boxGeometry; 101 | } 102 | else { 103 | // in case the geometry is already cached, return it immediately 104 | console.log("geometry is already cached") 105 | return geometryOrPromise as BufferGeometry; 106 | } 107 | } 108 | }; 109 | 110 | export default BlockRenderStructure; -------------------------------------------------------------------------------- /src/utils/DynamicInstancedMesh.ts: -------------------------------------------------------------------------------- 1 | import { InstancedMesh, Matrix4 } from "three"; 2 | import { Block } from "../types/types"; 3 | 4 | class DynamicInstancedMesh extends InstancedMesh { 5 | maxInstanceCount: number; 6 | locStringToInstance = new BidirectionalMap({}); 7 | constructor(geometry: THREE.BufferGeometry, material: THREE.Material, maxInstanceCount = 16) { 8 | super(geometry, material, maxInstanceCount); 9 | this.maxInstanceCount = maxInstanceCount; 10 | this.count = 0; 11 | } 12 | addBlock(locString: string, block: Block) { 13 | if (!block) throw new Error(`Given block is ${block}`); 14 | // if block exists, remove old block 15 | if (this.locStringToInstance.get(locString) !== undefined) { 16 | this.removeBlock(locString); 17 | } 18 | // and add new one 19 | let coords = locString.split(","); 20 | let mat = new Matrix4().setPosition( 21 | Number(coords[0]), 22 | Number(coords[1]), 23 | Number(coords[2]));; 24 | this.setMatrixAt(this.count, mat); 25 | this.instanceMatrix.needsUpdate = true; 26 | this.locStringToInstance.add(locString, this.count); 27 | this.count++; 28 | } 29 | removeBlock(locString: string) { 30 | let remIdx = this.locStringToInstance.get(locString); 31 | if (remIdx === undefined) return; 32 | 33 | // set transformation matrix of last entry into entry to delete 34 | let mat = new Matrix4(); 35 | this.getMatrixAt(this.count - 1, mat); 36 | this.setMatrixAt(remIdx, mat); 37 | this.instanceMatrix.needsUpdate = true; 38 | 39 | // put last instance in place of this one and decrement instance count 40 | this.locStringToInstance.remove(locString); 41 | let movedLocString = this.locStringToInstance.getByValue(this.count - 1); 42 | this.locStringToInstance.remove(movedLocString); 43 | this.locStringToInstance.add(movedLocString, remIdx); 44 | this.count--; 45 | } 46 | setFromDynamicInstancedMesh(dynInstMesh: DynamicInstancedMesh) { 47 | this.locStringToInstance = dynInstMesh.locStringToInstance; 48 | let mat = new Matrix4(); 49 | for (let i = 0; i < dynInstMesh.count; i++) { 50 | dynInstMesh.getMatrixAt(i, mat); 51 | this.setMatrixAt(i, mat); 52 | this.instanceMatrix.needsUpdate = true; 53 | this.count++; 54 | } 55 | } 56 | }; 57 | 58 | class BidirectionalMap { 59 | fwdMap = {} as { [locString: string]: number }; 60 | revMap = {} as { [index: number]: string }; 61 | 62 | constructor(map: { [key: string]: number }) { 63 | this.fwdMap = { ...map }; 64 | this.revMap = Object.keys(map).reduce( 65 | (acc, cur) => ({ 66 | ...acc, 67 | [map[cur]]: cur, 68 | }), 69 | {} 70 | ) 71 | } 72 | 73 | get(key: string): number | undefined { 74 | return this.fwdMap[key]; 75 | } 76 | 77 | getByValue(value: number) { 78 | return this.revMap[value]; 79 | } 80 | 81 | add(locString: string, index: number) { 82 | this.fwdMap[locString] = index; 83 | this.revMap[index] = locString; 84 | } 85 | 86 | remove(locString: string) { 87 | let index = this.fwdMap[locString]; 88 | if (index === undefined) return; 89 | delete this.fwdMap[locString]; 90 | delete this.revMap[index]; 91 | } 92 | 93 | removeByValue(index: number) { 94 | let locstring = this.revMap[index]; 95 | if (index === undefined) return; 96 | delete this.revMap[index]; 97 | delete this.fwdMap[locstring]; 98 | } 99 | } 100 | 101 | export default DynamicInstancedMesh; -------------------------------------------------------------------------------- /textures/blocks/minecraft/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exa-byte/CCTurtleRemoteController/cba45484f6b299ed9dd8abe6eac720a2d94b8eee/textures/blocks/minecraft/.gitkeep -------------------------------------------------------------------------------- /textures/blocks/someOtherModNamespace/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exa-byte/CCTurtleRemoteController/cba45484f6b299ed9dd8abe6eac720a2d94b8eee/textures/blocks/someOtherModNamespace/.gitkeep -------------------------------------------------------------------------------- /textures/items/minecraft/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exa-byte/CCTurtleRemoteController/cba45484f6b299ed9dd8abe6eac720a2d94b8eee/textures/items/minecraft/.gitkeep -------------------------------------------------------------------------------- /textures/items/someOtherModNamespace/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exa-byte/CCTurtleRemoteController/cba45484f6b299ed9dd8abe6eac720a2d94b8eee/textures/items/someOtherModNamespace/.gitkeep -------------------------------------------------------------------------------- /textures/turtle/CCTurtle.glb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exa-byte/CCTurtleRemoteController/cba45484f6b299ed9dd8abe6eac720a2d94b8eee/textures/turtle/CCTurtle.glb -------------------------------------------------------------------------------- /textures/turtle/CCTurtle_happy.glb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exa-byte/CCTurtleRemoteController/cba45484f6b299ed9dd8abe6eac720a2d94b8eee/textures/turtle/CCTurtle_happy.glb -------------------------------------------------------------------------------- /textures/turtle/cross.glb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/exa-byte/CCTurtleRemoteController/cba45484f6b299ed9dd8abe6eac720a2d94b8eee/textures/turtle/cross.glb -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "esnext", 4 | "useDefineForClassFields": true, 5 | "module": "esnext", 6 | "moduleResolution": "node", 7 | "strict": true, 8 | "jsx": "preserve", 9 | "sourceMap": true, 10 | "resolveJsonModule": true, 11 | "esModuleInterop": true, 12 | "lib": ["esnext", "dom"] 13 | }, 14 | "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"], 15 | "references": [{ "path": "./tsconfig.node.json" }] 16 | } 17 | -------------------------------------------------------------------------------- /tsconfig.node.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "composite": true, 4 | "module": "esnext", 5 | "moduleResolution": "node" 6 | }, 7 | "include": ["vite.config.ts"] 8 | } 9 | -------------------------------------------------------------------------------- /turtle/diskboot: -------------------------------------------------------------------------------- 1 | shell.run("cp disk/_startup startup") 2 | shell.run("cp disk/loc.sav loc.sav") 3 | shell.run("startup") -------------------------------------------------------------------------------- /turtle/location: -------------------------------------------------------------------------------- 1 | local Location = { 2 | add = function(self, o) 3 | return vector.new( 4 | self.x + o.x, 5 | self.y + o.y, 6 | self.z + o.z 7 | ) 8 | end, 9 | sub = function(self, o) 10 | return vector.new( 11 | self.x - o.x, 12 | self.y - o.y, 13 | self.z - o.z 14 | ) 15 | end, 16 | mul = function(self, m) 17 | return vector.new( 18 | self.x * m, 19 | self.y * m, 20 | self.z * m 21 | ) 22 | end, 23 | div = function(self, d) 24 | return vector.new( 25 | self.x / d, 26 | self.y / d, 27 | self.z / d 28 | ) 29 | end, 30 | left = function(self, turtle, noMove) 31 | self.h = self.h - 1 32 | if self.h < 1 then self.h = self.h + 4 end 33 | return noMove or turtle.turnLeft() 34 | end, 35 | right = function(self, turtle, noMove) 36 | self.h = self.h + 1 37 | if self.h > 4 then self.h = self.h - 4 end 38 | return noMove or turtle.turnRight() 39 | end, 40 | forward = function(self, turtle, noMove) 41 | if noMove or turtle then 42 | if noMove or turtle.forward() then 43 | self.x = self.x + (self.h - 2) * (self.h % 2) 44 | self.z = self.z + (self.h - 3) * ((self.h + 1) % 2) 45 | return true 46 | end 47 | end 48 | return false 49 | end, 50 | back = function(self, turtle, noMove) 51 | if turtle then 52 | if turtle.back() then 53 | self.x = self.x - (self.h - 2) * (self.h % 2) 54 | self.z = self.z - (self.h - 3) * ((self.h + 1) % 2) 55 | return true 56 | end 57 | end 58 | return false 59 | end, 60 | up = function(self, turtle, noMove) 61 | if noMove or turtle then 62 | if noMove or turtle.up() then 63 | self.y = self.y + 1 64 | return true 65 | end 66 | end 67 | return false 68 | end, 69 | down = function(self, turtle, noMove) 70 | if noMove or turtle then 71 | if noMove or turtle.down() then 72 | self.y = self.y - 1 73 | return true 74 | end 75 | end 76 | return false 77 | end, 78 | moveDeltas = function(self) 79 | return (self.h - 2) * (self.h % 2), (self.h - 3) * ((self.h + 1) % 2) 80 | end, 81 | setHeading = function(self, turtle, head) 82 | if not head or head < 1 or head > 4 then return nil, "Heading Not in Range" end 83 | while self.h ~= head do 84 | if (self.h + 1) % 4 == head % 4 then 85 | self:right(turtle) 86 | else 87 | self:left(turtle) 88 | end 89 | end 90 | return true 91 | end, 92 | tovector = function(self) 93 | if vector then 94 | return vector.new( 95 | self.x, 96 | self.y, 97 | self.z 98 | ) 99 | else 100 | return nil 101 | end 102 | end, 103 | tostring = function(self) 104 | return self.x..","..self.y..","..self.z..","..self.h 105 | end, 106 | value = function(self) 107 | return self.x, self.y, self.z, self.h 108 | end, 109 | } 110 | 111 | local lmetatable = { 112 | __index = Location, 113 | __add = Location.add, 114 | __sub = Location.sub, 115 | __mul = Location.mul, 116 | __div = Location.div, 117 | __unm = function(l) return l:mul(-1) end, 118 | __tostring = function(l) return l:tostring() end, 119 | } 120 | 121 | function new( x, y, z, h ) 122 | local l = { 123 | x = x or 0, 124 | y = y or 0, 125 | z = z or 0, 126 | h = h or 1 127 | } 128 | setmetatable( l, lmetatable ) 129 | return l 130 | end 131 | 132 | function getOrientation(x, z) 133 | return ((x + math.abs(x) * 2) + (z + math.abs(z) * 3)) 134 | end 135 | 136 | --[[ 137 | -x 1 (west) 138 | -z 2 (north) 139 | +x 3 (east) 140 | +z 4 (south) 141 | 142 | turn right, add one. 143 | turn left, sub one. 144 | --]] -------------------------------------------------------------------------------- /turtle/rcTurtle.lua: -------------------------------------------------------------------------------- 1 | -- github: https://github.com/exa-byte/CCTurtleRemoteController 2 | os.loadAPI("tapi") 3 | 4 | local get_command_url = tapi.url .. "getCommand/" 5 | local get_stop_signal_url = tapi.url .. "getStopSignal/" 6 | local command_result_url = tapi.url .. "commandResult/" 7 | 8 | function send_command_result(succ, ret) 9 | local valid, cmd_result = pcall(textutils.serializeJSON, { turtleId = os.getComputerID(), result = { succ = succ, ret = ret } }) 10 | if not valid then 11 | cmd_result = textutils.serializeJSON({ turtleId = os.getComputerID(), result = { succ = false, ret = "error: result contains function which cannot be serialized" } }) 12 | end 13 | -- print("sending cmd_result: " .. tostring(succ) .. ", " .. tostring(ret)) 14 | local res = http.post(command_result_url, cmd_result, { ["Content-Type"] = "application/json" }) 15 | if res then --[[print(res.readAll())]] res.close() end 16 | print(tapi.getLoc()) 17 | end 18 | 19 | function get_command() 20 | local json = textutils.serializeJSON({ id = os.getComputerID() }) 21 | local res = http.post(get_command_url, json, { ["Content-Type"] = "application/json" }) 22 | if res then 23 | local cmd_string = res.readAll() 24 | if cmd_string == "" then res.close(); return end 25 | local cmd, err = loadstring(cmd_string) 26 | if cmd then 27 | if #cmd_string > 0 then print("executing cmd: " .. cmd_string) end 28 | setfenv(cmd, getfenv()) 29 | send_command_result(pcall(cmd)) 30 | else 31 | print("error in loadstring(" .. cmd_string .. ")"); 32 | send_command_result(false, err) 33 | end 34 | res.close() 35 | end 36 | end 37 | 38 | function poll_stop_signal() 39 | while true do 40 | local json = textutils.serializeJSON({ id = os.getComputerID() }) 41 | local res = http.post(get_stop_signal_url, json, { ["Content-Type"] = "application/json" }) 42 | if res then 43 | local stop_string = res.readAll() 44 | if string.find(stop_string, "true") then 45 | res.close() 46 | print("got stop signal!") 47 | tapi.locSemaphore.stopSignal = true 48 | while tapi.locSemaphore.count > 0 do os.sleep(0.001) end 49 | return 50 | end 51 | res.close() 52 | end 53 | os.sleep(1) 54 | end 55 | end 56 | 57 | function main() 58 | while true do 59 | tapi.send_status_update() 60 | parallel.waitForAny(poll_stop_signal, get_command) 61 | tapi.locSemaphore.stopSignal = false 62 | end 63 | end 64 | 65 | main() 66 | -------------------------------------------------------------------------------- /turtle/setLocRot: -------------------------------------------------------------------------------- 1 | os.loadAPI("tapi") 2 | 3 | local x, y, z, h = ... 4 | 5 | tapi.loc_internal.x = tonumber(x) 6 | tapi.loc_internal.y = tonumber(y) 7 | tapi.loc_internal.z = tonumber(z) 8 | tapi.loc_internal.h = tonumber(h + 1) 9 | 10 | tapi.save_loc_to_file() 11 | -------------------------------------------------------------------------------- /turtle/startup: -------------------------------------------------------------------------------- 1 | -- github: https://github.com/exa-byte/CCTurtleRemoteController 2 | -- !MUST END WITH A '/' 3 | base_url = "http://localhost/" 4 | 5 | -- lib 6 | function Split(s, delimiter) 7 | result = {}; 8 | for match in (s..delimiter):gmatch("(.-)"..delimiter) do 9 | table.insert(result, match); 10 | end 11 | return result; 12 | end 13 | 14 | function get_files_from_server() 15 | repeat res = http.get( base_url .. "api/turtleFileNames", {["Content-Type"] = "application/json"} ) 16 | until res 17 | dl_files = res.readAll() 18 | dl_files = dl_files:sub(2, #dl_files-1):gsub("\"", "") 19 | 20 | term.write("autoupdate...") 21 | for _, name in pairs(Split(dl_files, ",")) do 22 | -- print("GET " .. base_url .. "turtle/" .. name) 23 | local res = http.get( base_url .. "turtle/" .. name ) 24 | if not res then print("Error on GET " .. base_url .. "turtle/" .. name) end 25 | local f = fs.open(name, "w") 26 | f.write(res.readAll()) 27 | f.close() 28 | if name == "startup" then 29 | fs.makeDir("backup") 30 | fs.delete("backup/startup") 31 | fs.copy("startup", "backup/startup") 32 | end 33 | end 34 | term.write("complete\n") 35 | end 36 | 37 | -- autoupdate 38 | get_files_from_server() 39 | shell.run("rcTurtle.lua") -------------------------------------------------------------------------------- /turtle/tapi: -------------------------------------------------------------------------------- 1 | -- github: https://github.com/exa-byte/CCTurtleRemoteController 2 | -- uses location api (https://github.com/lyqyd/LyqydNet-Programs/blob/master/apis/location) by lyqyd 3 | 4 | os.loadAPI("location") 5 | 6 | -- !MUST END WITH '/api/' 7 | url = "http://localhost/api/" 8 | state_url = url .. "state/" 9 | local headers = { 10 | ["Content-Type"] = "application/json" 11 | } 12 | local state = { 13 | id = -1, 14 | label = "", 15 | loc = { 16 | x = 0, 17 | y = 0, 18 | z = 0 19 | }, -- relative location to app origin 20 | rot = 0, -- look direction 21 | inv = { -- will include sensed items in turtle inventory with turtle.getItemDetail(slot) 22 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 23 | selectedSlot = -1, 24 | view = { -- will include sensed blocks with turtle.inspect[...] 25 | front = 0, 26 | top = 0, 27 | bottom = 0 28 | }, 29 | fuelLevel = -1, 30 | fuelLimit = -1 31 | } 32 | -- semaphore implementation 33 | local lmetatable = { 34 | __index = { 35 | incr = function(self) 36 | if self.stopSignal then os.sleep(1) end 37 | self.count = self.count + 1 38 | end, 39 | decr = function(self) 40 | self.count = self.count - 1 41 | end, 42 | tostring = function(self) 43 | return "currLocks:" .. tostring(self.count) 44 | end, 45 | value = function(self) 46 | return self.count 47 | end 48 | }, 49 | __tostring = function(l) return l:tostring() end, 50 | } 51 | locSemaphore = { count = 0, stopSignal = false } 52 | setmetatable(locSemaphore, lmetatable) 53 | 54 | if os.getComputerLabel() == "" then 55 | os.setComputerLabel("kukumba" .. tostring(os.getComputerID())) 56 | end 57 | 58 | -- global api overwrites 59 | 60 | local native = { 61 | turtle = { 62 | up = turtle.up, 63 | down = turtle.down, 64 | forward = turtle.forward, 65 | back = turtle.back, 66 | turnLeft = turtle.turnLeft, 67 | turnRight = turtle.turnRight, 68 | dig = turtle.dig, 69 | digUp = turtle.digUp, 70 | digDown = turtle.digDown, 71 | }, 72 | os = { 73 | os.restart 74 | } 75 | } 76 | os.restart = function() 77 | fs.delete("startup") 78 | fs.copy("backup/startup", "startup") 79 | native.os.restart() 80 | end 81 | os.shutdown = os.restart 82 | 83 | -- send status to server 84 | 85 | function send_status_update() 86 | scan_surrounding_blocks() 87 | scan_inventory() 88 | scan_turtle_specs() 89 | 90 | local state = textutils.serializeJSON(state) 91 | http.request(state_url, state, headers) 92 | end 93 | 94 | local function does_side_have_inventory(side) 95 | if not peripheral.isPresent(side) then return false end 96 | if not peripheral.hasType then 97 | -- added for backwards compatability 98 | return peripheral.getType(side) == "inventory" 99 | else 100 | return peripheral.hasType(side, "inventory") 101 | end 102 | end 103 | 104 | function scan_surrounding_blocks() 105 | local succ, block = turtle.inspect(); 106 | state.view.front = succ and block or 0 107 | if succ and does_side_have_inventory("front") then 108 | state.view.front.inventory = peripheral.call("front", "list") 109 | state.view.front.inventorySize = peripheral.call("front", "size") 110 | end 111 | succ, block = turtle.inspectUp(); 112 | state.view.top = succ and block or 0 113 | if succ and does_side_have_inventory("top") then 114 | state.view.top.inventory = peripheral.call("top", "list") 115 | state.view.top.inventorySize = peripheral.call("top", "size") 116 | end 117 | succ, block = turtle.inspectDown(); 118 | state.view.bottom = succ and block or 0 119 | if succ and does_side_have_inventory("bottom") then 120 | state.view.bottom.inventory = peripheral.call("bottom", "list") 121 | state.view.bottom.inventorySize = peripheral.call("bottom", "size") 122 | end 123 | end 124 | 125 | function scan_inventory() 126 | for i = 1, 16 do 127 | local stack = turtle.getItemDetail(i) 128 | state.inv[i] = stack or 0 129 | end 130 | state.selectedSlot = turtle.getSelectedSlot() 131 | end 132 | 133 | function scan_turtle_specs() 134 | state.loc.x = getLoc().x 135 | state.loc.y = getLoc().y 136 | state.loc.z = getLoc().z 137 | state.rot = getLoc().h - 1 138 | state.id = os.getComputerID() 139 | state.label = os.getComputerLabel() or "" 140 | state.fuelLevel = turtle.getFuelLevel() 141 | state.fuelLimit = turtle.getFuelLimit() 142 | end 143 | 144 | -- location functions 145 | 146 | function getLoc() 147 | return loc_internal 148 | end 149 | 150 | function setLoc(loc_in) 151 | loc_internal = loc_in 152 | end 153 | 154 | function save_loc_to_file() 155 | send_status_update() 156 | local f = fs.open("loc.sav", "w") 157 | f.writeLine(loc_internal.x) 158 | f.writeLine(loc_internal.y) 159 | f.writeLine(loc_internal.z) 160 | f.writeLine(loc_internal.h) 161 | f.close() 162 | end 163 | 164 | function parse_user_location_input() 165 | local input = io.read() 166 | local splitInput = {} 167 | local locAndHeading = {} 168 | for substring in input:gmatch("%S+") do 169 | table.insert(splitInput, substring) 170 | end 171 | for i = 1, 3 do 172 | locAndHeading[i] = tonumber(splitInput[i]) 173 | if locAndHeading[i] == nil then 174 | error(tostring(splitInput[i]) .. " is not a valid coordinate") 175 | end 176 | end 177 | local h = string.lower(splitInput[4]) 178 | if h == "west" then locAndHeading[4] = 1 179 | elseif h == "north" then locAndHeading[4] = 2 180 | elseif h == "east" then locAndHeading[4] = 3 181 | elseif h == "south" then locAndHeading[4] = 4 182 | else error(tostring(splitInput[4]) .. " is not a valid heading") 183 | end 184 | return locAndHeading 185 | end 186 | 187 | function load_loc_from_file() 188 | -- load from file if exists, else create new one 189 | local f = fs.open("loc.sav", "r") 190 | if f then 191 | loc_internal = location.new(tonumber(f.readLine()), tonumber(f.readLine()), tonumber(f.readLine()), 192 | tonumber(f.readLine())) 193 | f.close() 194 | else 195 | while true do 196 | print("Could not load location, please stand on the turtle in forward direction and open F3 screen") 197 | print("Please provide block coordinate and facing of the turtle: ") 198 | print("e.g. -263 68 79 south") 199 | 200 | local status, res = pcall(parse_user_location_input) 201 | if status then 202 | loc_internal = location.new(unpack(res)) 203 | save_loc_to_file() 204 | break 205 | else print(res) end 206 | end 207 | end 208 | end 209 | 210 | load_loc_from_file() 211 | 212 | -- movement 213 | 214 | function nativeUp() 215 | locSemaphore:incr() 216 | local succ = loc_internal:up(native.turtle) 217 | save_loc_to_file() 218 | locSemaphore:decr() 219 | return succ 220 | end 221 | function up(count, reliable) 222 | reliable = reliable or false 223 | count = count or 1 224 | local msg_written = false 225 | for i = 1, count do 226 | while not loc_internal:up(native.turtle) do 227 | if not reliable then 228 | return false, i - 1 229 | end 230 | 231 | if not msg_written then 232 | print("cannot move up - pls remove block") 233 | msg_written = true 234 | end 235 | os.sleep(1); 236 | end 237 | end 238 | return true 239 | end 240 | 241 | u = up 242 | turtle.up = nativeUp 243 | 244 | 245 | function nativeDown() 246 | locSemaphore:incr() 247 | local succ = loc_internal:down(native.turtle) 248 | save_loc_to_file() 249 | locSemaphore:decr() 250 | return succ 251 | end 252 | function down(count, reliable) 253 | reliable = reliable or false 254 | count = count or 1 255 | local msg_written = false 256 | for i = 1, count do 257 | while not nativeDown() do 258 | if not reliable then 259 | return false, i - 1 260 | end 261 | 262 | if not msg_written then 263 | print("cannot move down - pls remove block") 264 | save_loc_to_file() 265 | msg_written = true 266 | end 267 | os.sleep(1); 268 | end 269 | end 270 | return true 271 | end 272 | 273 | d = down 274 | turtle.down = nativeDown 275 | 276 | function nativeForward() 277 | locSemaphore:incr() 278 | local succ = loc_internal:forward(native.turtle) 279 | save_loc_to_file() 280 | locSemaphore:decr() 281 | return succ 282 | end 283 | function forward(count, reliable) 284 | reliable = reliable or false 285 | count = count or 1 286 | local msg_written = false 287 | for i = 1, count do 288 | while not nativeForward() do 289 | if not reliable then 290 | return false, i - 1 291 | end 292 | 293 | if not msg_written then 294 | print("cannot move forward - pls remove block") 295 | msg_written = true 296 | end 297 | os.sleep(1); 298 | end 299 | end 300 | return true 301 | end 302 | 303 | f = forward 304 | turtle.forward = nativeForward 305 | 306 | function nativeBack() 307 | locSemaphore:incr() 308 | local succ = loc_internal:back(native.turtle) 309 | save_loc_to_file() 310 | locSemaphore:decr() 311 | return succ 312 | end 313 | function back(count, reliable) 314 | reliable = reliable or false 315 | count = count or 1 316 | local msg_written = false 317 | for i = 1, count do 318 | while not nativeBack() do 319 | if not reliable then 320 | return false, i - 1 321 | end 322 | 323 | if not msg_written then 324 | print("cannot move back - pls remove block") 325 | msg_written = true 326 | end 327 | os.sleep(1); 328 | end 329 | end 330 | return true 331 | end 332 | 333 | b = back 334 | turtle.back = nativeBack 335 | 336 | function move(dx, dy, dz, reliable) -- move the turtle by a given vector (moves x first z last), unreliable 337 | print("move" .. tostring(dx) .. " " .. tostring(dy) .. " " .. tostring(dz)) 338 | if dx ~= 0 then 339 | turnTo((dx > 0) and 3 or 1) 340 | end -- west => neg x 341 | if not forward(math.abs(dx), reliable) then return false end 342 | if (dy > 0) then 343 | if not up(dy) then return false end 344 | else 345 | if not down(math.abs(dy), reliable) then return false end 346 | end 347 | if dz ~= 0 then 348 | turnTo((dz > 0) and 4 or 2) 349 | end -- north => negative z 350 | if not forward(math.abs(dz), reliable) then return false end 351 | return true 352 | end 353 | 354 | function goTo(x, y, z) 355 | while not (loc_internal.x == x and loc_internal.y == y and loc_internal.z == z) do 356 | local old_loc = loc_internal:tovector() 357 | local dx = x - loc_internal.x 358 | local dy = y - loc_internal.y 359 | local dz = z - loc_internal.z 360 | 361 | move(dx, 0, 0) 362 | move(0, dy, 0) 363 | move(0, 0, dz) 364 | 365 | if (old_loc - loc_internal:tovector()):length() == 0 then return false end 366 | end 367 | return true 368 | end 369 | 370 | -- rotation 371 | function nativeLeft() 372 | locSemaphore:incr() 373 | local succ = loc_internal:left(native.turtle) 374 | save_loc_to_file() 375 | locSemaphore:decr() 376 | return succ 377 | end 378 | function left(num_turns) 379 | num_turns = num_turns or 1 380 | for i = 1, num_turns do 381 | nativeLeft() 382 | end 383 | return true 384 | end 385 | 386 | l = left 387 | turtle.turnLeft = nativeLeft 388 | 389 | function nativeRight() 390 | locSemaphore:incr() 391 | local succ = loc_internal:right(native.turtle) 392 | save_loc_to_file() 393 | locSemaphore:decr() 394 | return succ 395 | end 396 | function right(num_turns) 397 | num_turns = num_turns or 1 398 | for i = 1, num_turns do 399 | nativeRight() 400 | end 401 | return true 402 | end 403 | 404 | r = right 405 | turtle.turnRight = nativeRight 406 | 407 | function turnTo(heading) 408 | locSemaphore:incr() 409 | local res = loc_internal:setHeading(native.turtle, heading) 410 | locSemaphore:decr() 411 | return res 412 | end 413 | 414 | face = turnTo 415 | 416 | -- placement 417 | function place(slot) 418 | if slot then 419 | select(slot) 420 | end 421 | local succ = turtle.place() 422 | send_status_update() 423 | return succ 424 | end 425 | 426 | p = place 427 | 428 | function placeDown(slot) 429 | if slot then 430 | select(slot) 431 | end 432 | local succ = turtle.placeDown() 433 | send_status_update() 434 | return succ 435 | end 436 | 437 | pd = placeDown 438 | 439 | function placeUp(slot) 440 | if slot then 441 | select(slot) 442 | end 443 | local succ = turtle.placeUp() 444 | send_status_update() 445 | return succ 446 | end 447 | 448 | pu = placeUp 449 | 450 | -- dig 451 | 452 | function dig() 453 | local succ = native.turtle.dig() 454 | send_status_update() 455 | return succ 456 | end 457 | 458 | e = dig 459 | turtle.dig = dig 460 | 461 | function digUp() 462 | local succ = native.turtle.digUp() 463 | send_status_update() 464 | return succ 465 | end 466 | 467 | eu = digUp 468 | turtle.digUp = digUp 469 | 470 | function digDown() 471 | local succ = native.turtle.digDown() 472 | send_status_update() 473 | return succ 474 | end 475 | 476 | ed = digDown 477 | turtle.digDown = digDown 478 | 479 | function digRepeat() 480 | local succ 481 | repeat 482 | succ = turtle.dig() 483 | until not succ 484 | send_status_update() 485 | return succ 486 | end 487 | 488 | e = dig 489 | 490 | function digUpRepeat() 491 | local succ 492 | repeat 493 | succ = turtle.digUp() 494 | until not succ 495 | send_status_update() 496 | return succ 497 | end 498 | 499 | eu = digUp 500 | 501 | function digDownRepeat() 502 | local succ 503 | repeat 504 | succ = turtle.digDown() 505 | until not succ 506 | send_status_update() 507 | return succ 508 | end 509 | 510 | ed = digDown 511 | 512 | function digSide(side) 513 | if not side then return false, "side must not be nil" end 514 | if side == "front" then return dig() end 515 | if side == "top" then return digUp() end 516 | if side == "bottom" then return digDown() end 517 | end 518 | 519 | -- sucking 520 | 521 | function suck() 522 | local succ = turtle.suck() 523 | send_status_update() 524 | return succ 525 | end 526 | 527 | function suckUp() 528 | local succ = turtle.suckUp() 529 | send_status_update() 530 | return succ 531 | end 532 | 533 | function suckDown() 534 | local succ = turtle.suckDown() 535 | send_status_update() 536 | return succ 537 | end 538 | 539 | function suckAll() 540 | return suck() or suckUp() or suckDown() 541 | end 542 | 543 | -- drop 544 | 545 | function drop(slot) 546 | if slot then 547 | select(slot) 548 | end 549 | local succ = turtle.drop() 550 | send_status_update() 551 | return succ 552 | end 553 | 554 | function dropUp(slot) 555 | if slot then 556 | select(slot) 557 | end 558 | local succ = turtle.dropUp() 559 | send_status_update() 560 | return succ 561 | end 562 | 563 | function dropDown(slot) 564 | if slot then 565 | select(slot) 566 | end 567 | local succ = turtle.dropDown() 568 | send_status_update() 569 | return succ 570 | end 571 | 572 | -- fuel 573 | 574 | function request_fuel() 575 | while turtle.getFuelLevel() < 100 do 576 | print("refuel needed: put fuel into selected slot and press enter") 577 | read() 578 | turtle.refuel() 579 | end 580 | end 581 | 582 | function refuel(count) 583 | turtle.refuel(count) 584 | send_status_update() 585 | end 586 | 587 | -- inventory 588 | function select(slot) 589 | if not slot then return false end 590 | if turtle.getSelectedSlot() == slot then return true end 591 | local succ = turtle.select(slot) 592 | send_status_update() 593 | return succ 594 | end 595 | 596 | function findItem(name) 597 | for i = 1, 16 do 598 | local stack = turtle.getItemDetail(i) 599 | if stack and stack.name == name then 600 | return i 601 | end 602 | end 603 | return false 604 | end 605 | 606 | -- get the first item where the string is contained in the id of the item 607 | -- e.g. when you input "chest" and there is a "ironchest:diamond_chest" in the turtle that slot will be returned 608 | function findItemFuzzy(string) 609 | for i = 1, 16 do 610 | local stack = turtle.getItemDetail(i) 611 | if stack and string.find(stack.name, string) then 612 | return i 613 | end 614 | end 615 | return false 616 | end 617 | 618 | function selectItem(name) 619 | local found = findItem(name) 620 | if found == false then 621 | return false 622 | end 623 | return select(found) 624 | end 625 | 626 | function contains_items(name, req_count, meta) 627 | local count = 0 628 | req_count = req_count or 1 629 | for i = 1, 16 do 630 | local stack = turtle.getItemDetail(i) 631 | if stack and stack.name == name and (not meta or stack.damage == meta) then 632 | count = count + stack.count 633 | if count >= req_count then 634 | return true 635 | end 636 | end 637 | end 638 | return false 639 | end 640 | 641 | function contains_all_items(item_list) 642 | for _, item in pairs(item_list) do 643 | if not contains_items(item.name, item.count, item.meta) then 644 | return false 645 | end 646 | end 647 | return true 648 | end 649 | 650 | function craft(times) 651 | turtle.craft(times) 652 | send_status_update() 653 | end 654 | 655 | -- will pull item from one adjacent inventory to another 656 | function moveItemsBetweenInventories(sourceInvSide, destInvSide, itemName, count) 657 | src = peripheral.wrap(sourceInvSide) 658 | if not src then print("src inventory (" .. tostring(sourceInvSide) .. ") is not available"); return false end 659 | 660 | for slot, item in pairs(src.list()) do 661 | print(("%d x %s in slot %d"):format(item.count, item.name, slot)) 662 | end 663 | 664 | dst = peripheral.wrap(destInvSide) 665 | if not dst then print("src inventory (" .. tostring(sourceInvSide) .. ") is not available"); return false end 666 | end 667 | 668 | -- itemList format: e.g.: {{count=5, name="minecraft:torch"}, {count=1, name="minecraft:cobblestone"}} 669 | -- returns true if all items in itemList are in the chest or false, missingItemList else 670 | function doesChestContainItemList(itemList, inventorySide) 671 | -- make a copy of itemList 672 | local _itemList = {} 673 | for pos, wantStack in pairs(itemList) do 674 | table.insert(_itemList, pos, { name = wantStack.name, count = wantStack.count }) 675 | end 676 | 677 | -- iterate chestItems and subtract from _wantList 678 | local chestItems = peripheral.call(inventorySide, "list") 679 | if not chestItems then return false end 680 | for i, wantStack in pairs(_itemList) do 681 | for j, haveStack in pairs(chestItems) do 682 | if haveStack.name == wantStack.name then 683 | _itemList[i].count = wantStack.count - math.min(haveStack.count, wantStack.count) 684 | end 685 | end 686 | end 687 | 688 | -- check if there are non zero entries left in the itemList 689 | for _, wantStack in pairs(_itemList) do 690 | if wantStack.count > 0 then return false, _itemList end 691 | end 692 | return true 693 | end 694 | 695 | -- places a chest to pull specific items from an inventory, then sucks the items from the intermediate chest 696 | -- !!! requires a chest in the inventory !!! 697 | function pullItemsFromChest(itemList, inventorySide, allowPartial) 698 | -- TODO: check if the result will actually fit in the turtle 699 | local srcChest = peripheral.wrap(inventorySide) 700 | if not srcChest then return false, "no valid inventory at side" .. tostring(inventorySide) end 701 | if not allowPartial and not doesChestContainItemList(itemList, inventorySide) then return false, "chest is missing items" end 702 | -- place intermediate chest 703 | local side, err = placeIntermediateChest() 704 | if not side then return false, err end 705 | 706 | local _itemList = {} 707 | for pos, wantStack in pairs(itemList) do 708 | table.insert(_itemList, pos, { name = wantStack.name, count = wantStack.count }) 709 | end 710 | 711 | -- iterate chestItems and subtract from _wantList 712 | os.sleep(.5) 713 | local tmpChest = peripheral.wrap(side) 714 | if not tmpChest then return false, "temp chest could not be found" end 715 | local chestItems = srcChest.list() 716 | if not chestItems then return false, "pull inventory does not exist" end 717 | for i, wantStack in pairs(_itemList) do 718 | for j, haveStack in pairs(chestItems) do 719 | if haveStack.name == wantStack.name then 720 | local transferCount = srcChest.pushItems(peripheral.getName(tmpChest), j, _itemList[i].count) 721 | _itemList[i].count = _itemList[i].count - transferCount 722 | end 723 | end 724 | end 725 | 726 | if allowPartial then return true, _itemList end 727 | 728 | -- check if there are non zero entries left in the itemList 729 | for _, wantStack in pairs(_itemList) do 730 | if wantStack.count > 0 then return false, _itemList end 731 | end 732 | digSide(side) 733 | return true 734 | end 735 | 736 | -- intermediate chest functionality 737 | 738 | -- try placing down intermediate chest 739 | -- @param chestId string|nil mc id of the intermediate chest or nil for default 740 | function placeIntermediateChest(chestId) 741 | chestId = chestId or "chest" 742 | if not select(findItemFuzzy(chestId)) then return false, "could not find intermediate chest in inventory" end 743 | local side 744 | if placeUp() then side = "top" 745 | elseif placeDown() then side = "bottom" 746 | elseif place() then side = "front" 747 | end 748 | if not side then return false, "can not place intermediate chest anywhere" end 749 | return side 750 | end 751 | -------------------------------------------------------------------------------- /utils/textureExtractor/textureExtractor.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | const unzipper = require('unzipper'); 4 | let MC_FILE = `${process.env.APPDATA}/.minecraft/versions/1.18/1.18.jar`.replaceAll('\\', '/'); 5 | let MOD_DIR = `${process.env.USERPROFILE}/curseforge/minecraft/Instances/computercraft thing/mods`.replaceAll('\\', '/'); 6 | const { exec } = require("child_process"); 7 | 8 | function extractTexturesFromJar(fileName) { 9 | fs.createReadStream(fileName) 10 | .pipe(unzipper.Parse()) 11 | .on('entry', function (entry) { 12 | const fileName = entry.path; 13 | let regex = /assets\/(?.*)\/textures\/(?.*)\/.*\.png$/m; 14 | let match = regex.exec(fileName); 15 | if (match && match.groups.textureType == "block") { 16 | const blockPath = `textures/blocks/${match.groups.modname}` 17 | fs.mkdirSync(blockPath, { recursive: true }); 18 | entry.pipe(fs.createWriteStream(`${blockPath}/${path.parse(fileName).base}`)); 19 | } 20 | else if (match && match.groups.textureType == "item") { 21 | const itemPath = `textures/items/${match.groups.modname}` 22 | fs.mkdirSync(itemPath, { recursive: true }); 23 | entry.pipe(fs.createWriteStream(`${itemPath}/${path.parse(fileName).base}`)); 24 | } else { 25 | entry.autodrain(); 26 | } 27 | }); 28 | } 29 | 30 | function renderBlockTextures() { 31 | fs.mkdirSync('grab/rendered', { recursive: true }); 32 | return new Promise((resolve, reject) => { 33 | exec("node node_modules/minecraft-blocks-render/bin/index.js render --type png --scale 4 --renderTransparent --renderSides", (error, stdout, stderr) => { 34 | if (error) { 35 | console.log(`error: ${error.message}`); 36 | } 37 | if (stderr) { 38 | console.log(`stderr: ${stderr}`); 39 | } 40 | resolve(); 41 | }); 42 | }) 43 | } 44 | 45 | function createBlockTextures() { 46 | return new Promise(async (resolve) => { 47 | const blockTexturePath = 'textures/blocks/' 48 | for (let modName of fs.readdirSync(blockTexturePath)) { 49 | copyFolderSync(blockTexturePath + modName, 'grab/blocks'); 50 | await renderBlockTextures(); 51 | copyFolderSync('grab/rendered', 'textures/items/' + modName); 52 | fs.rmSync('grab', { recursive: true }); 53 | } 54 | resolve(); 55 | }); 56 | } 57 | 58 | function copyFolderSync(from, to) { 59 | if (!fs.existsSync(to)) fs.mkdirSync(to, { recursive: true }); 60 | fs.readdirSync(from).forEach(element => { 61 | if (fs.lstatSync(path.join(from, element)).isFile()) { 62 | fs.copyFileSync(path.join(from, element), path.join(to, element)); 63 | } else { 64 | copyFolderSync(path.join(from, element), path.join(to, element)); 65 | } 66 | }); 67 | } 68 | 69 | function pickMultiFaceBlockDisplaySide() { 70 | // this adds some basic display for e.g. furnaces who dont have a furnace.png, but only furnace_front.png 71 | fs.readdirSync('textures/blocks/').forEach(modName => { 72 | const modDir = 'textures/blocks/' + modName; 73 | fs.readdirSync(modDir).forEach(fileName => { 74 | const filePath = modDir + '/' + fileName; 75 | if (fileName.endsWith('_front.png') && !fs.existsSync(modDir + '/' + fileName.replace('_front', ''))) 76 | fs.copyFileSync(filePath, modDir + '/' + fileName.replace('_front', '')); 77 | else if (fileName.endsWith('_top.png') && !fs.existsSync(modDir + '/' + fileName.replace('_top', ''))) 78 | fs.copyFileSync(filePath, modDir + '/' + fileName.replace('_top', '')); 79 | else if (fileName.endsWith('_still.png') && !fs.existsSync(modDir + '/' + fileName.replace('_still', ''))) 80 | fs.copyFileSync(filePath, modDir + '/' + fileName.replace('_still', '')); 81 | }); 82 | }); 83 | } 84 | 85 | process.stdout.write("Gathering textures..."); 86 | if (!process.argv[2]) 87 | throw new Error("Usage: node run build-textures \nPaths might need to be absolute, but I'm not sure."); 88 | MC_FILE = process.argv[2].replaceAll('\\\\', '/').replaceAll('\\', '/'); 89 | MOD_DIR = process.argv[3] ? process.argv[3].replaceAll('\\\\', '/').replaceAll('\\', '/') : '.'; 90 | 91 | extractTexturesFromJar(MC_FILE) 92 | fs.readdirSync(MOD_DIR).forEach(fileName => { 93 | if (fileName.endsWith('.jar')) 94 | extractTexturesFromJar(MOD_DIR + '/' + fileName) 95 | }); 96 | process.stdout.write("DONE\nRendering blocks for display as items..."); 97 | createBlockTextures() 98 | .then(() => { 99 | process.stdout.write("DONE\nSelecting appropriate side image to display for multi side blocks..."); 100 | pickMultiFaceBlockDisplaySide(); 101 | console.log("DONE\n\u001b[33mIF YOU GET ANY ERRORS, JUST RERUN THE COMMAND UNTIL NO ERRORS POP UP. Also please make sure to run this command at least twice to also get some basic support for multi side blocks like the furnace!\u001b[0m"); 102 | }); 103 | -------------------------------------------------------------------------------- /utils/zipPackaged.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const archiver = require('archiver'); 3 | 4 | const zipFolder = (sourceFolders, outputPath) => { 5 | const output = fs.createWriteStream(outputPath); 6 | const archive = archiver('zip', { zlib: { level: 9 } }); 7 | 8 | output.on('close', () => { 9 | console.log('Zip archive created successfully.'); 10 | }); 11 | 12 | archive.on('error', (err) => { 13 | throw err; 14 | }); 15 | 16 | archive.pipe(output); 17 | 18 | sourceFolders.forEach((folder) => { 19 | archive.glob(folder); 20 | }); 21 | 22 | binaries.forEach((folder) => { 23 | archive.directory(folder, false); 24 | }); 25 | 26 | archive.finalize(); 27 | }; 28 | 29 | const assets = [ 30 | 'dist/**/*', 31 | 'textures/turtle/**/*', 32 | 'textures/**/.gitkeep', 33 | 'turtle/**/*', 34 | 'src/turtlePrograms/**/*', 35 | ]; 36 | const binaries = [ 37 | 'packaged/' 38 | ] 39 | const outputPath = 'packagedZip/cc-remote-controller-1.2.0.zip'; 40 | 41 | if (!fs.existsSync('packagedZip')) { 42 | fs.mkdirSync('packagedZip'); 43 | } 44 | 45 | console.log('Packaging will take some time...') 46 | zipFolder(assets, outputPath); -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite' 2 | import vue from '@vitejs/plugin-vue' 3 | 4 | // https://vitejs.dev/config/ 5 | export default defineConfig({ 6 | plugins: [vue()] 7 | }) 8 | --------------------------------------------------------------------------------