hohserg

Untitled

Jan 23rd, 2020
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- Libraries
  2. local component = require("component")
  3. local fs = require("filesystem")
  4. local serial = require("serialization")
  5. local text = require("text")
  6. local shell = require("shell")
  7. local term = require("term")
  8. -- Componentes
  9. local gpu = component.gpu
  10. local printer = nil
  11. -- Constants
  12. local PROGRESS_BAR_LENGTH = 30
  13. local SCREEN_X, SCREEN_Y = gpu.getResolution()
  14. local WAITING = 2
  15. local COPIES = 1
  16. -- Global variables
  17. local args = shell.parse(...)
  18. -- Functions
  19. function normalizeModel(model)
  20.   local nModel = {}
  21.   for _, i in pairs(model) do
  22.     if (#i.shapes > 0) then
  23.       table.insert(nModel, i)
  24.     end
  25.   end
  26.   return nModel
  27. end
  28.  
  29. function getArgumnet(index)
  30.   if ((#args > 0) and (#args >= index)) then
  31.     return args[index]
  32.   else
  33.     return nil
  34.   end
  35. end
  36.  
  37. function getFile(text)
  38.   if (fs.exists(text)) then
  39.     return text
  40.   else
  41.     if (fs.exists(shell.getWorkingDirectory() .. "/" .. text)) then
  42.       return shell.getWorkingDirectory() .. "/" .. text
  43.     end
  44.   end
  45.   return nil
  46. end
  47.  
  48. function getModel(path)
  49.   local object
  50.   if (fs.exists(path)) then
  51.     local text = ""
  52.     local file = fs.open(path)
  53.     while true do
  54.       local temp = file:read(9999999)
  55.       if (temp) then
  56.         text = text .. temp
  57.       else
  58.         break
  59.       end
  60.     end
  61.     text2 = "{" .. text .. "}"
  62.     object = serial.unserialize(text2)
  63.     if (object) then
  64.       if (#object > 1) then
  65.       return true, serial.unserialize(text2)
  66.     else
  67.       return true, serial.unserialize(text)
  68.     end
  69.     else
  70.       return false, "Ошибка чтения файла! Файл поврежден!"
  71.     end
  72.   else
  73.     return false, "Файл по указанному пути не найден!"
  74.   end
  75. end
  76.  
  77. function isValid(model)
  78.   if (model.shapes) then
  79.     return true, "SIMPLE"
  80.   else
  81.     for _, i in pairs(model) do
  82.       if (not i.shapes) then
  83.         return false
  84.       end
  85.     end
  86.     return true, "ADVANCED"
  87.   end
  88. end
  89.  
  90. function getBar(status)
  91.   local bar = ""
  92.   if (status == 100) then
  93.     for i = 1,PROGRESS_BAR_LENGTH do
  94.       bar = bar .. "="
  95.     end
  96.   else
  97.     local one = 100 / PROGRESS_BAR_LENGTH
  98.     local prg = status / one
  99.     for i = 1,prg do
  100.       bar = bar .. "="
  101.     end
  102.     bar = text.padRight(bar, PROGRESS_BAR_LENGTH)
  103.   end
  104.   return bar
  105. end
  106.  
  107. function write(text)
  108.   local x, y = term.getCursor()
  109.   term.setCursor(1, y)
  110.   term.write(text)
  111. end
  112.  
  113. function drawStatus(modelName, count, status, length)
  114.   if (status == -1) then
  115.     write(text.padRight(text.padRight("[" .. count .. "] ", length + 3) .. modelName .. ": [" .. text.padRight("", PROGRESS_BAR_LENGTH) .. "] 0%   Подготовка...", SCREEN_X))
  116.   elseif ((status < 100) and (status >= 0)) then
  117.     write(text.padRight(text.padRight("[" .. count .. "] ", length + 3) .. modelName .. ": [" .. getBar(status) .. "] " .. text.padRight(tostring(status) .. "%", 4) .. " Печать...", SCREEN_X))
  118.   elseif (status == 100) then
  119.     write(text.padRight(text.padRight("[" .. count .. "] ", length + 3) .. modelName .. ": [" .. getBar(status) .. "] 100% Распечатано.", SCREEN_X))
  120.   end
  121. end
  122.  
  123. function setupShapes(shapes)
  124.   for _, shape in pairs(shapes) do
  125.     printer.addShape(shape[1], shape[2], shape[3], shape[4], shape[5], shape[6], shape.texture, shape.state, shape.tint)
  126.   end
  127. end
  128.  
  129. function setupPrinter(model, count)
  130.   printer.reset()
  131.   if (model.label) then printer.setLabel(model.label) end
  132.   if (model.emitRedstone) then printer.setRedstoneEmitter(model.emitRedstone) end
  133.   if (model.buttonMode) then printer.setButtonMode(model.buttonMode) end
  134.   if (model.shapes) then setupShapes(model.shapes) end
  135. end
  136.  
  137. function printModel(model, count, length)
  138.   setupPrinter(model, count)
  139.   local status, valid = printer.status()
  140.   if (not valid) then
  141.     if (#model.shapes > printer.getMaxShapeCount()) then
  142.       write(text.padRight("[" .. count .. "] ", length + 3) .. "Печать модели: '" .. model.label .. "' невозможно, всвязи с превышением кол-ва shape'ов!")
  143.     else
  144.       write(text.padRight("[" .. count .. "] ", length + 3) .. "Печать модели: '" .. model.label .. "' (" .. count .. ") невозможно! Пропуск...")
  145.     end
  146.   else
  147.     drawStatus(model.label, count, -1, length)
  148.     os.sleep(WAITING)
  149.     if (not printer.commit(1)) then
  150.       return false, "В принтере закончились материалы для создания 3D модели."
  151.     end
  152.     while true do
  153.       local status, progress = printer.status()
  154.       if (status == "idle") then
  155.         drawStatus(model.label, count, 100, length)
  156.         break
  157.       elseif (status == "busy") then
  158.         drawStatus(model.label, count, progress, length)
  159.       end
  160.     end
  161.   end
  162.   io.write("\n")
  163.   return true, 1
  164. end
  165.  
  166. function printModels(models)
  167.   for i, model in pairs(models) do
  168.     local status, reason = printModel(model, i, string.len(tostring(#models)))
  169.     if (not status) then
  170.       return false, i, model.label, reason
  171.     end
  172.   end
  173.   return true, #models
  174. end
  175.  
  176. -- Check system requirements
  177. print("Активация...")
  178. print("Чтение аргументов...")
  179. if (getArgumnet(3)) then COPIES = tonumber(getArgumnet(3)) end
  180. if (COPIES > 1) then print("Будет произведена печать " .. COPIES .. " копий указанной 3D модели!") end
  181.  
  182. for i = 1,COPIES do
  183.   print("\nПечать " .. i .. " копии...")
  184.   if (not component.isAvailable("printer3d")) then
  185.     print("Для использования программы необходим 3D принтер.")
  186.     print("Подключите 3D принтер и перезапустите программу.")
  187.   else
  188.     printer = component.printer3d
  189.     if (getArgumnet(2)) then WAITING = tonumber(getArgumnet(2)) end
  190.     print("Поиск файла...")
  191.     if (getArgumnet(1)) then
  192.       print("Чтение файла...")
  193.       local file = getFile(getArgumnet(1))
  194.       if (file) then
  195.         local status, model = getModel(file)
  196.         if (status) then
  197.           print("Загрузка модели завершена!")
  198.           print("Валидация...")
  199.           local status, modelType = isValid(model)
  200.           if (status) then
  201.             print("Модель прошла проверку!")        
  202.             if (modelType == "ADVANCED") then
  203.               if (not getArgumnet(4)) then
  204.                 print("Сложность модели: " .. #model .. " объектов.")
  205.                 print("Печать...")
  206.                 local status, count, name, reason = printModels(normalizeModel(model))
  207.                 if (status) then
  208.                   print("Печать завершена. Напечатано " .. count .. " моделей!")
  209.                 else
  210.                   print("Ошибка печати на модели: '" .. name .. "' (" .. count .. "). Ошибка: " .. reason)
  211.                 end
  212.               else
  213.                 print("Печать указанного объекта модели...")
  214.                 print("Выбранный объект: " .. normalizeModel(model)[tonumber(getArgumnet(4))].label .. " (" .. getArgumnet(4) .. ")")
  215.                 print("Печать...")
  216.               local status, reason = printModel(normalizeModel(model)[tonumber(getArgumnet(4))], tonumber(getArgumnet(4)), string.len(getArgumnet(4)))
  217.               if (status) then
  218.                 print("Печать завершена!")
  219.               else
  220.                 print("Ошибка печати на модели: '" .. name .. "'. Ошибка: " .. reason)
  221.               end
  222.               end
  223.             elseif (modelType == "SIMPLE") then
  224.               print("Сложность модели: 1 объект.")
  225.               print("Печать...")
  226.               local status, reason = printModel(model, 1, 1)
  227.               if (status) then
  228.                 print("Печать завершена. Напечатана 1 модель!")
  229.               else
  230.                 print("Ошибка печати на модели: '" .. name .. "'. Ошибка: " .. reason)
  231.               end
  232.             end
  233.           else
  234.             print("Файл не является шаблоном 3D модели или поврежден!")
  235.             print("Вероятно проблема в том, что в одной из моделей отсутствует хотя бы один shape!")
  236.           end
  237.         else
  238.           print("Ошибка чтения файла! Ошибка: " .. model)
  239.         end
  240.       else
  241.         print("Ошибка! Файл не найден!")
  242.       end
  243.     else
  244.       print("Укажите путь к модели!")
  245.       print("Пример: 3dprint /home/model.3dm")
  246.     end
  247.   end
  248. end
  249.  
  250. print("\nЗавершение печати...")
Add Comment
Please, Sign In to add comment