Advertisement
Sashaiolh

3dprint.lua

Jan 28th, 2024 (edited)
40,944
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 = 0
  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.tooltip) then printer.setTooltip("[" .. count .. "] " .. model.tooltip) else printer.setTooltip("[" .. count .. "]") end
  133.   if (model.emitRedstone) then printer.setRedstoneEmitter(model.emitRedstone) end
  134.   if (model.buttonMode) then printer.setButtonMode(model.buttonMode) end
  135.   if (model.shapes) then setupShapes(model.shapes) end
  136.   if (model.lightLevel) then printer.setLightLevel(model.lightLevel) end
  137. end
  138.  
  139. function printModel(model, count, length)
  140.   setupPrinter(model, count)
  141.   local status, valid = printer.status()
  142.   if (not valid) then
  143.     if (#model.shapes > printer.getMaxShapeCount()) then
  144.       write(text.padRight("[" .. count .. "] ", length + 3) .. "Печать модели: '" .. model.label .. "' невозможно, всвязи с превышением кол-ва shape'ов!")
  145.     else
  146.       write(text.padRight("[" .. count .. "] ", length + 3) .. "Печать модели: '" .. model.label .. "' (" .. count .. ") невозможно! Пропуск...")
  147.     end
  148.   else
  149.     drawStatus(model.label, count, -1, length)
  150.     os.sleep(WAITING)
  151.     if (not printer.commit(1)) then
  152.       return false, "В принтере закончились материалы для создания 3D модели."
  153.     end
  154.     while true do
  155.       local status, progress = printer.status()
  156.       if (status == "idle") then
  157.         drawStatus(model.label, count, 100, length)
  158.         break
  159.       elseif (status == "busy") then
  160.         drawStatus(model.label, count, progress, length)
  161.       end
  162.     end
  163.   end
  164.   io.write("\n")
  165.   return true, 1
  166. end
  167.  
  168. function printModels(models)
  169.   for i, model in pairs(models) do
  170.     local status, reason = printModel(model, i, string.len(tostring(#models)))
  171.     if (not status) then
  172.       return false, i, model.label, reason
  173.     end
  174.   end
  175.   return true, #models
  176. end
  177.  
  178. -- Check system requirements
  179. print("Активация...")
  180. print("Чтение аргументов...")
  181.  
  182. if (getArgumnet(2)) then COPIES = tonumber(getArgumnet(2)) end
  183. if (COPIES > 1) then print("Будет произведена печать " .. COPIES .. " копий указанной 3D модели!") end
  184.  
  185. for i = 1,COPIES do
  186.   print("\nПечать " .. i .. " копии...")
  187.   if (not component.isAvailable("printer3d")) then
  188.     print("Для использования программы необходим 3D принтер.")
  189.     print("Подключите 3D принтер и перезапустите программу.")
  190.   else
  191.     printer = component.printer3d
  192.     print("Поиск файла...")
  193.     if (getArgumnet(1)) then
  194.       print("Чтение файла...")
  195.       local file = getFile(getArgumnet(1))
  196.       if (file) then
  197.         local status, model = getModel(file)
  198.         if (status) then
  199.           print("Загрузка модели завершена!")
  200.           print("Валидация...")
  201.           local status, modelType = isValid(model)
  202.           if (status) then
  203.             print("Модель прошла проверку!")        
  204.             if (modelType == "ADVANCED") then
  205.               if (not getArgumnet(4)) then
  206.                 print("Сложность модели: " .. #model .. " объектов.")
  207.                 print("Печать...")
  208.                 local status, count, name, reason = printModels(normalizeModel(model))
  209.                 if (status) then
  210.                   print("Печать завершена. Напечатано " .. count .. " моделей!")
  211.                 else
  212.                   print("Ошибка печати на модели: '" .. name .. "' (" .. count .. "). Ошибка: " .. reason)
  213.                 end
  214.               else
  215.                 print("Печать указанного объекта модели...")
  216.                 print("Выбранный объект: " .. normalizeModel(model)[tonumber(getArgumnet(4))].label .. " (" .. getArgumnet(4) .. ")")
  217.                 print("Печать...")
  218.               local status, reason = printModel(normalizeModel(model)[tonumber(getArgumnet(4))], tonumber(getArgumnet(4)), string.len(getArgumnet(4)))
  219.               if (status) then
  220.                 print("Печать завершена!")
  221.               else
  222.                 print("Ошибка печати на модели: '" .. name .. "'. Ошибка: " .. reason)
  223.               end
  224.               end
  225.             elseif (modelType == "SIMPLE") then
  226.               print("Сложность модели: 1 объект.")
  227.               print("Печать...")
  228.               local status, reason = printModel(model, 1, 1)
  229.               if (status) then
  230.                 print("Печать завершена. Напечатана 1 модель!")
  231.               else
  232.                 print("Ошибка печати на модели: '" .. name .. "'. Ошибка: " .. reason)
  233.               end
  234.             end
  235.           else
  236.             print("Файл не является шаблоном 3D модели или поврежден!")
  237.             print("Вероятно проблема в том, что в одной из моделей отсутствует хотя бы один shape!")
  238.           end
  239.         else
  240.           print("Ошибка чтения файла! Ошибка: " .. model)
  241.         end
  242.       else
  243.         print("Ошибка! Файл не найден!")
  244.       end
  245.     else
  246.       print("Укажите путь к модели!")
  247.       print("Пример: 3dprint /home/model.3dm")
  248.     end
  249.   end
  250. end
  251.  
  252. print("\nЗавершение печати...")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement