Cura Script to Automatically Probe Only Printed Area
-
If anyone is interested, my friend and I developed a Cura post processing script (he did the hard part). I really think this would be better off a firmware feature, like I wrote a request for. But, in the meanwhile, for those using Cura:
You pass it a single parameter (mesh spacing value), and it parses the first layer gcode for min/max X and Y coordinates, and then replaces the M557 line in your start gcode.
Just remove the .txt, and drop it here: C:\Program Files\Ultimaker Cura 4.5.0\plugins\PostProcessingPlugin\scripts\
You must have a static mesh leveling command in your start gcode, like: M557 X0:200 Y0:200 S20
-
.
. -
That's a great post processing script. Thanks for sharing.
-
Thought it would be a fun project to learn Python and modified CCS86's script to work with Simplify3D. It was created with Python 3.8.1 on a Mac running Catalina and S3D 4.1.2 and tested with a 6mb gcode file. It will not work with Python2.
All you should need to do is copy the script to your computer (removing the .txt), make sure your starting script contains probing grid definition (ie M557 X30:300 Y30:300 S13.5) and add the following to the post processing.
python3 <full path to folder>/meshgrid.py "[output_filepath]" (quotes around [output_filepath] are manditory)
The script will read the first layer to obtain the print boundaries, verify it fits within the bed size specified in S3D, find the existing M557 and rewrite the min and max X Y coordinates. It might need some fine-tuning if used on a printer with 0,0 in the center of the bed.
Enjoy!
Edit: The forum server is not allowing the upload of txt files. Paste the code below into a text editor and save it as meshgrid.py .
#!/usr/bin/env python3 """Simplify3D post-processing script for RepRap firmware printers which dynamically defines the mesh grid dimensions (M557) based on the print dimensions. Usage: Within Simplify3D > Process Settings > Scripts > Post Processing > add the following command: python3 <script_location>/meshgrid.py "[output_filepath]" Starting script must contain M557 Command (ie M557 X30:300 Y30:300 P20). Args: Path: Complete path to the gcode file created by Simplify 3d. Requirements: Tested using Python 3.8.1. Credit: Adapted from code originally posted by CCS86 on https://forum.duet3d.com/topic/15302/cura-script-to-automatically-probe-only-printed-area?_=1587348242875. """ import sys import re import math def main(filename): try: _s3dFile = open(filename, encoding='utf-8') except TypeError: try: _s3dFile = open(filename) except: print("Open file exception. Exiting meshgrid.py.") sys.exit() except FileNotFoundError: print('File not found. Exiting meshgrid.py.') sys.exit() lines = _s3dFile.readlines() _s3dFile.close() linesNew = calcBed(lines) _s3dFileNew = open(filename, "r+") _s3dFileNew.seek(0) _s3dFileNew.truncate() for element in linesNew: _s3dFileNew.write(element) _s3dFileNew.close() return def calcBed(lines): bounds = findBounds(lines) bed = findBed(lines) for axis in bounds: if bounds[axis]['max'] - bounds[axis]['min'] < bed[axis]: print(f'Success: {axis} mesh is smaller than bed') else: print('Error: Mesh is larger than bed. Exiting meshgrid.py.') sys.exit() for limit in bounds[axis]: if limit == 'min': if (bed[axis] / 2) - bounds[axis][limit] > 0: print (f'Success: {axis} {limit} coordinate is on the bed.') else: print (f'Error: {axis} {limit} coordinate is off the bed. Exiting meshgrid.py.') sys.exit() if limit == 'max': if (bed[axis]) - bounds[axis][limit] > 0: print (f'Success: {axis} {limit} coordinate is on the bed.') else: print (f'Error: {axis} {limit} coordinate is off the bed. Exiting meshgrid.py.') sys.exit() return fillGrid(bounds, lines) def findBed(lines): bed = { 'X': 0, 'Y': 0, } for line in lines: if line.startswith('; strokeXoverride,'): bed['X'] = int(re.search(r'\d.+\S', line).group()) elif line.startswith('; strokeYoverride,'): bed['Y'] = int(re.search(r'\d.+', line).group()) break return bed def findBounds(lines): bounds = { 'X': {'min': 9999, 'max': 0}, 'Y': {'min': 9999, 'max': 0}, } parsing = False for line in lines: if line.startswith('; layer 1,'): parsing = True continue elif line.startswith('; layer 2,'): break if parsing: # Get coordinates on this line for match in re.findall(r'([YX])([\d.]+)\s', line): # Get axis letter axis = match[0] # Skip axes we don't care about if axis not in bounds: continue # Parse parameter value value = float(match[1]) # Update bounds bounds[axis]['min'] = math.floor(min(bounds[axis]['min'], value)) bounds[axis]['max'] = math.ceil(max(bounds[axis]['max'], value)) return bounds def fillGrid(bounds, lines): # Fill in the level command template gridNew = 'M557 X%d:%d Y%d:%d' % ( bounds['X']['min'], bounds['X']['max'], bounds['Y']['min'], bounds['Y']['max'], ) # Replace M557 command in GCODE linesNew = [] for line in lines: if line.startswith('M557'): linesNew.append(re.sub(r'^M557 X\d+:\d+ Y\d+:\d+', gridNew, line, flags=re.MULTILINE)) else: linesNew.append(line) return linesNew if __name__ == '__main__': if sys.argv[1]: main(filename = sys.argv[1]) else: print('Error: Proper s3d post processing command is python3 <script_location>/meshgrid.py "[output_filepath]". Exiting meshgrid.py.') sys.exit()
-
Thanks @CCS86, what a brilliant idea, and @mwolter, thanks, I used most of your code and got it working on Slic3r.
Works just great.
I never used mesh leveling because of the time involved probing the entire bed before printing. However, now I can, and I'm getting great first layer results.
Cheers guys.
-
Care to share?
-
@Luke-sLaboratory said in Cura Script to Automatically Probe Only Printed Area:
Care to share?
I was afraid that someone would ask that.
Its butt-ugly code right now. Let me clean it up and I'll post it here. -
For @Luke-sLaboratory.
This is @mwolter 's code modified to work with Slic3r, PrusaSlicer or Slic3r++. Follow the instructions in the comments to configure Slic3r.
Slightly changed so that the minimum size of the mesh is 3x3 on prints with small base size.
#!/usr/bin/python """ Slic3r post-processing script for RepRap firmware printers which dynamically defines the mesh grid dimensions (M557) based on the print dimensions. {1} Usage: {1} Slic3r Settings: In Print Settings > Output Options 1. turn no "Verbose G-code" 2. in "Post-processing scripts" type the full path to python and the full path to this script e.g. <Python Path>\python.exe <Script Path>\meshcalc.py; In Printer Settings > Custom G-code > Start G-code Make sure the start g-code contains the M557 command, and that you probe the bed and load the compensation map, e.g. M557 X10:290 Y10:290 S20 ; Setup default grid G29 ; Mesh bed probe G29 S1 ; Load compensation map Script Settings probeSpacing = 20 - change this to the preferred probe point spacing in M557 Note: The minimum X and Y of the probed area is limited to 2 times the probeSpacing. This is so that prints with a small footprint will have a minimum 3x3 probe mesh {1} Args: {1} Path: The path parameter will be provided by Slic3r. {1} Requirements: {1} The latest version of Python. Note that I use this on windows and haven't tried it on any other platform. Also this script assumes that the bed origin (0,0) is NOT the centre of the bed. Go ahead and modify this script as required. {1} Credit: {1} Based on code originally posted by CCS86 on https://forum.duet3d.com/topic/15302/cura-script-to-automatically-probe-only-printed-area?_=1587348242875. and maybe 90% or more is code posted by MWOLTER on the same thread. Thank you both. """ import sys import re import math import os probeSpacing = 20 # set your required probe point spacing for M557 def main(fname): print("Starting Mesh Calculations") try: _Slic3rFile = open(fname, encoding='utf-8') except TypeError: try: _Slic3rFile = open(fname) except: print("Open file exception. Exiting.") error() except FileNotFoundError: print('File not found. Exiting.') error() lines = _Slic3rFile.readlines() _Slic3rFile.close() linesNew = calcBed(lines) _Slic3rFile = open(fname, "r+") _Slic3rFile.seek(0) _Slic3rFile.truncate() for element in linesNew: _Slic3rFile.write(element) _Slic3rFile.close() return def error(): # remove the next 2 lines to close console automatically print("Press Enter to close") input() sys.exit() def calcBed(lines): bounds = findBounds(lines) bed = findBed() for axis in bounds: if bounds[axis]['max'] - bounds[axis]['min'] < bed[axis]: print(f'Success: {axis} mesh is smaller than bed') else: print('Error: Mesh is larger than bed. Exiting.') error() for limit in bounds[axis]: if limit == 'min': if (bed[axis]) - bounds[axis][limit] > 0: print(f'Success: {axis} {limit} coordinate is on the bed.') else: print(f'Error: {axis} {limit} coordinate is off the bed. Exiting.') error() if limit == 'max': if (bed[axis]) - bounds[axis][limit] > 0: print(f'Success: {axis} {limit} coordinate is on the bed.') else: print(f'Error: {axis} {limit} coordinate is off the bed. Exiting.') error() return fillGrid(bounds, lines) def findBed(): bed = { 'X': 0, 'Y': 0, } bedCorners = os.environ.get("SLIC3R_BED_SHAPE") maxXY = bedCorners.split(',')[2].split('x') bed['X'] = int(maxXY[0]) bed['Y'] = int(maxXY[1]) print(bed) return bed def findBounds(lines): bounds = { 'X': {'min': 9999, 'max': 0}, 'Y': {'min': 9999, 'max': 0}, } parsing = False for line in lines: if "move to next layer (0)" in line: parsing = True continue elif "move to next layer (1)" in line: break if parsing: # Get coordinates on this line for match in re.findall(r'([YX])([\d.]+)\s', line): # Get axis letter axis = match[0] # Skip axes we don't care about if axis not in bounds: continue # Parse parameter value value = float(match[1]) # Update bounds bounds[axis]['min'] = math.floor(min(bounds[axis]['min'], value)) bounds[axis]['max'] = math.ceil(max(bounds[axis]['max'], value)) # make sure the bounds are at least 2 x Probe Point Spacing, for small prints. if parsing: global probeSpacing for axis in bounds: spacing = (bounds[axis]['max'] - bounds[axis]['min'])/2 if spacing < probeSpacing: probeSpacing = spacing print("Bounds are: " + str(bounds)) return bounds def fillGrid(bounds, lines): # Fill in the level command template gridNew = 'M557 X%d:%d Y%d:%d S%d' % ( bounds['X']['min'], bounds['X']['max'], bounds['Y']['min'], bounds['Y']['max'], probeSpacing ) # Replace M557 command in GCODE linesNew = [] for line in lines: if line.startswith('M557'): linesNew.append(re.sub(r'^M557 X\d+:\d+ Y\d+:\d+ S\d+', gridNew, line, flags=re.MULTILINE)) print('New M557: ' + linesNew[-1]) else: linesNew.append(line) return linesNew if __name__ == '__main__': if sys.argv[1]: main(fname = sys.argv[1]) else: print('Error: Proper Slic3r post processing command is python3') error()
I've updated with improvements so that the console remains open if there is an error, and the probe point spacing automatically reduces in size for small prints.
-
-
Alright - I've made an improvement to the script, I have an extra-large machine and depending on how much of the bed I'm using at any given point, I can exceed the points-per-axis limitations of duet firmware (currently 21:21). It now will run the calculations, and if there are more than 21 points required, it converts over to using the P parameter instead of the S parameter, trying to honor the original requested spacing.
#!/usr/bin/python """ Slic3r post-processing script for RepRap firmware printers which dynamically defines the mesh grid dimensions (M557) based on the print dimensions. {1} Usage: {1} Slic3r Settings: In Print Settings > Output Options 1. turn no "Verbose G-code" 2. in "Post-processing scripts" type the full path to python and the full path to this script e.g. <Python Path>\python.exe <Script Path>\meshcalc.py; {1} In Printer Settings > Custom G-code > Start G-code Make sure the start g-code contains the M557 command, and that you probe the bed and load the compensation map, e.g. M557 X10:290 Y10:290 S20 ; Setup default grid G29 ; Mesh bed probe G29 S1 ; Load compensation map Script Settings probeSpacing = 20 - change this to the preferred probe point spacing in M557 Note: The minimum X and Y of the probed area is limited to 2 times the probeSpacing. This is so that prints with a small footprint will have a minimum 3x3 probe mesh {1} Args: {1} Path: The path parameter will be provided by Slic3r. {1} Requirements: {1} The latest version of Python. Note that I use this on windows and haven't tried it on any other platform. Also this script assumes that the bed origin (0,0) is NOT the centre of the bed. Go ahead and modify this script as required. {1} Credit: {1} Based on code originally posted by CCS86 on https://forum.duet3d.com/topic/15302/cura-script-to-automatically-probe-only-printed-area?_=1587348242875. and maybe 90% or more is code posted by MWOLTER on the same thread. Thank you both. """ import sys import re import math import os probeSpacing = 20 # set your required probe point spacing for M557 def main(fname): print("Starting Mesh Calculations") try: _Slic3rFile = open(fname, encoding='utf-8') except TypeError: try: _Slic3rFile = open(fname) except: print("Open file exception. Exiting.") error() except FileNotFoundError: print('File not found. Exiting.') error() lines = _Slic3rFile.readlines() _Slic3rFile.close() linesNew = calcBed(lines) _Slic3rFile = open(fname, "r+") _Slic3rFile.seek(0) _Slic3rFile.truncate() for element in linesNew: _Slic3rFile.write(element) _Slic3rFile.close() return def error(): # remove the next 2 lines to close console automatically print("Press Enter to close") input() sys.exit() def calcBed(lines): bounds = findBounds(lines) bed = findBed() for axis in bounds: if bounds[axis]['max'] - bounds[axis]['min'] < bed[axis]: print(f'Success: {axis} mesh is smaller than bed') else: print('Error: Mesh is larger than bed. Exiting.') error() for limit in bounds[axis]: if limit == 'min': if (bed[axis]) - bounds[axis][limit] > 0: print(f'Success: {axis} {limit} coordinate is on the bed.') else: print(f'Error: {axis} {limit} coordinate is off the bed. Exiting.') error() if limit == 'max': if (bed[axis]) - bounds[axis][limit] > 0: print(f'Success: {axis} {limit} coordinate is on the bed.') else: print(f'Error: {axis} {limit} coordinate is off the bed. Exiting.') error() return fillGrid(bounds, lines) def findBed(): bed = { 'X': 0, 'Y': 0, } bedCorners = os.environ.get("SLIC3R_BED_SHAPE") maxXY = bedCorners.split(',')[2].split('x') bed['X'] = int(maxXY[0]) bed['Y'] = int(maxXY[1]) print(bed) return bed def findBounds(lines): bounds = { 'X': {'min': 9999, 'max': 0}, 'Y': {'min': 9999, 'max': 0}, } parsing = False for line in lines: if "move to next layer (0)" in line: parsing = True continue elif "move to next layer (1)" in line: break if parsing: # Get coordinates on this line for match in re.findall(r'([YX])([\d.]+)\s', line): # Get axis letter axis = match[0] # Skip axes we don't care about if axis not in bounds: continue # Parse parameter value value = float(match[1]) # Update bounds bounds[axis]['min'] = math.floor(min(bounds[axis]['min'], value)) bounds[axis]['max'] = math.ceil(max(bounds[axis]['max'], value)) # make sure the bounds are at least 2 x Probe Point Spacing, for small prints. # also, make sure that the maximum amount of points isn't exceeded. if parsing: global probeSpacing for axis in bounds: spacing = (bounds[axis]['max'] - bounds[axis]['min'])/2 if spacing < probeSpacing: probeSpacing = spacing print("Bounds are: " + str(bounds)) return bounds def fillGrid(bounds, lines): #Check the quantity of points - cannot exceed 21points per axis, otherwise will throw error and ruin print by not running a mesh X_points=(bounds['X']['max']-bounds['X']['min'])/probeSpacing Y_points=(bounds['Y']['max']-bounds['Y']['min'])/probeSpacing if X_points>21 or Y_points>21: Points=True #basically, if its over 21, just use 21, if not, round up, keeping roughly the same spacing for the non-affected axis if X_points>21: X_points = 21 else: X_points = math.ceil(X_points) if Y_points>21: Y_points=21 else:Y_points = math.ceil(Y_points) print('With your required print footprint, you\'ll exceed 21 points on either axis, changing to point based. Your new point grid is {}:{} points'.format(X_points,Y_points)) else: Points=False if Points == True: # Fill in the level command template gridNew = 'M557 X{}:{} Y{}:{} P{}:{}'.format(bounds['X']['min'], bounds['X']['max'],bounds['Y']['min'], bounds['Y']['max'], X_points, Y_points) else: # Fill in the level command template gridNew = 'M557 X{}:{} Y{}:{} S{}'.format(bounds['X']['min'], bounds['X']['max'],bounds['Y']['min'], bounds['Y']['max'], probeSpacing) # Replace M557 command in GCODE linesNew = [] for line in lines: if line.startswith('M557'): linesNew.append(re.sub(r'^M557 X\d+:\d+ Y\d+:\d+ S\d+', gridNew, line, flags=re.MULTILINE)) print('New M557: ' + linesNew[-1]) else: linesNew.append(line) return linesNew if __name__ == '__main__': if sys.argv[1]: main(fname = sys.argv[1]) else: print('Error: Proper Slic3r post processing command is python3') error()
-
Does this work for Deltas who don't have their M557 as a x and y coordinate?
-
@Baenwort said in Cura Script to Automatically Probe Only Printed Area:
Does this work for Deltas who don't have their M557 as a x and y coordinate?
No it won't. But it could be modified.
-
@Luke-sLaboratory said in Cura Script to Automatically Probe Only Printed Area:
"move to next layer (0)"
Do we need to add to the prusaslicer gcode settings generation of layer markers or is there a setting to have it enabled automatically.
-
I setup my prusaslicer to use this script and it works very well. I looked for some time for per-print mesh automation and this one does the job. Thanks for sharing it.
The file version I am using is in the github link below. It uses utility classes to handle intervals and rectangles but otherwise it's the same flow. There are still a few TODOs but I am using it with my regular prints.
https://github.com/zapta/misc/blob/master/duet3d_automesh/duet3d_automesh.py
-
It would be great!
-
I cleaned up the python script. It now has command line flags that allow customization (set them in the slicer post processing command line).
https://github.com/zapta/misc/blob/master/duet3d_automesh/duet3d_automesh.py
I am very happy with the per-print quick partial meshing, getting good first layer without worrying about leveling. Ideally the slicers would provide the first layer's bounding box as place holders we can embed in gcode.
-
@zapta could you please change the script that it can handle negative coordinates in --meshable ?
This will make it usable for Delta printers, because
"For Cartesian printers, specify minimum and maximum X and Y values to probe and the probing interval. For Delta printers, specify the probing radius. If you define both, the probing area will be the intersection of the rectangular area and the circle. "
https://duet3d.dozuki.com/Wiki/Gcode#Section_M557_Set_Z_probe_point_or_define_probing_gridThank you
-
@tcj, I made the change. Can you give it another try?
-
@zapta thank you for the effort, but ist does not work yet
only defining the default meshable area within the script (line 50) bydefault="-185:185,-185:185"
works,
but when adding<path to your python3> <path_to_the_duet3d_automesh.py file> --meshable "-185:185,-185:185"
to the Post-processing script, it fails
-
@tcj, try this syntax for the flags (notice the '=')
--meshable=-30:250,-3:280