GCodeLoader.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import {
  2. BufferGeometry,
  3. FileLoader,
  4. Float32BufferAttribute,
  5. Group,
  6. LineBasicMaterial,
  7. LineSegments,
  8. Loader
  9. } from 'three';
  10. /**
  11. * A loader for the GCode format.
  12. *
  13. * GCode files are usually used for 3D printing or CNC applications.
  14. *
  15. * ```js
  16. * const loader = new GCodeLoader();
  17. * const object = await loader.loadAsync( 'models/gcode/benchy.gcode' );
  18. * scene.add( object );
  19. * ```
  20. *
  21. * @augments Loader
  22. * @three_import import { GCodeLoader } from 'three/addons/loaders/GCodeLoader.js';
  23. */
  24. class GCodeLoader extends Loader {
  25. /**
  26. * Constructs a new GCode loader.
  27. *
  28. * @param {LoadingManager} [manager] - The loading manager.
  29. */
  30. constructor( manager ) {
  31. super( manager );
  32. /**
  33. * Whether to split layers or not.
  34. *
  35. * @type {boolean}
  36. * @default false
  37. */
  38. this.splitLayer = false;
  39. }
  40. /**
  41. * Starts loading from the given URL and passes the loaded GCode asset
  42. * to the `onLoad()` callback.
  43. *
  44. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  45. * @param {function(Group)} onLoad - Executed when the loading process has been finished.
  46. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  47. * @param {onErrorCallback} onError - Executed when errors occur.
  48. */
  49. load( url, onLoad, onProgress, onError ) {
  50. const scope = this;
  51. const loader = new FileLoader( scope.manager );
  52. loader.setPath( scope.path );
  53. loader.setRequestHeader( scope.requestHeader );
  54. loader.setWithCredentials( scope.withCredentials );
  55. loader.load( url, function ( text ) {
  56. try {
  57. onLoad( scope.parse( text ) );
  58. } catch ( e ) {
  59. if ( onError ) {
  60. onError( e );
  61. } else {
  62. console.error( e );
  63. }
  64. scope.manager.itemError( url );
  65. }
  66. }, onProgress, onError );
  67. }
  68. /**
  69. * Parses the given GCode data and returns a group with lines.
  70. *
  71. * @param {string} data - The raw Gcode data as a string.
  72. * @return {Group} The parsed GCode asset.
  73. */
  74. parse( data ) {
  75. let state = { x: 0, y: 0, z: 0, e: 0, f: 0, extruding: false, relative: false };
  76. const layers = [];
  77. let currentLayer = undefined;
  78. const pathMaterial = new LineBasicMaterial( { color: 0xFF0000 } );
  79. pathMaterial.name = 'path';
  80. const extrudingMaterial = new LineBasicMaterial( { color: 0x00FF00 } );
  81. extrudingMaterial.name = 'extruded';
  82. function newLayer( line ) {
  83. currentLayer = { vertex: [], pathVertex: [], z: line.z };
  84. layers.push( currentLayer );
  85. }
  86. //Create lie segment between p1 and p2
  87. function addSegment( p1, p2 ) {
  88. if ( currentLayer === undefined ) {
  89. newLayer( p1 );
  90. }
  91. if ( state.extruding ) {
  92. currentLayer.vertex.push( p1.x, p1.y, p1.z );
  93. currentLayer.vertex.push( p2.x, p2.y, p2.z );
  94. } else {
  95. currentLayer.pathVertex.push( p1.x, p1.y, p1.z );
  96. currentLayer.pathVertex.push( p2.x, p2.y, p2.z );
  97. }
  98. }
  99. function delta( v1, v2 ) {
  100. return state.relative ? v2 : v2 - v1;
  101. }
  102. function absolute( v1, v2 ) {
  103. return state.relative ? v1 + v2 : v2;
  104. }
  105. const lines = data.replace( /;.+/g, '' ).split( '\n' );
  106. for ( let i = 0; i < lines.length; i ++ ) {
  107. const tokens = lines[ i ].split( ' ' );
  108. const cmd = tokens[ 0 ].toUpperCase();
  109. //Arguments
  110. const args = {};
  111. tokens.splice( 1 ).forEach( function ( token ) {
  112. if ( token[ 0 ] !== undefined ) {
  113. const key = token[ 0 ].toLowerCase();
  114. const value = parseFloat( token.substring( 1 ) );
  115. args[ key ] = value;
  116. }
  117. } );
  118. //Process commands
  119. //G0/G1 – Linear Movement
  120. if ( cmd === 'G0' || cmd === 'G1' ) {
  121. const line = {
  122. x: args.x !== undefined ? absolute( state.x, args.x ) : state.x,
  123. y: args.y !== undefined ? absolute( state.y, args.y ) : state.y,
  124. z: args.z !== undefined ? absolute( state.z, args.z ) : state.z,
  125. e: args.e !== undefined ? absolute( state.e, args.e ) : state.e,
  126. f: args.f !== undefined ? absolute( state.f, args.f ) : state.f,
  127. };
  128. //Layer change detection is or made by watching Z, it's made by watching when we extrude at a new Z position
  129. if ( delta( state.e, line.e ) > 0 ) {
  130. state.extruding = delta( state.e, line.e ) > 0;
  131. if ( currentLayer == undefined || line.z != currentLayer.z ) {
  132. newLayer( line );
  133. }
  134. }
  135. addSegment( state, line );
  136. state = line;
  137. } else if ( cmd === 'G2' || cmd === 'G3' ) {
  138. //G2/G3 - Arc Movement ( G2 clock wise and G3 counter clock wise )
  139. //console.warn( 'THREE.GCodeLoader: Arc command not supported' );
  140. } else if ( cmd === 'G90' ) {
  141. //G90: Set to Absolute Positioning
  142. state.relative = false;
  143. } else if ( cmd === 'G91' ) {
  144. //G91: Set to state.relative Positioning
  145. state.relative = true;
  146. } else if ( cmd === 'G92' ) {
  147. //G92: Set Position
  148. const line = state;
  149. line.x = args.x !== undefined ? args.x : line.x;
  150. line.y = args.y !== undefined ? args.y : line.y;
  151. line.z = args.z !== undefined ? args.z : line.z;
  152. line.e = args.e !== undefined ? args.e : line.e;
  153. } else {
  154. //console.warn( 'THREE.GCodeLoader: Command not supported:' + cmd );
  155. }
  156. }
  157. function addObject( vertex, extruding, i ) {
  158. const geometry = new BufferGeometry();
  159. geometry.setAttribute( 'position', new Float32BufferAttribute( vertex, 3 ) );
  160. const segments = new LineSegments( geometry, extruding ? extrudingMaterial : pathMaterial );
  161. segments.name = 'layer' + i;
  162. object.add( segments );
  163. }
  164. const object = new Group();
  165. object.name = 'gcode';
  166. if ( this.splitLayer ) {
  167. for ( let i = 0; i < layers.length; i ++ ) {
  168. const layer = layers[ i ];
  169. addObject( layer.vertex, true, i );
  170. addObject( layer.pathVertex, false, i );
  171. }
  172. } else {
  173. const vertex = [],
  174. pathVertex = [];
  175. for ( let i = 0; i < layers.length; i ++ ) {
  176. const layer = layers[ i ];
  177. const layerVertex = layer.vertex;
  178. const layerPathVertex = layer.pathVertex;
  179. for ( let j = 0; j < layerVertex.length; j ++ ) {
  180. vertex.push( layerVertex[ j ] );
  181. }
  182. for ( let j = 0; j < layerPathVertex.length; j ++ ) {
  183. pathVertex.push( layerPathVertex[ j ] );
  184. }
  185. }
  186. addObject( vertex, true, layers.length );
  187. addObject( pathVertex, false, layers.length );
  188. }
  189. object.rotation.set( - Math.PI / 2, 0, 0 );
  190. return object;
  191. }
  192. }
  193. export { GCodeLoader };