Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- if not docs then os.loadAPI("apis/docs.lua") end
- if not turt then os.loadAPI("apis/turt.lua") end
- if not refuel then os.loadAPI("apis/refuel.lua") end
- if not encryption then os.loadAPI("apis/encryption.lua") end
- if not screen then os.loadAPI("apis/screen.lua") end
- --if not require then os.loadAPI("rom/modules/main/cc/require.lua") end
- --Type registry
- local types = {
- ["Blockstate"]={colors.lightBlue,"A table with blockstate data, such as {facing=\"up\"}"},
- ["Nbt"]={colors.lightBlue,"A table with nbt data. Currently unused"},
- ["Block"]={colors.brown,"A minecraft block, with id, nbt, and blockstate"},
- ["Schema"]={colors.orange,"A 3D array of numbers, each representing schematic data. Indexed by Schema[y][x][z]"},
- ["SchematicTurtle"]={colors.brown,"dumb turtle thing"}
- }
- for k,v in pairs(types) do
- docs.registerType(k,v[1],v[2])
- end
- VALID_BLOCK_STATES = {
- facing={"up","down","north","east","west","south"},
- half={"top","bottom"},
- type={"top","bottom","double"},
- axis={"x","y","z"},
- open={"true","false"}
- }
- NBT_TAGS = {
- [0]="TAG_End", [1]="TAG_Byte", [2]="TAG_Short", [3]="TAG_Int", [4]="TAG_Long", [5]="TAG_Float", [6]="TAG_Double",
- [7]="TAG_Byte_Array", [8]="TAG_String", [9]="TAG_List", [10]="TAG_Compound", [11]="TAG_Int_Array", [12]="TAG_Long_Array"
- }
- facing_tab = {"north","east","south","west",north=0,east=1,south=2,west=3}
- --Default .schema values
- --0x0000 = y++
- --0x0001 = x++
- --0x0002 = {id="minecraft:air"}
- --Takes blockstate tables and turns them into validated blockstate tables (only blockstates that are allowed)
- --@Arg Blockstate blockstate: The blockstate to be validated
- --@Returns Blockstate bs: The blockstate with only valid blockstates included
- --@Returns None nil: No blockstate provided
- local function validateBlockstate(blockstate)
- if type(blockstate) ~= "table" then return end
- local bs = {}
- for k,v in pairs(blockstate) do
- local validStates = VALID_BLOCK_STATES[k]
- if validStates then
- for j,w in pairs(validStates) do
- if w == v then bs[k] = v end
- end
- end
- end
- return bs
- end
- --TODO: If I manage to get nbt working, make this do something instead of always returning nil
- --@Arg Nbt nbt: The nbt to be validated
- --@Returns Nbt valid_nbt: the validated nbt
- --@Returns None nil: There was no nbt provided
- local function validateNbt(nbt)
- end
- --Creates a new block with id, blockstate, and nbt
- --@Arg string id: The registry name of the block
- --@OptionalArg Blockstate blockstate: the blockstate of the specific block
- --@OptionalArg Nbt nbt: The nbt of the block (unused)
- --@Returns Block block: The completed block
- function newBlock(id,blockstate,nbt)
- blockstate = validateBlockstate(blockstate)
- nbt = validateNbt(nbt)
- local block = {}
- block.id = id
- if blockstate then block.bs = blockstate end
- if nbt then block.nbt = nbt end
- return block
- end
- function copyTab(tab)
- if type(tab) ~= "table" then return tab end
- local newTab = {}
- for k,v in pairs(tab) do
- newTab[k] = copyTab(v)
- end
- return newTab
- end
- --Copies a block
- function copyBlock(block)
- local newBlock = {}
- newBlock.id = block.id
- newBlock.bs = copyTab(block.bs)
- newBlock.nbt = copyTab(block.nbt)
- return newBlock
- end
- --Generates a a table that can turn the bytes into a table of values
- --@Returns table metadata: {[integer] = {id="",blockstate={}}
- function readSchemMD()
- if not fs.exists(".schematic_data.json") then return {[1]=newBlock("minecraft:air")} end
- local file = fs.open(".schematic_data.json","r")
- local data = textutils.unserialiseJSON(file.readAll())
- if type(data) ~= "table" then data = {} end
- data[1] = newBlock("minecraft:air")
- return data
- end
- --Adds schematic data to .schematic_data.json
- --@Arg Block block: The block to be added
- local function addSchemData(block)
- local md = readSchemMD()
- table.insert(md,block)
- local file = fs.open(".schematic_data.json","w+")
- file.write(textutils.serialiseJSON(md))
- file.close()
- end
- --Checks if two blockstates are equal
- --@Arg Blockstate bs1: The first blockstate to be compared
- --@Arg Blockstate bs2: The second blockstate to be compared
- --@Returns boolean equal: If the two blockstates are equal
- local function compareBlockstate(bs1, bs2)
- if bs1 == bs2 then return true end
- bs1 = bs1 or {}
- bs2 = bs2 or {}
- for k,v in pairs(bs1) do
- if v ~= bs2[k] then return false end
- end
- for k,v in pairs(bs2) do
- if v ~= bs1[k] then return false end
- end
- return true
- end
- --Checks if two blocks are equal
- --@Arg Block block1: The first block to be compared
- --@Arg Block block2: The second block to be compared
- --@Returns boolean equal: If the two blocks are equal
- local function compareBlock(block1, block2)
- if block1.id ~= block2.id then return false end
- return compareBlockstate(block1.bs,block2.bs) and compareBlockstate(block1.nbt,block2.nbt)
- end
- --Gets the schem data for a block, or adds it to the data
- --@Arg string id: the id of the block to add
- --@OptionalArg Blockstate blockstate: The specific blockstate to get.
- --@Returns number blockCode,Block block: The index of the block in the palette, and the block itself
- local function getOrAddSchemData(id,blockstate,nbt)
- local md = readSchemMD()
- local block = newBlock(id,blockstate,nbt)
- for k,v in pairs(md) do
- if compareBlock(v,block) then return k,v end
- end
- addSchemData(block)
- return getOrAddSchemData(id,blockstate,nbt)
- end
- --Turns a series of bytes into a number, in big Endian
- --@Args number bytes: A series of bytes from the schema
- --@Returns number index: The index number of the byte in the schema metadata
- local function schemaByteToNumber(...)
- local args = {...}
- local index = 0
- for i,v in ipairs(args) do
- index = 256*index+tonumber(v)
- end
- return index - 1
- end
- --Turns a series of bytes into a signed number, big endian
- --@Args number bytes: A series of bytes
- --@Returns number num: The signed number from the bytes
- local function bytesToSignedNumber(...)
- local args = {...}
- local num = 0
- for i,v in ipairs(args) do
- num = 256*num+tonumber(v)
- end
- local max_value = 256^(#args)
- if num >= max_value/2 then num = num - max_value end
- return num
- end
- --Turns a series of bytes into a floating point number
- --@Args number bytes: A series of bytes
- --@Returns number fp: A floating point number
- local function bytesToFloatingPoint(...)
- local args = {...}
- local double = false
- if #args >= 8 then double = true end
- local sign = (-1)^math.floor(args[1]/128)
- local exponent = args[1]%128
- local mantissa = 0
- local tempMantissa = 0
- local count = -1
- if double then
- exponent = exponent*16+math.floor(args[2]/16)
- if exponent > 0 then mantissa = 1 end --Weird fp stuff idk tbh
- exponent = exponent - 1023
- if exponent > 1024 then print("Floating point should be infinity, this might break stuff") end
- tempMantissa = args[2]%16
- for i=3,#args do
- tempMantissa = 256*tempMantissa+args[i]
- end
- else
- exponent = exponent*2+math.floor(args[2]/128)
- if exponent > 0 then mantissa = 1 end --Weird fp thing
- exponent = exponent - 127
- if exponent > 128 then print("Floating point should be infinity, this might break stuff") end
- tempMantissa = args[2]%128
- for i=3,#args do
- tempMantissa = 256*tempMantissa+args[i]
- end
- end
- local resolution = 23
- if double then resolution = 53 end
- mantissa = mantissa+tempMantissa/(2^resolution)
- return sign*math.ldexp(mantissa,exponent),exponent,mantissa
- end
- --Turns a series of bytes into a block
- --@Arg number index: The index of the schema metadata
- --@Returns Block block: The block corresponding to the bytes
- --@Returns None nil: If no block was found
- local function numberToBlock(index)
- local md = readSchemMD()
- if md[index] then return md[index] end
- end
- --Turns a index number into a set of schema bytes
- --@Arg number index: The index to convert into bytes
- --@OptionalArg number byteCount: The number of bytes to converr the data into
- --@Returns table bytes: A list of the bytes
- local function numberToSchemaBytes(index,byteCount)
- local bytes = {}
- if not tonumber(index) then return end
- index = tonumber(index)+1
- table.insert(bytes,index%256)
- index = math.floor(index/256)
- while index > 0 do
- table.insert(bytes,1,index%256)
- index = math.floor(index/256)
- end
- byteCount = tonumber(byteCount) or #bytes
- while #bytes < byteCount do
- table.insert(bytes,1,0)
- end
- return bytes
- end
- --Reads a .schema file, converting it into a table of numbers
- --@Arg string path: the absolute path to the file
- --@Returns Schema schema, number x, number y, number z: the completed schematic of the item, and its dimensions
- --@Returns None nil: If the schema could not be completed
- local function readSchema(path)
- if not fs.exists(path) then return end
- local md = readSchemMD()
- local file = fs.open(path,"rb")
- local schema = {}
- local row = {}
- local col = {}
- local x = 0 --how wide in x
- local y = 0 --how wide in y
- local z = 0 --how wide in z
- local dataWidth = file.read()
- while file.read(0) do
- local bytes = {}
- for i=1,dataWidth do
- table.insert(bytes,file.read() or 0)
- end
- local idx = schemaByteToNumber(unpack(bytes))
- if idx == -1 then
- if #col > 0 then
- table.insert(row,col)
- end
- z = math.max(z,#col)
- x = math.max(x,#row)
- table.insert(schema,row)
- row = {}
- col = {}
- elseif idx == 0 then
- table.insert(row,col)
- z = math.max(z,#col)
- col = {}
- else
- if not md[idx] then
- print("Invalid block metadata found")
- return
- end
- table.insert(col,idx)
- end
- end
- if #col > 0 then table.insert(row,col) end
- if #row > 0 and #row[1] > 0 then table.insert(schema,row) end
- local y = #schema
- return schema,x,y,z
- end
- --Saves a Schema to the path
- --@Arg string path: The path that the schema should be saved to
- --@Arg Schema schema: The schema to be saved
- --@Arg number x: The width of the schema
- --@Arg number y: The height of the schema
- --@Arg number z: The depth of the schema
- local function saveSchema(path,schema,x,y,z)
- if fs.exists(path) then fs.delete(path) end
- local md = readSchemMD()
- local dataWidth = math.floor(math.log(#md)/math.log(256))+1 --Change of base formula
- local file = fs.open(path,"w+b")
- file.write(dataWidth)
- for i=1,y do
- if type(schema[i]) ~= "table" then schema[i] = {} end
- for j=1,x do
- if type(schema[i][j]) ~= "table" then schema[i][j] = {} end
- for k=1,z do
- local bytes = numberToSchemaBytes(schema[i][j][k],dataWidth)
- for l=1,dataWidth do
- if type(bytes) == "table" and tonumber(bytes[l]) then file.write(bytes[l])
- else file.write(2) end --Writing down air if schema value not present
- end
- end
- file.write(1)
- end
- file.write(0)
- end
- file.close()
- end
- --Recursively reads a nbt tag
- --TYPE_IDS: 00 = END; 01,02,03,04 = Byte,Short,Int,Long; 05,06 = Float,Double; 08 = String; 07,0b,0c = ByteArray,IntArray,LongArray; 09 = List; 0a = CompoundTag
- --@Arg File file: The file handle to be read from, in rb mode
- --@OptionalArg number typeID: The nbt data type
- --@Returns Nbt nbt: The completed nbt tag
- local function readTag(file,typeID)
- typeID = typeID or 10
- --Any signed, whole number
- if typeID == 1 or typeID == 2 or typeID == 3 or typeID == 4 then
- len = 2^(typeID-1) --Number of bytes of the number
- local bytes = {}
- for i=1,len do
- table.insert(bytes,file.read())
- end
- return bytesToSignedNumber(unpack(bytes))
- end
- --The floating points, floats and doubles
- if typeID == 5 or typeID == 6 then
- len = 4
- if typeID == 6 then len = 8 end
- local bytes = {}
- for i=1,len do
- table.insert(bytes,file.read())
- end
- return bytesToFloatingPoint(unpack(bytes))
- end
- --String, which is prefixed with a 2 bit unsigned short determining the length
- if typeID == 8 then
- length = file.read()
- length = length * 256 + file.read() --Reading the prefix short
- return tostring(file.read(length))
- end
- --The arrays, which are prefixed with a signed integer for their length
- if typeID == 7 or typeID == 11 or typeID == 12 then
- local len = 1
- if typeID == 11 then len = 4
- elseif typeID == 12 then len = 8 end
- local arr = {}
- local length = readTag(file,3) --Gets signed integer length
- for i=1,length do
- local data = {}
- for j=1,len do
- table.insert(data,file.read())
- end
- table.insert(arr,bytesToSignedNumber(unpack(data)))
- end
- return arr
- end
- --The lists, which are prefixed with a single byte for their elements' type, and then a signed integer for the length
- if typeID == 9 then
- local listType = file.read()
- local length = readTag(file,3) --Gets signed integer length
- local list = {}
- for i=1,length do
- table.insert(list,readTag(file,listType))
- end
- return list
- end
- --The Compound tags, which are prefixed with a single byte for their elements' type, then each element is also prefixed with a string element (short for length + the string data), and is terminated by the END tag (00)
- if typeID == 10 then
- local t = {}
- local compoundType = file.read()
- while compoundType and compoundType > 0 do
- local name = readTag(file,8) --Gets the string name
- t[name] = readTag(file,compoundType)
- compoundType = file.read()
- end
- return t
- end
- return
- end
- --Turns a .nbt file into a table
- --@Arg string path: the absolute path to the nbt
- --@Returns Nbt nbt: the data read from the nbt files
- --@Returns boolean false: If there was an error reading the nbt
- function readNBT(path)
- if not fs.exists(path) then return false end
- local file = fs.open(path,"rb")
- local data = readTag(file)
- file.close()
- return data
- end
- --Converts NBT data into Schema, while registering the unrecognized blocks
- --@Arg Nbt nbt: the nbt data from readNBT()
- --@Returns Schema schem, number x, number y, number z: The loaded schematic and its dimensions
- --@Returns boolean false,string errMsg: If the nbt failed
- function serialiseNBTData(nbt)
- if type(nbt) ~= "table" then return false, "invalid input nbt" end
- nbt = nbt[""] --Dumb implied compoundtag fuckery
- if type(nbt) ~= "table" then return false, "nbt has no implied compoundTag, or it could not be found" end
- local x,y,z
- if type(nbt.size) == "table" then
- x,y,z = nbt.size[1], nbt.size[2], nbt.size[3]
- else
- return false, "Nbt did not have properly defined dimensions"
- end
- local schema = {}
- local palette = nbt.palette
- if type(palette) ~= "table" then return false, "No palette was provided for the nbt" end
- local blocks = nbt.blocks
- if type(blocks) ~= "table" then return false, "No blocks were provided for the nbt" end
- for k,v in pairs(blocks) do
- local pos = v.pos
- if not pos then return false, "Block position was undefined" end
- local state = v.state+1
- if not palette[state] then return false, "Invalid blockstate, not defined by palette" end
- local id,bs = palette[state].Name, palette[state].Properties
- local nbtTag = v.nbt
- local mdKey,block = getOrAddSchemData(id,bs,nbtTag)
- local iX,iY,iZ = unpack(pos)
- if type(schema[iY+1]) ~= "table" then schema[iY+1] = {} end
- if type(schema[iY+1][iX+1]) ~= "table" then schema[iY+1][iX+1] = {} end
- schema[iY+1][iX+1][iZ+1] = mdKey
- end
- if type(nbt.entities) == "table" and #nbt.entities > 1 then
- print("Entities detected within schematic, which will be ignored by the turtle")
- end
- for i=1,y do
- for j=1,x do
- for k=1,z do
- if not schema[i] then schema[i] = {} end
- if not schema[i][j] then schema[i][j] = {} end
- if not schema[i][j][k] then schema[i][j][k] = 1 end
- end
- end
- end
- return schema,x,y,z
- end
- --Prints an binary file in it's raw form for easy viewing
- --@Arg string path: The absolute path to the file
- --@OptionalArg Color color1: The first background color, for easy viewing
- --@OptionalArg Color color2: The second background color
- function printBinary(path,color1,color2)
- if not fs.exists(path) then return end
- color1 = color1 or colors.white
- color2 = color2 or colors.lightGray
- local file = fs.open(path,"rb")
- local byte = file.read()
- term.clear()
- term.setCursorPos(1,1)
- term.setTextColor(colors.black)
- term.setBackgroundColor(colors.black)
- while byte do
- local x,y = term.getCursorPos()
- local maxX, maxY = term.getSize()
- if x >= maxX then
- term.setCursorPos(1,y+1)
- end
- x,y = term.getCursorPos()
- if math.floor((x-1)/2)%2 == 0 then term.setBackgroundColor(color1) else term.setBackgroundColor(color2) end
- term.write(string.format("%02x",byte))
- byte = file.read()
- end
- term.setBackgroundColor(colors.black)
- term.setTextColor(colors.white)
- file.close()
- term.setTextColor(colors.white)
- end
- --Loads a schem inside the schematics folder
- --If it is not existing as a schema, the program converts it to a schema
- --@OptionalArg string schem: The name of the schem within the schematics folder
- --@Returns Schema schema, number x, number y, number z: The loaded schematic, and its dimensions
- --@Returns boolean false: If schematic loading failed
- function loadSchem(schem)
- local filepath,fileType = nil
- if type(schem) ~= "string" then
- filepath = encryption.selectFile("schematics")
- if filepath then
- fileType = string.match(filepath,"%.%w+$")
- schem = string.gsub(string.gsub(filepath,"%w+/",""),"%.%w+","")
- --schem = string.sub(string.gsub(string.match(filepath,"/%w+%.%w+$"),fileType,""),2,-1)
- end
- end
- if not schem then return false, "No valid path provided" end
- --Case schema already exists
- if ( fileType == ".schema" ) or (not fileType and type(schem) == "string" and fs.exists("schematics/"..schem ..".schema")) then
- local schema,x,y,z = readSchema(filepath or "schematics/" .. schem .. ".schema")
- if not schema then return false, "Reading .schema failed" end
- return schema,x,y,z
- elseif ( fileType == ".uncompressedNBT" ) or (not fileType and type(schem) == "string" and fs.exists(filepath or "schematics/"..schem .. ".uncompressedNBT")) then
- local schema,x,y,z = serialiseNBTData(readNBT(filepath or "schematics/"..schem .. ".uncompressedNBT"))
- if not schema then
- print(x)
- return false, "Serializing .uncompressedNBT failed"
- end
- saveSchema("schematics/"..schem .. ".schema", schema, x,y,z)
- return schema,x,y,z
- elseif ( fileType == ".nbt" ) or (not fileType and type(schem) == "string" and fs.exists(filepath or "schematics/"..schem .. ".nbt")) then
- print("Attempting to load .nbt file, make sure that it is uncompressed!")
- --LUA_PATH = "/apis/?.lua"
- --local zzlib = req("libs.zzlib")
- --local zzlib = shell.run("apis/libs/zzlib.lua")
- local zzlib = dofile("apis/libs/zzlib.lua")
- local file = fs.open(filepath or "schematics/"..schem..".nbt","r")
- local data = zzlib.gunzip(file.readAll())
- file.close()
- local file = fs.open("schematics/"..schem..".uncompressedNBT","w+")
- file.write(data)
- file.close()
- fs.delete(filepath or "schematics/"..schem..".nbt")
- local schema,x,y,z = serialiseNBTData(readNBT("schematics/"..schem .. ".uncompressedNBT"))
- if not schema then
- print(x)
- return false, "reading uncompressed .nbt from compressed nbt failed"
- end
- saveSchema("schematics/"..schem .. ".schema", schema, x,y,z)
- return schema,x,y,z
- end
- return false, "no schem found"
- end
- --Prints information about the api
- function printREADME()
- print("This api will load and place schematics")
- print("Currently, it only supports uncompressed .nbt files and the native .schema")
- print()
- print("To upload a .nbt, first uncompress the nbt schematic on your own computer with an archive manager")
- print("Then drag and drop the uncompressed file onto the computer's home screen to upload it")
- print("Make sure to move the file to the /schematics/ folder in your computer!")
- print()
- print("The .schema file is a easy-to-read schematic, but it only works on the computer it was created on")
- print("The data is converted into numbers, which correspond to keys inside the .schematic_data.json file")
- print("The first byte of the .schema file determines the length of each data value")
- print("The rest of the data is a list of a series of bytes (whose length is determined by the first byte)")
- print("A value of 0 corresponds to moving to a new y layer, while a value of 1 corresponds to moving to a new row within that layer")
- print("Otherwise, the values are block data")
- end
- --This generally relies on block ids matching their corresponding item ids
- --@Arg Schema schema: The schema used
- --@Returns table blocklist: A list of {[string blockId]=number count}
- function getBlockList(schema)
- local blockList = {}
- local md = readSchemMD()
- for k,v in pairs(schema) do
- for j,w in pairs(v) do
- for l,u in pairs(w) do
- if u > 1 then
- local id = md[u].id
- if not tonumber(blockList[id]) then blockList[id] = 1 else blockList[id] = blockList[id] + 1 end
- if type(md[u].bs) == "table" and #md[u].bs >= 1 then
- print("BlockState is currently not supported, ignoring it now!")
- end
- end
- end
- end
- end
- return blockList
- end
- local function addItem(blockList,item)
- for i=1,16 do
- if not blockList[i] or blockList[i].count <= 0 then
- blockList[i] = {count=1,id=item}
- return true
- elseif blockList[i].id == item and blockList[i].count < 64 then
- blockList[i].count = blockList[i].count + 1
- return true
- end
- end
- return false
- end
- --Gets a list of blocks needed for the schema
- --@Args Schema schema: The schema being used
- --@Returns table blockList: A list of the next 16 types of blocks to use
- local function getNeededBlocks(schema)
- local blockList = {}
- local md = readSchemMD()
- local count = 0
- for k,v in pairs(schema) do
- for j,w in pairs(v) do
- for l,u in pairs(w) do
- if u > 1 then
- if not addItem(blockList,md[u].id) then return blockList end
- end
- end
- end
- end
- return blockList
- end
- --Selects the item corresponding to the block
- --@Arg Block block: The block to select
- --@Returns boolean success: Whether the block could be selected or not
- local function selectBlock(block)
- local id = block.id
- local slot = refuel.findItem(id)
- if not slot then return false end
- turtle.select(slot)
- return true
- end
- --Places a block below the turtle
- --@Arg Block block: The block to place, with blockstate and nbt (though unused)
- --@Returns boolean success: Whether the block was placed or not
- local function placeBlock(block)
- if not selectBlock(block) then return false end
- turt.digDown()
- turt.placeDown()
- --TODO: Blockstate [+ nbt?] placements
- return true
- end
- --Pulls an item from an inventory below it
- --@Arg string id: The id of the item to pull
- --@OptionalArg number amount: The number of items to pull, from 1-64
- --@Returns boolean success: If the items were taken from the chest
- local function pullItemFromChest(id,amount)
- amount = math.max(math.min(math.floor(tonumber(amount) or 64),64),1)
- local chest = peripheral.wrap("bottom")
- if not chest then return false end
- local freeSlot = nil
- local targetSlot = nil
- for i=1,chest.size() do
- local item = chest.getItemDetail(i)
- if not item then freeSlot = i
- elseif item.name == id then targetSlot = i end
- end
- if turt.getFreeSpace(id) < amount then return false end --no free slots to put items in
- if not targetSlot then return false end
- if targetSlot == 1 then return turtle.suckDown(amount) end
- if not freeSlot then
- local tempItem = chest.getItemDetail(1)
- if tempItem.count > 64 then return false end --Dont want to tell with sophisticated backpacks with 2 billion items in a slot
- local turtSlot = turt.getFreeSlot()
- turtle.suckDown(64)
- chest.pullItems(peripheral.getName(chest),targetSlot,chest.getItemLimit(targetSlot),1)
- turt.dropDown(turtSlot)
- return turtle.suck(amount)
- else
- chest.pullItems(peripheral.getName(chest),1,chest.getItemLimit(1),freeSlot)
- chest.pullItems(peripheral.getName(chest),targetSlot,chest.getItemLimit(targetSlot),1)
- return turtle.suck(amount)
- end
- end
- --Creates a new schematic turtle (st)
- --@Arg Schema schema: The schema for the turtle
- --@OptionalArg number x: The x coordinate of the turtle (and its home position)
- --@OptionalArg number y: The y coordinate of the turtle
- --@OptionalArg number z: The z coordinate of the turtle
- --@OptionalArg number rot: The rotation of the turtle from what its reference frame should be
- --@Returns SchematicTurtle st: The schematic turtle
- function SchematicTurtle(schema,x,y,z,rot)
- local st = {
- x = math.floor(tonumber(x) or 0),
- y = math.floor(tonumber(y) or 0),
- z = math.floor(tonumber(z) or 0),
- rot = math.floor(tonumber(rot) or 0)%4,
- schema = schema
- }
- st.hx,st.hy,st.hz = st.x,st.y,st.z
- function st:rotate(rot)
- local delRot = (self.rot-rot)%4
- if delRot == 3 then
- turt.turnLeft()
- self.rot = (self.rot - 1)%4
- else
- turt.turnRight(delRot)
- self.rot = (self.rot + delRot)%4
- end
- end
- function st:moveX(amt)
- if amt > 0 then self:rotate(1) else self:rotate(3) end
- for i=1,math.abs(amt) do
- turt.dig()
- turt.forward()
- end
- self.x = self.x+amt
- end
- function st:moveY(amt)
- local f = function() turt.digUp() turt.up() end
- if amt < 0 then f = function() turt.digDown() turt.down() end end
- for i=1,math.abs(amt) do
- f()
- end
- self.y = self.y+amt
- end
- function st:moveZ(amt)
- if amt > 0 then self:rotate(0) else self:rotate(2) end
- for i=1,math.abs(amt) do
- turt.dig()
- turt.forward()
- end
- self.z = self.z+amt
- end
- --Move along straight axis
- function st:move(dir,amt)
- local f = function() turt.dig() turt.forward() end
- if dir == 2 then f = function() turt.digUp() turt.up() end
- self.y = self.y + amt
- elseif dir == -2 then f = function() turt.digDown() turt.down() end
- self.y = self.y - amt
- elseif dir == 3 then --forward -> rot = 0
- self:rotate(0)
- self.z = self.z + amt
- elseif dir == -3 then
- self:rotate(2)
- self.z = self.z - amt
- elseif dir == 1 then
- self:rotate(1)
- self.x = self.x + amt
- elseif dir == -1 then
- self:rotate(3)
- self.x = self.x - amt
- end
- for i=1,amt do
- f()
- end
- end
- --Go to x,y,z coord
- --Order is the order you should go in, number 0-8
- -- order//3 tells you the first axis [x,y,z] to travel along
- -- order%3 tells you the second axis [x,y,z] to travel along, after you finish the first
- -- The last axis is chosen by process of elimination
- -- Convoluted fckery
- function st:goToPos(x,y,z,order)
- cPos = {[0]=self.x,[1]=self.y,[2]=self.z}
- tPos = {[0]=x,[1]=y,[2]=z}
- order = math.min(math.max(math.floor(tonumber(order) or 3),0),8)
- local firstOrder = math.floor(order/3)
- local secondOrder = order%3
- local thirdOrder = 3-firstOrder-secondOrder
- -- for k,v in pairs({firstOrder,secondOrder,thirdOrder}) do
- -- local amt = tPos[v]-cPos[v]
- -- if amt ~= 0 then
- -- self:move((v+1)*amt/math.abs(amt),math.abs(amt))
- -- end
- -- end
- if firstOrder == 0 then self:moveX(x-self.x) elseif firstOrder == 1 then self:moveY(y-self.y) else self:moveZ(z-self.z) end
- if secondOrder == 0 then self:moveX(x-self.x) elseif secondOrder == 1 then self:moveY(y-self.y) else self:moveZ(z-self.z) end
- if thirdOrder == 0 then self:moveX(x-self.x) elseif thirdOrder == 1 then self:moveY(y-self.y) else self:moveZ(z-self.z) end
- end
- function st:goHome() --ET phone home
- self:goToPos(self.hx,self.hy,self.hz,2) --order z x y
- end
- function st:pickUpItems()
- local oldX,oldY,oldZ = self.x,self.y,self.z
- self:goHome()
- for i=1,16 do
- turt.dropDown()
- end
- local blockList = getNeededBlocks(self.schema)
- for k,v in pairs(blockList) do
- if v then
- while not pullItemFromChest(v.id,v.count) do
- sleep(1)
- term.setCursorPos(1,1)
- term.setTextColor(colors.red)
- term.write(string.format("Missing %d of %s",v.count,v.id))
- end
- term.clear()
- term.setTextColor(colors.white)
- end
- end
- self:goToPos(oldX,oldY,oldZ)
- end
- --Places a block below the turtle
- --@Arg Block block: The block to place, with blockstate and nbt (though unused)
- --@Returns boolean success: Whether the block was placed or not
- function st:placeBlock(block)
- if not selectBlock(block) then return false end
- if block.bs and block.bs.facing and facing_tab[block.bs.facing] then
- local dir = facing_tab[block.bs.facing] + 2
- local oldDir = self.rot
- self:rotate(dir)
- turt.digDown()
- turt.placeDown()
- self:rotate(oldDir)
- else
- turt.digDown()
- turt.placeDown()
- end
- --TODO: Blockstate [+ nbt?] placements
- return true
- end
- return st
- end
- --Prints a schema
- --@Arg Schema schema: The schematic to be loaded
- function printSchema(schema)
- local st
- if not peripheral.wrap("bottom") or not peripheral.wrap("bottom").list then --If not starting on a chest, checks if the turtle already has the necessary items
- local neededItems = getBlockList(schema)
- for i=1,16 do
- local item = turtle.getItemDetail(i)
- if item and neededItems[item.name] then
- neededItems[item.name] = neededItems[item.name] - item.count
- if neededItems[item.name] <= 0 then neededItems[item.name] = nil end
- end
- end
- local hasNeededItems = true
- for k,v in pairs(neededItems) do
- if tonumber(v) and v > 0 then hasNeededItems = false end
- end
- if not hasNeededItems then
- print(textutils.serialise(neededItems,{compact=true}))
- return false
- end
- st = SchematicTurtle(schema,1,0,0,2)
- else
- st = SchematicTurtle(schema,1,1,0,2)
- st:pickUpItems()
- end
- local md = readSchemMD()
- for k,v in ipairs(schema) do
- for j,w in ipairs(v) do
- for l,u in ipairs(w) do
- if u > 1 then
- st:goToPos(j,k,l)
- while not st:placeBlock(md[u]) do
- st:pickUpItems()
- end
- schema[k][j][l] = 0
- end
- end
- end
- end
- return true
- end
- --Constructs a 2d matrix
- --@OptionalArg table arg1: The 2d table to construct off of, or the width of the matrix
- --@OptionalArg number arg2: The height of the matrix
- --@Returns Matrix matrix: The constructed matrix
- function Matrix(arg1,arg2)
- local matrix = { {1,0},{0,1} } --Default matrix is I2
- if type(arg1) == "table" and type(arg1[1]) == "table" then --If 2d table provided, use this
- matrix = {}
- for k,v in ipairs(arg1) do
- matrix[k] = {}
- if type(v) ~= "table" then v = {} end
- for j,w in ipairs(v) do
- matrix[k][j] = w
- end
- end
- elseif tonumber(arg1) and tonumber(arg2) then --If 2 dimensions provided, fill in with 0s
- matrix = {}
- for i=1,tonumber(arg1) do
- matrix[i] = {}
- for j=1,tonumber(arg2) do
- matrix[i][j] = 0
- end
- end
- elseif tonumber(arg1) then --If only 1 dimension provided, create the identity matrix
- matrix = {}
- for i=1,tonumber(arg1) do
- matrix[i] = {}
- for j=1,tonumber(arg2) do
- if j == 1 then matrix[i][j] = 1 else matrix[i][j] = 0 end
- end
- end
- end
- local m = {matrix=matrix}
- function m:display()
- term.clear()
- term.setCursorPos(1,1)
- local x,y = term.getCursorPos()
- for k,v in ipairs(self.matrix) do
- term.setCursorPos(x,y+k-1)
- for j,w in ipairs(v) do
- term.write(w .. " ")
- end
- end
- end
- function m:transpose(replace)
- local n = {}
- for k,v in ipairs(self.matrix) do
- for j,w in ipairs(v) do
- if not n[j] then n[j] = {} end
- n[j][k] = w
- end
- end
- if replace then self.matrix = n end
- return n
- end
- --Matrix {1,2} {3,4} -> {3,4} {1,2}
- function m:reflectX(replace)
- local n = {}
- for i=1,#self.matrix do
- n[#self.matrix - i + 1] = self.matrix[i]
- end
- if replace then self.matrix = n end
- return n
- end
- function m:reflectY(replace)
- local n = {}
- for i=1,#self.matrix do
- n[i] = {}
- for j=1,#self.matrix[i] do
- n[#self.matrix[i] - j + 1] = self.matrix[i][j]
- end
- end
- if replace then self.matrix = n end
- return n
- end
- function m:rotate(amt,replace)
- amt = math.floor(tonumber(amt) or 1)%4
- local n = {}
- local function transform(x,y,w,h,amt)
- if amt <= 0 then return x,y
- --if amt <= 1 then return y, h - x + 1
- else return transform(y, h-x+1, h, w, amt - 1) end
- end
- for x,v in ipairs(self.matrix) do
- for y,w in ipairs(v) do
- local X,Y = transform(x,y,#v,#self.matrix,amt)
- if not n[X] then n[X] = {} end
- n[X][Y] = w
- end
- end
- if replace then self.matrix = n end
- return n
- end
- function m:mul(other)
- if type(other) ~= "table" then return false end
- if not other.matrix and type(other[1]) ~= "table" then --Case when matrix multiply by vector
- if #other ~= #self.matrix[1] then return false end --Invalid matrix dims
- local res = {}
- for i=1, #self.matrix do
- local sum = 0
- for j = 1, #other do
- sum = sum + other[j] * self.matrix[i][j]
- end
- res[i] = sum
- end
- return res
- end
- if not other.matrix then other = Matrix(other) end --If other is not a matrix, then convert it into one
- if #other.matrix ~= #self.matrix[1] then return false end --Cannot multiply the matrices
- other:transpose(true) --easier to extract vectors from transposed matrix
- local result = {}
- for i=1,#other.matrix do
- result[i] = self:mul(other.matrix[i]) --Multiply by the "vertical" vector of the original other matrix
- end
- result = Matrix(result)
- return result:transpose() --Undoing the transpose
- end
- return m
- end
- --Takes a block and returns a rotated version of itself
- --@Arg Block block: The block to rotate
- --@OptionalArg number amt: The amount to rotate
- --@Returns Block block: The rotated block
- function rotateBlock(block,amt,ref)
- if type(block.bs) ~= "table" then return block end
- if not block.bs.axis and not block.bs.facing and not block.bs.half and not block.bs.type then return block end
- amt = math.floor(tonumber(amt) or 0)%4
- ref = math.floor(tonumber(ref) or 0)%4
- local newBlock = copyBlock(block)
- if block.bs.axis and amt%2 == 1 then
- if block.bs.axis == "x" then newBlock.bs.axis = "z"
- elseif block.bs.axis == "z" then newBlock.bs.axis = "x" end
- end
- if block.bs.facing and facing_tab[block.bs.facing] then
- local newRot = facing_tab[block.bs.facing] + amt
- if (ref == 1 and facing_tab[block.bs.facing]%2 == 1) or (ref == 3 and facing_tab[block.bs.facing]%2 == 0) then newRot = newRot + 2 end
- newBlock.bs.facing = facing_tab[ 1 + newRot%4 ]
- end
- if block.bs.half and ref == 2 then
- if block.bs.half == "bottom" then newBlock.bs.half = "top"
- elseif block.bs.half == "top" then newBlock.bs.half = "bottom" end
- end
- if block.bs.type and ref == 2 then
- if block.bs.type == "bottom" then newBlock.bs.type = "top"
- elseif block.bs.type == "top" then newBlock.bs.type = "bottom" end
- end
- return newBlock
- end
- --Rotates a schematic
- --@Arg Schema schema: The schema to rotate
- --@OptionalArg number amt: The amount to rotate (only in xz plane)
- --@OptionalArg number ref: The coordinate to reflect 0/nil = no reflection, 1= x coordinates reflected, 2=y,3=z
- --@Returns Schema sch: The rotated schematic
- function rotateSchema(schema,amt,ref)
- amt = math.floor(tonumber(amt) or 0)%4
- ref = math.floor(tonumber(ref) or 0)%4
- local sch = {}
- local rotatedBlocks = {}
- local md = readSchemMD()
- for k,v in ipairs(schema) do
- local m = Matrix(v)
- if amt > 0 then m:rotate(amt,true) end
- if ref == 1 then m:reflectX(true)
- elseif ref == 3 then m:reflectY(true) end
- for j,w in ipairs(m.matrix) do --Rotating blocks
- for l,u in ipairs(w) do
- if not rotatedBlocks[u] then
- rotatedBlock = rotateBlock(md[u],amt,ref)
- local key,Block = getOrAddSchemData(rotatedBlock.id,rotatedBlock.bs,rotatedBlock.nbt)
- rotatedBlocks[u] = key
- m.matrix[j][l] = key
- else
- m.matrix[j][l] = rotatedBlocks[u]
- end
- end
- end
- if ref == 2 then
- sch[#schema - k + 1] = m.matrix
- else
- sch[k] = m.matrix
- end
- --TODO: Blockstate reflection and rotation
- end
- return sch
- end
- --Previews a .nbt schematic
- --@Arg Schema schema: The schematic to preview
- --@Returns Schema schema: The schematic that has been modified
- local function previewSchema(schema)
- local yPos = 1
- local md = readSchemMD()
- local maxX,maxY = term.getSize()
- startX = math.floor(maxX/2)+1
- local scns = {}
- local scn = screen.Screen(1,1,maxX,maxY)
- scn:useNewTerm()
- local textBoxes = {
- layer=screen.TextBox(startX, 1, "Layer 1", 8, 1, colors.orange, colors.black),
- itemID = screen.TextBox(startX,5,"ID:",maxX-startX+1,2, colors.black, colors.lime),
- itemBS = screen.TextBox(startX,7,"BS:",maxX-startX+1,maxY - 6, colors.black, colors.green)
- }
- local buttons = {
- upLayer = screen.Button(startX, 2, "Up", 2, 1, colors.black, colors.lightBlue,function() return "up" end,"up"),
- downLayer = screen.Button(startX+3, 2, "Down", 4, 1, colors.black, colors.lightBlue,function() return "down" end, "down"),
- previewScreen = screen.Button(1,1,"",math.floor(maxX/2),maxY,colors.black,colors.black,function() return "preview" end, "preview"),
- quit = screen.Button(startX,3,"Finish",6,1,colors.black,colors.red,function() return "quit" end,"quit"),
- rotate = screen.Button(startX,4,"Rotate",6,1,colors.black,colors.lightBlue,function() return "rotate" end, "rotate"),
- reflect = screen.Button(startX + 7, 4, "Reflect", 7, 1, colors.black,colors.lightBlue,function() return "reflect" end, "reflect"),
- flip = screen.Button(startX + 15, 4, "Flip", 4 , 1, colors.black, colors.lightBlue, function() return "flip" end, "flip")
- }
- scn.buttons,scn.textBoxes = buttons,textBoxes
- scn:useOldTerm()
- for k,v in ipairs(schema) do
- scns[k] = screen.Screen(1,1,math.floor(maxX/2),maxY)
- scns[k]:useNewTerm(colors.white,colors.lightGray)
- term.clear()
- local buttons = {}
- for j,w in ipairs(v) do
- for l,u in ipairs(w) do
- local char = "a"
- local idx = (u-2)%52
- if idx < 26 then char = string.char(65+idx) else char = string.char(97+idx%26) end
- if u > 1 then
- table.insert(buttons,screen.Button(j,#w-l+1,char,1,1,colors.white,colors.brown,function() return "block", u, char end,"block"))
- end
- end
- end
- scns[k].buttons = buttons
- term.clear()
- scns[k]:useOldTerm()
- end
- local current = scns[1]
- scns[1]:render()
- scns[1]:useNewTerm()
- local buttonType,id,char
- while true do
- term.clear()
- current = scns[yPos]
- term.redirect(scn.wndw)
- scn:useNewTerm()
- for k,v in pairs(scn.buttons) do
- if k ~= "previewScreen" then v:render() end
- end
- for k,v in pairs(scn.textBoxes) do
- v:render()
- end
- term.redirect(current.wndw)
- term.clear()
- current:render()
- for k,v in pairs(current.buttons) do
- v:render()
- end
- local button,x,y = scn:getClick()
- if button then buttonType,id,char = button:click() end
- if buttonType == "up" or buttonType == "down" then
- if buttonType == "up" then yPos = yPos + 1 else yPos = yPos - 1 end
- yPos = math.min(#schema,math.max(yPos,1))
- scn.textBoxes.layer.text = string.gsub(scn.textBoxes.layer.text,"%d","") .. yPos
- term.redirect(scn.wndw)
- scn.textBoxes.layer:render()
- scn.textBoxes.itemID.text = "ID:"
- scn.textBoxes.itemBS.text = "BS:"
- scn.textBoxes.itemID:render()
- scn.textBoxes.itemBS:render()
- term.redirect(current.wndw)
- elseif buttonType == "quit" then
- term.redirect(scn.oldTerm)
- term.clear()
- return schema
- elseif buttonType == "rotate" or buttonType == "reflect" or buttonType == "flip" then
- current:render(false)
- term.redirect(scn.oldTerm)
- term.clear()
- scn = nil
- scns = nil
- current = nil
- if buttonType == "rotate" then
- return previewSchema(rotateSchema(schema,1))
- elseif buttonType == "reflect" then
- return previewSchema(rotateSchema(schema,0,1))
- else
- return previewSchema(rotateSchema(schema,0,2))
- end
- else
- local button,x,y = current:getClick(x,y)
- if button then buttonType,id,char = button:click() end
- if buttonType == "block" then
- scn.textBoxes.itemID.text = "ID (" .. char .. "):" .. md[id].id
- local bsText = ""
- for k,v in pairs(md[id].bs or {}) do
- bsText = bsText .. " " .. (v or "")
- end
- scn.textBoxes.itemBS.text = "BS (" .. char .. "):" .. bsText
- term.redirect(scn.wndw)
- scn.textBoxes.itemID:render()
- scn.textBoxes.itemBS:render()
- term.redirect(current.wndw)
- end
- end
- end
- end
- function main()
- local schema = loadSchem()
- if not schema then return false end
- schema = previewSchema(schema)
- if not printSchema(schema) then print("Please ensure the schem turtle is on a valid inventory to begin printing the schematic") end
- end
Add Comment
Please, Sign In to add comment