View difference between Paste ID: cMdpMdRf and CtcSGkpc
SHOW: | | - or go back to the newest paste.
1
output_dir = ...
2
if not output_dir then
3
    output_dir = ''
4
end
5
path = shell.resolve(output_dir)
6
if not fs.isDir(path) then
7
    error(path .. ' is not a directory')
8
end
9
10
files = {
11
    ["LICENSE"] = [===[MIT License
12
13
Copyright (c) 2020 MerlinLikeTheWizard
14
15
Permission is hereby granted, free of charge, to any person obtaining a copy
16
of this software and associated documentation files (the "Software"), to deal
17
in the Software without restriction, including without limitation the rights
18
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
copies of the Software, and to permit persons to whom the Software is
20
furnished to do so, subject to the following conditions:
21
22
The above copyright notice and this permission notice shall be included in all
23
copies or substantial portions of the Software.
24
25
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
SOFTWARE.]===],
32
    ["README.md"] = [===[# Mastermine
33
A fully automated strip mining network for ComputerCraft turtles!
34
35
Here's all the code for anyone who is interested! Check out the tutorial below for installation instructions.
36
37
Also, here are steps for a quick install via pastebin:
38
39
1. Place your advanced computer next to a disk drive with a blank disk in.
40
2. Run `pastebin get CtcSGkpc mastermine.lua`
41
3. Run `mastermine disk`
42
4. Run `disk/hub.lua`
43
44
## Play with or without PeripheralsPlusOne
45
46
I highly recommend using the PeripheralsPlusOne and its chunky turtles, but upon popular request I added the ability to disable the need for chunky turtle pairs. Just go to the config and set `use_chunky_turtles = false`
47
48
## Video description:
49
50
[![https://www.youtube.com/watch?v=2I2VXl9Pg6Q](https://img.youtube.com/vi/2I2VXl9Pg6Q/0.jpg)](https://www.youtube.com/watch?v=2I2VXl9Pg6Q)
51
52
## Video tutorial:
53
54
[![https://www.youtube.com/watch?v=2DTP1LXuiCg](https://img.youtube.com/vi/2DTP1LXuiCg/0.jpg)](https://www.youtube.com/watch?v=2DTP1LXuiCg)
55
56
## User commands:
57
58
* `on/go`
59
* `off/stop`
60
* `turtle <#> <action>`
61
* `update <#>`
62
* `reboot <#>`
63
* `shutdown <#>`
64
* `reset <#>`
65
* `clear <#>`
66
* `halt <#>`
67
* `return <#>`
68
* `hubupdate`
69
* `hubreboot`
70
* `hubshutdown`
71
72
73
use `*` as notation for all turtles
74
75
76
## Required mods:
77
78
https://www.curseforge.com/minecraft/mc-mods/cc-tweaked
79
80
https://github.com/rolandoislas/PeripheralsPlusOne
81
82
Required by PeripheralsPlusOne: https://www.curseforge.com/minecraft/mc-mods/the-framework]===],
83
    ["hub.lua"] = [===[if fs.exists('/disk/hub_files/session_id') then
84
    fs.delete('/disk/hub_files/session_id')
85
end
86
if fs.exists('/session_id') then
87
    fs.copy('/session_id', '/disk/hub_files/session_id')
88
end
89
if fs.exists('/disk/hub_files/mine') then
90
    fs.delete('/disk/hub_files/mine')
91
end
92
if fs.exists('/mine') then
93
    fs.copy('/mine', '/disk/hub_files/mine')
94
end
95
96
for _, filename in pairs(fs.list('/')) do
97
    if filename ~= 'rom' and filename ~= 'disk' and filename ~= 'openp' and filename ~= 'ppp' and filename ~= 'persistent' then
98
        fs.delete(filename)
99
    end
100
end
101
for _, filename in pairs(fs.list('/disk/hub_files')) do
102
    fs.copy('/disk/hub_files/' .. filename, '/' .. filename)
103
end
104
os.reboot()]===],
105
    ["pocket.lua"] = [===[local src, dest = ...
106
107
fs.copy(fs.combine(src, 'pocket_files/update'), fs.combine(dest, 'update'))
108
file = fs.open(fs.combine(dest, 'hub_id'), 'w')
109
file.write(os.getComputerID())
110
file.close()]===],
111
    ["turtle.lua"] = [===[for _, filename in pairs(fs.list('/')) do
112
    if filename ~= 'rom' and filename ~= 'disk' and filename ~= 'openp' and filename ~= 'ppp' and filename ~= 'persistent' then
113
        fs.delete(filename)
114
    end
115
end
116
117
for _, filename in pairs(fs.list('/disk/turtle_files')) do
118
    fs.copy('/disk/turtle_files/' .. filename, '/' .. filename)
119
end
120
121
print("Enter ID of Hub computer to link to: ")
122
hub_id = tonumber(read())
123
if hub_id == nil then
124
    error("Invalid ID")
125
end
126
127
file = fs.open('/hub_id', 'w')
128
file.write(hub_id)
129
file.close()
130
131
print("Linked")
132
133
sleep(1)
134
os.reboot()]===],
135
    ["turtle_files/actions.lua"] = [===[inf = basics.inf
136
str_xyz = basics.str_xyz
137
138
--lua_print = print
139
--log_file = fs.open('log.txt', 'w')
140
--function print(thing)
141
--    lua_print(thing)
142
--    log_file.writeLine(thing)
143
--end
144
    
145
146
bumps = {
147
    north = { 0,  0, -1},
148
    south = { 0,  0,  1},
149
    east  = { 1,  0,  0},
150
    west  = {-1,  0,  0},
151
}
152
153
154
left_shift = {
155
    north = 'west',
156
    south = 'east',
157
    east  = 'north',
158
    west  = 'south',
159
}
160
161
162
right_shift = {
163
    north = 'east',
164
    south = 'west',
165
    east  = 'south',
166
    west  = 'north',
167
}
168
169
170
reverse_shift = {
171
    north = 'south',
172
    south = 'north',
173
    east  = 'west',
174
    west  = 'east',
175
}
176
177
178
move = {
179
    forward = turtle.forward,
180
    up      = turtle.up,
181
    down    = turtle.down,
182
    back    = turtle.back,
183
    left    = turtle.turnLeft,
184
    right   = turtle.turnRight
185
}
186
187
188
detect = {
189
    forward = turtle.detect,
190
    up      = turtle.detectUp,
191
    down    = turtle.detectDown
192
}
193
194
195
inspect = {
196
    forward = turtle.inspect,
197
    up      = turtle.inspectUp,
198
    down    = turtle.inspectDown
199
}
200
201
202
dig = {
203
    forward = turtle.dig,
204
    up      = turtle.digUp,
205
    down    = turtle.digDown
206
}
207
208
attack = {
209
    forward = turtle.attack,
210
    up      = turtle.attackUp,
211
    down    = turtle.attackDown
212
}
213
214
215
getblock = {
216
    
217
    up = function(pos, fac)
218
        if not pos then pos = state.location end
219
        if not fac then fac = state.orientation end
220
        return {x = pos.x, y = pos.y + 1, z = pos.z}
221
    end,
222
223
    down = function(pos, fac)
224
        if not pos then pos = state.location end
225
        if not fac then fac = state.orientation end
226
        return {x = pos.x, y = pos.y - 1, z = pos.z}
227
    end,
228
229
    forward = function(pos, fac)
230
        if not pos then pos = state.location end
231
        if not fac then fac = state.orientation end
232
        local bump = bumps[fac]
233
        return {x = pos.x + bump[1], y = pos.y + bump[2], z = pos.z + bump[3]}
234
    end,
235
    
236
    back = function(pos, fac)
237
        if not pos then pos = state.location end
238
        if not fac then fac = state.orientation end
239
        local bump = bumps[fac]
240
        return {x = pos.x - bump[1], y = pos.y - bump[2], z = pos.z - bump[3]}
241
    end,
242
    
243
    left = function(pos, fac)
244
        if not pos then pos = state.location end
245
        if not fac then fac = state.orientation end
246
        local bump = bumps[left_shift[fac]]
247
        return {x = pos.x + bump[1], y = pos.y + bump[2], z = pos.z + bump[3]}
248
    end,
249
    
250
    right = function(pos, fac)
251
        if not pos then pos = state.location end
252
        if not fac then fac = state.orientation end
253
        local bump = bumps[right_shift[fac]]
254
        return {x = pos.x + bump[1], y = pos.y + bump[2], z = pos.z + bump[3]}
255
    end,
256
}
257
258
259
function digblock(direction)
260
    dig[direction]()
261
    return true
262
end
263
264
265
function delay(duration)
266
    sleep(duration)
267
    return true
268
end
269
270
271
function up()
272
    return go('up')
273
end
274
275
276
function forward()
277
    return go('forward')
278
end
279
280
281
function down()
282
    return go('down')
283
end
284
285
286
function back()
287
    return go('back')
288
end
289
290
291
function left()
292
    return go('left')
293
end
294
295
296
function right()
297
    return go('right')
298
end
299
300
301
function follow_route(route)
302
    for step in route:gmatch'.' do
303
        if step == 'u' then
304
            if not go('up')      then return false end
305
        elseif step == 'f' then
306
            if not go('forward') then return false end
307
        elseif step == 'd' then
308
            if not go('down')    then return false end
309
        elseif step == 'b' then
310
            if not go('back')    then return false end
311
        elseif step == 'l' then
312
            if not go('left')    then return false end
313
        elseif step == 'r' then
314
            if not go('right')   then return false end
315
        end
316
    end
317
    return true
318
end
319
                    
320
                    
321
function face(orientation)
322
    if state.orientation == orientation then
323
        return true
324
    elseif right_shift[state.orientation] == orientation then
325
        if not go('right') then return false end
326
    elseif left_shift[state.orientation] == orientation then
327
        if not go('left') then return false end
328
    elseif right_shift[right_shift[state.orientation]] == orientation then
329
        if not go('right') then return false end
330
        if not go('right') then return false end
331
    else
332
        return false
333
    end
334
    return true
335
end
336
337
338
function log_movement(direction)
339
    if direction == 'up' then
340
        state.location.y = state.location.y +1
341
    elseif direction == 'down' then
342
        state.location.y = state.location.y -1
343
    elseif direction == 'forward' then
344
        bump = bumps[state.orientation]
345
        state.location = {x = state.location.x + bump[1], y = state.location.y + bump[2], z = state.location.z + bump[3]}
346
    elseif direction == 'back' then
347
        bump = bumps[state.orientation]
348
        state.location = {x = state.location.x - bump[1], y = state.location.y - bump[2], z = state.location.z - bump[3]}
349
    elseif direction == 'left' then
350
        state.orientation = left_shift[state.orientation]
351
    elseif direction == 'right' then
352
        state.orientation = right_shift[state.orientation]
353
    end
354
    return true
355
end
356
357
358
function go(direction, nodig)
359
    if not nodig then
360
        if detect[direction] then
361
            if detect[direction]() then
362
                safedig(direction)
363
            end
364
        end
365
    end
366
    if not move[direction] then
367
        return false
368
    end
369
    if not move[direction]() then
370
        if attack[direction] then
371
            attack[direction]()
372
        end
373
        return false
374
    end
375
    log_movement(direction)
376
    return true
377
end
378
379
380
function go_to_axis(axis, coordinate, nodig)
381
    local delta = coordinate - state.location[axis]
382
    if delta == 0 then
383
        return true
384
    end
385
    
386
    if axis == 'x' then
387
        if delta > 0 then
388
            if not face('east') then return false end
389
        else
390
            if not face('west') then return false end
391
        end
392
    elseif axis == 'z' then
393
        if delta > 0 then
394
            if not face('south') then return false end
395
        else
396
            if not face('north') then return false end
397
        end
398
    end
399
    
400
    for i = 1, math.abs(delta) do
401
        if axis == 'y' then
402
            if delta > 0 then
403
                if not go('up', nodig) then return false end
404
            else
405
                if not go('down', nodig) then return false end
406
            end
407
        else
408
            if not go('forward', nodig) then return false end
409
        end
410
    end
411
    return true
412
end
413
414
415
function go_to(end_location, end_orientation, path, nodig)
416
    if path then
417
        for axis in path:gmatch'.' do
418
            if not go_to_axis(axis, end_location[axis], nodig) then return false end
419
        end
420
    elseif end_location.path then
421
        for axis in end_location.path:gmatch'.' do
422
            if not go_to_axis(axis, end_location[axis], nodig) then return false end
423
        end
424
    else
425
        return false
426
    end
427
    if end_orientation then
428
        if not face(end_orientation) then return false end
429
    elseif end_location.orientation then
430
        if not face(end_location.orientation) then return false end
431
    end
432
    return true
433
end
434
435
436
function go_route(route, xyzo)
437
    local xyz_string
438
    if xyzo then
439
        xyz_string = str_xyz(xyzo)
440
    end
441
    local location_str = basics.str_xyz(state.location)
442
    while route[location_str] and location_str ~= xyz_string do
443
        if not go_to(route[location_str], nil, 'xyz') then return false end
444
        location_str = basics.str_xyz(state.location)
445
    end
446
    if xyzo then
447
        if location_str ~= xyz_string then
448
            return false
449
        end
450
        if xyzo.orientation then
451
            if not face(xyzo.orientation) then return false end
452
        end
453
    end
454
    return true
455
end
456
457
458
function go_to_home()
459
    state.updated_not_home = nil
460
    if basics.in_area(state.location, config.locations.home_area) then
461
        return true
462
    elseif basics.in_area(state.location, config.locations.greater_home_area) then
463
        if not go_to_home_exit() then return false end
464
    elseif basics.in_area(state.location, config.locations.waiting_room_area) then
465
        if not go_to(config.locations.mine_exit, nil, config.paths.waiting_room_to_mine_exit, true) then return false end
466
    elseif state.location.y < config.locations.mine_enter.y then
467
        return false
468
    end
469
    if config.locations.main_loop_route[basics.str_xyz(state.location)] then
470
        if not go_route(config.locations.main_loop_route, config.locations.home_enter) then return false end
471
    elseif basics.in_area(state.location, config.locations.control_room_area) then
472
        if not go_to(config.locations.home_enter, nil, config.paths.control_room_to_home_enter, true) then return false end
473
    else
474
        return false
475
    end
476
    if not forward() then return false end
477
    while detect.down() do
478
        if not forward() then return false end
479
    end
480
    if not down() then return false end
481
    if not right() then return false end
482
    if not right() then return false end
483
    return true
484
end
485
486
487
function go_to_home_exit()
488
    if basics.in_area(state.location, config.locations.greater_home_area) then
489
        if not go_to(config.locations.home_exit, nil, config.paths.home_to_home_exit) then return false end
490
    elseif config.locations.main_loop_route[basics.str_xyz(state.location)] then
491
        if not go_route(config.locations.main_loop_route, config.locations.home_exit) then return false end
492
    else
493
        return false
494
    end
495
    return true
496
end
497
498
499
function go_to_item_drop()
500
    if not config.locations.main_loop_route[basics.str_xyz(state.location)] then
501
        if not go_to_home() then return false end
502
        if not go_to_home_exit() then return false end
503
    end
504
    if not go_route(config.locations.main_loop_route, config.locations.item_drop) then return false end
505
    return true
506
end
507
508
509
function go_to_refuel()
510
    if not config.locations.main_loop_route[basics.str_xyz(state.location)] then
511
        if not go_to_home() then return false end
512
        if not go_to_home_exit() then return false end
513
    end
514
    if not go_route(config.locations.main_loop_route, config.locations.refuel) then return false end
515
    return true
516
end
517
518
519
function go_to_waiting_room()
520
    if not basics.in_area(state.location, config.locations.waiting_room_line_area) then
521
        if not go_to_home() then return false end
522
    end
523
    if not go_to(config.locations.waiting_room, nil, config.paths.home_to_waiting_room) then return false end
524
    return true
525
end
526
527
528
function go_to_mine_enter()
529
    if not go_route(config.locations.waiting_room_to_mine_enter_route) then return false end
530
    return true
531
end
532
533
534
function go_to_strip(strip)
535
    if state.location.y < config.locations.mine_enter.y or basics.in_location(state.location, config.locations.mine_enter) then
536
        if state.type == 'mining' then
537
            local bump = bumps[strip.orientation]
538
            strip = {
539
                x = strip.x + bump[1],
540
                y = strip.y + bump[2],
541
                z = strip.z + bump[3],
542
                orientation = strip.orientation
543
            }
544
        end
545
        if not go_to(strip, nil, config.paths.mine_enter_to_strip) then return false end
546
        return true
547
    end
548
end
549
550
551
function go_to_mine_exit(strip)
552
    if state.location.y < config.locations.mine_enter.y or (state.location.x == config.locations.mine_exit.x and state.location.z == config.locations.mine_exit.z) then
553
        if state.location.x == config.locations.mine_enter.x and state.location.z == config.locations.mine_enter.z then
554
            -- If directly under mine_enter, shift over to exit
555
            if not go_to_axis('z', config.locations.mine_exit.z) then return false end
556
        elseif state.location.x ~= config.locations.mine_exit.x or state.location.z ~= config.locations.mine_exit.z then
557
            -- If NOT directly under mine_exit go to proper y
558
            if not go_to_axis('y', strip.y + 1) then return false end
559
            if state.location.z ~= config.locations.mine_enter.z and strip.z ~= config.locations.mine_enter.z then
560
                -- If not in main_shaft, find your strip
561
                if not go_to_axis('x', strip.x) then return false end
562
            end
563
            if state.location.x ~= config.locations.mine_exit.x then
564
                -- If not in strip x = origin, go to main_shaft
565
                if not go_to_axis('z', config.locations.mine_enter.z) then return false end
566
            end
567
        end
568
        if not go_to(config.locations.mine_exit, nil, 'xzy') then return false end
569
        return true
570
    end
571
end
572
573
574
function safedig(direction)
575
    -- DIG IF BLOCK NOT ON BLACKLIST
576
    if not direction then
577
        direction = 'forward'
578
    end
579
    
580
    local block_name = ({inspect[direction]()})[2].name
581
    if block_name then
582
        for _, word in pairs(config.dig_disallow) do
583
            if string.find(string.lower(block_name), word) then
584
                return false
585
            end
586
        end
587
588
        return dig[direction]()
589
    end
590
    return true
591
end
592
593
594
function dump_items(omit)
595
    for slot = 1, 16 do
596
        if turtle.getItemCount(slot) > 0 and ((not omit) or (not omit[turtle.getItemDetail(slot).name])) then
597
            turtle.select(slot)
598
            if not turtle.drop() then return false end
599
        end
600
    end
601
    return true
602
end
603
    
604
605
606
function prepare(min_fuel_amount)
607
    if state.item_count > 0 then
608
        if not go_to_item_drop() then return false end
609
        if not dump_items(config.fuelnames) then return false end
610
    end
611
    local min_fuel_amount = min_fuel_amount + config.fuel_padding
612
    if not go_to_refuel() then return false end
613
    if not dump_items() then return false end
614
    turtle.select(1)
615
    if turtle.getFuelLevel() ~= 'unlimited' then
616
        while turtle.getFuelLevel() < min_fuel_amount do
617
            if not turtle.suck(math.min(64, math.ceil(min_fuel_amount / config.fuel_per_unit))) then return false end
618
            turtle.refuel()
619
        end
620
    end
621
    return true
622
end
623
624
625
function calibrate()
626
    -- GEOPOSITION BY MOVING TO ADJACENT BLOCK AND BACK
627
    local sx, sy, sz = gps.locate()
628
--    if sx == config.interface.x and sy == config.interface.y and sz == config.interface.z then
629
--        refuel()
630
--    end
631
    if not sx or not sy or not sz then
632
        return false
633
    end
634
    for i = 1, 4 do
635
        -- TRY TO FIND EMPTY ADJACENT BLOCK
636
        if not turtle.detect() then
637
            break
638
        end
639
        if not turtle.turnRight() then return false end
640
    end
641
    if turtle.detect() then
642
        -- TRY TO DIG ADJACENT BLOCK
643
        for i = 1, 4 do
644
            safedig('forward')
645
            if not turtle.detect() then
646
                break
647
            end
648
            if not turtle.turnRight() then return false end
649
        end
650
        if turtle.detect() then
651
            return false
652
        end
653
    end
654
    if not turtle.forward() then return false end
655
    local nx, ny, nz = gps.locate()
656
    if nx == sx + 1 then
657
        state.orientation = 'east'
658
    elseif nx == sx - 1 then
659
        state.orientation = 'west'
660
    elseif nz == sz + 1 then
661
        state.orientation = 'south'
662
    elseif nz == sz - 1 then
663
        state.orientation = 'north'
664
    else
665
        return false
666
    end
667
    state.location = {x = nx, y = ny, z = nz}
668
    print('Calibrated to ' .. str_xyz(state.location, state.orientation))
669
    
670
    back()
671
    
672
    if basics.in_area(state.location, config.locations.home_area) then
673
        face(left_shift[left_shift[config.locations.homes.increment]])
674
    end
675
    
676
    return true
677
end
678
679
680
function initialize(session_id, config_values)
681
    -- INITIALIZE TURTLE
682
    
683
    state.session_id = session_id
684
    
685
    -- COPY CONFIG DATA INTO MEMORY
686
    for k, v in pairs(config_values) do
687
        config[k] = v
688
    end
689
    
690
    -- DETERMINE TURTLE TYPE
691
    state.peripheral_left = peripheral.getType('left')
692
    state.peripheral_right = peripheral.getType('right')
693
    if state.peripheral_left == 'chunkLoader' or state.peripheral_right == 'chunkLoader' or state.peripheral_left == 'chunky' or state.peripheral_right == 'chunky' then
694
        state.type = 'chunky'
695
        for k, v in pairs(config.chunky_turtle_locations) do
696
            config.locations[k] = v
697
        end
698
    else
699
        state.type = 'mining'
700
        for k, v in pairs(config.mining_turtle_locations) do
701
            config.locations[k] = v
702
        end
703
        if state.peripheral_left == 'modem' then
704
            state.peripheral_right = 'pick'
705
        else
706
            state.peripheral_left = 'pick'
707
        end
708
    end
709
    
710
    state.request_id = 1
711
    state.initialized = true
712
    return true
713
end
714
715
716
function getcwd()
717
    local running_program = shell.getRunningProgram()
718
    local program_name = fs.getName(running_program)
719
    return "/" .. running_program:sub(1, #running_program - #program_name)
720
end
721
722
723
function pass()
724
    return true
725
end
726
727
728
function dump(direction)
729
    if not face(direction) then return false end
730
    if ({inspect.forward()})[2].name ~= 'computercraft:turtle_advanced' then
731
        return false
732
    end
733
    for slot = 1, 16 do
734
        if turtle.getItemCount(slot) > 0 then
735
            turtle.select(slot)
736
            turtle.drop()
737
        end
738
    end
739
    return true
740
end
741
742
743
function checkTags(data)
744
    if type(data.tags) ~= 'table' then
745
        return false
746
    end
747
    if not config.blocktags then
748
        return false
749
    end
750
    for k,v in pairs(data.tags) do
751
        if config.blocktags[k] then
752
            return true
753
        end
754
    end
755
    return false
756
end
757
758
759
function detect_ore(direction)
760
    local block = ({inspect[direction]()})[2]
761
    if config.orenames[block.name] then
762
        return true
763
    elseif checkTags(block) then
764
        return true
765
    end
766
    return false
767
end
768
769
770
function scan(valid, ores)
771
    local checked_left  = false
772
    local checked_right = false
773
    
774
    local f = str_xyz(getblock.forward())
775
    local u = str_xyz(getblock.up())
776
    local d = str_xyz(getblock.down())
777
    local l = str_xyz(getblock.left())
778
    local r = str_xyz(getblock.right())
779
    local b = str_xyz(getblock.back())
780
    
781
    if not valid[f] and valid[f] ~= false then
782
        valid[f] = detect_ore('forward')
783
        ores[f] = valid[f]
784
    end
785
    if not valid[u] and valid[u] ~= false then
786
        valid[u] = detect_ore('up')
787
        ores[u] = valid[u]
788
    end
789
    if not valid[d] and valid[d] ~= false then
790
        valid[d] = detect_ore('down')
791
        ores[d] = valid[d]
792
    end
793
    if not valid[l] and valid[l] ~= false then
794
        left()
795
        checked_left = true
796
        valid[l] = detect_ore('forward')
797
        ores[l] = valid[l]
798
    end
799
    if not valid[r] and valid[r] ~= false then
800
        right()
801
        if checked_left then
802
            right()
803
        end
804
        checked_right = true
805
        valid[r] = detect_ore('forward')
806
        ores[r] = valid[r]
807
    end
808
    if not valid[b] and valid[b] ~= false then
809
        if checked_right then
810
            right()
811
        elseif checked_left then
812
            left()
813
        else
814
            right(2)
815
        end
816
        valid[b] = detect_ore('forward')
817
        ores[b] = valid[b]
818
    end
819
end
820
821
822
function fastest_route(area, pos, fac, end_locations)
823
    local queue = {}
824
    local explored = {}
825
    table.insert(queue,
826
        {
827
            coords = {x = pos.x, y = pos.y, z = pos.z},
828
            facing = fac,
829
            path = '',
830
        }
831
    )
832
    explored[str_xyz(pos, fac)] = true
833
834
    while #queue > 0 do
835
        local node = table.remove(queue, 1)
836
        if end_locations[str_xyz(node.coords)] or end_locations[str_xyz(node.coords, node.facing)] then
837
            return node.path
838
        end
839
        for _, step in pairs({
840
                {coords = node.coords,                                facing = left_shift[node.facing],  path = node.path .. 'l'},
841
                {coords = node.coords,                                facing = right_shift[node.facing], path = node.path .. 'r'},
842
                {coords = getblock.forward(node.coords, node.facing), facing = node.facing,              path = node.path .. 'f'},
843
                {coords = getblock.up(node.coords, node.facing),      facing = node.facing,              path = node.path .. 'u'},
844
                {coords = getblock.down(node.coords, node.facing),    facing = node.facing,              path = node.path .. 'd'},
845
                }) do
846
            explore_string = str_xyz(step.coords, step.facing)
847
            if not explored[explore_string] and (not area or area[str_xyz(step.coords)]) then
848
                explored[explore_string] = true
849
                table.insert(queue, step)
850
            end
851
        end
852
    end
853
end
854
855
856
function mine_vein(direction)
857
    if not face(direction) then return false end
858
    
859
    -- Log starting location
860
    local start = str_xyz({x = state.location.x, y = state.location.y, z = state.location.z}, state.orientation)
861
862
    -- Begin block map
863
    local valid = {}
864
    local ores = {}
865
    valid[str_xyz(state.location)] = true
866
    valid[str_xyz(getblock.back(state.location, state.orientation))] = false
867
    for i = 1, config.vein_max do
868
869
        -- Scan adjacent
870
        scan(valid, ores)
871
872
        -- Search for nearest ore
873
        local route = fastest_route(valid, state.location, state.orientation, ores)
874
875
        -- Check if there is one
876
        if not route then
877
            break
878
        end
879
880
        -- Retrieve ore
881
        turtle.select(1)
882
        if not follow_route(route) then return false end
883
        ores[str_xyz(state.location)] = nil
884
885
    end
886
887
    if not follow_route(fastest_route(valid, state.location, state.orientation, {[start] = true})) then return false end
888
889
    if detect.up() then
890
        safedig('up')
891
    end
892
    
893
    return true
894
end
895
896
897
function clear_gravity_blocks()
898
    for _, direction in pairs({'forward', 'up'}) do
899
        while config.gravitynames[ ({inspect[direction]()})[2].name ] do
900
            safedig(direction)
901
            sleep(1)
902
        end
903
    end
904
    return true
905
end]===],
906
    ["turtle_files/basics.lua"] = [===[inf = 1e309
907
908
bumps = {
909
    north = { 0,  0, -1},
910
    south = { 0,  0,  1},
911
    east  = { 1,  0,  0},
912
    west  = {-1,  0,  0},
913
}
914
915
left_shift = {
916
    north = 'west',
917
    south = 'east',
918
    east  = 'north',
919
    west  = 'south',
920
}
921
922
right_shift = {
923
    north = 'east',
924
    south = 'west',
925
    east  = 'south',
926
    west  = 'north',
927
}
928
929
reverse_shift = {
930
    north = 'south',
931
    south = 'north',
932
    east  = 'west',
933
    west  = 'east',
934
}
935
936
function dprint(thing)
937
    -- PRINT; IF TABLE PRINT EACH ITEM
938
    if type(thing) == 'table' then
939
        for k, v in pairs(thing) do
940
            print(tostring(k) .. ': ' .. tostring(v))
941
        end
942
    else
943
        print(thing)
944
    end
945
    return true
946
end
947
948
949
function str_xyz(coords, facing)
950
    if facing then
951
        return coords.x .. ',' .. coords.y .. ',' .. coords.z .. ':' .. facing
952
    else
953
        return coords.x .. ',' .. coords.y .. ',' .. coords.z
954
    end
955
end
956
957
958
function distance(point_1, point_2)
959
    return math.abs(point_1.x - point_2.x)
960
         + math.abs(point_1.y - point_2.y)
961
         + math.abs(point_1.z - point_2.z)
962
end
963
964
965
function in_area(xyz, area)
966
    return xyz.x <= area.max_x and xyz.x >= area.min_x and xyz.y <= area.max_y and xyz.y >= area.min_y and xyz.z <= area.max_z and xyz.z >= area.min_z
967
end
968
969
970
function in_location(xyzo, location)
971
    for _, axis in pairs({'x', 'y', 'z'}) do
972
        if location[axis] then
973
            if location[axis] ~= xyzo[axis] then
974
                return false
975
            end
976
        end
977
    end
978
    return true
979
end]===],
980
    ["turtle_files/config.lua"] = [===[]===],
981
    ["turtle_files/mastermine.lua"] = [===[function parse_requests()
982
    -- PROCESS ALL REDNET REQUESTS
983
    while #state.requests > 0 do
984
        local request = table.remove(state.requests, 1)
985
        sender, message, protocol = request[1], request[2], request[3]
986
        if message.action == 'shutdown' then
987
            os.shutdown()
988
        elseif message.action == 'reboot' then
989
            os.reboot()
990
        elseif message.action == 'update' then
991
            os.run({}, '/update')
992
        elseif message.request_id == -1 or message.request_id == state.request_id then -- MAKE SURE REQUEST IS CURRENT
993
            if state.initialized or message.action == 'initialize' then
994
                print('Directive: ' .. message.action)
995
                state.busy = true
996
                state.success = actions[message.action](unpack(message.data)) -- EXECUTE DESIRED FUNCTION WITH DESIRED ARGUMENTS
997
                state.busy = false
998
                if not state.success then
999
                    sleep(1)
1000
                end
1001
                state.request_id = state.request_id + 1
1002
            end
1003
        end
1004
    end
1005
end
1006
1007
1008
function main()
1009
    state.last_ping = os.clock()
1010
    while true do
1011
        parse_requests()
1012
        sleep(0.3)
1013
    end
1014
end
1015
1016
1017
main()]===],
1018
    ["turtle_files/receive.lua"] = [===[-- CONTINUOUSLY RECIEVE REDNET MESSAGES
1019
while true do
1020
    signal = {rednet.receive('mastermine')}
1021
    if signal[2].action == 'shutdown' then
1022
        os.shutdown()
1023
    elseif signal[2].action == 'reboot' then
1024
        os.reboot()
1025
    elseif signal[2].action == 'update' then
1026
        os.run({}, '/update')
1027
    else
1028
        table.insert(state.requests, signal)
1029
    end
1030
end]===],
1031
    ["turtle_files/report.lua"] = [===[-- CONTINUOUSLY BROADCAST STATUS REPORTS
1032
hub_id = tonumber(fs.open('/hub_id', 'r').readAll())
1033
1034
while true do
1035
1036
    state.item_count = 0
1037
    state.empty_slot_count = 16
1038
    for slot = 1, 16 do
1039
        slot_item_count = turtle.getItemCount(slot)
1040
        if slot_item_count > 0 then
1041
            state.empty_slot_count = state.empty_slot_count - 1
1042
            state.item_count = state.item_count + slot_item_count
1043
        end
1044
    end
1045
    
1046
    rednet.send(hub_id, {
1047
            session_id       = state.session_id,
1048
            request_id       = state.request_id,
1049
            turtle_type      = state.type,
1050
            peripheral_left  = state.peripheral_left,
1051
            peripheral_right = state.peripheral_right,
1052
            updated_not_home = state.updated_not_home,
1053
            location         = state.location,
1054
            orientation      = state.orientation,
1055
            fuel_level       = turtle.getFuelLevel(),
1056
            item_count       = state.item_count,
1057
            empty_slot_count = state.empty_slot_count,
1058
            distance         = state.distance,
1059
            strip            = state.strip,
1060
            success          = state.success,
1061
            busy             = state.busy,
1062
        }, 'turtle_report')
1063
    
1064
    sleep(0.5)
1065
    
1066
end]===],
1067
    ["turtle_files/startup.lua"] = [===[-- SET LABEL
1068
os.setComputerLabel('Turtle ' .. os.getComputerID())
1069
1070
-- INITIALIZE APIS
1071
if fs.exists('/apis') then
1072
    fs.delete('/apis')
1073
end
1074
fs.makeDir('/apis')
1075
fs.copy('/config.lua', '/apis/config')
1076
fs.copy('/state.lua', '/apis/state')
1077
fs.copy('/basics.lua', '/apis/basics')
1078
fs.copy('/actions.lua', '/apis/actions')
1079
os.loadAPI('/apis/config')
1080
os.loadAPI('/apis/state')
1081
os.loadAPI('/apis/basics')
1082
os.loadAPI('/apis/actions')
1083
1084
1085
-- OPEN REDNET
1086
for _, side in pairs({'back', 'top', 'left', 'right'}) do
1087
    if peripheral.getType(side) == 'modem' then
1088
        rednet.open(side)
1089
        break
1090
    end
1091
end
1092
1093
1094
-- IF UPDATED PRINT "UPDATED"
1095
if fs.exists('/updated') then
1096
    fs.delete('/updated')
1097
    print('UPDATED')
1098
    state.updated_not_home = true
1099
end
1100
1101
1102
-- LAUNCH PROGRAMS AS SEPARATE THREADS
1103
multishell.launch({}, '/report.lua')
1104
multishell.launch({}, '/receive.lua')
1105
multishell.launch({}, '/mastermine.lua')
1106
multishell.setTitle(2, 'report')
1107
multishell.setTitle(3, 'receive')
1108
multishell.setTitle(4, 'mastermine')]===],
1109
    ["turtle_files/state.lua"] = [===[request_id = 1
1110
requests = {}
1111
busy = false]===],
1112
    ["turtle_files/update"] = [===[hub_id = tonumber(fs.open('/hub_id', 'r').readAll())
1113
1114
print('Sending update request...')
1115
rednet.send(hub_id, '/disk/turtle_files/', 'update_request')
1116
local sender, message, protocal = rednet.receive('update_package')
1117
1118
for _, file_name in pairs(fs.list('/')) do
1119
    if file_name ~= 'rom' and file_name ~= 'persistent' then
1120
        fs.delete(file_name)
1121
    end
1122
end
1123
1124
for file_name, file_contents in pairs(message) do
1125
    file = fs.open(file_name, 'w')
1126
    file.write(file_contents)
1127
    file.close()
1128
end
1129
1130
os.reboot()]===],
1131
    ["turtle_files/updated"] = [===[]===],
1132
    ["pocket_files/info.lua"] = [===[hub_id = tonumber(fs.open('/hub_id', 'r').readAll())
1133
1134
while true do
1135
    sender, hub_state, _ = rednet.receive('hub_report')
1136
    if sender == hub_id then
1137
        term.clear()
1138
        term.setCursorPos(1, 1)
1139
        term.setTextColor(colors.white)
1140
        term.write('POWER: ')
1141
        if hub_state.on then
1142
            term.setTextColor(colors.green)
1143
            print('ON')
1144
        else
1145
            term.setTextColor(colors.red)
1146
            print('OFF')
1147
        end
1148
        term.setTextColor(colors.white)
1149
        term.write('TURTLES PARKED: ')
1150
        if hub_state.turtles_parked >= hub_state.turtle_count then
1151
            term.setTextColor(colors.green)
1152
        else
1153
            term.setTextColor(colors.red)
1154
        end
1155
        term.write(hub_state.turtles_parked)
1156
    end
1157
end]===],
1158
    ["pocket_files/report.lua"] = [===[-- CONTINUOUSLY BROADCAST STATUS REPORTS
1159
hub_id = tonumber(fs.open('/hub_id', 'r').readAll())
1160
1161
while true do
1162
    
1163
    local x, y, z = gps.locate()
1164
    
1165
    rednet.send(hub_id, {
1166
            location = {x = x, y = y, z = z},
1167
        }, 'pocket_report')
1168
    
1169
    sleep(0.5)
1170
    
1171
end]===],
1172
    ["pocket_files/startup.lua"] = [===[-- SET LABEL
1173
os.setComputerLabel('pocket ' .. os.getComputerID())
1174
1175
1176
-- OPEN REDNET
1177
rednet.open('back')
1178
1179
1180
-- IF UPDATED PRINT "UPDATED"
1181
if fs.exists('/updated') then
1182
    fs.delete('/updated')
1183
    print('UPDATED')
1184
end
1185
1186
1187
-- LAUNCH PROGRAMS AS SEPARATE THREADS
1188
multishell.launch({}, '/user.lua')
1189
multishell.launch({}, '/info.lua')
1190
multishell.launch({}, '/report.lua')
1191
multishell.setTitle(2, 'usr')
1192
multishell.setTitle(3, 'info')
1193
multishell.setTitle(4, 'rep')]===],
1194
    ["pocket_files/update"] = [===[hub_id = tonumber(fs.open('/hub_id', 'r').readAll())
1195
rednet.open('back')
1196
1197
print('Sending update request...')
1198
rednet.broadcast('/disk/pocket_files/', 'update_request')
1199
local sender, message, protocal = rednet.receive('update_package')
1200
1201
for _, file_name in pairs(fs.list('/')) do
1202
    if file_name ~= 'rom' and file_name ~= 'disk' and file_name ~= 'persistent' then
1203
        fs.delete(file_name)
1204
    end
1205
end
1206
1207
for file_name, file_contents in pairs(message) do
1208
    file = fs.open(file_name, 'w')
1209
    file.write(file_contents)
1210
    file.close()
1211
end
1212
1213
os.reboot()]===],
1214
    ["pocket_files/updated"] = [===[]===],
1215
    ["pocket_files/user.lua"] = [===[-- CONTINUOUSLY AWAIT USER INPUT AND PLACE IN TABLE
1216
while true do
1217
    rednet.broadcast(read(), 'user_input')
1218
end]===],
1219
    ["hub_files/basics.lua"] = [===[inf = 1e309
1220
1221
bumps = {
1222
    north = { 0,  0, -1},
1223
    south = { 0,  0,  1},
1224
    east  = { 1,  0,  0},
1225
    west  = {-1,  0,  0},
1226
}
1227
1228
left_shift = {
1229
    north = 'west',
1230
    south = 'east',
1231
    east  = 'north',
1232
    west  = 'south',
1233
}
1234
1235
right_shift = {
1236
    north = 'east',
1237
    south = 'west',
1238
    east  = 'south',
1239
    west  = 'north',
1240
}
1241
1242
reverse_shift = {
1243
    north = 'south',
1244
    south = 'north',
1245
    east  = 'west',
1246
    west  = 'east',
1247
}
1248
1249
function dprint(thing)
1250
    -- PRINT; IF TABLE PRINT EACH ITEM
1251
    if type(thing) == 'table' then
1252
        for k, v in pairs(thing) do
1253
            print(tostring(k) .. ': ' .. tostring(v))
1254
        end
1255
    else
1256
        print(thing)
1257
    end
1258
    return true
1259
end
1260
1261
1262
function str_xyz(coords, facing)
1263
    if facing then
1264
        return coords.x .. ',' .. coords.y .. ',' .. coords.z .. ':' .. facing
1265
    else
1266
        return coords.x .. ',' .. coords.y .. ',' .. coords.z
1267
    end
1268
end
1269
1270
1271
function distance(point_1, point_2)
1272
    return math.abs(point_1.x - point_2.x)
1273
         + math.abs(point_1.y - point_2.y)
1274
         + math.abs(point_1.z - point_2.z)
1275
end
1276
1277
1278
function in_area(xyz, area)
1279
    return xyz.x <= area.max_x and xyz.x >= area.min_x and xyz.y <= area.max_y and xyz.y >= area.min_y and xyz.z <= area.max_z and xyz.z >= area.min_z
1280
end
1281
1282
1283
function in_location(xyzo, location)
1284
    for _, axis in pairs({'x', 'y', 'z'}) do
1285
        if location[axis] then
1286
            if location[axis] ~= xyzo[axis] then
1287
                return false
1288
            end
1289
        end
1290
    end
1291
    return true
1292
end]===],
1293
    ["hub_files/config.lua"] = [===[inf = 1e309
1294
1295
---==[ MINE ]==---
1296
1297
1298
-- LOCATION OF THE CENTER OF THE MINE
1299
--     the y value should be set to the height
1300
--     1 above the surface:
1301
--
1302
--            Y
1303
--     ####### #######
1304
--     ####### #######
1305
mine_entrance = {x = 104, y = 76, z = 215}
1306
c = mine_entrance
1307
1308
1309
-- WHETHER OR NOT TURTLES NEED PAIRS
1310
--     added this because a good number of
1311
--     people were asking for the ability to
1312
--     disale chunky turtles in case they
1313
--     couldn't access the peripherals mod.
1314
--     WARNING: not using chunky turtles will
1315
--     result in narcoleptic turtles!
1316-
use_chunky_turtles = true
1316+
use_chunky_turtles = false
1317
1318
1319
-- SPACE IN BLOCKS BETWEEN MINESHAFTS
1320
--     too close means less chance of finding
1321
--     ore veins, too far means longer commute
1322
--     times for turtles.
1323
grid_width = 8
1324
1325
1326
-- MAXIMUM MINING AMOUNT PER TRIP
1327
-- PER TURTLE
1328
--     most efficient would be to make this
1329
--     number huge, but turtles may be gone a
1330
--     while (plus harder to recall).
1331
mission_length = 150
1332
1333
1334
-- MAXIMUM BLOCKS A TURTLE MINES IN A
1335
-- SINGLE ORE VEIN
1336
--     veins can contain multiple types of ore
1337
--     and still count as one. also turtles will
1338
--     continue on a vein even when their
1339
--     inventory fills up, so this prevents them
1340
--     losing too many rousources.
1341
vein_max = 64
1342
1343
1344
-- EXTRA FUEL FOR TURTLES TO BRING ALONG,
1345
-- JUST IN CASE
1346
fuel_padding = 30
1347
1348
1349
-- FUEL PER ITEM 
1350
--     for coal default is 80. Other fuel sources
1351
--     can be used without changing this number,
1352
--     should be fine.
1353
fuel_per_unit = 80
1354
1355
1356
-- TIME AFTER LAST PING TO DECLARE TURTLE
1357
-- DISCONNECTED
1358
turtle_timeout = 5
1359
1360
1361
-- TIME AFTER LAST PING TO DECLARE POCKET
1362
-- COMPUTER DISCONNECTED
1363
pocket_timeout = 5
1364
1365
1366
-- TIME TO WAIT AFTER SENDING TASK WITH NO
1367
-- RESPONSE TO RESEND
1368
task_timeout = 0.5
1369
1370
1371
-- EVERY BLOCK NAME CONTAINING ANY OF THESE
1372
-- STRINGS WILL NOT BE MINED
1373
--     e.g. "chest" will prevent "minecraft:trapped_chest".
1374
--     ore types should not be put on this list,
1375
--     but if not desired should be removed from
1376
--     <orenames> below.
1377
dig_disallow = {
1378
    'computer',
1379
    'chest',
1380
    'chair',
1381
}
1382
1383
1384
mine_levels = {
1385
    -- LEVELS INCLUDED IN THE MINE
1386
    --     turtles will pick randomly with weight
1387
    --     between each listed level.
1388
    --
1389
    -- Level chances should sum to 1.0
1390
    -- e.g.
1391
    -- 
1392
    -- {level = 50, chance = 0.3},
1393
    -- {level = 40, chance = 0.2},
1394
    -- {level = 12, chance = 0.5},
1395
1396
    {level = 63, chance = 1.0},
1397
}
1398
1399
1400
paths = {
1401
    -- THE ORDER IN WHICH TURTLES WILL
1402
    -- TRAVERSE AXES BETWEEN AREAS
1403
    --     recommended not to change this one.
1404
    home_to_home_exit          = 'zyx',
1405
    control_room_to_home_enter = 'yzx',
1406
    home_to_waiting_room       = 'zyx',
1407
    waiting_room_to_mine_exit  = 'yzx',
1408
    mine_enter_to_strip        = 'yxz',
1409
}
1410
1411
1412
locations = {
1413
    -- THE VARIUS PLACES THE TURTLES MOVE
1414
    -- BETWEEN
1415
    --     coordinates are relative to the
1416
    --     <mine_center> variable. areas are for
1417
    --     altering turtle behavior to prevent
1418
    --     collisions and stuff.
1419
1420
     -- THE BLOCK TURTLES WILL GO TO BEFORE
1421
     -- DECENDING
1422
    mine_enter = {x = c.x+0, y = c.y+0, z = c.z+0},
1423
1424
     -- THE BLOCK TURTLES WILL COME UP TO
1425
     -- FROM THE MINE
1426
     --     one block higher by default.
1427
    mine_exit = {x = c.x+0, y = c.y+1, z = c.z+1},
1428
1429
     -- THE BLOCK TURTLES GO TO IN ORDER
1430
     -- TO ACCESS THE CHEST FOR ITEMS
1431
    item_drop = {x = c.x+2, y = c.y+1, z = c.z+1, orientation = 'east'},
1432
1433
     -- THE BLOCK TURTLES GO TO IN ORDER
1434
     -- TO ACCESS THE CHEST FOR FUEL
1435
    refuel = {x = c.x+2, y = c.y+1, z = c.z+0, orientation = 'east'},
1436
1437
     -- THE AREA ENCOMPASSING TURTLE HOMES
1438
     --     where they sleep.
1439
    greater_home_area = {
1440
        min_x =  -inf,
1441
        max_x = c.x-3,
1442
        min_y = c.y+0,
1443
        max_y = c.y+1,
1444
        min_z = c.z-1,
1445
        max_z = c.z+2
1446
    },
1447
1448
     -- THE ROOM WHERE THE MAGIC HAPPENS
1449
     --     turtles can find there way home from
1450
     --     here.
1451
    control_room_area = {
1452
        min_x = c.x-16,
1453
        max_x = c.x+8,
1454
        min_y = c.y+0,
1455
        max_y = c.y+8,
1456
        min_z = c.z-8,
1457
        max_z = c.z+8
1458
    },
1459
1460
     -- WHERE TURTLES QUEUE TO BE PAIRED UP
1461
    waiting_room_line_area = {
1462
        min_x =  -inf,
1463
        max_x = c.x-2,
1464
        min_y = c.y+0,
1465
        max_y = c.y+0,
1466
        min_z =  c.z+0,
1467
        max_z = c.z+1
1468
    },
1469
1470
     -- THE AREA ENCOMPASSING BOTH WHERE
1471
     -- TURTLES PAIR UP, AND THE PATH THEY
1472
     -- TAKE TO THE MINE ENTRANCE
1473
    waiting_room_area = {
1474
        min_x = c.x-2,
1475
        max_x = c.x+0,
1476
        min_y = c.y+0,
1477
        max_y = c.y+0,
1478
        min_z =  c.z+0,
1479
        max_z = c.z+1
1480
    },
1481
1482
     -- THE LOOP TURTLES GO IN BETWEEN THEIR
1483
     -- HOMES, THE ITEM DROP STATION, AND THE
1484
     -- REFUELING STATION
1485
     --     routes work like linked lists.
1486
     --     keys are current positions, and
1487
     --     values are the associated ajecent
1488
     --     blocks to move to. this loop should
1489
     --     be closed, and it should not be
1490
     --     possible for a collision to occur
1491
     --     between a turtle following the loop,
1492
     --     and a turtle pairing, traveling to
1493
     --     the mine entrance, or any other
1494
     --     movement.
1495
    main_loop_route = {
1496
1497
         -- MINING TURTLE HOME ENTER
1498
        [c.x-1 .. ',' .. c.y+1 .. ',' .. c.z-1] = {x = c.x-2, y = c.y+1, z = c.z-1},
1499
1500
         -- MINING TURTLE HOME EXIT
1501
        [c.x-2 .. ',' .. c.y+1 .. ',' .. c.z-1] = {x = c.x-2, y = c.y+1, z = c.z+0},
1502
1503
         -- CHUNKY TURTLE HOME EXIT
1504
        [c.x-2 .. ',' .. c.y+1 .. ',' .. c.z+0] = {x = c.x-2, y = c.y+1, z = c.z+1},
1505
1506
         -- CHUNKY TURTLE HOME ENTER
1507
        [c.x-2 .. ',' .. c.y+1 .. ',' .. c.z+1] = {x = c.x-2, y = c.y+1, z = c.z+2},
1508
1509
        [c.x-2 .. ',' .. c.y+1 .. ',' .. c.z+2] = {x = c.x-1, y = c.y+1, z = c.z+2},
1510
        [c.x-1 .. ',' .. c.y+1 .. ',' .. c.z+2] = {x = c.x+0, y = c.y+1, z = c.z+2},
1511
        [c.x+0 .. ',' .. c.y+1 .. ',' .. c.z+2] = {x = c.x+0, y = c.y+1, z = c.z+1},
1512
        [c.x+0 .. ',' .. c.y+1 .. ',' .. c.z+1] = {x = c.x+1, y = c.y+1, z = c.z+1},
1513
1514
         -- ITEM DROP STATION
1515
        [c.x+1 .. ',' .. c.y+1 .. ',' .. c.z+1] = {x = c.x+2, y = c.y+1, z = c.z+1},
1516
1517
         -- REFUELING STATION
1518
        [c.x+2 .. ',' .. c.y+1 .. ',' .. c.z+1] = {x = c.x+2, y = c.y+1, z = c.z+0},
1519
1520
        [c.x+2 .. ',' .. c.y+1 .. ',' .. c.z+0] = {x = c.x+2, y = c.y+1, z = c.z-1},
1521
        [c.x+2 .. ',' .. c.y+1 .. ',' .. c.z-1] = {x = c.x+1, y = c.y+1, z = c.z-1},
1522
        [c.x+1 .. ',' .. c.y+1 .. ',' .. c.z-1] = {x = c.x+0, y = c.y+1, z = c.z-1},
1523
        [c.x+0 .. ',' .. c.y+1 .. ',' .. c.z-1] = {x = c.x-1, y = c.y+1, z = c.z-1},
1524
    },
1525
}
1526
1527
1528
mining_turtle_locations = {
1529
    -- LOCATIONS THAT ARE SPECIFIC TO
1530
    -- MINING TURTLES
1531
1532
     -- TURTLE HOMES
1533
     --     this is where the first turtle parking
1534
     --     spot will be, and each following will
1535
     --     be in the <increment> direction.
1536
    homes = {x = c.x-3, y = c.y+0, z = c.z-3, increment = 'west'},
1537
1538
     -- THE AREA ENCOMPASSING THE HOME
1539
     -- LINE, AS WELL AS THE PATH TURTLES
1540
     -- TAKE TO GET TO THEIR HOME
1541
    home_area = {
1542
        min_x = -inf,
1543
        max_x = c.x-3,
1544
        min_y = c.y+0,
1545
        max_y = c.y+0,
1546
        min_z = c.z-1,
1547
        max_z = c.z-1
1548
    },
1549
1550
     -- WHERE TURTLES ENTER THE LINE TO
1551
     -- GET TO THEIR HOME
1552
    home_enter = {x = c.x-2, y = c.y+1, z = c.z-1, orientation = 'west'},
1553
1554
     -- WHERE TURTLES EXIT THEIR HOMES
1555
    home_exit = {x = c.x-2, y = c.y+1, z = c.z+0},
1556
1557
     -- WHERE TURTLES WAIT TO BE PAIRED
1558
    waiting_room = {x = c.x-2, y = c.y+0, z = c.z+0},
1559
1560
     -- THE PATH TURTLES WILL TAKE AFTER
1561
     -- PAIRING
1562
    waiting_room_to_mine_enter_route = {
1563
        [c.x-2 .. ',' .. c.y+0 .. ',' .. c.z+0] = {x = c.x-1, y = c.y+0, z = c.z+0},
1564
        [c.x-1 .. ',' .. c.y+0 .. ',' .. c.z+0] = {x = c.x+0, y = c.y+0, z = c.z+0},
1565
    }
1566
}
1567
1568
1569
chunky_turtle_locations = {
1570
    -- LOCATIONS THAT ARE SPECIFIC TO
1571
    -- MINING TURTLES
1572
1573
     -- TURTLE HOMES
1574
     --     this is where the first turtle parking
1575
     --     spot will be, and each following will
1576
     --     be in the <increment> direction.
1577
    homes = {x = c.x-3, y = c.y+0, z = c.z+2, increment = 'west'},
1578
1579
     -- THE AREA ENCOMPASSING THE HOME
1580
     -- LINE, AS WELL AS THE PATH TURTLES
1581
     -- TAKE TO GET TO THEIR HOME
1582
    home_area = {
1583
        min_x = -inf,
1584
        max_x = c.x-3,
1585
        min_y = c.y+0,
1586
        max_y = c.y+0,
1587
        min_z = c.z+2,
1588
        max_z = c.z+2
1589
    },
1590
1591
     -- WHERE TURTLES ENTER THE LINE TO
1592
     -- GET TO THEIR HOME
1593
    home_enter = {x = c.x-2, y = c.y+1, z = c.z+2, orientation = 'west'},
1594
1595
     -- WHERE TURTLES EXIT THEIR HOMES
1596
    home_exit = {x = c.x-2, y = c.y+1, z = c.z+1},
1597
1598
     -- WHERE TURTLES WAIT TO BE PAIRED
1599
    waiting_room = {x = c.x-2, y = c.y+0, z = c.z+1},
1600
1601
     -- THE PATH TURTLES WILL TAKE AFTER
1602
     -- PAIRING
1603
    waiting_room_to_mine_enter_route = {
1604
        [c.x-2 .. ',' .. c.y+0 .. ',' .. c.z+1] = {x = c.x-1, y = c.y+0, z = c.z+1},
1605
        [c.x-1 .. ',' .. c.y+0 .. ',' .. c.z+1] = {x = c.x-1, y = c.y+0, z = c.z+0},
1606
        [c.x-1 .. ',' .. c.y+0 .. ',' .. c.z+0] = {x = c.x+0, y = c.y+0, z = c.z+0},
1607
    }
1608
}
1609
1610
1611
gravitynames = {
1612
    -- ALL BLOCKS AFFECTED BY GRAVITY
1613
    --     if a turtle sees these it will take
1614
    --     extra care to make sure they're delt
1615
    --     with. works at least a lot percent of
1616
    --     the time
1617
    ['minecraft:gravel'] = true,
1618
    ['minecraft:sand'] = true,
1619
}
1620
1621
1622
orenames = {
1623
    -- ALL THE BLOCKS A TURTLE CONSIDERS ORE
1624
    --     a turtle will continue to mine out a
1625
    --     vein until it reaches <vein_max> or
1626
    --     it stops seeing blocks with names in
1627
    --     this list. block names are exact.
1628
    ['BigReactors:YelloriteOre'] = true,
1629
    ['bigreactors:oreyellorite'] = true,
1630-
    ['DraconicEvolution:draconiumDust'] = true,
1630+
1631-
    ['DraconicEvolution:draconiumOre'] = true,
1631+
1632-
    ['Forestry:apatite'] = true,
1632+
1633-
    ['Forestry:resources'] = true,
1633+
1634-
    ['IC2:blockOreCopper'] = true,
1634+
1635-
    ['IC2:blockOreLead'] = true,
1635+
1636-
    ['IC2:blockOreTin'] = true,
1636+
1637-
    ['IC2:blockOreUran'] = true,
1637+
1638-
    ['ic2:resource'] = true,
1638+
1639-
    ['ProjRed|Core:projectred.core.part'] = true,
1639+
1640-
    ['ProjRed|Exploration:projectred.exploration.ore'] = true,
1640+
1641-
    ['TConstruct:SearedBrick'] = true,
1641+
1642
    ['minecraft:iron_ore'] = true,
1643
    ['minecraft:lapis_ore'] = true,
1644
    ['minecraft:redstone'] = true,
1645
    ['minecraft:redstone_ore'] = true,
1646
    ['galacticraftcore:basic_block_core'] = true,
1647
    ['mekanism:oreblock'] = true,
1648
    ['appliedenergistics2:quartz_ore'] = true,
1649
    ['indrev:copper_ore'] = true,
1650
    ['indrev:tin_ore'] = true,
1651
    ['indrev:lead_ore'] = true,
1652
    ['indrev:silver_ore'] = true,
1653
    ['indrev:tungsten_ore'] = true,
1654
    ['modern_industrialization:copper_ore'] = true,
1655
    ['modern_industrialization:tin_ore'] = true,
1656
    ['modern_industrialization:lead_ore'] = true,
1657
    ['modern_industrialization:silver_ore'] = true,
1658
    ['modern_industrialization:nickel_ore'] = true,
1659
    ['techreborn:bauxite_ore'] = true,
1660-
    ['appliedenergistics2:quartz_ore'] = true
1660+
    ['techreborn:copper_ore'] = true,
1661
    ['techreborn:galena_ore'] = true,
1662
    ['techreborn:iridium_ore'] = true,
1663
    ['techreborn:lead_ore'] = true,
1664
    ['techreborn:ruby_ore'] = true,
1665
    ['techreborn:sapphire_ore'] = true,
1666
    ['techreborn:silver_ore'] = true,
1667
    ['techreborn:tin_ore'] = true,
1668
    ['powah:uraninite_ore'] = true,
1669
    ['create:zinc_ore'] = true,
1670
    ['minecraft:deepslate_coal_ore'] = true,
1671
    ['minecraft:deepslate_copper_ore'] = true,
1672
    ['minecraft:deepslate_diamond_ore'] = true,
1673
    ['minecraft:deepslate_emerald_ore'] = true,
1674
    ['minecraft:deepslate_gold_ore'] = true,
1675
    ['minecraft:deepslate_iron_ore'] = true,
1676
    ['minecraft:deepslate_lapis_ore'] = true,
1677
    ['minecraft:deepslate_redstone_ore'] = true
1678
}
1679
1680
blocktags = {
1681
    -- ALL BLOCKS WITH ONE OF THESE TAGS A TURTLE CONSIDERS ORE
1682
    --     most mods categorize ores with the forge:ores tag.
1683
    --     this is an easy way to detect all but a few ores,
1684
    --     which don't posess this exact tag (for example certus quartzfrom AE2)
1685
    ['forge:ores'] = true,
1686
    -- adds Certus Quartz and Charged Certus Quartz
1687
    ['forge:ores/certus_quartz'] = true
1688
}
1689
1690
fuelnames = {
1691
    -- ITEMS THE TURTLE CONSIDERS FUEL
1692
    ['minecraft:coal'] = true,
1693
}
1694
1695
1696
---==[ SCREEN ]==---
1697
1698
1699
-- MAXIMUM ZOOM OUT (INVERSE) OF THE
1700
-- MAP SCREEN
1701
monitor_max_zoom_level = 5
1702
1703
1704
-- DEFAULT ZOOM OF THE MAP SCREEN
1705
--     0 is [1 pixel : 1 block]
1706
default_monitor_zoom_level = 0
1707
1708
1709
-- CENTER OF THE MAP SCREEN
1710
--     probably want the mine center
1711
default_monitor_location = {x = c.x, z = c.z}]===],
1712
    ["hub_files/events.lua"] = [===[while true do
1713
    event = {os.pullEvent()}
1714
    if event[1] == 'rednet_message' then
1715
        local sender = event[2]
1716
        local message = event[3]
1717
        local protocol = event[4]
1718
        
1719
        if protocol == 'user_input' then
1720
            table.insert(state.user_input, message)
1721
        
1722
        elseif protocol == 'turtle_report' then
1723
            if not state.turtles[sender] then
1724
                state.turtles[sender] = {id = sender}
1725
            end
1726
            state.turtles[sender].data = message
1727
            state.turtles[sender].last_update = os.clock()
1728
        
1729
        elseif protocol == 'pocket_report' then
1730
            if not state.pockets[sender] then
1731
                state.pockets[sender] = {id = sender}
1732
            end
1733
            state.pockets[sender].data = message
1734
            state.pockets[sender].last_update = os.clock()
1735
            
1736
        elseif protocol == 'update_request' then
1737
            if fs.isDir(message) then
1738
                local update_package = {}
1739
                local queue = {''}
1740
                while #queue > 0 do
1741
                    dir_name = table.remove(queue)
1742
                    path_name = fs.combine(message, dir_name)
1743
                    for _, object_name in pairs(fs.list(path_name)) do
1744
                        sub_dir_name = fs.combine(dir_name, object_name)
1745
                        sub_path_name = fs.combine(message, sub_dir_name)
1746
                        if fs.isDir(sub_path_name) then
1747
                            table.insert(queue, sub_dir_name)
1748
                        else
1749
                            local file = fs.open(sub_path_name, 'r')
1750
                            update_package[sub_dir_name] = file.readAll()
1751
                            file.close()
1752
                        end
1753
                    end
1754
                end
1755
                update_package.hub_id = os.getComputerID()
1756
                rednet.send(sender, update_package, 'update_package')
1757
            end
1758
        end
1759
        
1760
    elseif event[1] == 'monitor_touch' then
1761
        if state.monitor_touches then
1762
            table.insert(state.monitor_touches, {x = event[3], y = event[4]})
1763
        end
1764
    end
1765
end]===],
1766
    ["hub_files/monitor.lua"] = [===[menu_lines = {
1767
    '#   # ##### #   # #####',
1768
    '## ##   #   ##  # #',
1769
    '# # #   #   # # # ###',
1770
    '#   #   #   #  ## #',
1771
    '#   # ##### #   # #',
1772
}
1773
1774
decimals = {
1775
    [0] = {
1776
        '#####',
1777
        '#   #',
1778
        '#   #',
1779
        '#   #',
1780
        '#####',
1781
    },
1782
    [1] = {
1783
        '###  ',
1784
        '  #  ',
1785
        '  #  ',
1786
        '  #  ',
1787
        '#####',
1788
    },
1789
    [2] = {
1790
        '#####',
1791
        '    #',
1792
        '#####',
1793
        '#    ',
1794
        '#####',
1795
    },
1796
    [3] = {
1797
        '#####',
1798
        '    #',
1799
        '#####',
1800
        '    #',
1801
        '#####',
1802
    },
1803
    [4] = {
1804
        '#   #',
1805
        '#   #',
1806
        '#####',
1807
        '    #',
1808
        '    #',
1809
    },
1810
    [5] = {
1811
        '#####',
1812
        '#    ',
1813
        '#####',
1814
        '    #',
1815
        '#####',
1816
    },
1817
    [6] = {
1818
        '#####',
1819
        '#    ',
1820
        '#####',
1821
        '#   #',
1822
        '#####',
1823
    },
1824
    [7] = {
1825
        '#####',
1826
        '    #',
1827
        '    #',
1828
        '    #',
1829
        '    #',
1830
    },
1831
    [8] = {
1832
        '#####',
1833
        '#   #',
1834
        '#####',
1835
        '#   #',
1836
        '#####',
1837
    },
1838
    [9] = {
1839
        '#####',
1840
        '#   #',
1841
        '#####',
1842
        '    #',
1843
        '    #',
1844
    },
1845
}
1846
1847
function debug_print(string)
1848
    term.redirect(monitor.restore_to)
1849
    print(string)
1850
    term.redirect(monitor)
1851
end
1852
1853
function turtle_viewer(turtle_ids)
1854
    term.redirect(monitor)
1855
    
1856
    local selected = 1
1857
    
1858
    while true do
1859
        local turtle_id = turtle_ids[selected]
1860
        local turtle = state.turtles[turtle_id]
1861
        
1862
        -- RESOLVE MONITOR TOUCHES, EITHER BY AFFECTING THE DISPLAY OR INSERTING INTO USER_INPUT TABLE
1863
        while #state.monitor_touches > 0 do
1864
            local monitor_touch = table.remove(state.monitor_touches)
1865
            if monitor_touch.x == elements.left.x and monitor_touch.y == elements.left.y then
1866
                selected = math.max(selected - 1, 1)
1867
            elseif monitor_touch.x == elements.right.x and monitor_touch.y == elements.right.y then
1868
                selected = math.min(selected + 1, #turtle_ids)
1869
            elseif monitor_touch.x == elements.viewer_exit.x and monitor_touch.y == elements.viewer_exit.y then
1870
                term.redirect(monitor.restore_to)
1871
                return
1872
            elseif monitor_touch.x == elements.turtle_return.x and monitor_touch.y == elements.turtle_return.y then
1873
                table.insert(state.user_input, 'return ' .. turtle_id)
1874
            elseif monitor_touch.x == elements.turtle_update.x and monitor_touch.y == elements.turtle_update.y then
1875
                table.insert(state.user_input, 'update ' .. turtle_id)
1876
            elseif monitor_touch.x == elements.turtle_reboot.x and monitor_touch.y == elements.turtle_reboot.y then
1877
                table.insert(state.user_input, 'reboot ' .. turtle_id)
1878
            elseif monitor_touch.x == elements.turtle_halt.x and monitor_touch.y == elements.turtle_halt.y then
1879
                table.insert(state.user_input, 'halt ' .. turtle_id)
1880
            elseif monitor_touch.x == elements.turtle_clear.x and monitor_touch.y == elements.turtle_clear.y then
1881
                table.insert(state.user_input, 'clear ' .. turtle_id)
1882
            elseif monitor_touch.x == elements.turtle_reset.x and monitor_touch.y == elements.turtle_reset.y then
1883
                table.insert(state.user_input, 'reset ' .. turtle_id)
1884
            elseif monitor_touch.x == elements.turtle_find.x and monitor_touch.y == elements.turtle_find.y then
1885
                monitor_location.x = turtle.data.location.x
1886
                monitor_location.z = turtle.data.location.z
1887
                monitor_zoom_level = 0
1888
                for level_index, level_and_chance in pairs(config.mine_levels) do
1889
                    if turtle.strip and level_and_chance.level == turtle.strip.y then
1890
                        monitor_level_index = level_index
1891
                        select_mine_level()
1892
                        break
1893
                    end
1894
                end
1895
                term.redirect(monitor.restore_to)
1896
                return
1897
            elseif monitor_touch.x == elements.turtle_forward.x and monitor_touch.y == elements.turtle_forward.y then
1898
                table.insert(state.user_input, 'turtle ' .. turtle_id .. ' go forward')
1899
            elseif monitor_touch.x == elements.turtle_back.x and monitor_touch.y == elements.turtle_back.y then
1900
                table.insert(state.user_input, 'turtle ' .. turtle_id .. ' go back')
1901
            elseif monitor_touch.x == elements.turtle_up.x and monitor_touch.y == elements.turtle_up.y then
1902
                table.insert(state.user_input, 'turtle ' .. turtle_id .. ' go up')
1903
            elseif monitor_touch.x == elements.turtle_down.x and monitor_touch.y == elements.turtle_down.y then
1904
                table.insert(state.user_input, 'turtle ' .. turtle_id .. ' go down')
1905
            elseif monitor_touch.x == elements.turtle_left.x and monitor_touch.y == elements.turtle_left.y then
1906
                table.insert(state.user_input, 'turtle ' .. turtle_id .. ' go left')
1907
            elseif monitor_touch.x == elements.turtle_right.x and monitor_touch.y == elements.turtle_right.y then
1908
                table.insert(state.user_input, 'turtle ' .. turtle_id .. ' go right')
1909
            elseif turtle.data.turtle_type == 'mining' then
1910
                if monitor_touch.x == elements.turtle_dig_up.x and monitor_touch.y == elements.turtle_dig_up.y then
1911
                    table.insert(state.user_input, 'turtle ' .. turtle_id .. ' digblock up')
1912
                elseif monitor_touch.x == elements.turtle_dig.x and monitor_touch.y == elements.turtle_dig.y then
1913
                    table.insert(state.user_input, 'turtle ' .. turtle_id .. ' digblock forward')
1914
                elseif monitor_touch.x == elements.turtle_dig_down.x and monitor_touch.y == elements.turtle_dig_down.y then
1915
                    table.insert(state.user_input, 'turtle ' .. turtle_id .. ' digblock down')
1916
                end
1917
            end
1918
        end
1919
        
1920
        turtle_id = turtle_ids[selected]
1921
        turtle = state.turtles[turtle_id]
1922
        
1923
        background_color = colors.black
1924
        term.setBackgroundColor(background_color)
1925
        monitor.clear()
1926
        
1927
        if turtle.last_update + config.turtle_timeout < os.clock() then
1928
            term.setCursorPos(elements.turtle_lost.x, elements.turtle_lost.y)
1929
            term.setTextColor(colors.red)
1930
            term.write('CONNECTION LOST')
1931
        end
1932
        
1933
        local x_position = elements.turtle_id.x
1934
        for decimal_string in string.format('%04d', turtle_id):gmatch"." do
1935
            for y_offset, line in pairs(decimals[tonumber(decimal_string)]) do
1936
                term.setCursorPos(x_position, elements.turtle_id.y + y_offset - 1)
1937
                for char in line:gmatch"." do
1938
                    if char == '#' then
1939
                        term.setBackgroundColor(colors.green)
1940
                    else
1941
                        term.setBackgroundColor(colors.black)
1942
                    end
1943
                    term.write(' ')
1944
                end
1945
            end
1946
            x_position = x_position + 6
1947
        end
1948
        
1949
        term.setCursorPos(elements.turtle_face.x + 1, elements.turtle_face.y)
1950
        term.setBackgroundColor(colors.yellow)
1951
        term.write('       ')
1952
        term.setCursorPos(elements.turtle_face.x + 1, elements.turtle_face.y + 1)
1953
        term.setBackgroundColor(colors.yellow)
1954
        term.write(' ')
1955
        term.setBackgroundColor(colors.gray)
1956
        term.write('     ')
1957
        term.setBackgroundColor(colors.yellow)
1958
        term.write(' ')
1959
        term.setCursorPos(elements.turtle_face.x + 1, elements.turtle_face.y + 2)
1960
        term.setBackgroundColor(colors.yellow)
1961
        term.write('       ')
1962
        term.setCursorPos(elements.turtle_face.x + 1, elements.turtle_face.y + 3)
1963
        term.setBackgroundColor(colors.yellow)
1964
        term.write('       ')
1965
        term.setCursorPos(elements.turtle_face.x + 1, elements.turtle_face.y + 4)
1966
        term.setBackgroundColor(colors.yellow)
1967
        term.write('       ')
1968
        
1969
        if turtle.data.peripheral_right == 'modem' then
1970
            term.setBackgroundColor(colors.lightGray)
1971
            term.setCursorPos(elements.turtle_face.x, elements.turtle_face.y + 1)
1972
            term.write(' ')
1973
            term.setCursorPos(elements.turtle_face.x, elements.turtle_face.y + 2)
1974
            term.write(' ')
1975
            term.setCursorPos(elements.turtle_face.x, elements.turtle_face.y + 3)
1976
            term.write(' ')
1977
        elseif turtle.data.peripheral_right == 'pick' then
1978
            term.setBackgroundColor(colors.cyan)
1979
            term.setCursorPos(elements.turtle_face.x, elements.turtle_face.y + 1)
1980
            term.write(' ')
1981
            term.setCursorPos(elements.turtle_face.x, elements.turtle_face.y + 2)
1982
            term.write(' ')
1983
            term.setBackgroundColor(colors.brown)
1984
            term.setCursorPos(elements.turtle_face.x, elements.turtle_face.y + 3)
1985
            term.write(' ')
1986
        elseif turtle.data.peripheral_right == 'chunkLoader' then
1987
            term.setBackgroundColor(colors.gray)
1988
            term.setCursorPos(elements.turtle_face.x, elements.turtle_face.y + 1)
1989
            term.write(' ')
1990
            term.setCursorPos(elements.turtle_face.x, elements.turtle_face.y + 3)
1991
            term.write(' ')
1992
            term.setBackgroundColor(colors.blue)
1993
            term.setCursorPos(elements.turtle_face.x, elements.turtle_face.y + 2)
1994
            term.write(' ')
1995
        elseif turtle.data.peripheral_right == 'chunky' then
1996
            term.setBackgroundColor(colors.white)
1997
            term.setCursorPos(elements.turtle_face.x, elements.turtle_face.y + 1)
1998
            term.write(' ')
1999
            term.setCursorPos(elements.turtle_face.x, elements.turtle_face.y + 3)
2000
            term.write(' ')
2001
            term.setBackgroundColor(colors.red)
2002
            term.setCursorPos(elements.turtle_face.x, elements.turtle_face.y + 2)
2003
            term.write(' ')
2004
        end
2005
        
2006
        if turtle.data.peripheral_left == 'modem' then
2007
            term.setBackgroundColor(colors.lightGray)
2008
            term.setCursorPos(elements.turtle_face.x + 8, elements.turtle_face.y + 1)
2009
            term.write(' ')
2010
            term.setCursorPos(elements.turtle_face.x + 8, elements.turtle_face.y + 2)
2011
            term.write(' ')
2012
            term.setCursorPos(elements.turtle_face.x + 8, elements.turtle_face.y + 3)
2013
            term.write(' ')
2014
        elseif turtle.data.peripheral_left == 'pick' then
2015
            term.setBackgroundColor(colors.cyan)
2016
            term.setCursorPos(elements.turtle_face.x + 8, elements.turtle_face.y + 1)
2017
            term.write(' ')
2018
            term.setCursorPos(elements.turtle_face.x + 8, elements.turtle_face.y + 2)
2019
            term.write(' ')
2020
            term.setBackgroundColor(colors.brown)
2021
            term.setCursorPos(elements.turtle_face.x + 8, elements.turtle_face.y + 3)
2022
            term.write(' ')
2023
        elseif turtle.data.peripheral_left == 'chunkLoader' then
2024
            term.setBackgroundColor(colors.gray)
2025
            term.setCursorPos(elements.turtle_face.x + 8, elements.turtle_face.y + 1)
2026
            term.write(' ')
2027
            term.setCursorPos(elements.turtle_face.x + 8, elements.turtle_face.y + 3)
2028
            term.write(' ')
2029
            term.setBackgroundColor(colors.blue)
2030
            term.setCursorPos(elements.turtle_face.x + 8, elements.turtle_face.y + 2)
2031
            term.write(' ')
2032
        elseif turtle.data.peripheral_left == 'chunky' then
2033
            term.setBackgroundColor(colors.white)
2034
            term.setCursorPos(elements.turtle_face.x + 8, elements.turtle_face.y + 1)
2035
            term.write(' ')
2036
            term.setCursorPos(elements.turtle_face.x + 8, elements.turtle_face.y + 3)
2037
            term.write(' ')
2038
            term.setBackgroundColor(colors.red)
2039
            term.setCursorPos(elements.turtle_face.x + 8, elements.turtle_face.y + 2)
2040
            term.write(' ')
2041
        end
2042
        
2043
        term.setBackgroundColor(background_color)
2044
        
2045
        term.setCursorPos(elements.turtle_data.x, elements.turtle_data.y)
2046
        term.setTextColor(colors.white)
2047
        term.write('State: ')
2048
        term.setTextColor(colors.green)
2049
        term.write(turtle.state)
2050
        
2051
        term.setCursorPos(elements.turtle_data.x, elements.turtle_data.y + 1)
2052
        term.setTextColor(colors.white)
2053
        term.write('X: ')
2054
        term.setTextColor(colors.green)
2055
        if turtle.data.location then
2056
            term.write(turtle.data.location.x)
2057
        end
2058
        
2059
        term.setCursorPos(elements.turtle_data.x, elements.turtle_data.y + 2)
2060
        term.setTextColor(colors.white)
2061
        term.write('Y: ')
2062
        term.setTextColor(colors.green)
2063
        if turtle.data.location then
2064
            term.write(turtle.data.location.y)
2065
        end
2066
        
2067
        term.setCursorPos(elements.turtle_data.x, elements.turtle_data.y + 3)
2068
        term.setTextColor(colors.white)
2069
        term.write('Z: ')
2070
        term.setTextColor(colors.green)
2071
        if turtle.data.location then
2072
            term.write(turtle.data.location.z)
2073
        end
2074
        
2075
        term.setCursorPos(elements.turtle_data.x, elements.turtle_data.y + 4)
2076
        term.setTextColor(colors.white)
2077
        term.write('Facing: ')
2078
        term.setTextColor(colors.green)
2079
        term.write(turtle.data.orientation)
2080
        
2081
        term.setCursorPos(elements.turtle_data.x, elements.turtle_data.y + 5)
2082
        term.setTextColor(colors.white)
2083
        term.write('Fuel: ')
2084
        term.setTextColor(colors.green)
2085
        term.write(turtle.data.fuel_level)
2086
        
2087
        term.setCursorPos(elements.turtle_data.x, elements.turtle_data.y + 6)
2088
        term.setTextColor(colors.white)
2089
        term.write('Items: ')
2090
        term.setTextColor(colors.green)
2091
        term.write(turtle.data.item_count)
2092
        
2093
--        term.setCursorPos(elements.turtle_data.x, elements.turtle_data.y + 7)
2094
--        term.setTextColor(colors.white)
2095
--        term.write('Dist: ')
2096
--        term.setTextColor(colors.green)
2097
--        term.write(turtle.data.distance)
2098
        
2099
        term.setTextColor(colors.white)
2100
        
2101
        term.setCursorPos(elements.turtle_return.x, elements.turtle_return.y)
2102
        term.setBackgroundColor(colors.green)
2103
        term.write('*')
2104
        term.setBackgroundColor(colors.brown)
2105
        term.write('-RETURN')
2106
        
2107
        term.setCursorPos(elements.turtle_update.x, elements.turtle_update.y)
2108
        term.setBackgroundColor(colors.green)
2109
        term.write('*')
2110
        term.setBackgroundColor(colors.brown)
2111
        term.write('-UPDATE')
2112
        
2113
        term.setCursorPos(elements.turtle_reboot.x, elements.turtle_reboot.y)
2114
        term.setBackgroundColor(colors.green)
2115
        term.write('*')
2116
        term.setBackgroundColor(colors.brown)
2117
        term.write('-REBOOT')
2118
        
2119
        term.setCursorPos(elements.turtle_halt.x, elements.turtle_halt.y)
2120
        term.setBackgroundColor(colors.green)
2121
        term.write('*')
2122
        term.setBackgroundColor(colors.brown)
2123
        term.write('-HALT')
2124
        
2125
        term.setCursorPos(elements.turtle_clear.x, elements.turtle_clear.y)
2126
        term.setBackgroundColor(colors.green)
2127
        term.write('*')
2128
        term.setBackgroundColor(colors.brown)
2129
        term.write('-CLEAR')
2130
        
2131
        term.setCursorPos(elements.turtle_reset.x, elements.turtle_reset.y)
2132
        term.setBackgroundColor(colors.green)
2133
        term.write('*')
2134
        term.setBackgroundColor(colors.brown)
2135
        term.write('-RESET')
2136
        
2137
        term.setCursorPos(elements.turtle_find.x, elements.turtle_find.y)
2138
        term.setBackgroundColor(colors.green)
2139
        term.write('*')
2140
        term.setBackgroundColor(colors.brown)
2141
        term.write('-FIND')
2142
        
2143
        term.setCursorPos(elements.turtle_forward.x, elements.turtle_forward.y)
2144
        term.setTextColor(colors.white)
2145
        term.setBackgroundColor(colors.green)
2146
        term.write('^')
2147
        term.setTextColor(colors.gray)
2148
        term.setBackgroundColor(background_color)
2149
        term.write('-FORWARD')
2150
        
2151
        term.setCursorPos(elements.turtle_back.x, elements.turtle_back.y)
2152
        term.setTextColor(colors.white)
2153
        term.setBackgroundColor(colors.green)
2154
        term.write('V')
2155
        term.setTextColor(colors.gray)
2156
        term.setBackgroundColor(background_color)
2157
        term.write('-BACK')
2158
        
2159
        term.setCursorPos(elements.turtle_up.x, elements.turtle_up.y)
2160
        term.setTextColor(colors.white)
2161
        term.setBackgroundColor(colors.green)
2162
        term.write('^')
2163
        term.setTextColor(colors.gray)
2164
        term.setBackgroundColor(background_color)
2165
        term.write('-UP')
2166
        
2167
        term.setCursorPos(elements.turtle_down.x, elements.turtle_down.y)
2168
        term.setTextColor(colors.white)
2169
        term.setBackgroundColor(colors.green)
2170
        term.write('V')
2171
        term.setTextColor(colors.gray)
2172
        term.setBackgroundColor(background_color)
2173
        term.write('-DOWN')
2174
        
2175
        term.setCursorPos(elements.turtle_left.x, elements.turtle_left.y)
2176
        term.setTextColor(colors.white)
2177
        term.setBackgroundColor(colors.green)
2178
        term.write('<')
2179
        term.setTextColor(colors.gray)
2180
        term.setBackgroundColor(background_color)
2181
        term.write('-LEFT')
2182
        
2183
        term.setCursorPos(elements.turtle_right.x, elements.turtle_right.y)
2184
        term.setTextColor(colors.white)
2185
        term.setBackgroundColor(colors.green)
2186
        term.write('>')
2187
        term.setTextColor(colors.gray)
2188
        term.setBackgroundColor(background_color)
2189
        term.write('-RIGHT')
2190
        
2191
        term.setCursorPos(elements.turtle_dig_up.x, elements.turtle_dig_up.y)
2192
        term.setTextColor(colors.white)
2193
        if turtle.data.turtle_type == 'mining' then
2194
            term.setBackgroundColor(colors.green)
2195
        else
2196
            term.setBackgroundColor(colors.gray)
2197
        end
2198
        term.write('^')
2199
        
2200
        term.setCursorPos(elements.turtle_dig.x, elements.turtle_dig.y)
2201
        term.setTextColor(colors.white)
2202
        if turtle.data.turtle_type == 'mining' then
2203
            term.setBackgroundColor(colors.green)
2204
        else
2205
            term.setBackgroundColor(colors.gray)
2206
        end
2207
        term.write('*')
2208
        term.setTextColor(colors.gray)
2209
        term.setBackgroundColor(background_color)
2210
        term.write('-DIG')
2211
        
2212
        term.setCursorPos(elements.turtle_dig_down.x, elements.turtle_dig_down.y)
2213
        term.setTextColor(colors.white)
2214
        if turtle.data.turtle_type == 'mining' then
2215
            term.setBackgroundColor(colors.green)
2216
        else
2217
            term.setBackgroundColor(colors.gray)
2218
        end
2219
        term.write('v')
2220
        
2221
        term.setTextColor(colors.white)
2222
        if selected == 1 then
2223
            term.setBackgroundColor(colors.gray)
2224
        else
2225
            term.setBackgroundColor(colors.green)
2226
        end
2227
        term.setCursorPos(elements.left.x, elements.left.y)
2228
        term.write('<')
2229
        if selected == #turtle_ids then
2230
            term.setBackgroundColor(colors.gray)
2231
        else
2232
            term.setBackgroundColor(colors.green)
2233
        end
2234
        term.setCursorPos(elements.right.x, elements.right.y)
2235
        term.write('>')
2236
        term.setBackgroundColor(colors.red)
2237
        term.setCursorPos(elements.viewer_exit.x, elements.viewer_exit.y)
2238
        term.write('x')
2239
        
2240
        monitor.setVisible(true)
2241
        monitor.setVisible(false)
2242
        
2243
        sleep(sleep_len)
2244
    end
2245
end
2246
2247
2248
function menu()
2249
    term.redirect(monitor)
2250
    
2251
    while true do
2252
        while #state.monitor_touches > 0 do
2253
            local monitor_touch = table.remove(state.monitor_touches)
2254
            if monitor_touch.x == elements.viewer_exit.x and monitor_touch.y == elements.viewer_exit.y then
2255
                term.redirect(monitor.restore_to)
2256
                return
2257
            elseif monitor_touch.x == elements.menu_toggle.x and monitor_touch.y == elements.menu_toggle.y then
2258
                if state.on then
2259
                    table.insert(state.user_input, 'off')
2260
                else
2261
                    table.insert(state.user_input, 'on')
2262
                end
2263
            elseif monitor_touch.x == elements.menu_update.x and monitor_touch.y == elements.menu_update.y then
2264
                table.insert(state.user_input, 'update')
2265
            elseif monitor_touch.x == elements.menu_return.x and monitor_touch.y == elements.menu_return.y then
2266
                table.insert(state.user_input, 'return')
2267
            elseif monitor_touch.x == elements.menu_reboot.x and monitor_touch.y == elements.menu_reboot.y then
2268
                table.insert(state.user_input, 'reboot')
2269
            elseif monitor_touch.x == elements.menu_halt.x and monitor_touch.y == elements.menu_halt.y then
2270
                table.insert(state.user_input, 'halt')
2271
            elseif monitor_touch.x == elements.menu_clear.x and monitor_touch.y == elements.menu_clear.y then
2272
                table.insert(state.user_input, 'clear')
2273
            elseif monitor_touch.x == elements.menu_reset.x and monitor_touch.y == elements.menu_reset.y then
2274
                table.insert(state.user_input, 'reset')
2275
            end
2276
        end
2277
        
2278
        term.setBackgroundColor(colors.black)
2279
        monitor.clear()
2280
        
2281
        term.setTextColor(colors.white)
2282
        term.setCursorPos(elements.menu_title.x, elements.menu_title.y)
2283
        term.write('MASTER')
2284
        
2285
        for y_offset, line in pairs(menu_lines) do
2286
            term.setCursorPos(elements.menu_title.x, elements.menu_title.y + y_offset)
2287
            for char in line:gmatch"." do
2288
                if char == '#' then
2289
                    if state.on then
2290
                        term.setBackgroundColor(colors.lime)
2291
                    else
2292
                        term.setBackgroundColor(colors.red)
2293
                    end
2294
                else
2295
                    term.setBackgroundColor(colors.black)
2296
                end
2297
                term.write(' ')
2298
            end
2299
        end
2300
        
2301
        term.write('.lua')
2302
        
2303
        term.setBackgroundColor(colors.red)
2304
        term.setCursorPos(elements.viewer_exit.x, elements.viewer_exit.y)
2305
        term.write('x')
2306
        term.setBackgroundColor(colors.green)
2307
        term.setCursorPos(elements.menu_toggle.x, elements.menu_toggle.y)
2308
        term.write('*')
2309
        term.setCursorPos(elements.menu_return.x, elements.menu_return.y)
2310
        term.write('*')
2311
        term.setCursorPos(elements.menu_update.x, elements.menu_update.y)
2312
        term.write('*')
2313
        term.setCursorPos(elements.menu_reboot.x, elements.menu_reboot.y)
2314
        term.write('*')
2315
        term.setCursorPos(elements.menu_halt.x, elements.menu_halt.y)
2316
        term.write('*')
2317
        term.setCursorPos(elements.menu_clear.x, elements.menu_clear.y)
2318
        term.write('*')
2319
        term.setCursorPos(elements.menu_reset.x, elements.menu_reset.y)
2320
        term.write('*')
2321
        term.setBackgroundColor(colors.brown)
2322
        term.setCursorPos(elements.menu_toggle.x + 1, elements.menu_toggle.y)
2323
        term.write('-TOGGLE POWER')
2324
        term.setCursorPos(elements.menu_update.x + 1, elements.menu_update.y)
2325
        term.write('-UPDATE')
2326
        term.setCursorPos(elements.menu_return.x + 1, elements.menu_return.y)
2327
        term.write('-RETURN')
2328
        term.setCursorPos(elements.menu_reboot.x + 1, elements.menu_reboot.y)
2329
        term.write('-REBOOT')
2330
        term.setCursorPos(elements.menu_halt.x + 1, elements.menu_halt.y)
2331
        term.write('-HALT')
2332
        term.setCursorPos(elements.menu_clear.x + 1, elements.menu_clear.y)
2333
        term.write('-CLEAR')
2334
        term.setCursorPos(elements.menu_reset.x + 1, elements.menu_reset.y)
2335
        term.write('-RESET')
2336
        
2337
        monitor.setVisible(true)
2338
        monitor.setVisible(false)
2339
        
2340
        sleep(sleep_len)
2341
    end
2342
end
2343
2344
2345
function draw_location(location, color)
2346
    if location then
2347
        local pixel = {
2348
            -- x = monitor_width  - math.floor((location.x - min_location.x) / zoom_factor),
2349
            -- y = monitor_height - math.floor((location.z - min_location.z) / zoom_factor),
2350
            x = math.floor((location.x - min_location.x) / zoom_factor),
2351
            y = math.floor((location.z - min_location.z) / zoom_factor),
2352
        }
2353
        if pixel.x >= 1 and pixel.x <= monitor_width and pixel.y >= 1 and pixel.y <= monitor_height then
2354
            if color then
2355
                paintutils.drawPixel(pixel.x, pixel.y, color)
2356
            end
2357
            return pixel
2358
        end
2359
    end
2360
end
2361
    
2362
2363
function draw_monitor()
2364
    
2365
    term.redirect(monitor)
2366
    term.setBackgroundColor(colors.black)
2367
    monitor.clear()
2368
    
2369
    zoom_factor = math.pow(2, monitor_zoom_level)
2370
    min_location = {
2371
        x = monitor_location.x - math.floor(monitor_width  * zoom_factor / 2) - 1,
2372
        z = monitor_location.z - math.floor(monitor_height * zoom_factor / 2) - 1,
2373
    }
2374
    
2375
    local mined = {}
2376
    local xz
2377
    for x = min_location.x - ((min_location.x - config.locations.mine_enter.x) % config.grid_width), min_location.x + (monitor_width * zoom_factor), config.grid_width do
2378
        for z = min_location.z, min_location.z + (monitor_height * zoom_factor), zoom_factor do
2379
            xz = x .. ',' .. z
2380
            if not mined[xz] then
2381
                if z > config.locations.mine_enter.z then
2382
                    if monitor_level[x] and monitor_level[x].south.z > z then
2383
                        mined[xz] = true
2384
                        draw_location({x = x, z = z}, colors.lightGray)
2385
                    else
2386
                        draw_location({x = x, z = z}, colors.gray)
2387
                    end
2388
                else
2389
                    if monitor_level[x] and monitor_level[x].north.z < z then
2390
                        mined[xz] = true
2391
                        draw_location({x = x, z = z}, colors.lightGray)
2392
                    else
2393
                        draw_location({x = x, z = z}, colors.gray)
2394
                    end
2395
                end
2396
            end
2397
        end
2398
    end
2399
    
2400
    for x = min_location.x, min_location.x + (monitor_width * zoom_factor), zoom_factor do
2401
        if x > monitor_level.main_shaft.west.x and x < monitor_level.main_shaft.east.x then
2402
            draw_location({x = x, z = config.locations.mine_enter.z}, colors.lightGray)
2403
        else
2404
            draw_location({x = x, z = config.locations.mine_enter.z}, colors.gray)
2405
        end
2406
    end
2407
    
2408
    local pixel
2409
    local special = {}
2410
    
2411
    pixel = draw_location(config.locations.mine_exit, colors.blue)
2412
    if pixel then
2413
        special[pixel.x .. ',' .. pixel.y] = colors.blue
2414
    end
2415
    
2416
    pixel = draw_location(config.locations.mine_enter, colors.blue)
2417
    if pixel then
2418
        special[pixel.x .. ',' .. pixel.y] = colors.blue
2419
    end
2420
    
2421
    -- DRAW STRIP ENDINGS
2422
    for name, strip in pairs(monitor_level) do
2423
        if name ~= 'y' then
2424
            for _, strip_end in pairs(strip) do
2425
                if strip_end.turtles then
2426
                    pixel = draw_location(strip_end, colors.green)
2427
                    if pixel then
2428
                        special[pixel.x .. ',' .. pixel.y] = colors.green
2429
                    end
2430
                end
2431
            end
2432
        end
2433
    end
2434
    
2435
    term.setTextColor(colors.black)
2436
    turtles = {}
2437
    local str_pixel
2438
    for _, turtle in pairs(state.turtles) do
2439
        if turtle.data then
2440
            local location = turtle.data.location
2441
            if location and location.x and location.y then
2442
                pixel = draw_location(location)
2443
                if pixel then
2444
                    term.setCursorPos(pixel.x, pixel.y)
2445
                    str_pixel = pixel.x .. ',' .. pixel.y
2446
                    if special[str_pixel] then
2447
                        term.setBackgroundColor(special[str_pixel])
2448
                    elseif turtle.last_update + config.turtle_timeout < os.clock() then
2449
                        term.setBackgroundColor(colors.red)
2450
                    else
2451
                        term.setBackgroundColor(colors.yellow)
2452
                    end
2453
                    if not turtles[str_pixel] then
2454
                        turtles[str_pixel] = {turtle.id}
2455
                        term.write('-')
2456
                    else
2457
                        table.insert(turtles[str_pixel], turtle.id)
2458
                        if #turtles[str_pixel] <= 9 then
2459
                            term.write(#turtles[str_pixel])
2460
                        else
2461
                            term.write('+')
2462
                        end
2463
                    end
2464
                end
2465
            end
2466
        end
2467
    end
2468
    
2469
    for _, pocket in pairs(state.pockets) do
2470
        local location = pocket.data.location
2471
        if location and location.x and location.y then
2472
            pixel = draw_location(location)
2473
            if pixel then
2474
                term.setCursorPos(pixel.x, pixel.y)
2475
                str_pixel = pixel.x .. ',' .. pixel.y
2476
                if pocket.last_update + config.pocket_timeout < os.clock() then
2477
                    term.setBackgroundColor(colors.red)
2478
                else
2479
                    term.setBackgroundColor(colors.green)
2480
                end
2481
                term.write('M')
2482
            end
2483
        end
2484
    end
2485
    
2486
    term.setTextColor(colors.white)
2487
    term.setBackgroundColor(colors.green)
2488
    term.setCursorPos(elements.menu.x, elements.menu.y)
2489
    term.write('*')
2490
    term.setCursorPos(elements.all_turtles.x, elements.all_turtles.y)
2491
    term.write('*')
2492
    term.setCursorPos(elements.mining_turtles.x, elements.mining_turtles.y)
2493
    term.write('*')
2494
    term.setCursorPos(elements.center.x, elements.center.y)
2495
    term.write('*')
2496
    term.setCursorPos(elements.up.x, elements.up.y)
2497
    term.write('N')
2498
    term.setCursorPos(elements.down.x, elements.down.y)
2499
    term.write('S')
2500
    term.setCursorPos(elements.left.x, elements.left.y)
2501
    term.write('W')
2502
    term.setCursorPos(elements.right.x, elements.right.y)
2503
    term.write('E')
2504
    term.setCursorPos(elements.level_up.x, elements.level_up.y)
2505
    term.write('+')
2506
    term.setCursorPos(elements.level_down.x, elements.level_down.y)
2507
    term.write('-')
2508
    term.setCursorPos(elements.zoom_in.x, elements.zoom_in.y)
2509
    term.write('+')
2510
    term.setCursorPos(elements.zoom_out.x, elements.zoom_out.y)
2511
    term.write('-')
2512
    term.setBackgroundColor(colors.brown)
2513
    term.setCursorPos(elements.level_indicator.x, elements.level_indicator.y)
2514
    term.write(string.format('LEVEL: %3d', monitor_level.y))
2515
    term.setCursorPos(elements.zoom_indicator.x, elements.zoom_indicator.y)
2516
    term.write('ZOOM: ' .. monitor_zoom_level)
2517
    term.setCursorPos(elements.x_indicator.x, elements.x_indicator.y)
2518
    term.write('X: ' .. monitor_location.x)
2519
    term.setCursorPos(elements.z_indicator.x, elements.z_indicator.y)
2520
    term.write('Z: ' .. monitor_location.z)
2521
    term.setCursorPos(elements.center_indicator.x, elements.center_indicator.y)
2522
    term.write('-CENTER')
2523
    term.setCursorPos(elements.menu_indicator.x, elements.menu_indicator.y)
2524
    term.write('-MENU')
2525
    term.setCursorPos(elements.all_indicator.x, elements.all_indicator.y)
2526
    term.write('ALL-')
2527
    term.setCursorPos(elements.mining_indicator.x, elements.mining_indicator.y)
2528
    term.write('MINING-')
2529
    
2530
    term.redirect(monitor.restore_to)
2531
end
2532
2533
2534
function touch_monitor(monitor_touch)
2535
    if monitor_touch.x == elements.up.x and monitor_touch.y == elements.up.y then
2536
        monitor_location.z = monitor_location.z - zoom_factor
2537
    elseif monitor_touch.x == elements.down.x and monitor_touch.y == elements.down.y then
2538
        monitor_location.z = monitor_location.z + zoom_factor
2539
    elseif monitor_touch.x == elements.left.x and monitor_touch.y == elements.left.y then
2540
        monitor_location.x = monitor_location.x - zoom_factor
2541
    elseif monitor_touch.x == elements.right.x and monitor_touch.y == elements.right.y then
2542
        monitor_location.x = monitor_location.x + zoom_factor
2543
    elseif monitor_touch.x == elements.level_up.x and monitor_touch.y == elements.level_up.y then
2544
        monitor_level_index = math.min(monitor_level_index + 1, #config.mine_levels)
2545
        select_mine_level()
2546
    elseif monitor_touch.x == elements.level_down.x and monitor_touch.y == elements.level_down.y then
2547
        monitor_level_index = math.max(monitor_level_index - 1, 1)
2548
        select_mine_level()
2549
    elseif monitor_touch.x == elements.zoom_in.x and monitor_touch.y == elements.zoom_in.y then
2550
        monitor_zoom_level = math.max(monitor_zoom_level - 1, 0)
2551
    elseif monitor_touch.x == elements.zoom_out.x and monitor_touch.y == elements.zoom_out.y then
2552
        monitor_zoom_level = math.min(monitor_zoom_level + 1, config.monitor_max_zoom_level)
2553
    elseif monitor_touch.x == elements.menu.x and monitor_touch.y == elements.menu.y then
2554
        menu()
2555
    elseif monitor_touch.x == elements.center.x and monitor_touch.y == elements.center.y then
2556
        monitor_location = {x = config.default_monitor_location.x, z = config.default_monitor_location.z}
2557
    elseif monitor_touch.x == elements.all_turtles.x and monitor_touch.y == elements.all_turtles.y then
2558
        local turtle_ids = {}
2559
        for _, turtle in pairs(state.turtles) do
2560
            if turtle.data then
2561
                table.insert(turtle_ids, turtle.id)
2562
            end
2563
        end
2564
        if #turtle_ids then
2565
            turtle_viewer(turtle_ids)
2566
        end
2567
    elseif monitor_touch.x == elements.mining_turtles.x and monitor_touch.y == elements.mining_turtles.y then
2568
        local turtle_ids = {}
2569
        for _, turtle in pairs(state.turtles) do
2570
            if turtle.data and turtle.data.turtle_type == 'mining' then
2571
                table.insert(turtle_ids, turtle.id)
2572
            end
2573
        end
2574
        if #turtle_ids then
2575
            turtle_viewer(turtle_ids)
2576
        end
2577
    else
2578
        local str_pos = monitor_touch.x .. ',' .. monitor_touch.y
2579
        if turtles[str_pos] then
2580
            turtle_viewer(turtles[str_pos])
2581
        end
2582
    end
2583
end
2584
2585
2586
function init_elements()
2587
    elements = {
2588
        up               = {x = math.ceil(monitor_width / 2), y = 1                            },
2589
        down             = {x = math.ceil(monitor_width / 2), y = monitor_height               },
2590
        left             = {x = 1,                            y = math.ceil(monitor_height / 2)},
2591
        right            = {x = monitor_width,                y = math.ceil(monitor_height / 2)},
2592
        level_up         = {x = monitor_width, y =  1},
2593
        level_down       = {x = monitor_width - 11, y =  1},
2594
        level_indicator  = {x = monitor_width - 10, y =  1},
2595
        zoom_in          = {x = monitor_width, y =  2},
2596
        zoom_out         = {x = monitor_width - 8, y = 2},
2597
        zoom_indicator   = {x = monitor_width - 7, y = 2},
2598
        all_turtles      = {x = monitor_width, y = monitor_height-1},
2599
        all_indicator    = {x = monitor_width - 4, y = monitor_height-1},
2600
        mining_turtles   = {x = monitor_width, y = monitor_height},
2601
        mining_indicator = {x = monitor_width - 7, y = monitor_height},
2602
        menu             = {x =  1, y = monitor_height},
2603
        menu_indicator   = {x =  2, y = monitor_height},
2604
        center           = {x =  1, y =  1},
2605
        center_indicator = {x =  2, y =  1},
2606
        x_indicator      = {x =  1, y =  2},
2607
        z_indicator      = {x =  1, y =  3},
2608
        viewer_exit      = {x =  1, y =  1},
2609
        turtle_face      = {x =  5, y =  2},
2610
        turtle_id        = {x = 16, y =  2},
2611
        turtle_lost      = {x = 13, y =  1},
2612
        turtle_data      = {x =  4, y =  8},
2613
        turtle_return    = {x = 26, y =  8},
2614
        turtle_update    = {x = 26, y =  9},
2615
        turtle_reboot    = {x = 26, y = 10},
2616
        turtle_halt      = {x = 26, y = 11},
2617
        turtle_clear     = {x = 26, y = 12},
2618
        turtle_reset     = {x = 26, y = 13},
2619
        turtle_find      = {x = 26, y = 14},
2620
        turtle_forward   = {x = 10, y = 16},
2621
        turtle_back      = {x = 10, y = 18},
2622
        turtle_up        = {x = 23, y = 16},
2623
        turtle_down      = {x = 23, y = 18},
2624
        turtle_left      = {x =  6, y = 17},
2625
        turtle_right     = {x = 14, y = 17},
2626
        turtle_dig_up    = {x = 31, y = 16},
2627
        turtle_dig       = {x = 31, y = 17},
2628
        turtle_dig_down  = {x = 31, y = 18},
2629
        menu_title       = {x =  9, y =  3},
2630
        menu_toggle      = {x = 10, y = 11},
2631
        menu_update      = {x = 10, y = 13},
2632
        menu_return      = {x = 10, y = 14},
2633
        menu_reboot      = {x = 10, y = 15},
2634
        menu_halt        = {x = 10, y = 16},
2635
        menu_clear       = {x = 10, y = 17},
2636
        menu_reset       = {x = 10, y = 18},
2637
    }
2638
end
2639
2640
2641
function select_mine_level()
2642
    monitor_level = state.mine[config.mine_levels[monitor_level_index].level]
2643
end
2644
2645
2646
function step()
2647
    while #state.monitor_touches > 0 do
2648
        touch_monitor(table.remove(state.monitor_touches))
2649
    end
2650
    draw_monitor()
2651
    monitor.setVisible(true)
2652
    monitor.setVisible(false)
2653
    sleep(sleep_len)
2654
end
2655
2656
2657
function main()
2658
    sleep_len = 0.3
2659
    
2660
    local attached = peripheral.find('monitor')
2661
    
2662
    if not attached then
2663
        error('No monitor connected.')
2664
    end
2665
    
2666
    monitor_size = {attached.getSize()}
2667
    monitor_width = monitor_size[1]
2668
    monitor_height = monitor_size[2]
2669
    
2670
    if monitor_width < 29 or monitor_height < 12 then -- Must be at least that big
2671
        return
2672
    end
2673
    
2674
    monitor = window.create(attached, 1, 1, monitor_width, monitor_height)
2675
    monitor.restore_to = term.current()
2676
    monitor.clear()
2677
    monitor.setVisible(false)
2678
    monitor.setCursorPos(1, 1)
2679
    
2680
    monitor_location = {x = config.locations.mine_enter.x, z = config.locations.mine_enter.z}
2681
    monitor_zoom_level = config.default_monitor_zoom_level
2682
    
2683
    init_elements()
2684
    
2685
    while not state.mine do
2686
        sleep(0.5)
2687
    end
2688
    
2689
    monitor_level_index = 1
2690
    select_mine_level()
2691
    
2692
    state.monitor_touches = {}
2693
    while true do
2694
        local status, caught_error = pcall(step)
2695
        if not status then
2696
            term.redirect(monitor.restore_to)
2697
            error(caught_error)
2698
        end
2699
    end
2700
end
2701
2702
2703
main()]===],
2704
    ["hub_files/report.lua"] = [===[-- CONTINUOUSLY BROADCAST STATUS REPORTS
2705
while true do
2706
    
2707
    turtles_parked = 0
2708
    turtle_count = 0
2709
    for _, turtle in pairs(state.turtles) do
2710
        if turtle.state == 'park' then
2711
            turtles_parked = turtles_parked + 1
2712
        end
2713
        turtle_count = turtle_count + 1
2714
    end
2715
2716
    rednet.broadcast({
2717
            on             = state.on,
2718
            turtles_parked = turtles_parked,
2719
            turtle_count   = turtle_count,
2720
        }, 'hub_report')
2721
    
2722
    sleep(0.5)
2723
    
2724
end]===],
2725
    ["hub_files/session_id"] = [===[29.0]===],
2726
    ["hub_files/startup.lua"] = [===[-- SET LABEL
2727
os.setComputerLabel('Hub')
2728
2729
-- INITIALIZE APIS
2730
if fs.exists('/apis') then
2731
    fs.delete('/apis')
2732
end
2733
fs.makeDir('/apis')
2734
fs.copy('/config.lua', '/apis/config')
2735
fs.copy('/state.lua', '/apis/state')
2736
fs.copy('/basics.lua', '/apis/basics')
2737
os.loadAPI('/apis/config')
2738
os.loadAPI('/apis/state')
2739
os.loadAPI('/apis/basics')
2740
2741
2742
-- OPEN REDNET
2743
for _, side in pairs({'back', 'top', 'left', 'right'}) do
2744
    if peripheral.getType(side) == 'modem' then
2745
        rednet.open(side)
2746
        break
2747
    end
2748
end
2749
2750
2751
-- IF UPDATED PRINT "UPDATED"
2752
if fs.exists('/updated') then
2753
    fs.delete('/updated')
2754
    print('UPDATED')
2755
    state.updated = true
2756
end
2757
2758
2759
-- LAUNCH PROGRAMS AS SEPARATE THREADS
2760
multishell.launch({}, '/user.lua')
2761
multishell.launch({}, '/report.lua')
2762
multishell.launch({}, '/monitor.lua')
2763
multishell.launch({}, '/events.lua')
2764
multishell.launch({}, '/whosmineisitanyway.lua')
2765
multishell.setTitle(2, 'user')
2766
multishell.setTitle(3, 'report')
2767
multishell.setTitle(4, 'monitor')
2768
multishell.setTitle(5, 'events')
2769
multishell.setTitle(6, 'whosmine')]===],
2770
    ["hub_files/state.lua"] = [===[user_input = {}
2771
turtles = {}
2772
pockets = {}
2773
homes = {}]===],
2774
    ["hub_files/update"] = [===[os.run({}, '/disk/hub.lua')]===],
2775
    ["hub_files/updated"] = [===[]===],
2776
    ["hub_files/user.lua"] = [===[-- CONTINUOUSLY AWAIT USER INPUT AND PLACE IN TABLE
2777
while true do
2778
    table.insert(state.user_input, read())
2779
end]===],
2780
    ["hub_files/whosmineisitanyway.lua"] = [===[inf = basics.inf
2781
str_xyz = basics.str_xyz
2782
2783
2784
reverse_shift = {
2785
    north = 'south',
2786
    south = 'north',
2787
    east  = 'west',
2788
    west  = 'east',
2789
}
2790
2791
2792
function load_mine()
2793
    -- LOAD MINE INTO state.mine FROM /mine/<x,z>/ DIRECTORY
2794
    state.mine_dir_path = '/mine/' .. config.locations.mine_enter.x .. ',' .. config.locations.mine_enter.z .. '/'
2795
    state.mine = {}
2796
    
2797
    if not fs.exists(state.mine_dir_path) then
2798
        fs.makeDir(state.mine_dir_path)
2799
    end
2800
    
2801
    if fs.exists(state.mine_dir_path .. 'on') then
2802
        state.on = true
2803
    end
2804
    
2805
    for _, level_and_chance in pairs(config.mine_levels) do
2806
        local level = level_and_chance.level
2807
        state.mine[level] = {y = level}
2808
    
2809
        -- START WITH AT LEAST A MAIN SHAFT
2810
        state.mine[level].main_shaft = {}
2811
        state.mine[level].main_shaft.west = {name = 'main_shaft', x = config.locations.mine_enter.x, y = level, z = config.locations.mine_enter.z, orientation = 'west'}
2812
        state.mine[level].main_shaft.east = {name = 'main_shaft', x = config.locations.mine_enter.x, y = level, z = config.locations.mine_enter.z, orientation = 'east'}
2813
        
2814
        -- FOR EACH STRIP IN /mine/<x,z>/<level>/ PUT INTO MEMORY
2815
        local level_dir_path = state.mine_dir_path .. level .. '/'
2816
        if not fs.exists(level_dir_path) then
2817
            fs.makeDir(level_dir_path)
2818
        else
2819
            for _, file_name in pairs(fs.list(level_dir_path)) do
2820
                if file_name:sub(1, 1) ~= '.' then
2821
                    local file = fs.open(level_dir_path .. file_name, 'r')
2822
                    if file == nil then
2823
                        error('Failed to open file ' .. level_dir_path .. file_name)
2824
                    else
2825
                        if file_name == 'main_shaft' then
2826
                            local xs = string.gmatch(file.readAll(), '[^,]+')
2827
                            state.mine[level].main_shaft = {}
2828
                            state.mine[level].main_shaft.west = {name = 'main_shaft', x = tonumber(xs()), y = level, z = config.locations.mine_enter.z, orientation = 'west'}
2829
                            state.mine[level].main_shaft.east = {name = 'main_shaft', x = tonumber(xs()), y = level, z = config.locations.mine_enter.z, orientation = 'east'}
2830
                        else
2831
                            local zs = string.gmatch(file.readAll(), '[^,]+')
2832
                            local x = tonumber(file_name)
2833
                            state.mine[level][x] = {}
2834
                            state.mine[level][x].north = {name = x, x = x, y = level, z = tonumber(zs()), orientation = 'north'}
2835
                            state.mine[level][x].south = {name = x, x = x, y = level, z = tonumber(zs()), orientation = 'south'}
2836
                        end
2837
                        file.close()
2838
                    end
2839
                end
2840
            end
2841
        end
2842
    end
2843
    
2844
    state.turtles_dir_path = state.mine_dir_path .. 'turtles/'
2845
    
2846
    if not fs.exists(state.turtles_dir_path) then
2847
        fs.makeDir(state.turtles_dir_path)
2848
    end
2849
    
2850
    local turtle_pairs = {}
2851
    
2852
    for _, turtle_id in pairs(fs.list(state.turtles_dir_path)) do
2853
        if turtle_id:sub(1, 1) ~= '.' then
2854
            turtle_id = tonumber(turtle_id)
2855
            local turtle = {id = turtle_id}
2856
            state.turtles[turtle_id] = turtle
2857
            local turtle_dir_path = state.turtles_dir_path .. turtle_id .. '/'
2858
            if fs.exists(turtle_dir_path .. 'strip') then
2859
                local file = fs.open(turtle_dir_path .. 'strip', 'r')
2860
                if file == nil then
2861
                    error('Failed to open file ' .. turtle_dir_path .. 'strip')
2862
                end
2863
                local strip_args = string.gmatch(file.readAll(), '[^,]+')
2864
2865
                local level = tonumber(strip_args())
2866
                local name = strip_args()
2867
                if name ~= 'main_shaft' then
2868
                    name = tonumber(name)
2869
                end
2870
                local orientation = strip_args()
2871
2872
                if state.mine[level] and state.mine[level][name] and state.mine[level][name][orientation] then
2873
                    turtle.strip = state.mine[level][name][orientation]
2874
                    if fs.exists(turtle_dir_path .. 'deployed') then
2875
                        file = fs.open(turtle_dir_path .. 'deployed', 'r')
2876
                        if file == nil then
2877
                            error('Failed to open file ' .. turtle_dir_path .. 'deployed')
2878
                        end
2879
                        turtle.steps_left = tonumber(file.readAll())
2880
                        if not turtle_pairs[turtle.strip] then
2881
                            turtle_pairs[turtle.strip] = {}
2882
                        end
2883
                        table.insert(turtle_pairs[turtle.strip], turtle)
2884
                    end
2885
                end
2886
2887
            end
2888
            if fs.exists(turtle_dir_path .. 'halt') then
2889
                turtle.state = 'halt'
2890
            end
2891
        end
2892
    end
2893
    
2894
    for strip, turtles in pairs(turtle_pairs) do
2895
        if #turtles == 2 then
2896
            strip.turtles = turtles
2897
            turtles[1].pair = turtles[2]
2898
            turtles[2].pair = turtles[1]
2899
        elseif #turtles == 1 and not config.use_chunky_turtles then
2900
            strip.turtles = turtles
2901
        end
2902
    end
2903
end
2904
2905
2906
function write_strip(level, name)
2907
    -- RECORD THE STATE OF A STRIP AT A GIVEN level AND name TO /mine/<center>/<level>/<name>
2908
    local file = fs.open(state.mine_dir_path .. level .. '/' .. name, 'w')
2909
    if name == 'main_shaft' then
2910
        file.write(state.mine[level][name].west.x .. ',' .. state.mine[level][name].east.x)
2911
    else
2912
        file.write(state.mine[level][name].north.z .. ',' .. state.mine[level][name].south.z)
2913
    end
2914
    file.close()
2915
end
2916
2917
2918
function write_turtle_strip(turtle, strip)
2919
    local file = fs.open(state.turtles_dir_path .. turtle.id .. '/strip', 'w')
2920
    file.write(strip.y .. ',' .. strip.name .. ',' .. strip.orientation)
2921
    file.close()
2922
end
2923
2924
2925
function halt(turtle)
2926
    add_task(turtle, {action = 'pass', end_state = 'halt'})
2927
    fs.open(state.turtles_dir_path .. turtle.id .. '/halt', 'w').close()
2928
end
2929
2930
2931
function unhalt(turtle)
2932
    fs.delete(state.turtles_dir_path .. turtle.id .. '/halt', 'w')
2933
end
2934
2935
2936
function update_strip(turtle)
2937
    -- RECORD THAT A STRIP HAS BEEN EXPLORED TO TURTLE'S POSITION
2938
    local strip = turtle.strip
2939
    if strip then
2940
        if strip.orientation == 'north' then
2941
            strip.z = math.min(strip.z, turtle.data.location.z)
2942
        elseif strip.orientation == 'south' then
2943
            strip.z = math.max(strip.z, turtle.data.location.z)
2944
        elseif strip.orientation == 'east' then
2945
            strip.x = math.max(strip.x, turtle.data.location.x)
2946
        elseif strip.orientation == 'west' then
2947
            strip.x = math.min(strip.x, turtle.data.location.x)
2948
        end
2949
        write_strip(strip.y, strip.name)
2950
    end
2951
end
2952
2953
2954
function expand_mine(level, x)
2955
    if not state.mine[level][x] then
2956
        state.mine[level][x] = {}
2957
        state.mine[level][x].north = {name = x, x = x, y = level, z = config.locations.mine_enter.z, orientation = 'north'}
2958
        state.mine[level][x].south = {name = x, x = x, y = level, z = config.locations.mine_enter.z, orientation = 'south'}
2959
        write_strip(level, x)
2960
    end
2961
end
2962
2963
2964
function gen_next_strip()
2965
    local level = get_mining_level()
2966
    state.next_strip = get_closest_free_strip(level)
2967
    if state.next_strip then
2968
        state.min_fuel = (basics.distance(state.next_strip, config.locations.mine_enter) + config.mission_length) * 3
2969
    else
2970
        state.min_fuel = nil
2971
    end
2972
end
2973
2974
2975
function get_closest_free_strip(level)
2976
    local west_x = config.locations.mine_enter.x
2977
    local east_x = config.locations.mine_enter.x
2978
    local offset_x = 0
2979
    local min_x = state.mine[level].main_shaft.west.x
2980
    local max_x = state.mine[level].main_shaft.east.x
2981
    
2982
    local closest_strip
2983
    local distance
2984
    local z_distance
2985
    local min_dist = inf
2986
    
2987
    while west_x >= min_x and east_x <= max_x and offset_x < min_dist do
2988
        for _, x in pairs({west_x, east_x}) do
2989
            for _, z_side in pairs({'north', 'south'}) do
2990
                expand_mine(level, x)
2991
                strip = state.mine[level][x][z_side]
2992
                if not strip.turtles then
2993
                    z_distance = math.abs(strip.z - config.locations.mine_enter.z)
2994
                    distance = z_distance + math.abs(strip.x - config.locations.mine_enter.x)
2995
                    if distance < min_dist then
2996
                        min_dist = distance
2997
                        closest_strip = strip
2998
                    end
2999
                end
3000
            end
3001
        end
3002
        offset_x = offset_x + config.grid_width
3003
        west_x = config.locations.mine_enter.x - offset_x
3004
        east_x = config.locations.mine_enter.x + offset_x
3005
    end
3006
    
3007
    for _, strip in pairs({state.mine[level].main_shaft.west, state.mine[level].main_shaft.east}) do
3008
        if not strip.turtles then
3009
            distance = math.abs(strip.x - config.locations.mine_enter.x)
3010
            if distance <= min_dist then
3011
                min_dist = distance
3012
                closest_strip = strip
3013
            end
3014
        end
3015
    end
3016
    
3017
    return closest_strip
3018
end
3019
3020
3021
function get_mining_level()
3022
    local n = 0
3023
    local r = math.random()
3024
    for _, level_and_chance in pairs(config.mine_levels) do
3025
        n = n + level_and_chance.chance
3026
        if n > r then
3027
            return level_and_chance.level
3028
        end
3029
    end
3030
end
3031
3032
3033
function good_on_fuel(mining_turtle, chunky_turtle)
3034
    local fuel_needed = math.ceil(basics.distance(mining_turtle.data.location, config.locations.mine_exit) * 1.5)
3035
    return (mining_turtle.data.fuel_level == "unlimited" or mining_turtle.data.fuel_level > fuel_needed) and ((not config.use_chunky_turtles) or (chunky_turtle.data.fuel_level == "unlimited" or chunky_turtle.data.fuel_level > fuel_needed))
3036
end
3037
3038
3039
function follow(chunky_turtle)
3040
    add_task(chunky_turtle, {
3041
        action = 'go_to_strip',
3042
        data = {chunky_turtle.strip},
3043
        end_state = 'wait',
3044
    })
3045
end
3046
3047
3048
function go_mine(mining_turtle)
3049
    update_strip(mining_turtle)
3050
    add_task(mining_turtle, {
3051
        action = 'mine_vein',
3052
        data = {mining_turtle.strip.orientation},
3053
    })
3054
    add_task(mining_turtle, {
3055
        action = 'clear_gravity_blocks',
3056
    })
3057
    if config.use_chunky_turtles then
3058
        add_task(mining_turtle, {
3059
            action = 'go_to_strip',
3060
            data = {mining_turtle.strip},
3061
            end_state = 'wait',
3062
            end_function = follow,
3063
            end_function_args = {mining_turtle.pair},
3064
        })
3065
    else
3066
        add_task(mining_turtle, {
3067
            action = 'go_to_strip',
3068
            data = {mining_turtle.strip},
3069
            end_state = 'wait',
3070
        })
3071
    end
3072
    mining_turtle.steps_left = mining_turtle.steps_left - 1
3073
    local file = fs.open(state.turtles_dir_path .. mining_turtle.id .. '/deployed', 'w')
3074
    file.write(mining_turtle.steps_left)
3075
    file.close()
3076
end
3077
3078
3079
function free_turtle(turtle)
3080
    if turtle.pair then
3081
        fs.delete(state.turtles_dir_path .. turtle.id .. '/deployed')
3082
        fs.delete(state.turtles_dir_path .. turtle.pair.id .. '/deployed')
3083
        turtle.pair.pair = nil
3084
        turtle.pair = nil
3085
        turtle.strip.turtles = nil
3086
    end
3087
end
3088
3089
3090
function pair_turtles_finish()
3091
    state.pair_hold = nil
3092
end
3093
3094
3095
function pair_turtles_send(chunky_turtle)
3096
    add_task(chunky_turtle, {
3097
        action = 'go_to_mine_enter',
3098
        end_function = pair_turtles_finish
3099
    })
3100
    
3101
    add_task(chunky_turtle, {
3102
        action = 'go_to_strip',
3103
        data = {chunky_turtle.strip},
3104
        end_state = 'wait',
3105
    })
3106
end
3107
3108
3109
function pair_turtles_begin(turtle1, turtle2)
3110
    local mining_turtle
3111
    local chunky_turtle
3112
    if turtle1.data.turtle_type == 'mining' then
3113
        if turtle2.data.turtle_type ~= 'chunky' then
3114
            error('Incompatable turtles')
3115
        end
3116
        mining_turtle = turtle1
3117
        chunky_turtle = turtle2
3118
    elseif turtle1.data.turtle_type == 'chunky' then
3119
        if turtle2.data.turtle_type ~= 'mining' then
3120
            error('Incompatable turtles')
3121
        end
3122
        chunky_turtle = turtle1
3123
        mining_turtle = turtle2
3124
    end
3125
    
3126
    local strip = state.next_strip
3127
    local level = strip.level
3128
    
3129
    if not strip then
3130
        gen_next_strip()
3131
        add_task(mining_turtle, {action = 'pass', end_state = 'idle'})
3132
        add_task(chunky_turtle, {action = 'pass', end_state = 'idle'})
3133
        return
3134
    end
3135
    
3136
    print('Pairing ' .. mining_turtle.id .. ' and ' .. chunky_turtle.id)
3137
    
3138
    mining_turtle.pair = chunky_turtle
3139
    chunky_turtle.pair = mining_turtle
3140
    
3141
    state.pair_hold = {mining_turtle, chunky_turtle}
3142
        
3143
    mining_turtle.steps_left = config.mission_length
3144
    
3145
    strip.turtles = {mining_turtle, chunky_turtle}
3146
    
3147
    for _, turtle in pairs(strip.turtles) do
3148
        turtle.strip = strip
3149
        write_turtle_strip(turtle, strip)
3150
        add_task(turtle, {action = 'pass', end_state = 'trip'})
3151
    end
3152
    
3153
    fs.open(state.turtles_dir_path .. chunky_turtle.id .. '/deployed', 'w').close()
3154
    local file = fs.open(state.turtles_dir_path .. mining_turtle.id .. '/deployed', 'w')
3155
    file.write(mining_turtle.steps_left)
3156
    file.close()
3157
    
3158
    add_task(mining_turtle, {
3159
        action = 'go_to_mine_enter',
3160
        end_function = pair_turtles_send,
3161
        end_function_args = {chunky_turtle}
3162
    })
3163
    
3164
    add_task(mining_turtle, {
3165
        action = 'go_to_strip',
3166
        data = {mining_turtle.strip},
3167
        end_state = 'wait',
3168
    })
3169
    
3170
    gen_next_strip()
3171
end
3172
3173
3174
function solo_turtle_begin(turtle)
3175
    
3176
    local strip = state.next_strip
3177
    local level = strip.level
3178
    
3179
    if not strip then
3180
        gen_next_strip()
3181
        add_task(turtle, {action = 'pass', end_state = 'idle'})
3182
        return
3183
    end
3184
    
3185
    print('Assigning ' .. turtle.id)
3186
        
3187
    turtle.steps_left = config.mission_length
3188
    
3189
    strip.turtles = {turtle}
3190
    
3191
    for _, turtle in pairs(strip.turtles) do
3192
        turtle.strip = strip
3193
        write_turtle_strip(turtle, strip)
3194
        add_task(turtle, {action = 'pass', end_state = 'trip'})
3195
    end
3196
    
3197
    local file = fs.open(state.turtles_dir_path .. turtle.id .. '/deployed', 'w')
3198
    file.write(turtle.steps_left)
3199
    file.close()
3200
    
3201
    add_task(turtle, {
3202
        action = 'go_to_mine_enter',
3203
    })
3204
    
3205
    add_task(turtle, {
3206
        action = 'go_to_strip',
3207
        data = {turtle.strip},
3208
        end_state = 'wait',
3209
    })
3210
    
3211
    gen_next_strip()
3212
end
3213
3214
3215
function check_pair_fuel(turtle)
3216
    if state.min_fuel then
3217
        if (turtle.data.fuel_level ~= "unlimited" and turtle.data.fuel_level <= state.min_fuel) then
3218
            add_task(turtle, {action = 'prepare', data = {state.min_fuel}})
3219
        else
3220
            add_task(turtle, {action = 'pass', end_state = 'pair'})
3221
        end
3222
    else
3223
        gen_next_strip()
3224
    end
3225
end
3226
3227
3228
function send_turtle_up(turtle)
3229
    if turtle.data.location.y < config.locations.mine_enter.y then
3230
        if turtle.strip then
3231
            
3232
            if turtle.data.turtle_type == 'chunky' and turtle.data.location.y == turtle.strip.y then
3233
                add_task(turtle, {action = 'delay', data={3}})
3234
            end
3235
            
3236
            add_task(turtle, {action = 'go_to_mine_exit', data = {turtle.strip}})
3237
        end
3238
    end
3239
end
3240
3241
3242
function initialize_turtle(turtle)
3243
    local data = {session_id, config}
3244
    
3245
    if turtle.state ~= 'halt' then
3246
        turtle.state = 'lost'
3247
    end
3248
    turtle.task_id = 2
3249
    turtle.tasks = {}
3250
    add_task(turtle, {action = 'initialize', data = data})
3251
end
3252
3253
3254
function add_task(turtle, task)
3255
    if not task.data then
3256
        task.data = {}
3257
    end
3258
    table.insert(turtle.tasks, task)
3259
end
3260
3261
3262
function send_tasks(turtle)
3263
    local task = turtle.tasks[1]
3264
    if task then
3265
        local turtle_data = turtle.data
3266
        if turtle_data.request_id == turtle.task_id and turtle.data.session_id == session_id then
3267
            if turtle_data.success then
3268
                if task.end_state then
3269
                    if turtle.state == 'halt' and task.end_state ~= 'halt' then
3270
                        unhalt(turtle)
3271
                    end
3272
                    turtle.state = task.end_state
3273
                end
3274
                if task.end_function then
3275
                    if task.end_function_args then
3276
                        task.end_function(unpack(task.end_function_args))
3277
                    else
3278
                        task.end_function()
3279
                    end
3280
                end
3281
                table.remove(turtle.tasks, 1)
3282
            end
3283
            turtle.task_id = turtle.task_id + 1
3284
        elseif (not turtle_data.busy) and ((not task.epoch) or (task.epoch > os.clock()) or (task.epoch + config.task_timeout < os.clock())) then
3285
            -- ONLY SEND INSTRUCTION AFTER <config.task_timeout> SECONDS HAVE PASSED
3286
            task.epoch = os.clock()
3287
            print(string.format('Sending %s directive to %d', task.action, turtle.id))
3288
            rednet.send(turtle.id, {
3289
                action = task.action,
3290
                data = task.data,
3291
                request_id = turtle_data.request_id
3292
            }, 'mastermine')
3293
        end
3294
    end
3295
end
3296
3297
3298
function user_input(input)
3299
    -- PROCESS USER INPUT FROM USER_INPUT TABLE
3300
    while #state.user_input > 0 do
3301
        local input = table.remove(state.user_input, 1)
3302
        local next_word = string.gmatch(input, '%S+')
3303
        local command = next_word()
3304
        local turtle_id_string = next_word()
3305
        local turtle_id
3306
        local turtles = {}
3307
        if turtle_id_string and turtle_id_string ~= '*' then
3308
            turtle_id = tonumber(turtle_id_string)
3309
            if state.turtles[turtle_id] then
3310
                turtles = {state.turtles[turtle_id]}
3311
            end
3312
        else
3313
            turtles = state.turtles
3314
        end
3315
        if command == 'turtle' then
3316
            -- SEND COMMAND DIRECTLY TO TURTLE
3317
            local action = next_word()
3318
            local data = {}
3319
            for user_arg in next_word do
3320
                table.insert(data, user_arg)
3321
            end
3322
            for _, turtle in pairs(turtles) do
3323
                halt(turtle)
3324
                add_task(turtle, {
3325
                    action = action,
3326
                    data = data,
3327
                })
3328
            end
3329
        elseif command == 'clear' then
3330
            for _, turtle in pairs(turtles) do
3331
                turtle.tasks = {}
3332
                add_task(turtle, {action = 'pass'})
3333
            end
3334
        elseif command == 'shutdown' then
3335
            -- REBOOT TURTLE
3336
            for _, turtle in pairs(turtles) do
3337
                turtle.tasks = {}
3338
                add_task(turtle, {action = 'pass'})
3339
                rednet.send(turtle.id, {
3340
                    action = 'shutdown',
3341
                }, 'mastermine')
3342
            end
3343
        elseif command == 'reboot' then
3344
            -- REBOOT TURTLE
3345
            for _, turtle in pairs(turtles) do
3346
                turtle.tasks = {}
3347
                add_task(turtle, {action = 'pass'})
3348
                rednet.send(turtle.id, {
3349
                    action = 'reboot',
3350
                }, 'mastermine')
3351
            end
3352
        elseif command == 'update' then
3353
            -- FEED TURTLE DINNER
3354
            for _, turtle in pairs(turtles) do
3355
                turtle.tasks = {}
3356
                add_task(turtle, {action = 'pass'})
3357
                rednet.send(turtle.id, {
3358
                    action = 'update',
3359
                }, 'mastermine')
3360
            end
3361
        elseif command == 'return' then
3362
            -- BRING TURTLE HOME
3363
            for _, turtle in pairs(turtles) do
3364
                turtle.tasks = {}
3365
                add_task(turtle, {action = 'pass'})
3366
                halt(turtle)
3367
                send_turtle_up(turtle)
3368
                add_task(turtle, {action = 'go_to_home'})
3369
            end
3370
        elseif command == 'halt' then
3371
            -- HALT TURTLE(S)
3372
            for _, turtle in pairs(turtles) do
3373
                turtle.tasks = {}
3374
                add_task(turtle, {action = 'pass'})
3375
                halt(turtle)
3376
            end
3377
        elseif command == 'reset' then
3378
            -- HALT TURTLE(S)
3379
            for _, turtle in pairs(turtles) do
3380
                turtle.tasks = {}
3381
                add_task(turtle, {action = 'pass'})
3382
                add_task(turtle, {action = 'pass', end_state = 'lost'})
3383
            end
3384
        elseif command == 'on' or command == 'go' then
3385
            -- ACTIVATE MINING NETWORK
3386
            if not turtle_id_string then
3387
                for _, turtle in pairs(state.turtles) do
3388
                    turtle.tasks = {}
3389
                    add_task(turtle, {action = 'pass'})
3390
                end
3391
                state.on = true
3392
                fs.open(state.mine_dir_path .. 'on', 'w').close()
3393
            end
3394
        elseif command == 'off' or command == 'stop' then
3395
            -- STANDBY MINING NETWORK
3396
            if not turtle_id_string then
3397
                for _, turtle in pairs(state.turtles) do
3398
                    turtle.tasks = {}
3399
                    add_task(turtle, {action = 'pass'})
3400
                    free_turtle(turtle)
3401
                end
3402
                state.on = nil
3403
                fs.delete(state.mine_dir_path .. 'on')
3404
            end
3405
        elseif command == 'hubshutdown' then
3406
            -- STANDBY MINING NETWORK
3407
            if not turtle_id_string then
3408
                os.shutdown()
3409
            end
3410
        elseif command == 'hubreboot' then
3411
            -- STANDBY MINING NETWORK
3412
            if not turtle_id_string then
3413
                os.reboot()
3414
            end
3415
        elseif command == 'hubupdate' then
3416
            -- STANDBY MINING NETWORK
3417
            if not turtle_id_string then
3418
                os.run({}, '/update')
3419
            end
3420
        elseif command == 'debug' then
3421
            -- DEBUG
3422
        end
3423
    end
3424
end
3425
3426
3427
function command_turtles()
3428
    local turtles_for_pair = {}
3429
    
3430
    for _, turtle in pairs(state.turtles) do
3431
        
3432
        if turtle.data then
3433
        
3434
            if turtle.data.session_id ~= session_id then
3435
                -- BABY TURTLE NEEDS TO LEARN
3436
                if (not turtle.tasks) or (not turtle.tasks[1]) or (not (turtle.tasks[1].action == 'initialize')) then
3437
                    initialize_turtle(turtle)
3438
                end
3439
            end
3440
3441
            if #turtle.tasks > 0 then
3442
                -- TURTLE IS BUSY
3443
                send_tasks(turtle)
3444
3445
            elseif not turtle.data.location then
3446
                -- TURTLE NEEDS A MAP
3447
                add_task(turtle, {action = 'calibrate'})
3448
3449
            elseif turtle.state ~= 'halt' then
3450
3451
                if turtle.state == 'park' then
3452
                    -- TURTLE FOUND PARKING
3453
                    if state.on and (config.use_chunky_turtles or turtle.data.turtle_type == 'mining') then
3454
                        add_task(turtle, {action = 'pass', end_state = 'idle'})
3455
                    end
3456
3457
                elseif not state.on and turtle.state ~= 'idle' then
3458
                    -- TURTLE HAS TO STOP
3459
                    add_task(turtle, {action = 'pass', end_state = 'idle'})
3460
3461
                elseif turtle.state == 'lost' then
3462
                    -- TURTLE IS CONFUSED
3463
                    if turtle.data.location.y < config.locations.mine_enter.y and (turtle.pair or not config.use_chunky_turtles) then
3464
                        add_task(turtle, {action = 'pass', end_state = 'trip'})
3465
                        add_task(turtle, {
3466
                            action = 'go_to_strip',
3467
                            data = {turtle.strip},
3468
                            end_state = 'wait'
3469
                        })
3470
                    else
3471
                        add_task(turtle, {action = 'pass', end_state = 'idle'})
3472
                    end
3473
3474
                elseif turtle.state == 'idle' then
3475
                    -- TURTLE IS BORED
3476
                    free_turtle(turtle)
3477
                    if turtle.data.location.y < config.locations.mine_enter.y then
3478
                        send_turtle_up(turtle)
3479
                    elseif not basics.in_area(turtle.data.location, config.locations.control_room_area) then
3480
                        halt(turtle)
3481
                    elseif turtle.data.item_count > 0 or (turtle.data.fuel_level ~= "unlimited" and turtle.data.fuel_level < config.fuel_per_unit) then
3482
                        add_task(turtle, {action = 'prepare', data = {config.fuel_per_unit}})
3483
                    elseif state.on then
3484
                        add_task(turtle, {
3485
                            action = 'go_to_waiting_room',
3486
                            end_function = check_pair_fuel,
3487
                            end_function_args = {turtle},
3488
                        })
3489
                    else
3490
                        add_task(turtle, {action = 'go_to_home', end_state = 'park'})
3491
                    end
3492
3493
                elseif turtle.state == 'pair' then
3494
                    -- TURTLE NEEDS A FRIEND
3495
                    if config.use_chunky_turtles then
3496
                        if not state.pair_hold then
3497
                            if not turtle.pair then
3498
                                table.insert(turtles_for_pair, turtle)
3499
                            end
3500
                        else
3501
                            if not (state.pair_hold[1].pair and state.pair_hold[2].pair) then
3502
                                state.pair_hold = nil
3503
                            end
3504
                        end
3505
                    else
3506
                        solo_turtle_begin(turtle)
3507
                    end
3508
3509
                elseif turtle.state == 'wait' then
3510
                    -- TURTLE GO DO SOME WORK
3511
                    if turtle.pair then
3512
                        if turtle.data.turtle_type == 'mining' and turtle.pair.state == 'wait' then
3513
                            if turtle.steps_left <= 0 or (turtle.data.empty_slot_count == 0 and turtle.pair.data.empty_slot_count == 0) or not good_on_fuel(turtle, turtle.pair) then
3514
                                add_task(turtle, {action = 'pass', end_state = 'idle'})
3515
                                add_task(turtle.pair, {action = 'pass', end_state = 'idle'})
3516
                            elseif turtle.data.empty_slot_count == 0 then
3517
                                add_task(turtle, {
3518
                                    action = 'dump',
3519
                                    data = {reverse_shift[turtle.strip.orientation]}
3520
                                })
3521
                            else
3522
                                add_task(turtle, {action = 'pass', end_state = 'mine'})
3523
                                add_task(turtle.pair, {action = 'pass', end_state = 'mine'})
3524
                                go_mine(turtle)
3525
                            end
3526
                        end
3527
                    elseif not config.use_chunky_turtles then
3528
                        if turtle.steps_left <= 0 or turtle.data.empty_slot_count == 0 or not good_on_fuel(turtle) then
3529
                            add_task(turtle, {action = 'pass', end_state = 'idle'})
3530
                        else
3531
                            add_task(turtle, {action = 'pass', end_state = 'mine'})
3532
                            go_mine(turtle)
3533
                        end
3534
                    else
3535
                        add_task(turtle, {action = 'pass', end_state = 'idle'})
3536
                    end
3537
                elseif turtle.state == 'mine' then
3538
                    if config.use_chunky_turtles and not turtle.pair then
3539
                        add_task(turtle, {action = 'pass', end_state = 'idle'})
3540
                    end
3541
                end
3542
            end
3543
        end
3544
    end
3545
    if #turtles_for_pair == 2 then
3546
        pair_turtles_begin(turtles_for_pair[1], turtles_for_pair[2])
3547
    end
3548
end
3549
3550
3551
function main()
3552
    -- INCREASE SESSION ID BY ONE
3553
    if fs.exists('/session_id') then
3554
        session_id = tonumber(fs.open('/session_id', 'r').readAll()) + 1
3555
    else
3556
        session_id = 1
3557
    end
3558
    local file = fs.open('/session_id', 'w')
3559
    file.write(session_id)
3560
    file.close()
3561
    
3562
    -- LOAD MINE INTO MEMORY
3563
    load_mine()
3564
    
3565
    -- FIND THE CLOSEST STRIP
3566
    gen_next_strip()
3567
    
3568
    local cycle = 0
3569
    while true do
3570
        print('Cycle: ' .. cycle)
3571
        user_input()         -- PROCESS USER INPUT
3572
        command_turtles()    -- COMMAND TURTLES
3573
        sleep(0.1)           -- DELAY 0.1 SECONDS
3574
        cycle = cycle + 1
3575
    end
3576
end
3577
3578
3579
main()]===],
3580
}
3581
3582
for k, v in pairs(files) do
3583
    local file = fs.open(fs.combine(path, k), 'w')
3584
    file.write(v)
3585
    file.close()
3586
end
3587