public override RectangleDouble GetBounds() { RectangleDouble bounds = new RectangleDouble(double.MaxValue, double.MaxValue, double.MinValue, double.MinValue); Agg.Parallel.For <RectangleDouble>( 0, GCodeCommandQueue.Count, () => new RectangleDouble(double.MaxValue, double.MaxValue, double.MinValue, double.MinValue), (int index, ParallelLoopState loop, RectangleDouble subtotal) => { PrinterMachineInstruction state = GCodeCommandQueue[index]; subtotal.Left = Math.Min(state.Position.X, subtotal.Left); subtotal.Right = Math.Max(state.Position.X, subtotal.Right); subtotal.Bottom = Math.Min(state.Position.Y, subtotal.Bottom); subtotal.Top = Math.Max(state.Position.Y, subtotal.Top); return(subtotal); }, (x) => { bounds.Left = Math.Min(x.Left, bounds.Left); bounds.Right = Math.Max(x.Right, bounds.Right); bounds.Bottom = Math.Min(x.Bottom, bounds.Bottom); bounds.Top = Math.Max(x.Top, bounds.Top); } ); return(bounds); }
public override Vector2 GetWeightedCenter() { Vector2 total = new Vector2(); #if !MULTI_THREAD foreach (PrinterMachineInstruction state in GCodeCommandQueue) { total += new Vector2(state.Position.x, state.Position.y); } #else Parallel.For <Vector2>( 0, GCodeCommandQueue.Count, () => new Vector2(), (int index, ParallelLoopState loop, Vector2 subtotal) => { PrinterMachineInstruction state = GCodeCommandQueue[index]; subtotal += new Vector2(state.Position.x, state.Position.y); return(subtotal); }, (x) => { total += new Vector2(x.x, x.y); } ); #endif return(total / GCodeCommandQueue.Count); }
private void SetInitalLayer() { activeLayerIndex = 0; if (loadedGCode.LineCount > 0) { int firstExtrusionIndex = 0; Vector3 lastPosition = loadedGCode.Instruction(0).Position; double ePosition = loadedGCode.Instruction(0).EPosition; // let's find the first layer that has extrusion if possible and go to that for (int i = 1; i < loadedGCode.LineCount; i++) { PrinterMachineInstruction currentInstruction = loadedGCode.Instruction(i); if (currentInstruction.EPosition > ePosition && lastPosition != currentInstruction.Position) { firstExtrusionIndex = i; break; } lastPosition = currentInstruction.Position; } if (firstExtrusionIndex > 0) { for (int layerIndex = 0; layerIndex < loadedGCode.NumChangesInZ; layerIndex++) { if (firstExtrusionIndex < loadedGCode.GetInstructionIndexAtLayer(layerIndex)) { activeLayerIndex = Math.Max(0, layerIndex - 1); break; } } } } }
public void CreateFeaturesForLayerIfRequired(int layerToCreate) { if (renderFeatures.Count == 0 || renderFeatures[layerToCreate].Count > 0) { return; } List <RenderFeatureBase> renderFeaturesForLayer = renderFeatures[layerToCreate]; int startRenderIndex = gCodeFileToDraw.GetFirstLayerInstruction(layerToCreate); int endRenderIndex = gCodeFileToDraw.LineCount - 1; if (layerToCreate < gCodeFileToDraw.LayerCount - 1) { endRenderIndex = gCodeFileToDraw.GetFirstLayerInstruction(layerToCreate + 1); } for (int instructionIndex = startRenderIndex; instructionIndex < endRenderIndex; instructionIndex++) { PrinterMachineInstruction currentInstruction = gCodeFileToDraw.Instruction(instructionIndex); PrinterMachineInstruction previousInstruction = currentInstruction; if (instructionIndex > 0) { previousInstruction = gCodeFileToDraw.Instruction(instructionIndex - 1); } if (currentInstruction.Position == previousInstruction.Position) { if (Math.Abs(currentInstruction.EPosition - previousInstruction.EPosition) > 0) { // this is a retraction renderFeaturesForLayer.Add(new RenderFeatureRetract(currentInstruction.Position, currentInstruction.EPosition - previousInstruction.EPosition, currentInstruction.ExtruderIndex, currentInstruction.FeedRate)); } if (currentInstruction.Line.StartsWith("G10")) { renderFeaturesForLayer.Add(new RenderFeatureRetract(currentInstruction.Position, -1, currentInstruction.ExtruderIndex, currentInstruction.FeedRate)); } else if (currentInstruction.Line.StartsWith("G11")) { renderFeaturesForLayer.Add(new RenderFeatureRetract(currentInstruction.Position, 1, currentInstruction.ExtruderIndex, currentInstruction.FeedRate)); } } else { if (gCodeFileToDraw.IsExtruding(instructionIndex)) { double layerThickness = gCodeFileToDraw.GetLayerHeight(layerToCreate); Color extrusionColor = ExtrusionColors.GetColorForSpeed((float)currentInstruction.FeedRate); renderFeaturesForLayer.Add(new RenderFeatureExtrusion(previousInstruction.Position, currentInstruction.Position, currentInstruction.ExtruderIndex, currentInstruction.FeedRate, currentInstruction.EPosition - previousInstruction.EPosition, gCodeFileToDraw.GetFilamentDiameter(), layerThickness, extrusionColor)); } else { renderFeaturesForLayer.Add(new RenderFeatureTravel(previousInstruction.Position, currentInstruction.Position, currentInstruction.ExtruderIndex, currentInstruction.FeedRate)); } } } }
public PrinterMachineInstruction(string Line, PrinterMachineInstruction copy) : this(Line) { xyzPosition = copy.xyzPosition; feedRate = copy.feedRate; ePosition = copy.ePosition; movementType = copy.movementType; secondsToEndFromHere = copy.secondsToEndFromHere; ExtruderIndex = copy.ExtruderIndex; }
public string ApplyLeveling(Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode, string lineBeingSent, bool addLFCR, bool includeSpaces) { if ((lineBeingSent.StartsWith("G0") || lineBeingSent.StartsWith("G1")) && lineBeingSent.Length > 2 && lineBeingSent[2] == ' ') { double extruderDelta = 0; GCodeFile.GetFirstNumberAfter("E", lineBeingSent, ref extruderDelta); double feedRate = 0; GCodeFile.GetFirstNumberAfter("F", lineBeingSent, ref feedRate); string newLine = "G1 "; if (lineBeingSent.Contains('X') || lineBeingSent.Contains('Y') || lineBeingSent.Contains('Z')) { Vector3 outPosition = PrintLeveling.Instance.ApplyLeveling(currentDestination); if (movementMode == PrinterMachineInstruction.MovementTypes.Relative) { Vector3 relativeMove = Vector3.Zero; GCodeFile.GetFirstNumberAfter("X", lineBeingSent, ref relativeMove.x); GCodeFile.GetFirstNumberAfter("Y", lineBeingSent, ref relativeMove.y); GCodeFile.GetFirstNumberAfter("Z", lineBeingSent, ref relativeMove.z); outPosition = PrintLeveling.Instance.ApplyLevelingRotation(relativeMove); } if (includeSpaces) { newLine = newLine + String.Format("X{0:0.##} Y{1:0.##} Z{2:0.##}", outPosition.x, outPosition.y, outPosition.z); } else { newLine = newLine + String.Format("X{0:0.##}Y{1:0.##}Z{2:0.##}", outPosition.x, outPosition.y, outPosition.z); } } if (extruderDelta != 0) { newLine = newLine + String.Format(" E{0:0.###}", extruderDelta); } if (feedRate != 0) { newLine = newLine + String.Format(" F{0:0.##}", feedRate); } lineBeingSent = newLine; if (addLFCR) { lineBeingSent += "\r\n"; } } return lineBeingSent; }
public PrinterMachineInstruction(string Line, PrinterMachineInstruction copy, bool clientInsertion = false) : this(Line) { xyzPosition = copy.xyzPosition; feedRate = copy.feedRate; ePosition = copy.ePosition; movementType = copy.movementType; secondsToEndFromHere = copy.secondsToEndFromHere; ExtruderIndex = copy.ExtruderIndex; this.clientInsertion = clientInsertion; }
public void Insert(int insertIndex, PrinterMachineInstruction printerMachineInstruction) { for (int i = 0; i < indexOfChangeInZ.Count; i++) { if (insertIndex < indexOfChangeInZ[i]) { indexOfChangeInZ[i]++; } } GCodeCommandQueue.Insert(insertIndex, printerMachineInstruction); }
public static string ApplyLeveling(string lineBeingSent, Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode) { var settings = ActiveSliceSettings.Instance; if (settings?.GetValue<bool>(SettingsKey.print_leveling_enabled) == true && (lineBeingSent.StartsWith("G0 ") || lineBeingSent.StartsWith("G1 ")) && lineBeingSent.Length > 2 && lineBeingSent[2] == ' ') { return GetLevelingFunctions(numberOfRadialSamples, settings.Helpers.GetPrintLevelingData(), ActiveSliceSettings.Instance.GetValue<Vector2>(SettingsKey.print_center)) .DoApplyLeveling(lineBeingSent, currentDestination, movementMode); } return lineBeingSent; }
public static string ApplyLeveling(string lineBeingSent, Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode) { var settings = ActiveSliceSettings.Instance; if (settings?.DoPrintLeveling == true && (lineBeingSent.StartsWith("G0 ") || lineBeingSent.StartsWith("G1 ")) && lineBeingSent.Length > 2 && lineBeingSent[2] == ' ') { return GetLevelingFunctions(numberOfRadialSamples, settings.PrintLevelingData, ActiveSliceSettings.Instance.BedCenter) .DoApplyLeveling(lineBeingSent, currentDestination, movementMode); } return lineBeingSent; }
public static string ApplyLeveling(string lineBeingSent, Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode) { Printer activePrinter = PrinterConnectionAndCommunication.Instance.ActivePrinter; if (activePrinter != null && activePrinter.DoPrintLeveling && (lineBeingSent.StartsWith("G0 ") || lineBeingSent.StartsWith("G1 ")) && lineBeingSent.Length > 2 && lineBeingSent[2] == ' ') { PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(activePrinter); return GetLevelingFunctions(numberOfRadialSamples, levelingData, ActiveSliceSettings.Instance.BedCenter) .DoApplyLeveling(lineBeingSent, currentDestination, movementMode); } return lineBeingSent; }
public override double GetFilamentUsedMm(double filamentDiameter) { if (filamentUsedMmCache == 0 || filamentDiameter != diameterOfFilamentUsedMmCache) { double lastEPosition = 0; double filamentMm = 0; for (int i = 0; i < GCodeCommandQueue.Count; i++) { PrinterMachineInstruction instruction = GCodeCommandQueue[i]; //filamentMm += instruction.EPosition; string lineToParse = instruction.Line; if (lineToParse.StartsWith("G0") || lineToParse.StartsWith("G1")) { double ePosition = lastEPosition; if (GetFirstNumberAfter("E", lineToParse, ref ePosition)) { if (instruction.movementType == PrinterMachineInstruction.MovementTypes.Absolute) { double deltaEPosition = ePosition - lastEPosition; filamentMm += deltaEPosition; } else { filamentMm += ePosition; } lastEPosition = ePosition; } } else if (lineToParse.StartsWith("G92")) { double ePosition = 0; if (GetFirstNumberAfter("E", lineToParse, ref ePosition)) { lastEPosition = ePosition; } } } filamentUsedMmCache = filamentMm; diameterOfFilamentUsedMmCache = filamentDiameter; } return(filamentUsedMmCache); }
public override void Insert(int indexToStartInjection, PrinterMachineInstruction printerMachineInstruction) { using (TimedLock.Lock(this, "Adding Instruction")) { if (indexToStartInjection < readLineCount - MaxLinesToBuffer) { throw new Exception("You are asking for a line we no longer have bufferd"); } // Make room for the instruction we are inserting, push all the existing instructions up for (int movingIndex = indexToStartInjection; movingIndex < readLineCount; movingIndex++) { readLinesRingBuffer[(movingIndex + 1) % MaxLinesToBuffer] = readLinesRingBuffer[movingIndex % MaxLinesToBuffer]; } readLinesRingBuffer[indexToStartInjection % MaxLinesToBuffer] = printerMachineInstruction; readLineCount++; } }
public override Vector2 GetWeightedCenter() { Vector2 total = new Vector2(); Agg.Parallel.For <Vector2>( 0, GCodeCommandQueue.Count, () => new Vector2(), (int index, ParallelLoopState loop, Vector2 subtotal) => { PrinterMachineInstruction state = GCodeCommandQueue[index]; subtotal += new Vector2(state.Position.X, state.Position.Y); return(subtotal); }, (x) => { total += new Vector2(x.X, x.Y); } ); return(total / GCodeCommandQueue.Count); }
public static GCodeFileLoaded ParseFileContents(string gCodeString, CancellationToken cancellationToken, Action <double, string> progressReporter) { if (gCodeString == null) { return(null); } Stopwatch loadTime = Stopwatch.StartNew(); Stopwatch maxProgressReport = new Stopwatch(); maxProgressReport.Start(); PrinterMachineInstruction machineInstructionForLine = new PrinterMachineInstruction("None"); bool gcodeHasExplicitLayerChangeInfo = false; if (gCodeString.Contains("LAYER:")) { gcodeHasExplicitLayerChangeInfo = true; } GCodeFileLoaded loadedGCodeFile = new GCodeFileLoaded(gcodeHasExplicitLayerChangeInfo); int crCount = CountNumLines(gCodeString); int lineIndex = 0; foreach (string outputString in CustomSplit(gCodeString, '\n')) { string lineString = outputString.Trim(); machineInstructionForLine = new PrinterMachineInstruction(lineString, machineInstructionForLine, false); if (lineString.Length > 0) { switch (lineString[0]) { case 'G': loadedGCodeFile.ParseGLine(lineString, machineInstructionForLine); break; case 'M': loadedGCodeFile.ParseMLine(lineString, machineInstructionForLine); break; case 'T': double extruderIndex = 0; if (GetFirstNumberAfter("T", lineString, ref extruderIndex)) { machineInstructionForLine.ExtruderIndex = (int)extruderIndex; } break; case ';': if (gcodeHasExplicitLayerChangeInfo && IsLayerChange(lineString)) { loadedGCodeFile.IndexOfChangeInZ.Add(loadedGCodeFile.GCodeCommandQueue.Count); } if (lineString.StartsWith("; layerThickness")) { loadedGCodeFile.layerThickness = double.Parse(lineString.Split('=')[1]); } else if (lineString.StartsWith("; firstLayerThickness") && loadedGCodeFile.firstLayerThickness == 0) { loadedGCodeFile.firstLayerThickness = double.Parse(lineString.Split('=')[1]); } break; case '@': break; default: #if DEBUG throw new NotImplementedException(); #else break; #endif } } loadedGCodeFile.GCodeCommandQueue.Add(machineInstructionForLine); if (progressReporter != null && maxProgressReport.ElapsedMilliseconds > 200) { progressReporter((double)lineIndex / crCount / 2, ""); if (cancellationToken.IsCancellationRequested) { return(null); } maxProgressReport.Restart(); } lineIndex++; } loadedGCodeFile.AnalyzeGCodeLines(CancellationToken.None, progressReporter); loadTime.Stop(); Console.WriteLine("Time To Load Seconds: {0:0.00}".FormatWith(loadTime.Elapsed.TotalSeconds)); return(loadedGCodeFile); }
private void SaveGCodeToNewLocation(string source, string dest) { try { if (ActiveSliceSettings.Instance.DoPrintLeveling) { GCodeFileLoaded unleveledGCode = new GCodeFileLoaded(source); if (applyLeveling.Checked) { PrintLevelingData levelingData = ActiveSliceSettings.Instance.PrintLevelingData; if (levelingData != null) { for (int lineIndex = 0; lineIndex < unleveledGCode.LineCount; lineIndex++) { PrinterMachineInstruction instruction = unleveledGCode.Instruction(lineIndex); Vector3 currentDestination = instruction.Position; List<string> linesToWrite = null; switch (levelingData.CurrentPrinterLevelingSystem) { case PrintLevelingData.LevelingSystem.Probe2Points: instruction.Line = LevelWizard2Point.ApplyLeveling(instruction.Line, currentDestination, instruction.movementType); linesToWrite = LevelWizard2Point.ProcessCommand(instruction.Line); break; case PrintLevelingData.LevelingSystem.Probe3Points: instruction.Line = LevelWizard3Point.ApplyLeveling(instruction.Line, currentDestination, instruction.movementType); linesToWrite = LevelWizard3Point.ProcessCommand(instruction.Line); break; case PrintLevelingData.LevelingSystem.Probe7PointRadial: instruction.Line = LevelWizard7PointRadial.ApplyLeveling(instruction.Line, currentDestination, instruction.movementType); linesToWrite = LevelWizard7PointRadial.ProcessCommand(instruction.Line); break; case PrintLevelingData.LevelingSystem.Probe13PointRadial: instruction.Line = LevelWizard13PointRadial.ApplyLeveling(instruction.Line, currentDestination, instruction.movementType); linesToWrite = LevelWizard13PointRadial.ProcessCommand(instruction.Line); break; default: throw new NotImplementedException(); } instruction.Line = linesToWrite[0]; linesToWrite.RemoveAt(0); // now insert any new lines foreach (string line in linesToWrite) { PrinterMachineInstruction newInstruction = new PrinterMachineInstruction(line); unleveledGCode.Insert(++lineIndex, newInstruction); } } } } unleveledGCode.Save(dest); } else { File.Copy(source, dest, true); } ShowFileIfRequested(dest); } catch { } }
public void CreateFeaturesForLayerIfRequired(int layerToCreate) { if (all.layers.Count == 0 || all.layers[layerToCreate].features.Count > 0) { return; } List <RenderFeatureBase> renderFeaturesForLayer = all.layers[layerToCreate].features; int startRenderIndex = gCodeFileToDraw.GetFirstLayerInstruction(layerToCreate); int endRenderIndex = gCodeFileToDraw.LineCount - 1; if (layerToCreate < gCodeFileToDraw.LayerCount - 1) { endRenderIndex = gCodeFileToDraw.GetFirstLayerInstruction(layerToCreate + 1); } for (int instructionIndex = startRenderIndex; instructionIndex < endRenderIndex; instructionIndex++) { PrinterMachineInstruction currentInstruction = gCodeFileToDraw.Instruction(instructionIndex); PrinterMachineInstruction previousInstruction = currentInstruction; if (instructionIndex > 0) { previousInstruction = gCodeFileToDraw.Instruction(instructionIndex - 1); } if (currentInstruction.Position == previousInstruction.Position) { double eMovement = 0; if (currentInstruction.PositionSet != PositionSet.E) { eMovement = currentInstruction.EPosition - previousInstruction.EPosition; } if (Math.Abs(eMovement) > 0) { // this is a retraction renderFeaturesForLayer.Add(new RenderFeatureRetract(instructionIndex, currentInstruction.Position, eMovement, currentInstruction.ToolIndex, currentInstruction.FeedRate)); } if (currentInstruction.Line.StartsWith("G10")) { renderFeaturesForLayer.Add(new RenderFeatureRetract(instructionIndex, currentInstruction.Position, -1, currentInstruction.ToolIndex, currentInstruction.FeedRate)); } else if (currentInstruction.Line.StartsWith("G11")) { renderFeaturesForLayer.Add(new RenderFeatureRetract(instructionIndex, currentInstruction.Position, 1, currentInstruction.ToolIndex, currentInstruction.FeedRate)); } } else { var extrusionAmount = currentInstruction.EPosition - previousInstruction.EPosition; var filamentDiameterMm = gCodeFileToDraw.GetFilamentDiameter(); if (gCodeFileToDraw.IsExtruding(instructionIndex)) { double layerThickness = gCodeFileToDraw.GetLayerHeight(layerToCreate); Color extrusionColor = ExtrusionColors.GetColorForSpeed((float)currentInstruction.FeedRate); renderFeaturesForLayer.Add( new RenderFeatureExtrusion( instructionIndex, previousInstruction.Position, currentInstruction.Position, currentInstruction.ToolIndex, currentInstruction.FeedRate, extrusionAmount, filamentDiameterMm, layerThickness, extrusionColor, this.Gray)); } else { if (extrusionAmount < 0) { double moveLength = (currentInstruction.Position - previousInstruction.Position).Length; double filamentRadius = filamentDiameterMm / 2; double areaSquareMm = (filamentRadius * filamentRadius) * Math.PI; var extrusionVolumeMm3 = (float)(areaSquareMm * extrusionAmount); var area = extrusionVolumeMm3 / moveLength; } renderFeaturesForLayer.Add( new RenderFeatureTravel( instructionIndex, previousInstruction.Position, currentInstruction.Position, currentInstruction.ToolIndex, currentInstruction.FeedRate, extrusionAmount < 0)); } } } }
public override PrinterMachineInstruction Instruction(int index) { using (TimedLock.Lock(this, "Loading Instruction")) { if (index < readLineCount - MaxLinesToBuffer) { throw new Exception("You are asking for a line we no longer have bufferd"); } while (index >= readLineCount) { string line = openGcodeStream.ReadLine(); if (line == null) { readLastLineOfFile = true; line = ""; } int ringBufferIndex = readLineCount % MaxLinesToBuffer; readLinesRingBuffer[ringBufferIndex] = new PrinterMachineInstruction(line); PrinterMachineInstruction instruction = readLinesRingBuffer[ringBufferIndex]; Vector3 deltaPositionThisLine = new Vector3(); double deltaEPositionThisLine = 0; string lineToParse = line.ToUpper().Trim(); if (lineToParse.StartsWith("G0") || lineToParse.StartsWith("G1")) { double newFeedRateMmPerMin = 0; if (GetFirstNumberAfter("F", lineToParse, ref newFeedRateMmPerMin)) { feedRateMmPerMin = newFeedRateMmPerMin; } Vector3 attemptedDestination = lastPrinterPosition; GetFirstNumberAfter("X", lineToParse, ref attemptedDestination.x); GetFirstNumberAfter("Y", lineToParse, ref attemptedDestination.y); GetFirstNumberAfter("Z", lineToParse, ref attemptedDestination.z); double ePosition = lastEPosition; GetFirstNumberAfter("E", lineToParse, ref ePosition); deltaPositionThisLine = attemptedDestination - lastPrinterPosition; deltaEPositionThisLine = Math.Abs(ePosition - lastEPosition); lastPrinterPosition = attemptedDestination; lastEPosition = ePosition; } else if (lineToParse.StartsWith("G92")) { double ePosition = 0; if (GetFirstNumberAfter("E", lineToParse, ref ePosition)) { lastEPosition = ePosition; } } if (feedRateMmPerMin > 0) { instruction.secondsThisLine = (float)GetSecondsThisLine(deltaPositionThisLine, deltaEPositionThisLine, feedRateMmPerMin); } readLineCount++; } } return(readLinesRingBuffer[index % MaxLinesToBuffer]); }
void ParseMLine(string lineString, PrinterMachineInstruction processingMachineState) { string[] splitOnSpace = lineString.Split(' '); switch (splitOnSpace[0].Substring(1).Trim()) { case "01": // show a message? break; case "6": // wait for tool to heat up (wait for condition?) break; case "101": // extrude on, forward break; case "18": // turn off stepers break; case "42": // Stop on material exhausted / Switch I/O pin break; case "82": // set extruder to absolute mode break; case "84": // lineString = "M84 ; disable motors\r" break; case "102": // extrude on reverse break; case "103": // extrude off break; case "104": // set extruder tempreature break; case "105": // M105 Custom code for temperature reading. (Not used) break; case "106": // turn fan on break; case "107": // turn fan off break; case "108": // set extruder speed break; case "109": // set heated platform temperature break; case "114": break; case "117": // in Marlin: Display Message break; case "126": // enable fan (makerbot) break; case "127": // disable fan (makerbot) break; case "132": // recall stored home offsets for axis xyzab break; case "140": // set bed temperature break; case "190": // wait for bed temperature to be reached break; case "200": // M200 sets the filament diameter. break; case "201": // set axis acceleration break; case "204": // - Set default acceleration break; case "207": // M207: calibrate z axis by detecting z max length break; case "208": // M208: set axis max travel break; case "209": // M209: enable automatic retract break; case "227": // Enable Automatic Reverse and Prime break; case "301": break; case "565": // M565: Set Z probe offset break; #if DEBUG default: throw new NotImplementedException(lineString); #else default: break; #endif } }
public abstract void Insert(int indexToStartInjection, PrinterMachineInstruction printerMachineInstruction);
private void SaveGCodeToNewLocation(string source, string dest) { if (ActivePrinterProfile.Instance.DoPrintLeveling) { GCodeFileLoaded unleveledGCode = new GCodeFileLoaded(source); if (applyLeveling.Checked) { PrintLevelingPlane.Instance.ApplyLeveling(unleveledGCode); PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); if (levelingData != null) { for (int lineIndex = 0; lineIndex < unleveledGCode.LineCount; lineIndex++) { PrinterMachineInstruction instruction = unleveledGCode.Instruction(lineIndex); List<string> linesToWrite = null; switch (levelingData.levelingSystem) { case PrintLevelingData.LevelingSystem.Probe2Points: linesToWrite = LevelWizard2Point.ProcessCommand(instruction.Line); break; case PrintLevelingData.LevelingSystem.Probe3Points: linesToWrite = LevelWizard3Point.ProcessCommand(instruction.Line); break; } instruction.Line = linesToWrite[0]; linesToWrite.RemoveAt(0); // now insert any new lines foreach (string line in linesToWrite) { PrinterMachineInstruction newInstruction = new PrinterMachineInstruction(line); unleveledGCode.Insert(++lineIndex, newInstruction); } } } } unleveledGCode.Save(dest); } else { File.Copy(source, dest, true); } ShowFileIfRequested(dest); }
public static void ParseFileContents(object sender, DoWorkEventArgs doWorkEventArgs) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; string gCodeString = (string)doWorkEventArgs.Argument; if (gCodeString == null) { return; } Stopwatch loadTime = Stopwatch.StartNew(); BackgroundWorker backgroundWorker = sender as BackgroundWorker; Stopwatch maxProgressReport = new Stopwatch(); maxProgressReport.Start(); PrinterMachineInstruction machineInstructionForLine = new PrinterMachineInstruction("None"); bool gcodeHasExplicitLayerChangeInfo = false; if (gCodeString.Contains("; LAYER:")) { gcodeHasExplicitLayerChangeInfo = true; } GCodeFileLoaded loadedGCodeFile = new GCodeFileLoaded(gcodeHasExplicitLayerChangeInfo); int crCount = CountNumLines(gCodeString); int lineIndex = 0; foreach (string outputString in CustomSplit(gCodeString, '\n')) { string lineString = outputString.Trim(); machineInstructionForLine = new PrinterMachineInstruction(lineString, machineInstructionForLine, false); if (lineString.Length > 0) { switch (lineString[0]) { case 'G': loadedGCodeFile.ParseGLine(lineString, machineInstructionForLine); break; case 'M': loadedGCodeFile.ParseMLine(lineString, machineInstructionForLine); break; case 'T': double extruderIndex = 0; if (GetFirstNumberAfter("T", lineString, ref extruderIndex)) { machineInstructionForLine.ExtruderIndex = (int)extruderIndex; } break; case ';': if (gcodeHasExplicitLayerChangeInfo && lineString.StartsWith("; LAYER:")) { loadedGCodeFile.IndexOfChangeInZ.Add(loadedGCodeFile.GCodeCommandQueue.Count); } if (lineString.StartsWith("; layerThickness")) { loadedGCodeFile.layerThickness = double.Parse(lineString.Split('=')[1]); } else if (lineString.StartsWith("; firstLayerThickness")) { loadedGCodeFile.firstLayerThickness = double.Parse(lineString.Split('=')[1]); } break; case '@': break; default: #if DEBUG throw new NotImplementedException(); #else break; #endif } } loadedGCodeFile.GCodeCommandQueue.Add(machineInstructionForLine); if (backgroundWorker != null) { if (backgroundWorker.CancellationPending) { return; } if (backgroundWorker.WorkerReportsProgress && maxProgressReport.ElapsedMilliseconds > 200) { backgroundWorker.ReportProgress(lineIndex * 100 / crCount / 2); maxProgressReport.Restart(); } } lineIndex++; } loadedGCodeFile.AnalyzeGCodeLines(backgroundWorker); doWorkEventArgs.Result = loadedGCodeFile; loadTime.Stop(); Console.WriteLine("Time To Load Seconds: {0:0.00}".FormatWith(loadTime.Elapsed.TotalSeconds)); }
public virtual void AddInstruction(PrinterMachineInstruction newCommand) { throw new NotImplementedException(); }
public override void Add(PrinterMachineInstruction printerMachineInstruction) { Insert(Count, printerMachineInstruction); }
public void CreateFeaturesForLayerIfRequired(int layerToCreate) { if (extrusionColors == null && gCodeFileToDraw != null && gCodeFileToDraw.LineCount > 0) { extrusionColors = new ExtrusionColors(); HashSet <float> speeds = new HashSet <float>(); PrinterMachineInstruction prevInstruction = gCodeFileToDraw.Instruction(0); for (int i = 1; i < gCodeFileToDraw.LineCount; i++) { PrinterMachineInstruction instruction = gCodeFileToDraw.Instruction(i); if (instruction.EPosition > prevInstruction.EPosition && (instruction.Line.IndexOf('X') != -1 || instruction.Line.IndexOf('Y') != -1)) { speeds.Add((float)instruction.FeedRate); } prevInstruction = instruction; } foreach (float speed in speeds) { extrusionColors.GetColorForSpeed(speed); } } if (renderFeatures.Count == 0 || renderFeatures[layerToCreate].Count > 0) { return; } List <RenderFeatureBase> renderFeaturesForLayer = renderFeatures[layerToCreate]; int startRenderIndex = gCodeFileToDraw.GetInstructionIndexAtLayer(layerToCreate); int endRenderIndex = gCodeFileToDraw.LineCount - 1; if (layerToCreate < gCodeFileToDraw.NumChangesInZ - 1) { endRenderIndex = gCodeFileToDraw.GetInstructionIndexAtLayer(layerToCreate + 1); } for (int instructionIndex = startRenderIndex; instructionIndex < endRenderIndex; instructionIndex++) { PrinterMachineInstruction currentInstruction = gCodeFileToDraw.Instruction(instructionIndex); PrinterMachineInstruction previousInstruction = currentInstruction; if (instructionIndex > 0) { previousInstruction = gCodeFileToDraw.Instruction(instructionIndex - 1); } if (currentInstruction.Position == previousInstruction.Position) { if (Math.Abs(currentInstruction.EPosition - previousInstruction.EPosition) > 0) { // this is a retraction renderFeaturesForLayer.Add(new RenderFeatureRetract(currentInstruction.Position, currentInstruction.EPosition - previousInstruction.EPosition, currentInstruction.ExtruderIndex, currentInstruction.FeedRate)); } if (currentInstruction.Line.StartsWith("G10")) { renderFeaturesForLayer.Add(new RenderFeatureRetract(currentInstruction.Position, -1, currentInstruction.ExtruderIndex, currentInstruction.FeedRate)); } else if (currentInstruction.Line.StartsWith("G11")) { renderFeaturesForLayer.Add(new RenderFeatureRetract(currentInstruction.Position, 1, currentInstruction.ExtruderIndex, currentInstruction.FeedRate)); } } else { if (gCodeFileToDraw.IsExtruding(instructionIndex)) { double layerThickness = gCodeFileToDraw.GetLayerHeight(); if (layerToCreate == 0) { layerThickness = gCodeFileToDraw.GetFirstLayerHeight(); } Color extrusionColor = extrusionColors.GetColorForSpeed((float)currentInstruction.FeedRate); renderFeaturesForLayer.Add(new RenderFeatureExtrusion(previousInstruction.Position, currentInstruction.Position, currentInstruction.ExtruderIndex, currentInstruction.FeedRate, currentInstruction.EPosition - previousInstruction.EPosition, gCodeFileToDraw.GetFilamentDiameter(), layerThickness, extrusionColor)); } else { renderFeaturesForLayer.Add(new RenderFeatureTravel(previousInstruction.Position, currentInstruction.Position, currentInstruction.ExtruderIndex, currentInstruction.FeedRate)); } } } }
public override void Add(PrinterMachineInstruction printerMachineInstruction) { source.Add(printerMachineInstruction); }
public override void Insert(int indexToStartInjection, PrinterMachineInstruction printerMachineInstruction) { source.Insert(indexToStartInjection, printerMachineInstruction); }
private void AnalyzeGCodeLines(CancellationToken cancellationToken, Action <double, string> progressReporter) { double feedRateMmPerMin = 0; Vector3 lastPrinterPosition = new Vector3(); double lastEPosition = 0; Stopwatch maxProgressReport = new Stopwatch(); maxProgressReport.Start(); for (int lineIndex = 0; lineIndex < GCodeCommandQueue.Count; lineIndex++) { PrinterMachineInstruction instruction = GCodeCommandQueue[lineIndex]; string line = instruction.Line; Vector3 deltaPositionThisLine = new Vector3(); double deltaEPositionThisLine = 0; string lineToParse = line.ToUpper().Trim(); if (lineToParse.StartsWith("G0") || lineToParse.StartsWith("G1")) { double newFeedRateMmPerMin = 0; if (GetFirstNumberAfter("F", lineToParse, ref newFeedRateMmPerMin)) { feedRateMmPerMin = newFeedRateMmPerMin; } Vector3 attemptedDestination = lastPrinterPosition; GetFirstNumberAfter("X", lineToParse, ref attemptedDestination.X); GetFirstNumberAfter("Y", lineToParse, ref attemptedDestination.Y); GetFirstNumberAfter("Z", lineToParse, ref attemptedDestination.Z); double ePosition = lastEPosition; GetFirstNumberAfter("E", lineToParse, ref ePosition); deltaPositionThisLine = attemptedDestination - lastPrinterPosition; deltaEPositionThisLine = Math.Abs(ePosition - lastEPosition); lastPrinterPosition = attemptedDestination; lastEPosition = ePosition; } else if (lineToParse.StartsWith("G92")) { double ePosition = 0; if (GetFirstNumberAfter("E", lineToParse, ref ePosition)) { lastEPosition = ePosition; } } if (feedRateMmPerMin > 0) { instruction.secondsThisLine = (float)GetSecondsThisLine(deltaPositionThisLine, deltaEPositionThisLine, feedRateMmPerMin); } if (progressReporter != null && maxProgressReport.ElapsedMilliseconds > 200) { progressReporter(((double)lineIndex / GCodeCommandQueue.Count / 2) + .5, ""); if (cancellationToken.IsCancellationRequested) { return; } maxProgressReport.Restart(); } } double accumulatedTime = 0; for (int i = GCodeCommandQueue.Count - 1; i >= 0; i--) { PrinterMachineInstruction line = GCodeCommandQueue[i]; accumulatedTime += line.secondsThisLine; line.secondsToEndFromHere = (float)accumulatedTime; } }
private void ParseGLine(string lineString, PrinterMachineInstruction processingMachineState) { // take off any comments before we check its length int commentIndex = lineString.IndexOf(';'); if (commentIndex != -1) { lineString = lineString.Substring(0, commentIndex); } string[] splitOnSpace = lineString.Split(' '); string onlyNumber = splitOnSpace[0].Substring(1).Trim(); switch (onlyNumber) { case "0": goto case "1"; case "4": case "04": // wait a given number of miliseconds break; case "1": // get the x y z to move to { double valueX = 0; if (GCodeFile.GetFirstNumberAfter("X", lineString, ref valueX)) { processingMachineState.X = valueX; } double valueY = 0; if (GCodeFile.GetFirstNumberAfter("Y", lineString, ref valueY)) { processingMachineState.Y = valueY; } double valueZ = 0; if (GCodeFile.GetFirstNumberAfter("Z", lineString, ref valueZ)) { processingMachineState.Z = valueZ; } double valueE = 0; if (GCodeFile.GetFirstNumberAfter("E", lineString, ref valueE)) { if (processingMachineState.movementType == PrinterMachineInstruction.MovementTypes.Absolute) { processingMachineState.EPosition = valueE + amountOfAccumulatedEWhileParsing; } else { processingMachineState.EPosition += valueE; } } double valueF = 0; if (GCodeFile.GetFirstNumberAfter("F", lineString, ref valueF)) { processingMachineState.FeedRate = valueF; } } if (!gcodeHasExplicitLayerChangeInfo) { if (processingMachineState.Z != parsingLastZ || indexOfChangeInZ.Count == 0) { // if we changed z or there is a movement and we have never started a layer index indexOfChangeInZ.Add(GCodeCommandQueue.Count); } } parsingLastZ = processingMachineState.Position.z; break; case "10": // firmware retract break; case "11": // firmware unretract break; case "21": // set to metric break; case "28": // G28 Return to home position (machine zero, aka machine reference point) break; case "29": // G29 Probe the z-bed in 3 places break; case "30": // G30 Probe z in current position break; case "90": // G90 is Absolute Distance Mode processingMachineState.movementType = PrinterMachineInstruction.MovementTypes.Absolute; break; case "91": // G91 is Incremental Distance Mode processingMachineState.movementType = PrinterMachineInstruction.MovementTypes.Relative; break; case "92": // set current head position values (used to reset origin) double ePosition = 0; if (GetFirstNumberAfter("E", lineString, ref ePosition)) { // remember how much e position we just gave up amountOfAccumulatedEWhileParsing = (processingMachineState.EPosition - ePosition); } break; case "130": //Set Digital Potentiometer value break; case "161": // home x,y axis minimum break; case "162": // home z axis maximum break; default: break; } }
public static string ApplyLeveling(string lineBeingSent, Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode) { if (PrinterConnectionAndCommunication.Instance.ActivePrinter != null && PrinterConnectionAndCommunication.Instance.ActivePrinter.DoPrintLeveling && (lineBeingSent.StartsWith("G0 ") || lineBeingSent.StartsWith("G1 "))) { lineBeingSent = PrintLevelingPlane.Instance.ApplyLeveling(currentDestination, movementMode, lineBeingSent); } return lineBeingSent; }
public abstract void Add(PrinterMachineInstruction printerMachineInstruction);
public void Add(PrinterMachineInstruction printerMachineInstruction) { Insert(LineCount, printerMachineInstruction); }
public override void Add(PrinterMachineInstruction printerMachineInstruction) { readLinesRingBuffer[readLineCount % MaxLinesToBuffer] = printerMachineInstruction; readLineCount++; }
public void Add(PrinterMachineInstruction printerMachineInstruction) { Insert(Count, printerMachineInstruction); }
public static void ParseFileContents(object sender, DoWorkEventArgs doWorkEventArgs) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; string gCodeString = (string)doWorkEventArgs.Argument; if (gCodeString == null) { return; } Stopwatch loadTime = Stopwatch.StartNew(); BackgroundWorker backgroundWorker = sender as BackgroundWorker; Stopwatch maxProgressReport = new Stopwatch(); maxProgressReport.Start(); PrinterMachineInstruction machineInstructionForLine = new PrinterMachineInstruction("None"); bool gcodeHasExplicitLayerChangeInfo = false; if (gCodeString.Contains("LAYER:")) { gcodeHasExplicitLayerChangeInfo = true; } GCodeFileLoaded loadedGCodeFile = new GCodeFileLoaded(gcodeHasExplicitLayerChangeInfo); int crCount = CountNumLines(gCodeString); int lineIndex = 0; foreach (string outputString in CustomSplit(gCodeString, '\n')) { string lineString = outputString.Trim(); machineInstructionForLine = new PrinterMachineInstruction(lineString, machineInstructionForLine, false); if (lineString.Length > 0) { switch (lineString[0]) { case 'G': loadedGCodeFile.ParseGLine(lineString, machineInstructionForLine); break; case 'M': loadedGCodeFile.ParseMLine(lineString, machineInstructionForLine); break; case 'T': double extruderIndex = 0; if (GetFirstNumberAfter("T", lineString, ref extruderIndex)) { machineInstructionForLine.ExtruderIndex = (int)extruderIndex; } break; case ';': if (gcodeHasExplicitLayerChangeInfo && IsLayerChange(lineString)) { loadedGCodeFile.IndexOfChangeInZ.Add(loadedGCodeFile.GCodeCommandQueue.Count); } if (lineString.StartsWith("; layerThickness")) { loadedGCodeFile.layerThickness = double.Parse(lineString.Split('=')[1]); } else if (lineString.StartsWith("; firstLayerThickness")) { loadedGCodeFile.firstLayerThickness = double.Parse(lineString.Split('=')[1]); } break; case '@': break; default: #if DEBUG throw new NotImplementedException(); #else break; #endif } } loadedGCodeFile.GCodeCommandQueue.Add(machineInstructionForLine); if (backgroundWorker != null) { if (backgroundWorker.CancellationPending) { return; } if (backgroundWorker.WorkerReportsProgress && maxProgressReport.ElapsedMilliseconds > 200) { backgroundWorker.ReportProgress(lineIndex * 100 / crCount / 2); maxProgressReport.Restart(); } } lineIndex++; } loadedGCodeFile.AnalyzeGCodeLines(backgroundWorker); doWorkEventArgs.Result = loadedGCodeFile; loadTime.Stop(); Console.WriteLine("Time To Load Seconds: {0:0.00}".FormatWith(loadTime.Elapsed.TotalSeconds)); }
public static string ApplyLeveling(string lineBeingSent, Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode) { var settings = ActiveSliceSettings.Instance; if (settings?.DoPrintLeveling == true && (lineBeingSent.StartsWith("G0 ") || lineBeingSent.StartsWith("G1 "))) { lineBeingSent = PrintLevelingPlane.Instance.ApplyLeveling(currentDestination, movementMode, lineBeingSent); } return lineBeingSent; }
private void AnalyzeGCodeLines(BackgroundWorker backgroundWorker = null) { double feedRateMmPerMin = 0; Vector3 lastPrinterPosition = new Vector3(); double lastEPosition = 0; Stopwatch maxProgressReport = new Stopwatch(); maxProgressReport.Start(); for (int lineIndex = 0; lineIndex < GCodeCommandQueue.Count; lineIndex++) { PrinterMachineInstruction instruction = GCodeCommandQueue[lineIndex]; string line = instruction.Line; Vector3 deltaPositionThisLine = new Vector3(); double deltaEPositionThisLine = 0; string lineToParse = line.ToUpper().Trim(); if (lineToParse.StartsWith("G0") || lineToParse.StartsWith("G1")) { double newFeedRateMmPerMin = 0; if (GetFirstNumberAfter("F", lineToParse, ref newFeedRateMmPerMin)) { feedRateMmPerMin = newFeedRateMmPerMin; } Vector3 attemptedDestination = lastPrinterPosition; GetFirstNumberAfter("X", lineToParse, ref attemptedDestination.x); GetFirstNumberAfter("Y", lineToParse, ref attemptedDestination.y); GetFirstNumberAfter("Z", lineToParse, ref attemptedDestination.z); double ePosition = lastEPosition; GetFirstNumberAfter("E", lineToParse, ref ePosition); deltaPositionThisLine = attemptedDestination - lastPrinterPosition; deltaEPositionThisLine = Math.Abs(ePosition - lastEPosition); lastPrinterPosition = attemptedDestination; lastEPosition = ePosition; } else if (lineToParse.StartsWith("G92")) { double ePosition = 0; if (GetFirstNumberAfter("E", lineToParse, ref ePosition)) { lastEPosition = ePosition; } } if (feedRateMmPerMin > 0) { instruction.secondsThisLine = (float)GetSecondsThisLine(deltaPositionThisLine, deltaEPositionThisLine, feedRateMmPerMin); } if (backgroundWorker != null) { if (backgroundWorker.CancellationPending) { return; } if (backgroundWorker.WorkerReportsProgress && maxProgressReport.ElapsedMilliseconds > 200) { backgroundWorker.ReportProgress(lineIndex * 100 / GCodeCommandQueue.Count / 2 + 50); maxProgressReport.Restart(); } } } double accumulatedTime = 0; for (int i = GCodeCommandQueue.Count - 1; i >= 0; i--) { PrinterMachineInstruction line = GCodeCommandQueue[i]; accumulatedTime += line.secondsThisLine; line.secondsToEndFromHere = (float)accumulatedTime; } }
public static void ParseFileContents(object sender, DoWorkEventArgs doWorkEventArgs) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; string gCodeString = (string)doWorkEventArgs.Argument; if (gCodeString == null) { return; } BackgroundWorker backgroundWorker = sender as BackgroundWorker; Stopwatch maxProgressReport = new Stopwatch(); maxProgressReport.Start(); PrinterMachineInstruction machineInstructionForLine = new PrinterMachineInstruction("None"); bool gcodeHasExplicitLayerChangeInfo = false; if (gCodeString.Contains("; LAYER:")) { gcodeHasExplicitLayerChangeInfo = true; } GCodeFile loadedGCodeFile = new GCodeFile(gcodeHasExplicitLayerChangeInfo); int crCount = CountNumLines(gCodeString); int lineIndex = 0; foreach (string outputString in CustomSplit(gCodeString, '\n')) { string lineString = outputString.Trim(); machineInstructionForLine = new PrinterMachineInstruction(lineString, machineInstructionForLine); // take off any comments before we check its length if (lineString.Length > 0) { switch (lineString[0]) { case 'M': loadedGCodeFile.ParseMLine(lineString, machineInstructionForLine); break; case 'G': loadedGCodeFile.ParseGLine(lineString, machineInstructionForLine); break; case ';': if (gcodeHasExplicitLayerChangeInfo && lineString.StartsWith("; LAYER:")) { loadedGCodeFile.IndexOfChangeInZ.Add(loadedGCodeFile.GCodeCommandQueue.Count); } if(lineString.StartsWith("; layerThickness")) { loadedGCodeFile.layerThickness = double.Parse(lineString.Split('=')[1]); } else if(lineString.StartsWith("; firstLayerThickness")) { loadedGCodeFile.firstLayerThickness = double.Parse(lineString.Split('=')[1]); } break; default: break; } } loadedGCodeFile.GCodeCommandQueue.Add(machineInstructionForLine); if (backgroundWorker != null) { if (backgroundWorker.CancellationPending) { return; } if (backgroundWorker.WorkerReportsProgress && maxProgressReport.ElapsedMilliseconds > 200) { backgroundWorker.ReportProgress(lineIndex * 100 / crCount / 2); maxProgressReport.Restart(); } } lineIndex++; } loadedGCodeFile.AnalyzeGCodeLines(backgroundWorker); doWorkEventArgs.Result = loadedGCodeFile; }
private void ParseMLine(string lineString, PrinterMachineInstruction processingMachineState) { // take off any comments before we check its length int commentIndex = lineString.IndexOf(';'); if (commentIndex != -1) { lineString = lineString.Substring(0, commentIndex); } string[] splitOnSpace = lineString.Split(' '); switch (splitOnSpace[0].Substring(1).Trim()) { case "01": // show a message? break; case "6": // wait for tool to heat up (wait for condition?) break; case "101": // extrude on, forward break; case "18": // turn off stepers break; case "42": // Stop on material exhausted / Switch I/O pin break; case "72": // makerbot, Play tone or song break; case "73": // makerbot, Manually set build percentage break; case "82": // set extruder to absolute mode break; case "83": //Set extruder to relative mode break; case "84": // lineString = "M84 ; disable motors\r" break; case "92": // set steps per mm break; case "102": // extrude on reverse break; case "103": // extrude off break; case "104": // set extruder tempreature break; case "105": // M105 Custom code for temperature reading. (Not used) break; case "106": // turn fan on break; case "107": // turn fan off break; case "108": // set extruder speed break; case "109": // set heated platform temperature break; case "114": break; case "117": // in Marlin: Display Message break; case "126": // enable fan (makerbot) break; case "127": // disable fan (makerbot) break; case "132": // recall stored home offsets for axis xyzab break; case "133": // MakerBot wait for toolhead to heat break; case "134": // MakerBot wait for platform to reach target temp break; case "135": // MakerBot change toolhead break; case "140": // set bed temperature break; case "190": // wait for bed temperature to be reached break; case "200": // M200 sets the filament diameter. break; case "201": // set axis acceleration break; case "204": // - Set default acceleration break; case "207": // M207: calibrate z axis by detecting z max length break; case "208": // M208: set axis max travel break; case "209": // M209: enable automatic retract break; case "210": // Set homing rate break; case "226": // user request pause break; case "227": // Enable Automatic Reverse and Prime break; case "301": break; case "400": // Wait for current moves to finish break; case "565": // M565: Set Z probe offset break; case "1200": //M1200 Makerbot Fake gCode command for start build notification break; case "1201": //M1201 Makerbot Fake gCode command for end build notification break; case "1202": //M1202 Makerbot Fake gCode command for reset board break; default: break; } }
private void ParseMLine(string lineString, PrinterMachineInstruction processingMachineState) { // take off any comments before we check its length int commentIndex = lineString.IndexOf(';'); if (commentIndex != -1) { lineString = lineString.Substring(0, commentIndex); } string[] splitOnSpace = lineString.Split(' '); switch (splitOnSpace[0].Substring(1).Trim()) { case "01": // show a message? break; case "6": // wait for tool to heat up (wait for condition?) break; case "101": // extrude on, forward break; case "18": // turn off stepers break; case "42": // Stop on material exhausted / Switch I/O pin break; case "73": // makerbot, Manually set build percentage break; case "82": // set extruder to absolute mode break; case "84": // lineString = "M84 ; disable motors\r" break; case "92": // set steps per mm break; case "102": // extrude on reverse break; case "103": // extrude off break; case "104": // set extruder tempreature break; case "105": // M105 Custom code for temperature reading. (Not used) break; case "106": // turn fan on break; case "107": // turn fan off break; case "108": // set extruder speed break; case "109": // set heated platform temperature break; case "114": break; case "117": // in Marlin: Display Message break; case "126": // enable fan (makerbot) break; case "127": // disable fan (makerbot) break; case "132": // recall stored home offsets for axis xyzab break; case "140": // set bed temperature break; case "190": // wait for bed temperature to be reached break; case "200": // M200 sets the filament diameter. break; case "201": // set axis acceleration break; case "204": // - Set default acceleration break; case "207": // M207: calibrate z axis by detecting z max length break; case "208": // M208: set axis max travel break; case "209": // M209: enable automatic retract break; case "210": // Set homing rate break; case "226": // user request pause break; case "227": // Enable Automatic Reverse and Prime break; case "301": break; case "400": // Wait for current moves to finish break; case "565": // M565: Set Z probe offset break; case "1200"://M1200 Makerbot Fake gCode command for start build notification break; case "1201"://M1201 Makerbot Fake gCode command for end build notification break; case "1202"://M1202 Makerbot Fake gCode command for reset board break; #if DEBUG default: throw new NotImplementedException(lineString); #else default: break; #endif } }
public override PrinterMachineInstruction Instruction(int index) { lock(locker) { if (index < readLineCount - MaxLinesToBuffer) { throw new Exception("You are asking for a line we no longer have bufferd"); } while (index >= readLineCount) { string line = openGcodeStream.ReadLine(); if (line == null) { readLastLineOfFile = true; line = ""; } int ringBufferIndex = readLineCount % MaxLinesToBuffer; readLinesRingBuffer[ringBufferIndex] = new PrinterMachineInstruction(line); PrinterMachineInstruction instruction = readLinesRingBuffer[ringBufferIndex]; Vector3 deltaPositionThisLine = new Vector3(); double deltaEPositionThisLine = 0; string lineToParse = line.ToUpper().Trim(); if (lineToParse.StartsWith("G0") || lineToParse.StartsWith("G1")) { double newFeedRateMmPerMin = 0; if (GetFirstNumberAfter("F", lineToParse, ref newFeedRateMmPerMin)) { feedRateMmPerMin = newFeedRateMmPerMin; } Vector3 attemptedDestination = lastPrinterPosition; GetFirstNumberAfter("X", lineToParse, ref attemptedDestination.x); GetFirstNumberAfter("Y", lineToParse, ref attemptedDestination.y); GetFirstNumberAfter("Z", lineToParse, ref attemptedDestination.z); double ePosition = lastEPosition; GetFirstNumberAfter("E", lineToParse, ref ePosition); deltaPositionThisLine = attemptedDestination - lastPrinterPosition; deltaEPositionThisLine = Math.Abs(ePosition - lastEPosition); lastPrinterPosition = attemptedDestination; lastEPosition = ePosition; } else if (lineToParse.StartsWith("G92")) { double ePosition = 0; if (GetFirstNumberAfter("E", lineToParse, ref ePosition)) { lastEPosition = ePosition; } } if (feedRateMmPerMin > 0) { instruction.secondsThisLine = (float)GetSecondsThisLine(deltaPositionThisLine, deltaEPositionThisLine, feedRateMmPerMin); } readLineCount++; } } return readLinesRingBuffer[index % MaxLinesToBuffer]; }
public static string ApplyLeveling(string lineBeingSent, Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode) { if (PrinterConnectionAndCommunication.Instance.ActivePrinter != null && PrinterConnectionAndCommunication.Instance.ActivePrinter.DoPrintLeveling && (lineBeingSent.StartsWith("G0 ") || lineBeingSent.StartsWith("G1 ")) && lineBeingSent.Length > 2 && lineBeingSent[2] == ' ') { double extruderDelta = 0; GCodeFile.GetFirstNumberAfter("E", lineBeingSent, ref extruderDelta); double feedRate = 0; GCodeFile.GetFirstNumberAfter("F", lineBeingSent, ref feedRate); StringBuilder newLine = new StringBuilder("G1 "); if (lineBeingSent.Contains("X") || lineBeingSent.Contains("Y") || lineBeingSent.Contains("Z")) { PrintLevelingData levelingData = PrintLevelingData.GetForPrinter(ActivePrinterProfile.Instance.ActivePrinter); Vector3 outPosition = GetPositionWithZOffset(currentDestination, levelingData); if (movementMode == PrinterMachineInstruction.MovementTypes.Relative) { // TODO: this is not correct for 13 point leveling Vector3 relativeMove = Vector3.Zero; GCodeFile.GetFirstNumberAfter("X", lineBeingSent, ref relativeMove.x); GCodeFile.GetFirstNumberAfter("Y", lineBeingSent, ref relativeMove.y); GCodeFile.GetFirstNumberAfter("Z", lineBeingSent, ref relativeMove.z); outPosition = PrintLevelingPlane.Instance.ApplyLevelingRotation(relativeMove); } newLine = newLine.Append(String.Format("X{0:0.##} Y{1:0.##} Z{2:0.###}", outPosition.x, outPosition.y, outPosition.z)); } if (extruderDelta != 0) { newLine = newLine.Append(String.Format(" E{0:0.###}", extruderDelta)); } if (feedRate != 0) { newLine = newLine.Append(String.Format(" F{0:0.##}", feedRate)); } lineBeingSent = newLine.ToString(); return lineBeingSent; } return lineBeingSent; }
private void ParseGLine(string lineString, PrinterMachineInstruction processingMachineState) { // take off any comments before we check its length int commentIndex = lineString.IndexOf(';'); if (commentIndex != -1) { lineString = lineString.Substring(0, commentIndex); } string[] splitOnSpace = lineString.Split(' '); string onlyNumber = splitOnSpace[0].Substring(1).Trim(); switch (onlyNumber) { case "0": goto case "1"; case "4": case "04": // wait a given number of miliseconds break; case "1": // get the x y z to move to { double valueX = 0; if (GCodeFile.GetFirstNumberAfter("X", lineString, ref valueX)) { processingMachineState.X = valueX; } double valueY = 0; if (GCodeFile.GetFirstNumberAfter("Y", lineString, ref valueY)) { processingMachineState.Y = valueY; } double valueZ = 0; if (GCodeFile.GetFirstNumberAfter("Z", lineString, ref valueZ)) { processingMachineState.Z = valueZ; } double valueE = 0; if (GCodeFile.GetFirstNumberAfter("E", lineString, ref valueE)) { if (processingMachineState.movementType == PrinterMachineInstruction.MovementTypes.Absolute) { processingMachineState.EPosition = valueE + amountOfAccumulatedEWhileParsing; } else { processingMachineState.EPosition += valueE; } } double valueF = 0; if (GCodeFile.GetFirstNumberAfter("F", lineString, ref valueF)) { processingMachineState.FeedRate = valueF; } } if (!gcodeHasExplicitLayerChangeInfo) { if (processingMachineState.Z != parsingLastZ || indexOfChangeInZ.Count == 0) { // if we changed z or there is a movement and we have never started a layer index indexOfChangeInZ.Add(GCodeCommandQueue.Count); } } parsingLastZ = processingMachineState.Position.z; break; case "10": // firmware retract break; case "11": // firmware unretract break; case "21": // set to metric break; case "28": // G28 Return to home position (machine zero, aka machine reference point) break; case "29": // G29 Probe the z-bed in 3 places break; case "30": // G30 Probe z in current position break; case "90": // G90 is Absolute Distance Mode processingMachineState.movementType = PrinterMachineInstruction.MovementTypes.Absolute; break; case "91": // G91 is Incremental Distance Mode processingMachineState.movementType = PrinterMachineInstruction.MovementTypes.Relative; break; case "92": // set current head position values (used to reset origin) double ePosition = 0; if (GetFirstNumberAfter("E", lineString, ref ePosition)) { // remember how much e position we just gave up amountOfAccumulatedEWhileParsing = (processingMachineState.EPosition - ePosition); } break; case "161": // home x,y axis minimum break; case "162": // home z axis maximum break; #if DEBUG default: throw new NotImplementedException(); #else default: break; #endif } }
public string DoApplyLeveling(string lineBeingSent, Vector3 currentDestination, PrinterMachineInstruction.MovementTypes movementMode) { double extruderDelta = 0; GCodeFile.GetFirstNumberAfter("E", lineBeingSent, ref extruderDelta); double feedRate = 0; GCodeFile.GetFirstNumberAfter("F", lineBeingSent, ref feedRate); StringBuilder newLine = new StringBuilder("G1 "); if (lineBeingSent.Contains("X") || lineBeingSent.Contains("Y") || lineBeingSent.Contains("Z")) { Vector3 outPosition = GetPositionWithZOffset(currentDestination); if (movementMode == PrinterMachineInstruction.MovementTypes.Relative) { Vector3 delta = outPosition - lastDestinationWithLevelingApplied; lastDestinationWithLevelingApplied = outPosition; outPosition = delta; } else { lastDestinationWithLevelingApplied = outPosition; } newLine = newLine.Append(String.Format("X{0:0.##} Y{1:0.##} Z{2:0.###}", outPosition.x, outPosition.y, outPosition.z)); } if (extruderDelta != 0) { newLine = newLine.Append(String.Format(" E{0:0.###}", extruderDelta)); } if (feedRate != 0) { newLine = newLine.Append(String.Format(" F{0:0.##}", feedRate)); } lineBeingSent = newLine.ToString(); return lineBeingSent; }
public override void Add(PrinterMachineInstruction printerMachineInstruction) { Insert(LineCount, printerMachineInstruction); }
public override void Insert(int insertIndex, PrinterMachineInstruction printerMachineInstruction) { for (int i = 0; i < indexOfChangeInZ.Count; i++) { if (insertIndex < indexOfChangeInZ[i]) { indexOfChangeInZ[i]++; } } GCodeCommandQueue.Insert(insertIndex, printerMachineInstruction); }