# -*- coding: utf-8 -*-## This file is subject to the terms and conditions defined in# file 'LICENSE.txt', which is part of this source code package.#"""Gcode file reader"""importnumpyasnpimportMuscat.Containers.ElementsDescriptionasEDimportMuscat.Containers.MeshasUMfromMuscat.IO.ReaderBaseimportReaderBasefromMuscat.TypesimportMuscatFloat,MuscatIndex
[docs]defReadGCode(fileName:str='',string:str=''):"""Function API for reading a Gcode mesh file Parameters ---------- fileName : str, optional name of the file to be read, by default None string : str, optional data to be read as a string instead of a file, by default None Returns ------- Mesh output unstructured mesh object containing reading result """reader=GReader()reader.SetFileName(fileName)reader.SetStringToRead(string)returnreader.Read()
[docs]classGReader(ReaderBase):"""Gcode Reader class """def__init__(self):super().__init__()
[docs]defRead(self):"""Function that performs the reading of an Gcode file Returns ------- Mesh output unstructured mesh object containing reading result """extrudeur=0self.StartReading()res=UM.Mesh()res.nodes=np.empty((0,3),float)currentposx=0.currentposy=0.currentposz=0.nodes=[]thicknes=[]firsttime=Trueforlineinself.filePointer:l=line.strip('\n').lstrip().rstrip()#empty lineiflen(l)==0:continue#commentifl[0]==";":continuel=l.split(';')[0]st=l.split()ifst[0][0]=="N":st.pop(0)ifst[0][0:2]=="G0"orst[0]=="G1"orst[0][0]=="X"orst[0][0]=="Y"orst[0][0]=="Z":thi=0forsinst:ifs[0]=="X":currentposx=float(s[1:])ifs[0]=="Y":currentposy=float(s[1:])ifs[0]=="Z":currentposz=float(s[1:])ifs[0]=="E":val=float(s[1:])ifval>extrudeur:thi=1else:# pragma: no coverthi=0extrudeur=valiffirsttime:firsttime=Falseelse:thicknes.append(thi)nodes.append(currentposx)nodes.append(currentposy)nodes.append(currentposz)continueifst[0]=="G92":forsinst:ifs[0]=="E":extrudeur=float(s[1:])continueifst[0]=="M106":continueprint("ignoring line "+str(l))self.EndReading()res.nodes=np.reshape(np.asarray(nodes,dtype=MuscatFloat),newshape=(len(nodes)//3,3))res.originalIDNodes=np.arange(res.GetNumberOfNodes(),dtype=MuscatIndex)elems=res.GetElementsOfType(ED.Bar_2)elems.Allocate(res.GetNumberOfNodes()-1)elems.connectivity[:,0]=range(res.GetNumberOfNodes()-1)elems.connectivity[:,1]=range(1,res.GetNumberOfNodes())res.elemFields={}G=np.array(thicknes)G.shape=(res.GetNumberOfNodes()-1,1)res.elemFields['OnOff']=Greturnres