OrcaSlicer/src/libslic3r/GCode/GCodeProcessor.cpp
SoftFever 1bb8fad63f
Merge some changes from BS 1.9 (#4994)
* FIX: do not touch the plate with different printing sequence

jira: STUDIO-5424
Change-Id: I8ad00fa991b753de126a5bef0d320c452033e2e7
(cherry picked from commit c4adfe16e285f238f2c5cd8938b2167fdfb6b1b0)

* FIX: global arrange setting is wrong

global arrange setting is wrong if a plate's setting is changed from object list

jira: STUDIO-5438
Change-Id: Iaa7f35837edbacff9b97ca17a8ab34c8e6bb023d
(cherry picked from commit fa2f56575b2e4305e35dd59ff55e0881720de025)

* FIX: temperature symbols not shown correctly

Need to use wxString::FromUTF8 to convert unicode symbols to wxString.

jira: none

Change-Id: Ia8b559d437c956a2cc28916d8963823356402d05

* FIX:Repair calculation process of plate_box

Jira: STUDIO-5520
Change-Id: I4c3f9597542ad2dfec4d7849e75fa28272fa4ea3

* FIX:frequent calls to _update_imgui_select_plate_toolbar

Jira: STUDIO-5488
Change-Id: I12e6f37c2fe94de004aa6da43421970d6df10f0f

* FIX: & is not displayed on the sending print page

Jira: STUDIO-5343

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I1736bb97433581ff117bfe09afe8ee70c1b08fc4

* FIX: file name is not fully displayed if it is too long

Jira: STUDIO-5230
Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I992fa0c0575afbd2eecb2af02c8a305eda028f7f
(cherry picked from commit d0d7fb0b1394429ee9d28d8ef4060a286ba0112d)

* FIX: The warning box still exits when the temperature has reset.

Jira: STUDIO-5562

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I7532db69880449eb3fa0a14fc4dfc61e7f6d518e
(cherry picked from commit 589ed5fe045b5e7ec3effe437c9685085960c0fc)

* FIX: White circle is not clear on auto refill page

Jira: STUDIO-3262

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I05ac6257638063d32a9943c09bb7c14cc9229b3a

* FIX: Groove text ctrl is not wide engough

Jira: STUDIO-5434

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I93c0995473a72b5c19bc413c38c090906e360455
(cherry picked from commit e4a8b0ef5e62ba0053dc782c30ea79b237a46ac3)

* FIX: values are not saved when clicking on an empty space

Jira: STUDIO-4637

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I837050029635f673b3ae671ea1ad049aaf4fdd16

* FIX: Temperature warning is not fully displayed

Jira: STUDIO-5038

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I460cbe2a5d0a092c4257b7bd5192058bf2e4707b

* NEW: display bitmap when calibrating

Jira: STUDIO-4661

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I60cf4f9769feca74699012418880e93fcfe34432
(cherry picked from commit 1213aea816694405311dc0c1061655a4c2a1d067)

* FIX: remember the flow ratio calibration type

Jira: STUDIO-5181
Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: Id6125d1d4ea58972ce55c2c2498259596b25111e
(cherry picked from commit 1af1038fd4824d989e992cb630cf34e00c787af7)

* FIX: File panel crash on scroll

Change-Id: I56833a376fa52c960efea5fbd60003367ba410c2
Jira: STUDIO-5337, STUDIO-5513

* FIX: auto arranging skip unprintable high items

Jira: STUDIO-5646
Change-Id: I72dc3d8c71a075bab8204f4418e869a7a34c0c8e
(cherry picked from commit 0afdf8361493485da2254c426719594fd9a982ed)

* FIX: MediaFilePanel error state

Change-Id: I318ef59fb97478ffee16dff594022b2b9029964a
Jira: STUDIO-5638

* FIX: sync whole preset vendor directory

Change-Id: I191dbe979a87ff35d38cab1149b7975664344838
Jira: STUDIO-5534

* ENH: support turn off liveview auto retry

Change-Id: I24b39f74e0a40a13277d6eae3830c95c5c9de333
Jira: none
(cherry picked from commit f6ceb3fb8e4df3f876c50a1c4ba96b4a1be60190)

* FIX: SwitchButton auto scale font

Change-Id: If4004c0963cc8bb2f41e8e71c304d5239bf252ab
Jira: STUDIO-4969 STUDIO-4921

* FIX: set WEBKIT_DISABLE_COMPOSITING_MODE=1 for linux gtk

Change-Id: I8a500585ca815948bab1210578ba5c45858ed78e
Jira: STUDIO-5199

* FIX: Prefer old selection when sync AMS not compatible

Change-Id: I6b18db51887132a997cf78d70fff9a92e23bc44a
Jira: STUDIO-5416

* ENH: show liveview stat

Change-Id: I70d1f458aa2ed379ad7fe07dee76fbe035316420
Jira: none

* NEW:remember custom color

Jira: STUDIO-5635
Change-Id: I439080f6a8ddb6fde3899cffbabc3b6e66afbd96

* FIX: copy live555 dll

Change-Id: Idf727b8e26107e93aa9934299e87dc71531d1c63
Jira: STUDIO-4480

* FIX: optimize batch update object list on macOS

Change-Id: I92e24cc53c0b3bf0658d15abc64292f0e17c0a82
Jira: STUDIO-5440 STUDIO-5515

* FIX: network plugins tip disappear on dark mode

Change-Id: I422ab63f71158a49920438f01dd9c39774c27744
Jira: STUDIO-4891

* FIX: Display inconsistence in parameter table

JIra: STUDIO-3716

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: I986473bcbb3efff4abd9c5917926d9e888a4f28c

* FIX: Incomplete copy display in Transfer or discard dialog

Jira: 5569 5549

Change-Id: I757b636259d7e1a222b9fc09276c12235360fd57

* FIX: Limit the max length of k when calibrating

Jira: STUDIO-4291

Signed-off-by: wenjie.guo <wenjie.guo@bambulab.com>
Change-Id: Ie7cff086cf2a3c744213525d5d83f9ac4b55333d

* fix build break

* FIX: delete sdcard file crash

Change-Id: I814fd4b557fa92ac4060cbeb18a53f5616e49662
Jira: STUDIO-5977

* FIX: Yield when join media thread

Change-Id: I746d7df88a0de8363da7d9507cb63c9e0ffe970a
Jira: STUDIO-5952

* FIX: Guide page can't show in screen with mainframe

Jira: STUDIO-4911

Change-Id: I7e89614e0f1585263456c847a1b38dcfd0ad59e6

* FIX: filament combox has blank line

Change-Id: Ia39ddb564b3c9cc943d0ea4c0cf7cc4d24bef799

* FIX: load 3mf crash when studio has no base filament

Jira: none

Change-Id: I4387f425f60e6a53a53cf68addb1ab2d6f8f8901
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* FIX:add resume button

JIRA:github:2860
Change-Id: I39035d929876ab3c84c5f5c3494376967300938c

* FIX: CLI: fix an arrange issue when duplicate failed

restore the wipe_tower position to original when duplicate fail

JIRA: MAK-2638
Change-Id: I355056f1d87648cc1f6aafa15a98ff569359b44f

* FIX: fix printer list without nozzle such as 0.35 or 0.75

Jira: 5409

Change-Id: I1a258fd10bcc03e297b791256880f2518d602905

* ENH:The first object should locate at plate center

Jira: STUDIO-6023
Change-Id: If4284136fe63ca576463445f3ab16b6e18ead30f

* FIX: Colored filament is not matched against.

github: #2190
Colored filament is not matched against the same color in AMS slot.

Signed-off-by: Kunlong Ma <kunlong.ma@bambulab.com>
Change-Id: Id4588fc9c8115a46881e2f5d198d79fe831f4371

* FIX: Revert "[STUDIO-4284] not set max height of liveview window"

This reverts commit 0312aee4d9b92e23884be8802da9801ff3b9fe93.

Reason for revert: STUDIO-5653
Jira: STUDIO-5653

Change-Id: If9d5f3e63968a0a54f9af1a2dae8f95f7f1f3f80

* ENH:modify file name rules when export stl

Jira: STUDIO-6091
Change-Id: Ic27e4e341cc09099e98a5eab7dfd48416f2922ae

* FIX: Flow calibration stage incorrect when switching printers

Jira: 6093
Change-Id: I41f1ac10ac9422ac808eab3254f32ea14a0d3b76

* FIX: UserGuide Can not Click When Computer User name has chinese

JIRA: None
Change-Id: If50baa8c6a13eb501918fd5cdaf0ea3da7c788ef
(cherry picked from commit 4e5ccc9f2de5ac429af6541c6a8bd412848801d0)

* ENH: Little Optimize JS Code Execute Progress

JIRA: STUDIO-5792

Change-Id: I12b03d8b968a9dd8dfce9eb3ef925fa8768e2046
(cherry picked from commit 2bf861092c9e306e1311eda8ac36fd981e73b6c2)

* FIX: Delete Test Code

JIRA: NONE
Change-Id: I838a348edb22e09d2b1d5c41600c6fade535d184
(cherry picked from commit 51e664da0209ae8a3de5cbf30a72505c0b5bd028)

* FIX: the object list order changed after clone

github: 2798
Change-Id: I10a05ee7e00b05cb1255cfb708876ed784cabac7

* ENH: add alias for custom Filament preset

Jira: XXXX

Change-Id: I2fecc8b2bdb63618155e3d21f9db374a6119e416

* FIX: [5779] fix show alias logic when load preset

Jira: 5779

Change-Id: I4fefe3c1ffbca9bd8296f1b3fdd5de48c6a36a28

* ENH: Optimize the logic for deleting third-party printers

Mark the Filament and Process presets to be deleted first
then delete the child presets first and then the parent presets.

Jira: none

Change-Id: I100b873baae96c6ba27af258e708e6ab8e6ee4ab

* ENH:default selection of virtual tray

jira:[for def selected]

Change-Id: I0661f179f8e4bcac33ae12fbbeaeaf95c5b7c110

* ENH:add protection when no thumbnail data

jira:[for protection]

Change-Id: I3834a5ffde11ff54567dd854271184f06f94547f

* FIX:fixed issue with chinese path

jira:[Fixed the issue of failed loading of configuration files under Chinese path]

Change-Id: I9badd8fc158fcf49f46411ac4e5f72d58823eeb2

* NEW:add new msg notification for hms

jira:[STUDIO-6154]

Change-Id: If1aa33030a99550d0c859d594a2711aea4dcea4a

* NEW:using new humidity display ui

jira:[STUDIO-5967]

Change-Id: I13be4212e6b97f646d21e0af64cbc5006753fdeb

* NEW:Dye materials above grade 10 with shortcut keys

JIRA:STUDIO-5827
Change-Id: I002ecdd19167fb36772e4b4e9e2f7760e21079db

* NEW:update automatically when inserting materials

JIRA: STUDIO-6157
Change-Id: I2cefbb7b330ca4f13e841066548992b3fb3740f1

* FIX: check sdcard exists for file connect

Change-Id: I69199a29294c04d1fe46ee66682085b1f1d1d049
Jira: none

* FIX: not load printer files when it's busy

Change-Id: Ie5a58befcfc0d7fa0d4e587e8429c0b1bfeff72a
Jira: STUDIO-6105

* ENH: save video ctrl size to reduce layout change

Change-Id: I470f29d7f029d304c9badeeb8f94bed281080b29
Jira: STUDIO-6141

* ENH: stop liveview track record

Change-Id: Id4f236b239740bd919f2aa2f2892c1e63ce233bd
Jira: STUDIO-6131

* FIX: thread safe of http extra headers

Change-Id: I6ffa424be7ccb6abd78a66cc8be535f038b05469
Jira: none

* optimize MeshBoolean

* FIX: parse printer_model_id from 3mf

Change-Id: Ib149c986885ee6412898f1f51dd5a4aaad0a596d
Jira: none

* ENH: find grid empty cells for fill bed if the item is too small

jira: STUDIO-6015
Change-Id: I4e5eafdadd77482a27a8903d32bb83325283088d
(cherry picked from commit 8df4da4a863cdc42c790a9d5da37f8633423e406)

* ENH: always return product for firmware and lifycycle

JIRA: STUDIO-6282

Change-Id: I1f942babdcb7afee2c9a9076ac539063c5406ad7
Signed-off-by: Stone Li <stone.li@bambulab.com>

* ENH:STL tracking restricted area

jira:[STUDIO-6155]

Change-Id: I289c8b8aa8f62f0e5cc7004fb60437aa3337ca85

* NEW:add nozzle settings

jira:[STUDIO-6226]

Change-Id: I0db8333e5b5c8195add111fdcfa2e92387997815

* ENH:display the current humidity of AMS

jira:[ENH]

Change-Id: I98bdd6d70cd173ed640f0d96692fcb6836416bb8

* FIX: [6123] create printer for exist printer can not into next page

Jira: 6123

Change-Id: I338ac0fde4f69b6f312f20e53851d91339e8156f

* ENH: Display value of flushing volumes

JIRA:STUDIO-6139

Signed-off-by: Kunlong Ma <kunlong.ma@bambulab.com>
Change-Id: I273fb22b0d378a839c34e9e0e9c414f0e5134799

* FIX: show printer file path & title

Change-Id: Ie5eff188c3039deeca5da96b54407194bf8910a0
Jira: STUDIO-6268

* FIX: liveview error message

Change-Id: Ie437e07916d7b6feae2dbcfa166c4e73bdcf31a1
Jira: STUDIO-6107

* FIX: file proto error message

Change-Id: I2c4117961c615e424780fb3830441e6a93c50bcc
Jira: none

* ENH: earse sensitive fields when export configs

Jira: None

Change-Id: Id9ca0637240b80773f39d2308192f8c78a5de3c6

* fix build errors

* FIX: unexpected layers in multi color print

github: 3131
Change-Id: I2a42e3bbd2247fbc0957022e1baae43c9375a8fb

* ENH: Add "New" button for PA cali

Jira: XXXX
Change-Id: Ic39f2508f2f9d390c2b9246fb3d3e281cde9b064

* NEW:add printer compatible check from sd card view

jira:[STUDIO-5969]

Change-Id: I86d10ebe2e9bc77e6350e26aeed6b4f0f9fdcecb

* NEW:enable loadl/unload when printing pause

jira:[STUDIO-5968]

Change-Id: Ieb3ef2423378e44b81a61a2b18c16f68aa335922

* FIX:fixed HMS message not cleared

jira:[STUDIO-6296]

Change-Id: Ic7692ce337fd00ece4ab8d65214a8c406f8543f8

* ENH:error code setting default value

jira:[for error code]

Change-Id: Ica61344c8217d41adb2947a40f633dc8d19a197a

* ENH:display conflict information

jira:[STUDIO-6297]

Change-Id: Ie1501323a7e8d9ceb4060ae6c0b4eab20f8b088a

* ENH: refresh printer file list

Change-Id: Ic86942d2b0b2e8383ef0f06311164aad59e837ad
Github: 3383

* FIX: Unnecessary prime tower error prompts

Custom gcode on other plate causes unnecessary prime tower error prompts
Jira: 6305

Change-Id: If499659b364a6b6898db1587b7b2aeed03758667

* FIX:multi colour displayed as gradient color on AMS

JIRA:5925
Change-Id: Ic7a925dda2e3bde066ba40ba27002569040f9518

* NEW:Color painting shortcut keys 10~16

JIRA:STUDIO-6238
Change-Id: I3cce838fad5e73d41f109b32f2e563716fd5b0da

* ENH: Print when unnamed project, task named as object names

github: #2286

Change-Id: I9be3fd25d16a00b78326ec43db9afcf3645d90f1

* ENH:reset user access code

jira:[for lan mode]

Change-Id: I2d0ed48411d683c3f20b2febc0d54747287870a7

* FIX:fixed crash when selecting new printer

jira:[fix]

Change-Id: I6a81186e822eb6bf6ce7aa70561dfae35d4de0e7

* FIX: not show printer's camera error when updating

Jira: STUDIO-6232
Change-Id: I985d75b3772849e07100799c4f13db5d4cbafde3

* FIX: clear error after reload file list ok

Change-Id: I5d5e4f2870302b198d3a9d40603a6fa8010b7e76
Jira: STUDIO-6306

* ENH: custom filament sync with printer

1. prompt sync user presets when create custom filament
2. Fix the issue of not displaying printers when creating custom Filaments based on presets when selecting PLA Aero Type.
3. Optimizing the traversal logic during AMS Setting Pop up reduces time complexity and allows for quick pop ups. Additionally, using nozzle calibers for retrieval and repairing custom materials may result in inaccurate retrieval.
4. Implement synchronization logic with the printer
	-a. Received slot information, reset the slot when the "filament_id" in the information does not exist in Studio
	-b. Received slot information, the nozzle temperature in the information is different from the preset nozzle temperature in Studio, reset the current temperature.

Jira: none

Change-Id: I511dc82563ec77a341839671d398607048ce1985
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* NEW: add api of "toggle_selected_volume_visibility"

Jira: STUDIO-6166
Change-Id: I77eb988a3ea43cd37d50888d1753b973795d8b36

* FIX: No data in the drop-down menu of the AMS settings page

Jira: 6342 6343

Change-Id: I6938fb4a7ae2816a4675d8d739622e25f219f469

* fix build error

* FIX: label wrap all & ping test for liveview

Change-Id: I7767ed0740e20bb578b6ef9f5e9873c8c79d172a
Jira: STUDIO-5821

* ENH: reuse controls in param Field

Change-Id: I42bb4da01e1e9b64c343b7fda4357a9553cf8684
Jira: STUDIO-5983

* FIX: use wide path to create camera process

Change-Id: I5de31fce0dea14df9a0ad363f3cb16dc40c275bc
Jira: STUDIO-4946

* ENH: optimize the get_tool_order func

Use Dp to refine performance

jira:[NEW]

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I38b0c875e4deee9d9fbe926087fb5b2e274f8f90
(cherry picked from commit 9b7b66dc7a1f5e3efa318227ae7694bec5ec1216)

* Fix build errors

* ENH: add customize other layers print sequence

Jira: 6338
Change-Id: Ic14b2671ade37ab37583b81c5b509447b6c0d8f8

* ENH: [#3236] Unsaved changes to interface copy adjustment

github: #3236

Change-Id: I53931859bdcdfedfa9f63f6239d0fd2fd6d2766c

* NEW: support to adjust other layers print sequence

Jira: 6338

Change-Id: I5e6aef71aa9e6e97c1859aaaeb9ada5f1340414a

* FIX: imgui support toolbar window text wrapping issue

jira: STUDIO-5821

Change-Id: I57ee984baffbb2f00a7ecc5d5c8061074b06aff6

* FIX: updater: fix force upgrade logic

JIRA: STUDIO-6393
Change-Id: I46c51e09e7390e5ab0de40215911aac9635ab476
(cherry picked from commit 673ba6ff4ebda039d71dcbfdaa28c1252f5b8821)

* FIX:final step of slicing is to execute post-processing script

JIRA: STUDIO-5828
Change-Id: I8c33e2a66ac5c692244c778586040663b7b54bd7

* NEW:enable 3dMouse detect in .conf

JIRA: 5830
Change-Id: I8731e0244d2f551130c84bcfbbb46967ae6b19cd

* FIX:finish init "return" icon and hide it

Jira: STUDIO-6350
Change-Id: I0f1efd4a64ea204daeac7de822602ef6dfa3e4a5

* FIX: seq_print: fix an invalid warning caused by sinking

github: https://github.com/bambulab/BambuStudio/issues/3007
Change-Id: I1111910f2c625d5a871ea01b37dbfa7b04a849ee
(cherry picked from commit a3db95bb0940d5afe07ef0bb07113cc2acd7cd0a)

* ENH: plater: optimize the loading time of 3mf with large objects

JIRA: STUDIO-6021
Change-Id: Ia97f681041bb553c5c4b5b1d9109e5e5c42daf6b

* FIX:Fixed HMS issue

jira:[STUDIO-6344 STUDIO-6310 STUDIO-6356  STUDIO-6348]

Change-Id: I9d6660e7c349775004b69bfe41b651bfa8b359b7

* ENH:handling dirty data after nozzle settings

jira:[STUDIO-6332]

Change-Id: I00d6d1324376f973ec3cf9f2154ae83ef3302705

* ENH: use Bambu_StartStreamEx for agora tunnel

Change-Id: I5c28dea49d267bf7ff967d0982dd83555899c8c4
Jira: none

* FIX: use safe language code for http

Change-Id: Id1f4927308350ee35b891a5352cbf1e2d0c2577e
Github: 3655

* FIX: add cli_id, cli_ver to bambu url

Change-Id: Ic527d1497c6dee0c723d7b4629f0be825a8f7545
Jira: none

* FIX: not throw when _add_auxiliary_dir_to_archive

Change-Id: Idf54bbbd0ef557ec5e1a8e51ed669a1eb1fb4261
Jira: STUDIO-6339

* NEW: vase mode can be applied to one plate

jira: STUDIO-5838

Change-Id: Ifb315f7d79b570aeb7ee31d3495b4d465e3af0c6

* fix crashes

* ENH: update overhang degree method on calssic mode

Jira: none

Signed-off-by: qing.zhang <qing.zhang@bambulab.com>
Change-Id: I90f6e4c2ef618fdaef00bdaf1ca309893f484c1e

* FIX: auto-arranging unprintable items may crash

github: #3676
Change-Id: I68eb87c73ad2c0c269f60e661136fd1a72ee5e2f
(cherry picked from commit 7e3c57eaa811424935fe8db6a4e77dd142ee2b58)

* FIX: use old slicer_uuid for client_id

Change-Id: I6c45e83213d613fc28eef04115f9cfb19dea703e
Jira: none

* ci: update network module based on commit 542ced8

Change-Id: I3ad5032cc56a99d1c3a687b2891d147b13af066d

* NEW:Support OLTP file

Jira: STUDIO-6421
Change-Id: I58bc94e978e6d2dd136ea370fb01f6ec80e14b23

* ENH: detect in_head_wrap_zone more precisly

1.Union first layer convex hull with object's bbox to detect whether
model enter head_wrap_detect_zone

jira:NEW

Signed-off-by: XunZhangBambu <xun.zhang@bambulab.com>
Change-Id: I11f26967d7421f41e9c824e62794c96591e6ae71

* FIX: fix the plate cannot be searched

JIRA: STUDIO-6283

Signed-off-by: Kunlong Ma <kunlong.ma@bambulab.com>
Change-Id: I88206c91ea24c6a41a0bd06f05f0f3c2fdc58a36

* NEW:hms error code

JIRA: STUDIO-6302
Change-Id: Ia33511f4c636c8ada39ed5a4e52d9b185da9c00b

* FIX:Color adaptation for numpad

JIRA:STUDIO-6410
Change-Id: If6e49638af8616fd349367073883592e6bebb503

* FIX: error overhang degree mapping

Jira: none

Signed-off-by: qing.zhang <qing.zhang@bambulab.com>
Change-Id: Ifa24aa0cad0a06b09ee62a8be8781188a765d1d0

* FIX:display correct humidity

jira:[fix]

Change-Id: I27aae54a8355911b5d88ed45be320d3c9178081c

* ENH:Hide confirmation button when unable to send print

jira:[STUDIO-6355, STUDIO-6332]

Change-Id: I8f9c0edea4d5ee70e9fef1e9d42838d598dc32c4

* NEW: new type for Custom Filament

Type: "PE", "PP", "EVA", "PHA", "BVOH", "PE-CF", "PP-CF", "PP-GF"

Github: 3205 3169 3127

Change-Id: I8a30dd806c35460d9dae0f808190ce013b125d51
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* FIX:fixed filament settings page display error in French

jira:[STUDIO-5821]

Change-Id: I6cc6dd9b83c7570688c2adc55efe2407cbcb4390

* FIX:fixed thumbnail not updating when using multiple plates

jira:[STUDIO-6313]

Change-Id: If49daa5b38b9a580ae226ff00a1e0085d167c15c

* FIX: Color Bleed in slicer

github: 3681 jira: 6450
Change-Id: Icb6274f7ddb238c238c133b95167310b1af905f7

* ci: update network module based on commit 8befd46

Change-Id: I3a6420684f106bdde5897a50d27dfec69e0aa37f

* ci: update network module based on commit e411785

Change-Id: I3a9c7bfa5ac5a942f339ad0194a24d9170847371

* FIX:reload paint after background process apply

Jira: STUDIO-6493
Change-Id: I9a1986152f05163f236f58bb24210b690ca3d562

* FIX: use object name of plate when send task in untitled project

Jira: 6430

Change-Id: I78ec811fab1cf028c0d5f81ac7738abdbeb6145f

* FIX: auto arranging spacing can't be adjusted correctly

jira: none
Change-Id: Ibddfe85aab9f3fad6a1612e8db437e52c40e20a3
(cherry picked from commit 136bca01f45e62042bd699a9a0a9f6d13519712c)

* FIX: fix change nozzle temp in Studio but printer not change

Jira: 6510

Change-Id: Ia0e1ac586ff41ddbabdac0845415e70774299387
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* ENH:rename some img files

jira:[STUDIO-6512]

Change-Id: I69872533cccda37b94384bc219cc35c5dec9310b

* ENH:PEI bed is no longer unchecked by default

jira:[STUDIO-6508]

Change-Id: Ic9ca99860d46c27ca4c36a735df3f57fe71417df

* FIX:fix the load status of vtray

jira:[STUDIO-6435]

Change-Id: I8cafcc0b6caf19492aae6c153fb509f470dc7e83

* FIX: Supports automatic calibration of textured PEI

jira: 6504
Change-Id: I3234fb555b9bf0ea97e73387651874733e761ee7

* ENH:add tooltip for search item

JIRA: STUDIO-6459

Signed-off-by: Kunlong Ma <kunlong.ma@bambulab.com>
Change-Id: I7602a32159d21de8f37ea0208dd6a9f59b90dcce

* ENH: CLI: add version check logic

add option allow_newer_file

Change-Id: I8e8e4a45f77ebdd6dae6189841e4a9952e95ca82

* ci: update build version to 01.09.00.52

Change-Id: Id6e32b5afcf5eaabce9c0c7ab2c422e97b00e632

* NEW: switch to object panel if double click on object

jira: none

switch to object panel if double click on object,
otherwise switch to global panel if double click on background.

Change-Id: I6e54d7957aa19f1ebb1f993bc38125bbee8a1c98
(cherry picked from commit cc2e07bc9489c76a7d767acff0406c83c996504c)

* FIX:fixed loading img resource failure

jira:[for fix img load]

Change-Id: Ifb26b2ca23029abeda000322bf2ef7d2b3cda3b4

* FIX: Project Title can Click

JIRA: none
Change-Id: I614c60e76efe04875e36e3a8ef7a10acd3ef9ecf

* FIX:Prioritize selecting filament with smaller serial numbers in AMS

JIRA: 5909
Change-Id: If3030d4dd8d59af36bc1ae1801be1b89b0027a71

* NEW:material adaptation in select machine dialog

JIRA:xxxx
Change-Id: I625eac75c88cad804dd3741f750c5ea68a975421

* FIX:mac ams setting display

JIRA: STUDIO-6228\6409
Change-Id: I432a3aa96601a8e223b5949bc0ad5234c1374dca

* FIX: Image Scale Mode and Online Display

JIRA: none
Change-Id: I528f16e93b82748d86dc93e2dd3d85f317babaa7

* FIX: sequential_print_clearance_valid not working

not working  correctly with short objects

jira: STUDIO-6489
Change-Id: I33e1a165f448e1c3e272d4045934c63ad345db2f
(cherry picked from commit 9348eaa22a056db5384a38ea966cec9ba4a533a7)

* NEW: add nozzle_height to machine profile and do not detect conflict

Jira: request from 1.9

1. add nozzle_height to machine profile
2. auto arranging and sequential_print_clearance_valid don't consider objects conflicting if they are all shorter than nozzle_height and close.
3. do not detect conflict when all models are short.

Change-Id: I8d1eebb15d5bfa8c40d7491e033149e360531b89
(cherry picked from commit 6b4b52653db5f08d724a556c5c766c0bfa00f34d)

* FIX: sequential_print_clearance_valid not working

not working  correctly with short objects

jira: STUDIO-6489
Change-Id: I33e1a165f448e1c3e272d4045934c63ad345db2f
(cherry picked from commit 9348eaa22a056db5384a38ea966cec9ba4a533a7)

* FIX: [6510] set nozzle temp incorrectly when popup AMS Setting

Change-Id: I898f0b94794a3d67017b1917ce196c4019f5eb4a

* FIX: auto-calculate flushing volumes

JIRA: STUDIO-6547
FIX the first modification of consumable color after synchronizing filaments, without automatically calculating the flushing volumes

Signed-off-by: Kunlong Ma <kunlong.ma@bambulab.com>
Change-Id: I2bc76a29afde5241d100cc42a5161db0f9b901c4

* FIX: custom layer sequence from End to End comboBox display issue

jira: new

Change-Id: I413cd5896d7e921f2c7c03b91b08788fefb9a4f3

* FIX:fix the v tray's filament unload logic

jira:[STUDIO-6627]

Change-Id: I34420bc4d1d27b6b36defb9852bba2eaf77fdcf2

* NEW:reducing purge through retracting filament

1.reducing purge through retracting filament.Currently only
applicable to X&P series

github: PR#3100

Signed-off-by: XunZhangBambu <xun.zhang@bambulab.com>
Change-Id: Ie328039872e50e699dc5e5082fa99f68ac5f5fd1

* FIX: wrong role cache in wipe tower

1. Add wipe tower role cache in GCodeProcessor result
2. Add wiki link for prime tower

jira:NEW

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Ia766c7218df68fb1ffba567af193d6bfecacf588

* Fix plate settng icon

* NEW:revert hms error code

Change-Id: Ib5cc8bb8b8ced0f70d5bbe4751a1f97258218c6f

* FIX: calibration page button broken display issue

jira: STUDIO-3913

Change-Id: I2fd488e829d898b7d81d09db814ed6518f0c54a8

* FIX: do not check spiral vase mode config if an object is loaded

jira: STUDIO-6514

Change-Id: Ib44ec8322ff178b5765f7fe94b588aa38339691d

* FIX: implicitly set spiral vase config for objects just loading

jira: 6514

Change-Id: I04bb2b1abeb62d4dfff4e526b723b1cf1bd5fd7f

* FIX: filling bed fails if the bed is already full

JIRA: STUDIO-6490

Signed-off-by: Kunlong Ma <kunlong.ma@bambulab.com>
Change-Id: I71b5a01a95cdffef7c0750e6347fa8911dcd781d

* ci: update network module based on commit 868f5d7

Change-Id: I5584e4441e1f2ab400addaa87ee8013927fb9e15

* FIX: add query_real_volume_idx_from_other_view api

Jira: STUDIO-6545
Change-Id: Ib8216981c5d2945a0221a5caa1fbc14ed74e930b

* FIX: Can't edit text

github: 3750
Change-Id: I1caecaa968e60cadcdbe9f7aa67cba141bb88230

* FIX: Slicer creates invalid color pattern

github: 3749
Change-Id: I3fd74a9ca59b75873fcbca4437e4858c749ee853

* ENH: hide tuck did

Change-Id: I9021d3f51c9a73bc9208b479f96b1ddbe7a2f8f8
Jira: none

* FIX: PrinterFileSystem: retry connect on user action

Change-Id: I3e8902298385ed2e5906fd15d1817b6e33522a76
Jira: STUDIO-6354

* FIX: Remove user ID and other information

Jira: XXXX

Change-Id: Ia63ec88a335d88fd40a29952abe6d40d8991efee

* ENH: refine retraction before cut

1. Add filament retraction before cut control

jira:NEW

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Ifcb087c9791c0461b793ef811b21ebd4c007d880

* FIX: enable resumed read only Field

Change-Id: Id09e671932458699c020f0a061d8cfc11a6958ab
Jira: STUDIO-6641

* ENH: add precise_z_height

jira: none
Change-Id: Idb9fcf0063e773f1531a49961478460b91ded10f

* ENH: modify the multi-material segmentation and voronoi

This patch is cherry pick from Prusa, thanks to Prusa

Rework multi-material segmentation to work directly on the Voronoi diagram without creating a copy of it.

Previous algorithms assume that they can get an invalid Voronoi diagram. Because of that, during the multi-material segmentation, a copy of the Voronoi diagram was created, and there were several attempts to fix missing vertices and edges. But as it shows, this wasn't a good enough approach and sometimes led to several issues like bleeding layers.

After generalization, our approach for detection and repairs of invalid Voronoi diagrams from Arachne, we could assume that multi-material segmentation gets non-invalid Voronoi diagrams.
With this assumption, we reimplement multi-materials segmentation to work directly on the Voronoi diagram. That should make multi-material segmentation more stable.

So, this should fix several issues like bleeding layers. Also, memory consumption should decrease by a lot. Also, there should be some speedup of multi-materials segmentation.

Jira: none
Change-Id: I72aa6e1f9634d9ee8759aa469a0b39a36ace62f5

* FIX: infill speed not work on region level

Jira: none

Signed-off-by: qing.zhang <qing.zhang@bambulab.com>
Change-Id: Ie3d17c5e3cbf91a8854e3b4cd80babeb2b1bd121

* ENH: support saving PA calibration results for P series

Jira: none

Change-Id: I9402b8bcce7b48a63d0e97e0708080701d065e7a

* ENH: refine long retraction ui

1. associate button display logic
2. Add valid range tip
3. seperate the printer into three types

jira:NEW

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Ie14c8746eb20456dacd5c129a5449c1e7c7db372

* FIX:height range cut = volume_count * 2

Jira: none
Change-Id: I539c2f9cda7985b4b3c318ca8aa1eb7c52fdce82

* FIX: auto arranging gets wrong object height

obj->bounding_box().size() is not the real object size if the object has been rotated.

jira: STUDIO-5999
Change-Id: I6553d4c990696efd674e3e57063802127d5d5282
(cherry picked from commit 479ea9fb02f55d24f27c94633f3d852bd5c62c83)

* ENH: seperate support weight from model

jira:NEW

Signed-off-by: XunZhangBambu <xun.zhang@bambulab.com>
Change-Id: I86bb34941269bf1aa29436a94ebbdff675497e85

* ENH: add support for gcodeviewer statistics

jira: new

Change-Id: Ied6d61e8c48ac82daf16579d9caed9723cf8e29d

* FIX: invalid support weight per extruder

jira:NEW

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: I0e4b857c9c758ab7c54ef13aee1bf596f975640b

* FIX: do not need reset bed_type for pa calibration

jira: none
Change-Id: I411064cf14d94a9bd1f0f6668ee23aa10d372f3d

* FIX: P1P/S can not modify the k value in old version

jira: 6745
Change-Id: I5c9dffe8e998213e6af6e1d01a6b0ae82521e8db

* Add rotation support for 3D Honeycomb
Ported from BS

* ENH: add default params for long retraction

1. Only auto calculate flush when enabled
2. Add default params for long retraction
3. Disable filament override for unsupport machines

jira:NEW

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Ib5d51505b58101839527e944f9a237483951f9fe

* misc fixes

* ENH: remove long retraction warning

jira:NEW

Signed-off-by: tao wang <tao.wang@bambulab.com>
Change-Id: If60236b3282991a2d94df7d125427cff86899536

* avoid zero length path

* FIX: check recommended nozzle temperature

Jira: XXXX

Change-Id: I4dbb274cf27ef9c6d20a8479b29af1069652b2bc

* FIX: fix not popping up a prompt when the temperature is set to 0

Jira: 6497

Change-Id: I6498fc6962e7da376d4c652dab0a99a161932eef
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* ENH: When creating a custom Filament, use the system Filament type.

Jira: 6301

Change-Id: I1bfddcf43d2ebaebca4eb494d1f64165c3d59e9e
Signed-off-by: maosheng.wei <maosheng.wei@bambulab.com>

* FIX: seam and unretarct pos error on smooth vase
casused by invalid path of smooth vase mode

Signed-off-by: qing.zhang <qing.zhang@bambulab.com>
Change-Id: Ib597e8c05760886aae2c42e42e8d46e82b844578

* FIX: unable to map if filament not used in model

1.Fix filament can not map if it's not used in model body

jira:NEW

Signed-off-by: xun.zhang <xun.zhang@bambulab.com>
Change-Id: Ibd2685ffd198b2e17dbf44289d0144b5b7c25788

* NEW:Update data only on device pages

jira:[STUDIO-6776]

Change-Id: I33b0c9f35c1dc6df2db3b6bd4f446f46b31ecf6c

* set(SLIC3R_VERSION "01.09.00.70")

* update BBL machine profile 01.09.00.04

* scarf clip start and end
Ported from BambuStudio

* fix linux build error

---------

Co-authored-by: Arthur <arthur.tang@bambulab.com>
Co-authored-by: zhou.xu <zhou.xu@bambulab.com>
Co-authored-by: wenjie.guo <wenjie.guo@bambulab.com>
Co-authored-by: chunmao.guo <chunmao.guo@bambulab.com>
Co-authored-by: maosheng.wei <maosheng.wei@bambulab.com>
Co-authored-by: hu.wang <hu.wang@bambulab.com>
Co-authored-by: lane.wei <lane.wei@bambulab.com>
Co-authored-by: Kunlong Ma <kunlong.ma@bambulab.com>
Co-authored-by: zhimin.zeng <zhimin.zeng@bambulab.com>
Co-authored-by: zorro.zhang <zorro.zhang@bambulab.com>
Co-authored-by: tao wang <tao.wang@bambulab.com>
Co-authored-by: Stone Li <stone.li@bambulab.com>
Co-authored-by: xun.zhang <xun.zhang@bambulab.com>
Co-authored-by: liz.li <liz.li@bambulab.com>
Co-authored-by: qing.zhang <qing.zhang@bambulab.com>
Co-authored-by: gerrit <gerrit@bambulab.com>
Co-authored-by: Leon Fisher-Skipper <47602359+LeonFisherSkipper@users.noreply.github.com>
Co-authored-by: Lukas Matena <lukasmatena@seznam.cz>
Co-authored-by: jianjia.ma <jianjia.ma@bambulab.com>
2024-04-14 22:07:00 +08:00

4665 lines
194 KiB
C++

#include "ExtrusionEntity.hpp"
#include "PrintConfig.hpp"
#include "libslic3r/libslic3r.h"
#include "libslic3r/Utils.hpp"
#include "libslic3r/Print.hpp"
#include "libslic3r/LocalesUtils.hpp"
#include "libslic3r/format.hpp"
#include "GCodeProcessor.hpp"
#include <boost/log/trivial.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/nowide/fstream.hpp>
#include <boost/nowide/cstdio.hpp>
#include <boost/filesystem/path.hpp>
#include <fast_float/fast_float.h>
#include <float.h>
#include <assert.h>
#include <regex>
#include <charconv>
#include <system_error>
#if __has_include(<charconv>)
#include <charconv>
#include <utility>
#endif
#include <chrono>
static const float DEFAULT_TOOLPATH_WIDTH = 0.4f;
static const float DEFAULT_TOOLPATH_HEIGHT = 0.2f;
static const float INCHES_TO_MM = 25.4f;
static const float MMMIN_TO_MMSEC = 1.0f / 60.0f;
static const float DRAW_ARC_TOLERANCE = 0.0125f; //0.0125mm tolerance for drawing arc
static const float DEFAULT_ACCELERATION = 1500.0f; // Prusa Firmware 1_75mm_MK2
static const float DEFAULT_RETRACT_ACCELERATION = 1500.0f; // Prusa Firmware 1_75mm_MK2
static const float DEFAULT_TRAVEL_ACCELERATION = 1250.0f;
static const size_t MIN_EXTRUDERS_COUNT = 5;
static const float DEFAULT_FILAMENT_DIAMETER = 1.75f;
static const int DEFAULT_FILAMENT_HRC = 0;
static const float DEFAULT_FILAMENT_DENSITY = 1.245f;
static const float DEFAULT_FILAMENT_COST = 29.99f;
static const int DEFAULT_FILAMENT_VITRIFICATION_TEMPERATURE = 0;
static const Slic3r::Vec3f DEFAULT_EXTRUDER_OFFSET = Slic3r::Vec3f::Zero();
namespace Slic3r {
const std::vector<std::string> GCodeProcessor::Reserved_Tags = {
" FEATURE: ",
" WIPE_START",
" WIPE_END",
" LAYER_HEIGHT: ",
" LINE_WIDTH: ",
" CHANGE_LAYER",
" COLOR_CHANGE",
" PAUSE_PRINTING",
" CUSTOM_GCODE",
"_GP_FIRST_LINE_M73_PLACEHOLDER",
"_GP_LAST_LINE_M73_PLACEHOLDER",
"_GP_ESTIMATED_PRINTING_TIME_PLACEHOLDER",
"_GP_TOTAL_LAYER_NUMBER_PLACEHOLDER",
" MANUAL_TOOL_CHANGE ",
"_DURING_PRINT_EXHAUST_FAN",
" WIPE_TOWER_START",
" WIPE_TOWER_END"
};
const std::vector<std::string> GCodeProcessor::Reserved_Tags_compatible = {
"TYPE:",
"WIPE_START",
"WIPE_END",
"HEIGHT:",
"WIDTH:",
"LAYER_CHANGE",
"COLOR_CHANGE",
"PAUSE_PRINT",
"CUSTOM_GCODE",
"_GP_FIRST_LINE_M73_PLACEHOLDER",
"_GP_LAST_LINE_M73_PLACEHOLDER",
"_GP_ESTIMATED_PRINTING_TIME_PLACEHOLDER",
"_GP_TOTAL_LAYER_NUMBER_PLACEHOLDER",
" MANUAL_TOOL_CHANGE ",
"_DURING_PRINT_EXHAUST_FAN",
" WIPE_TOWER_START",
" WIPE_TOWER_END"
};
const std::string GCodeProcessor::Flush_Start_Tag = " FLUSH_START";
const std::string GCodeProcessor::Flush_End_Tag = " FLUSH_END";
const float GCodeProcessor::Wipe_Width = 0.05f;
const float GCodeProcessor::Wipe_Height = 0.05f;
bool GCodeProcessor::s_IsBBLPrinter = true;
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
const std::string GCodeProcessor::Mm3_Per_Mm_Tag = "MM3_PER_MM:";
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
static void set_option_value(ConfigOptionFloats& option, size_t id, float value)
{
if (id < option.values.size())
option.values[id] = static_cast<double>(value);
};
static float get_option_value(const ConfigOptionFloats& option, size_t id)
{
return option.values.empty() ? 0.0f :
((id < option.values.size()) ? static_cast<float>(option.values[id]) : static_cast<float>(option.values.back()));
}
static float estimated_acceleration_distance(float initial_rate, float target_rate, float acceleration)
{
return (acceleration == 0.0f) ? 0.0f : (sqr(target_rate) - sqr(initial_rate)) / (2.0f * acceleration);
}
static float intersection_distance(float initial_rate, float final_rate, float acceleration, float distance)
{
return (acceleration == 0.0f) ? 0.0f : (2.0f * acceleration * distance - sqr(initial_rate) + sqr(final_rate)) / (4.0f * acceleration);
}
static float speed_from_distance(float initial_feedrate, float distance, float acceleration)
{
// to avoid invalid negative numbers due to numerical errors
float value = std::max(0.0f, sqr(initial_feedrate) + 2.0f * acceleration * distance);
return ::sqrt(value);
}
// Calculates the maximum allowable speed at this point when you must be able to reach target_velocity using the
// acceleration within the allotted distance.
static float max_allowable_speed(float acceleration, float target_velocity, float distance)
{
// to avoid invalid negative numbers due to numerical errors
float value = std::max(0.0f, sqr(target_velocity) - 2.0f * acceleration * distance);
return std::sqrt(value);
}
static float acceleration_time_from_distance(float initial_feedrate, float distance, float acceleration)
{
return (acceleration != 0.0f) ? (speed_from_distance(initial_feedrate, distance, acceleration) - initial_feedrate) / acceleration : 0.0f;
}
void GCodeProcessor::CachedPosition::reset()
{
std::fill(position.begin(), position.end(), FLT_MAX);
feedrate = FLT_MAX;
}
void GCodeProcessor::CpColor::reset()
{
counter = 0;
current = 0;
}
float GCodeProcessor::Trapezoid::acceleration_time(float entry_feedrate, float acceleration) const
{
return acceleration_time_from_distance(entry_feedrate, accelerate_until, acceleration);
}
float GCodeProcessor::Trapezoid::cruise_time() const
{
return (cruise_feedrate != 0.0f) ? cruise_distance() / cruise_feedrate : 0.0f;
}
float GCodeProcessor::Trapezoid::deceleration_time(float distance, float acceleration) const
{
return acceleration_time_from_distance(cruise_feedrate, (distance - decelerate_after), -acceleration);
}
float GCodeProcessor::Trapezoid::cruise_distance() const
{
return decelerate_after - accelerate_until;
}
void GCodeProcessor::TimeBlock::calculate_trapezoid()
{
trapezoid.cruise_feedrate = feedrate_profile.cruise;
float accelerate_distance = std::max(0.0f, estimated_acceleration_distance(feedrate_profile.entry, feedrate_profile.cruise, acceleration));
float decelerate_distance = std::max(0.0f, estimated_acceleration_distance(feedrate_profile.cruise, feedrate_profile.exit, -acceleration));
float cruise_distance = distance - accelerate_distance - decelerate_distance;
// Not enough space to reach the nominal feedrate.
// This means no cruising, and we'll have to use intersection_distance() to calculate when to abort acceleration
// and start braking in order to reach the exit_feedrate exactly at the end of this block.
if (cruise_distance < 0.0f) {
accelerate_distance = std::clamp(intersection_distance(feedrate_profile.entry, feedrate_profile.exit, acceleration, distance), 0.0f, distance);
cruise_distance = 0.0f;
trapezoid.cruise_feedrate = speed_from_distance(feedrate_profile.entry, accelerate_distance, acceleration);
}
trapezoid.accelerate_until = accelerate_distance;
trapezoid.decelerate_after = accelerate_distance + cruise_distance;
}
float GCodeProcessor::TimeBlock::time() const
{
return trapezoid.acceleration_time(feedrate_profile.entry, acceleration)
+ trapezoid.cruise_time()
+ trapezoid.deceleration_time(distance, acceleration);
}
void GCodeProcessor::TimeMachine::State::reset()
{
feedrate = 0.0f;
safe_feedrate = 0.0f;
axis_feedrate = { 0.0f, 0.0f, 0.0f, 0.0f };
abs_axis_feedrate = { 0.0f, 0.0f, 0.0f, 0.0f };
//BBS
enter_direction = { 0.0f, 0.0f, 0.0f };
exit_direction = { 0.0f, 0.0f, 0.0f };
}
void GCodeProcessor::TimeMachine::CustomGCodeTime::reset()
{
needed = false;
cache = 0.0f;
times = std::vector<std::pair<CustomGCode::Type, float>>();
}
void GCodeProcessor::TimeMachine::reset()
{
enabled = false;
acceleration = 0.0f;
max_acceleration = 0.0f;
retract_acceleration = 0.0f;
max_retract_acceleration = 0.0f;
travel_acceleration = 0.0f;
max_travel_acceleration = 0.0f;
extrude_factor_override_percentage = 1.0f;
time = 0.0f;
stop_times = std::vector<StopTime>();
curr.reset();
prev.reset();
gcode_time.reset();
blocks = std::vector<TimeBlock>();
g1_times_cache = std::vector<G1LinesCacheItem>();
std::fill(moves_time.begin(), moves_time.end(), 0.0f);
std::fill(roles_time.begin(), roles_time.end(), 0.0f);
layers_time = std::vector<float>();
prepare_time = 0.0f;
}
void GCodeProcessor::TimeMachine::simulate_st_synchronize(float additional_time)
{
if (!enabled)
return;
calculate_time(0, additional_time);
}
static void planner_forward_pass_kernel(GCodeProcessor::TimeBlock& prev, GCodeProcessor::TimeBlock& curr)
{
// If the previous block is an acceleration block, but it is not long enough to complete the
// full speed change within the block, we need to adjust the entry speed accordingly. Entry
// speeds have already been reset, maximized, and reverse planned by reverse planner.
// If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
if (!prev.flags.nominal_length) {
if (prev.feedrate_profile.entry < curr.feedrate_profile.entry) {
float entry_speed = std::min(curr.feedrate_profile.entry, max_allowable_speed(-prev.acceleration, prev.feedrate_profile.entry, prev.distance));
// Check for junction speed change
if (curr.feedrate_profile.entry != entry_speed) {
curr.feedrate_profile.entry = entry_speed;
curr.flags.recalculate = true;
}
}
}
}
void planner_reverse_pass_kernel(GCodeProcessor::TimeBlock& curr, GCodeProcessor::TimeBlock& next)
{
// If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
// If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
// check for maximum allowable speed reductions to ensure maximum possible planned speed.
if (curr.feedrate_profile.entry != curr.max_entry_speed) {
// If nominal length true, max junction speed is guaranteed to be reached. Only compute
// for max allowable speed if block is decelerating and nominal length is false.
if (!curr.flags.nominal_length && curr.max_entry_speed > next.feedrate_profile.entry)
curr.feedrate_profile.entry = std::min(curr.max_entry_speed, max_allowable_speed(-curr.acceleration, next.feedrate_profile.entry, curr.distance));
else
curr.feedrate_profile.entry = curr.max_entry_speed;
curr.flags.recalculate = true;
}
}
static void recalculate_trapezoids(std::vector<GCodeProcessor::TimeBlock>& blocks)
{
GCodeProcessor::TimeBlock* curr = nullptr;
GCodeProcessor::TimeBlock* next = nullptr;
for (size_t i = 0; i < blocks.size(); ++i) {
GCodeProcessor::TimeBlock& b = blocks[i];
curr = next;
next = &b;
if (curr != nullptr) {
// Recalculate if current block entry or exit junction speed has changed.
if (curr->flags.recalculate || next->flags.recalculate) {
// NOTE: Entry and exit factors always > 0 by all previous logic operations.
GCodeProcessor::TimeBlock block = *curr;
block.feedrate_profile.exit = next->feedrate_profile.entry;
block.calculate_trapezoid();
curr->trapezoid = block.trapezoid;
curr->flags.recalculate = false; // Reset current only to ensure next trapezoid is computed
}
}
}
// Last/newest block in buffer. Always recalculated.
if (next != nullptr) {
GCodeProcessor::TimeBlock block = *next;
block.feedrate_profile.exit = next->safe_feedrate;
block.calculate_trapezoid();
next->trapezoid = block.trapezoid;
next->flags.recalculate = false;
}
}
void GCodeProcessor::TimeMachine::calculate_time(size_t keep_last_n_blocks, float additional_time)
{
if (!enabled || blocks.size() < 2)
return;
assert(keep_last_n_blocks <= blocks.size());
// forward_pass
for (size_t i = 0; i + 1 < blocks.size(); ++i) {
planner_forward_pass_kernel(blocks[i], blocks[i + 1]);
}
// reverse_pass
for (int i = static_cast<int>(blocks.size()) - 1; i > 0; --i)
planner_reverse_pass_kernel(blocks[i - 1], blocks[i]);
recalculate_trapezoids(blocks);
size_t n_blocks_process = blocks.size() - keep_last_n_blocks;
for (size_t i = 0; i < n_blocks_process; ++i) {
const TimeBlock& block = blocks[i];
float block_time = block.time();
if (i == 0)
block_time += additional_time;
time += block_time;
gcode_time.cache += block_time;
//BBS: don't calculate travel of start gcode into travel time
if (!block.flags.prepare_stage || block.move_type != EMoveType::Travel)
moves_time[static_cast<size_t>(block.move_type)] += block_time;
roles_time[static_cast<size_t>(block.role)] += block_time;
if (block.layer_id >= layers_time.size()) {
const size_t curr_size = layers_time.size();
layers_time.resize(block.layer_id);
for (size_t i = curr_size; i < layers_time.size(); ++i) {
layers_time[i] = 0.0f;
}
}
layers_time[block.layer_id - 1] += block_time;
//BBS
if (block.flags.prepare_stage)
prepare_time += block_time;
g1_times_cache.push_back({ block.g1_line_id, time });
// update times for remaining time to printer stop placeholders
auto it_stop_time = std::lower_bound(stop_times.begin(), stop_times.end(), block.g1_line_id,
[](const StopTime& t, unsigned int value) { return t.g1_line_id < value; });
if (it_stop_time != stop_times.end() && it_stop_time->g1_line_id == block.g1_line_id)
it_stop_time->elapsed_time = time;
}
if (keep_last_n_blocks)
blocks.erase(blocks.begin(), blocks.begin() + n_blocks_process);
else
blocks.clear();
}
void GCodeProcessor::TimeProcessor::reset()
{
extruder_unloaded = true;
machine_envelope_processing_enabled = false;
machine_limits = MachineEnvelopeConfig();
filament_load_times = std::vector<float>();
filament_unload_times = std::vector<float>();
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
machines[i].reset();
}
machines[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Normal)].enabled = true;
}
void GCodeProcessor::TimeProcessor::post_process(const std::string& filename, std::vector<GCodeProcessorResult::MoveVertex>& moves, std::vector<size_t>& lines_ends, size_t total_layer_num)
{
FilePtr in{ boost::nowide::fopen(filename.c_str(), "rb") };
if (in.f == nullptr)
throw Slic3r::RuntimeError(std::string("Time estimator post process export failed.\nCannot open file for reading.\n"));
const bool disable_m73 = this->disable_m73;
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": before process %1%")%filename.c_str();
// temporary file to contain modified gcode
std::string out_path = filename + ".postprocess";
FilePtr out{ boost::nowide::fopen(out_path.c_str(), "wb") };
if (out.f == nullptr) {
throw Slic3r::RuntimeError(std::string("Time estimator post process export failed.\nCannot open file for writing.\n"));
}
auto time_in_minutes = [](float time_in_seconds) {
assert(time_in_seconds >= 0.f);
return int((time_in_seconds + 0.5f) / 60.0f);
};
auto time_in_last_minute = [](float time_in_seconds) {
assert(time_in_seconds <= 60.0f);
return time_in_seconds / 60.0f;
};
auto format_line_M73_main = [](const std::string& mask, int percent, int time) {
char line_M73[64];
sprintf(line_M73, mask.c_str(),
std::to_string(percent).c_str(),
std::to_string(time).c_str());
return std::string(line_M73);
};
auto format_line_M73_stop_int = [](const std::string& mask, int time) {
char line_M73[64];
sprintf(line_M73, mask.c_str(), std::to_string(time).c_str());
return std::string(line_M73);
};
auto format_line_exhaust_fan_control = [](const std::string& mask,int fan_index,int percent) {
char line_fan[64] = { 0 };
sprintf(line_fan,mask.c_str(),
std::to_string(fan_index).c_str(),
std::to_string(int((percent/100.0)*255)).c_str());
return std::string(line_fan);
};
auto format_time_float = [](float time) {
return Slic3r::float_to_string_decimal_point(time, 2);
};
auto format_line_M73_stop_float = [format_time_float](const std::string& mask, float time) {
char line_M73[64];
sprintf(line_M73, mask.c_str(), format_time_float(time).c_str());
return std::string(line_M73);
};
std::string gcode_line;
size_t g1_lines_counter = 0;
// keeps track of last exported pair <percent, remaining time>
std::array<std::pair<int, int>, static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count)> last_exported_main;
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
last_exported_main[i] = { 0, time_in_minutes(machines[i].time) };
}
// keeps track of last exported remaining time to next printer stop
std::array<int, static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count)> last_exported_stop;
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
last_exported_stop[i] = time_in_minutes(machines[i].time);
}
// buffer line to export only when greater than 64K to reduce writing calls
std::string export_line;
// replace placeholder lines with the proper final value
// gcode_line is in/out parameter, to reduce expensive memory allocation
auto process_placeholders = [&](std::string& gcode_line) {
int extra_lines_count = 0;
// remove trailing '\n'
auto line = std::string_view(gcode_line).substr(0, gcode_line.length() - 1);
std::string ret;
if (line.length() > 1) {
line = line.substr(1);
if (line == reserved_tag(ETags::First_Line_M73_Placeholder) || line == reserved_tag(ETags::Last_Line_M73_Placeholder)) {
if (disable_m73) {
// Remove current line
gcode_line = "";
return std::tuple(true, -1);
}
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
const TimeMachine& machine = machines[i];
if (machine.enabled) {
// export pair <percent, remaining time>
ret += format_line_M73_main(machine.line_m73_main_mask.c_str(),
(line == reserved_tag(ETags::First_Line_M73_Placeholder)) ? 0 : 100,
(line == reserved_tag(ETags::First_Line_M73_Placeholder)) ? time_in_minutes(machine.time) : 0);
++extra_lines_count;
// export remaining time to next printer stop
if (line == reserved_tag(ETags::First_Line_M73_Placeholder) && !machine.stop_times.empty()) {
int to_export_stop = time_in_minutes(machine.stop_times.front().elapsed_time);
ret += format_line_M73_stop_int(machine.line_m73_stop_mask.c_str(), to_export_stop);
last_exported_stop[i] = to_export_stop;
++extra_lines_count;
}
}
}
}
else if (line == reserved_tag(ETags::Estimated_Printing_Time_Placeholder)) {
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
const TimeMachine& machine = machines[i];
PrintEstimatedStatistics::ETimeMode mode = static_cast<PrintEstimatedStatistics::ETimeMode>(i);
if (mode == PrintEstimatedStatistics::ETimeMode::Normal || machine.enabled) {
char buf[128];
if(!s_IsBBLPrinter)
// SoftFever: compatibility with klipper_estimator
sprintf(buf, "; estimated printing time (normal mode) = %s\n", get_time_dhms(machine.time).c_str());
else {
//sprintf(buf, "; estimated printing time (%s mode) = %s\n",
// (mode == PrintEstimatedStatistics::ETimeMode::Normal) ? "normal" : "silent",
// get_time_dhms(machine.time).c_str());
sprintf(buf, "; model printing time: %s; total estimated time: %s\n",
get_time_dhms(machine.time - machine.prepare_time).c_str(),
get_time_dhms(machine.time).c_str());
}
ret += buf;
}
}
}
//BBS: write total layer number
else if (line == reserved_tag(ETags::Total_Layer_Number_Placeholder)) {
char buf[128];
sprintf(buf, "; total layer number: %zd\n", total_layer_num);
ret += buf;
}
}
if (! ret.empty())
// Not moving the move operator on purpose, so that the gcode_line allocation will grow and it will not be reallocated after handful of lines are processed.
gcode_line = ret;
return std::tuple(!ret.empty(), (extra_lines_count == 0) ? extra_lines_count : extra_lines_count - 1);
};
// check for temporary lines
auto is_temporary_decoration = [](const std::string_view gcode_line) {
// remove trailing '\n'
assert(! gcode_line.empty());
assert(gcode_line.back() == '\n');
// return true for decorations which are used in processing the gcode but that should not be exported into the final gcode
// i.e.:
// bool ret = gcode_line.substr(0, gcode_line.length() - 1) == ";" + Layer_Change_Tag;
// ...
// return ret;
return false;
};
// Iterators for the normal and silent cached time estimate entry recently processed, used by process_line_G1.
auto g1_times_cache_it = Slic3r::reserve_vector<std::vector<TimeMachine::G1LinesCacheItem>::const_iterator>(machines.size());
for (const auto& machine : machines)
g1_times_cache_it.emplace_back(machine.g1_times_cache.begin());
// add lines M73 to exported gcode
auto process_line_move = [
// Lambdas, mostly for string formatting, all with an empty capture block.
time_in_minutes, format_time_float, format_line_M73_main, format_line_M73_stop_int, format_line_M73_stop_float, time_in_last_minute,format_line_exhaust_fan_control,
&self = std::as_const(*this),
// Caches, to be modified
&g1_times_cache_it, &last_exported_main, &last_exported_stop,
// String output
&export_line]
(const size_t g1_lines_counter) {
unsigned int exported_lines_count = 0;
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
const TimeMachine& machine = self.machines[i];
if (machine.enabled) {
// export pair <percent, remaining time>
// Skip all machine.g1_times_cache below g1_lines_counter.
auto& it = g1_times_cache_it[i];
while (it != machine.g1_times_cache.end() && it->id < g1_lines_counter)
++it;
if (it != machine.g1_times_cache.end() && it->id == g1_lines_counter) {
std::pair<int, int> to_export_main = { int(100.0f * it->elapsed_time / machine.time),
time_in_minutes(machine.time - it->elapsed_time) };
if (last_exported_main[i] != to_export_main) {
export_line += format_line_M73_main(machine.line_m73_main_mask.c_str(),
to_export_main.first, to_export_main.second);
last_exported_main[i] = to_export_main;
++exported_lines_count;
}
// export remaining time to next printer stop
auto it_stop = std::upper_bound(machine.stop_times.begin(), machine.stop_times.end(), it->elapsed_time,
[](float value, const TimeMachine::StopTime& t) { return value < t.elapsed_time; });
if (it_stop != machine.stop_times.end()) {
int to_export_stop = time_in_minutes(it_stop->elapsed_time - it->elapsed_time);
if (last_exported_stop[i] != to_export_stop) {
if (to_export_stop > 0) {
if (last_exported_stop[i] != to_export_stop) {
export_line += format_line_M73_stop_int(machine.line_m73_stop_mask.c_str(), to_export_stop);
last_exported_stop[i] = to_export_stop;
++exported_lines_count;
}
}
else {
bool is_last = false;
auto next_it = it + 1;
is_last |= (next_it == machine.g1_times_cache.end());
if (next_it != machine.g1_times_cache.end()) {
auto next_it_stop = std::upper_bound(machine.stop_times.begin(), machine.stop_times.end(), next_it->elapsed_time,
[](float value, const TimeMachine::StopTime& t) { return value < t.elapsed_time; });
is_last |= (next_it_stop != it_stop);
std::string time_float_str = format_time_float(time_in_last_minute(it_stop->elapsed_time - it->elapsed_time));
std::string next_time_float_str = format_time_float(time_in_last_minute(it_stop->elapsed_time - next_it->elapsed_time));
is_last |= (string_to_double_decimal_point(time_float_str) > 0. && string_to_double_decimal_point(next_time_float_str) == 0.);
}
if (is_last) {
if (std::distance(machine.stop_times.begin(), it_stop) == static_cast<ptrdiff_t>(machine.stop_times.size() - 1))
export_line += format_line_M73_stop_int(machine.line_m73_stop_mask.c_str(), to_export_stop);
else
export_line += format_line_M73_stop_float(machine.line_m73_stop_mask.c_str(), time_in_last_minute(it_stop->elapsed_time - it->elapsed_time));
last_exported_stop[i] = to_export_stop;
++exported_lines_count;
}
}
}
}
}
}
}
return exported_lines_count;
};
// helper function to write to disk
size_t out_file_pos = 0;
lines_ends.clear();
auto write_string = [&export_line, &out, &out_path, &out_file_pos, &lines_ends](const std::string& str) {
fwrite((const void*)export_line.c_str(), 1, export_line.length(), out.f);
if (ferror(out.f)) {
out.close();
boost::nowide::remove(out_path.c_str());
throw Slic3r::RuntimeError(std::string("Time estimator post process export failed.\nIs the disk full?\n"));
}
for (size_t i = 0; i < export_line.size(); ++ i)
if (export_line[i] == '\n')
lines_ends.emplace_back(out_file_pos + i + 1);
out_file_pos += export_line.size();
export_line.clear();
};
unsigned int line_id = 0;
std::vector<std::pair<unsigned int, unsigned int>> offsets;
{
// Read the input stream 64kB at a time, extract lines and process them.
std::vector<char> buffer(65536 * 10, 0);
// Line buffer.
assert(gcode_line.empty());
for (;;) {
size_t cnt_read = ::fread(buffer.data(), 1, buffer.size(), in.f);
if (::ferror(in.f))
throw Slic3r::RuntimeError(std::string("Time estimator post process export failed.\nError while reading from file.\n"));
bool eof = cnt_read == 0;
auto it = buffer.begin();
auto it_bufend = buffer.begin() + cnt_read;
while (it != it_bufend || (eof && ! gcode_line.empty())) {
// Find end of line.
bool eol = false;
auto it_end = it;
for (; it_end != it_bufend && ! (eol = *it_end == '\r' || *it_end == '\n'); ++ it_end) ;
// End of line is indicated also if end of file was reached.
eol |= eof && it_end == it_bufend;
gcode_line.insert(gcode_line.end(), it, it_end);
if (eol) {
++line_id;
// determine the end of line character and pass to output
gcode_line += *it_end;
if(*it_end == '\r' && *(++ it_end) == '\n')
gcode_line += '\n';
// replace placeholder lines
auto [processed, lines_added_count] = process_placeholders(gcode_line);
if (processed && lines_added_count != 0)
offsets.push_back({ line_id, lines_added_count });
if (!disable_m73 && !processed &&!is_temporary_decoration(gcode_line) &&
(GCodeReader::GCodeLine::cmd_is(gcode_line, "G1") ||
GCodeReader::GCodeLine::cmd_is(gcode_line, "G2") ||
GCodeReader::GCodeLine::cmd_is(gcode_line, "G3"))) {
// remove temporary lines, add lines M73 where needed
unsigned int extra_lines_count = process_line_move(g1_lines_counter ++);
if (extra_lines_count > 0)
offsets.push_back({ line_id, extra_lines_count });
}
if (disable_m73 && !processed && GCodeReader::GCodeLine::cmd_is(gcode_line, "M73")) {
// Remove any existing M73 command
gcode_line = "";
offsets.push_back({line_id, -1});
}
export_line += gcode_line;
if (export_line.length() > 65535)
write_string(export_line);
gcode_line.clear();
}
// Skip EOL.
it = it_end;
if (it != it_bufend && *it == '\r')
++ it;
if (it != it_bufend && *it == '\n')
++ it;
}
if (eof)
break;
}
}
if (!export_line.empty())
write_string(export_line);
out.close();
in.close();
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": after process %1%")%filename.c_str();
// updates moves' gcode ids which have been modified by the insertion of the M73 lines
unsigned int curr_offset_id = 0;
unsigned int total_offset = 0;
for (GCodeProcessorResult::MoveVertex& move : moves) {
while (curr_offset_id < static_cast<unsigned int>(offsets.size()) && offsets[curr_offset_id].first <= move.gcode_id) {
total_offset += offsets[curr_offset_id].second;
++curr_offset_id;
}
move.gcode_id += total_offset;
}
if (rename_file(out_path, filename)) {
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": Failed to rename the output G-code file from %1% to %2%")%out_path.c_str() % filename.c_str();
throw Slic3r::RuntimeError(std::string("Failed to rename the output G-code file from ") + out_path + " to " + filename + '\n' +
"Is " + out_path + " locked?" + '\n');
}
}
void GCodeProcessor::UsedFilaments::reset()
{
color_change_cache = 0.0f;
volumes_per_color_change = std::vector<double>();
model_extrude_cache = 0.0f;
volumes_per_extruder.clear();
flush_per_filament.clear();
role_cache = 0.0f;
filaments_per_role.clear();
wipe_tower_cache = 0.0f;
wipe_tower_volume_per_extruder.clear();
support_volume_cache = 0.0f;
support_volume_per_extruder.clear();
}
void GCodeProcessor::UsedFilaments::increase_support_caches(double extruded_volume)
{
support_volume_cache += extruded_volume;
role_cache += extruded_volume;
}
void GCodeProcessor::UsedFilaments::increase_model_caches(double extruded_volume)
{
color_change_cache += extruded_volume;
model_extrude_cache += extruded_volume;
role_cache += extruded_volume;
}
void GCodeProcessor::UsedFilaments::increase_wipe_tower_caches(double extruded_volume)
{
wipe_tower_cache += extruded_volume;
role_cache += extruded_volume;
}
void GCodeProcessor::UsedFilaments::process_color_change_cache()
{
if (color_change_cache != 0.0f) {
volumes_per_color_change.push_back(color_change_cache);
color_change_cache = 0.0f;
}
}
void GCodeProcessor::UsedFilaments::process_model_cache(GCodeProcessor* processor)
{
size_t active_extruder_id = processor->m_extruder_id;
if (model_extrude_cache != 0.0f) {
if (volumes_per_extruder.find(active_extruder_id) != volumes_per_extruder.end())
volumes_per_extruder[active_extruder_id] += model_extrude_cache;
else
volumes_per_extruder[active_extruder_id] = model_extrude_cache;
model_extrude_cache = 0.0f;
}
}
void GCodeProcessor::UsedFilaments::process_wipe_tower_cache(GCodeProcessor* processor)
{
size_t active_extruder_id = processor->m_extruder_id;
if (wipe_tower_cache != 0.0f) {
if (wipe_tower_volume_per_extruder.find(active_extruder_id) != wipe_tower_volume_per_extruder.end())
wipe_tower_volume_per_extruder[active_extruder_id] += wipe_tower_cache;
else
wipe_tower_volume_per_extruder[active_extruder_id] = wipe_tower_cache;
wipe_tower_cache = 0.0f;
}
}
void GCodeProcessor::UsedFilaments::process_support_cache(GCodeProcessor* processor)
{
size_t active_extruder_id = processor->m_extruder_id;
if (support_volume_cache != 0.0f){
if (support_volume_per_extruder.find(active_extruder_id) != support_volume_per_extruder.end())
support_volume_per_extruder[active_extruder_id] += support_volume_cache;
else
support_volume_per_extruder[active_extruder_id] = support_volume_cache;
support_volume_cache = 0.0f;
}
}
void GCodeProcessor::UsedFilaments::update_flush_per_filament(size_t extrude_id, float flush_volume)
{
if (flush_per_filament.find(extrude_id) != flush_per_filament.end())
flush_per_filament[extrude_id] += flush_volume;
else
flush_per_filament[extrude_id] = flush_volume;
}
void GCodeProcessor::UsedFilaments::process_role_cache(GCodeProcessor* processor)
{
if (role_cache != 0.0f) {
std::pair<double, double> filament = { 0.0f, 0.0f };
double s = PI * sqr(0.5 * processor->m_result.filament_diameters[processor->m_extruder_id]);
filament.first = role_cache / s * 0.001;
filament.second = role_cache * processor->m_result.filament_densities[processor->m_extruder_id] * 0.001;
ExtrusionRole active_role = processor->m_extrusion_role;
if (filaments_per_role.find(active_role) != filaments_per_role.end()) {
filaments_per_role[active_role].first += filament.first;
filaments_per_role[active_role].second += filament.second;
}
else
filaments_per_role[active_role] = filament;
role_cache = 0.0f;
}
}
void GCodeProcessor::UsedFilaments::process_caches(GCodeProcessor* processor)
{
process_color_change_cache();
process_model_cache(processor);
process_role_cache(processor);
process_wipe_tower_cache(processor);
process_support_cache(processor);
}
#if ENABLE_GCODE_VIEWER_STATISTICS
void GCodeProcessorResult::reset() {
//BBS: add mutex for protection of gcode result
lock();
moves = std::vector<GCodeProcessorResult::MoveVertex>();
printable_area = Pointfs();
//BBS: add bed exclude area
bed_exclude_area = Pointfs();
//BBS: add toolpath_outside
toolpath_outside = false;
//BBS: add label_object_enabled
label_object_enabled = false;
timelapse_warning_code = 0;
printable_height = 0.0f;
settings_ids.reset();
extruders_count = 0;
extruder_colors = std::vector<std::string>();
filament_diameters = std::vector<float>(MIN_EXTRUDERS_COUNT, DEFAULT_FILAMENT_DIAMETER);
filament_densities = std::vector<float>(MIN_EXTRUDERS_COUNT, DEFAULT_FILAMENT_DENSITY);
custom_gcode_per_print_z = std::vector<CustomGCode::Item>();
spiral_vase_layers = std::vector<std::pair<float, std::pair<size_t, size_t>>>();
time = 0;
//BBS: add mutex for protection of gcode result
unlock();
}
#else
void GCodeProcessorResult::reset() {
//BBS: add mutex for protection of gcode result
lock();
moves.clear();
lines_ends.clear();
printable_area = Pointfs();
//BBS: add bed exclude area
bed_exclude_area = Pointfs();
//BBS: add toolpath_outside
toolpath_outside = false;
//BBS: add label_object_enabled
label_object_enabled = false;
long_retraction_when_cut = false;
timelapse_warning_code = 0;
printable_height = 0.0f;
settings_ids.reset();
extruders_count = 0;
extruder_colors = std::vector<std::string>();
filament_diameters = std::vector<float>(MIN_EXTRUDERS_COUNT, DEFAULT_FILAMENT_DIAMETER);
required_nozzle_HRC = std::vector<int>(MIN_EXTRUDERS_COUNT, DEFAULT_FILAMENT_HRC);
filament_densities = std::vector<float>(MIN_EXTRUDERS_COUNT, DEFAULT_FILAMENT_DENSITY);
filament_costs = std::vector<float>(MIN_EXTRUDERS_COUNT, DEFAULT_FILAMENT_COST);
custom_gcode_per_print_z = std::vector<CustomGCode::Item>();
spiral_vase_layers = std::vector<std::pair<float, std::pair<size_t, size_t>>>();
bed_match_result = BedMatchResult(true);
warnings.clear();
//BBS: add mutex for protection of gcode result
unlock();
//BBS: add logs
BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(" %1%: this=%2% reset finished")%__LINE__%this;
}
#endif // ENABLE_GCODE_VIEWER_STATISTICS
const std::vector<std::pair<GCodeProcessor::EProducer, std::string>> GCodeProcessor::Producers = {
//BBS: OrcaSlicer is also "bambu". Otherwise the time estimation didn't work.
//FIXME: Workaround and should be handled when do removing-bambu
{ EProducer::OrcaSlicer, SLIC3R_APP_NAME },
{ EProducer::OrcaSlicer, "generated by OrcaSlicer" },
{ EProducer::OrcaSlicer, "generated by BambuStudio" },
{ EProducer::OrcaSlicer, "BambuStudio" }
//{ EProducer::Slic3rPE, "generated by Slic3r Bambu Edition" },
//{ EProducer::Slic3r, "generated by Slic3r" },
//{ EProducer::SuperSlicer, "generated by SuperSlicer" },
//{ EProducer::Cura, "Cura_SteamEngine" },
//{ EProducer::Simplify3D, "G-Code generated by Simplify3D(R)" },
//{ EProducer::CraftWare, "CraftWare" },
//{ EProducer::ideaMaker, "ideaMaker" },
//{ EProducer::KissSlicer, "KISSlicer" }
};
unsigned int GCodeProcessor::s_result_id = 0;
bool GCodeProcessor::contains_reserved_tag(const std::string& gcode, std::string& found_tag)
{
bool ret = false;
GCodeReader parser;
auto& _tags = s_IsBBLPrinter ? Reserved_Tags : Reserved_Tags_compatible;
parser.parse_buffer(gcode, [&ret, &found_tag, _tags](GCodeReader& parser, const GCodeReader::GCodeLine& line) {
std::string comment = line.raw();
if (comment.length() > 2 && comment.front() == ';') {
comment = comment.substr(1);
for (const std::string& s : _tags) {
if (boost::starts_with(comment, s)) {
ret = true;
found_tag = comment;
parser.quit_parsing();
return;
}
}
}
});
return ret;
}
bool GCodeProcessor::contains_reserved_tags(const std::string& gcode, unsigned int max_count, std::vector<std::string>& found_tag)
{
max_count = std::max(max_count, 1U);
bool ret = false;
CNumericLocalesSetter locales_setter;
GCodeReader parser;
auto& _tags = s_IsBBLPrinter ? Reserved_Tags : Reserved_Tags_compatible;
parser.parse_buffer(gcode, [&ret, &found_tag, max_count, _tags](GCodeReader& parser, const GCodeReader::GCodeLine& line) {
std::string comment = line.raw();
if (comment.length() > 2 && comment.front() == ';') {
comment = comment.substr(1);
for (const std::string& s : _tags) {
if (boost::starts_with(comment, s)) {
ret = true;
found_tag.push_back(comment);
if (found_tag.size() == max_count) {
parser.quit_parsing();
return;
}
}
}
}
});
return ret;
}
GCodeProcessor::GCodeProcessor()
: m_options_z_corrector(m_result)
{
reset();
m_time_processor.machines[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Normal)].line_m73_main_mask = "M73 P%s R%s\n";
m_time_processor.machines[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Normal)].line_m73_stop_mask = "M73 C%s\n";
m_time_processor.machines[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Stealth)].line_m73_main_mask = "M73 Q%s S%s\n";
m_time_processor.machines[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Stealth)].line_m73_stop_mask = "M73 D%s\n";
}
void GCodeProcessor::apply_config(const PrintConfig& config)
{
m_parser.apply_config(config);
m_flavor = config.gcode_flavor;
// BBS
size_t extruders_count = config.filament_diameter.values.size();
m_result.extruders_count = extruders_count;
m_extruder_offsets.resize(extruders_count);
m_extruder_colors.resize(extruders_count);
m_result.filament_diameters.resize(extruders_count);
m_result.required_nozzle_HRC.resize(extruders_count);
m_result.filament_densities.resize(extruders_count);
m_result.filament_vitrification_temperature.resize(extruders_count);
m_result.filament_costs.resize(extruders_count);
m_extruder_temps.resize(extruders_count);
m_result.nozzle_hrc = static_cast<int>(config.nozzle_hrc.getInt());
m_result.nozzle_type = config.nozzle_type;
for (size_t i = 0; i < extruders_count; ++ i) {
m_extruder_offsets[i] = to_3d(config.extruder_offset.get_at(i).cast<float>().eval(), 0.f);
m_extruder_colors[i] = static_cast<unsigned char>(i);
m_result.filament_diameters[i] = static_cast<float>(config.filament_diameter.get_at(i));
m_result.required_nozzle_HRC[i] = static_cast<int>(config.required_nozzle_HRC.get_at(i));
m_result.filament_densities[i] = static_cast<float>(config.filament_density.get_at(i));
m_result.filament_vitrification_temperature[i] = static_cast<float>(config.temperature_vitrification.get_at(i));
m_result.filament_costs[i] = static_cast<float>(config.filament_cost.get_at(i));
}
if (m_flavor == gcfMarlinLegacy || m_flavor == gcfMarlinFirmware || m_flavor == gcfKlipper || m_flavor == gcfRepRapFirmware) {
m_time_processor.machine_limits = reinterpret_cast<const MachineEnvelopeConfig&>(config);
if (m_flavor == gcfMarlinLegacy || m_flavor == gcfKlipper) {
// Legacy Marlin does not have separate travel acceleration, it uses the 'extruding' value instead.
m_time_processor.machine_limits.machine_max_acceleration_travel = m_time_processor.machine_limits.machine_max_acceleration_extruding;
}
if (m_flavor == gcfRepRapFirmware) {
// RRF does not support setting min feedrates. Set them to zero.
m_time_processor.machine_limits.machine_min_travel_rate.values.assign(m_time_processor.machine_limits.machine_min_travel_rate.size(), 0.);
m_time_processor.machine_limits.machine_min_extruding_rate.values.assign(m_time_processor.machine_limits.machine_min_extruding_rate.size(), 0.);
}
}
// Filament load / unload times are not specific to a firmware flavor. Let anybody use it if they find it useful.
// As of now the fields are shown at the UI dialog in the same combo box as the ramming values, so they
// are considered to be active for the single extruder multi-material printers only.
if(s_IsBBLPrinter){
// BBL printers use machine_load_filament_time and machine_unload_filament_time
m_time_processor.filament_load_times.resize(1);
m_time_processor.filament_load_times[0] = static_cast<float>(config.machine_load_filament_time.value);
m_time_processor.filament_unload_times.resize(1);
m_time_processor.filament_unload_times[0] = static_cast<float>(config.machine_unload_filament_time.value);
} else {
// for non-BBL printers use the filament_load_time and filament_unload_time
m_time_processor.filament_load_times.resize(config.filament_load_time.values.size());
for (size_t i = 0; i < config.filament_load_time.values.size(); ++i) {
m_time_processor.filament_load_times[i] = static_cast<float>(config.filament_load_time.values[i]);
}
m_time_processor.filament_unload_times.resize(config.filament_unload_time.values.size());
for (size_t i = 0; i < config.filament_unload_time.values.size(); ++i) {
m_time_processor.filament_unload_times[i] = static_cast<float>(config.filament_unload_time.values[i]);
}
}
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
float max_acceleration = get_option_value(m_time_processor.machine_limits.machine_max_acceleration_extruding, i);
m_time_processor.machines[i].max_acceleration = max_acceleration;
m_time_processor.machines[i].acceleration = (max_acceleration > 0.0f) ? max_acceleration : DEFAULT_ACCELERATION;
float max_retract_acceleration = get_option_value(m_time_processor.machine_limits.machine_max_acceleration_retracting, i);
m_time_processor.machines[i].max_retract_acceleration = max_retract_acceleration;
m_time_processor.machines[i].retract_acceleration = (max_retract_acceleration > 0.0f) ? max_retract_acceleration :
DEFAULT_RETRACT_ACCELERATION;
float max_travel_acceleration = get_option_value(m_time_processor.machine_limits.machine_max_acceleration_travel, i);
if (!GCodeWriter::supports_separate_travel_acceleration(config.gcode_flavor.value)){
max_travel_acceleration = 0;
}
m_time_processor.machines[i].max_travel_acceleration = max_travel_acceleration;
m_time_processor.machines[i].travel_acceleration = (max_travel_acceleration > 0.0f) ? max_travel_acceleration :
DEFAULT_TRAVEL_ACCELERATION;
}
m_time_processor.disable_m73 = config.disable_m73;
const ConfigOptionFloat* initial_layer_print_height = config.option<ConfigOptionFloat>("initial_layer_print_height");
if (initial_layer_print_height != nullptr)
m_first_layer_height = std::abs(initial_layer_print_height->value);
m_result.printable_height = config.printable_height;
const ConfigOptionBool* spiral_vase = config.option<ConfigOptionBool>("spiral_mode");
if (spiral_vase != nullptr)
m_detect_layer_based_on_tag = spiral_vase->value;
const ConfigOptionBool* has_scarf_joint_seam = config.option<ConfigOptionBool>("has_scarf_joint_seam");
if (has_scarf_joint_seam != nullptr)
m_detect_layer_based_on_tag = m_detect_layer_based_on_tag || has_scarf_joint_seam->value;
const ConfigOptionBool* manual_filament_change = config.option<ConfigOptionBool>("manual_filament_change");
if (manual_filament_change != nullptr)
m_manual_filament_change = manual_filament_change->value;
const ConfigOptionFloat* z_offset = config.option<ConfigOptionFloat>("z_offset");
if (z_offset != nullptr)
m_z_offset = z_offset->value;
}
void GCodeProcessor::apply_config(const DynamicPrintConfig& config)
{
m_parser.apply_config(config);
//BBS
const ConfigOptionFloat* nozzle_volume = config.option<ConfigOptionFloat>("nozzle_volume");
if (nozzle_volume != nullptr)
m_nozzle_volume = nozzle_volume->value;
const ConfigOptionInt *nozzle_HRC = config.option<ConfigOptionInt>("nozzle_hrc");
if (nozzle_HRC != nullptr) m_result.nozzle_hrc = nozzle_HRC->value;
const ConfigOptionEnum<NozzleType>* nozzle_type = config.option<ConfigOptionEnum<NozzleType>>("nozzle_type");
if (nozzle_type != nullptr)
m_result.nozzle_type=nozzle_type->value;
const ConfigOptionEnum<GCodeFlavor>* gcode_flavor = config.option<ConfigOptionEnum<GCodeFlavor>>("gcode_flavor");
if (gcode_flavor != nullptr)
m_flavor = gcode_flavor->value;
const ConfigOptionPoints* printable_area = config.option<ConfigOptionPoints>("printable_area");
if (printable_area != nullptr)
m_result.printable_area = printable_area->values;
//BBS: add bed_exclude_area
const ConfigOptionPoints* bed_exclude_area = config.option<ConfigOptionPoints>("bed_exclude_area");
if (bed_exclude_area != nullptr)
m_result.bed_exclude_area = bed_exclude_area->values;
const ConfigOptionString* print_settings_id = config.option<ConfigOptionString>("print_settings_id");
if (print_settings_id != nullptr)
m_result.settings_ids.print = print_settings_id->value;
const ConfigOptionStrings* filament_settings_id = config.option<ConfigOptionStrings>("filament_settings_id");
if (filament_settings_id != nullptr)
m_result.settings_ids.filament = filament_settings_id->values;
const ConfigOptionString* printer_settings_id = config.option<ConfigOptionString>("printer_settings_id");
if (printer_settings_id != nullptr)
m_result.settings_ids.printer = printer_settings_id->value;
// BBS
m_result.extruders_count = config.option<ConfigOptionFloats>("filament_diameter")->values.size();
const ConfigOptionFloats* filament_diameters = config.option<ConfigOptionFloats>("filament_diameter");
if (filament_diameters != nullptr) {
m_result.filament_diameters.clear();
m_result.filament_diameters.resize(filament_diameters->values.size());
for (size_t i = 0; i < filament_diameters->values.size(); ++i) {
m_result.filament_diameters[i] = static_cast<float>(filament_diameters->values[i]);
}
}
if (m_result.filament_diameters.size() < m_result.extruders_count) {
for (size_t i = m_result.filament_diameters.size(); i < m_result.extruders_count; ++i) {
m_result.filament_diameters.emplace_back(DEFAULT_FILAMENT_DIAMETER);
}
}
const ConfigOptionInts *filament_HRC = config.option<ConfigOptionInts>("required_nozzle_HRC");
if (filament_HRC != nullptr) {
m_result.required_nozzle_HRC.clear();
m_result.required_nozzle_HRC.resize(filament_HRC->values.size());
for (size_t i = 0; i < filament_HRC->values.size(); ++i) { m_result.required_nozzle_HRC[i] = static_cast<float>(filament_HRC->values[i]); }
}
if (m_result.required_nozzle_HRC.size() < m_result.extruders_count) {
for (size_t i = m_result.required_nozzle_HRC.size(); i < m_result.extruders_count; ++i) { m_result.required_nozzle_HRC.emplace_back(DEFAULT_FILAMENT_HRC);
}
}
const ConfigOptionFloats* filament_densities = config.option<ConfigOptionFloats>("filament_density");
if (filament_densities != nullptr) {
m_result.filament_densities.clear();
m_result.filament_densities.resize(filament_densities->values.size());
for (size_t i = 0; i < filament_densities->values.size(); ++i) {
m_result.filament_densities[i] = static_cast<float>(filament_densities->values[i]);
}
}
if (m_result.filament_densities.size() < m_result.extruders_count) {
for (size_t i = m_result.filament_densities.size(); i < m_result.extruders_count; ++i) {
m_result.filament_densities.emplace_back(DEFAULT_FILAMENT_DENSITY);
}
}
//BBS
const ConfigOptionFloats* filament_costs = config.option<ConfigOptionFloats>("filament_cost");
if (filament_costs != nullptr) {
m_result.filament_costs.clear();
m_result.filament_costs.resize(filament_costs->values.size());
for (size_t i = 0; i < filament_costs->values.size(); ++i)
m_result.filament_costs[i]=static_cast<float>(filament_costs->values[i]);
}
for (size_t i = m_result.filament_costs.size(); i < m_result.extruders_count; ++i) {
m_result.filament_costs.emplace_back(DEFAULT_FILAMENT_COST);
}
//BBS
const ConfigOptionInts* filament_vitrification_temperature = config.option<ConfigOptionInts>("temperature_vitrification");
if (filament_vitrification_temperature != nullptr) {
m_result.filament_vitrification_temperature.clear();
m_result.filament_vitrification_temperature.resize(filament_vitrification_temperature->values.size());
for (size_t i = 0; i < filament_vitrification_temperature->values.size(); ++i) {
m_result.filament_vitrification_temperature[i] = static_cast<int>(filament_vitrification_temperature->values[i]);
}
}
if (m_result.filament_vitrification_temperature.size() < m_result.extruders_count) {
for (size_t i = m_result.filament_vitrification_temperature.size(); i < m_result.extruders_count; ++i) {
m_result.filament_vitrification_temperature.emplace_back(DEFAULT_FILAMENT_VITRIFICATION_TEMPERATURE);
}
}
const ConfigOptionPoints* extruder_offset = config.option<ConfigOptionPoints>("extruder_offset");
const ConfigOptionBool* single_extruder_multi_material = config.option<ConfigOptionBool>("single_extruder_multi_material");
if (extruder_offset != nullptr) {
//BBS: for single extruder multi material, only use the offset of first extruder
if (single_extruder_multi_material != nullptr && single_extruder_multi_material->getBool()) {
Vec2f offset = extruder_offset->values[0].cast<float>();
m_extruder_offsets.resize(m_result.extruders_count);
for (size_t i = 0; i < m_result.extruders_count; ++i) {
m_extruder_offsets[i] = { offset(0), offset(1), 0.0f };
}
}
else {
m_extruder_offsets.resize(extruder_offset->values.size());
for (size_t i = 0; i < extruder_offset->values.size(); ++i) {
Vec2f offset = extruder_offset->values[i].cast<float>();
m_extruder_offsets[i] = { offset(0), offset(1), 0.0f };
}
}
}
if (m_extruder_offsets.size() < m_result.extruders_count) {
for (size_t i = m_extruder_offsets.size(); i < m_result.extruders_count; ++i) {
m_extruder_offsets.emplace_back(DEFAULT_EXTRUDER_OFFSET);
}
}
// BBS
const ConfigOptionStrings* filament_colour = config.option<ConfigOptionStrings>("filament_colour");
if (filament_colour != nullptr && filament_colour->values.size() == m_result.extruder_colors.size()) {
for (size_t i = 0; i < m_result.extruder_colors.size(); ++i) {
if (m_result.extruder_colors[i].empty())
m_result.extruder_colors[i] = filament_colour->values[i];
}
}
if (m_result.extruder_colors.size() < m_result.extruders_count) {
for (size_t i = m_result.extruder_colors.size(); i < m_result.extruders_count; ++i) {
m_result.extruder_colors.emplace_back(std::string());
}
}
// replace missing values with default
for (size_t i = 0; i < m_result.extruder_colors.size(); ++i) {
if (m_result.extruder_colors[i].empty())
m_result.extruder_colors[i] = "#FF8000";
}
m_extruder_colors.resize(m_result.extruder_colors.size());
for (size_t i = 0; i < m_result.extruder_colors.size(); ++i) {
m_extruder_colors[i] = static_cast<unsigned char>(i);
}
m_extruder_temps.resize(m_result.extruders_count);
if(s_IsBBLPrinter){
// BBL printers use machine_load_filament_time and machine_unload_filament_time
const ConfigOptionFloat* machine_load_filament_time = config.option<ConfigOptionFloat>("machine_load_filament_time");
if (machine_load_filament_time != nullptr){
m_time_processor.filament_load_times.resize(1);
m_time_processor.filament_load_times[0] = static_cast<float>(machine_load_filament_time->value);
}
const ConfigOptionFloat* machine_unload_filament_time = config.option<ConfigOptionFloat>("machine_unload_filament_time");
if (machine_unload_filament_time != nullptr){
m_time_processor.filament_unload_times.resize(1);
m_time_processor.filament_unload_times[0] = static_cast<float>(machine_unload_filament_time->value);
}
} else {
// non-BBL printers use filament_load_time and filament_unload_time
const ConfigOptionFloats* filament_load_time = config.option<ConfigOptionFloats>("filament_load_time");
if (filament_load_time != nullptr) {
m_time_processor.filament_load_times.resize(filament_load_time->values.size());
for (size_t i = 0; i < filament_load_time->values.size(); ++i) {
m_time_processor.filament_load_times[i] = static_cast<float>(filament_load_time->values[i]);
}
}
const ConfigOptionFloats* filament_unload_time = config.option<ConfigOptionFloats>("filament_unload_time");
if (filament_unload_time != nullptr) {
m_time_processor.filament_unload_times.resize(filament_unload_time->values.size());
for (size_t i = 0; i < filament_unload_time->values.size(); ++i) {
m_time_processor.filament_unload_times[i] = static_cast<float>(filament_unload_time->values[i]);
}
}
}
if (m_flavor == gcfMarlinLegacy || m_flavor == gcfMarlinFirmware || m_flavor == gcfKlipper) {
const ConfigOptionFloats* machine_max_acceleration_x = config.option<ConfigOptionFloats>("machine_max_acceleration_x");
if (machine_max_acceleration_x != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_x.values = machine_max_acceleration_x->values;
const ConfigOptionFloats* machine_max_acceleration_y = config.option<ConfigOptionFloats>("machine_max_acceleration_y");
if (machine_max_acceleration_y != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_y.values = machine_max_acceleration_y->values;
const ConfigOptionFloats* machine_max_acceleration_z = config.option<ConfigOptionFloats>("machine_max_acceleration_z");
if (machine_max_acceleration_z != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_z.values = machine_max_acceleration_z->values;
const ConfigOptionFloats* machine_max_acceleration_e = config.option<ConfigOptionFloats>("machine_max_acceleration_e");
if (machine_max_acceleration_e != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_e.values = machine_max_acceleration_e->values;
const ConfigOptionFloats* machine_max_speed_x = config.option<ConfigOptionFloats>("machine_max_speed_x");
if (machine_max_speed_x != nullptr)
m_time_processor.machine_limits.machine_max_speed_x.values = machine_max_speed_x->values;
const ConfigOptionFloats* machine_max_speed_y = config.option<ConfigOptionFloats>("machine_max_speed_y");
if (machine_max_speed_y != nullptr)
m_time_processor.machine_limits.machine_max_speed_y.values = machine_max_speed_y->values;
const ConfigOptionFloats* machine_max_speed_z = config.option<ConfigOptionFloats>("machine_max_speed_z");
if (machine_max_speed_z != nullptr)
m_time_processor.machine_limits.machine_max_speed_z.values = machine_max_speed_z->values;
const ConfigOptionFloats* machine_max_speed_e = config.option<ConfigOptionFloats>("machine_max_speed_e");
if (machine_max_speed_e != nullptr)
m_time_processor.machine_limits.machine_max_speed_e.values = machine_max_speed_e->values;
const ConfigOptionFloats* machine_max_jerk_x = config.option<ConfigOptionFloats>("machine_max_jerk_x");
if (machine_max_jerk_x != nullptr)
m_time_processor.machine_limits.machine_max_jerk_x.values = machine_max_jerk_x->values;
const ConfigOptionFloats* machine_max_jerk_y = config.option<ConfigOptionFloats>("machine_max_jerk_y");
if (machine_max_jerk_y != nullptr)
m_time_processor.machine_limits.machine_max_jerk_y.values = machine_max_jerk_y->values;
const ConfigOptionFloats* machine_max_jerk_z = config.option<ConfigOptionFloats>("machine_max_jerkz");
if (machine_max_jerk_z != nullptr)
m_time_processor.machine_limits.machine_max_jerk_z.values = machine_max_jerk_z->values;
const ConfigOptionFloats* machine_max_jerk_e = config.option<ConfigOptionFloats>("machine_max_jerk_e");
if (machine_max_jerk_e != nullptr)
m_time_processor.machine_limits.machine_max_jerk_e.values = machine_max_jerk_e->values;
const ConfigOptionFloats* machine_max_acceleration_extruding = config.option<ConfigOptionFloats>("machine_max_acceleration_extruding");
if (machine_max_acceleration_extruding != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_extruding.values = machine_max_acceleration_extruding->values;
const ConfigOptionFloats* machine_max_acceleration_retracting = config.option<ConfigOptionFloats>("machine_max_acceleration_retracting");
if (machine_max_acceleration_retracting != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_retracting.values = machine_max_acceleration_retracting->values;
// Legacy Marlin does not have separate travel acceleration, it uses the 'extruding' value instead.
const ConfigOptionFloats* machine_max_acceleration_travel = config.option<ConfigOptionFloats>(m_flavor == gcfMarlinLegacy || m_flavor == gcfKlipper
? "machine_max_acceleration_extruding"
: "machine_max_acceleration_travel");
if (machine_max_acceleration_travel != nullptr)
m_time_processor.machine_limits.machine_max_acceleration_travel.values = machine_max_acceleration_travel->values;
const ConfigOptionFloats* machine_min_extruding_rate = config.option<ConfigOptionFloats>("machine_min_extruding_rate");
if (machine_min_extruding_rate != nullptr)
m_time_processor.machine_limits.machine_min_extruding_rate.values = machine_min_extruding_rate->values;
const ConfigOptionFloats* machine_min_travel_rate = config.option<ConfigOptionFloats>("machine_min_travel_rate");
if (machine_min_travel_rate != nullptr)
m_time_processor.machine_limits.machine_min_travel_rate.values = machine_min_travel_rate->values;
}
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
float max_acceleration = get_option_value(m_time_processor.machine_limits.machine_max_acceleration_extruding, i);
m_time_processor.machines[i].max_acceleration = max_acceleration;
m_time_processor.machines[i].acceleration = (max_acceleration > 0.0f) ? max_acceleration : DEFAULT_ACCELERATION;
float max_retract_acceleration = get_option_value(m_time_processor.machine_limits.machine_max_acceleration_retracting, i);
m_time_processor.machines[i].max_retract_acceleration = max_retract_acceleration;
m_time_processor.machines[i].retract_acceleration = (max_retract_acceleration > 0.0f) ? max_retract_acceleration :
DEFAULT_RETRACT_ACCELERATION;
float max_travel_acceleration = get_option_value(m_time_processor.machine_limits.machine_max_acceleration_travel, i);
m_time_processor.machines[i].max_travel_acceleration = max_travel_acceleration;
m_time_processor.machines[i].travel_acceleration = (max_travel_acceleration > 0.0f) ? max_travel_acceleration :
DEFAULT_TRAVEL_ACCELERATION;
}
if (m_flavor == gcfMarlinLegacy || m_flavor == gcfMarlinFirmware) {
const ConfigOptionBool* silent_mode = config.option<ConfigOptionBool>("silent_mode");
if (silent_mode != nullptr) {
if (silent_mode->value && m_time_processor.machine_limits.machine_max_acceleration_x.values.size() > 1)
enable_stealth_time_estimator(true);
}
}
const ConfigOptionFloat* initial_layer_print_height = config.option<ConfigOptionFloat>("initial_layer_print_height");
if (initial_layer_print_height != nullptr)
m_first_layer_height = std::abs(initial_layer_print_height->value);
const ConfigOptionFloat* printable_height = config.option<ConfigOptionFloat>("printable_height");
if (printable_height != nullptr)
m_result.printable_height = printable_height->value;
const ConfigOptionBool* spiral_vase = config.option<ConfigOptionBool>("spiral_mode");
if (spiral_vase != nullptr)
m_detect_layer_based_on_tag = spiral_vase->value;
const ConfigOptionBool* has_scarf_joint_seam = config.option<ConfigOptionBool>("has_scarf_joint_seam");
if (has_scarf_joint_seam != nullptr)
m_detect_layer_based_on_tag = m_detect_layer_based_on_tag || has_scarf_joint_seam->value;
const ConfigOptionEnumGeneric *bed_type = config.option<ConfigOptionEnumGeneric>("curr_bed_type");
if (bed_type != nullptr)
m_result.bed_type = (BedType)bed_type->value;
const ConfigOptionFloat* z_offset = config.option<ConfigOptionFloat>("z_offset");
if (z_offset != nullptr)
m_z_offset = z_offset->value;
}
void GCodeProcessor::enable_stealth_time_estimator(bool enabled)
{
m_time_processor.machines[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Stealth)].enabled = enabled;
}
void GCodeProcessor::reset()
{
m_units = EUnits::Millimeters;
m_global_positioning_type = EPositioningType::Absolute;
m_e_local_positioning_type = EPositioningType::Absolute;
m_extruder_offsets = std::vector<Vec3f>(MIN_EXTRUDERS_COUNT, Vec3f::Zero());
m_flavor = gcfRepRapSprinter;
m_nozzle_volume = 0.f;
m_start_position = { 0.0f, 0.0f, 0.0f, 0.0f };
m_end_position = { 0.0f, 0.0f, 0.0f, 0.0f };
m_origin = { 0.0f, 0.0f, 0.0f, 0.0f };
m_cached_position.reset();
m_wiping = false;
m_flushing = false;
m_wipe_tower = false;
m_remaining_volume = 0.f;
// BBS: arc move related data
m_move_path_type = EMovePathType::Noop_move;
m_arc_center = Vec3f::Zero();
m_line_id = 0;
m_last_line_id = 0;
m_feedrate = 0.0f;
m_width = 0.0f;
m_height = 0.0f;
m_forced_width = 0.0f;
m_forced_height = 0.0f;
m_mm3_per_mm = 0.0f;
m_fan_speed = 0.0f;
m_z_offset = 0.0f;
m_extrusion_role = erNone;
m_extruder_id = 0;
m_last_extruder_id = 0;
m_extruder_colors.resize(MIN_EXTRUDERS_COUNT);
for (size_t i = 0; i < MIN_EXTRUDERS_COUNT; ++i) {
m_extruder_colors[i] = static_cast<unsigned char>(i);
}
m_extruder_temps.resize(MIN_EXTRUDERS_COUNT);
for (size_t i = 0; i < MIN_EXTRUDERS_COUNT; ++i) {
m_extruder_temps[i] = 0.0f;
}
m_highest_bed_temp = 0;
m_extruded_last_z = 0.0f;
m_zero_layer_height = 0.0f;
m_first_layer_height = 0.0f;
m_processing_start_custom_gcode = false;
m_g1_line_id = 0;
m_layer_id = 0;
m_cp_color.reset();
m_producer = EProducer::Unknown;
m_time_processor.reset();
m_used_filaments.reset();
m_result.reset();
m_result.id = ++s_result_id;
m_last_default_color_id = 0;
m_options_z_corrector.reset();
m_detect_layer_based_on_tag = false;
m_seams_count = 0;
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
m_mm3_per_mm_compare.reset();
m_height_compare.reset();
m_width_compare.reset();
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
}
static inline const char* skip_whitespaces(const char *begin, const char *end) {
for (; begin != end && (*begin == ' ' || *begin == '\t'); ++ begin);
return begin;
}
static inline const char* remove_eols(const char *begin, const char *end) {
for (; begin != end && (*(end - 1) == '\r' || *(end - 1) == '\n'); -- end);
return end;
}
// Load a G-code into a stand-alone G-code viewer.
// throws CanceledException through print->throw_if_canceled() (sent by the caller as callback).
void GCodeProcessor::process_file(const std::string& filename, std::function<void()> cancel_callback)
{
CNumericLocalesSetter locales_setter;
#if ENABLE_GCODE_VIEWER_STATISTICS
m_start_time = std::chrono::high_resolution_clock::now();
#endif // ENABLE_GCODE_VIEWER_STATISTICS
// pre-processing
// parse the gcode file to detect its producer
{
m_parser.parse_file_raw(filename, [this](GCodeReader& reader, const char *begin, const char *end) {
begin = skip_whitespaces(begin, end);
if (begin != end && *begin == ';') {
// Comment.
begin = skip_whitespaces(++ begin, end);
end = remove_eols(begin, end);
if (begin != end) {
if (m_producer == EProducer::Unknown) {
if (detect_producer(std::string_view(begin, end - begin))) {
m_parser.quit_parsing();
}
} else if (std::string(begin, end).find("CONFIG_BLOCK_END") != std::string::npos) {
m_parser.quit_parsing();
}
}
}
});
m_parser.reset();
// if the gcode was produced by OrcaSlicer,
// extract the config from it
if (m_producer == EProducer::OrcaSlicer || m_producer == EProducer::Slic3rPE || m_producer == EProducer::Slic3r) {
DynamicPrintConfig config;
config.apply(FullPrintConfig::defaults());
// Silently substitute unknown values by new ones for loading configurations from OrcaSlicer's own G-code.
// Showing substitution log or errors may make sense, but we are not really reading many values from the G-code config,
// thus a probability of incorrect substitution is low and the G-code viewer is a consumer-only anyways.
config.load_from_gcode_file(filename, ForwardCompatibilitySubstitutionRule::EnableSilent);
apply_config(config);
}
else if (m_producer == EProducer::Simplify3D)
apply_config_simplify3d(filename);
else if (m_producer == EProducer::SuperSlicer)
apply_config_superslicer(filename);
}
// process gcode
m_result.filename = filename;
m_result.id = ++s_result_id;
// 1st move must be a dummy move
m_result.moves.emplace_back(GCodeProcessorResult::MoveVertex());
size_t parse_line_callback_cntr = 10000;
m_parser.parse_file(filename, [this, cancel_callback, &parse_line_callback_cntr](GCodeReader& reader, const GCodeReader::GCodeLine& line) {
if (-- parse_line_callback_cntr == 0) {
// Don't call the cancel_callback() too often, do it every at every 10000'th line.
parse_line_callback_cntr = 10000;
if (cancel_callback)
cancel_callback();
}
this->process_gcode_line(line, true);
}, m_result.lines_ends);
// Don't post-process the G-code to update time stamps.
this->finalize(false);
}
void GCodeProcessor::initialize(const std::string& filename)
{
assert(is_decimal_separator_point());
#if ENABLE_GCODE_VIEWER_STATISTICS
m_start_time = std::chrono::high_resolution_clock::now();
#endif // ENABLE_GCODE_VIEWER_STATISTICS
// process gcode
m_result.filename = filename;
m_result.id = ++s_result_id;
// 1st move must be a dummy move
m_result.moves.emplace_back(GCodeProcessorResult::MoveVertex());
}
void GCodeProcessor::process_buffer(const std::string &buffer)
{
//FIXME maybe cache GCodeLine gline to be over multiple parse_buffer() invocations.
m_parser.parse_buffer(buffer, [this](GCodeReader&, const GCodeReader::GCodeLine& line) {
this->process_gcode_line(line, false);
});
}
void GCodeProcessor::finalize(bool post_process)
{
// update width/height of wipe moves
for (GCodeProcessorResult::MoveVertex& move : m_result.moves) {
if (move.type == EMoveType::Wipe) {
move.width = Wipe_Width;
move.height = Wipe_Height;
}
}
// process the time blocks
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
TimeMachine& machine = m_time_processor.machines[i];
TimeMachine::CustomGCodeTime& gcode_time = machine.gcode_time;
machine.calculate_time();
if (gcode_time.needed && gcode_time.cache != 0.0f)
gcode_time.times.push_back({ CustomGCode::ColorChange, gcode_time.cache });
}
m_used_filaments.process_caches(this);
update_estimated_times_stats();
auto time_mode = m_result.print_statistics.modes[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Normal)];
auto it = std::find_if(time_mode.roles_times.begin(), time_mode.roles_times.end(), [](const std::pair<ExtrusionRole, float>& item) { return erCustom == item.first; });
auto prepare_time = (it != time_mode.roles_times.end()) ? it->second : 0.0f;
//update times for results
for (size_t i = 0; i < m_result.moves.size(); i++) {
//field layer_duration contains the layer id for the move in which the layer_duration has to be set.
size_t layer_id = size_t(m_result.moves[i].layer_duration);
std::vector<float>& layer_times = m_result.print_statistics.modes[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Normal)].layers_times;
if (layer_times.size() > layer_id - 1 && layer_id > 0)
m_result.moves[i].layer_duration = layer_id == 1 ? std::max(0.f,layer_times[layer_id - 1] - prepare_time) : layer_times[layer_id - 1];
else
m_result.moves[i].layer_duration = 0;
}
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
std::cout << "\n";
m_mm3_per_mm_compare.output();
m_height_compare.output();
m_width_compare.output();
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
if (post_process){
m_time_processor.post_process(m_result.filename, m_result.moves, m_result.lines_ends, m_layer_id);
}
#if ENABLE_GCODE_VIEWER_STATISTICS
m_result.time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - m_start_time).count();
#endif // ENABLE_GCODE_VIEWER_STATISTICS
//BBS: update slice warning
update_slice_warnings();
}
float GCodeProcessor::get_time(PrintEstimatedStatistics::ETimeMode mode) const
{
return (mode < PrintEstimatedStatistics::ETimeMode::Count) ? m_time_processor.machines[static_cast<size_t>(mode)].time : 0.0f;
}
float GCodeProcessor::get_prepare_time(PrintEstimatedStatistics::ETimeMode mode) const
{
return (mode < PrintEstimatedStatistics::ETimeMode::Count) ? m_time_processor.machines[static_cast<size_t>(mode)].prepare_time : 0.0f;
}
std::string GCodeProcessor::get_time_dhm(PrintEstimatedStatistics::ETimeMode mode) const
{
return (mode < PrintEstimatedStatistics::ETimeMode::Count) ? short_time(get_time_dhms(m_time_processor.machines[static_cast<size_t>(mode)].time)) : std::string("N/A");
}
std::vector<std::pair<CustomGCode::Type, std::pair<float, float>>> GCodeProcessor::get_custom_gcode_times(PrintEstimatedStatistics::ETimeMode mode, bool include_remaining) const
{
std::vector<std::pair<CustomGCode::Type, std::pair<float, float>>> ret;
if (mode < PrintEstimatedStatistics::ETimeMode::Count) {
const TimeMachine& machine = m_time_processor.machines[static_cast<size_t>(mode)];
float total_time = 0.0f;
for (const auto& [type, time] : machine.gcode_time.times) {
float remaining = include_remaining ? machine.time - total_time : 0.0f;
ret.push_back({ type, { time, remaining } });
total_time += time;
}
}
return ret;
}
std::vector<std::pair<EMoveType, float>> GCodeProcessor::get_moves_time(PrintEstimatedStatistics::ETimeMode mode) const
{
std::vector<std::pair<EMoveType, float>> ret;
if (mode < PrintEstimatedStatistics::ETimeMode::Count) {
for (size_t i = 0; i < m_time_processor.machines[static_cast<size_t>(mode)].moves_time.size(); ++i) {
float time = m_time_processor.machines[static_cast<size_t>(mode)].moves_time[i];
if (time > 0.0f)
ret.push_back({ static_cast<EMoveType>(i), time });
}
}
return ret;
}
std::vector<std::pair<ExtrusionRole, float>> GCodeProcessor::get_roles_time(PrintEstimatedStatistics::ETimeMode mode) const
{
std::vector<std::pair<ExtrusionRole, float>> ret;
if (mode < PrintEstimatedStatistics::ETimeMode::Count) {
for (size_t i = 0; i < m_time_processor.machines[static_cast<size_t>(mode)].roles_time.size(); ++i) {
float time = m_time_processor.machines[static_cast<size_t>(mode)].roles_time[i];
if (time > 0.0f)
ret.push_back({ static_cast<ExtrusionRole>(i), time });
}
}
return ret;
}
ConfigSubstitutions load_from_superslicer_gcode_file(const std::string& filename, DynamicPrintConfig& config, ForwardCompatibilitySubstitutionRule compatibility_rule)
{
// for reference, see: ConfigBase::load_from_gcode_file()
boost::nowide::ifstream ifs(filename);
auto header_end_pos = ifs.tellg();
ConfigSubstitutionContext substitutions_ctxt(compatibility_rule);
size_t key_value_pairs = 0;
ifs.seekg(0, ifs.end);
auto file_length = ifs.tellg();
auto data_length = std::min<std::fstream::pos_type>(65535, file_length - header_end_pos);
ifs.seekg(file_length - data_length, ifs.beg);
std::vector<char> data(size_t(data_length) + 1, 0);
ifs.read(data.data(), data_length);
ifs.close();
key_value_pairs = ConfigBase::load_from_gcode_string_legacy(config, data.data(), substitutions_ctxt);
if (key_value_pairs < 80)
throw Slic3r::RuntimeError(format("Suspiciously low number of configuration values extracted from %1%: %2%", filename, key_value_pairs));
return std::move(substitutions_ctxt.substitutions);
}
void GCodeProcessor::apply_config_superslicer(const std::string& filename)
{
DynamicPrintConfig config;
config.apply(FullPrintConfig::defaults());
load_from_superslicer_gcode_file(filename, config, ForwardCompatibilitySubstitutionRule::EnableSilent);
apply_config(config);
}
std::vector<float> GCodeProcessor::get_layers_time(PrintEstimatedStatistics::ETimeMode mode) const
{
return (mode < PrintEstimatedStatistics::ETimeMode::Count) ?
m_time_processor.machines[static_cast<size_t>(mode)].layers_time :
std::vector<float>();
}
void GCodeProcessor::apply_config_simplify3d(const std::string& filename)
{
struct BedSize
{
double x{ 0.0 };
double y{ 0.0 };
bool is_defined() const { return x > 0.0 && y > 0.0; }
};
BedSize bed_size;
bool producer_detected = false;
m_parser.parse_file_raw(filename, [this, &bed_size, &producer_detected](GCodeReader& reader, const char* begin, const char* end) {
auto extract_double = [](const std::string_view cmt, const std::string& key, double& out) {
size_t pos = cmt.find(key);
if (pos != cmt.npos) {
pos = cmt.find(',', pos);
if (pos != cmt.npos) {
out = string_to_double_decimal_point(cmt.substr(pos+1));
return true;
}
}
return false;
};
auto extract_floats = [](const std::string_view cmt, const std::string& key, std::vector<float>& out) {
size_t pos = cmt.find(key);
if (pos != cmt.npos) {
pos = cmt.find(',', pos);
if (pos != cmt.npos) {
const std::string_view data_str = cmt.substr(pos + 1);
std::vector<std::string> values_str;
boost::split(values_str, data_str, boost::is_any_of("|,"), boost::token_compress_on);
for (const std::string& s : values_str) {
out.emplace_back(static_cast<float>(string_to_double_decimal_point(s)));
}
return true;
}
}
return false;
};
begin = skip_whitespaces(begin, end);
end = remove_eols(begin, end);
if (begin != end) {
if (*begin == ';') {
// Comment.
begin = skip_whitespaces(++ begin, end);
if (begin != end) {
std::string_view comment(begin, end - begin);
if (producer_detected) {
if (bed_size.x == 0.0 && comment.find("strokeXoverride") != comment.npos)
extract_double(comment, "strokeXoverride", bed_size.x);
else if (bed_size.y == 0.0 && comment.find("strokeYoverride") != comment.npos)
extract_double(comment, "strokeYoverride", bed_size.y);
else if (comment.find("filamentDiameters") != comment.npos) {
m_result.filament_diameters.clear();
extract_floats(comment, "filamentDiameters", m_result.filament_diameters);
} else if (comment.find("filamentDensities") != comment.npos) {
m_result.filament_densities.clear();
extract_floats(comment, "filamentDensities", m_result.filament_densities);
} else if (comment.find("extruderDiameter") != comment.npos) {
std::vector<float> extruder_diameters;
extract_floats(comment, "extruderDiameter", extruder_diameters);
m_result.extruders_count = extruder_diameters.size();
}
} else if (boost::starts_with(comment, "G-Code generated by Simplify3D(R)"))
producer_detected = true;
}
} else {
// Some non-empty G-code line detected, stop parsing config comments.
reader.quit_parsing();
}
}
});
if (m_result.extruders_count == 0)
m_result.extruders_count = std::max<size_t>(1, std::min(m_result.filament_diameters.size(), m_result.filament_densities.size()));
if (bed_size.is_defined()) {
m_result.printable_area = {
{ 0.0, 0.0 },
{ bed_size.x, 0.0 },
{ bed_size.x, bed_size.y },
{ 0.0, bed_size.y }
};
}
}
void GCodeProcessor::process_gcode_line(const GCodeReader::GCodeLine& line, bool producers_enabled)
{
/* std::cout << line.raw() << std::endl; */
++m_line_id;
// update start position
m_start_position = m_end_position;
const std::string_view cmd = line.cmd();
if (m_flavor == gcfKlipper)
{
if (boost::iequals(cmd, "SET_VELOCITY_LIMIT"))
{
process_SET_VELOCITY_LIMIT(line);
return;
}
}
if (cmd.length() > 1) {
// process command lines
switch (cmd[0])
{
case 'g':
case 'G':
switch (cmd.size()) {
case 2:
switch (cmd[1]) {
case '0': { process_G0(line); break; } // Move
case '1': { process_G1(line); break; } // Move
case '2':
case '3': { process_G2_G3(line); break; } // Move
//BBS
case 4: { process_G4(line); break; } // Delay
default: break;
}
break;
case 3:
switch (cmd[1]) {
case '1':
switch (cmd[2]) {
case '0': { process_G10(line); break; } // Retract
case '1': { process_G11(line); break; } // Unretract
default: break;
}
break;
case '2':
switch (cmd[2]) {
case '0': { process_G20(line); break; } // Set Units to Inches
case '1': { process_G21(line); break; } // Set Units to Millimeters
case '2': { process_G22(line); break; } // Firmware controlled retract
case '3': { process_G23(line); break; } // Firmware controlled unretract
case '8': { process_G28(line); break; } // Move to origin
case '9': { process_G29(line); break; }
default: break;
}
break;
case '9':
switch (cmd[2]) {
case '0': { process_G90(line); break; } // Set to Absolute Positioning
case '1': { process_G91(line); break; } // Set to Relative Positioning
case '2': { process_G92(line); break; } // Set Position
default: break;
}
break;
}
break;
default:
break;
}
break;
case 'm':
case 'M':
switch (cmd.size()) {
case 2:
switch (cmd[1]) {
case '1': { process_M1(line); break; } // Sleep or Conditional stop
default: break;
}
break;
case 3:
switch (cmd[1]) {
case '8':
switch (cmd[2]) {
case '2': { process_M82(line); break; } // Set extruder to absolute mode
case '3': { process_M83(line); break; } // Set extruder to relative mode
default: break;
}
break;
default:
break;
}
break;
case 4:
switch (cmd[1]) {
case '1':
switch (cmd[2]) {
case '0':
switch (cmd[3]) {
case '4': { process_M104(line); break; } // Set extruder temperature
case '6': { process_M106(line); break; } // Set fan speed
case '7': { process_M107(line); break; } // Disable fan
case '8': { process_M108(line); break; } // Set tool (Sailfish)
case '9': { process_M109(line); break; } // Set extruder temperature and wait
default: break;
}
break;
case '3':
switch (cmd[3]) {
case '2': { process_M132(line); break; } // Recall stored home offsets
case '5': { process_M135(line); break; } // Set tool (MakerWare)
default: break;
}
break;
case '4':
switch (cmd[3]) {
case '0': { process_M140(line); break; } // Set bed temperature
default: break;
}
case '9':
switch (cmd[3]) {
case '0': { process_M190(line); break; } // Wait bed temperature
case '1': { process_M191(line); break; } // Wait chamber temperature
default: break;
}
default:
break;
}
break;
case '2':
switch (cmd[2]) {
case '0':
switch (cmd[3]) {
case '1': { process_M201(line); break; } // Set max printing acceleration
case '3': { process_M203(line); break; } // Set maximum feedrate
case '4': { process_M204(line); break; } // Set default acceleration
case '5': { process_M205(line); break; } // Advanced settings
default: break;
}
break;
case '2':
switch (cmd[3]) {
case '1': { process_M221(line); break; } // Set extrude factor override percentage
default: break;
}
break;
default:
break;
}
break;
case '4':
switch (cmd[2]) {
case '0':
switch (cmd[3]) {
//BBS
case '0': { process_M400(line); break; } // BBS delay
case '1': { process_M401(line); break; } // Repetier: Store x, y and z position
case '2': { process_M402(line); break; } // Repetier: Go to stored position
default: break;
}
break;
default:
break;
}
break;
case '5':
switch (cmd[2]) {
case '6':
switch (cmd[3]) {
case '6': { process_M566(line); break; } // Set allowable instantaneous speed change
default: break;
}
break;
default:
break;
}
break;
case '7':
switch (cmd[2]) {
case '0':
switch (cmd[3]) {
case '2': { process_M702(line); break; } // Unload the current filament into the MK3 MMU2 unit at the end of print.
default: break;
}
break;
default:
break;
}
break;
default:
break;
}
break;
default:
break;
}
break;
case 't':
case 'T':
process_T(line); // Select Tool
break;
default:
break;
}
}
else {
const std::string &comment = line.raw();
if (comment.length() > 2 && comment.front() == ';')
// Process tags embedded into comments. Tag comments always start at the start of a line
// with a comment and continue with a tag without any whitespace separator.
process_tags(comment.substr(1), producers_enabled);
}
}
#if __has_include(<charconv>)
template <typename T, typename = void>
struct is_from_chars_convertible : std::false_type {};
template <typename T>
struct is_from_chars_convertible<T, std::void_t<decltype(std::from_chars(std::declval<const char*>(), std::declval<const char*>(), std::declval<T&>()))>> : std::true_type {};
#endif
// Returns true if the number was parsed correctly into out and the number spanned the whole input string.
template<typename T>
[[nodiscard]] static inline bool parse_number(const std::string_view sv, T &out)
{
// https://www.bfilipek.com/2019/07/detect-overload-from-chars.html#example-stdfromchars
#if __has_include(<charconv>)
// Visual Studio 19 supports from_chars all right.
// OSX compiler that we use only implements std::from_chars just for ints.
// GCC that we compile on does not provide <charconv> at all.
if constexpr (is_from_chars_convertible<T>::value) {
auto str_end = sv.data() + sv.size();
auto [end_ptr, error_code] = std::from_chars(sv.data(), str_end, out);
return error_code == std::errc() && end_ptr == str_end;
}
else
#endif
{
// Legacy conversion, which is costly due to having to make a copy of the string before conversion.
try {
assert(sv.size() < 1024);
assert(sv.data() != nullptr);
std::string str { sv };
size_t read = 0;
if constexpr (std::is_same_v<T, int>)
out = std::stoi(str, &read);
else if constexpr (std::is_same_v<T, long>)
out = std::stol(str, &read);
else if constexpr (std::is_same_v<T, float>)
out = string_to_double_decimal_point(str, &read);
else if constexpr (std::is_same_v<T, double>)
out = string_to_double_decimal_point(str, &read);
return str.size() == read;
} catch (...) {
return false;
}
}
}
int GCodeProcessor::get_gcode_last_filament(const std::string& gcode_str)
{
int str_size = gcode_str.size();
int start_index = 0;
int end_index = 0;
int out_filament = -1;
while (end_index < str_size) {
if (gcode_str[end_index] != '\n') {
end_index++;
continue;
}
if (end_index > start_index) {
std::string line_str = gcode_str.substr(start_index, end_index - start_index);
line_str.erase(0, line_str.find_first_not_of(" "));
line_str.erase(line_str.find_last_not_of(" ") + 1);
if (line_str.empty() || line_str[0] != 'T') {
start_index = end_index + 1;
end_index = start_index;
continue;
}
int out = -1;
if (parse_number(line_str.substr(1), out) && out >= 0 && out < 255)
out_filament = out;
}
start_index = end_index + 1;
end_index = start_index;
}
return out_filament;
}
//BBS: get last z position from gcode
bool GCodeProcessor::get_last_z_from_gcode(const std::string& gcode_str, double& z)
{
int str_size = gcode_str.size();
int start_index = 0;
int end_index = 0;
bool is_z_changed = false;
while (end_index < str_size) {
//find a full line
if (gcode_str[end_index] != '\n') {
end_index++;
continue;
}
//parse the line
if (end_index > start_index) {
std::string line_str = gcode_str.substr(start_index, end_index - start_index);
line_str.erase(0, line_str.find_first_not_of(" "));
line_str.erase(line_str.find_last_not_of(";") + 1);
line_str.erase(line_str.find_last_not_of(" ") + 1);
//command which may have z movement
if (line_str.size() > 5 && (line_str.find("G0 ") == 0
|| line_str.find("G1 ") == 0
|| line_str.find("G2 ") == 0
|| line_str.find("G3 ") == 0))
{
auto z_pos = line_str.find(" Z");
double temp_z = 0;
if (z_pos != line_str.npos
&& z_pos + 2 < line_str.size()) {
// Try to parse the numeric value.
std::string z_sub = line_str.substr(z_pos + 2);
char* c = &z_sub[0];
char* end = c + sizeof(z_sub.c_str());
auto is_end_of_word = [](char c) {
return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 0 || c == ';';
};
auto [pend, ec] = fast_float::from_chars(c, end, temp_z);
if (pend != c && is_end_of_word(*pend)) {
// The axis value has been parsed correctly.
z = temp_z;
is_z_changed = true;
}
}
}
}
//loop to handle next line
start_index = end_index + 1;
end_index = start_index;
}
return is_z_changed;
}
void GCodeProcessor::process_tags(const std::string_view comment, bool producers_enabled)
{
// producers tags
if (producers_enabled && process_producers_tags(comment))
return;
// extrusion role tag
if (boost::starts_with(comment, reserved_tag(ETags::Role))) {
set_extrusion_role(ExtrusionEntity::string_to_role(comment.substr(reserved_tag(ETags::Role).length())));
if (m_extrusion_role == erExternalPerimeter)
m_seams_detector.activate(true);
m_processing_start_custom_gcode = (m_extrusion_role == erCustom && m_g1_line_id == 0);
return;
}
// wipe start tag
if (boost::starts_with(comment, reserved_tag(ETags::Wipe_Start))) {
m_wiping = true;
return;
}
// wipe end tag
if (boost::starts_with(comment, reserved_tag(ETags::Wipe_End))) {
m_wiping = false;
return;
}
if (boost::starts_with(comment, reserved_tag(ETags::Wipe_Tower_Start))) {
m_wipe_tower = true;
return;
}
if (boost::starts_with(comment, reserved_tag(ETags::Wipe_Tower_End))) {
m_wipe_tower = false;
m_used_filaments.process_wipe_tower_cache(this);
return;
}
//BBS: flush start tag
if (boost::starts_with(comment, GCodeProcessor::Flush_Start_Tag)) {
m_flushing = true;
return;
}
//BBS: flush end tag
if (boost::starts_with(comment, GCodeProcessor::Flush_End_Tag)) {
m_flushing = false;
return;
}
if (!producers_enabled || m_producer == EProducer::OrcaSlicer) {
// height tag
if (boost::starts_with(comment, reserved_tag(ETags::Height))) {
if (!parse_number(comment.substr(reserved_tag(ETags::Height).size()), m_forced_height))
BOOST_LOG_TRIVIAL(error) << "GCodeProcessor encountered an invalid value for Height (" << comment << ").";
return;
}
// width tag
if (boost::starts_with(comment, reserved_tag(ETags::Width))) {
if (!parse_number(comment.substr(reserved_tag(ETags::Width).size()), m_forced_width))
BOOST_LOG_TRIVIAL(error) << "GCodeProcessor encountered an invalid value for Width (" << comment << ").";
return;
}
// Orca: manual tool change tag
if (m_manual_filament_change && boost::starts_with(comment, reserved_tag(ETags::Manual_Tool_Change))) {
std::string_view tool_change_cmd = comment.substr(reserved_tag(ETags::Manual_Tool_Change).length());
if (boost::starts_with(tool_change_cmd, "T")) {
process_T(tool_change_cmd);
}
}
}
// color change tag
if (boost::starts_with(comment, reserved_tag(ETags::Color_Change))) {
unsigned char extruder_id = 0;
static std::vector<std::string> Default_Colors = {
"#0B2C7A", // { 0.043f, 0.173f, 0.478f }, // bluish
"#1C8891", // { 0.110f, 0.533f, 0.569f },
"#AAF200", // { 0.667f, 0.949f, 0.000f },
"#F5CE0A", // { 0.961f, 0.808f, 0.039f },
"#D16830", // { 0.820f, 0.408f, 0.188f },
"#942616", // { 0.581f, 0.149f, 0.087f } // reddish
};
std::string color = Default_Colors[0];
auto is_valid_color = [](const std::string& color) {
auto is_hex_digit = [](char c) {
return ((c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'F') ||
(c >= 'a' && c <= 'f'));
};
if (color[0] != '#' || color.length() != 7)
return false;
for (int i = 1; i <= 6; ++i) {
if (!is_hex_digit(color[i]))
return false;
}
return true;
};
std::vector<std::string> tokens;
boost::split(tokens, comment, boost::is_any_of(","), boost::token_compress_on);
if (tokens.size() > 1) {
if (tokens[1][0] == 'T') {
int eid;
if (!parse_number(tokens[1].substr(1), eid) || eid < 0 || eid > 255) {
BOOST_LOG_TRIVIAL(error) << "GCodeProcessor encountered an invalid value for Color_Change (" << comment << ").";
return;
}
extruder_id = static_cast<unsigned char>(eid);
}
}
if (tokens.size() > 2) {
if (is_valid_color(tokens[2]))
color = tokens[2];
}
else {
color = Default_Colors[m_last_default_color_id];
++m_last_default_color_id;
if (m_last_default_color_id == Default_Colors.size())
m_last_default_color_id = 0;
}
if (extruder_id < m_extruder_colors.size())
m_extruder_colors[extruder_id] = static_cast<unsigned char>(m_extruder_offsets.size()) + m_cp_color.counter; // color_change position in list of color for preview
++m_cp_color.counter;
if (m_cp_color.counter == UCHAR_MAX)
m_cp_color.counter = 0;
if (m_extruder_id == extruder_id) {
m_cp_color.current = m_extruder_colors[extruder_id];
store_move_vertex(EMoveType::Color_change);
CustomGCode::Item item = { static_cast<double>(m_end_position[2]), CustomGCode::ColorChange, extruder_id + 1, color, "" };
m_result.custom_gcode_per_print_z.emplace_back(item);
m_options_z_corrector.set();
process_custom_gcode_time(CustomGCode::ColorChange);
process_filaments(CustomGCode::ColorChange);
}
return;
}
// pause print tag
if (comment == reserved_tag(ETags::Pause_Print)) {
store_move_vertex(EMoveType::Pause_Print);
CustomGCode::Item item = { static_cast<double>(m_end_position[2]), CustomGCode::PausePrint, m_extruder_id + 1, "", "" };
m_result.custom_gcode_per_print_z.emplace_back(item);
m_options_z_corrector.set();
process_custom_gcode_time(CustomGCode::PausePrint);
return;
}
// custom code tag
if (comment == reserved_tag(ETags::Custom_Code)) {
store_move_vertex(EMoveType::Custom_GCode);
CustomGCode::Item item = { static_cast<double>(m_end_position[2]), CustomGCode::Custom, m_extruder_id + 1, "", "" };
m_result.custom_gcode_per_print_z.emplace_back(item);
m_options_z_corrector.set();
return;
}
// layer change tag
if (comment == reserved_tag(ETags::Layer_Change)) {
++m_layer_id;
if (m_detect_layer_based_on_tag) {
if (m_result.moves.empty() || m_result.spiral_vase_layers.empty())
// add a placeholder for layer height. the actual value will be set inside process_G1() method
m_result.spiral_vase_layers.push_back({ FLT_MAX, { 0, 0 } });
else {
const size_t move_id = m_result.moves.size() - 1 - m_seams_count;
if (!m_result.spiral_vase_layers.empty())
m_result.spiral_vase_layers.back().second.second = move_id;
// add a placeholder for layer height. the actual value will be set inside process_G1() method
m_result.spiral_vase_layers.push_back({ FLT_MAX, { move_id, move_id } });
}
}
return;
}
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
// mm3_per_mm print tag
if (boost::starts_with(comment, Mm3_Per_Mm_Tag)) {
if (! parse_number(comment.substr(Mm3_Per_Mm_Tag.size()), m_mm3_per_mm_compare.last_tag_value))
BOOST_LOG_TRIVIAL(error) << "GCodeProcessor encountered an invalid value for Mm3_Per_Mm (" << comment << ").";
return;
}
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
}
bool GCodeProcessor::process_producers_tags(const std::string_view comment)
{
switch (m_producer)
{
case EProducer::Slic3rPE:
case EProducer::Slic3r:
case EProducer::SuperSlicer:
case EProducer::OrcaSlicer: { return process_bambuslicer_tags(comment); }
case EProducer::Cura: { return process_cura_tags(comment); }
case EProducer::Simplify3D: { return process_simplify3d_tags(comment); }
case EProducer::CraftWare: { return process_craftware_tags(comment); }
case EProducer::ideaMaker: { return process_ideamaker_tags(comment); }
case EProducer::KissSlicer: { return process_kissslicer_tags(comment); }
default: { return false; }
}
}
bool GCodeProcessor::process_bambuslicer_tags(const std::string_view comment)
{
return false;
}
bool GCodeProcessor::process_cura_tags(const std::string_view comment)
{
// TYPE -> extrusion role
std::string tag = "TYPE:";
size_t pos = comment.find(tag);
if (pos != comment.npos) {
const std::string_view type = comment.substr(pos + tag.length());
if (type == "SKIRT")
set_extrusion_role(erSkirt);
else if (type == "WALL-OUTER")
set_extrusion_role(erExternalPerimeter);
else if (type == "WALL-INNER")
set_extrusion_role(erPerimeter);
else if (type == "SKIN")
set_extrusion_role(erSolidInfill);
else if (type == "FILL")
set_extrusion_role(erInternalInfill);
else if (type == "SUPPORT")
set_extrusion_role(erSupportMaterial);
else if (type == "SUPPORT-INTERFACE")
set_extrusion_role(erSupportMaterialInterface);
else if (type == "PRIME-TOWER")
set_extrusion_role(erWipeTower);
else {
set_extrusion_role(erNone);
BOOST_LOG_TRIVIAL(warning) << "GCodeProcessor found unknown extrusion role: " << type;
}
if (m_extrusion_role == erExternalPerimeter)
m_seams_detector.activate(true);
return true;
}
// flavor
tag = "FLAVOR:";
pos = comment.find(tag);
if (pos != comment.npos) {
const std::string_view flavor = comment.substr(pos + tag.length());
if (flavor == "BFB")
m_flavor = gcfMarlinLegacy; // is this correct ?
else if (flavor == "Mach3")
m_flavor = gcfMach3;
else if (flavor == "Makerbot")
m_flavor = gcfMakerWare;
else if (flavor == "UltiGCode")
m_flavor = gcfMarlinLegacy; // is this correct ?
else if (flavor == "Marlin(Volumetric)")
m_flavor = gcfMarlinLegacy; // is this correct ?
else if (flavor == "Griffin")
m_flavor = gcfMarlinLegacy; // is this correct ?
else if (flavor == "Repetier")
m_flavor = gcfRepetier;
else if (flavor == "RepRap")
m_flavor = gcfRepRapFirmware;
else if (flavor == "Marlin")
m_flavor = gcfMarlinLegacy;
else
BOOST_LOG_TRIVIAL(warning) << "GCodeProcessor found unknown flavor: " << flavor;
return true;
}
// layer
tag = "LAYER:";
pos = comment.find(tag);
if (pos != comment.npos) {
++m_layer_id;
return true;
}
return false;
}
bool GCodeProcessor::process_simplify3d_tags(const std::string_view comment)
{
// extrusion roles
// in older versions the comments did not contain the key 'feature'
std::string_view cmt = comment;
size_t pos = cmt.find(" feature");
if (pos == 0)
cmt.remove_prefix(8);
// ; skirt
pos = cmt.find(" skirt");
if (pos == 0) {
set_extrusion_role(erSkirt);
return true;
}
// ; outer perimeter
pos = cmt.find(" outer perimeter");
if (pos == 0) {
set_extrusion_role(erExternalPerimeter);
m_seams_detector.activate(true);
return true;
}
// ; inner perimeter
pos = cmt.find(" inner perimeter");
if (pos == 0) {
set_extrusion_role(erPerimeter);
return true;
}
// ; gap fill
pos = cmt.find(" gap fill");
if (pos == 0) {
set_extrusion_role(erGapFill);
return true;
}
// ; infill
pos = cmt.find(" infill");
if (pos == 0) {
set_extrusion_role(erInternalInfill);
return true;
}
// ; solid layer
pos = cmt.find(" solid layer");
if (pos == 0) {
set_extrusion_role(erSolidInfill);
return true;
}
// ; bridge
pos = cmt.find(" bridge");
if (pos == 0) {
set_extrusion_role(erBridgeInfill);
return true;
}
// ; internal bridge
pos = cmt.find(" internal bridge");
if (pos == 0) {
set_extrusion_role(erInternalBridgeInfill);
return true;
}
// ; support
pos = cmt.find(" support");
if (pos == 0) {
set_extrusion_role(erSupportMaterial);
return true;
}
// ; dense support
pos = cmt.find(" dense support");
if (pos == 0) {
set_extrusion_role(erSupportMaterialInterface);
return true;
}
// ; prime pillar
pos = cmt.find(" prime pillar");
if (pos == 0) {
set_extrusion_role(erWipeTower);
return true;
}
// ; ooze shield
pos = cmt.find(" ooze shield");
if (pos == 0) {
set_extrusion_role(erNone); // Missing mapping
return true;
}
// ; raft
pos = cmt.find(" raft");
if (pos == 0) {
set_extrusion_role(erSupportMaterial);
return true;
}
// ; internal single extrusion
pos = cmt.find(" internal single extrusion");
if (pos == 0) {
set_extrusion_role(erNone); // Missing mapping
return true;
}
// geometry
// ; tool
std::string tag = " tool";
pos = cmt.find(tag);
if (pos == 0) {
const std::string_view data = cmt.substr(pos + tag.length());
std::string h_tag = "H";
size_t h_start = data.find(h_tag);
size_t h_end = data.find_first_of(' ', h_start);
std::string w_tag = "W";
size_t w_start = data.find(w_tag);
size_t w_end = data.find_first_of(' ', w_start);
if (h_start != data.npos) {
if (!parse_number(data.substr(h_start + 1, (h_end != data.npos) ? h_end - h_start - 1 : h_end), m_forced_height))
BOOST_LOG_TRIVIAL(error) << "GCodeProcessor encountered an invalid value for Height (" << comment << ").";
}
if (w_start != data.npos) {
if (!parse_number(data.substr(w_start + 1, (w_end != data.npos) ? w_end - w_start - 1 : w_end), m_forced_width))
BOOST_LOG_TRIVIAL(error) << "GCodeProcessor encountered an invalid value for Width (" << comment << ").";
}
return true;
}
// ; layer
tag = " layer";
pos = cmt.find(tag);
if (pos == 0) {
// skip lines "; layer end"
const std::string_view data = cmt.substr(pos + tag.length());
size_t end_start = data.find("end");
if (end_start == data.npos)
++m_layer_id;
return true;
}
return false;
}
bool GCodeProcessor::process_craftware_tags(const std::string_view comment)
{
// segType -> extrusion role
std::string tag = "segType:";
size_t pos = comment.find(tag);
if (pos != comment.npos) {
const std::string_view type = comment.substr(pos + tag.length());
if (type == "Skirt")
set_extrusion_role(erSkirt);
else if (type == "Perimeter")
set_extrusion_role(erExternalPerimeter);
else if (type == "HShell")
set_extrusion_role(erNone); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
else if (type == "InnerHair")
set_extrusion_role(erNone); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
else if (type == "Loop")
set_extrusion_role(erNone); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
else if (type == "Infill")
set_extrusion_role(erInternalInfill);
else if (type == "Raft")
set_extrusion_role(erSkirt);
else if (type == "Support")
set_extrusion_role(erSupportMaterial);
else if (type == "SupportTouch")
set_extrusion_role(erSupportMaterial);
else if (type == "SoftSupport")
set_extrusion_role(erSupportMaterialInterface);
else if (type == "Pillar")
set_extrusion_role(erWipeTower);
else {
set_extrusion_role(erNone);
BOOST_LOG_TRIVIAL(warning) << "GCodeProcessor found unknown extrusion role: " << type;
}
if (m_extrusion_role == erExternalPerimeter)
m_seams_detector.activate(true);
return true;
}
// layer
pos = comment.find(" Layer #");
if (pos == 0) {
++m_layer_id;
return true;
}
return false;
}
bool GCodeProcessor::process_ideamaker_tags(const std::string_view comment)
{
// TYPE -> extrusion role
std::string tag = "TYPE:";
size_t pos = comment.find(tag);
if (pos != comment.npos) {
const std::string_view type = comment.substr(pos + tag.length());
if (type == "RAFT")
set_extrusion_role(erSkirt);
else if (type == "WALL-OUTER")
set_extrusion_role(erExternalPerimeter);
else if (type == "WALL-INNER")
set_extrusion_role(erPerimeter);
else if (type == "SOLID-FILL")
set_extrusion_role(erSolidInfill);
else if (type == "FILL")
set_extrusion_role(erInternalInfill);
else if (type == "BRIDGE")
set_extrusion_role(erBridgeInfill);
else if (type == "INTERNAL BRIDGE")
set_extrusion_role(erInternalBridgeInfill);
else if (type == "SUPPORT")
set_extrusion_role(erSupportMaterial);
else {
set_extrusion_role(erNone);
BOOST_LOG_TRIVIAL(warning) << "GCodeProcessor found unknown extrusion role: " << type;
}
if (m_extrusion_role == erExternalPerimeter)
m_seams_detector.activate(true);
return true;
}
// geometry
// width
tag = "WIDTH:";
pos = comment.find(tag);
if (pos != comment.npos) {
if (!parse_number(comment.substr(pos + tag.length()), m_forced_width))
BOOST_LOG_TRIVIAL(error) << "GCodeProcessor encountered an invalid value for Width (" << comment << ").";
return true;
}
// height
tag = "HEIGHT:";
pos = comment.find(tag);
if (pos != comment.npos) {
if (!parse_number(comment.substr(pos + tag.length()), m_forced_height))
BOOST_LOG_TRIVIAL(error) << "GCodeProcessor encountered an invalid value for Height (" << comment << ").";
return true;
}
// layer
pos = comment.find("LAYER:");
if (pos == 0) {
++m_layer_id;
return true;
}
return false;
}
bool GCodeProcessor::process_kissslicer_tags(const std::string_view comment)
{
// extrusion roles
// ; 'Raft Path'
size_t pos = comment.find(" 'Raft Path'");
if (pos == 0) {
set_extrusion_role(erSkirt);
return true;
}
// ; 'Support Interface Path'
pos = comment.find(" 'Support Interface Path'");
if (pos == 0) {
set_extrusion_role(erSupportMaterialInterface);
return true;
}
// ; 'Travel/Ironing Path'
pos = comment.find(" 'Travel/Ironing Path'");
if (pos == 0) {
set_extrusion_role(erIroning);
return true;
}
// ; 'Support (may Stack) Path'
pos = comment.find(" 'Support (may Stack) Path'");
if (pos == 0) {
set_extrusion_role(erSupportMaterial);
return true;
}
// ; 'Perimeter Path'
pos = comment.find(" 'Perimeter Path'");
if (pos == 0) {
set_extrusion_role(erExternalPerimeter);
m_seams_detector.activate(true);
return true;
}
// ; 'Pillar Path'
pos = comment.find(" 'Pillar Path'");
if (pos == 0) {
set_extrusion_role(erNone); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
return true;
}
// ; 'Destring/Wipe/Jump Path'
pos = comment.find(" 'Destring/Wipe/Jump Path'");
if (pos == 0) {
set_extrusion_role(erNone); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
return true;
}
// ; 'Prime Pillar Path'
pos = comment.find(" 'Prime Pillar Path'");
if (pos == 0) {
set_extrusion_role(erNone); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
return true;
}
// ; 'Loop Path'
pos = comment.find(" 'Loop Path'");
if (pos == 0) {
set_extrusion_role(erNone); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
return true;
}
// ; 'Crown Path'
pos = comment.find(" 'Crown Path'");
if (pos == 0) {
set_extrusion_role(erNone); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
return true;
}
// ; 'Solid Path'
pos = comment.find(" 'Solid Path'");
if (pos == 0) {
set_extrusion_role(erNone);
return true;
}
// ; 'Stacked Sparse Infill Path'
pos = comment.find(" 'Stacked Sparse Infill Path'");
if (pos == 0) {
set_extrusion_role(erInternalInfill);
return true;
}
// ; 'Sparse Infill Path'
pos = comment.find(" 'Sparse Infill Path'");
if (pos == 0) {
set_extrusion_role(erSolidInfill);
return true;
}
// geometry
// layer
pos = comment.find(" BEGIN_LAYER_");
if (pos == 0) {
++m_layer_id;
return true;
}
return false;
}
bool GCodeProcessor::detect_producer(const std::string_view comment)
{
for (const auto& [id, search_string] : Producers) {
size_t pos = comment.find(search_string);
if (pos != comment.npos) {
m_producer = id;
//BOOST_LOG_TRIVIAL(info) << "Detected gcode producer: " << search_string;
return true;
}
}
return false;
}
void GCodeProcessor::process_G0(const GCodeReader::GCodeLine& line)
{
process_G1(line);
}
void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line)
{
float filament_diameter = (static_cast<size_t>(m_extruder_id) < m_result.filament_diameters.size()) ? m_result.filament_diameters[m_extruder_id] : m_result.filament_diameters.back();
float filament_radius = 0.5f * filament_diameter;
float area_filament_cross_section = static_cast<float>(M_PI) * sqr(filament_radius);
auto absolute_position = [this, area_filament_cross_section](Axis axis, const GCodeReader::GCodeLine& lineG1) {
bool is_relative = (m_global_positioning_type == EPositioningType::Relative);
if (axis == E)
is_relative |= (m_e_local_positioning_type == EPositioningType::Relative);
if (lineG1.has(Slic3r::Axis(axis))) {
float lengthsScaleFactor = (m_units == EUnits::Inches) ? INCHES_TO_MM : 1.0f;
float ret = lineG1.value(Slic3r::Axis(axis)) * lengthsScaleFactor;
return is_relative ? m_start_position[axis] + ret : m_origin[axis] + ret;
}
else
return m_start_position[axis];
};
auto move_type = [this](const AxisCoords& delta_pos) {
EMoveType type = EMoveType::Noop;
if (m_wiping)
type = EMoveType::Wipe;
else if (delta_pos[E] < 0.0f)
type = (delta_pos[X] != 0.0f || delta_pos[Y] != 0.0f || delta_pos[Z] != 0.0f) ? EMoveType::Travel : EMoveType::Retract;
else if (delta_pos[E] > 0.0f) {
if (delta_pos[X] == 0.0f && delta_pos[Y] == 0.0f)
type = (delta_pos[Z] == 0.0f) ? EMoveType::Unretract : EMoveType::Travel;
else if (delta_pos[X] != 0.0f || delta_pos[Y] != 0.0f)
type = EMoveType::Extrude;
}
else if (delta_pos[X] != 0.0f || delta_pos[Y] != 0.0f || delta_pos[Z] != 0.0f)
type = EMoveType::Travel;
return type;
};
++m_g1_line_id;
// enable processing of lines M201/M203/M204/M205
m_time_processor.machine_envelope_processing_enabled = true;
// updates axes positions from line
for (unsigned char a = X; a <= E; ++a) {
m_end_position[a] = absolute_position((Axis)a, line);
}
// updates feedrate from line, if present
if (line.has_f())
m_feedrate = line.f() * MMMIN_TO_MMSEC;
// calculates movement deltas
float max_abs_delta = 0.0f;
AxisCoords delta_pos;
for (unsigned char a = X; a <= E; ++a) {
delta_pos[a] = m_end_position[a] - m_start_position[a];
max_abs_delta = std::max<float>(max_abs_delta, std::abs(delta_pos[a]));
}
// no displacement, return
if (max_abs_delta == 0.0f)
return;
EMoveType type = move_type(delta_pos);
if (type == EMoveType::Extrude) {
float delta_xyz = std::sqrt(sqr(delta_pos[X]) + sqr(delta_pos[Y]) + sqr(delta_pos[Z]));
float volume_extruded_filament = area_filament_cross_section * delta_pos[E];
float area_toolpath_cross_section = volume_extruded_filament / delta_xyz;
if(m_extrusion_role == ExtrusionRole::erSupportMaterial || m_extrusion_role == ExtrusionRole::erSupportMaterialInterface || m_extrusion_role ==ExtrusionRole::erSupportTransition)
m_used_filaments.increase_support_caches(volume_extruded_filament);
else if (m_extrusion_role==ExtrusionRole::erWipeTower) {
m_used_filaments.increase_wipe_tower_caches(volume_extruded_filament);
}
else {
// save extruded volume to the cache
m_used_filaments.increase_model_caches(volume_extruded_filament);
}
// volume extruded filament / tool displacement = area toolpath cross section
m_mm3_per_mm = area_toolpath_cross_section;
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
m_mm3_per_mm_compare.update(area_toolpath_cross_section, m_extrusion_role);
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
if (m_forced_height > 0.0f)
m_height = m_forced_height;
else {
if (m_end_position[Z] > m_extruded_last_z + EPSILON)
m_height = m_end_position[Z] - m_extruded_last_z;
}
if (m_height == 0.0f)
m_height = DEFAULT_TOOLPATH_HEIGHT;
if (m_end_position[Z] == 0.0f)
m_end_position[Z] = m_height;
m_extruded_last_z = m_end_position[Z];
m_options_z_corrector.update(m_height);
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
m_height_compare.update(m_height, m_extrusion_role);
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
if (m_forced_width > 0.0f)
m_width = m_forced_width;
else if (m_extrusion_role == erExternalPerimeter)
// cross section: rectangle
m_width = delta_pos[E] * static_cast<float>(M_PI * sqr(1.05f * filament_radius)) / (delta_xyz * m_height);
else if (m_extrusion_role == erBridgeInfill || m_extrusion_role == erInternalBridgeInfill || m_extrusion_role == erNone)
// cross section: circle
m_width = static_cast<float>(m_result.filament_diameters[m_extruder_id]) * std::sqrt(delta_pos[E] / delta_xyz);
else
// cross section: rectangle + 2 semicircles
m_width = delta_pos[E] * static_cast<float>(M_PI * sqr(filament_radius)) / (delta_xyz * m_height) + static_cast<float>(1.0 - 0.25 * M_PI) * m_height;
if (m_width == 0.0f)
m_width = DEFAULT_TOOLPATH_WIDTH;
// clamp width to avoid artifacts which may arise from wrong values of m_height
m_width = std::min(m_width, std::max(2.0f, 4.0f * m_height));
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
m_width_compare.update(m_width, m_extrusion_role);
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
}
else if (type == EMoveType::Unretract && m_flushing) {
float volume_flushed_filament = area_filament_cross_section * delta_pos[E];
if (m_remaining_volume > volume_flushed_filament)
{
m_used_filaments.update_flush_per_filament(m_last_extruder_id, volume_flushed_filament);
m_remaining_volume -= volume_flushed_filament;
}
else {
m_used_filaments.update_flush_per_filament(m_last_extruder_id, m_remaining_volume);
m_used_filaments.update_flush_per_filament(m_extruder_id, volume_flushed_filament - m_remaining_volume);
m_remaining_volume = 0.f;
}
}
// time estimate section
auto move_length = [](const AxisCoords& delta_pos) {
float sq_xyz_length = sqr(delta_pos[X]) + sqr(delta_pos[Y]) + sqr(delta_pos[Z]);
return (sq_xyz_length > 0.0f) ? std::sqrt(sq_xyz_length) : std::abs(delta_pos[E]);
};
auto is_extrusion_only_move = [](const AxisCoords& delta_pos) {
return delta_pos[X] == 0.0f && delta_pos[Y] == 0.0f && delta_pos[Z] == 0.0f && delta_pos[E] != 0.0f;
};
float distance = move_length(delta_pos);
assert(distance != 0.0f);
float inv_distance = 1.0f / distance;
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
TimeMachine& machine = m_time_processor.machines[i];
if (!machine.enabled)
continue;
TimeMachine::State& curr = machine.curr;
TimeMachine::State& prev = machine.prev;
std::vector<TimeBlock>& blocks = machine.blocks;
curr.feedrate = (delta_pos[E] == 0.0f) ?
minimum_travel_feedrate(static_cast<PrintEstimatedStatistics::ETimeMode>(i), m_feedrate) :
minimum_feedrate(static_cast<PrintEstimatedStatistics::ETimeMode>(i), m_feedrate);
//BBS: calculeta enter and exit direction
curr.enter_direction = { static_cast<float>(delta_pos[X]), static_cast<float>(delta_pos[Y]), static_cast<float>(delta_pos[Z]) };
float norm = curr.enter_direction.norm();
if (!is_extrusion_only_move(delta_pos))
curr.enter_direction = curr.enter_direction / norm;
curr.exit_direction = curr.enter_direction;
TimeBlock block;
block.move_type = type;
//BBS: don't calculate travel time into extrusion path, except travel inside start and end gcode.
block.role = (type != EMoveType::Travel || m_extrusion_role == erCustom) ? m_extrusion_role : erNone;
block.distance = distance;
block.g1_line_id = m_g1_line_id;
block.layer_id = std::max<unsigned int>(1, m_layer_id);
block.flags.prepare_stage = m_processing_start_custom_gcode;
//BBS: limite the cruise according to centripetal acceleration
//Only need to handle when both prev and curr segment has movement in x-y plane
if ((prev.exit_direction(0) != 0.0f || prev.exit_direction(1) != 0.0f) &&
(curr.enter_direction(0) != 0.0f || curr.enter_direction(1) != 0.0f)) {
Vec3f v1 = prev.exit_direction;
v1(2, 0) = 0.0f;
v1.normalize();
Vec3f v2 = curr.enter_direction;
v2(2, 0) = 0.0f;
v2.normalize();
float norm_diff = (v2 - v1).norm();
//BBS: don't need to consider limitation of centripetal acceleration
//when angle changing is larger than 28.96 degree or two lines are almost collinear.
//Attention!!! these two value must be same with MC side.
if (norm_diff < 0.5f && norm_diff > 0.00001f) {
//BBS: calculate angle
float dot = v1(0) * v2(0) + v1(1) * v2(1);
float cross = v1(0) * v2(1) - v1(1) * v2(0);
float angle = float(atan2(double(cross), double(dot)));
float sin_theta_2 = sqrt((1.0f - cos(angle)) * 0.5f);
float r = sqrt(sqr(delta_pos[X]) + sqr(delta_pos[Y])) * 0.5 / sin_theta_2;
float acc = get_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i));
curr.feedrate = std::min(curr.feedrate, sqrt(acc * r));
}
}
// calculates block cruise feedrate
float min_feedrate_factor = 1.0f;
for (unsigned char a = X; a <= E; ++a) {
curr.axis_feedrate[a] = curr.feedrate * delta_pos[a] * inv_distance;
if (a == E)
curr.axis_feedrate[a] *= machine.extrude_factor_override_percentage;
curr.abs_axis_feedrate[a] = std::abs(curr.axis_feedrate[a]);
if (curr.abs_axis_feedrate[a] != 0.0f) {
float axis_max_feedrate = get_axis_max_feedrate(static_cast<PrintEstimatedStatistics::ETimeMode>(i), static_cast<Axis>(a));
if (axis_max_feedrate != 0.0f) min_feedrate_factor = std::min<float>(min_feedrate_factor, axis_max_feedrate / curr.abs_axis_feedrate[a]);
}
}
//BBS: update curr.feedrate
curr.feedrate *= min_feedrate_factor;
block.feedrate_profile.cruise = curr.feedrate;
if (min_feedrate_factor < 1.0f) {
for (unsigned char a = X; a <= E; ++a) {
curr.axis_feedrate[a] *= min_feedrate_factor;
curr.abs_axis_feedrate[a] *= min_feedrate_factor;
}
}
// calculates block acceleration
float acceleration =
(type == EMoveType::Travel) ? get_travel_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i)) :
(is_extrusion_only_move(delta_pos) ?
get_retract_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i)) :
get_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i)));
//BBS
for (unsigned char a = X; a <= E; ++a) {
float axis_max_acceleration = get_axis_max_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i), static_cast<Axis>(a));
if (acceleration * std::abs(delta_pos[a]) * inv_distance > axis_max_acceleration)
acceleration = axis_max_acceleration / (std::abs(delta_pos[a]) * inv_distance);
}
block.acceleration = acceleration;
// calculates block exit feedrate
curr.safe_feedrate = block.feedrate_profile.cruise;
for (unsigned char a = X; a <= E; ++a) {
float axis_max_jerk = get_axis_max_jerk(static_cast<PrintEstimatedStatistics::ETimeMode>(i), static_cast<Axis>(a));
if (curr.abs_axis_feedrate[a] > axis_max_jerk)
curr.safe_feedrate = std::min(curr.safe_feedrate, axis_max_jerk);
}
block.feedrate_profile.exit = curr.safe_feedrate;
static const float PREVIOUS_FEEDRATE_THRESHOLD = 0.0001f;
// calculates block entry feedrate
float vmax_junction = curr.safe_feedrate;
if (!blocks.empty() && prev.feedrate > PREVIOUS_FEEDRATE_THRESHOLD) {
bool prev_speed_larger = prev.feedrate > block.feedrate_profile.cruise;
float smaller_speed_factor = prev_speed_larger ? (block.feedrate_profile.cruise / prev.feedrate) : (prev.feedrate / block.feedrate_profile.cruise);
// Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
vmax_junction = prev_speed_larger ? block.feedrate_profile.cruise : prev.feedrate;
float v_factor = 1.0f;
bool limited = false;
for (unsigned char a = X; a <= E; ++a) {
// Limit an axis. We have to differentiate coasting from the reversal of an axis movement, or a full stop.
if (a == X) {
Vec3f exit_v = prev.feedrate * (prev.exit_direction);
if (prev_speed_larger)
exit_v *= smaller_speed_factor;
Vec3f entry_v = block.feedrate_profile.cruise * (curr.enter_direction);
Vec3f jerk_v = entry_v - exit_v;
jerk_v = Vec3f(abs(jerk_v.x()), abs(jerk_v.y()), abs(jerk_v.z()));
Vec3f max_xyz_jerk_v = get_xyz_max_jerk(static_cast<PrintEstimatedStatistics::ETimeMode>(i));
for (size_t i = 0; i < 3; i++)
{
if (jerk_v[i] > max_xyz_jerk_v[i]) {
v_factor *= max_xyz_jerk_v[i] / jerk_v[i];
jerk_v *= v_factor;
limited = true;
}
}
}
else if (a == Y || a == Z) {
continue;
}
else {
float v_exit = prev.axis_feedrate[a];
float v_entry = curr.axis_feedrate[a];
if (prev_speed_larger)
v_exit *= smaller_speed_factor;
if (limited) {
v_exit *= v_factor;
v_entry *= v_factor;
}
// Calculate the jerk depending on whether the axis is coasting in the same direction or reversing a direction.
float jerk =
(v_exit > v_entry) ?
(((v_entry > 0.0f) || (v_exit < 0.0f)) ?
// coasting
(v_exit - v_entry) :
// axis reversal
std::max(v_exit, -v_entry)) :
// v_exit <= v_entry
(((v_entry < 0.0f) || (v_exit > 0.0f)) ?
// coasting
(v_entry - v_exit) :
// axis reversal
std::max(-v_exit, v_entry));
float axis_max_jerk = get_axis_max_jerk(static_cast<PrintEstimatedStatistics::ETimeMode>(i), static_cast<Axis>(a));
if (jerk > axis_max_jerk) {
v_factor *= axis_max_jerk / jerk;
limited = true;
}
}
}
if (limited)
vmax_junction *= v_factor;
// Now the transition velocity is known, which maximizes the shared exit / entry velocity while
// respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
float vmax_junction_threshold = vmax_junction * 0.99f;
// Not coasting. The machine will stop and start the movements anyway, better to start the segment from start.
if (prev.safe_feedrate > vmax_junction_threshold && curr.safe_feedrate > vmax_junction_threshold)
vmax_junction = curr.safe_feedrate;
}
float v_allowable = max_allowable_speed(-acceleration, curr.safe_feedrate, block.distance);
block.feedrate_profile.entry = std::min(vmax_junction, v_allowable);
block.max_entry_speed = vmax_junction;
block.flags.nominal_length = (block.feedrate_profile.cruise <= v_allowable);
block.flags.recalculate = true;
block.safe_feedrate = curr.safe_feedrate;
// calculates block trapezoid
block.calculate_trapezoid();
// updates previous
prev = curr;
blocks.push_back(block);
if (blocks.size() > TimeProcessor::Planner::refresh_threshold)
machine.calculate_time(TimeProcessor::Planner::queue_size);
}
const Vec3f plate_offset = {(float) m_x_offset, (float) m_y_offset, 0.0f};
if (m_seams_detector.is_active()) {
// check for seam starting vertex
if (type == EMoveType::Extrude && m_extrusion_role == erExternalPerimeter) {
//BBS: m_result.moves.back().position has plate offset, must minus plate offset before calculate the real seam position
const Vec3f new_pos = m_result.moves.back().position - m_extruder_offsets[m_extruder_id] - plate_offset;
if (!m_seams_detector.has_first_vertex()) {
m_seams_detector.set_first_vertex(new_pos);
} else if (m_detect_layer_based_on_tag) {
// We may have sloped loop, drop any previous start pos if we have z increment
const std::optional<Vec3f> first_vertex = m_seams_detector.get_first_vertex();
if (new_pos.z() > first_vertex->z()) {
m_seams_detector.set_first_vertex(new_pos);
}
}
}
// check for seam ending vertex and store the resulting move
else if ((type != EMoveType::Extrude || (m_extrusion_role != erExternalPerimeter && m_extrusion_role != erOverhangPerimeter)) && m_seams_detector.has_first_vertex()) {
auto set_end_position = [this](const Vec3f& pos) {
m_end_position[X] = pos.x(); m_end_position[Y] = pos.y(); m_end_position[Z] = pos.z();
};
const Vec3f curr_pos(m_end_position[X], m_end_position[Y], m_end_position[Z]);
//BBS: m_result.moves.back().position has plate offset, must minus plate offset before calculate the real seam position
const Vec3f new_pos = m_result.moves.back().position - m_extruder_offsets[m_extruder_id] - plate_offset;
const std::optional<Vec3f> first_vertex = m_seams_detector.get_first_vertex();
// the threshold value = 0.0625f == 0.25 * 0.25 is arbitrary, we may find some smarter condition later
if ((new_pos - *first_vertex).squaredNorm() < 0.0625f) {
set_end_position(0.5f * (new_pos + *first_vertex) + m_z_offset * Vec3f::UnitZ());
store_move_vertex(EMoveType::Seam);
set_end_position(curr_pos);
}
m_seams_detector.activate(false);
}
}
else if (type == EMoveType::Extrude && m_extrusion_role == erExternalPerimeter) {
m_seams_detector.activate(true);
m_seams_detector.set_first_vertex(m_result.moves.back().position - m_extruder_offsets[m_extruder_id] - plate_offset);
}
if (m_detect_layer_based_on_tag && !m_result.spiral_vase_layers.empty()) {
if (delta_pos[Z] >= 0.0 && type == EMoveType::Extrude) {
const float current_z = static_cast<float>(m_end_position[Z]);
// replace layer height placeholder with correct value
if (m_result.spiral_vase_layers.back().first == FLT_MAX) {
m_result.spiral_vase_layers.back().first = current_z;
} else {
m_result.spiral_vase_layers.back().first = std::max(m_result.spiral_vase_layers.back().first, current_z);
}
}
if (!m_result.moves.empty())
m_result.spiral_vase_layers.back().second.second = m_result.moves.size() - 1 - m_seams_count;
}
// store move
store_move_vertex(type);
}
// BBS: this function is absolutely new for G2 and G3 gcode
void GCodeProcessor::process_G2_G3(const GCodeReader::GCodeLine& line)
{
float filament_diameter = (static_cast<size_t>(m_extruder_id) < m_result.filament_diameters.size()) ? m_result.filament_diameters[m_extruder_id] : m_result.filament_diameters.back();
float filament_radius = 0.5f * filament_diameter;
float area_filament_cross_section = static_cast<float>(M_PI) * sqr(filament_radius);
auto absolute_position = [this, area_filament_cross_section](Axis axis, const GCodeReader::GCodeLine& lineG2_3) {
bool is_relative = (m_global_positioning_type == EPositioningType::Relative);
if (axis == E)
is_relative |= (m_e_local_positioning_type == EPositioningType::Relative);
if (lineG2_3.has(Slic3r::Axis(axis))) {
float lengthsScaleFactor = (m_units == EUnits::Inches) ? INCHES_TO_MM : 1.0f;
float ret = lineG2_3.value(Slic3r::Axis(axis)) * lengthsScaleFactor;
if (axis == I)
return m_start_position[X] + ret;
else if (axis == J)
return m_start_position[Y] + ret;
else
return is_relative ? m_start_position[axis] + ret : m_origin[axis] + ret;
}
else {
if (axis == I)
return m_start_position[X];
else if (axis == J)
return m_start_position[Y];
else
return m_start_position[axis];
}
};
auto move_type = [this](const float& delta_E) {
if (delta_E == 0.0f)
return EMoveType::Travel;
else
return EMoveType::Extrude;
};
auto arc_interpolation = [this](const Vec3f& start_pos, const Vec3f& end_pos, const Vec3f& center_pos, const bool is_ccw) {
float radius = ArcSegment::calc_arc_radius(start_pos, center_pos);
//BBS: radius is too small to draw
if (radius <= DRAW_ARC_TOLERANCE) {
m_interpolation_points.resize(0);
return;
}
float radian_step = 2 * acos((radius - DRAW_ARC_TOLERANCE) / radius);
float num = ArcSegment::calc_arc_radian(start_pos, end_pos, center_pos, is_ccw) / radian_step;
float z_step = (num < 1)? end_pos.z() - start_pos.z() : (end_pos.z() - start_pos.z()) / num;
radian_step = is_ccw ? radian_step : -radian_step;
int interpolation_num = floor(num);
m_interpolation_points.resize(interpolation_num, Vec3f::Zero());
Vec3f delta = start_pos - center_pos;
for (auto i = 0; i < interpolation_num; i++) {
float cos_val = cos((i+1) * radian_step);
float sin_val = sin((i+1) * radian_step);
m_interpolation_points[i] = Vec3f(center_pos.x() + delta.x() * cos_val - delta.y() * sin_val,
center_pos.y() + delta.x() * sin_val + delta.y() * cos_val,
start_pos.z() + (i + 1) * z_step);
}
};
++m_g1_line_id;
//BBS: enable processing of lines M201/M203/M204/M205
m_time_processor.machine_envelope_processing_enabled = true;
//BBS: get axes positions from line
for (unsigned char a = X; a <= E; ++a) {
m_end_position[a] = absolute_position((Axis)a, line);
}
//BBS: G2 G3 line but has no I and J axis, invalid G code format
if (!line.has(I) && !line.has(J))
return;
//BBS: P mode, but xy position is not same, or P is not 1, invalid G code format
if (line.has(P) &&
(m_start_position[X] != m_end_position[X] ||
m_start_position[Y] != m_end_position[Y] ||
((int)line.p()) != 1))
return;
m_arc_center = Vec3f(absolute_position(I, line),absolute_position(J, line),m_start_position[Z]);
//BBS: G2 is CW direction, G3 is CCW direction
const std::string_view cmd = line.cmd();
m_move_path_type = (::atoi(&cmd[1]) == 2) ? EMovePathType::Arc_move_cw : EMovePathType::Arc_move_ccw;
//BBS: get arc length,interpolation points and radian in X-Y plane
Vec3f start_point = Vec3f(m_start_position[X], m_start_position[Y], m_start_position[Z]);
Vec3f end_point = Vec3f(m_end_position[X], m_end_position[Y], m_end_position[Z]);
float arc_length;
if (!line.has(P))
arc_length = ArcSegment::calc_arc_length(start_point, end_point, m_arc_center, (m_move_path_type == EMovePathType::Arc_move_ccw));
else
arc_length = ((int)line.p()) * 2 * PI * (start_point - m_arc_center).norm();
//BBS: Attention! arc_onterpolation does not support P mode while P is not 1.
arc_interpolation(start_point, end_point, m_arc_center, (m_move_path_type == EMovePathType::Arc_move_ccw));
float radian = ArcSegment::calc_arc_radian(start_point, end_point, m_arc_center, (m_move_path_type == EMovePathType::Arc_move_ccw));
Vec3f start_dir = Circle::calc_tangential_vector(start_point, m_arc_center, (m_move_path_type == EMovePathType::Arc_move_ccw));
Vec3f end_dir = Circle::calc_tangential_vector(end_point, m_arc_center, (m_move_path_type == EMovePathType::Arc_move_ccw));
//BBS: updates feedrate from line, if present
if (line.has_f())
m_feedrate = line.f() * MMMIN_TO_MMSEC;
//BBS: calculates movement deltas
AxisCoords delta_pos;
for (unsigned char a = X; a <= E; ++a) {
delta_pos[a] = m_end_position[a] - m_start_position[a];
}
//BBS: no displacement, return
if (arc_length == 0.0f && delta_pos[Z] == 0.0f)
return;
EMoveType type = move_type(delta_pos[E]);
float delta_xyz = std::sqrt(sqr(arc_length) + sqr(delta_pos[Z]));
if (type == EMoveType::Extrude) {
float volume_extruded_filament = area_filament_cross_section * delta_pos[E];
float area_toolpath_cross_section = volume_extruded_filament / delta_xyz;
if(m_extrusion_role == ExtrusionRole::erSupportMaterial || m_extrusion_role == ExtrusionRole::erSupportMaterialInterface || m_extrusion_role ==ExtrusionRole::erSupportTransition)
m_used_filaments.increase_support_caches(volume_extruded_filament);
else if (m_extrusion_role == ExtrusionRole::erWipeTower) {
//BBS: save wipe tower volume to the cache
m_used_filaments.increase_wipe_tower_caches(volume_extruded_filament);
}
else {
//BBS: save extruded volume to the cache
m_used_filaments.increase_model_caches(volume_extruded_filament);
}
//BBS: volume extruded filament / tool displacement = area toolpath cross section
m_mm3_per_mm = area_toolpath_cross_section;
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
m_mm3_per_mm_compare.update(area_toolpath_cross_section, m_extrusion_role);
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
if (m_forced_height > 0.0f)
m_height = m_forced_height;
else {
if (m_end_position[Z] > m_extruded_last_z + EPSILON)
m_height = m_end_position[Z] - m_extruded_last_z;
}
if (m_height == 0.0f)
m_height = DEFAULT_TOOLPATH_HEIGHT;
if (m_end_position[Z] == 0.0f)
m_end_position[Z] = m_height;
m_extruded_last_z = m_end_position[Z];
m_options_z_corrector.update(m_height);
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
m_height_compare.update(m_height, m_extrusion_role);
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
if (m_forced_width > 0.0f)
m_width = m_forced_width;
else if (m_extrusion_role == erExternalPerimeter)
//BBS: cross section: rectangle
m_width = delta_pos[E] * static_cast<float>(M_PI * sqr(1.05f * filament_radius)) / (delta_xyz * m_height);
else if (m_extrusion_role == erBridgeInfill || m_extrusion_role == erInternalBridgeInfill || m_extrusion_role == erNone)
//BBS: cross section: circle
m_width = static_cast<float>(m_result.filament_diameters[m_extruder_id]) * std::sqrt(delta_pos[E] / delta_xyz);
else
//BBS: cross section: rectangle + 2 semicircles
m_width = delta_pos[E] * static_cast<float>(M_PI * sqr(filament_radius)) / (delta_xyz * m_height) + static_cast<float>(1.0 - 0.25 * M_PI) * m_height;
if (m_width == 0.0f)
m_width = DEFAULT_TOOLPATH_WIDTH;
//BBS: clamp width to avoid artifacts which may arise from wrong values of m_height
m_width = std::min(m_width, std::max(2.0f, 4.0f * m_height));
#if ENABLE_GCODE_VIEWER_DATA_CHECKING
m_width_compare.update(m_width, m_extrusion_role);
#endif // ENABLE_GCODE_VIEWER_DATA_CHECKING
}
//BBS: time estimate section
assert(delta_xyz != 0.0f);
float inv_distance = 1.0f / delta_xyz;
float radius = ArcSegment::calc_arc_radius(start_point, m_arc_center);
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
TimeMachine& machine = m_time_processor.machines[i];
if (!machine.enabled)
continue;
TimeMachine::State& curr = machine.curr;
TimeMachine::State& prev = machine.prev;
std::vector<TimeBlock>& blocks = machine.blocks;
curr.feedrate = (type == EMoveType::Travel) ?
minimum_travel_feedrate(static_cast<PrintEstimatedStatistics::ETimeMode>(i), m_feedrate) :
minimum_feedrate(static_cast<PrintEstimatedStatistics::ETimeMode>(i), m_feedrate);
//BBS: calculeta enter and exit direction
curr.enter_direction = start_dir;
curr.exit_direction = end_dir;
TimeBlock block;
block.move_type = type;
//BBS: don't calculate travel time into extrusion path, except travel inside start and end gcode.
block.role = (type != EMoveType::Travel || m_extrusion_role == erCustom) ? m_extrusion_role : erNone;
block.distance = delta_xyz;
block.g1_line_id = m_g1_line_id;
block.layer_id = std::max<unsigned int>(1, m_layer_id);
block.flags.prepare_stage = m_processing_start_custom_gcode;
// BBS: calculates block cruise feedrate
// For arc move, we need to limite the cruise according to centripetal acceleration which is
// same with acceleration in x-y plane. Because arc move part is only on x-y plane, we use x-y acceleration directly
float centripetal_acceleration = get_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i));
float max_feedrate_by_centri_acc = sqrtf(centripetal_acceleration * radius) / (arc_length * inv_distance);
curr.feedrate = std::min(curr.feedrate, max_feedrate_by_centri_acc);
float min_feedrate_factor = 1.0f;
for (unsigned char a = X; a <= E; ++a) {
if (a == X || a == Y)
//BBS: use resultant feedrate in x-y plane
curr.axis_feedrate[a] = curr.feedrate * arc_length * inv_distance;
else if (a == Z)
curr.axis_feedrate[a] = curr.feedrate * delta_pos[a] * inv_distance;
else
curr.axis_feedrate[a] *= machine.extrude_factor_override_percentage;
curr.abs_axis_feedrate[a] = std::abs(curr.axis_feedrate[a]);
if (curr.abs_axis_feedrate[a] != 0.0f) {
float axis_max_feedrate = get_axis_max_feedrate(static_cast<PrintEstimatedStatistics::ETimeMode>(i), static_cast<Axis>(a));
if (axis_max_feedrate != 0.0f) min_feedrate_factor = std::min<float>(min_feedrate_factor, axis_max_feedrate / curr.abs_axis_feedrate[a]);
}
}
curr.feedrate *= min_feedrate_factor;
block.feedrate_profile.cruise = curr.feedrate;
if (min_feedrate_factor < 1.0f) {
for (unsigned char a = X; a <= E; ++a) {
curr.axis_feedrate[a] *= min_feedrate_factor;
curr.abs_axis_feedrate[a] *= min_feedrate_factor;
}
}
//BBS: calculates block acceleration
float acceleration = (type == EMoveType::Travel) ?
get_travel_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i)) :
get_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i));
float min_acc_factor = 1.0f;
AxisCoords axis_acc;
for (unsigned char a = X; a <= Z; ++a) {
if (a == X || a == Y)
//BBS: use resultant feedrate in x-y plane
axis_acc[a] = acceleration * arc_length * inv_distance;
else
axis_acc[a] = acceleration * std::abs(delta_pos[a]) * inv_distance;
if (axis_acc[a] != 0.0f) {
float axis_max_acceleration = get_axis_max_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i), static_cast<Axis>(a));
if (axis_max_acceleration != 0.0f && axis_acc[a] > axis_max_acceleration) min_acc_factor = std::min<float>(min_acc_factor, axis_max_acceleration / axis_acc[a]);
}
}
block.acceleration = acceleration * min_acc_factor;
//BBS: calculates block exit feedrate
for (unsigned char a = X; a <= E; ++a) {
float axis_max_jerk = get_axis_max_jerk(static_cast<PrintEstimatedStatistics::ETimeMode>(i), static_cast<Axis>(a));
if (curr.abs_axis_feedrate[a] > axis_max_jerk)
curr.safe_feedrate = std::min(curr.safe_feedrate, axis_max_jerk);
}
block.feedrate_profile.exit = curr.safe_feedrate;
//BBS: calculates block entry feedrate
static const float PREVIOUS_FEEDRATE_THRESHOLD = 0.0001f;
float vmax_junction = curr.safe_feedrate;
if (!blocks.empty() && prev.feedrate > PREVIOUS_FEEDRATE_THRESHOLD) {
bool prev_speed_larger = prev.feedrate > block.feedrate_profile.cruise;
float smaller_speed_factor = prev_speed_larger ? (block.feedrate_profile.cruise / prev.feedrate) : (prev.feedrate / block.feedrate_profile.cruise);
//BBS: Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
vmax_junction = prev_speed_larger ? block.feedrate_profile.cruise : prev.feedrate;
float v_factor = 1.0f;
bool limited = false;
for (unsigned char a = X; a <= E; ++a) {
//BBS: Limit an axis. We have to differentiate coasting from the reversal of an axis movement, or a full stop.
if (a == X) {
Vec3f exit_v = prev.feedrate * (prev.exit_direction);
if (prev_speed_larger)
exit_v *= smaller_speed_factor;
Vec3f entry_v = block.feedrate_profile.cruise * (curr.enter_direction);
Vec3f jerk_v = entry_v - exit_v;
jerk_v = Vec3f(abs(jerk_v.x()), abs(jerk_v.y()), abs(jerk_v.z()));
Vec3f max_xyz_jerk_v = get_xyz_max_jerk(static_cast<PrintEstimatedStatistics::ETimeMode>(i));
for (size_t i = 0; i < 3; i++)
{
if (jerk_v[i] > max_xyz_jerk_v[i]) {
v_factor *= max_xyz_jerk_v[i] / jerk_v[i];
jerk_v *= v_factor;
limited = true;
}
}
}
else if (a == Y || a == Z) {
continue;
}
else {
float v_exit = prev.axis_feedrate[a];
float v_entry = curr.axis_feedrate[a];
if (prev_speed_larger)
v_exit *= smaller_speed_factor;
if (limited) {
v_exit *= v_factor;
v_entry *= v_factor;
}
//BBS: Calculate the jerk depending on whether the axis is coasting in the same direction or reversing a direction.
float jerk =
(v_exit > v_entry) ?
(((v_entry > 0.0f) || (v_exit < 0.0f)) ?
//BBS: coasting
(v_exit - v_entry) :
//BBS: axis reversal
std::max(v_exit, -v_entry)) :
(((v_entry < 0.0f) || (v_exit > 0.0f)) ?
//BBS: coasting
(v_entry - v_exit) :
//BBS: axis reversal
std::max(-v_exit, v_entry));
float axis_max_jerk = get_axis_max_jerk(static_cast<PrintEstimatedStatistics::ETimeMode>(i), static_cast<Axis>(a));
if (jerk > axis_max_jerk) {
v_factor *= axis_max_jerk / jerk;
limited = true;
}
}
}
if (limited)
vmax_junction *= v_factor;
//BBS: Now the transition velocity is known, which maximizes the shared exit / entry velocity while
// respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
float vmax_junction_threshold = vmax_junction * 0.99f;
//BBS: Not coasting. The machine will stop and start the movements anyway, better to start the segment from start.
if ((prev.safe_feedrate > vmax_junction_threshold) && (curr.safe_feedrate > vmax_junction_threshold))
vmax_junction = curr.safe_feedrate;
}
float v_allowable = max_allowable_speed(-acceleration, curr.safe_feedrate, block.distance);
block.feedrate_profile.entry = std::min(vmax_junction, v_allowable);
block.max_entry_speed = vmax_junction;
block.flags.nominal_length = (block.feedrate_profile.cruise <= v_allowable);
block.flags.recalculate = true;
block.safe_feedrate = curr.safe_feedrate;
//BBS: calculates block trapezoid
block.calculate_trapezoid();
//BBS: updates previous
prev = curr;
blocks.push_back(block);
if (blocks.size() > TimeProcessor::Planner::refresh_threshold)
machine.calculate_time(TimeProcessor::Planner::queue_size);
}
//BBS: seam detector
Vec3f plate_offset = {(float) m_x_offset, (float) m_y_offset, 0.0f};
if (m_seams_detector.is_active()) {
//BBS: check for seam starting vertex
if (type == EMoveType::Extrude && m_extrusion_role == erExternalPerimeter) {
const Vec3f new_pos = m_result.moves.back().position - m_extruder_offsets[m_extruder_id] - plate_offset;
if (!m_seams_detector.has_first_vertex()) {
m_seams_detector.set_first_vertex(new_pos);
} else if (m_detect_layer_based_on_tag) {
// We may have sloped loop, drop any previous start pos if we have z increment
const std::optional<Vec3f> first_vertex = m_seams_detector.get_first_vertex();
if (new_pos.z() > first_vertex->z()) {
m_seams_detector.set_first_vertex(new_pos);
}
}
}
//BBS: check for seam ending vertex and store the resulting move
else if ((type != EMoveType::Extrude || (m_extrusion_role != erExternalPerimeter && m_extrusion_role != erOverhangPerimeter)) && m_seams_detector.has_first_vertex()) {
auto set_end_position = [this](const Vec3f& pos) {
m_end_position[X] = pos.x(); m_end_position[Y] = pos.y(); m_end_position[Z] = pos.z();
};
const Vec3f curr_pos(m_end_position[X], m_end_position[Y], m_end_position[Z]);
const Vec3f new_pos = m_result.moves.back().position - m_extruder_offsets[m_extruder_id] - plate_offset;
const std::optional<Vec3f> first_vertex = m_seams_detector.get_first_vertex();
//BBS: the threshold value = 0.0625f == 0.25 * 0.25 is arbitrary, we may find some smarter condition later
if ((new_pos - *first_vertex).squaredNorm() < 0.0625f) {
set_end_position(0.5f * (new_pos + *first_vertex));
store_move_vertex(EMoveType::Seam);
set_end_position(curr_pos);
}
m_seams_detector.activate(false);
}
}
else if (type == EMoveType::Extrude && m_extrusion_role == erExternalPerimeter) {
m_seams_detector.activate(true);
m_seams_detector.set_first_vertex(m_result.moves.back().position - m_extruder_offsets[m_extruder_id] - plate_offset);
}
// Orca: we now use spiral_vase_layers for proper layer detect when scarf joint is enabled,
// and this is needed if the layer has only arc moves
if (m_detect_layer_based_on_tag && !m_result.spiral_vase_layers.empty()) {
if (delta_pos[Z] >= 0.0 && type == EMoveType::Extrude) {
const float current_z = static_cast<float>(m_end_position[Z]);
// replace layer height placeholder with correct value
if (m_result.spiral_vase_layers.back().first == FLT_MAX) {
m_result.spiral_vase_layers.back().first = current_z;
} else {
m_result.spiral_vase_layers.back().first = std::max(m_result.spiral_vase_layers.back().first, current_z);
}
}
if (!m_result.moves.empty())
m_result.spiral_vase_layers.back().second.second = m_result.moves.size() - 1 - m_seams_count;
}
//BBS: store move
store_move_vertex(type, m_move_path_type);
}
//BBS
void GCodeProcessor::process_G4(const GCodeReader::GCodeLine& line)
{
float value_s = 0.0;
float value_p = 0.0;
if (line.has_value('S', value_s) || line.has_value('P', value_p)) {
value_s += value_p * 0.001;
simulate_st_synchronize(value_s);
}
}
//BBS
void GCodeProcessor::process_G29(const GCodeReader::GCodeLine& line)
{
//BBS: hardcode 260 seconds for G29
//Todo: use a machine related setting when we have second kind of BBL printer
const float value_s = 260.0;
simulate_st_synchronize(value_s);
}
void GCodeProcessor::process_G10(const GCodeReader::GCodeLine& line)
{
// stores retract move
store_move_vertex(EMoveType::Retract);
}
void GCodeProcessor::process_G11(const GCodeReader::GCodeLine& line)
{
// stores unretract move
store_move_vertex(EMoveType::Unretract);
}
void GCodeProcessor::process_G20(const GCodeReader::GCodeLine& line)
{
m_units = EUnits::Inches;
}
void GCodeProcessor::process_G21(const GCodeReader::GCodeLine& line)
{
m_units = EUnits::Millimeters;
}
void GCodeProcessor::process_G22(const GCodeReader::GCodeLine& line)
{
// stores retract move
store_move_vertex(EMoveType::Retract);
}
void GCodeProcessor::process_G23(const GCodeReader::GCodeLine& line)
{
// stores unretract move
store_move_vertex(EMoveType::Unretract);
}
void GCodeProcessor::process_G28(const GCodeReader::GCodeLine& line)
{
std::string_view cmd = line.cmd();
std::string new_line_raw = { cmd.data(), cmd.size() };
bool found = false;
if (line.has('X')) {
new_line_raw += " X0";
found = true;
}
if (line.has('Y')) {
new_line_raw += " Y0";
found = true;
}
if (line.has('Z')) {
new_line_raw += " Z0";
found = true;
}
if (!found)
new_line_raw += " X0 Y0 Z0";
GCodeReader::GCodeLine new_gline;
GCodeReader reader;
reader.parse_line(new_line_raw, [&](GCodeReader& reader, const GCodeReader::GCodeLine& gline) { new_gline = gline; });
process_G1(new_gline);
}
void GCodeProcessor::process_G90(const GCodeReader::GCodeLine& line)
{
m_global_positioning_type = EPositioningType::Absolute;
}
void GCodeProcessor::process_G91(const GCodeReader::GCodeLine& line)
{
m_global_positioning_type = EPositioningType::Relative;
}
void GCodeProcessor::process_G92(const GCodeReader::GCodeLine& line)
{
float lengths_scale_factor = (m_units == EUnits::Inches) ? INCHES_TO_MM : 1.0f;
bool any_found = false;
if (line.has_x()) {
m_origin[X] = m_end_position[X] - line.x() * lengths_scale_factor;
any_found = true;
}
if (line.has_y()) {
m_origin[Y] = m_end_position[Y] - line.y() * lengths_scale_factor;
any_found = true;
}
if (line.has_z()) {
m_origin[Z] = m_end_position[Z] - line.z() * lengths_scale_factor;
any_found = true;
}
if (line.has_e()) {
// extruder coordinate can grow to the point where its float representation does not allow for proper addition with small increments,
// we set the value taken from the G92 line as the new current position for it
m_end_position[E] = line.e() * lengths_scale_factor;
any_found = true;
}
else
simulate_st_synchronize();
if (!any_found && !line.has_unknown_axis()) {
// The G92 may be called for axes that PrusaSlicer does not recognize, for example see GH issue #3510,
// where G92 A0 B0 is called although the extruder axis is till E.
for (unsigned char a = X; a <= E; ++a) {
m_origin[a] = m_end_position[a];
}
}
}
void GCodeProcessor::process_M1(const GCodeReader::GCodeLine& line)
{
simulate_st_synchronize();
}
void GCodeProcessor::process_M82(const GCodeReader::GCodeLine& line)
{
m_e_local_positioning_type = EPositioningType::Absolute;
}
void GCodeProcessor::process_M83(const GCodeReader::GCodeLine& line)
{
m_e_local_positioning_type = EPositioningType::Relative;
}
void GCodeProcessor::process_M104(const GCodeReader::GCodeLine& line)
{
float new_temp;
if (line.has_value('S', new_temp))
m_extruder_temps[m_extruder_id] = new_temp;
}
void GCodeProcessor::process_M106(const GCodeReader::GCodeLine& line)
{
//BBS: for Bambu machine ,we both use M106 P1 and M106 to indicate the part cooling fan
//So we must not ignore M106 P1
if (!line.has('P') || (line.has('P') && line.p() == 1.0f)) {
// The absence of P means the print cooling fan, so ignore anything else.
float new_fan_speed;
if (line.has_value('S', new_fan_speed))
m_fan_speed = (100.0f / 255.0f) * new_fan_speed;
else
m_fan_speed = 100.0f;
}
}
void GCodeProcessor::process_M107(const GCodeReader::GCodeLine& line)
{
m_fan_speed = 0.0f;
}
void GCodeProcessor::process_M108(const GCodeReader::GCodeLine& line)
{
// These M-codes are used by Sailfish to change active tool.
// They have to be processed otherwise toolchanges will be unrecognised
if (m_flavor != gcfSailfish)
return;
std::string cmd = line.raw();
size_t pos = cmd.find("T");
if (pos != std::string::npos)
process_T(cmd.substr(pos));
}
void GCodeProcessor::process_M109(const GCodeReader::GCodeLine& line)
{
float new_temp;
if (line.has_value('R', new_temp)) {
float val;
if (line.has_value('T', val)) {
size_t eid = static_cast<size_t>(val);
if (eid < m_extruder_temps.size())
m_extruder_temps[eid] = new_temp;
}
else
m_extruder_temps[m_extruder_id] = new_temp;
}
else if (line.has_value('S', new_temp))
m_extruder_temps[m_extruder_id] = new_temp;
}
void GCodeProcessor::process_M132(const GCodeReader::GCodeLine& line)
{
// This command is used by Makerbot to load the current home position from EEPROM
// see: https://github.com/makerbot/s3g/blob/master/doc/GCodeProtocol.md
if (line.has('X'))
m_origin[X] = 0.0f;
if (line.has('Y'))
m_origin[Y] = 0.0f;
if (line.has('Z'))
m_origin[Z] = 0.0f;
if (line.has('E'))
m_origin[E] = 0.0f;
}
void GCodeProcessor::process_M135(const GCodeReader::GCodeLine& line)
{
// These M-codes are used by MakerWare to change active tool.
// They have to be processed otherwise toolchanges will be unrecognised
if (m_flavor != gcfMakerWare)
return;
std::string cmd = line.raw();
size_t pos = cmd.find("T");
if (pos != std::string::npos)
process_T(cmd.substr(pos));
}
void GCodeProcessor::process_M140(const GCodeReader::GCodeLine& line)
{
float new_temp;
if (line.has_value('S', new_temp))
m_highest_bed_temp = m_highest_bed_temp < (int)new_temp ? (int)new_temp : m_highest_bed_temp;
}
void GCodeProcessor::process_M190(const GCodeReader::GCodeLine& line)
{
float new_temp;
if (line.has_value('S', new_temp))
m_highest_bed_temp = m_highest_bed_temp < (int)new_temp ? (int)new_temp : m_highest_bed_temp;
}
void GCodeProcessor::process_M191(const GCodeReader::GCodeLine& line)
{
float chamber_temp = 0;
const float wait_chamber_temp_time = 720.0;
// BBS: when chamber_temp>40,caculate time required for heating
if (line.has_value('S', chamber_temp) && chamber_temp > 40)
simulate_st_synchronize(wait_chamber_temp_time);
}
void GCodeProcessor::process_M201(const GCodeReader::GCodeLine& line)
{
// see http://reprap.org/wiki/G-code#M201:_Set_max_printing_acceleration
float factor = ((m_flavor != gcfRepRapSprinter && m_flavor != gcfRepRapFirmware) && m_units == EUnits::Inches) ? INCHES_TO_MM : 1.0f;
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
if (static_cast<PrintEstimatedStatistics::ETimeMode>(i) == PrintEstimatedStatistics::ETimeMode::Normal ||
m_time_processor.machine_envelope_processing_enabled) {
if (line.has_x())
set_option_value(m_time_processor.machine_limits.machine_max_acceleration_x, i, line.x() * factor);
if (line.has_y())
set_option_value(m_time_processor.machine_limits.machine_max_acceleration_y, i, line.y() * factor);
if (line.has_z())
set_option_value(m_time_processor.machine_limits.machine_max_acceleration_z, i, line.z() * factor);
if (line.has_e())
set_option_value(m_time_processor.machine_limits.machine_max_acceleration_e, i, line.e() * factor);
}
}
}
void GCodeProcessor::process_M203(const GCodeReader::GCodeLine& line)
{
// see http://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate
if (m_flavor == gcfRepetier)
return;
// see http://reprap.org/wiki/G-code#M203:_Set_maximum_feedrate
// http://smoothieware.org/supported-g-codes
float factor = (m_flavor == gcfMarlinLegacy || m_flavor == gcfMarlinFirmware || m_flavor == gcfSmoothie || m_flavor == gcfKlipper) ? 1.0f : MMMIN_TO_MMSEC;
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
if (static_cast<PrintEstimatedStatistics::ETimeMode>(i) == PrintEstimatedStatistics::ETimeMode::Normal ||
m_time_processor.machine_envelope_processing_enabled) {
if (line.has_x())
set_option_value(m_time_processor.machine_limits.machine_max_speed_x, i, line.x() * factor);
if (line.has_y())
set_option_value(m_time_processor.machine_limits.machine_max_speed_y, i, line.y() * factor);
if (line.has_z())
set_option_value(m_time_processor.machine_limits.machine_max_speed_z, i, line.z() * factor);
if (line.has_e())
set_option_value(m_time_processor.machine_limits.machine_max_speed_e, i, line.e() * factor);
}
}
}
void GCodeProcessor::process_M204(const GCodeReader::GCodeLine& line)
{
float value;
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
if (static_cast<PrintEstimatedStatistics::ETimeMode>(i) == PrintEstimatedStatistics::ETimeMode::Normal ||
m_time_processor.machine_envelope_processing_enabled) {
if (line.has_value('S', value)) {
// Legacy acceleration format. This format is used by the legacy Marlin, MK2 or MK3 firmware
// It is also generated by PrusaSlicer to control acceleration per extrusion type
// (perimeters, first layer etc) when 'Marlin (legacy)' flavor is used.
set_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i), value);
set_travel_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i), value);
if (line.has_value('T', value))
set_retract_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i), value);
}
else {
// New acceleration format, compatible with the upstream Marlin.
if (line.has_value('P', value))
set_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i), value);
if (line.has_value('R', value))
set_retract_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i), value);
if (line.has_value('T', value))
// Interpret the T value as the travel acceleration in the new Marlin format.
set_travel_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i), value);
}
}
}
}
void GCodeProcessor::process_M205(const GCodeReader::GCodeLine& line)
{
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
if (static_cast<PrintEstimatedStatistics::ETimeMode>(i) == PrintEstimatedStatistics::ETimeMode::Normal ||
m_time_processor.machine_envelope_processing_enabled) {
if (line.has_x()) {
float max_jerk = line.x();
set_option_value(m_time_processor.machine_limits.machine_max_jerk_x, i, max_jerk);
set_option_value(m_time_processor.machine_limits.machine_max_jerk_y, i, max_jerk);
}
if (line.has_y())
set_option_value(m_time_processor.machine_limits.machine_max_jerk_y, i, line.y());
if (line.has_z())
set_option_value(m_time_processor.machine_limits.machine_max_jerk_z, i, line.z());
if (line.has_e())
set_option_value(m_time_processor.machine_limits.machine_max_jerk_e, i, line.e());
float value;
if (line.has_value('S', value))
set_option_value(m_time_processor.machine_limits.machine_min_extruding_rate, i, value);
if (line.has_value('T', value))
set_option_value(m_time_processor.machine_limits.machine_min_travel_rate, i, value);
}
}
}
void GCodeProcessor::process_SET_VELOCITY_LIMIT(const GCodeReader::GCodeLine& line)
{
// handle SQUARE_CORNER_VELOCITY
std::regex pattern("\\sSQUARE_CORNER_VELOCITY\\s*=\\s*([0-9]*\\.*[0-9]*)");
std::smatch matches;
if (std::regex_search(line.raw(), matches, pattern) && matches.size() == 2) {
float _jerk = 0;
try
{
_jerk = std::stof(matches[1]);
}
catch (...){}
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
set_option_value(m_time_processor.machine_limits.machine_max_jerk_x, i, _jerk);
set_option_value(m_time_processor.machine_limits.machine_max_jerk_y, i, _jerk);
}
}
pattern = std::regex("\\sACCEL\\s*=\\s*([0-9]*\\.*[0-9]*)");
if (std::regex_search(line.raw(), matches, pattern) && matches.size() == 2) {
float _accl = 0;
try
{
_accl = std::stof(matches[1]);
}
catch (...) {}
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
set_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i), _accl);
set_travel_acceleration(static_cast<PrintEstimatedStatistics::ETimeMode>(i), _accl);
}
}
pattern = std::regex("\\sVELOCITY\\s*=\\s*([0-9]*\\.*[0-9]*)");
if (std::regex_search(line.raw(), matches, pattern) && matches.size() == 2) {
float _speed = 0;
try
{
_speed = std::stof(matches[1]);
}
catch (...) {}
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
set_option_value(m_time_processor.machine_limits.machine_max_speed_x, i, _speed);
set_option_value(m_time_processor.machine_limits.machine_max_speed_y, i, _speed);
}
}
}
void GCodeProcessor::process_M221(const GCodeReader::GCodeLine& line)
{
float value_s;
float value_t;
if (line.has_value('S', value_s) && !line.has_value('T', value_t)) {
value_s *= 0.01f;
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
m_time_processor.machines[i].extrude_factor_override_percentage = value_s;
}
}
}
void GCodeProcessor::process_M400(const GCodeReader::GCodeLine& line)
{
float value_s = 0.0;
float value_p = 0.0;
if (line.has_value('S', value_s) || line.has_value('P', value_p)) {
value_s += value_p * 0.001;
simulate_st_synchronize(value_s);
}
}
void GCodeProcessor::process_M401(const GCodeReader::GCodeLine& line)
{
if (m_flavor != gcfRepetier)
return;
for (unsigned char a = 0; a <= 3; ++a) {
m_cached_position.position[a] = m_start_position[a];
}
m_cached_position.feedrate = m_feedrate;
}
void GCodeProcessor::process_M402(const GCodeReader::GCodeLine& line)
{
if (m_flavor != gcfRepetier)
return;
// see for reference:
// https://github.com/repetier/Repetier-Firmware/blob/master/src/ArduinoAVR/Repetier/Printer.cpp
// void Printer::GoToMemoryPosition(bool x, bool y, bool z, bool e, float feed)
bool has_xyz = !(line.has('X') || line.has('Y') || line.has('Z'));
float p = FLT_MAX;
for (unsigned char a = X; a <= Z; ++a) {
if (has_xyz || line.has(a)) {
p = m_cached_position.position[a];
if (p != FLT_MAX)
m_start_position[a] = p;
}
}
p = m_cached_position.position[E];
if (p != FLT_MAX)
m_start_position[E] = p;
p = FLT_MAX;
if (!line.has_value(4, p))
p = m_cached_position.feedrate;
if (p != FLT_MAX)
m_feedrate = p;
}
void GCodeProcessor::process_M566(const GCodeReader::GCodeLine& line)
{
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
if (line.has_x())
set_option_value(m_time_processor.machine_limits.machine_max_jerk_x, i, line.x() * MMMIN_TO_MMSEC);
if (line.has_y())
set_option_value(m_time_processor.machine_limits.machine_max_jerk_y, i, line.y() * MMMIN_TO_MMSEC);
if (line.has_z())
set_option_value(m_time_processor.machine_limits.machine_max_jerk_z, i, line.z() * MMMIN_TO_MMSEC);
if (line.has_e())
set_option_value(m_time_processor.machine_limits.machine_max_jerk_e, i, line.e() * MMMIN_TO_MMSEC);
}
}
void GCodeProcessor::process_M702(const GCodeReader::GCodeLine& line)
{
if (line.has('C')) {
// MK3 MMU2 specific M code:
// M702 C is expected to be sent by the custom end G-code when finalizing a print.
// The MK3 unit shall unload and park the active filament into the MMU2 unit.
m_time_processor.extruder_unloaded = true;
simulate_st_synchronize(get_filament_unload_time(m_extruder_id));
}
}
void GCodeProcessor::process_T(const GCodeReader::GCodeLine& line)
{
process_T(line.cmd());
}
void GCodeProcessor::process_T(const std::string_view command)
{
unsigned int new_extruder = 0;
auto ret = std::from_chars(command.data() + 1, command.data()+command.size(), new_extruder);
if (std::errc::invalid_argument == ret.ec)
return;
if (command.length() > 1) {
if (new_extruder < 0 || new_extruder > 254) {
//BBS: T255, T1000 and T1100 is used as special command for BBL machine and does not cost time. return directly
if ((m_flavor == gcfMarlinLegacy || m_flavor == gcfMarlinFirmware) && (command == "Tx" || command == "Tc" || command == "T?" ||
new_extruder == 1000 || new_extruder == 1100 || new_extruder == 255))
return;
// T-1 is a valid gcode line for RepRap Firmwares (used to deselects all tools)
if ((m_flavor != gcfRepRapFirmware && m_flavor != gcfRepRapSprinter) || new_extruder != -1)
BOOST_LOG_TRIVIAL(error) << "Invalid T command (" << command << ").";
} else {
unsigned char id = static_cast<unsigned char>(new_extruder);
if (m_extruder_id != id) {
if (id >= m_result.extruders_count)
BOOST_LOG_TRIVIAL(error) << "Invalid T command (" << command << ").";
else {
m_last_extruder_id = m_extruder_id;
process_filaments(CustomGCode::ToolChange);
m_extruder_id = id;
m_cp_color.current = m_extruder_colors[id];
//BBS: increase filament change times
m_result.lock();
m_result.print_statistics.total_filamentchanges++;
m_result.unlock();
// Specific to the MK3 MMU2:
// The initial value of extruder_unloaded is set to true indicating
// that the filament is parked in the MMU2 unit and there is nothing to be unloaded yet.
float extra_time = get_filament_unload_time(static_cast<size_t>(m_last_extruder_id));
m_time_processor.extruder_unloaded = false;
extra_time += get_filament_load_time(static_cast<size_t>(m_extruder_id));
simulate_st_synchronize(extra_time);
}
// store tool change move
store_move_vertex(EMoveType::Tool_change);
}
}
}
}
void GCodeProcessor::store_move_vertex(EMoveType type, EMovePathType path_type)
{
m_last_line_id = (type == EMoveType::Color_change || type == EMoveType::Pause_Print || type == EMoveType::Custom_GCode) ?
m_line_id + 1 :
((type == EMoveType::Seam) ? m_last_line_id : m_line_id);
//BBS: apply plate's and extruder's offset to arc interpolation points
if (path_type == EMovePathType::Arc_move_cw ||
path_type == EMovePathType::Arc_move_ccw) {
for (size_t i = 0; i < m_interpolation_points.size(); i++)
m_interpolation_points[i] =
Vec3f(m_interpolation_points[i].x() + m_x_offset,
m_interpolation_points[i].y() + m_y_offset,
m_processing_start_custom_gcode ? m_first_layer_height : m_interpolation_points[i].z()) +
m_extruder_offsets[m_extruder_id];
}
m_result.moves.push_back({
m_last_line_id,
type,
m_extrusion_role,
m_extruder_id,
m_cp_color.current,
//BBS: add plate's offset to the rendering vertices
Vec3f(m_end_position[X] + m_x_offset, m_end_position[Y] + m_y_offset, m_processing_start_custom_gcode ? m_first_layer_height : m_end_position[Z]- m_z_offset) + m_extruder_offsets[m_extruder_id],
static_cast<float>(m_end_position[E] - m_start_position[E]),
m_feedrate,
m_width,
m_height,
m_mm3_per_mm,
m_fan_speed,
m_extruder_temps[m_extruder_id],
static_cast<float>(m_result.moves.size()),
static_cast<float>(m_layer_id), //layer_duration: set later
//BBS: add arc move related data
path_type,
Vec3f(m_arc_center(0, 0) + m_x_offset, m_arc_center(1, 0) + m_y_offset, m_arc_center(2, 0)) + m_extruder_offsets[m_extruder_id],
m_interpolation_points,
});
if (type == EMoveType::Seam) {
m_seams_count++;
}
// stores stop time placeholders for later use
if (type == EMoveType::Color_change || type == EMoveType::Pause_Print) {
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
TimeMachine& machine = m_time_processor.machines[i];
if (!machine.enabled)
continue;
machine.stop_times.push_back({ m_g1_line_id, 0.0f });
}
}
}
void GCodeProcessor::set_extrusion_role(ExtrusionRole role)
{
m_used_filaments.process_role_cache(this);
m_extrusion_role = role;
}
float GCodeProcessor::minimum_feedrate(PrintEstimatedStatistics::ETimeMode mode, float feedrate) const
{
if (m_time_processor.machine_limits.machine_min_extruding_rate.empty())
return feedrate;
return std::max(feedrate, get_option_value(m_time_processor.machine_limits.machine_min_extruding_rate, static_cast<size_t>(mode)));
}
float GCodeProcessor::minimum_travel_feedrate(PrintEstimatedStatistics::ETimeMode mode, float feedrate) const
{
if (m_time_processor.machine_limits.machine_min_travel_rate.empty())
return feedrate;
return std::max(feedrate, get_option_value(m_time_processor.machine_limits.machine_min_travel_rate, static_cast<size_t>(mode)));
}
float GCodeProcessor::get_axis_max_feedrate(PrintEstimatedStatistics::ETimeMode mode, Axis axis) const
{
switch (axis)
{
case X: { return get_option_value(m_time_processor.machine_limits.machine_max_speed_x, static_cast<size_t>(mode)); }
case Y: { return get_option_value(m_time_processor.machine_limits.machine_max_speed_y, static_cast<size_t>(mode)); }
case Z: { return get_option_value(m_time_processor.machine_limits.machine_max_speed_z, static_cast<size_t>(mode)); }
case E: { return get_option_value(m_time_processor.machine_limits.machine_max_speed_e, static_cast<size_t>(mode)); }
default: { return 0.0f; }
}
}
float GCodeProcessor::get_axis_max_acceleration(PrintEstimatedStatistics::ETimeMode mode, Axis axis) const
{
switch (axis)
{
case X: { return get_option_value(m_time_processor.machine_limits.machine_max_acceleration_x, static_cast<size_t>(mode)); }
case Y: { return get_option_value(m_time_processor.machine_limits.machine_max_acceleration_y, static_cast<size_t>(mode)); }
case Z: { return get_option_value(m_time_processor.machine_limits.machine_max_acceleration_z, static_cast<size_t>(mode)); }
case E: { return get_option_value(m_time_processor.machine_limits.machine_max_acceleration_e, static_cast<size_t>(mode)); }
default: { return 0.0f; }
}
}
float GCodeProcessor::get_axis_max_jerk(PrintEstimatedStatistics::ETimeMode mode, Axis axis) const
{
switch (axis)
{
case X: { return get_option_value(m_time_processor.machine_limits.machine_max_jerk_x, static_cast<size_t>(mode)); }
case Y: { return get_option_value(m_time_processor.machine_limits.machine_max_jerk_y, static_cast<size_t>(mode)); }
case Z: { return get_option_value(m_time_processor.machine_limits.machine_max_jerk_z, static_cast<size_t>(mode)); }
case E: { return get_option_value(m_time_processor.machine_limits.machine_max_jerk_e, static_cast<size_t>(mode)); }
default: { return 0.0f; }
}
}
Vec3f GCodeProcessor::get_xyz_max_jerk(PrintEstimatedStatistics::ETimeMode mode) const
{
return Vec3f(get_option_value(m_time_processor.machine_limits.machine_max_jerk_x, static_cast<size_t>(mode)),
get_option_value(m_time_processor.machine_limits.machine_max_jerk_y, static_cast<size_t>(mode)),
get_option_value(m_time_processor.machine_limits.machine_max_jerk_z, static_cast<size_t>(mode)));
}
float GCodeProcessor::get_retract_acceleration(PrintEstimatedStatistics::ETimeMode mode) const
{
size_t id = static_cast<size_t>(mode);
return (id < m_time_processor.machines.size()) ? m_time_processor.machines[id].retract_acceleration : DEFAULT_RETRACT_ACCELERATION;
}
void GCodeProcessor::set_retract_acceleration(PrintEstimatedStatistics::ETimeMode mode, float value)
{
size_t id = static_cast<size_t>(mode);
if (id < m_time_processor.machines.size()) {
m_time_processor.machines[id].retract_acceleration = (m_time_processor.machines[id].max_retract_acceleration == 0.0f) ? value :
// Clamp the acceleration with the maximum.
std::min(value, m_time_processor.machines[id].max_retract_acceleration);
}
}
float GCodeProcessor::get_acceleration(PrintEstimatedStatistics::ETimeMode mode) const
{
size_t id = static_cast<size_t>(mode);
return (id < m_time_processor.machines.size()) ? m_time_processor.machines[id].acceleration : DEFAULT_ACCELERATION;
}
void GCodeProcessor::set_acceleration(PrintEstimatedStatistics::ETimeMode mode, float value)
{
size_t id = static_cast<size_t>(mode);
if (id < m_time_processor.machines.size()) {
m_time_processor.machines[id].acceleration = (m_time_processor.machines[id].max_acceleration == 0.0f) ? value :
// Clamp the acceleration with the maximum.
std::min(value, m_time_processor.machines[id].max_acceleration);
}
}
float GCodeProcessor::get_travel_acceleration(PrintEstimatedStatistics::ETimeMode mode) const
{
size_t id = static_cast<size_t>(mode);
return (id < m_time_processor.machines.size()) ? m_time_processor.machines[id].travel_acceleration : DEFAULT_TRAVEL_ACCELERATION;
}
void GCodeProcessor::set_travel_acceleration(PrintEstimatedStatistics::ETimeMode mode, float value)
{
size_t id = static_cast<size_t>(mode);
if (id < m_time_processor.machines.size()) {
m_time_processor.machines[id].travel_acceleration = (m_time_processor.machines[id].max_travel_acceleration == 0.0f) ? value :
// Clamp the acceleration with the maximum.
std::min(value, m_time_processor.machines[id].max_travel_acceleration);
}
}
float GCodeProcessor::get_filament_load_time(size_t extruder_id)
{
if (s_IsBBLPrinter) {
// BBL printers
// BBS: change load time to machine config and all extruder has same value
return m_time_processor.extruder_unloaded ? 0.0f : m_time_processor.filament_load_times[0];
} else {
// non-BBL printers
return (m_time_processor.filament_load_times.empty() || m_time_processor.extruder_unloaded) ?
0.0f :
((extruder_id < m_time_processor.filament_load_times.size()) ? m_time_processor.filament_load_times[extruder_id] :
m_time_processor.filament_load_times.front());
}
}
float GCodeProcessor::get_filament_unload_time(size_t extruder_id)
{
if (s_IsBBLPrinter) {
// BBL printers
// BBS: change unload time to machine config and all extruder has same value
return m_time_processor.extruder_unloaded ? 0.0f : m_time_processor.filament_unload_times[0];
} else {
// non-BBL printers
return (m_time_processor.filament_unload_times.empty() || m_time_processor.extruder_unloaded) ?
0.0f :
((extruder_id < m_time_processor.filament_unload_times.size()) ? m_time_processor.filament_unload_times[extruder_id] :
m_time_processor.filament_unload_times.front());
}
}
//BBS
int GCodeProcessor::get_filament_vitrification_temperature(size_t extrude_id)
{
if (extrude_id < m_result.filament_vitrification_temperature.size())
return m_result.filament_vitrification_temperature[extrude_id];
else
return 0;
}
void GCodeProcessor::process_custom_gcode_time(CustomGCode::Type code)
{
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
TimeMachine& machine = m_time_processor.machines[i];
if (!machine.enabled)
continue;
TimeMachine::CustomGCodeTime& gcode_time = machine.gcode_time;
gcode_time.needed = true;
//FIXME this simulates st_synchronize! is it correct?
// The estimated time may be longer than the real print time.
machine.simulate_st_synchronize();
if (gcode_time.cache != 0.0f) {
gcode_time.times.push_back({ code, gcode_time.cache });
gcode_time.cache = 0.0f;
}
}
}
void GCodeProcessor::process_filaments(CustomGCode::Type code)
{
if (code == CustomGCode::ColorChange)
m_used_filaments.process_color_change_cache();
if (code == CustomGCode::ToolChange) {
m_used_filaments.process_model_cache(this);
m_used_filaments.process_support_cache(this);
//BBS: reset remaining filament
m_remaining_volume = m_nozzle_volume;
}
}
void GCodeProcessor::simulate_st_synchronize(float additional_time)
{
for (size_t i = 0; i < static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count); ++i) {
m_time_processor.machines[i].simulate_st_synchronize(additional_time);
}
}
void GCodeProcessor::update_estimated_times_stats()
{
auto update_mode = [this](PrintEstimatedStatistics::ETimeMode mode) {
PrintEstimatedStatistics::Mode& data = m_result.print_statistics.modes[static_cast<size_t>(mode)];
data.time = get_time(mode);
data.prepare_time = get_prepare_time(mode);
data.custom_gcode_times = get_custom_gcode_times(mode, true);
data.moves_times = get_moves_time(mode);
data.roles_times = get_roles_time(mode);
data.layers_times = get_layers_time(mode);
};
update_mode(PrintEstimatedStatistics::ETimeMode::Normal);
if (m_time_processor.machines[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Stealth)].enabled)
update_mode(PrintEstimatedStatistics::ETimeMode::Stealth);
else
m_result.print_statistics.modes[static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Stealth)].reset();
m_result.print_statistics.volumes_per_color_change = m_used_filaments.volumes_per_color_change;
m_result.print_statistics.volumes_per_extruder = m_used_filaments.volumes_per_extruder;
m_result.print_statistics.wipe_tower_volumes_per_extruder = m_used_filaments.wipe_tower_volume_per_extruder;
m_result.print_statistics.support_volumes_per_extruder = m_used_filaments.support_volume_per_extruder;
m_result.print_statistics.flush_per_filament = m_used_filaments.flush_per_filament;
m_result.print_statistics.used_filaments_per_role = m_used_filaments.filaments_per_role;
}
//BBS: ugly code...
void GCodeProcessor::update_slice_warnings()
{
m_result.warnings.clear();
auto get_used_extruders = [this]() {
std::vector<size_t> used_extruders;
used_extruders.reserve(m_used_filaments.volumes_per_extruder.size());
for (auto item : m_used_filaments.volumes_per_extruder) {
used_extruders.push_back(item.first);
}
return used_extruders;
};
auto used_extruders = get_used_extruders();
assert(!used_extruders.empty());
GCodeProcessorResult::SliceWarning warning;
warning.level = 1;
if (m_highest_bed_temp != 0) {
for (size_t i = 0; i < used_extruders.size(); i++) {
int temperature = get_filament_vitrification_temperature(used_extruders[i]);
if (temperature != 0 && m_highest_bed_temp >= temperature)
warning.params.push_back(std::to_string(used_extruders[i]));
}
}
if (!warning.params.empty()) {
warning.msg = BED_TEMP_TOO_HIGH_THAN_FILAMENT;
warning.error_code = "1000C001";
m_result.warnings.push_back(warning);
}
//bbs:HRC checker
warning.params.clear();
warning.level=1;
int nozzle_hrc = m_result.nozzle_hrc;
if(nozzle_hrc <= 0)
nozzle_hrc = Print::get_hrc_by_nozzle_type(m_result.nozzle_type);
if (nozzle_hrc!=0) {
for (size_t i = 0; i < used_extruders.size(); i++) {
int HRC=0;
if (used_extruders[i] < m_result.required_nozzle_HRC.size())
HRC = m_result.required_nozzle_HRC[used_extruders[i]];
if (HRC != 0 && (nozzle_hrc<HRC))
warning.params.push_back(std::to_string(used_extruders[i]));
}
}
if (!warning.params.empty()) {
warning.msg = NOZZLE_HRC_CHECKER;
warning.error_code = "1000C002";
m_result.warnings.push_back(warning);
}
// bbs:HRC checker
warning.params.clear();
warning.level = 1;
if (!m_result.support_traditional_timelapse) {
warning.msg = NOT_SUPPORT_TRADITIONAL_TIMELAPSE;
warning.error_code = "1000C003";
m_result.warnings.push_back(warning);
}
if (m_result.timelapse_warning_code != 0) {
if (m_result.timelapse_warning_code & 1) {
warning.msg = NOT_GENERATE_TIMELAPSE;
warning.error_code = "1001C001";
m_result.warnings.push_back(warning);
}
if ((m_result.timelapse_warning_code >> 1) & 1) {
warning.msg = NOT_GENERATE_TIMELAPSE;
warning.error_code = "1001C002";
m_result.warnings.push_back(warning);
}
}
m_result.warnings.shrink_to_fit();
}
} /* namespace Slic3r */