t8rt0t

schemAPI.lua

Mar 30th, 2024 (edited)
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 45.18 KB | None | 0 0
  1. if not docs then os.loadAPI("apis/docs.lua") end
  2. if not turt then os.loadAPI("apis/turt.lua") end
  3. if not refuel then os.loadAPI("apis/refuel.lua") end
  4. if not encryption then os.loadAPI("apis/encryption.lua") end
  5. if not screen then os.loadAPI("apis/screen.lua") end
  6. --if not require then os.loadAPI("rom/modules/main/cc/require.lua") end
  7. --Type registry
  8. local types = {
  9.     ["Blockstate"]={colors.lightBlue,"A table with blockstate data, such as {facing=\"up\"}"},
  10.     ["Nbt"]={colors.lightBlue,"A table with nbt data. Currently unused"},
  11.     ["Block"]={colors.brown,"A minecraft block, with id, nbt, and blockstate"},
  12.     ["Schema"]={colors.orange,"A 3D array of numbers, each representing schematic data. Indexed by Schema[y][x][z]"},
  13.     ["SchematicTurtle"]={colors.brown,"dumb turtle thing"}
  14. }
  15. for k,v in pairs(types) do
  16.     docs.registerType(k,v[1],v[2])
  17. end
  18. VALID_BLOCK_STATES = {
  19.     facing={"up","down","north","east","west","south"},
  20.     half={"top","bottom"},
  21.     type={"top","bottom","double"},
  22.     axis={"x","y","z"},
  23.     open={"true","false"}
  24. }
  25. NBT_TAGS = {
  26.     [0]="TAG_End", [1]="TAG_Byte", [2]="TAG_Short", [3]="TAG_Int", [4]="TAG_Long", [5]="TAG_Float", [6]="TAG_Double",
  27.     [7]="TAG_Byte_Array", [8]="TAG_String", [9]="TAG_List", [10]="TAG_Compound", [11]="TAG_Int_Array", [12]="TAG_Long_Array"
  28. }
  29. facing_tab = {"north","east","south","west",north=0,east=1,south=2,west=3}
  30. --Default .schema values
  31. --0x0000 = y++
  32. --0x0001 = x++
  33. --0x0002 = {id="minecraft:air"}
  34.  
  35. --Takes blockstate tables and turns them into validated blockstate tables (only blockstates that are allowed)
  36. --@Arg Blockstate blockstate: The blockstate to be validated
  37. --@Returns Blockstate bs: The blockstate with only valid blockstates included
  38. --@Returns None nil: No blockstate provided
  39. local function validateBlockstate(blockstate)
  40.     if type(blockstate) ~= "table" then return end
  41.     local bs = {}
  42.     for k,v in pairs(blockstate) do
  43.         local validStates = VALID_BLOCK_STATES[k]
  44.         if validStates then
  45.             for j,w in pairs(validStates) do
  46.                 if w == v then bs[k] = v end
  47.             end
  48.         end
  49.     end
  50.     return bs
  51. end
  52. --TODO: If I manage to get nbt working, make this do something instead of always returning nil
  53. --@Arg Nbt nbt: The nbt to be validated
  54. --@Returns Nbt valid_nbt: the validated nbt
  55. --@Returns None nil: There was no nbt provided
  56. local function validateNbt(nbt)
  57. end
  58. --Creates a new block with id, blockstate, and nbt
  59. --@Arg string id: The registry name of the block
  60. --@OptionalArg Blockstate blockstate: the blockstate of the specific block
  61. --@OptionalArg Nbt nbt: The nbt of the block (unused)
  62. --@Returns Block block: The completed block
  63. function newBlock(id,blockstate,nbt)
  64.     blockstate = validateBlockstate(blockstate)
  65.     nbt = validateNbt(nbt)
  66.     local block = {}
  67.     block.id = id
  68.     if blockstate then block.bs = blockstate end
  69.     if nbt then block.nbt = nbt end
  70.     return block
  71. end
  72.  
  73. function copyTab(tab)
  74.     if type(tab) ~= "table" then return tab end
  75.     local newTab = {}
  76.     for k,v in pairs(tab) do
  77.         newTab[k] = copyTab(v)
  78.     end
  79.     return newTab
  80. end
  81.        
  82. --Copies a block
  83. function copyBlock(block)
  84.     local newBlock = {}
  85.     newBlock.id = block.id
  86.     newBlock.bs = copyTab(block.bs)
  87.     newBlock.nbt = copyTab(block.nbt)
  88.     return newBlock
  89. end
  90. --Generates a a table that can turn the bytes into a table of values
  91. --@Returns table metadata: {[integer] = {id="",blockstate={}}
  92. function readSchemMD()
  93.     if not fs.exists(".schematic_data.json") then return {[1]=newBlock("minecraft:air")} end
  94.     local file = fs.open(".schematic_data.json","r")
  95.     local data = textutils.unserialiseJSON(file.readAll())
  96.     if type(data) ~= "table" then data = {} end
  97.     data[1] = newBlock("minecraft:air")
  98.     return data
  99. end
  100. --Adds schematic data to .schematic_data.json
  101. --@Arg Block block: The block to be added
  102. local function addSchemData(block)
  103.     local md = readSchemMD()
  104.     table.insert(md,block)
  105.     local file = fs.open(".schematic_data.json","w+")
  106.     file.write(textutils.serialiseJSON(md))
  107.     file.close()
  108. end
  109. --Checks if two blockstates are equal
  110. --@Arg Blockstate bs1: The first blockstate to be compared
  111. --@Arg Blockstate bs2: The second blockstate to be compared
  112. --@Returns boolean equal: If the two blockstates are equal
  113. local function compareBlockstate(bs1, bs2)
  114.     if bs1 == bs2 then return true end
  115.     bs1 = bs1 or {}
  116.     bs2 = bs2 or {}
  117.     for k,v in pairs(bs1) do
  118.         if v ~= bs2[k] then return false end
  119.     end
  120.     for k,v in pairs(bs2) do
  121.         if v ~= bs1[k] then return false end
  122.     end
  123.     return true
  124. end
  125. --Checks if two blocks are equal
  126. --@Arg Block block1: The first block to be compared
  127. --@Arg Block block2: The second block to be compared
  128. --@Returns boolean equal: If the two blocks are equal
  129. local function compareBlock(block1, block2)
  130.     if block1.id ~= block2.id then return false end
  131.     return compareBlockstate(block1.bs,block2.bs) and compareBlockstate(block1.nbt,block2.nbt)
  132. end
  133. --Gets the schem data for a block, or adds it to the data
  134. --@Arg string id: the id of the block to add
  135. --@OptionalArg Blockstate blockstate: The specific blockstate to get.
  136. --@Returns number blockCode,Block block: The index of the block in the palette, and the block itself
  137. local function getOrAddSchemData(id,blockstate,nbt)
  138.     local md = readSchemMD()
  139.     local block = newBlock(id,blockstate,nbt)
  140.     for k,v in pairs(md) do
  141.         if compareBlock(v,block) then return k,v end
  142.     end
  143.     addSchemData(block)
  144.     return getOrAddSchemData(id,blockstate,nbt)
  145. end
  146. --Turns a series of bytes into a number, in big Endian
  147. --@Args number bytes: A series of bytes from the schema
  148. --@Returns number index: The index number of the byte in the schema metadata
  149. local function schemaByteToNumber(...)
  150.     local args = {...}
  151.     local index = 0
  152.     for i,v in ipairs(args) do
  153.         index = 256*index+tonumber(v)
  154.     end
  155.     return index - 1
  156. end
  157. --Turns a series of bytes into a signed number, big endian
  158. --@Args number bytes: A series of bytes
  159. --@Returns number num: The signed number from the bytes
  160. local function bytesToSignedNumber(...)
  161.     local args = {...}
  162.     local num = 0
  163.     for i,v in ipairs(args) do
  164.         num = 256*num+tonumber(v)
  165.     end
  166.     local max_value = 256^(#args)
  167.     if num >= max_value/2 then num = num - max_value end
  168.     return num
  169. end
  170. --Turns a series of bytes into a floating point number
  171. --@Args number bytes: A series of bytes
  172. --@Returns number fp: A floating point number
  173. local function bytesToFloatingPoint(...)
  174.     local args = {...}
  175.     local double = false
  176.     if #args >= 8 then double = true end
  177.     local sign = (-1)^math.floor(args[1]/128)
  178.     local exponent = args[1]%128
  179.     local mantissa = 0
  180.     local tempMantissa = 0
  181.     local count = -1
  182.     if double then
  183.         exponent = exponent*16+math.floor(args[2]/16)
  184.         if exponent > 0 then mantissa = 1 end --Weird fp stuff idk tbh
  185.         exponent = exponent - 1023
  186.         if exponent > 1024 then print("Floating point should be infinity, this might break stuff") end
  187.         tempMantissa = args[2]%16
  188.         for i=3,#args do
  189.             tempMantissa = 256*tempMantissa+args[i]
  190.         end
  191.     else
  192.         exponent = exponent*2+math.floor(args[2]/128)
  193.         if exponent > 0 then mantissa = 1 end --Weird fp thing
  194.         exponent = exponent - 127
  195.         if exponent > 128 then print("Floating point should be infinity, this might break stuff") end
  196.         tempMantissa = args[2]%128
  197.         for i=3,#args do
  198.             tempMantissa = 256*tempMantissa+args[i]
  199.         end
  200.     end
  201.     local resolution = 23
  202.     if double then resolution = 53 end
  203.     mantissa = mantissa+tempMantissa/(2^resolution)
  204.     return sign*math.ldexp(mantissa,exponent),exponent,mantissa
  205. end
  206. --Turns a series of bytes into a block
  207. --@Arg number index: The index of the schema metadata
  208. --@Returns Block block: The block corresponding to the bytes
  209. --@Returns None nil: If no block was found
  210. local function numberToBlock(index)
  211.     local md = readSchemMD()
  212.     if md[index] then return md[index] end
  213. end
  214. --Turns a index number into a set of schema bytes
  215. --@Arg number index: The index to convert into bytes
  216. --@OptionalArg number byteCount: The number of bytes to converr the data into
  217. --@Returns table bytes: A list of the bytes
  218. local function numberToSchemaBytes(index,byteCount)
  219.     local bytes = {}
  220.     if not tonumber(index) then return end
  221.     index = tonumber(index)+1
  222.     table.insert(bytes,index%256)
  223.     index = math.floor(index/256)
  224.     while index > 0 do
  225.         table.insert(bytes,1,index%256)
  226.         index = math.floor(index/256)
  227.     end
  228.     byteCount = tonumber(byteCount) or #bytes
  229.     while #bytes < byteCount do
  230.         table.insert(bytes,1,0)
  231.     end
  232.     return bytes  
  233. end
  234. --Reads a .schema file, converting it into a table of numbers
  235. --@Arg string path: the absolute path to the file
  236. --@Returns Schema schema, number x, number y, number z: the completed schematic of the item, and its dimensions
  237. --@Returns None nil: If the schema could not be completed
  238. local function readSchema(path)
  239.     if not fs.exists(path) then return end
  240.     local md = readSchemMD()
  241.     local file = fs.open(path,"rb")
  242.     local schema = {}
  243.     local row = {}
  244.     local col = {}
  245.     local x = 0 --how wide in x
  246.     local y = 0 --how wide in y
  247.     local z = 0 --how wide in z
  248.     local dataWidth = file.read()
  249.     while file.read(0) do
  250.         local bytes = {}
  251.         for i=1,dataWidth do
  252.             table.insert(bytes,file.read() or 0)
  253.         end
  254.         local idx = schemaByteToNumber(unpack(bytes))
  255.         if idx == -1 then
  256.             if #col > 0 then
  257.                 table.insert(row,col)
  258.             end
  259.             z = math.max(z,#col)
  260.             x = math.max(x,#row)
  261.             table.insert(schema,row)
  262.             row = {}
  263.             col = {}
  264.         elseif idx == 0 then
  265.             table.insert(row,col)
  266.             z = math.max(z,#col)
  267.             col = {}
  268.         else
  269.             if not md[idx] then
  270.                 print("Invalid block metadata found")
  271.                 return
  272.             end
  273.             table.insert(col,idx)
  274.         end
  275.     end
  276.     if #col > 0 then table.insert(row,col) end
  277.     if #row > 0 and #row[1] > 0 then table.insert(schema,row) end
  278.     local y = #schema
  279.     return schema,x,y,z
  280. end
  281. --Saves a Schema to the path
  282. --@Arg string path: The path that the schema should be saved to
  283. --@Arg Schema schema: The schema to be saved
  284. --@Arg number x: The width of the schema
  285. --@Arg number y: The height of the schema
  286. --@Arg number z: The depth of the schema
  287. local function saveSchema(path,schema,x,y,z)
  288.     if fs.exists(path) then fs.delete(path) end
  289.     local md = readSchemMD()
  290.     local dataWidth = math.floor(math.log(#md)/math.log(256))+1 --Change of base formula
  291.     local file = fs.open(path,"w+b")
  292.     file.write(dataWidth)
  293.     for i=1,y do
  294.         if type(schema[i]) ~= "table" then schema[i] = {} end
  295.         for j=1,x do
  296.             if type(schema[i][j]) ~= "table" then schema[i][j] = {} end
  297.             for k=1,z do
  298.                 local bytes = numberToSchemaBytes(schema[i][j][k],dataWidth)
  299.                 for l=1,dataWidth do
  300.                     if type(bytes) == "table" and tonumber(bytes[l]) then file.write(bytes[l])
  301.                     else file.write(2) end --Writing down air if schema value not present
  302.                 end
  303.             end
  304.             file.write(1)
  305.         end
  306.         file.write(0)
  307.     end
  308.     file.close()
  309. end              
  310. --Recursively reads a nbt tag
  311. --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
  312. --@Arg File file: The file handle to be read from, in rb mode
  313. --@OptionalArg number typeID: The nbt data type
  314. --@Returns Nbt nbt: The completed nbt tag
  315. local function readTag(file,typeID)
  316.     typeID = typeID or 10
  317.     --Any signed, whole number
  318.     if typeID == 1 or typeID == 2 or typeID == 3 or typeID == 4 then
  319.         len = 2^(typeID-1) --Number of bytes of the number
  320.         local bytes = {}
  321.         for i=1,len do
  322.             table.insert(bytes,file.read())
  323.         end
  324.         return bytesToSignedNumber(unpack(bytes))
  325.     end
  326.     --The floating points, floats and doubles
  327.     if typeID == 5 or typeID == 6 then
  328.         len = 4
  329.         if typeID == 6 then len = 8 end
  330.         local bytes = {}
  331.         for i=1,len do
  332.             table.insert(bytes,file.read())
  333.         end
  334.         return bytesToFloatingPoint(unpack(bytes))
  335.     end
  336.     --String, which is prefixed with a 2 bit unsigned short determining the length
  337.     if typeID == 8 then
  338.         length = file.read()
  339.         length = length * 256 + file.read() --Reading the prefix short
  340.         return tostring(file.read(length))
  341.     end
  342.     --The arrays, which are prefixed with a signed integer for their length
  343.     if typeID == 7 or typeID == 11 or typeID == 12 then
  344.         local len = 1
  345.         if typeID == 11 then len = 4
  346.         elseif typeID == 12 then len = 8 end
  347.         local arr = {}
  348.         local length = readTag(file,3) --Gets signed integer length
  349.         for i=1,length do
  350.             local data = {}
  351.             for j=1,len do
  352.                 table.insert(data,file.read())
  353.             end
  354.             table.insert(arr,bytesToSignedNumber(unpack(data)))
  355.         end
  356.         return arr
  357.     end
  358.     --The lists, which are prefixed with a single byte for their elements' type, and then a signed integer for the length
  359.     if typeID == 9 then
  360.         local listType = file.read()
  361.         local length = readTag(file,3) --Gets signed integer length
  362.         local list = {}
  363.         for i=1,length do
  364.             table.insert(list,readTag(file,listType))
  365.         end
  366.         return list
  367.     end
  368.     --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)
  369.     if typeID == 10 then
  370.         local t = {}
  371.         local compoundType = file.read()
  372.         while compoundType and compoundType > 0 do
  373.             local name = readTag(file,8) --Gets the string name
  374.             t[name] = readTag(file,compoundType)
  375.             compoundType = file.read()
  376.         end
  377.         return t
  378.     end
  379.     return
  380. end    
  381. --Turns a .nbt file into a table
  382. --@Arg string path: the absolute path to the nbt
  383. --@Returns Nbt nbt: the data read from the nbt files
  384. --@Returns boolean false: If there was an error reading the nbt
  385. function readNBT(path)
  386.     if not fs.exists(path) then return false end
  387.     local file = fs.open(path,"rb")
  388.     local data = readTag(file)
  389.     file.close()
  390.     return data
  391. end
  392. --Converts NBT data into Schema, while registering the unrecognized blocks
  393. --@Arg Nbt nbt: the nbt data from readNBT()
  394. --@Returns Schema schem, number x, number y, number z: The loaded schematic and its dimensions
  395. --@Returns boolean false,string errMsg: If the nbt failed
  396. function serialiseNBTData(nbt)
  397.     if type(nbt) ~= "table" then return false, "invalid input nbt" end
  398.     nbt = nbt[""] --Dumb implied compoundtag fuckery
  399.     if type(nbt) ~= "table" then return false, "nbt has no implied compoundTag, or it could not be found" end
  400.     local x,y,z
  401.     if type(nbt.size) == "table" then
  402.         x,y,z = nbt.size[1], nbt.size[2], nbt.size[3]
  403.     else
  404.         return false, "Nbt did not have properly defined dimensions"
  405.     end
  406.     local schema = {}
  407.     local palette = nbt.palette
  408.     if type(palette) ~= "table" then return false, "No palette was provided for the nbt" end
  409.     local blocks = nbt.blocks
  410.     if type(blocks) ~= "table" then return false, "No blocks were provided for the nbt" end
  411.     for k,v in pairs(blocks) do
  412.         local pos = v.pos
  413.         if not pos then return false, "Block position was undefined" end
  414.         local state = v.state+1
  415.         if not palette[state] then return false, "Invalid blockstate, not defined by palette" end
  416.         local id,bs = palette[state].Name, palette[state].Properties
  417.         local nbtTag = v.nbt
  418.         local mdKey,block = getOrAddSchemData(id,bs,nbtTag)
  419.         local iX,iY,iZ = unpack(pos)
  420.         if type(schema[iY+1]) ~= "table" then schema[iY+1] = {} end
  421.         if type(schema[iY+1][iX+1]) ~= "table" then schema[iY+1][iX+1] = {} end
  422.         schema[iY+1][iX+1][iZ+1] = mdKey
  423.     end
  424.     if type(nbt.entities) == "table" and #nbt.entities > 1 then
  425.         print("Entities detected within schematic, which will be ignored by the turtle")
  426.     end
  427.     for i=1,y do
  428.         for j=1,x do
  429.             for k=1,z do
  430.                 if not schema[i] then schema[i] = {} end
  431.                 if not schema[i][j] then schema[i][j] = {} end
  432.                 if not schema[i][j][k] then schema[i][j][k] = 1 end
  433.             end
  434.         end
  435.     end
  436.     return schema,x,y,z
  437. end
  438. --Prints an binary file in it's raw form for easy viewing
  439. --@Arg string path: The absolute path to the file
  440. --@OptionalArg Color color1: The first background color, for easy viewing
  441. --@OptionalArg Color color2: The second background color
  442. function printBinary(path,color1,color2)
  443.     if not fs.exists(path) then return end
  444.     color1 = color1 or colors.white
  445.     color2 = color2 or colors.lightGray
  446.     local file = fs.open(path,"rb")
  447.     local byte = file.read()
  448.     term.clear()
  449.     term.setCursorPos(1,1)
  450.     term.setTextColor(colors.black)
  451.     term.setBackgroundColor(colors.black)
  452.     while byte do
  453.         local x,y = term.getCursorPos()
  454.         local maxX, maxY = term.getSize()
  455.         if x >= maxX then
  456.             term.setCursorPos(1,y+1)
  457.         end
  458.         x,y = term.getCursorPos()
  459.         if math.floor((x-1)/2)%2 == 0 then term.setBackgroundColor(color1) else term.setBackgroundColor(color2) end
  460.         term.write(string.format("%02x",byte))
  461.         byte = file.read()
  462.     end
  463.     term.setBackgroundColor(colors.black)
  464.     term.setTextColor(colors.white)
  465.     file.close()
  466.     term.setTextColor(colors.white)
  467. end
  468. --Loads a schem inside the schematics folder
  469. --If it is not existing as a schema, the program converts it to a schema
  470. --@OptionalArg string schem: The name of the schem within the schematics folder
  471. --@Returns Schema schema, number x, number y, number z: The loaded schematic, and its dimensions
  472. --@Returns boolean false: If schematic loading failed
  473. function loadSchem(schem)
  474.     local filepath,fileType = nil
  475.     if type(schem) ~= "string" then
  476.         filepath = encryption.selectFile("schematics")
  477.         if filepath then
  478.             fileType = string.match(filepath,"%.%w+$")
  479.             schem = string.gsub(string.gsub(filepath,"%w+/",""),"%.%w+","")
  480.             --schem = string.sub(string.gsub(string.match(filepath,"/%w+%.%w+$"),fileType,""),2,-1)
  481.         end
  482.     end
  483.     if not schem then return false, "No valid path provided" end
  484.     --Case schema already exists
  485.     if ( fileType == ".schema" ) or (not fileType and type(schem) == "string" and fs.exists("schematics/"..schem ..".schema")) then
  486.         local schema,x,y,z = readSchema(filepath or "schematics/" .. schem .. ".schema")
  487.         if not schema then return false, "Reading .schema failed" end
  488.         return schema,x,y,z
  489.     elseif ( fileType == ".uncompressedNBT" ) or (not fileType and type(schem) == "string" and fs.exists(filepath or "schematics/"..schem .. ".uncompressedNBT")) then
  490.         local schema,x,y,z = serialiseNBTData(readNBT(filepath or "schematics/"..schem .. ".uncompressedNBT"))
  491.         if not schema then
  492.             print(x)
  493.             return false, "Serializing .uncompressedNBT failed"
  494.         end
  495.         saveSchema("schematics/"..schem .. ".schema", schema, x,y,z)
  496.         return schema,x,y,z
  497.     elseif ( fileType == ".nbt" ) or (not fileType and type(schem) == "string" and fs.exists(filepath or "schematics/"..schem .. ".nbt")) then
  498.         print("Attempting to load .nbt file, make sure that it is uncompressed!")
  499.         --LUA_PATH = "/apis/?.lua"
  500.         --local zzlib = req("libs.zzlib")
  501.         --local zzlib = shell.run("apis/libs/zzlib.lua")
  502.         local zzlib = dofile("apis/libs/zzlib.lua")
  503.         local file = fs.open(filepath or "schematics/"..schem..".nbt","r")
  504.         local data = zzlib.gunzip(file.readAll())
  505.         file.close()
  506.         local file = fs.open("schematics/"..schem..".uncompressedNBT","w+")
  507.         file.write(data)
  508.         file.close()
  509.         fs.delete(filepath or "schematics/"..schem..".nbt")
  510.         local schema,x,y,z = serialiseNBTData(readNBT("schematics/"..schem .. ".uncompressedNBT"))
  511.         if not schema then
  512.             print(x)
  513.             return false, "reading uncompressed .nbt from compressed nbt failed"
  514.         end
  515.         saveSchema("schematics/"..schem .. ".schema", schema, x,y,z)
  516.         return schema,x,y,z
  517.     end
  518.     return false, "no schem found"
  519. end
  520. --Prints information about the api
  521. function printREADME()
  522.     print("This api will load and place schematics")
  523.     print("Currently, it only supports uncompressed .nbt files and the native .schema")
  524.     print()
  525.     print("To upload a .nbt, first uncompress the nbt schematic on your own computer with an archive manager")
  526.     print("Then drag and drop the uncompressed file onto the computer's home screen to upload it")
  527.     print("Make sure to move the file to the /schematics/ folder in your computer!")
  528.     print()
  529.     print("The .schema file is a easy-to-read schematic, but it only works on the computer it was created on")
  530.     print("The data is converted into numbers, which correspond to keys inside the .schematic_data.json file")
  531.     print("The first byte of the .schema file determines the length of each data value")
  532.     print("The rest of the data is a list of a series of bytes (whose length is determined by the first byte)")
  533.     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")
  534.     print("Otherwise, the values are block data")
  535. end
  536. --This generally relies on block ids matching their corresponding item ids
  537. --@Arg Schema schema: The schema used
  538. --@Returns table blocklist: A list of {[string blockId]=number count}
  539. function getBlockList(schema)
  540.     local blockList = {}
  541.     local md = readSchemMD()
  542.     for k,v in pairs(schema) do
  543.         for j,w in pairs(v) do
  544.             for l,u in pairs(w) do
  545.                 if u > 1 then
  546.                     local id = md[u].id
  547.                     if not tonumber(blockList[id]) then blockList[id] = 1 else blockList[id] = blockList[id] + 1 end
  548.                     if type(md[u].bs) == "table" and #md[u].bs >= 1 then
  549.                         print("BlockState is currently not supported, ignoring it now!")
  550.                     end
  551.                 end
  552.             end
  553.         end
  554.     end
  555.     return blockList
  556. end
  557.  
  558. local function addItem(blockList,item)
  559.     for i=1,16 do
  560.         if not blockList[i] or blockList[i].count <= 0 then
  561.             blockList[i] = {count=1,id=item}
  562.             return true
  563.         elseif blockList[i].id == item and blockList[i].count < 64 then
  564.             blockList[i].count = blockList[i].count + 1
  565.             return true
  566.         end
  567.     end
  568.     return false
  569. end
  570. --Gets a list of blocks needed for the schema
  571. --@Args Schema schema: The schema being used
  572. --@Returns table blockList: A list of the next 16 types of blocks to use
  573. local function getNeededBlocks(schema)
  574.     local blockList = {}
  575.     local md = readSchemMD()
  576.     local count = 0
  577.     for k,v in pairs(schema) do
  578.         for j,w in pairs(v) do
  579.             for l,u in pairs(w) do
  580.                 if u > 1 then
  581.                     if not addItem(blockList,md[u].id) then return blockList end
  582.                 end
  583.             end
  584.         end
  585.     end
  586.     return blockList
  587. end          
  588. --Selects the item corresponding to the block
  589. --@Arg Block block: The block to select
  590. --@Returns boolean success: Whether the block could be selected or not
  591. local function selectBlock(block)
  592.     local id = block.id
  593.     local slot = refuel.findItem(id)
  594.     if not slot then return false end
  595.     turtle.select(slot)
  596.     return true
  597. end
  598. --Places a block below the turtle
  599. --@Arg Block block: The block to place, with blockstate and nbt (though unused)
  600. --@Returns boolean success: Whether the block was placed or not
  601. local function placeBlock(block)
  602.     if not selectBlock(block) then return false end
  603.     turt.digDown()
  604.     turt.placeDown()
  605.     --TODO: Blockstate [+ nbt?] placements
  606.     return true
  607. end
  608. --Pulls an item from an inventory below it
  609. --@Arg string id: The id of the item to pull
  610. --@OptionalArg number amount: The number of items to pull, from 1-64
  611. --@Returns boolean success: If the items were taken from the chest
  612. local function pullItemFromChest(id,amount)
  613.     amount = math.max(math.min(math.floor(tonumber(amount) or 64),64),1)
  614.     local chest = peripheral.wrap("bottom")
  615.     if not chest then return false end
  616.     local freeSlot = nil
  617.     local targetSlot = nil
  618.     for i=1,chest.size() do
  619.         local item = chest.getItemDetail(i)
  620.         if not item then freeSlot = i
  621.         elseif item.name == id then targetSlot = i end
  622.     end
  623.     if turt.getFreeSpace(id) < amount then return false end --no free slots to put items in
  624.     if not targetSlot then return false end
  625.     if targetSlot == 1 then return turtle.suckDown(amount) end
  626.     if not freeSlot then
  627.         local tempItem = chest.getItemDetail(1)
  628.         if tempItem.count > 64 then return false end --Dont want to tell with sophisticated backpacks with 2 billion items in a slot
  629.         local turtSlot = turt.getFreeSlot()
  630.         turtle.suckDown(64)
  631.         chest.pullItems(peripheral.getName(chest),targetSlot,chest.getItemLimit(targetSlot),1)
  632.         turt.dropDown(turtSlot)
  633.         return turtle.suck(amount)
  634.     else
  635.         chest.pullItems(peripheral.getName(chest),1,chest.getItemLimit(1),freeSlot)
  636.         chest.pullItems(peripheral.getName(chest),targetSlot,chest.getItemLimit(targetSlot),1)
  637.         return turtle.suck(amount)
  638.     end
  639. end
  640.  
  641. --Creates a new schematic turtle (st)
  642. --@Arg Schema schema: The schema for the turtle
  643. --@OptionalArg number x: The x coordinate of the turtle (and its home position)
  644. --@OptionalArg number y: The y coordinate of the turtle
  645. --@OptionalArg number z: The z coordinate of the turtle
  646. --@OptionalArg number rot: The rotation of the turtle from what its reference frame should be
  647. --@Returns SchematicTurtle st: The schematic turtle
  648. function SchematicTurtle(schema,x,y,z,rot)
  649.     local st = {
  650.         x = math.floor(tonumber(x) or 0),
  651.         y = math.floor(tonumber(y) or 0),
  652.         z = math.floor(tonumber(z) or 0),
  653.         rot = math.floor(tonumber(rot) or 0)%4,
  654.         schema = schema
  655.     }
  656.     st.hx,st.hy,st.hz = st.x,st.y,st.z
  657.     function st:rotate(rot)
  658.         local delRot = (self.rot-rot)%4
  659.         if delRot == 3 then
  660.             turt.turnLeft()
  661.             self.rot = (self.rot - 1)%4
  662.         else
  663.             turt.turnRight(delRot)
  664.             self.rot = (self.rot + delRot)%4
  665.         end
  666.     end
  667.     function st:moveX(amt)
  668.         if amt > 0 then self:rotate(1) else self:rotate(3) end
  669.         for i=1,math.abs(amt) do
  670.             turt.dig()
  671.             turt.forward()
  672.         end
  673.         self.x = self.x+amt
  674.     end
  675.     function st:moveY(amt)
  676.         local f = function() turt.digUp() turt.up() end
  677.         if amt < 0 then f = function() turt.digDown() turt.down() end end
  678.         for i=1,math.abs(amt) do
  679.             f()
  680.         end
  681.         self.y = self.y+amt
  682.     end
  683.     function st:moveZ(amt)
  684.         if amt > 0 then self:rotate(0) else self:rotate(2) end
  685.         for i=1,math.abs(amt) do
  686.             turt.dig()
  687.             turt.forward()
  688.         end
  689.         self.z = self.z+amt
  690.     end
  691.     --Move along straight axis
  692.     function st:move(dir,amt)
  693.         local f = function() turt.dig() turt.forward() end
  694.         if dir == 2 then f = function() turt.digUp() turt.up() end
  695.             self.y = self.y + amt
  696.         elseif dir == -2 then f = function() turt.digDown() turt.down() end
  697.             self.y = self.y - amt
  698.         elseif dir == 3 then --forward -> rot = 0
  699.             self:rotate(0)
  700.             self.z = self.z + amt
  701.         elseif dir == -3 then
  702.             self:rotate(2)
  703.             self.z = self.z - amt
  704.         elseif dir == 1 then
  705.             self:rotate(1)
  706.             self.x = self.x + amt
  707.         elseif dir == -1 then
  708.             self:rotate(3)
  709.             self.x = self.x - amt
  710.         end
  711.         for i=1,amt do
  712.             f()
  713.         end
  714.     end
  715.     --Go to x,y,z coord
  716.     --Order is the order you should go in, number 0-8
  717.     -- order//3 tells you the first axis [x,y,z] to travel along
  718.     -- order%3 tells you the second axis [x,y,z] to travel along, after you finish the first
  719.     -- The last axis is chosen by process of elimination
  720.     -- Convoluted fckery
  721.     function st:goToPos(x,y,z,order)
  722.         cPos = {[0]=self.x,[1]=self.y,[2]=self.z}
  723.         tPos = {[0]=x,[1]=y,[2]=z}
  724.         order = math.min(math.max(math.floor(tonumber(order) or 3),0),8)
  725.         local firstOrder = math.floor(order/3)
  726.         local secondOrder = order%3
  727.         local thirdOrder = 3-firstOrder-secondOrder
  728.         -- for k,v in pairs({firstOrder,secondOrder,thirdOrder}) do
  729.         --     local amt = tPos[v]-cPos[v]
  730.         --     if amt ~= 0 then
  731.         --         self:move((v+1)*amt/math.abs(amt),math.abs(amt))
  732.         --     end
  733.         -- end
  734.         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
  735.         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
  736.         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
  737.     end
  738.     function st:goHome() --ET phone home
  739.         self:goToPos(self.hx,self.hy,self.hz,2) --order z x y
  740.     end
  741.     function st:pickUpItems()
  742.         local oldX,oldY,oldZ = self.x,self.y,self.z
  743.         self:goHome()
  744.         for i=1,16 do
  745.             turt.dropDown()
  746.         end
  747.         local blockList = getNeededBlocks(self.schema)
  748.         for k,v in pairs(blockList) do
  749.             if v then
  750.                 while not pullItemFromChest(v.id,v.count) do
  751.                     sleep(1)
  752.                     term.setCursorPos(1,1)
  753.                     term.setTextColor(colors.red)
  754.                     term.write(string.format("Missing %d of %s",v.count,v.id))
  755.                 end
  756.                 term.clear()
  757.                 term.setTextColor(colors.white)
  758.             end
  759.         end
  760.         self:goToPos(oldX,oldY,oldZ)
  761.     end
  762.     --Places a block below the turtle
  763.     --@Arg Block block: The block to place, with blockstate and nbt (though unused)
  764.     --@Returns boolean success: Whether the block was placed or not
  765.     function st:placeBlock(block)
  766.         if not selectBlock(block) then return false end
  767.         if block.bs and block.bs.facing and facing_tab[block.bs.facing] then
  768.             local dir = facing_tab[block.bs.facing] + 2
  769.             local oldDir = self.rot
  770.             self:rotate(dir)
  771.             turt.digDown()
  772.             turt.placeDown()
  773.             self:rotate(oldDir)
  774.         else
  775.             turt.digDown()
  776.             turt.placeDown()
  777.         end
  778.         --TODO: Blockstate [+ nbt?] placements
  779.         return true
  780.     end
  781.     return st
  782. end
  783. --Prints a schema
  784. --@Arg Schema schema: The schematic to be loaded
  785. function printSchema(schema)
  786.     local st
  787.     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
  788.         local neededItems = getBlockList(schema)
  789.         for i=1,16 do
  790.             local item = turtle.getItemDetail(i)
  791.             if item and neededItems[item.name] then
  792.                 neededItems[item.name] = neededItems[item.name] - item.count
  793.                 if neededItems[item.name] <= 0 then neededItems[item.name] = nil end
  794.             end
  795.         end
  796.         local hasNeededItems = true
  797.         for k,v in pairs(neededItems) do
  798.             if tonumber(v) and v > 0 then hasNeededItems = false end
  799.         end
  800.         if not hasNeededItems then
  801.             print(textutils.serialise(neededItems,{compact=true}))
  802.             return false
  803.         end
  804.         st = SchematicTurtle(schema,1,0,0,2)
  805.     else
  806.         st = SchematicTurtle(schema,1,1,0,2)
  807.         st:pickUpItems()
  808.     end
  809.     local md = readSchemMD()
  810.     for k,v in ipairs(schema) do
  811.         for j,w in ipairs(v) do
  812.             for l,u in ipairs(w) do
  813.                 if u > 1 then
  814.                     st:goToPos(j,k,l)
  815.                     while not st:placeBlock(md[u]) do
  816.                         st:pickUpItems()
  817.                     end
  818.                     schema[k][j][l] = 0
  819.                 end
  820.             end
  821.         end
  822.     end
  823.     return true
  824. end
  825. --Constructs a 2d matrix
  826. --@OptionalArg table arg1: The 2d table to construct off of, or the width of the matrix
  827. --@OptionalArg number arg2: The height of the matrix
  828. --@Returns Matrix matrix: The constructed matrix
  829. function Matrix(arg1,arg2)
  830.     local matrix = { {1,0},{0,1} } --Default matrix is I2
  831.     if type(arg1) == "table" and type(arg1[1]) == "table" then --If 2d table provided, use this
  832.         matrix = {}
  833.         for k,v in ipairs(arg1) do
  834.             matrix[k] = {}
  835.             if type(v) ~= "table" then v = {} end
  836.             for j,w in ipairs(v) do
  837.                 matrix[k][j] = w
  838.             end
  839.         end
  840.     elseif tonumber(arg1) and tonumber(arg2) then --If 2 dimensions provided, fill in with 0s
  841.         matrix = {}
  842.         for i=1,tonumber(arg1) do
  843.             matrix[i] = {}
  844.             for j=1,tonumber(arg2) do
  845.                 matrix[i][j] = 0
  846.             end
  847.         end
  848.     elseif tonumber(arg1) then --If only 1 dimension provided, create the identity matrix
  849.         matrix = {}
  850.         for i=1,tonumber(arg1) do
  851.             matrix[i] = {}
  852.             for j=1,tonumber(arg2) do
  853.                 if j == 1 then matrix[i][j] = 1 else matrix[i][j] = 0 end
  854.             end
  855.         end
  856.     end
  857.     local m = {matrix=matrix}
  858.     function m:display()
  859.         term.clear()
  860.         term.setCursorPos(1,1)
  861.         local x,y = term.getCursorPos()
  862.         for k,v in ipairs(self.matrix) do
  863.             term.setCursorPos(x,y+k-1)
  864.             for j,w in ipairs(v) do
  865.                 term.write(w .. " ")
  866.             end
  867.         end
  868.     end
  869.     function m:transpose(replace)
  870.         local n = {}
  871.         for k,v in ipairs(self.matrix) do
  872.             for j,w in ipairs(v) do
  873.                 if not n[j] then n[j] = {} end
  874.                 n[j][k] = w
  875.             end
  876.         end
  877.         if replace then self.matrix = n end
  878.         return n
  879.     end
  880.     --Matrix {1,2} {3,4} -> {3,4} {1,2}
  881.     function m:reflectX(replace)
  882.         local n = {}
  883.         for i=1,#self.matrix do
  884.             n[#self.matrix - i + 1] = self.matrix[i]
  885.         end
  886.         if replace then self.matrix = n end
  887.         return n
  888.     end
  889.     function m:reflectY(replace)
  890.         local n = {}
  891.         for i=1,#self.matrix do
  892.             n[i] = {}
  893.             for j=1,#self.matrix[i] do
  894.                 n[#self.matrix[i] - j + 1] = self.matrix[i][j]
  895.             end
  896.         end
  897.         if replace then self.matrix = n end
  898.         return n
  899.     end
  900.     function m:rotate(amt,replace)
  901.         amt = math.floor(tonumber(amt) or 1)%4
  902.         local n = {}
  903.         local function transform(x,y,w,h,amt)
  904.             if amt <= 0 then return x,y
  905.             --if amt <= 1 then return y, h - x + 1
  906.             else return transform(y, h-x+1, h, w, amt - 1) end
  907.         end
  908.         for x,v in ipairs(self.matrix) do
  909.             for y,w in ipairs(v) do
  910.                 local X,Y = transform(x,y,#v,#self.matrix,amt)
  911.                 if not n[X] then n[X] = {} end
  912.                 n[X][Y] = w
  913.             end
  914.         end
  915.         if replace then self.matrix = n end
  916.         return n
  917.     end
  918.     function m:mul(other)
  919.         if type(other) ~= "table" then return false end
  920.         if not other.matrix and type(other[1]) ~= "table" then --Case when matrix multiply by vector
  921.             if #other ~= #self.matrix[1] then return false end --Invalid matrix dims
  922.             local res = {}
  923.             for i=1, #self.matrix do
  924.                 local sum = 0
  925.                 for j = 1, #other do
  926.                     sum = sum + other[j] * self.matrix[i][j]
  927.                 end
  928.                 res[i] = sum
  929.             end
  930.             return res
  931.         end
  932.         if not other.matrix then other = Matrix(other) end --If other is not a matrix, then convert it into one
  933.         if #other.matrix ~= #self.matrix[1] then return false end --Cannot multiply the matrices
  934.         other:transpose(true) --easier to extract vectors from transposed matrix
  935.         local result = {}
  936.         for i=1,#other.matrix do
  937.             result[i] = self:mul(other.matrix[i]) --Multiply by the "vertical" vector of the original other matrix
  938.         end
  939.         result = Matrix(result)
  940.         return result:transpose() --Undoing the transpose
  941.     end
  942.     return m
  943. end
  944.  
  945. --Takes a block and returns a rotated version of itself
  946. --@Arg Block block: The block to rotate
  947. --@OptionalArg number amt: The amount to rotate
  948. --@Returns Block block: The rotated block
  949. function rotateBlock(block,amt,ref)
  950.     if type(block.bs) ~= "table" then return block end
  951.     if not block.bs.axis and not block.bs.facing and not block.bs.half and not block.bs.type then return block end
  952.     amt = math.floor(tonumber(amt) or 0)%4
  953.     ref = math.floor(tonumber(ref) or 0)%4
  954.     local newBlock = copyBlock(block)
  955.     if block.bs.axis and amt%2 == 1 then
  956.         if block.bs.axis == "x" then newBlock.bs.axis = "z"
  957.         elseif block.bs.axis == "z" then newBlock.bs.axis = "x" end
  958.     end
  959.     if block.bs.facing and facing_tab[block.bs.facing] then
  960.         local newRot = facing_tab[block.bs.facing] + amt
  961.         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
  962.         newBlock.bs.facing = facing_tab[ 1 + newRot%4 ]
  963.     end
  964.     if block.bs.half and ref == 2 then
  965.         if block.bs.half == "bottom" then newBlock.bs.half = "top"
  966.         elseif block.bs.half == "top" then newBlock.bs.half = "bottom" end
  967.     end
  968.     if block.bs.type and ref == 2 then
  969.         if block.bs.type == "bottom" then newBlock.bs.type = "top"
  970.         elseif block.bs.type == "top" then newBlock.bs.type = "bottom" end
  971.     end
  972.     return newBlock
  973. end
  974. --Rotates a schematic
  975. --@Arg Schema schema: The schema to rotate
  976. --@OptionalArg number amt: The amount to rotate (only in xz plane)
  977. --@OptionalArg number ref: The coordinate to reflect 0/nil = no reflection, 1= x coordinates reflected, 2=y,3=z
  978. --@Returns Schema sch: The rotated schematic
  979. function rotateSchema(schema,amt,ref)
  980.     amt = math.floor(tonumber(amt) or 0)%4
  981.     ref = math.floor(tonumber(ref) or 0)%4
  982.     local sch = {}
  983.     local rotatedBlocks = {}
  984.     local md = readSchemMD()
  985.     for k,v in ipairs(schema) do
  986.         local m = Matrix(v)
  987.         if amt > 0 then m:rotate(amt,true) end
  988.         if ref == 1 then m:reflectX(true)
  989.         elseif ref == 3 then m:reflectY(true) end
  990.         for j,w in ipairs(m.matrix) do --Rotating blocks
  991.             for l,u in ipairs(w) do
  992.                 if not rotatedBlocks[u] then
  993.                     rotatedBlock = rotateBlock(md[u],amt,ref)
  994.                     local key,Block = getOrAddSchemData(rotatedBlock.id,rotatedBlock.bs,rotatedBlock.nbt)
  995.                     rotatedBlocks[u] = key
  996.                     m.matrix[j][l] = key
  997.                 else
  998.                     m.matrix[j][l] = rotatedBlocks[u]
  999.                 end
  1000.             end
  1001.         end
  1002.         if ref == 2 then
  1003.             sch[#schema - k + 1] = m.matrix
  1004.         else
  1005.             sch[k] = m.matrix
  1006.         end      
  1007.         --TODO: Blockstate reflection and rotation
  1008.     end
  1009.     return sch
  1010. end
  1011. --Previews a .nbt schematic
  1012. --@Arg Schema schema: The schematic to preview
  1013. --@Returns Schema schema: The schematic that has been modified
  1014. local function previewSchema(schema)
  1015.     local yPos = 1
  1016.     local md = readSchemMD()
  1017.     local maxX,maxY = term.getSize()
  1018.     startX = math.floor(maxX/2)+1
  1019.     local scns = {}
  1020.     local scn = screen.Screen(1,1,maxX,maxY)
  1021.     scn:useNewTerm()
  1022.     local textBoxes = {
  1023.         layer=screen.TextBox(startX, 1, "Layer 1", 8, 1, colors.orange, colors.black),
  1024.         itemID = screen.TextBox(startX,5,"ID:",maxX-startX+1,2, colors.black, colors.lime),
  1025.         itemBS = screen.TextBox(startX,7,"BS:",maxX-startX+1,maxY - 6, colors.black, colors.green)
  1026.     }
  1027.     local buttons = {
  1028.         upLayer = screen.Button(startX, 2, "Up", 2, 1, colors.black, colors.lightBlue,function() return "up" end,"up"),
  1029.         downLayer = screen.Button(startX+3, 2, "Down", 4, 1, colors.black, colors.lightBlue,function() return "down" end, "down"),
  1030.         previewScreen = screen.Button(1,1,"",math.floor(maxX/2),maxY,colors.black,colors.black,function() return "preview" end, "preview"),
  1031.         quit = screen.Button(startX,3,"Finish",6,1,colors.black,colors.red,function() return "quit" end,"quit"),
  1032.         rotate = screen.Button(startX,4,"Rotate",6,1,colors.black,colors.lightBlue,function() return "rotate" end, "rotate"),
  1033.         reflect = screen.Button(startX + 7, 4, "Reflect", 7, 1, colors.black,colors.lightBlue,function() return "reflect" end, "reflect"),
  1034.         flip = screen.Button(startX + 15, 4, "Flip", 4 , 1, colors.black, colors.lightBlue, function() return "flip" end, "flip")
  1035.     }
  1036.     scn.buttons,scn.textBoxes = buttons,textBoxes
  1037.     scn:useOldTerm()
  1038.     for k,v in ipairs(schema) do
  1039.         scns[k] = screen.Screen(1,1,math.floor(maxX/2),maxY)
  1040.         scns[k]:useNewTerm(colors.white,colors.lightGray)
  1041.         term.clear()
  1042.         local buttons = {}
  1043.         for j,w in ipairs(v) do
  1044.             for l,u in ipairs(w) do
  1045.                 local char = "a"
  1046.                 local idx = (u-2)%52
  1047.                 if idx < 26 then char = string.char(65+idx) else char = string.char(97+idx%26) end
  1048.                 if u > 1 then
  1049.                     table.insert(buttons,screen.Button(j,#w-l+1,char,1,1,colors.white,colors.brown,function() return "block", u, char end,"block"))
  1050.                 end
  1051.             end
  1052.         end
  1053.         scns[k].buttons = buttons
  1054.         term.clear()
  1055.         scns[k]:useOldTerm()
  1056.     end
  1057.     local current = scns[1]
  1058.     scns[1]:render()
  1059.     scns[1]:useNewTerm()
  1060.     local buttonType,id,char
  1061.     while true do
  1062.         term.clear()
  1063.         current = scns[yPos]
  1064.         term.redirect(scn.wndw)
  1065.         scn:useNewTerm()
  1066.         for k,v in pairs(scn.buttons) do
  1067.             if k ~= "previewScreen" then v:render() end
  1068.         end
  1069.         for k,v in pairs(scn.textBoxes) do
  1070.             v:render()
  1071.         end
  1072.         term.redirect(current.wndw)
  1073.         term.clear()
  1074.         current:render()
  1075.         for k,v in pairs(current.buttons) do
  1076.             v:render()
  1077.         end
  1078.         local button,x,y = scn:getClick()
  1079.         if button then buttonType,id,char = button:click() end
  1080.         if buttonType == "up" or buttonType == "down" then
  1081.             if buttonType == "up" then yPos = yPos + 1 else yPos = yPos - 1 end
  1082.             yPos = math.min(#schema,math.max(yPos,1))
  1083.             scn.textBoxes.layer.text = string.gsub(scn.textBoxes.layer.text,"%d","") .. yPos
  1084.             term.redirect(scn.wndw)
  1085.             scn.textBoxes.layer:render()
  1086.             scn.textBoxes.itemID.text = "ID:"
  1087.             scn.textBoxes.itemBS.text = "BS:"
  1088.             scn.textBoxes.itemID:render()
  1089.             scn.textBoxes.itemBS:render()
  1090.             term.redirect(current.wndw)
  1091.         elseif buttonType == "quit" then
  1092.             term.redirect(scn.oldTerm)
  1093.             term.clear()
  1094.             return schema
  1095.         elseif buttonType == "rotate" or buttonType == "reflect" or buttonType == "flip" then
  1096.             current:render(false)
  1097.             term.redirect(scn.oldTerm)
  1098.             term.clear()
  1099.             scn = nil
  1100.             scns = nil
  1101.             current = nil
  1102.             if buttonType == "rotate" then
  1103.                 return previewSchema(rotateSchema(schema,1))
  1104.             elseif buttonType == "reflect" then
  1105.                 return previewSchema(rotateSchema(schema,0,1))
  1106.             else
  1107.                 return previewSchema(rotateSchema(schema,0,2))
  1108.             end
  1109.         else
  1110.             local button,x,y = current:getClick(x,y)
  1111.             if button then buttonType,id,char = button:click() end
  1112.             if buttonType == "block" then
  1113.                 scn.textBoxes.itemID.text = "ID (" .. char .. "):" .. md[id].id
  1114.                 local bsText = ""
  1115.                 for k,v in pairs(md[id].bs or {}) do
  1116.                     bsText = bsText .. " " .. (v or "")
  1117.                 end
  1118.                 scn.textBoxes.itemBS.text = "BS (" .. char .. "):" .. bsText
  1119.                 term.redirect(scn.wndw)
  1120.                 scn.textBoxes.itemID:render()
  1121.                 scn.textBoxes.itemBS:render()
  1122.                 term.redirect(current.wndw)
  1123.             end
  1124.         end
  1125.     end
  1126. end
  1127.  
  1128. function main()
  1129.     local schema = loadSchem()
  1130.     if not schema then return false end
  1131.     schema = previewSchema(schema)
  1132.     if not printSchema(schema) then print("Please ensure the schem turtle is on a valid inventory to begin printing the schematic") end
  1133. end
Add Comment
Please, Sign In to add comment