Commit 0a58a45f authored by leonmuller's avatar leonmuller

Merge back to master

parents 376ff061 a4ef99b1
About This Project
------------------
About This Fork Modified to output gcode that is compatible with K40 style laser cutter
--------------- running Marlin (https://github.com/lansing-makers-network/buildlog-lasercutter-marlin).
10.14.14 by ajf (https://github.com/ajfoul) 26-Feb-2015 - 2 hours : Forked from user ajfoul to extend functionality of smoothie
laser power levels 0.0 to 1.0, generic Marlin power levels being 0 to 100.
Modified to output gcode that is compatible with K40 style laser cutter running Marlin (https://github.com/lansing-makers-network/buildlog-lasercutter-marlin). 07-March-2015 - 10 hours : Cleaned up the exporters code a lot. Added ppm and feedrate detection from
the layer name. Updated the gcode that is exported to be neater and work better with
pulsed mode using G01, G02 and G03 commands.
I couldn't get the original version from LMN repo to work with LMN's Marlin as it never set the laser intensity on the M3 command. 07-March-2015 - Fixed the G28 command at the end of the job. Added defaults for laser power,
feedrates and ppm if defined. If ppm isn't defined in the layer options it will operate as
continuous wave mode. See the help in the extension dialog for how to use.
This works form me, but YMMV. Very limited testing. Never leave your laser cutter unattended while it's powered/operating. Keep a fire extinguisher close by, wear saftey goggles, and be afraid! 07-March-2015 - Marlin codebase mod : You need to patch the Marlin codebase to turn on the
laser before moving for G02 and G03 commands. This plugin assumes this has been done. More
details to come in the future. Copy the code from the G01 above in marlin_main.cpp
USE AT YOUR OWN RISK! Turnkey Laser Inkscape Gcode Export Plugin
------------------------------------------
10.17.14 - A little more testing reveals that G02 (CW ARC) and G03 (CCW ARC) moves are problematic. Not sure if it's the modifications in this fork, the original THLaser, LMN's Marlin, Inkscape, or some combination that is causing the issues.
Basically, you should consider this pre-alpha code. Examine the exported Gcode and do test runs on cardboard/paper before trying to cut on valuable stock.
Also: G28 at the end of the job doesn't seem to be working at the moment, at least not when running the gcode on my machine.
10.19.14 - G02 and G03 really screw things up, so I've set the default min_arc_radius to 500 to force all cut moves to be G01. That has it's own issues. At this point I wouldn't recommend using the Gcode from this for any real jobs.
11.22.14 - Reverted min_arc_radius default
THLaser Inkscape Plugin
-----------------------
This program is an Inkscape extension for exporting a set of paths as This program is an Inkscape extension for exporting a set of paths as
gcode script. It is primarily used by members to the think|haus hacker gcode script.
space (thinkhaus.org) for use with their laser cutter. As such it is
customized to suit our needs and so may not be your best choice if you
are looking for a general purpose Inkscape to gcode script.
This script is a fork of Gcodetools v1.2 written by Nick Drobchenko and This script is a fork of Gcodetools v1.2 written by Nick Drobchenko and
is released under the same license (GPL v2). is released under the same license (GPL v2).
...@@ -37,7 +31,7 @@ is released under the same license (GPL v2). ...@@ -37,7 +31,7 @@ is released under the same license (GPL v2).
Installation Installation
------------ ------------
Copy the files thlaser.py and thlaser.inx into your Inkscape extensions Copy the files turnkeylaser.py and turnkeylaser.inx into your Inkscape extensions
folder. Fire up inkscape and you will find the plugin under Extensions -> folder. Fire up inkscape and you will find the plugin under Extensions ->
Export -> THLaser GCode Export. Export -> THLaser GCode Export.
...@@ -48,7 +42,8 @@ You may find it handy to assign the extension to a keyboard shortcut. ...@@ -48,7 +42,8 @@ You may find it handy to assign the extension to a keyboard shortcut.
Include something like the following line to your inkscape keys Include something like the following line to your inkscape keys
preferences file (this will bind the plugin to Ctrl+\): preferences file (this will bind the plugin to Ctrl+\):
<bind key="backslash" modifiers="Ctrl" action="org.thinkhaus.filter.thlaser" display="true"/> <bind key="backslash" modifiers="Ctrl" action="org.thinkhaus.filter.thlaser"
display="true"/>
You can find your keyboard preferences file: You can find your keyboard preferences file:
...@@ -59,6 +54,6 @@ If that file doesn't exist, create it and include the following: ...@@ -59,6 +54,6 @@ If that file doesn't exist, create it and include the following:
<?xml version="1.0"?> <?xml version="1.0"?>
<keys name="My Keys"> <keys name="My Keys">
<bind key="backslash" modifiers="Ctrl" action="org.thinkhaus.filter.thlaser" display="true"/> <bind key="backslash" modifiers="Ctrl" action="org.thinkhaus.filter.thlaser"
display="true"/>
</keys> </keys>
This source diff could not be displayed because it is too large. You can view the blob instead.
Note : 73% on my unit runs the laser tube at 18ma. This is the maximum current that should be put through a 40 watt CO2 laser tube.
Cut Perspex = F300 @ 73%
Score cardboard = F1400 @ 9%
Cut Paper (Pulsed) = F600 @ 8% - 60ms pulse 2 pulse per millimetre.
\ No newline at end of file
G21 ; All units in mm
; Default Cut Feedrate 300 mm per minute
; Default Move Feedrate 2000 mm per minute
; Default Laser Intensity 72 percent
G28 ; home all
M5 ;turn the laser off
;(************************************************************)
;(***** Layer: 8 *****)
;(***** Laser Power: 8 *****)
;(***** Feed Rate: 600.0 *****)
;(***** Pulse Rate: None *****)
;(************************************************************)
;(MSG,Starting layer '8')
G00 X93.693928 Y42.800959 F2000
G01 S8.00 X93.693928 Y123.034303 F600 B0 D0
M5 ;turn the laser off
M5 ;turn the laser off
;(************************************************************)
;(***** Layer: 8 *****)
;(***** Laser Power: 8 *****)
;(***** Feed Rate: 600.0 *****)
;(***** Pulse Rate: 2.0 *****)
;(************************************************************)
;(MSG,Starting layer '8')
G00 X89.182149 Y42.856593 F2000
G01 S8.00 X89.182149 Y123.089937 F600 L60000 P1 B1 D0
M5 ;turn the laser off
M5 ;turn the laser off
;(************************************************************)
;(***** Layer: 8 *****)
;(***** Laser Power: 8 *****)
;(***** Feed Rate: 600.0 *****)
;(***** Pulse Rate: 1.0 *****)
;(************************************************************)
;(MSG,Starting layer '8')
G00 X84.297648 Y42.816729 F2000
G01 S8.00 X84.297648 Y123.050073 F600 L60000 P0.5 B1 D0
M5 ;turn the laser off
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension> <inkscape-extension>
<name>THLaser GCode Exporter</name> <name>TurnkeyLaser Exporter</name>
<id>org.thinkhaus.filter.thlaser</id> <id>com.turnkey.Tyranny</id>
<effect> <effect>
<object-type>path</object-type> <object-type>path</object-type>
...@@ -10,44 +10,61 @@ ...@@ -10,44 +10,61 @@
</effects-menu> </effects-menu>
</effect> </effect>
<dependency type="executable" location="extensions">thlaser.py</dependency> <dependency type="executable" location="extensions">turnkeylaser.py</dependency>
<dependency type="executable" location="extensions">inkex.py</dependency> <dependency type="executable" location="extensions">inkex.py</dependency>
<script> <script>
<command reldir="extensions" interpreter="python">thlaser.py</command> <command reldir="extensions" interpreter="python">turnkeylaser.py</command>
</script> </script>
<param name='tab' type="notebook"> <param name='tab' type="notebook">
<page name='tab' _gui-text='Help'> <page name='tab' _gui-text='Help'>
<_param name="fullhelp" type="description">THLaser converts inkscape paths to Gcode. (v1.30) <_param name="fullhelp" type="description">TurnkeyLaser exports Inkscape paths to Gcode compatible with Ramps+Marlin or Smoothieware laser mainboards.
You're able to specify in your layer names the laser power output, feedrate and optionally the pulse per millimetre option for pulsed lasing mode as opposed to the default continuous wave operation mode.
1)Name your layer like the following example :
35 [feed=600,ppm=40]
2)Draw your designs and group them based on lasing options in the layer name.
3)Select the paths you want to export, then run this script.
In the example above the layer will be cut at 35% power with a feedrate of 600mm per minute and a pulse rate of 40 pulses per millimetre (at 60ms pulses).
This script is a fork of Gcodetools v1.2 by Nick Drobchenko. It is currently maintained by Peter Rogers (peter.rogers@gmail.com) at think|haus.</_param> If the ppm option isn't specified in the layer options then output lines will be cut in continuous wave mode at the power and feed specified.
If you do not specify the laser power or other options in the layer name then they will default to the options in the export dialog box under "Preferences".
For the latest revision please visit https://github.com/TurnkeyTyranny/laser-gcode-exporter-inkscape-plugin
</_param>
</page> </page>
<page name='tab' _gui-text='Advanced'> <page name='tab' _gui-text='Advanced'>
<param name="biarc-tolerance" type='float' _gui-text='Biarc interpolation tolerance'>1</param> <param name="mainboard" type="enum" _gui-text="Mainboard: ">
<item value="ramps">Ramps 1.4</item>
<item value="smoothie">Smoothie</item>
</param>
<param name="biarc-tolerance" type='float' _gui-text='Biarc interpolation tolerance'>0.5</param>
<_param name="help" type="description">Biarc interpolation tolerance is the maximum allowed distance between a path and it's approximation. If this value is exceeded, the path will be split into two segments.</_param> <_param name="help" type="description">Biarc interpolation tolerance is the maximum allowed distance between a path and it's approximation. If this value is exceeded, the path will be split into two segments.</_param>
<param name="biarc-max-split-depth" type="int" _gui-text="Maximum splitting depth">4</param> <param name="biarc-max-split-depth" type="int" _gui-text="Maximum splitting depth">4</param>
<param name="min-arc-radius" type="float" precision="5" min="-1000" max="1000" _gui-text="Minimum arc radius">0.05</param> <param name="min-arc-radius" type="float" precision="5" min="-1000" max="5000" _gui-text="Minimum arc radius">0.00005</param>
<param name="Xoffset" type="float" precision="4" min="-1000" max="1000" _gui-text="Offset along X axis">0.0</param> <param name="Xoffset" type="float" precision="4" min="-1000" max="1000" _gui-text="Offset along X axis">0.0</param>
<param name="Yoffset" type="float" precision="4" min="-1000" max="1000" _gui-text="Offset along Y axis">0.0</param> <param name="Yoffset" type="float" precision="4" min="-1000" max="1000" _gui-text="Offset along Y axis">0.0</param>
<param name="logging" type="boolean" _gui-text="Log debug output from plugin:">true</param> <param name="logging" type="boolean" _gui-text="Log debug output from plugin:">true</param>
</page> </page>
<page name='tab' _gui-text='Preferences'> <page name='tab' _gui-text='Preferences'>
<param name="filename" type="string" _gui-text="File name: ">output.ngc</param> <param name="filename" type="string" _gui-text="File name: ">output.g</param>
<param name="directory" type="string" _gui-text="Directory: "></param> <param name="directory" type="string" _gui-text="Directory: "></param>
<_param name="help" type="description">(blank is your desktop)</_param> <_param name="help" type="description">(blank is your desktop)</_param>
<param name="feed" type="int" min="0" max="1000" _gui-text="Cut Feedrate:">60</param> <param name="feed" type="int" min="0" max="5000" _gui-text="Default Cut Feedrate:">300</param>
<param name="Mfeed" type="int" min="0" max="5000" _gui-text="Traversal Feedrate:">300</param> <param name="Mfeed" type="int" min="0" max="5000" _gui-text="Default Traversal Feedrate:">2000</param>
<param name="laser" type="int" min="0" max="100" _gui-text="Laser Intensity (0-100):">10</param> <param name="laser" type="int" min="0" max="100" _gui-text="Default Laser Intensity (0-100%):">10</param>
<param name="homebefore" type="boolean" _gui-text="HOMEALL (G28) Before:">true</param> <param name="homebefore" type="boolean" _gui-text="Home X & Y Before:">true</param>
<param name="homeafter" type="boolean" _gui-text="HOMEALL (G28) After:">false</param> <param name="homeafter" type="boolean" _gui-text="Home X & Y After:">false</param>
<param name="Xscale" type="float" precision="4" min="-1000" max="1000" _gui-text="Scale along X axis:">1</param> <param name="Xscale" type="float" precision="4" min="-1000" max="1000" _gui-text="Scale along X axis:">1</param>
<param name="Yscale" type="float" precision="4" min="-1000" max="1000" _gui-text="Scale along Y axis:">1</param> <param name="Yscale" type="float" precision="4" min="-1000" max="1000" _gui-text="Scale along Y axis:">1</param>
<param name="double_sided_cutting" type="boolean" _gui-text="Double-sided cutting:">false</param> <param name="double_sided_cutting" type="boolean" _gui-text="Cut both sides of material?">false</param>
<param name="draw-curves" type="boolean" _gui-text="Draw curves:">true</param> <param name="draw-curves" type="boolean" _gui-text="Draw curves in inkscape layer">true</param>
<param name="unit" type="enum" _gui-text="Units: "> <param name="unit" type="enum" _gui-text="Units: ">
<item value="mm">mm</item> <item value="mm">mm</item>
...@@ -55,4 +72,4 @@ This script is a fork of Gcodetools v1.2 by Nick Drobchenko. It is currently mai ...@@ -55,4 +72,4 @@ This script is a fork of Gcodetools v1.2 by Nick Drobchenko. It is currently mai
</param> </param>
</page> </page>
</param> </param>
</inkscape-extension> </inkscape-extension>
\ No newline at end of file
#!/usr/bin/env python #!/usr/bin/env python
""" """
think|haus gcode inkscape extension TurnkeyLaserExporter
-----------------------------------
Maintained by Peter Rogers (peter.rogers@gmail.com) -----------------------------------
Customized to suit our needs at thinkhaus.org (see change log below) Maintained by Turnkey Tyranny (https://github.com/TurnkeyTyranny/laser-gcode-exporter-inkscape-plugin)
Based on a script by Nick Drobchenko from the CNC club Designed to run on Ramps 1.4 + Marlin firmware on a K40 CO2 Laser Cutter.
Based on think|haus gcode inkscape extension
*** Based on a script by Nick Drobchenko from the CNC club
Copyright (C) 2009 Nick Drobchenko, nick@cnc-club.ru ***
based on gcode.py (C) 2007 hugomatic...
based on addnodes.py (C) 2005,2007 Aaron Spike, aaron@ekips.org Copyright (C) 2009 Nick Drobchenko, nick@cnc-club.ru
based on dots.py (C) 2005 Aaron Spike, aaron@ekips.org based on gcode.py (C) 2007 hugomatic...
based on interp.py (C) 2005 Aaron Spike, aaron@ekips.org based on addnodes.py (C) 2005,2007 Aaron Spike, aaron@ekips.org
based on dots.py (C) 2005 Aaron Spike, aaron@ekips.org
This program is free software; you can redistribute it and/or modify based on interp.py (C) 2005 Aaron Spike, aaron@ekips.org
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or This program is free software; you can redistribute it and/or modify
(at your option) any later version. it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
This program is distributed in the hope that it will be useful, (at your option) any later version.
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the This program is distributed in the hope that it will be useful,
GNU General Public License for more details. but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
You should have received a copy of the GNU General Public License GNU General Public License for more details.
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA You should have received a copy of the GNU General Public License
""" along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
""" """
Changelog 2012-01-12 - PAR:
* fixed bug in compile_paths when dealing with empty node data """
Changelog 2011-10-16 - PAR: Changelog 2015-02-01:
* general code cleanup to make things more readable * Beginning of the project. Based on a fork from ShinyLaser(https://github.com/ajfoul/thlaser-inkscape-plugin)
* now inkscape coordinate system matches laser bed coordinate system
* removed "area curve" code, since it wasn't being used and wasn't working anyways Changelog 2015-02-16:
* cleanup of source code, reorganized the dialog window Added an option to export as Marlin or Smoothie Power levels
Changelog 2011-08-06 - PAR: Changelog 2015-03-07:
* layer and group transforms now taken into account Added capability to pick out power, ppm, feedrate etc from the layer names
* tool change now happens on every layer (only when multiple layers present) Added code to support Pulse Per Minute burning or continuous burning. Will default to continuous.
* displays a message at the start of each layer M649 S100 L300 P10 - Set Laser settings to 100 percent power, pulses are each 300ms, and 10 pulses per mm.
G0 : Move to a new location with the laser off.
Changelog 2011-07-31 - PAR: G1 : Move to a new location with the laser on.
* misc bug fixes G2 : Move in a Clockwise Arc
* objects in document root (ie not in a layer) now outputted properly G3 : Move in a Counter Clockwise Arc
* skips 'comment' layers (ie name prefixed with '#') Name your layer like 10 [feed=600,ppm=40] for 10% power, 600mm per minute cut and 40 pulse per millimetre at 60ms duration
* warns about any selected objects not outputted by the script """
Changelog 2011-07-01 - PAR: ###
* logging is now enabled by default ### Gcode tools
* handling groups and layers properly ###
* toolchange operation (M6) added between outputting layers
* removed 'options.ids' in favor of 'self.selected' import inkex, simplestyle, simplepath
import cubicsuperpath, simpletransform, bezmisc
Changelog 2011-02-20 - Adina:
* removed any movement in the z axis when the laser is trying to etch a curve. import os
* removed extra M3s: the laser only turns on at the beginning of a cut block, not before every line. import math
import bezmisc
Changelog 2010-04-07 - Adina: import re
* separate scaling factor for x and y, import copy
* x and y scaled to mm or inches that match the dimensions in inkscape (not 1px = 1 in or mm) import sys
import time
Changelog 2010-04-20: #_ = inkex._
* made the .inx file refer to the correct .py file... it should work now?
"""
################################################################################
### ###
### Gcode tools ### Constants
### ###
################################################################################
import inkex, simplestyle, simplepath
import cubicsuperpath, simpletransform, bezmisc VERSION = "1.0.1"
import os STRAIGHT_TOLERANCE = 0.0001
import math STRAIGHT_DISTANCE_TOLERANCE = 0.0001
import bezmisc LASER_ON = "M3 ;turn the laser on" # LASER ON MCODE
import re LASER_OFF = "M5 ;turn the laser off\n" # LASER OFF MCODE
import copy
import sys HEADER_TEXT = ""
import time FOOTER_TEXT = ""
_ = inkex._
BIARC_STYLE = {
'biarc0': simplestyle.formatStyle({ 'stroke': '#88f', 'fill': 'none', 'stroke-width':'1' }),
################################################################################ 'biarc1': simplestyle.formatStyle({ 'stroke': '#8f8', 'fill': 'none', 'stroke-width':'1' }),
### 'line': simplestyle.formatStyle({ 'stroke': '#f88', 'fill': 'none', 'stroke-width':'1' }),
### Constants 'area': simplestyle.formatStyle({ 'stroke': '#777', 'fill': 'none', 'stroke-width':'0.1' }),
### }
################################################################################
# Inkscape group tag
VERSION = "1.30" SVG_GROUP_TAG = inkex.addNS("g", "svg")
SVG_PATH_TAG = inkex.addNS('path','svg')
STRAIGHT_TOLERANCE = 0.0001 SVG_LABEL_TAG = inkex.addNS("label", "inkscape")
STRAIGHT_DISTANCE_TOLERANCE = 0.0001
LASER_ON = "M3" # Peter - LASER ON MCODE
LASER_OFF = "M5\n" # Peter - LASER OFF MCODE GCODE_EXTENSION = ".g" # changed to be Marlin friendly (ajf)
TOOL_CHANGE = "T%02d (select tool)\nM6 (tool change)\n\n"
options = {}
HEADER_TEXT = ""
FOOTER_TEXT = "" ################################################################################
###
BIARC_STYLE = { ### Common functions
'biarc0': simplestyle.formatStyle({ 'stroke': '#88f', 'fill': 'none', 'stroke-width':'1' }), ###
'biarc1': simplestyle.formatStyle({ 'stroke': '#8f8', 'fill': 'none', 'stroke-width':'1' }), ################################################################################
'line': simplestyle.formatStyle({ 'stroke': '#f88', 'fill': 'none', 'stroke-width':'1' }),
'area': simplestyle.formatStyle({ 'stroke': '#777', 'fill': 'none', 'stroke-width':'0.1' }),
} ###
### Just simple output function for better debugging
# Inkscape group tag ###
SVG_GROUP_TAG = inkex.addNS("g", "svg")
SVG_PATH_TAG = inkex.addNS('path','svg') class Logger(object):
SVG_LABEL_TAG = inkex.addNS("label", "inkscape") first = True
enabled = True
def __init__(self):
GCODE_EXTENSION = ".g" # changed to be Marlin friendly (ajf) home = os.getenv("HOME") or os.getenv("USERPROFILE")
self.logpath = os.path.join(home, "thlaser.log")
options = {}
def write(self, s):
################################################################################ if (not self.enabled):
### return
### Common functions
### if self.first and os.path.isfile(self.logpath):
################################################################################ os.remove(self.logpath)
self.first = False
### f = open(self.logpath, "a")
### Just simple output function for better debugging f.write(str(s)+"\n")
### f.close()
class Logger(object): # The global logger object
first = True logger = Logger()
enabled = True
def __init__(self):
home = os.getenv("HOME") or os.getenv("USERPROFILE") ###
self.logpath = os.path.join(home, "thlaser.log") ### Point (x,y) operations
###
def write(self, s): ## Pretty much what it sounds like: defines some arithmetic functions that can be applied to points.
if (not self.enabled): class P:
return def __init__(self, x, y=None):
if not y==None:
if self.first and os.path.isfile(self.logpath): self.x, self.y = float(x), float(y)
os.remove(self.logpath) else:
self.first = False self.x, self.y = float(x[0]), float(x[1])
def __add__(self, other): return P(self.x + other.x, self.y + other.y)
f = open(self.logpath, "a") def __sub__(self, other): return P(self.x - other.x, self.y - other.y)
f.write(str(s)+"\n") def __neg__(self): return P(-self.x, -self.y)
f.close() def __mul__(self, other):
if isinstance(other, P):
# The global logger object return self.x * other.x + self.y * other.y
logger = Logger() return P(self.x * other, self.y * other)
__rmul__ = __mul__
def __div__(self, other): return P(self.x / other, self.y / other)
### def mag(self): return math.hypot(self.x, self.y)
### Point (x,y) operations def unit(self):
### h = self.mag()
## Pretty much what it sounds like: defines some arithmetic functions that can be applied to points. if h: return self / h
class P: else: return P(0,0)
def __init__(self, x, y=None): def dot(self, other): return self.x * other.x + self.y * other.y
if not y==None: def rot(self, theta):
self.x, self.y = float(x), float(y) c = math.cos(theta)
else: s = math.sin(theta)
self.x, self.y = float(x[0]), float(x[1]) return P(self.x * c - self.y * s, self.x * s + self.y * c)
def __add__(self, other): return P(self.x + other.x, self.y + other.y) def angle(self): return math.atan2(self.y, self.x)
def __sub__(self, other): return P(self.x - other.x, self.y - other.y) def __repr__(self): return '%f,%f' % (self.x, self.y)
def __neg__(self): return P(-self.x, -self.y) def pr(self): return "%.2f,%.2f" % (self.x, self.y)
def __mul__(self, other): def to_list(self): return [self.x, self.y]
if isinstance(other, P):
return self.x * other.x + self.y * other.y
return P(self.x * other, self.y * other) ###
__rmul__ = __mul__ ### Functions to operate with CubicSuperPath
def __div__(self, other): return P(self.x / other, self.y / other) ###
def mag(self): return math.hypot(self.x, self.y)
def unit(self): def csp_at_t(sp1,sp2,t):
h = self.mag() bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:])
if h: return self / h return bezmisc.bezierpointatt(bez,t)
else: return P(0,0)
def dot(self, other): return self.x * other.x + self.y * other.y def cspbezsplit(sp1, sp2, t = 0.5):
def rot(self, theta): s1,s2 = bezmisc.beziersplitatt((sp1[1],sp1[2],sp2[0],sp2[1]),t)
c = math.cos(theta) return [ [sp1[0][:], sp1[1][:], list(s1[1])], [list(s1[2]), list(s1[3]), list(s2[1])], [list(s2[2]), sp2[1][:], sp2[2][:]] ]
s = math.sin(theta)
return P(self.x * c - self.y * s, self.x * s + self.y * c) def cspbezsplitatlength(sp1, sp2, l = 0.5, tolerance = 0.01):
def angle(self): return math.atan2(self.y, self.x) bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:])
def __repr__(self): return '%f,%f' % (self.x, self.y) t = bezmisc.beziertatlength(bez, l, tolerance)
def pr(self): return "%.2f,%.2f" % (self.x, self.y) return cspbezsplit(sp1, sp2, t)
def to_list(self): return [self.x, self.y]
def cspseglength(sp1,sp2, tolerance = 0.001):
bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:])
### return bezmisc.bezierlength(bez, tolerance)
### Functions to operate with CubicSuperPath
### def csplength(csp):
total = 0
def csp_at_t(sp1,sp2,t): lengths = []
bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:]) for sp in csp:
return bezmisc.bezierpointatt(bez,t) for i in xrange(1,len(sp)):
l = cspseglength(sp[i-1],sp[i])
def cspbezsplit(sp1, sp2, t = 0.5): lengths.append(l)
s1,s2 = bezmisc.beziersplitatt((sp1[1],sp1[2],sp2[0],sp2[1]),t) total += l
return [ [sp1[0][:], sp1[1][:], list(s1[1])], [list(s1[2]), list(s1[3]), list(s2[1])], [list(s2[2]), sp2[1][:], sp2[2][:]] ] return lengths, total
def cspbezsplitatlength(sp1, sp2, l = 0.5, tolerance = 0.01):
bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:]) ###
t = bezmisc.beziertatlength(bez, l, tolerance) ### Distance calculattion from point to arc
return cspbezsplit(sp1, sp2, t) ###
def cspseglength(sp1,sp2, tolerance = 0.001): def between(c,x,y):
bez = (sp1[1][:],sp1[2][:],sp2[0][:],sp2[1][:]) return x-STRAIGHT_TOLERANCE<=c<=y+STRAIGHT_TOLERANCE or y-STRAIGHT_TOLERANCE<=c<=x+STRAIGHT_TOLERANCE
return bezmisc.bezierlength(bez, tolerance)
def distance_from_point_to_arc(p, arc):
def csplength(csp): P0,P2,c,a = arc
total = 0 dist = None
lengths = [] p = P(p)
for sp in csp: r = (P0-c).mag()
for i in xrange(1,len(sp)): if r>0 :
l = cspseglength(sp[i-1],sp[i]) i = c + (p-c).unit()*r
lengths.append(l) alpha = ((i-c).angle() - (P0-c).angle())
total += l if a*alpha<0:
return lengths, total if alpha>0: alpha = alpha-2*math.pi
else: alpha = 2*math.pi+alpha
if between(alpha,0,a) or min(abs(alpha),abs(alpha-a))<STRAIGHT_TOLERANCE :
### return (p-i).mag(), [i.x, i.y]
### Distance calculattion from point to arc else :
### d1, d2 = (p-P0).mag(), (p-P2).mag()
if d1<d2 :
def between(c,x,y): return (d1, [P0.x,P0.y])
return x-STRAIGHT_TOLERANCE<=c<=y+STRAIGHT_TOLERANCE or y-STRAIGHT_TOLERANCE<=c<=x+STRAIGHT_TOLERANCE else :
return (d2, [P2.x,P2.y])
def distance_from_point_to_arc(p, arc):
P0,P2,c,a = arc def get_distance_from_csp_to_arc(sp1,sp2, arc1, arc2, tolerance = 0.001 ): # arc = [start,end,center,alpha]
dist = None n, i = 10, 0
p = P(p) d, d1, dl = (0,(0,0)), (0,(0,0)), 0
r = (P0-c).mag() while i<1 or (abs(d1[0]-dl[0])>tolerance and i<2):
if r>0 : i += 1
i = c + (p-c).unit()*r dl = d1*1
alpha = ((i-c).angle() - (P0-c).angle()) for j in range(n+1):
if a*alpha<0: t = float(j)/n
if alpha>0: alpha = alpha-2*math.pi p = csp_at_t(sp1,sp2,t)
else: alpha = 2*math.pi+alpha d = min(distance_from_point_to_arc(p,arc1), distance_from_point_to_arc(p,arc2))
if between(alpha,0,a) or min(abs(alpha),abs(alpha-a))<STRAIGHT_TOLERANCE : d1 = max(d1,d)
return (p-i).mag(), [i.x, i.y] n=n*2
else : return d1[0]
d1, d2 = (p-P0).mag(), (p-P2).mag()
if d1<d2 : ################################################################################
return (d1, [P0.x,P0.y]) ###
else : ### Biarc function
return (d2, [P2.x,P2.y]) ###
### Calculates biarc approximation of cubic super path segment
def get_distance_from_csp_to_arc(sp1,sp2, arc1, arc2, tolerance = 0.001 ): # arc = [start,end,center,alpha] ### splits segment if needed or approximates it with straight line
n, i = 10, 0 ###
d, d1, dl = (0,(0,0)), (0,(0,0)), 0 ################################################################################
while i<1 or (abs(d1[0]-dl[0])>tolerance and i<2):
i += 1
dl = d1*1 def biarc(sp1, sp2, z1, z2, depth=0,):
for j in range(n+1): def biarc_split(sp1,sp2, z1, z2, depth):
t = float(j)/n if depth<options.biarc_max_split_depth:
p = csp_at_t(sp1,sp2,t) sp1,sp2,sp3 = cspbezsplit(sp1,sp2)
d = min(distance_from_point_to_arc(p,arc1), distance_from_point_to_arc(p,arc2)) l1, l2 = cspseglength(sp1,sp2), cspseglength(sp2,sp3)
d1 = max(d1,d) if l1+l2 == 0 : zm = z1
n=n*2 else : zm = z1+(z2-z1)*l1/(l1+l2)
return d1[0] return biarc(sp1,sp2,depth+1,z1,zm)+biarc(sp2,sp3,depth+1,z1,zm)
else: return [ [sp1[1],'line', 0, 0, sp2[1], [z1,z2]] ]
################################################################################
### P0, P4 = P(sp1[1]), P(sp2[1])
### Biarc function TS, TE, v = (P(sp1[2])-P0), -(P(sp2[0])-P4), P0 - P4
### tsa, tea, va = TS.angle(), TE.angle(), v.angle()
### Calculates biarc approximation of cubic super path segment if TE.mag()<STRAIGHT_DISTANCE_TOLERANCE and TS.mag()<STRAIGHT_DISTANCE_TOLERANCE:
### splits segment if needed or approximates it with straight line # Both tangents are zerro - line straight
### return [ [sp1[1],'line', 0, 0, sp2[1], [z1,z2]] ]
################################################################################ if TE.mag() < STRAIGHT_DISTANCE_TOLERANCE:
TE = -(TS+v).unit()
r = TS.mag()/v.mag()*2
def biarc(sp1, sp2, z1, z2, depth=0,): elif TS.mag() < STRAIGHT_DISTANCE_TOLERANCE:
def biarc_split(sp1,sp2, z1, z2, depth): TS = -(TE+v).unit()
if depth<options.biarc_max_split_depth: r = 1/( TE.mag()/v.mag()*2 )
sp1,sp2,sp3 = cspbezsplit(sp1,sp2) else:
l1, l2 = cspseglength(sp1,sp2), cspseglength(sp2,sp3) r=TS.mag()/TE.mag()
if l1+l2 == 0 : zm = z1 TS, TE = TS.unit(), TE.unit()
else : zm = z1+(z2-z1)*l1/(l1+l2) tang_are_parallel = ((tsa-tea)%math.pi<STRAIGHT_TOLERANCE or math.pi-(tsa-tea)%math.pi<STRAIGHT_TOLERANCE )
return biarc(sp1,sp2,depth+1,z1,zm)+biarc(sp2,sp3,depth+1,z1,zm) if ( tang_are_parallel and
else: return [ [sp1[1],'line', 0, 0, sp2[1], [z1,z2]] ] ((v.mag()<STRAIGHT_DISTANCE_TOLERANCE or TE.mag()<STRAIGHT_DISTANCE_TOLERANCE or TS.mag()<STRAIGHT_DISTANCE_TOLERANCE) or
1-abs(TS*v/(TS.mag()*v.mag()))<STRAIGHT_TOLERANCE) ):
P0, P4 = P(sp1[1]), P(sp2[1]) # Both tangents are parallel and start and end are the same - line straight
TS, TE, v = (P(sp1[2])-P0), -(P(sp2[0])-P4), P0 - P4 # or one of tangents still smaller then tollerance
tsa, tea, va = TS.angle(), TE.angle(), v.angle()
if TE.mag()<STRAIGHT_DISTANCE_TOLERANCE and TS.mag()<STRAIGHT_DISTANCE_TOLERANCE: # Both tangents and v are parallel - line straight
# Both tangents are zerro - line straight return [ [sp1[1],'line', 0, 0, sp2[1], [z1,z2]] ]
return [ [sp1[1],'line', 0, 0, sp2[1], [z1,z2]] ]
if TE.mag() < STRAIGHT_DISTANCE_TOLERANCE: c,b,a = v*v, 2*v*(r*TS+TE), 2*r*(TS*TE-1)
TE = -(TS+v).unit() if v.mag()==0:
r = TS.mag()/v.mag()*2 return biarc_split(sp1, sp2, z1, z2, depth)
elif TS.mag() < STRAIGHT_DISTANCE_TOLERANCE: asmall, bsmall, csmall = abs(a)<10**-10,abs(b)<10**-10,abs(c)<10**-10
TS = -(TE+v).unit() if asmall and b!=0: beta = -c/b
r = 1/( TE.mag()/v.mag()*2 ) elif csmall and a!=0: beta = -b/a
else: elif not asmall:
r=TS.mag()/TE.mag() discr = b*b-4*a*c
TS, TE = TS.unit(), TE.unit() if discr < 0: raise ValueError, (a,b,c,discr)
tang_are_parallel = ((tsa-tea)%math.pi<STRAIGHT_TOLERANCE or math.pi-(tsa-tea)%math.pi<STRAIGHT_TOLERANCE ) disq = discr**.5
if ( tang_are_parallel and beta1 = (-b - disq) / 2 / a
((v.mag()<STRAIGHT_DISTANCE_TOLERANCE or TE.mag()<STRAIGHT_DISTANCE_TOLERANCE or TS.mag()<STRAIGHT_DISTANCE_TOLERANCE) or beta2 = (-b + disq) / 2 / a
1-abs(TS*v/(TS.mag()*v.mag()))<STRAIGHT_TOLERANCE) ): if beta1*beta2 > 0 : raise ValueError, (a,b,c,disq,beta1,beta2)
# Both tangents are parallel and start and end are the same - line straight beta = max(beta1, beta2)
# or one of tangents still smaller then tollerance elif asmall and bsmall:
return biarc_split(sp1, sp2, z1, z2, depth)
# Both tangents and v are parallel - line straight alpha = beta * r
return [ [sp1[1],'line', 0, 0, sp2[1], [z1,z2]] ] ab = alpha + beta
P1 = P0 + alpha * TS
c,b,a = v*v, 2*v*(r*TS+TE), 2*r*(TS*TE-1) P3 = P4 - beta * TE
if v.mag()==0: P2 = (beta / ab) * P1 + (alpha / ab) * P3
return biarc_split(sp1, sp2, z1, z2, depth)
asmall, bsmall, csmall = abs(a)<10**-10,abs(b)<10**-10,abs(c)<10**-10 def calculate_arc_params(P0,P1,P2):
if asmall and b!=0: beta = -c/b D = (P0+P2)/2
elif csmall and a!=0: beta = -b/a if (D-P1).mag()==0: return None, None
elif not asmall: R = D - ( (D-P0).mag()**2/(D-P1).mag() )*(P1-D).unit()
discr = b*b-4*a*c p0a, p1a, p2a = (P0-R).angle()%(2*math.pi), (P1-R).angle()%(2*math.pi), (P2-R).angle()%(2*math.pi)
if discr < 0: raise ValueError, (a,b,c,discr) alpha = (p2a - p0a) % (2*math.pi)
disq = discr**.5 if (p0a<p2a and (p1a<p0a or p2a<p1a)) or (p2a<p1a<p0a) :
beta1 = (-b - disq) / 2 / a alpha = -2*math.pi+alpha
beta2 = (-b + disq) / 2 / a if abs(R.x)>1000000 or abs(R.y)>1000000 or (R-P0).mag<options.min_arc_radius :
if beta1*beta2 > 0 : raise ValueError, (a,b,c,disq,beta1,beta2) return None, None
beta = max(beta1, beta2) else :
elif asmall and bsmall: return R, alpha
return biarc_split(sp1, sp2, z1, z2, depth) R1,a1 = calculate_arc_params(P0,P1,P2)
alpha = beta * r R2,a2 = calculate_arc_params(P2,P3,P4)
ab = alpha + beta if R1==None or R2==None or (R1-P0).mag()<STRAIGHT_TOLERANCE or (R2-P2).mag()<STRAIGHT_TOLERANCE : return [ [sp1[1],'line', 0, 0, sp2[1], [z1,z2]] ]
P1 = P0 + alpha * TS
P3 = P4 - beta * TE d = get_distance_from_csp_to_arc(sp1,sp2, [P0,P2,R1,a1],[P2,P4,R2,a2])
P2 = (beta / ab) * P1 + (alpha / ab) * P3 if d > options.biarc_tolerance and depth<options.biarc_max_split_depth : return biarc_split(sp1, sp2, z1, z2, depth)
else:
def calculate_arc_params(P0,P1,P2): if R2.mag()*a2 == 0 : zm = z2
D = (P0+P2)/2 else : zm = z1 + (z2-z1)*(R1.mag()*a1)/(R2.mag()*a2+R1.mag()*a1)
if (D-P1).mag()==0: return None, None return [ [ sp1[1], 'arc', [R1.x,R1.y], a1, [P2.x,P2.y], [z1,zm] ], [ [P2.x,P2.y], 'arc', [R2.x,R2.y], a2, [P4.x,P4.y], [zm,z2] ] ]
R = D - ( (D-P0).mag()**2/(D-P1).mag() )*(P1-D).unit()
p0a, p1a, p2a = (P0-R).angle()%(2*math.pi), (P1-R).angle()%(2*math.pi), (P2-R).angle()%(2*math.pi)
alpha = (p2a - p0a) % (2*math.pi)
if (p0a<p2a and (p1a<p0a or p2a<p1a)) or (p2a<p1a<p0a) : ################################################################################
alpha = -2*math.pi+alpha ###
if abs(R.x)>1000000 or abs(R.y)>1000000 or (R-P0).mag<options.min_arc_radius : ### Inkscape helper functions
return None, None ###
else : ################################################################################
return R, alpha
R1,a1 = calculate_arc_params(P0,P1,P2) # Returns true if the given node is a layer
R2,a2 = calculate_arc_params(P2,P3,P4) def is_layer(node):
if R1==None or R2==None or (R1-P0).mag()<STRAIGHT_TOLERANCE or (R2-P2).mag()<STRAIGHT_TOLERANCE : return [ [sp1[1],'line', 0, 0, sp2[1], [z1,z2]] ] return (node.tag == SVG_GROUP_TAG and
node.get(inkex.addNS("groupmode", "inkscape")) == "layer")
d = get_distance_from_csp_to_arc(sp1,sp2, [P0,P2,R1,a1],[P2,P4,R2,a2])
if d > options.biarc_tolerance and depth<options.biarc_max_split_depth : return biarc_split(sp1, sp2, z1, z2, depth) def get_layers(document):
else: layers = []
if R2.mag()*a2 == 0 : zm = z2 root = document.getroot()
else : zm = z1 + (z2-z1)*(R1.mag()*a1)/(R2.mag()*a2+R1.mag()*a1) for node in root.iterchildren():
return [ [ sp1[1], 'arc', [R1.x,R1.y], a1, [P2.x,P2.y], [z1,zm] ], [ [P2.x,P2.y], 'arc', [R2.x,R2.y], a2, [P4.x,P4.y], [zm,z2] ] ] if (is_layer(node)):
# Found an inkscape layer
layers.append(node)
return layers
################################################################################
### def parse_layer_name(txt):
### Inkscape helper functions params = {}
### try:
################################################################################ n = txt.index("[")
except ValueError:
# Returns true if the given node is a layer layerName = txt.strip()
def is_layer(node): else:
return (node.tag == SVG_GROUP_TAG and layerName = txt[0:n].strip()
node.get(inkex.addNS("groupmode", "inkscape")) == "layer") args = txt[n+1:].strip()
if (args.endswith("]")):
def get_layers(document): args = args[0:-1]
layers = []
root = document.getroot() for arg in args.split(","):
for node in root.iterchildren(): try:
if (is_layer(node)): (field, value) = arg.split("=")
# Found an inkscape layer except:
layers.append(node) raise ValueError("Invalid argument in layer '%s'" % layerName)
return layers if (field == "feed" or field == "ppm"):
try:
def parse_layer_name(txt): value = float(value)
params = {} except:
try: raise ValueError("Invalid layer name '%s'" % value)
n = txt.index("[") params[field] = value
except ValueError: logger.write("%s == %s" % (field, value))
layerName = txt.strip()
else: return (layerName, params)
layerName = txt[0:n].strip()
args = txt[n+1:].strip() ################################################################################
if (args.endswith("]")): ###
args = args[0:-1] ### Gcode tools class
###
for arg in args.split(","): ################################################################################
try:
(field, value) = arg.split("=")
except:
raise ValueError("Invalid argument in layer '%s'" % layerName)
if (field == "feed"): class Gcode_tools(inkex.Effect):
try:
value = float(value) def __init__(self):
except: inkex.Effect.__init__(self)
raise ValueError("Invalid feed rate '%s'" % value)
params[field] = value outdir = os.getenv("HOME") or os.getenv("USERPROFILE")
logger.write("%s == %s" % (field, value)) if (outdir):
outdir = os.path.join(outdir, "Desktop")
return (layerName, params) else:
outdir = os.getcwd()
################################################################################
### self.OptionParser.add_option("-d", "--directory", action="store", type="string", dest="directory", default=outdir, help="Directory for gcode file")
### Gcode tools class self.OptionParser.add_option("-f", "--filename", action="store", type="string", dest="file", default="-1.0", help="File name")
### self.OptionParser.add_option("-u", "--Xscale", action="store", type="float", dest="Xscale", default="1.0", help="Scale factor X")
################################################################################ self.OptionParser.add_option("-v", "--Yscale", action="store", type="float", dest="Yscale", default="1.0", help="Scale factor Y")
self.OptionParser.add_option("-x", "--Xoffset", action="store", type="float", dest="Xoffset", default="0.0", help="Offset along X")
self.OptionParser.add_option("-y", "--Yoffset", action="store", type="float", dest="Yoffset", default="0.0", help="Offset along Y")
# added move (laser off) feedrate and laser intensity; made all int rather than float - (ajf)
class Gcode_tools(inkex.Effect): self.OptionParser.add_option("-m", "--Mfeed", action="store", type="int", dest="Mfeed", default="2000", help="Default Move Feed rate in unit/min")
self.OptionParser.add_option("-p", "--feed", action="store", type="int", dest="feed", default="300", help="Default Cut Feed rate in unit/min")
def __init__(self): self.OptionParser.add_option("-l", "--laser", action="store", type="int", dest="laser", default="10", help="Default Laser intensity (0-100 %)")
inkex.Effect.__init__(self) self.OptionParser.add_option("-b", "--homebefore", action="store", type="inkbool", dest="homebefore", default=True, help="Home all beofre starting (G28)")
self.OptionParser.add_option("-a", "--homeafter", action="store", type="inkbool", dest="homeafter", default=False, help="Home X Y at end of job")
outdir = os.getenv("HOME") or os.getenv("USERPROFILE")
if (outdir):
outdir = os.path.join(outdir, "Desktop") self.OptionParser.add_option("", "--biarc-tolerance", action="store", type="float", dest="biarc_tolerance", default="1", help="Tolerance used when calculating biarc interpolation.")
else: self.OptionParser.add_option("", "--biarc-max-split-depth", action="store", type="int", dest="biarc_max_split_depth", default="4", help="Defines maximum depth of splitting while approximating using biarcs.")
outdir = os.getcwd()
self.OptionParser.add_option("", "--unit", action="store", type="string", dest="unit", default="G21 (All units in mm)\n", help="Units")
self.OptionParser.add_option("-d", "--directory", action="store", type="string", dest="directory", default=outdir, help="Directory for gcode file") self.OptionParser.add_option("", "--function", action="store", type="string", dest="function", default="Curve", help="What to do: Curve|Area|Area inkscape")
self.OptionParser.add_option("-f", "--filename", action="store", type="string", dest="file", default="-1.0", help="File name") self.OptionParser.add_option("", "--tab", action="store", type="string", dest="tab", default="", help="Means nothing right now. Notebooks Tab.")
self.OptionParser.add_option("-u", "--Xscale", action="store", type="float", dest="Xscale", default="1.0", help="Scale factor X") self.OptionParser.add_option("", "--generate_not_parametric_code",action="store", type="inkbool", dest="generate_not_parametric_code", default=False,help="Generated code will be not parametric.")
self.OptionParser.add_option("-v", "--Yscale", action="store", type="float", dest="Yscale", default="1.0", help="Scale factor Y") self.OptionParser.add_option("", "--double_sided_cutting",action="store", type="inkbool", dest="double_sided_cutting", default=False,help="Generate code for double-sided cutting.")
self.OptionParser.add_option("-x", "--Xoffset", action="store", type="float", dest="Xoffset", default="0.0", help="Offset along X") self.OptionParser.add_option("", "--draw-curves", action="store", type="inkbool", dest="drawCurves", default=False,help="Draws curves to show what geometry was processed")
self.OptionParser.add_option("-y", "--Yoffset", action="store", type="float", dest="Yoffset", default="0.0", help="Offset along Y") self.OptionParser.add_option("", "--logging", action="store", type="inkbool", dest="logging", default=False, help="Enable output logging from the plugin")
# added move (laser off) feedrate and laser intensity; made all int rather than float - (ajf)
self.OptionParser.add_option("-p", "--feed", action="store", type="int", dest="feed", default="60", help="Cut Feed rate in unit/min") self.OptionParser.add_option("", "--loft-distances", action="store", type="string", dest="loft_distances", default="10", help="Distances between paths.")
self.OptionParser.add_option("-m", "--Mfeed", action="store", type="int", dest="Mfeed", default="300", help="Move Feed rate in unit/min") self.OptionParser.add_option("", "--loft-direction", action="store", type="string", dest="loft_direction", default="crosswise", help="Direction of loft's interpolation.")
self.OptionParser.add_option("-l", "--laser", action="store", type="int", dest="laser", default="10", help="Laser intensity (0-100)") self.OptionParser.add_option("", "--loft-interpolation-degree",action="store", type="float", dest="loft_interpolation_degree", default="2", help="Which interpolation use to loft the paths smooth interpolation or staright.")
self.OptionParser.add_option("-b", "--homebefore", action="store", type="inkbool", dest="homebefore", default=True, help="Home all axis beofre starting (G28)")
self.OptionParser.add_option("-a", "--homeafter", action="store", type="inkbool", dest="homeafter", default=False, help="Home all axis at end of job (G28)") self.OptionParser.add_option("", "--min-arc-radius", action="store", type="float", dest="min_arc_radius", default="0.0005", help="All arc having radius less than minimum will be considered as straight line")
self.OptionParser.add_option("", "--mainboard", action="store", type="string", dest="mainboard", default="ramps", help="Mainboard")
self.OptionParser.add_option("", "--biarc-tolerance", action="store", type="float", dest="biarc_tolerance", default="1", help="Tolerance used when calculating biarc interpolation.")
self.OptionParser.add_option("", "--biarc-max-split-depth", action="store", type="int", dest="biarc_max_split_depth", default="4", help="Defines maximum depth of splitting while approximating using biarcs.") def parse_curve(self, path):
# if self.options.Xscale!=self.options.Yscale:
self.OptionParser.add_option("", "--unit", action="store", type="string", dest="unit", default="G21 (All units in mm)\n", help="Units") # xs,ys = self.options.Xscale,self.options.Yscale
self.OptionParser.add_option("", "--function", action="store", type="string", dest="function", default="Curve", help="What to do: Curve|Area|Area inkscape") # self.options.Xscale,self.options.Yscale = 1.0, 1.0
self.OptionParser.add_option("", "--tab", action="store", type="string", dest="tab", default="", help="Means nothing right now. Notebooks Tab.") # else :
self.OptionParser.add_option("", "--generate_not_parametric_code",action="store", type="inkbool", dest="generate_not_parametric_code", default=False,help="Generated code will be not parametric.") xs,ys = 1.0,1.0
self.OptionParser.add_option("", "--double_sided_cutting",action="store", type="inkbool", dest="double_sided_cutting", default=False,help="Generate code for double-sided cutting.")
self.OptionParser.add_option("", "--draw-curves", action="store", type="inkbool", dest="drawCurves", default=False,help="Draws curves to show what geometry was processed") # ### Sort to reduce Rapid distance
self.OptionParser.add_option("", "--logging", action="store", type="inkbool", dest="logging", default=False, help="Enable output logging from the plugin") # np = [p[0]]
# del p[0]
self.OptionParser.add_option("", "--loft-distances", action="store", type="string", dest="loft_distances", default="10", help="Distances between paths.") # while len(p)>0:
self.OptionParser.add_option("", "--loft-direction", action="store", type="string", dest="loft_direction", default="crosswise", help="Direction of loft's interpolation.") # end = np[-1][-1][1]
self.OptionParser.add_option("", "--loft-interpolation-degree",action="store", type="float", dest="loft_interpolation_degree", default="2", help="Which interpolation use to loft the paths smooth interpolation or staright.") # dist = None
# for i in range(len(p)):
self.OptionParser.add_option("", "--min-arc-radius", action="store", type="float", dest="min_arc_radius", default=".1", help="All arc having radius less than minimum will be considered as straight line") # start = p[i][0][1]
#
def parse_curve(self, path): # dist = max( ( -( ( end[0]-start[0])**2+(end[1]-start[1])**2 ) ,i) , dist )
# if self.options.Xscale!=self.options.Yscale: # np += [p[dist[1]][:]]
# xs,ys = self.options.Xscale,self.options.Yscale # del p[dist[1]]
# self.options.Xscale,self.options.Yscale = 1.0, 1.0 # p = np[:]
# else :
xs,ys = 1.0,1.0 lst = []
for subpath in path:
# ### Sort to reduce Rapid distance lst.append(
# np = [p[0]] [[subpath[0][1][0]*xs, subpath[0][1][1]*ys], 'move', 0, 0]
# del p[0] )
# while len(p)>0: for i in range(1,len(subpath)):
# end = np[-1][-1][1] sp1 = [ [subpath[i-1][j][0]*xs, subpath[i-1][j][1]*ys] for j in range(3)]
# dist = None sp2 = [ [subpath[i ][j][0]*xs, subpath[i ][j][1]*ys] for j in range(3)]
# for i in range(len(p)): lst += biarc(sp1,sp2,0,0)
# start = p[i][0][1]
# lst.append(
# dist = max( ( -( ( end[0]-start[0])**2+(end[1]-start[1])**2 ) ,i) , dist ) [[subpath[-1][1][0]*xs, subpath[-1][1][1]*ys], 'end', 0, 0]
# np += [p[dist[1]][:]] )
# del p[dist[1]]
# p = np[:] return lst
lst = [] def draw_curve(self, curve, group=None, style=BIARC_STYLE):
for subpath in path: if group==None:
lst.append( group = inkex.etree.SubElement( self.biarcGroup, SVG_GROUP_TAG )
[[subpath[0][1][0]*xs, subpath[0][1][1]*ys], 'move', 0, 0] s, arcn = '', 0
) for si in curve:
for i in range(1,len(subpath)): if s!='':
sp1 = [ [subpath[i-1][j][0]*xs, subpath[i-1][j][1]*ys] for j in range(3)] if s[1] == 'line':
sp2 = [ [subpath[i ][j][0]*xs, subpath[i ][j][1]*ys] for j in range(3)] inkex.etree.SubElement( group, SVG_PATH_TAG,
lst += biarc(sp1,sp2,0,0) {
'style': style['line'],
lst.append( 'd':'M %s,%s L %s,%s' % (s[0][0], s[0][1], si[0][0], si[0][1]),
[[subpath[-1][1][0]*xs, subpath[-1][1][1]*ys], 'end', 0, 0] 'comment': str(s)
) }
)
return lst elif s[1] == 'arc':
arcn += 1
def draw_curve(self, curve, group=None, style=BIARC_STYLE): sp = s[0]
if group==None: c = s[2]
group = inkex.etree.SubElement( self.biarcGroup, SVG_GROUP_TAG ) a = ( (P(si[0])-P(c)).angle() - (P(s[0])-P(c)).angle() )%(2*math.pi) #s[3]
s, arcn = '', 0 if s[3]*a<0:
for si in curve: if a>0: a = a-2*math.pi
if s!='': else: a = 2*math.pi+a
if s[1] == 'line': r = math.sqrt( (sp[0]-c[0])**2 + (sp[1]-c[1])**2 )
inkex.etree.SubElement( group, SVG_PATH_TAG, a_st = ( math.atan2(sp[0]-c[0],- (sp[1]-c[1])) - math.pi/2 ) % (math.pi*2)
{ if a>0:
'style': style['line'], a_end = a_st+a
'd':'M %s,%s L %s,%s' % (s[0][0], s[0][1], si[0][0], si[0][1]), else:
'comment': str(s) a_end = a_st*1
} a_st = a_st+a
) inkex.etree.SubElement( group, inkex.addNS('path','svg'),
elif s[1] == 'arc': {
arcn += 1 'style': style['biarc%s' % (arcn%2)],
sp = s[0] inkex.addNS('cx','sodipodi'): str(c[0]),
c = s[2] inkex.addNS('cy','sodipodi'): str(c[1]),
a = ( (P(si[0])-P(c)).angle() - (P(s[0])-P(c)).angle() )%(2*math.pi) #s[3] inkex.addNS('rx','sodipodi'): str(r),
if s[3]*a<0: inkex.addNS('ry','sodipodi'): str(r),
if a>0: a = a-2*math.pi inkex.addNS('start','sodipodi'): str(a_st),
else: a = 2*math.pi+a inkex.addNS('end','sodipodi'): str(a_end),
r = math.sqrt( (sp[0]-c[0])**2 + (sp[1]-c[1])**2 ) inkex.addNS('open','sodipodi'): 'true',
a_st = ( math.atan2(sp[0]-c[0],- (sp[1]-c[1])) - math.pi/2 ) % (math.pi*2) inkex.addNS('type','sodipodi'): 'arc',
if a>0: 'comment': str(s)
a_end = a_st+a })
else: s = si
a_end = a_st*1
a_st = a_st+a
inkex.etree.SubElement( group, inkex.addNS('path','svg'), def check_dir(self):
{ if (os.path.isdir(self.options.directory)):
'style': style['biarc%s' % (arcn%2)], if (os.path.isfile(self.options.directory+'/header')):
inkex.addNS('cx','sodipodi'): str(c[0]), f = open(self.options.directory+'/header', 'r')
inkex.addNS('cy','sodipodi'): str(c[1]), self.header = f.read()
inkex.addNS('rx','sodipodi'): str(r), f.close()
inkex.addNS('ry','sodipodi'): str(r), else:
inkex.addNS('start','sodipodi'): str(a_st), self.header = HEADER_TEXT
inkex.addNS('end','sodipodi'): str(a_end), if (os.path.isfile(self.options.directory+'/footer')):
inkex.addNS('open','sodipodi'): 'true', f = open(self.options.directory+'/footer','r')
inkex.addNS('type','sodipodi'): 'arc', self.footer = f.read()
'comment': str(s) f.close()
}) else:
s = si self.footer = FOOTER_TEXT
else:
inkex.errormsg(_("Directory does not exist!"))
def check_dir(self): return
if (os.path.isdir(self.options.directory)):
if (os.path.isfile(self.options.directory+'/header')): # Turns a list of arguments into gcode-style parameters (eg (1, 2, 3) -> "X1 Y2 Z3"),
f = open(self.options.directory+'/header', 'r') # taking scaling, offsets and the "parametric curve" setting into account
self.header = f.read() def make_args(self, c):
f.close() c = [c[i] if i<len(c) else None for i in range(6)]
else: if c[5] == 0:
self.header = HEADER_TEXT c[5] = None
if (os.path.isfile(self.options.directory+'/footer')): # next few lines generate the stuff at the front of the file - scaling, offsets, etc (adina)
f = open(self.options.directory+'/footer','r') if self.options.generate_not_parametric_code:
self.footer = f.read() s = ["X", "Y", "Z", "I", "J", "K"]
f.close() s1 = ["","","","","",""]
else:
self.footer = FOOTER_TEXT # my replacement that hopefully makes sense (adina, june 22 2010)
else: m = [self.options.Xscale, -self.options.Yscale, 1,
inkex.errormsg(_("Directory does not exist!")) self.options.Xscale, -self.options.Yscale, 1]
return a = [self.options.Xoffset, self.options.Yoffset, 0, 0, 0, 0]
else:
# Turns a list of arguments into gcode-style parameters (eg (1, 2, 3) -> "X1 Y2 Z3"), s = ["X", "Y", "Z", "I", "J", "K"]
# taking scaling, offsets and the "parametric curve" setting into account s1 = ["", "", "", "", "", ""]
def make_args(self, c): m = [1, -1, 1, 1, -1, 1]
c = [c[i] if i<len(c) else None for i in range(6)] a = [0, 0, 0, 0, 0, 0]
if c[5] == 0:
c[5] = None a[1] += self.pageHeight
# next few lines generate the stuff at the front of the file - scaling, offsets, etc (adina)
if self.options.generate_not_parametric_code: #I think this is the end of generating the header stuff (adina, june 22 2010)
s = ["X", "Y", "Z", "I", "J", "K"] args = []
s1 = ["","","","","",""] for i in range(6):
if c[i]!=None:
# my replacement that hopefully makes sense (adina, june 22 2010) value = self.unitScale*(c[i]*m[i]+a[i])
m = [self.options.Xscale, -self.options.Yscale, 1, args.append(s[i] + ("%f" % value) + s1[i])
self.options.Xscale, -self.options.Yscale, 1] return " ".join(args)
a = [self.options.Xoffset, self.options.Yoffset, 0, 0, 0, 0]
else: def generate_gcode(self, curve, depth, laserPower, altfeed=None, altppm=None):
s = ["X", "Y", "Z", "I", "J", "K"] gcode = ''
s1 = ["", "", "", "", "", ""]
m = [1, -1, 1, 1, -1, 1] #Setup our feed rate, either from the layer name or from the default value.
a = [0, 0, 0, 0, 0, 0] if (altfeed):
# Use the "alternative" feed rate specified
a[1] += self.pageHeight cutFeed = "F%i" % altfeed
else:
#I think this is the end of generating the header stuff (adina, june 22 2010) if self.options.generate_not_parametric_code:
args = [] cutFeed = "F%i" % self.options.feed
for i in range(6): else:
if c[i]!=None: cutFeed = "F%i" % self.options.feed
value = self.unitScale*(c[i]*m[i]+a[i])
args.append(s[i] + ("%f" % value) + s1[i]) #Setup our pulse per millimetre option, if applicable
return " ".join(args) #B: laser firing mode (0 = continuous, 1 = pulsed, 2 = raster)
if (altppm):
def generate_gcode(self, curve, depth, altfeed=None): # Use the "alternative" ppm - L60000 is 60ms
gcode = '' ppmValue = "L60000 P%.2f B1 D0" % altppm
if (altfeed): else:
# Use the "alternative" feed rate specified #Set the laser firing mode to continuous.
f = " F%i" % altfeed ppmValue = "B0 D0"
else:
if self.options.generate_not_parametric_code: cwArc = "G02"
f = " F%i" % self.options.feed ccwArc = "G03"
else:
f = " F100" # The geometry is reflected, so invert the orientation of the arcs to match
if (self.flipArcs):
cwArc = "G02" (cwArc, ccwArc) = (ccwArc, cwArc)
ccwArc = "G03"
if (self.flipArcs): # The 'laser on' and 'laser off' m-codes get appended to the GCODE generation
# The geometry is reflected, so invert the orientation of the arcs to match lg = 'G00'
(cwArc, ccwArc) = (ccwArc, cwArc) for i in range(1,len(curve)):
s, si = curve[i-1], curve[i]
# Peter's note: Here's where the 'laser on' and 'laser off' m-codes get appended to the GCODE generation
lg = 'G00' #G00 : Move with the laser off to a new point
for i in range(1,len(curve)): if s[1] == 'move':
s, si = curve[i-1], curve[i] #Turn off the laser if it was on previously.
#feed = f if lg not in ['G01','G02','G03'] else '' if lg != "G00":
gcode += LASER_OFF + "\n"
if (lg not in ["G01", "G02", "G03"]):
feed = f gcode += "G00" + " " + self.make_args(si[0]) + " F%i" % self.options.Mfeed + "\n"
else: lg = 'G00'
feed = ""
elif s[1] == 'end':
if s[1] == 'move': lg = 'G00'
# Traversals (G00) tend to signal either the toolhead coming up, going down, or indexing to a new workplace. All other cases seem to signal cutting.
gcode += LASER_OFF + "\nG00" + " " + self.make_args(si[0]) + " F%i" % self.options.Mfeed + "\n" #G01 : Move with the laser turned on to a new point
lg = 'G00' elif s[1] == 'line':
#No longer needed because G01, G02 and G03 will be forced in marlin to automatically fire the laser.
elif s[1] == 'end': #If the laser was turned off, turn it back on.
lg = 'G00' #if lg == "G00":
# gcode += LASER_ON + "\n"
elif s[1] == 'line':
if lg=="G00": gcode += "G01 " + "S%.2f " % laserPower + self.make_args(si[0]) + " %s " % cutFeed + "%s" % ppmValue + "\n"
#gcode += "G01 " + self.make_args([None,None,s[5][0]+depth]) + feed +"\n" + LASER_ON lg = 'G01'
gcode += LASER_ON + " S%i" % self.options.laser + "\n"
gcode += "G01 " +self.make_args(si[0]) + " F%i" % self.options.feed + "\n" #G02 and G03 : Move in an arc with the laser turned on.
lg = 'G01' elif s[1] == 'arc':
#No longer needed because G01, G02 and G03 will be forced in marlin to automatically fire the laser.
elif s[1] == 'arc': #If the laser was turned off, turn it back on.
if lg=="G00": #if lg == "G00":
#gcode += "G01 " + self.make_args([None,None,s[5][0]+depth]) + feed +"\n" + LASER_ON # gcode += LASER_ON + "\n"
gcode += LASER_ON + " S%i" % self.options.laser + "\n"
dx = s[2][0]-s[0][0]
dx = s[2][0]-s[0][0] dy = s[2][1]-s[0][1]
dy = s[2][1]-s[0][1] if abs((dx**2 + dy**2)*self.options.Xscale) > self.options.min_arc_radius:
if abs((dx**2 + dy**2)*self.options.Xscale) > self.options.min_arc_radius: r1 = P(s[0])-P(s[2])
r1 = P(s[0])-P(s[2]) r2 = P(si[0])-P(s[2])
r2 = P(si[0])-P(s[2]) if abs(r1.mag() - r2.mag()) < 0.001:
if abs(r1.mag() - r2.mag()) < 0.001: if (s[3] > 0):
if (s[3] > 0): gcode += cwArc
gcode += cwArc else:
else: gcode += ccwArc
gcode += ccwArc gcode += " " + "S%.2f " % laserPower + self.make_args(si[0] + [None, dx, dy, None]) + " %s " % cutFeed + "%s" % ppmValue + "\n"
gcode += " " + self.make_args(si[0] + [None, dx, dy, None]) + " F%i" % self.options.feed + "\n"
else:
else: r = (r1.mag()+r2.mag())/2
r = (r1.mag()+r2.mag())/2 if (s[3] > 0):
if (s[3] > 0): gcode += cwArc
gcode += cwArc else:
else: gcode += ccwArc
gcode += ccwArc gcode += " " + "S%.2f " % laserPower + self.make_args(si[0]) + " R%f" % (r*self.options.Xscale) + " %s " % cutFeed + "%s" % ppmValue + "\n"
gcode += " " + self.make_args(si[0]) + " R%f" % (r*self.options.Xscale) + " F%i" % self.options.feed + "\n"
lg = cwArc
lg = cwArc #The arc is less than the minimum arc radius, draw it as a straight line.
else: else:
if lg=="G00": gcode += "G01 " + "S%.2f " % laserPower + self.make_args(si[0]) + " %s " % cutFeed + "%s" % ppmValue + "\n"
#gcode += "G01 " + self.make_args([None,None,s[5][0]+depth]) + feed +"\n" + LASER_ON lg = 'G01'
gcode += LASER_ON + " S%i" % self.options.laser + "\n"
gcode += "G01 " +self.make_args(si[0]) + " F%i" % self.options.feed + "\n"
lg = 'G01' #The end of the layer.
if si[1] == 'end':
gcode += LASER_OFF
if si[1] == 'end':
gcode += LASER_OFF
if self.options.homeafter: return gcode
gcode += "\n\nG28 ; home all"
def tool_change(self):
return gcode # Include a tool change operation
gcode = TOOL_CHANGE % (self.currentTool+1)
def tool_change(self): # Select the next available tool
# Include a tool change operation self.currentTool = (self.currentTool+1) % 32
gcode = TOOL_CHANGE % (self.currentTool+1) return gcode
# Select the next available tool
self.currentTool = (self.currentTool+1) % 32 ################################################################################
return gcode ###
### Curve to Gcode
################################################################################ ###
### ################################################################################
### Curve to Gcode
### def effect_curve(self, selected):
################################################################################ selected = list(selected)
def effect_curve(self, selected): # Set group
selected = list(selected) if self.options.drawCurves and len(selected)>0:
self.biarcGroup = inkex.etree.SubElement( selected[0].getparent(), SVG_GROUP_TAG )
# Set group options.Group = self.biarcGroup
if self.options.drawCurves and len(selected)>0:
self.biarcGroup = inkex.etree.SubElement( selected[0].getparent(), SVG_GROUP_TAG ) # Recursively compiles a list of paths that are decendant from the given node
options.Group = self.biarcGroup self.skipped = 0
def compile_paths(node, trans):
# Recursively compiles a list of paths that are decendant from the given node # Apply the object transform, along with the parent transformation
self.skipped = 0 mat = node.get('transform', None)
def compile_paths(node, trans): if mat:
# Apply the object transform, along with the parent transformation mat = simpletransform.parseTransform(mat)
mat = node.get('transform', None) trans = simpletransform.composeTransform(trans, mat)
if mat:
mat = simpletransform.parseTransform(mat) if node.tag == SVG_PATH_TAG:
trans = simpletransform.composeTransform(trans, mat) # This is a path object
if (not node.get("d")): return []
if node.tag == SVG_PATH_TAG: csp = cubicsuperpath.parsePath(node.get("d"))
# This is a path object if (trans):
if (not node.get("d")): return [] simpletransform.applyTransformToPath(trans, csp)
csp = cubicsuperpath.parsePath(node.get("d")) return csp
if (trans):
simpletransform.applyTransformToPath(trans, csp) elif node.tag == SVG_GROUP_TAG:
return csp # This node is a group of other nodes
path = []
elif node.tag == SVG_GROUP_TAG: for child in node.iterchildren():
# This node is a group of other nodes path += compile_paths(child, trans)
path = [] return path
for child in node.iterchildren(): logger.write("skipping " + str(node.tag))
path += compile_paths(child, trans) self.skipped += 1
return path return []
logger.write("skipping " + str(node.tag))
self.skipped += 1 # Compile a list of layers in this document. We compile a list of only the layers
return [] # we need to use, so we can know ahead of time whether to put tool change
# operations between them.
# Compile a list of layers in this document. We compile a list of only the layers layers = []
# we need to use, so we can know ahead of time whether to put tool change for layer in reversed(get_layers(self.document)):
# operations between them. for node in layer.iterchildren():
layers = [] if (node in selected):
for layer in reversed(get_layers(self.document)): layers.append(layer)
for node in layer.iterchildren(): break
if (node in selected):
layers.append(layer) layers = list(reversed(get_layers(self.document)))
break
# Loop over the layers and objects
layers = list(reversed(get_layers(self.document))) gcode = ""
for layer in layers:
# Loop over the layers and objects label = layer.get(SVG_LABEL_TAG).strip()
gcode = "" if (label.startswith("#")):
for layer in layers: # Ignore everything selected in this layer
label = layer.get(SVG_LABEL_TAG).strip() for node in layer.iterchildren():
if (label.startswith("#")): if (node in selected):
# Ignore everything selected in this layer selected.remove(node)
for node in layer.iterchildren(): continue
if (node in selected):
selected.remove(node) # Parse the layer label text, which consists of the layer name followed
continue # by an optional number of arguments in square brackets.
try:
# Parse the layer label text, which consists of the layer name followed (layerName, layerParams) = parse_layer_name(label)
# by an optional number of arguments in square brackets. except ValueError,e:
try: inkex.errormsg(str(e))
(layerName, layerParams) = parse_layer_name(label) return
except ValueError,e:
inkex.errormsg(str(e)) # Check if the layer specifies an alternative (from the default) feed rate
return altfeed = layerParams.get("feed", None)
altppm = layerParams.get("ppm", None)
# Check if the layer specifies an alternative (from the default) feed rate
altfeed = layerParams.get("feed", None) logger.write("layer %s" % layerName)
if (layerParams):
logger.write("layer %s" % layerName) logger.write("layer params == %s" % layerParams)
if (layerParams): pathList = []
logger.write("layer params == %s" % layerParams) # Apply the layer transform to all objects within the layer
pathList = [] trans = layer.get('transform', None)
# Apply the layer transform to all objects within the layer trans = simpletransform.parseTransform(trans)
trans = layer.get('transform', None)
trans = simpletransform.parseTransform(trans) for node in layer.iterchildren():
if (node in selected):
for node in layer.iterchildren(): logger.write("node %s" % str(node.tag))
if (node in selected): selected.remove(node)
logger.write("node %s" % str(node.tag)) pathList += compile_paths(node, trans)
selected.remove(node) else:
pathList += compile_paths(node, trans) logger.write("skipping node %s" % node)
else:
logger.write("skipping node %s" % node) if (not pathList):
logger.write("no objects in layer")
if (not pathList): continue
logger.write("no objects in layer") curve = self.parse_curve(pathList)
continue
curve = self.parse_curve(pathList) #Determind the power of the laser that this layer should be cut at.
#If the layer is not named as an integer value then default to the laser intensity set at the export settings.
# If there are several layers, start with a tool change operation #Fetch the laser power from the export dialog box.
if (len(layers) > 1): laserPower = self.options.laser
gcode += LASER_OFF+"\n"
size = 60 if (int(layerName) > 0 and int(layerName) <= 100):
gcode += "(%s)\n" % ("*"*size) laserPower = int(layerName)
gcode += ("(***** LAYER: %%-%ds *****)\n" % (size-19)) % (layerName) else :
gcode += "(%s)\n" % ("*"*size) laserPower = self.options.laser
gcode += "(MSG,Starting layer '%s')\n\n" % layerName
# Move the laser into the starting position (so that way it is positioned #Switch between smoothie power levels and ramps+marlin power levels
# for testing the power level, if the user wants to change that). #ramps and marlin expect 0 to 100 while smoothie wants 0.0 to 1.0
arg = curve[0] if (self.options.mainboard == 'smoothie'):
pt = arg[0] laserPower = laserPower / 100
gcode += "G00 " + self.make_args(pt) + "\n"
gcode += self.tool_change()
# If there are several layers, start with a tool change operation
if (self.options.drawCurves): #Turnkey : Always output the layer header for information.
self.draw_curve(curve) if (len(layers) > 0):
gcode += LASER_OFF+"\n"
gcode += self.generate_gcode(curve, 0, altfeed=altfeed) size = 60
gcode += ";(%s)\n" % ("*"*size)
# If there are any objects left over, it's because they don't belong gcode += (";(***** Layer: %%-%ds *****)\n" % (size-19)) % (layerName)
# to any inkscape layer (bug in inkscape?). Output those now. gcode += (";(***** Laser Power: %%-%ds *****)\n" % (size-25)) % (laserPower)
if (selected): gcode += (";(***** Feed Rate: %%-%ds *****)\n" % (size-23)) % (altfeed)
pathList = [] gcode += (";(***** Pulse Rate: %%-%ds *****)\n" % (size-24)) % (altppm)
# Use the identity transform (eg no transform) for the root objects gcode += ";(%s)\n" % ("*"*size)
trans = simpletransform.parseTransform("") gcode += ";(MSG,Starting layer '%s')\n\n" % layerName
for node in selected: # Move the laser into the starting position (so that way it is positioned
pathList += compile_paths(node, trans) # for testing the power level, if the user wants to change that).
arg = curve[0]
if (pathList): pt = arg[0]
curve = self.parse_curve(pathList) #gcode += "G00 " + self.make_args(pt) + "\n"
if (self.options.drawCurves):
self.draw_curve(curve)
if (self.options.drawCurves):
gcode += "\n(*** Root objects ***)\n" self.draw_curve(curve)
if (layers):
# Include a tool change operation between the layers outputted above #Generate the GCode for this layer
# and these "orphaned" objects. gcode += self.generate_gcode(curve, 0, laserPower, altfeed=altfeed, altppm=altppm)
gcode += self.tool_change()
# If there are any objects left over, it's because they don't belong
gcode += self.generate_gcode(curve, 0) # to any inkscape layer (bug in inkscape?). Output those now.
return gcode if (selected):
pathList = []
def effect(self): # Use the identity transform (eg no transform) for the root objects
global options trans = simpletransform.parseTransform("")
options = self.options for node in selected:
selected = self.selected.values() pathList += compile_paths(node, trans)
root = self.document.getroot() if (pathList):
self.pageHeight = float(root.get("height", None)) curve = self.parse_curve(pathList)
self.flipArcs = (self.options.Xscale*self.options.Yscale < 0) if (self.options.drawCurves):
self.currentTool = 0 self.draw_curve(curve)
self.filename = options.file.strip() gcode += "\n;(*** Root objects ***)\n"
if (self.filename == "-1.0" or self.filename == ""):
inkex.errormsg(_("Please select an output file name.")) #Fetch the laser power from the export dialog box.
return laserPower = self.options.laser
if (not self.filename.lower().endswith(GCODE_EXTENSION)): #Switch between smoothie power levels and ramps+marlin power levels
# Automatically append the correct extension #ramps and marlin expect 0 to 100 while smoothie wants 0.0 to 1.0
self.filename += GCODE_EXTENSION if (self.options.mainboard == 'smoothie'):
laserPower = laserPower / 100
logger.enabled = self.options.logging
logger.write("thlaser script started") gcode += self.generate_gcode(curve, 0, laserPower)
logger.write("output file == %s" % self.options.file)
if self.options.homeafter:
if len(selected)<=0: gcode += "\n\nG00 X0 Y0 F4000 ; home"
inkex.errormsg(_("This extension requires at least one selected path."))
return return gcode
self.check_dir() def effect(self):
global options
gcode = self.header; options = self.options
selected = self.selected.values()
if (self.options.unit == "mm"):
self.unitScale = 0.282222 root = self.document.getroot()
gcode += "G21 ; All units in mm\n" self.pageHeight = float(root.get("height", None))
elif (self.options.unit == "in"): self.flipArcs = (self.options.Xscale*self.options.Yscale < 0)
self.unitScale = 0.011111 self.currentTool = 0
gcode += "G20 ; All units in in\n"
else: self.filename = options.file.strip()
inkex.errormsg(_("You must choose mm or in")) if (self.filename == "-1.0" or self.filename == ""):
return inkex.errormsg(_("Please select an output file name."))
return
if not self.options.generate_not_parametric_code:
gcode += """ if (not self.filename.lower().endswith(GCODE_EXTENSION)):
; Cut Feedrate %i # Automatically append the correct extension
; Move Feedrate %i self.filename += GCODE_EXTENSION
; Laser Intensity %i \n""" % (self.options.feed, self.options.Mfeed, self.options.laser)
logger.enabled = self.options.logging
if self.options.homebefore: logger.write("thlaser script started")
gcode += "G28 ; home all\n\n" logger.write("output file == %s" % self.options.file)
#if self.options.function == 'Curve': if len(selected)<=0:
gcode += self.effect_curve(selected) inkex.errormsg(_("This extension requires at least one selected path."))
return
if (self.options.double_sided_cutting):
gcode += "\n\n(MSG,Please flip over material)\n\n" self.check_dir()
# Include a tool change operation
gcode += self.tool_change() gcode = self.header;
logger.write("*** processing mirror image") if (self.options.unit == "mm"):
self.unitScale = 0.282222
self.options.Yscale *= -1 gcode += "G21 ; All units in mm\n"
self.flipArcs = not(self.flipArcs) elif (self.options.unit == "in"):
self.options.generate_not_parametric_code = True self.unitScale = 0.011111
self.pageHeight = 0 gcode += "G20 ; All units in in\n"
gcode += self.effect_curve(selected) else:
inkex.errormsg(_("You must choose mm or in"))
try: return
f = open(self.options.directory+'/'+self.options.file, "w")
f.write(gcode + self.footer) if not self.options.generate_not_parametric_code:
f.close() gcode += """
except: ; Default Cut Feedrate %i mm per minute
inkex.errormsg(_("Can not write to specified file!")) ; Default Move Feedrate %i mm per minute
return ; Default Laser Intensity %i percent\n""" % (self.options.feed, self.options.Mfeed, self.options.laser)
if (self.skipped > 0): if self.options.homebefore:
inkex.errormsg(_("Warning: skipped %d object(s) because they were not paths" % self.skipped)) gcode += "G28 ; home all\n\n"
e = Gcode_tools() #if self.options.function == 'Curve':
e.affect() gcode += self.effect_curve(selected)
if (self.options.double_sided_cutting):
gcode += "\n\n;(MSG,Please flip over material)\n\n"
# Include a tool change operation
gcode += self.tool_change()
logger.write("*** processing mirror image")
self.options.Yscale *= -1
self.flipArcs = not(self.flipArcs)
self.options.generate_not_parametric_code = True
self.pageHeight = 0
gcode += self.effect_curve(selected)
try:
f = open(self.options.directory+'/'+self.options.file, "w")
f.write(gcode + self.footer)
f.close()
except:
inkex.errormsg(_("Can not write to specified file!"))
return
if (self.skipped > 0):
inkex.errormsg(_("Warning: skipped %d object(s) because they were not paths" % self.skipped))
e = Gcode_tools()
e.affect()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment