From 0f4bec8af0d3c31741db8765fc8ed3fee437312e Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Mon, 8 Jan 2018 13:44:10 +0100 Subject: [PATCH 01/57] gcode preview - first installment - wip --- lib/Slic3r/GUI/3DScene.pm | 9 + lib/Slic3r/GUI/Plater.pm | 12 + lib/Slic3r/GUI/Plater/3DPreview.pm | 113 +++- lib/Slic3r/GUI/Plater/3DToolpaths.pm | 24 +- xs/src/libslic3r/BoundingBox.cpp | 12 + xs/src/libslic3r/BoundingBox.hpp | 54 ++ xs/src/libslic3r/ExtrusionEntity.hpp | 29 +- xs/src/libslic3r/GCode.cpp | 114 ++++ xs/src/libslic3r/GCode.hpp | 61 ++ xs/src/libslic3r/GCode/Analyzer.cpp | 960 +++++++++++++++++++++++++++ xs/src/libslic3r/GCode/Analyzer.hpp | 382 ++++++++++- xs/src/libslic3r/Line.cpp | 14 + xs/src/libslic3r/Line.hpp | 27 + xs/src/libslic3r/MultiPoint.cpp | 59 ++ xs/src/libslic3r/MultiPoint.hpp | 28 + xs/src/libslic3r/Point.hpp | 60 ++ xs/src/libslic3r/Polyline.cpp | 18 + xs/src/libslic3r/Polyline.hpp | 12 + xs/src/libslic3r/Print.cpp | 35 + xs/src/libslic3r/Print.hpp | 21 + xs/src/libslic3r/libslic3r.h | 17 + xs/src/slic3r/GUI/3DScene.cpp | 479 ++++++++++++- xs/src/slic3r/GUI/3DScene.hpp | 23 + xs/xsp/GUI_3DScene.xsp | 8 + xs/xsp/Print.xsp | 8 + 25 files changed, 2552 insertions(+), 27 deletions(-) diff --git a/lib/Slic3r/GUI/3DScene.pm b/lib/Slic3r/GUI/3DScene.pm index 730216a8b..f97586073 100644 --- a/lib/Slic3r/GUI/3DScene.pm +++ b/lib/Slic3r/GUI/3DScene.pm @@ -1979,6 +1979,15 @@ sub load_wipe_tower_toolpaths { if ($print->step_done(STEP_WIPE_TOWER)); } +# ===================== ENRICO_GCODE_PREVIEW ================================================== +sub load_gcode_preview { + my ($self, $print) = @_; + + $self->SetCurrent($self->GetContext) if $self->UseVBOs; + Slic3r::GUI::_3DScene::load_gcode_preview($print, $self->volumes, $self->UseVBOs); +} +# ===================== ENRICO_GCODE_PREVIEW ================================================== + sub set_toolpaths_range { my ($self, $min_z, $max_z) = @_; $self->volumes->set_range($min_z, $max_z); diff --git a/lib/Slic3r/GUI/Plater.pm b/lib/Slic3r/GUI/Plater.pm index 10d65475c..63e628f3e 100644 --- a/lib/Slic3r/GUI/Plater.pm +++ b/lib/Slic3r/GUI/Plater.pm @@ -776,6 +776,9 @@ sub remove { splice @{$self->{objects}}, $obj_idx, 1; $self->{model}->delete_object($obj_idx); $self->{print}->delete_object($obj_idx); +# ===================== ENRICO_GCODE_PREVIEW ================================================== + $self->{print}->clear_gcode_preview_data; +# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->{list}->DeleteItem($obj_idx); $self->object_list_changed; @@ -796,6 +799,9 @@ sub reset { @{$self->{objects}} = (); $self->{model}->clear_objects; $self->{print}->clear_objects; +# ===================== ENRICO_GCODE_PREVIEW ================================================== + $self->{print}->clear_gcode_preview_data; +# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->{list}->DeleteAllItems; $self->object_list_changed; @@ -1435,6 +1441,12 @@ sub on_export_completed { # this updates buttons status $self->object_list_changed; + +# ===================== ENRICO_GCODE_PREVIEW ================================================== + # refresh preview + $self->{toolpaths2D}->reload_print if $self->{toolpaths2D}; + $self->{preview3D}->reload_print if $self->{preview3D}; +# ===================== ENRICO_GCODE_PREVIEW ================================================== } sub do_print { diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index c7d4cc4a8..9ff3461e0 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -5,10 +5,16 @@ use utf8; use Slic3r::Print::State ':steps'; use Wx qw(:misc :sizer :slider :statictext :keycode wxWHITE); -use Wx::Event qw(EVT_SLIDER EVT_KEY_DOWN EVT_CHECKBOX); +# ===================== ENRICO_GCODE_PREVIEW ================================================== +use Wx::Event qw(EVT_SLIDER EVT_KEY_DOWN EVT_CHECKBOX EVT_CHOICE EVT_CHECKLISTBOX); +#use Wx::Event qw(EVT_SLIDER EVT_KEY_DOWN EVT_CHECKBOX); +# ===================== ENRICO_GCODE_PREVIEW ================================================== use base qw(Wx::Panel Class::Accessor); -__PACKAGE__->mk_accessors(qw(print enabled _loaded canvas slider_low slider_high single_layer)); +# ===================== ENRICO_GCODE_PREVIEW ================================================== +__PACKAGE__->mk_accessors(qw(print enabled _loaded canvas slider_low slider_high single_layer auto_zoom)); +#__PACKAGE__->mk_accessors(qw(print enabled _loaded canvas slider_low slider_high single_layer)); +# ===================== ENRICO_GCODE_PREVIEW ================================================== sub new { my $class = shift; @@ -18,6 +24,9 @@ sub new { $self->{config} = $config; $self->{number_extruders} = 1; $self->{preferred_color_mode} = 'feature'; +# ===================== ENRICO_GCODE_PREVIEW ================================================== + $self->auto_zoom(1); +# ===================== ENRICO_GCODE_PREVIEW ================================================== # init GUI elements my $canvas = Slic3r::GUI::3DScene->new($self); @@ -60,6 +69,35 @@ sub new { my $checkbox_singlelayer = $self->{checkbox_singlelayer} = Wx::CheckBox->new($self, -1, "1 Layer"); my $checkbox_color_by_extruder = $self->{checkbox_color_by_extruder} = Wx::CheckBox->new($self, -1, "Tool"); +# ===================== ENRICO_GCODE_PREVIEW ================================================== + my $choice_view_type = Wx::Choice->new($self, -1); + $choice_view_type->Append("Feature type"); + $choice_view_type->Append("Height"); + $choice_view_type->Append("Width"); + $choice_view_type->Append("Speed"); + $choice_view_type->SetSelection(0); + + my $checklist_features = Wx::CheckListBox->new($self, -1, wxDefaultPosition, [-1, 150]); + $checklist_features->Append("Perimeter"); + $checklist_features->Append("External perimeter"); + $checklist_features->Append("Overhang perimeter"); + $checklist_features->Append("Internal infill"); + $checklist_features->Append("Solid infill"); + $checklist_features->Append("Top solid infill"); + $checklist_features->Append("Bridge infill"); + $checklist_features->Append("Gap fill"); + $checklist_features->Append("Skirt"); + $checklist_features->Append("Support material"); + $checklist_features->Append("Support material interface"); + for (my $i = 0; $i < $checklist_features->GetCount(); $i += 1) + { + $checklist_features->Check($i, 1); + } + + my $checkbox_travel = Wx::CheckBox->new($self, -1, "Travel"); + my $checkbox_retractions = Wx::CheckBox->new($self, -1, "Retractions"); +# ===================== ENRICO_GCODE_PREVIEW ================================================== + my $hsizer = Wx::BoxSizer->new(wxHORIZONTAL); my $vsizer = Wx::BoxSizer->new(wxVERTICAL); my $vsizer_outer = Wx::BoxSizer->new(wxVERTICAL); @@ -73,6 +111,12 @@ sub new { $vsizer_outer->Add($hsizer, 3, wxALIGN_CENTER_HORIZONTAL, 0); $vsizer_outer->Add($checkbox_singlelayer, 0, wxTOP | wxALIGN_CENTER_HORIZONTAL, 5); $vsizer_outer->Add($checkbox_color_by_extruder, 0, wxTOP | wxALIGN_CENTER_HORIZONTAL, 5); +# ===================== ENRICO_GCODE_PREVIEW ================================================== + $vsizer_outer->Add($choice_view_type, 0, wxEXPAND | wxALL | wxALIGN_CENTER_HORIZONTAL, 5); + $vsizer_outer->Add($checklist_features, 0, wxTOP | wxALL | wxALIGN_CENTER_HORIZONTAL, 5); + $vsizer_outer->Add($checkbox_travel, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); + $vsizer_outer->Add($checkbox_retractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); +# ===================== ENRICO_GCODE_PREVIEW ================================================== my $sizer = Wx::BoxSizer->new(wxHORIZONTAL); $sizer->Add($canvas, 1, wxALL | wxEXPAND, 0); @@ -153,6 +197,39 @@ sub new { $self->reload_print; }); +# ===================== ENRICO_GCODE_PREVIEW ================================================== + EVT_CHOICE($self, $choice_view_type, sub { + my $selection = $choice_view_type->GetCurrentSelection(); + $self->print->set_gcode_preview_type($selection); + $self->auto_zoom(0); + $self->reload_print; + }); + EVT_CHECKLISTBOX($self, $checklist_features, sub { + my $flags = 0; + for (my $i = 0; $i < $checklist_features->GetCount(); $i += 1) + { + if ($checklist_features->IsChecked($i)) + { + $flags += 2 ** $i; + } + } + + $self->print->set_gcode_preview_extrusion_flags($flags); + $self->auto_zoom(0); + $self->reload_print; + }); + EVT_CHECKBOX($self, $checkbox_travel, sub { + $self->print->set_gcode_preview_travel_visible($checkbox_travel->IsChecked()); + $self->auto_zoom(0); + $self->reload_print; + }); + EVT_CHECKBOX($self, $checkbox_retractions, sub { + $self->print->set_gcode_preview_retractions_visible($checkbox_retractions->IsChecked()); + $self->auto_zoom(0); + $self->reload_print; + }); +# ===================== ENRICO_GCODE_PREVIEW ================================================== + $self->SetSizer($sizer); $self->SetMinSize($self->GetSize); $sizer->SetSizeHints($self); @@ -258,18 +335,30 @@ sub load_print { } if ($self->IsShown) { +# ===================== ENRICO_GCODE_PREVIEW ================================================== + $self->canvas->load_gcode_preview($self->print); + # load skirt and brim - $self->canvas->load_print_toolpaths($self->print, \@colors); - $self->canvas->load_wipe_tower_toolpaths($self->print, \@colors); - - foreach my $object (@{$self->print->objects}) { - $self->canvas->load_print_object_toolpaths($object, \@colors); - - # Show the objects in very transparent color. - #my @volume_ids = $self->canvas->load_object($object->model_object); - #$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids; - } +# $self->canvas->load_print_toolpaths($self->print, \@colors); +# $self->canvas->load_wipe_tower_toolpaths($self->print, \@colors); +# +# foreach my $object (@{$self->print->objects}) { +# $self->canvas->load_print_object_toolpaths($object, \@colors); +# +# # Show the objects in very transparent color. +# #my @volume_ids = $self->canvas->load_object($object->model_object); +# #$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids; +# } +# ===================== ENRICO_GCODE_PREVIEW ================================================== +# ===================== ENRICO_GCODE_PREVIEW ================================================== + if ($self->auto_zoom) + { +# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->canvas->zoom_to_volumes; +# ===================== ENRICO_GCODE_PREVIEW ================================================== + $self->auto_zoom(1); + } +# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->_loaded(1); } diff --git a/lib/Slic3r/GUI/Plater/3DToolpaths.pm b/lib/Slic3r/GUI/Plater/3DToolpaths.pm index fb904b0fd..3dbe59d57 100644 --- a/lib/Slic3r/GUI/Plater/3DToolpaths.pm +++ b/lib/Slic3r/GUI/Plater/3DToolpaths.pm @@ -122,16 +122,20 @@ sub load_print { } if ($self->IsShown) { - # load skirt and brim - $self->canvas->load_print_toolpaths($self->print); - - foreach my $object (@{$self->print->objects}) { - $self->canvas->load_print_object_toolpaths($object); - - # Show the objects in very transparent color. - #my @volume_ids = $self->canvas->load_object($object->model_object); - #$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids; - } +# ===================== ENRICO_GCODE_PREVIEW ================================================== + $self->canvas->load_gcode_preview($self->print); + +# # load skirt and brim +# $self->canvas->load_print_toolpaths($self->print); +# +# foreach my $object (@{$self->print->objects}) { +# $self->canvas->load_print_object_toolpaths($object); +# +# # Show the objects in very transparent color. +# #my @volume_ids = $self->canvas->load_object($object->model_object); +# #$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids; +# } +# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->canvas->zoom_to_volumes; $self->_loaded(1); } diff --git a/xs/src/libslic3r/BoundingBox.cpp b/xs/src/libslic3r/BoundingBox.cpp index 46a43ca69..929488a3a 100644 --- a/xs/src/libslic3r/BoundingBox.cpp +++ b/xs/src/libslic3r/BoundingBox.cpp @@ -4,6 +4,9 @@ namespace Slic3r { +//############################################################################################################ +#if !ENRICO_GCODE_PREVIEW +//############################################################################################################ template BoundingBoxBase::BoundingBoxBase(const std::vector &points) { @@ -20,9 +23,15 @@ BoundingBoxBase::BoundingBoxBase(const std::vector &poin } this->defined = true; } +//############################################################################################################ +#endif // !ENRICO_GCODE_PREVIEW +//############################################################################################################ template BoundingBoxBase::BoundingBoxBase(const std::vector &points); template BoundingBoxBase::BoundingBoxBase(const std::vector &points); +//############################################################################################################ +#if !ENRICO_GCODE_PREVIEW +//############################################################################################################ template BoundingBox3Base::BoundingBox3Base(const std::vector &points) : BoundingBoxBase(points) @@ -36,6 +45,9 @@ BoundingBox3Base::BoundingBox3Base(const std::vector &po this->max.z = std::max(it->z, this->max.z); } } +//############################################################################################################ +#endif // !ENRICO_GCODE_PREVIEW +//############################################################################################################ template BoundingBox3Base::BoundingBox3Base(const std::vector &points); BoundingBox::BoundingBox(const Lines &lines) diff --git a/xs/src/libslic3r/BoundingBox.hpp b/xs/src/libslic3r/BoundingBox.hpp index 90179d3f9..f1782805b 100644 --- a/xs/src/libslic3r/BoundingBox.hpp +++ b/xs/src/libslic3r/BoundingBox.hpp @@ -23,7 +23,31 @@ public: BoundingBoxBase() : defined(false) {}; BoundingBoxBase(const PointClass &pmin, const PointClass &pmax) : min(pmin), max(pmax), defined(pmin.x < pmax.x && pmin.y < pmax.y) {} +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + BoundingBoxBase(const std::vector& points) + { + if (points.empty()) + CONFESS("Empty point set supplied to BoundingBoxBase constructor"); + + std::vector::const_iterator it = points.begin(); + this->min.x = this->max.x = it->x; + this->min.y = this->max.y = it->y; + for (++it; it != points.end(); ++it) + { + this->min.x = std::min(it->x, this->min.x); + this->min.y = std::min(it->y, this->min.y); + this->max.x = std::max(it->x, this->max.x); + this->max.y = std::max(it->y, this->max.y); + } + this->defined = (this->min.x < this->max.x) && (this->min.y < this->max.y); + } +#else +//############################################################################################################ BoundingBoxBase(const std::vector &points); +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ void merge(const PointClass &point); void merge(const std::vector &points); void merge(const BoundingBoxBase &bb); @@ -54,7 +78,29 @@ public: BoundingBox3Base(const PointClass &pmin, const PointClass &pmax) : BoundingBoxBase(pmin, pmax) { if (pmin.z >= pmax.z) BoundingBoxBase::defined = false; } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + BoundingBox3Base(const std::vector& points) + : BoundingBoxBase(points) + { + if (points.empty()) + CONFESS("Empty point set supplied to BoundingBox3Base constructor"); + + std::vector::const_iterator it = points.begin(); + this->min.z = this->max.z = it->z; + for (++it; it != points.end(); ++it) + { + this->min.z = std::min(it->z, this->min.z); + this->max.z = std::max(it->z, this->max.z); + } + this->defined &= (this->min.z < this->max.z); + } +#else +//############################################################################################################ BoundingBox3Base(const std::vector &points); +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ void merge(const PointClass &point); void merge(const std::vector &points); void merge(const BoundingBox3Base &bb); @@ -92,7 +138,15 @@ class BoundingBox3 : public BoundingBox3Base public: BoundingBox3() : BoundingBox3Base() {}; BoundingBox3(const Point3 &pmin, const Point3 &pmax) : BoundingBox3Base(pmin, pmax) {}; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + BoundingBox3(const Points3& points) : BoundingBox3Base(points) {}; +#else +//############################################################################################################ BoundingBox3(const std::vector &points) : BoundingBox3Base(points) {}; +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ }; class BoundingBoxf : public BoundingBoxBase diff --git a/xs/src/libslic3r/ExtrusionEntity.hpp b/xs/src/libslic3r/ExtrusionEntity.hpp index 6e5b123dc..282a0b5d4 100644 --- a/xs/src/libslic3r/ExtrusionEntity.hpp +++ b/xs/src/libslic3r/ExtrusionEntity.hpp @@ -104,15 +104,42 @@ public: float width; // Height of the extrusion, used for visualization purposed. float height; - +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + // Feedrate of the extrusion, used for visualization purposed. + float feedrate; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + ExtrusionPath(ExtrusionRole role) : mm3_per_mm(-1), width(-1), height(-1), feedrate(0.0f), m_role(role) {}; + ExtrusionPath(ExtrusionRole role, double mm3_per_mm, float width, float height) : mm3_per_mm(mm3_per_mm), width(width), height(height), feedrate(0.0f), m_role(role) {}; + ExtrusionPath(const ExtrusionPath &rhs) : polyline(rhs.polyline), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), feedrate(rhs.feedrate), m_role(rhs.m_role) {} + ExtrusionPath(ExtrusionPath &&rhs) : polyline(std::move(rhs.polyline)), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), feedrate(rhs.feedrate), m_role(rhs.m_role) {} +// ExtrusionPath(ExtrusionRole role, const Flow &flow) : m_role(role), mm3_per_mm(flow.mm3_per_mm()), width(flow.width), height(flow.height), feedrate(0.0f) {}; +#else +//############################################################################################################ ExtrusionPath(ExtrusionRole role) : mm3_per_mm(-1), width(-1), height(-1), m_role(role) {}; ExtrusionPath(ExtrusionRole role, double mm3_per_mm, float width, float height) : mm3_per_mm(mm3_per_mm), width(width), height(height), m_role(role) {}; ExtrusionPath(const ExtrusionPath &rhs) : polyline(rhs.polyline), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), m_role(rhs.m_role) {} ExtrusionPath(ExtrusionPath &&rhs) : polyline(std::move(rhs.polyline)), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), m_role(rhs.m_role) {} // ExtrusionPath(ExtrusionRole role, const Flow &flow) : m_role(role), mm3_per_mm(flow.mm3_per_mm()), width(flow.width), height(flow.height) {}; +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + ExtrusionPath& operator=(const ExtrusionPath &rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->feedrate = rhs.feedrate, this->polyline = rhs.polyline; return *this; } + ExtrusionPath& operator=(ExtrusionPath &&rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->feedrate = rhs.feedrate, this->polyline = std::move(rhs.polyline); return *this; } +#else +//############################################################################################################ ExtrusionPath& operator=(const ExtrusionPath &rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->polyline = rhs.polyline; return *this; } ExtrusionPath& operator=(ExtrusionPath &&rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->polyline = std::move(rhs.polyline); return *this; } +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ ExtrusionPath* clone() const { return new ExtrusionPath (*this); } void reverse() { this->polyline.reverse(); } diff --git a/xs/src/libslic3r/GCode.cpp b/xs/src/libslic3r/GCode.cpp index e85b21f80..97347b9b9 100644 --- a/xs/src/libslic3r/GCode.cpp +++ b/xs/src/libslic3r/GCode.cpp @@ -401,6 +401,18 @@ void GCode::_do_export(Print &print, FILE *file) // resets time estimator m_time_estimator.reset(); +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + // resets analyzer + m_analyzer.reset(); + + // resets analyzer's tracking data + m_last_mm3_per_mm = GCodeAnalyzer::Default_mm3_per_mm; + m_last_width = GCodeAnalyzer::Default_Width; + m_last_height = GCodeAnalyzer::Default_Height; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + // How many times will be change_layer() called? // change_layer() in turn increments the progress bar status. m_layer_count = 0; @@ -809,6 +821,13 @@ void GCode::_do_export(Print &print, FILE *file) _write_format(file, "; %s = %s\n", key.c_str(), cfg->serialize(key).c_str()); } } + +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + // starts analizer calculations + m_analyzer.calc_gcode_preview_data(print); +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ } std::string GCode::placeholder_parser_process(const std::string &name, const std::string &templ, unsigned int current_extruder_id, const DynamicConfig *config_override) @@ -1300,12 +1319,18 @@ void GCode::process_layer( if (print_object == nullptr) // This layer is empty for this particular object, it has neither object extrusions nor support extrusions at this print_z. continue; +//############################################################################################################ +#if !ENRICO_GCODE_PREVIEW +//############################################################################################################ if (m_enable_analyzer_markers) { // Store the binary pointer to the layer object directly into the G-code to be accessed by the GCodeAnalyzer. char buf[64]; sprintf(buf, ";_LAYEROBJ:%p\n", m_layer); gcode += buf; } +//############################################################################################################ +#endif // !ENRICO_GCODE_PREVIEW +//############################################################################################################ m_config.apply(print_object->config, true); m_layer = layers[layer_id].layer(); if (m_config.avoid_crossing_perimeters) @@ -1997,13 +2022,36 @@ std::string GCode::extrude_support(const ExtrusionEntityCollection &support_fill return gcode; } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +void GCode::_write(FILE* file, const char *what) +#else +//############################################################################################################ void GCode::_write(FILE* file, const char *what, size_t size) +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ { +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + if (what != nullptr) { + // apply analyzer, if enabled + const char* gcode = m_enable_analyzer ? m_analyzer.process_gcode(what).c_str() : what; + + // writes string to file + fwrite(gcode, 1, ::strlen(gcode), file); + // updates time estimator and gcode lines vector + m_time_estimator.add_gcode_block(gcode); +#else +//############################################################################################################ if (size > 0) { // writes string to file fwrite(what, 1, size, file); // updates time estimator and gcode lines vector m_time_estimator.add_gcode_block(what); +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ } } @@ -2037,7 +2085,15 @@ void GCode::_write_format(FILE* file, const char* format, ...) char *bufptr = buffer_dynamic ? (char*)malloc(buflen) : buffer; int res = ::vsnprintf(bufptr, buflen, format, args); if (res > 0) +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + _write(file, bufptr); +#else +//############################################################################################################ _write(file, bufptr, res); +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ if (buffer_dynamic) free(bufptr); @@ -2122,6 +2178,60 @@ std::string GCode::_extrude(const ExtrusionPath &path, std::string description, double F = speed * 60; // convert mm/sec to mm/min // extrude arc or line +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + if (m_enable_extrusion_role_markers || m_enable_analyzer) + { + if (path.role() != m_last_extrusion_role) + { + m_last_extrusion_role = path.role(); + if (m_enable_extrusion_role_markers) + { + char buf[32]; + sprintf(buf, ";_EXTRUSION_ROLE:%d\n", int(m_last_extrusion_role)); + gcode += buf; + } + if (m_enable_analyzer) + { + char buf[32]; + sprintf(buf, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), int(m_last_extrusion_role)); + gcode += buf; + } + } + } + + // adds analyzer tags and updates analyzer's tracking data + if (m_enable_analyzer) + { + if (m_last_mm3_per_mm != path.mm3_per_mm) + { + m_last_mm3_per_mm = path.mm3_per_mm; + + char buf[32]; + sprintf(buf, ";%s%f\n", GCodeAnalyzer::Mm3_Per_Mm_Tag.c_str(), m_last_mm3_per_mm); + gcode += buf; + } + + if (m_last_width != path.width) + { + m_last_width = path.width; + + char buf[32]; + sprintf(buf, ";%s%f\n", GCodeAnalyzer::Width_Tag.c_str(), m_last_width); + gcode += buf; + } + + if (m_last_height != path.height) + { + m_last_height = path.height; + + char buf[32]; + sprintf(buf, ";%s%f\n", GCodeAnalyzer::Height_Tag.c_str(), m_last_height); + gcode += buf; + } + } +#else +//############################################################################################################ if (m_enable_extrusion_role_markers || m_enable_analyzer_markers) { if (path.role() != m_last_extrusion_role) { m_last_extrusion_role = path.role(); @@ -2130,6 +2240,10 @@ std::string GCode::_extrude(const ExtrusionPath &path, std::string description, gcode += buf; } } +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + std::string comment; if (m_enable_cooling_markers) { if (is_bridge(path.role())) diff --git a/xs/src/libslic3r/GCode.hpp b/xs/src/libslic3r/GCode.hpp index 5c622ec2d..97d6d6927 100644 --- a/xs/src/libslic3r/GCode.hpp +++ b/xs/src/libslic3r/GCode.hpp @@ -17,6 +17,11 @@ #include "GCode/WipeTower.hpp" #include "GCodeTimeEstimator.hpp" #include "EdgeGrid.hpp" +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +#include "GCode/Analyzer.hpp" +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ #include #include @@ -118,13 +123,28 @@ public: m_enable_loop_clipping(true), m_enable_cooling_markers(false), m_enable_extrusion_role_markers(false), +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + m_enable_analyzer(true), +#else +//############################################################################################################ m_enable_analyzer_markers(false), +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ m_layer_count(0), m_layer_index(-1), m_layer(nullptr), m_volumetric_speed(0), m_last_pos_defined(false), m_last_extrusion_role(erNone), +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + m_last_mm3_per_mm(GCodeAnalyzer::Default_mm3_per_mm), + m_last_width(GCodeAnalyzer::Default_Width), + m_last_height(GCodeAnalyzer::Default_Height), +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ m_brim_done(false), m_second_layer_things_done(false), m_last_obj_copy(nullptr, Point(std::numeric_limits::max(), std::numeric_limits::max())) @@ -149,6 +169,12 @@ public: // inside the generated string and after the G-code export finishes. std::string placeholder_parser_process(const std::string &name, const std::string &templ, unsigned int current_extruder_id, const DynamicConfig *config_override = nullptr); bool enable_cooling_markers() const { return m_enable_cooling_markers; } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + bool enable_analyzer() const { return m_enable_analyzer; } + void enable_analyzer(bool enable) { m_enable_analyzer = enable; } +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ // For Perl bindings, to be used exclusively by unit tests. unsigned int layer_count() const { return m_layer_count; } @@ -241,9 +267,20 @@ protected: // Markers for the Pressure Equalizer to recognize the extrusion type. // The Pressure Equalizer removes the markers from the final G-code. bool m_enable_extrusion_role_markers; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + // Enableds the G-code Analyzer. + // Extended markers will be added during G-code generation. + // The G-code Analyzer will remove these comments from the final G-code. + bool m_enable_analyzer; +#else +//############################################################################################################ // Extended markers for the G-code Analyzer. // The G-code Analyzer will remove these comments from the final G-code. bool m_enable_analyzer_markers; +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ // How many times will change_layer() be called? // change_layer() will update the progress bar. unsigned int m_layer_count; @@ -256,6 +293,14 @@ protected: double m_volumetric_speed; // Support for the extrusion role markers. Which marker is active? ExtrusionRole m_last_extrusion_role; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + // Support for G-Code Analyzer + double m_last_mm3_per_mm; + float m_last_width; + float m_last_height; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ Point m_last_pos; bool m_last_pos_defined; @@ -277,9 +322,25 @@ protected: // Time estimator GCodeTimeEstimator m_time_estimator; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + // Analyzer + GCodeAnalyzer m_analyzer; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + // Write a string into a file. +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + void _write(FILE* file, const std::string& what) { this->_write(file, what.c_str()); } + void _write(FILE* file, const char *what); +#else +//############################################################################################################ void _write(FILE* file, const std::string& what) { this->_write(file, what.c_str(), what.size()); } void _write(FILE* file, const char *what, size_t size); +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ // Write a string into a file. // Add a newline, if the string does not end with a newline already. diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index ab2955eb5..467e2b6ae 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -4,11 +4,31 @@ #include "../libslic3r.h" #include "../PrintConfig.hpp" +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +#include "Print.hpp" +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ #include "Analyzer.hpp" +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +static const std::string AXIS_STR = "XYZE"; +static const float MMMIN_TO_MMSEC = 1.0f / 60.0f; +static const float INCHES_TO_MM = 25.4f; +static const float DEFAULT_FEEDRATE = 0.0f; +static const unsigned int DEFAULT_EXTRUDER_ID = 0; +static const Slic3r::Pointf3 DEFAULT_START_POSITION = Slic3r::Pointf3(0.0f, 0.0f, 0.0f); +static const float DEFAULT_START_EXTRUSION = 0.0f; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + namespace Slic3r { +//############################################################################################################ +#if !ENRICO_GCODE_PREVIEW +//############################################################################################################ void GCodeMovesDB::reset() { for (size_t i = 0; i < m_layers.size(); ++ i) @@ -322,5 +342,945 @@ void GCodeAnalyzer::push_to_output(const char *text, const size_t len, bool add_ output_buffer[output_buffer_length ++] = '\n'; output_buffer[output_buffer_length] = 0; } +//############################################################################################################ +#endif // !ENRICO_GCODE_PREVIEW +//############################################################################################################ + +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +const std::string GCodeAnalyzer::Extrusion_Role_Tag = "_ANALYZER_EXTR_ROLE:"; +const std::string GCodeAnalyzer::Mm3_Per_Mm_Tag = "_ANALYZER_MM3_PER_MM:"; +const std::string GCodeAnalyzer::Width_Tag = "_ANALYZER_WIDTH:"; +const std::string GCodeAnalyzer::Height_Tag = "_ANALYZER_HEIGHT:"; + +const double GCodeAnalyzer::Default_mm3_per_mm = 0.0; +const float GCodeAnalyzer::Default_Width = 0.0f; +const float GCodeAnalyzer::Default_Height = 0.0f; + +GCodeAnalyzer::Metadata::Metadata() + : extrusion_role(erNone) + , extruder_id(DEFAULT_EXTRUDER_ID) + , mm3_per_mm(GCodeAnalyzer::Default_mm3_per_mm) + , width(GCodeAnalyzer::Default_Width) + , height(GCodeAnalyzer::Default_Height) + , feedrate(DEFAULT_FEEDRATE) +{ +} + +GCodeAnalyzer::Metadata::Metadata(ExtrusionRole extrusion_role, unsigned int extruder_id, double mm3_per_mm, float width, float height, float feedrate) + : extrusion_role(extrusion_role) + , extruder_id(extruder_id) + , mm3_per_mm(mm3_per_mm) + , width(width) + , height(height) + , feedrate(feedrate) +{ +} + +bool GCodeAnalyzer::Metadata::operator != (const GCodeAnalyzer::Metadata& other) const +{ + if (extrusion_role != other.extrusion_role) + return true; + + if (extruder_id != other.extruder_id) + return true; + + if (mm3_per_mm != other.mm3_per_mm) + return true; + + if (width != other.width) + return true; + + if (height != other.height) + return true; + + if (feedrate != other.feedrate) + return true; + + return false; +} + +GCodeAnalyzer::GCodeMove::GCodeMove(GCodeMove::EType type, ExtrusionRole extrusion_role, unsigned int extruder_id, double mm3_per_mm, float width, float height, float feedrate, const Pointf3& start_position, const Pointf3& end_position, float delta_extruder) + : type(type) + , data(extrusion_role, extruder_id, mm3_per_mm, width, height, feedrate) + , start_position(start_position) + , end_position(end_position) + , delta_extruder(delta_extruder) +{ +} + +GCodeAnalyzer::GCodeMove::GCodeMove(GCodeMove::EType type, const GCodeAnalyzer::Metadata& data, const Pointf3& start_position, const Pointf3& end_position, float delta_extruder) + : type(type) + , data(data) + , start_position(start_position) + , end_position(end_position) + , delta_extruder(delta_extruder) +{ +} + +const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Color::Dummy(0.0f, 0.0f, 0.0f, 0.0f); + +GCodeAnalyzer::PreviewData::Color::Color() +{ + rgba[0] = 1.0f; + rgba[1] = 1.0f; + rgba[2] = 1.0f; + rgba[3] = 1.0f; +} + +GCodeAnalyzer::PreviewData::Color::Color(float r, float g, float b, float a) +{ + rgba[0] = r; + rgba[1] = g; + rgba[2] = b; + rgba[3] = a; +} + +GCodeAnalyzer::PreviewData::Extrusion::Layer::Layer(float z, const ExtrusionPaths& paths) + : z(z) + , paths(paths) +{ +} + +GCodeAnalyzer::PreviewData::Travel::Polyline::Polyline(EType type, EDirection direction, const Polyline3& polyline) + : type(type) + , direction(direction) + , polyline(polyline) +{ +} + +const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Range::Default_Colors[Colors_Count] = +{ + Color(0.043f, 0.173f, 0.478f, 1.0f), + Color(0.075f, 0.349f, 0.522f, 1.0f), + Color(0.110f, 0.533f, 0.569f, 1.0f), + Color(0.016f, 0.839f, 0.059f, 1.0f), + Color(0.667f, 0.949f, 0.000f, 1.0f), + Color(0.988f, 0.975f, 0.012f, 1.0f), + Color(0.961f, 0.808f, 0.039f, 1.0f), + Color(0.890f, 0.533f, 0.125f, 1.0f), + Color(0.820f, 0.408f, 0.188f, 1.0f), + Color(0.761f, 0.322f, 0.235f, 1.0f) +}; + +GCodeAnalyzer::PreviewData::Range::Range() +{ + reset(); +} + +void GCodeAnalyzer::PreviewData::Range::reset() +{ + min = FLT_MAX; + max = -FLT_MAX; +} + +bool GCodeAnalyzer::PreviewData::Range::empty() const +{ + return min == max; +} + +void GCodeAnalyzer::PreviewData::Range::update_from(float value) +{ + min = std::min(min, value); + max = std::max(max, value); +} + +void GCodeAnalyzer::PreviewData::Range::set_from(const Range& other) +{ + min = other.min; + max = other.max; +} + +const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::Range::get_color_at_max() const +{ + return colors[Colors_Count - 1]; +} + +const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::Range::get_color_at(float value) const +{ + return empty() ? get_color_at_max() : colors[clamp((unsigned int)0, Colors_Count - 1, unsigned int((value - min) / _step()))]; +} + +float GCodeAnalyzer::PreviewData::Range::_step() const +{ + return (max - min) / (float)Colors_Count; +} + +const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Extrusion::Default_Extrusion_Role_Colors[Num_Extrusion_Roles] = +{ + Color(0.0f, 0.0f, 0.0f, 1.0f), // erNone + Color(1.0f, 0.0f, 0.0f, 1.0f), // erPerimeter + Color(0.0f, 1.0f, 0.0f, 1.0f), // erExternalPerimeter + Color(0.0f, 0.0f, 1.0f, 1.0f), // erOverhangPerimeter + Color(1.0f, 1.0f, 0.0f, 1.0f), // erInternalInfill + Color(1.0f, 0.0f, 1.0f, 1.0f), // erSolidInfill + Color(0.0f, 1.0f, 1.0f, 1.0f), // erTopSolidInfill + Color(0.5f, 0.5f, 0.5f, 1.0f), // erBridgeInfill + Color(1.0f, 1.0f, 1.0f, 1.0f), // erGapFill + Color(0.5f, 0.0f, 0.0f, 1.0f), // erSkirt + Color(0.0f, 0.5f, 0.0f, 1.0f), // erSupportMaterial + Color(0.0f, 0.0f, 0.5f, 1.0f), // erSupportMaterialInterface + Color(0.0f, 0.0f, 0.0f, 1.0f) // erMixed +}; + +const GCodeAnalyzer::PreviewData::Extrusion::EViewType GCodeAnalyzer::PreviewData::Extrusion::Default_View_Type = GCodeAnalyzer::PreviewData::Extrusion::FeatureType; + +void GCodeAnalyzer::PreviewData::Extrusion::set_default() +{ + view_type = Default_View_Type; + + ::memcpy((void*)role_colors, (const void*)Default_Extrusion_Role_Colors, Num_Extrusion_Roles * sizeof(Color)); + ::memcpy((void*)ranges.height.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color)); + ::memcpy((void*)ranges.width.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color)); + ::memcpy((void*)ranges.feedrate.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color)); + + role_flags = 0; + for (unsigned int i = 0; i < Num_Extrusion_Roles; ++i) + { + role_flags += (unsigned int)::exp2((double)i); + } +} + +bool GCodeAnalyzer::PreviewData::Extrusion::is_role_flag_set(ExtrusionRole role) const +{ + if ((role < erPerimeter) || (erSupportMaterialInterface < role)) + return false; + + unsigned int flag = (unsigned int)::exp2((double)(role - erPerimeter)); + return (role_flags & flag) == flag; +} + +const float GCodeAnalyzer::PreviewData::Travel::Default_Width = 0.075f; +const float GCodeAnalyzer::PreviewData::Travel::Default_Height = 0.075f; +const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Travel::Default_Type_Colors[Num_Types] = +{ + Color(0.0f, 0.0f, 0.75f, 1.0f), // Move + Color(0.0f, 0.75f, 0.0f, 1.0f), // Extrude + Color(0.75f, 0.0f, 0.0f, 1.0f), // Retract +}; + +void GCodeAnalyzer::PreviewData::Travel::set_default() +{ + width = Default_Width; + height = Default_Height; + ::memcpy((void*)type_colors, (const void*)Default_Type_Colors, Num_Types * sizeof(Color)); + is_visible = false; +} + +void GCodeAnalyzer::PreviewData::Retraction::set_default() +{ + is_visible = false; +}; + +GCodeAnalyzer::PreviewData::PreviewData() +{ + set_default(); +} + +void GCodeAnalyzer::PreviewData::set_default() +{ + extrusion.set_default(); + travel.set_default(); + retraction.set_default(); +} + +void GCodeAnalyzer::PreviewData::reset() +{ + extrusion.layers.clear(); + travel.polylines.clear(); + retraction.positions.clear(); +} + +const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::get_extrusion_role_color(ExtrusionRole role) const +{ + return extrusion.role_colors[role]; +} + +const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::get_extrusion_height_color(float height) const +{ + return extrusion.ranges.height.get_color_at(height); +} + +const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::get_extrusion_width_color(float width) const +{ + return extrusion.ranges.width.get_color_at(width); +} + +const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::get_extrusion_feedrate_color(float feedrate) const +{ + return extrusion.ranges.feedrate.get_color_at(feedrate); +} + +GCodeAnalyzer::GCodeAnalyzer() +{ + reset(); +} + +void GCodeAnalyzer::reset() +{ + _set_units(Millimeters); + _set_positioning_xyz_type(Absolute); + _set_positioning_e_type(Relative); + _set_extrusion_role(erNone); + _set_extruder_id(DEFAULT_EXTRUDER_ID); + _set_mm3_per_mm(Default_mm3_per_mm); + _set_width(Default_Width); + _set_height(Default_Height); + _set_feedrate(DEFAULT_FEEDRATE); + _set_start_position(DEFAULT_START_POSITION); + _set_start_extrusion(DEFAULT_START_EXTRUSION); + _reset_axes_position(); + + m_moves_map.clear(); +} + +const std::string& GCodeAnalyzer::process_gcode(const std::string& gcode) +{ + m_process_output = ""; + + m_parser.parse_buffer(gcode, + [this](GCodeReader& reader, const GCodeReader::GCodeLine& line) + { this->_process_gcode_line(reader, line); }); + + return m_process_output; +} + +void GCodeAnalyzer::calc_gcode_preview_data(Print& print) +{ + // resets preview data + print.gcode_preview.reset(); + + // calculates extrusion layers + _calc_gcode_preview_extrusion_layers(print); + + // calculates travel + _calc_gcode_preview_travel(print); + + // calculates retractions + _calc_gcode_preview_retractions(print); +} + +void GCodeAnalyzer::_process_gcode_line(GCodeReader&, const GCodeReader::GCodeLine& line) +{ + // processes 'special' comments contained in line + if (_process_tags(line)) + return; + + // sets new start position/extrusion + _set_start_position(_get_end_position()); + _set_start_extrusion(_get_axis_position(E)); + + // processes 'normal' gcode lines + std::string cmd = line.cmd(); + if (cmd.length() > 1) + { + switch (::toupper(cmd[0])) + { + case 'G': + { + switch (::atoi(&cmd[1])) + { + case 1: // Move + { + _processG1(line); + break; + } + case 22: // Firmware controlled Retract + { + _processG22(line); + break; + } + case 23: // Firmware controlled Unretract + { + _processG23(line); + break; + } + case 90: // Set to Absolute Positioning + { + _processG90(line); + break; + } + case 91: // Set to Relative Positioning + { + _processG91(line); + break; + } + case 92: // Set Position + { + _processG92(line); + break; + } + } + + break; + } + case 'M': + { + switch (::atoi(&cmd[1])) + { + case 82: // Set extruder to absolute mode + { + _processM82(line); + break; + } + case 83: // Set extruder to relative mode + { + _processM83(line); + break; + } + } + + break; + } + case 'T': // Select Tools + { + _processT(line); + break; + } + } + } + + // puts the line back into the gcode + m_process_output += line.raw() + "\n"; +} + +// Returns the new absolute position on the given axis in dependence of the given parameters +float axis_absolute_position_from_G1_line(GCodeAnalyzer::EAxis axis, const GCodeReader::GCodeLine& lineG1, GCodeAnalyzer::EUnits units, GCodeAnalyzer::EPositioningType type, float current_absolute_position) +{ + float lengthsScaleFactor = (units == GCodeAnalyzer::Inches) ? INCHES_TO_MM : 1.0f; + if (lineG1.has(Slic3r::Axis(axis))) + { + float ret = lineG1.value(Slic3r::Axis(axis)) * lengthsScaleFactor; + return (type == GCodeAnalyzer::Absolute) ? ret : current_absolute_position + ret; + } + else + return current_absolute_position; +} + +void GCodeAnalyzer::_processG1(const GCodeReader::GCodeLine& line) +{ + // updates axes positions from line + EUnits units = _get_units(); + float new_pos[Num_Axis]; + for (unsigned char a = X; a < Num_Axis; ++a) + { + new_pos[a] = axis_absolute_position_from_G1_line((EAxis)a, line, units, (a == E) ? _get_positioning_e_type() : _get_positioning_xyz_type(), _get_axis_position((EAxis)a)); + } + + // updates feedrate from line, if present + if (line.has_f()) + _set_feedrate(line.f() * MMMIN_TO_MMSEC); + + // calculates movement deltas + float delta_pos[Num_Axis]; + for (unsigned char a = X; a < Num_Axis; ++a) + { + delta_pos[a] = new_pos[a] - _get_axis_position((EAxis)a); + } + + // Detects move type + GCodeMove::EType type = GCodeMove::Noop; + + if (delta_pos[E] < 0.0f) + { + if ((delta_pos[X] != 0.0f) || (delta_pos[Y] != 0.0f) || (delta_pos[Z] != 0.0f)) + type = GCodeMove::Move; + else + type = GCodeMove::Retract; + } + else if (delta_pos[E] > 0.0f) + { + if ((delta_pos[X] == 0.0f) && (delta_pos[Y] == 0.0f) && (delta_pos[Z] == 0.0f)) + type = GCodeMove::Unretract; + else if ((delta_pos[X] != 0.0f) || (delta_pos[Y] != 0.0f)) + type = GCodeMove::Extrude; + } + else if ((delta_pos[X] != 0.0f) || (delta_pos[Y] != 0.0f) || (delta_pos[Z] != 0.0f)) + type = GCodeMove::Move; + + ExtrusionRole role = _get_extrusion_role(); + if ((type == GCodeMove::Extrude) && ((_get_width() == 0.0f) || (_get_height() == 0.0f) || (role < erPerimeter) || (erSupportMaterialInterface < role))) + type = GCodeMove::Move; + + // updates axis positions + for (unsigned char a = X; a < Num_Axis; ++a) + { + _set_axis_position((EAxis)a, new_pos[a]); + } + + // stores the move + if (type != GCodeMove::Noop) + _store_move(type); +} + +void GCodeAnalyzer::_processG22(const GCodeReader::GCodeLine& line) +{ + // stores retract move + _store_move(GCodeMove::Retract); +} + +void GCodeAnalyzer::_processG23(const GCodeReader::GCodeLine& line) +{ + // stores unretract move + _store_move(GCodeMove::Unretract); +} + +void GCodeAnalyzer::_processG90(const GCodeReader::GCodeLine& line) +{ + _set_positioning_xyz_type(Absolute); +} + +void GCodeAnalyzer::_processG91(const GCodeReader::GCodeLine& line) +{ + _set_positioning_xyz_type(Relative); +} + +void GCodeAnalyzer::_processG92(const GCodeReader::GCodeLine& line) +{ + float lengthsScaleFactor = (_get_units() == Inches) ? INCHES_TO_MM : 1.0f; + bool anyFound = false; + + if (line.has_x()) + { + _set_axis_position(X, line.x() * lengthsScaleFactor); + anyFound = true; + } + + if (line.has_y()) + { + _set_axis_position(Y, line.y() * lengthsScaleFactor); + anyFound = true; + } + + if (line.has_z()) + { + _set_axis_position(Z, line.z() * lengthsScaleFactor); + anyFound = true; + } + + if (line.has_e()) + { + _set_axis_position(E, line.e() * lengthsScaleFactor); + anyFound = true; + } + + if (!anyFound) + { + for (unsigned char a = X; a < Num_Axis; ++a) + { + _set_axis_position((EAxis)a, 0.0f); + } + } +} + +void GCodeAnalyzer::_processM82(const GCodeReader::GCodeLine& line) +{ + _set_positioning_e_type(Absolute); +} + +void GCodeAnalyzer::_processM83(const GCodeReader::GCodeLine& line) +{ + _set_positioning_e_type(Relative); +} + +void GCodeAnalyzer::_processT(const GCodeReader::GCodeLine& line) +{ + std::string cmd = line.cmd(); + if (cmd.length() > 1) + { + int id = (int)::strtol(cmd.substr(1).c_str(), nullptr, 10); + // todo - add id validity check ? + if (_get_extruder_id() != id) + { + _set_extruder_id(id); + + // stores tool change move + _store_move(GCodeMove::Tool_change); + } + } +} + +bool GCodeAnalyzer::_process_tags(const GCodeReader::GCodeLine& line) +{ + std::string comment = line.comment(); + + // extrusion role tag + size_t pos = comment.find(Extrusion_Role_Tag); + if (pos != comment.npos) + { + _process_extrusion_role_tag(comment, pos); + return true; + } + + // mm3 per mm tag + pos = comment.find(Mm3_Per_Mm_Tag); + if (pos != comment.npos) + { + _process_mm3_per_mm_tag(comment, pos); + return true; + } + + // width tag + pos = comment.find(Width_Tag); + if (pos != comment.npos) + { + _process_width_tag(comment, pos); + return true; + } + + // height tag + pos = comment.find(Height_Tag); + if (pos != comment.npos) + { + _process_height_tag(comment, pos); + return true; + } + + return false; +} + +void GCodeAnalyzer::_process_extrusion_role_tag(const std::string& comment, size_t pos) +{ + int role = (int)::strtol(comment.substr(pos + Extrusion_Role_Tag.length()).c_str(), nullptr, 10); + if (_is_valid_extrusion_role(role)) + _set_extrusion_role((ExtrusionRole)role); + else + { + // todo: show some error ? + } +} + +void GCodeAnalyzer::_process_mm3_per_mm_tag(const std::string& comment, size_t pos) +{ + _set_mm3_per_mm(::strtod(comment.substr(pos + Mm3_Per_Mm_Tag.length()).c_str(), nullptr)); +} + +void GCodeAnalyzer::_process_width_tag(const std::string& comment, size_t pos) +{ + _set_width((float)::strtod(comment.substr(pos + Width_Tag.length()).c_str(), nullptr)); +} + +void GCodeAnalyzer::_process_height_tag(const std::string& comment, size_t pos) +{ + _set_height((float)::strtod(comment.substr(pos + Height_Tag.length()).c_str(), nullptr)); +} + +void GCodeAnalyzer::_set_units(GCodeAnalyzer::EUnits units) +{ + m_state.units = units; +} + +GCodeAnalyzer::EUnits GCodeAnalyzer::_get_units() const +{ + return m_state.units; +} + +void GCodeAnalyzer::_set_positioning_xyz_type(GCodeAnalyzer::EPositioningType type) +{ + m_state.positioning_xyz_type = type; +} + +GCodeAnalyzer::EPositioningType GCodeAnalyzer::_get_positioning_xyz_type() const +{ + return m_state.positioning_xyz_type; +} + +void GCodeAnalyzer::_set_positioning_e_type(GCodeAnalyzer::EPositioningType type) +{ + m_state.positioning_e_type = type; +} + +GCodeAnalyzer::EPositioningType GCodeAnalyzer::_get_positioning_e_type() const +{ + return m_state.positioning_e_type; +} + +void GCodeAnalyzer::_set_extrusion_role(ExtrusionRole extrusion_role) +{ + m_state.data.extrusion_role = extrusion_role; +} + +ExtrusionRole GCodeAnalyzer::_get_extrusion_role() const +{ + return m_state.data.extrusion_role; +} + +void GCodeAnalyzer::_set_extruder_id(unsigned int id) +{ + m_state.data.extruder_id = id; +} + +unsigned int GCodeAnalyzer::_get_extruder_id() const +{ + return m_state.data.extruder_id; +} + +void GCodeAnalyzer::_set_mm3_per_mm(double value) +{ + m_state.data.mm3_per_mm = value; +} + +double GCodeAnalyzer::_get_mm3_per_mm() const +{ + return m_state.data.mm3_per_mm; +} + +void GCodeAnalyzer::_set_width(float width) +{ + m_state.data.width = width; +} + +float GCodeAnalyzer::_get_width() const +{ + return m_state.data.width; +} + +void GCodeAnalyzer::_set_height(float height) +{ + m_state.data.height = height; +} + +float GCodeAnalyzer::_get_height() const +{ + return m_state.data.height; +} + +void GCodeAnalyzer::_set_feedrate(float feedrate_mm_sec) +{ + m_state.data.feedrate = feedrate_mm_sec; +} + +float GCodeAnalyzer::_get_feedrate() const +{ + return m_state.data.feedrate; +} + +void GCodeAnalyzer::_set_axis_position(EAxis axis, float position) +{ + m_state.position[axis] = position; +} + +float GCodeAnalyzer::_get_axis_position(EAxis axis) const +{ + return m_state.position[axis]; +} + +void GCodeAnalyzer::_reset_axes_position() +{ + ::memset((void*)m_state.position, 0, Num_Axis * sizeof(float)); +} + +void GCodeAnalyzer::_set_start_position(const Pointf3& position) +{ + m_state.start_position = position; +} + +const Pointf3& GCodeAnalyzer::_get_start_position() const +{ + return m_state.start_position; +} + +void GCodeAnalyzer::_set_start_extrusion(float extrusion) +{ + m_state.start_extrusion = extrusion; +} + +float GCodeAnalyzer::_get_start_extrusion() const +{ + return m_state.start_extrusion; +} + +float GCodeAnalyzer::_get_delta_extrusion() const +{ + return _get_axis_position(E) - m_state.start_extrusion; +} + +Pointf3 GCodeAnalyzer::_get_end_position() const +{ + return Pointf3(m_state.position[X], m_state.position[Y], m_state.position[Z]); +} + +void GCodeAnalyzer::_store_move(GCodeAnalyzer::GCodeMove::EType type) +{ + // if type non mapped yet, map it + TypeToMovesMap::iterator it = m_moves_map.find(type); + if (it == m_moves_map.end()) + it = m_moves_map.insert(TypeToMovesMap::value_type(type, GCodeMovesList())).first; + + // store move + it->second.emplace_back(type, _get_extrusion_role(), _get_extruder_id(), _get_mm3_per_mm(), _get_width(), _get_height(), _get_feedrate(), _get_start_position(), _get_end_position(), _get_delta_extrusion()); +} + +bool GCodeAnalyzer::_is_valid_extrusion_role(int value) const +{ + return ((int)erNone <= value) && (value <= (int)erMixed); +} + +void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(Print& print) +{ + struct Helper + { + static PreviewData::Extrusion::Layer& get_layer_at_z(PreviewData::Extrusion::LayersList& layers, float z) + { + for (PreviewData::Extrusion::Layer& layer : layers) + { + // if layer found, return it + if (layer.z == z) + return layer; + } + + // if layer not found, create and return it + layers.emplace_back(z, ExtrusionPaths()); + return layers.back(); + } + + static void store_polyline(const Polyline& polyline, const Metadata& data, float z, Print& print) + { + // if the polyline is valid, create the extrusion path from it and store it + if (polyline.is_valid()) + { + ExtrusionPath path(data.extrusion_role, data.mm3_per_mm, data.width, data.height); + path.polyline = polyline; + path.feedrate = data.feedrate; + + get_layer_at_z(print.gcode_preview.extrusion.layers, z).paths.push_back(path); + } + } + }; + + TypeToMovesMap::iterator extrude_moves = m_moves_map.find(GCodeMove::Extrude); + if (extrude_moves == m_moves_map.end()) + return; + + Metadata data; + float z = FLT_MAX; + Polyline polyline; + Pointf3 position(FLT_MAX, FLT_MAX, FLT_MAX); + PreviewData::Range height_range; + PreviewData::Range width_range; + PreviewData::Range feedrate_range; + + // constructs the polylines while traversing the moves + for (const GCodeMove& move : extrude_moves->second) + { + if ((data != move.data) || (data.feedrate != move.data.feedrate) || (z != move.start_position.z) || (position != move.start_position)) + { + // store current polyline + Helper::store_polyline(polyline, data, z, print); + + // reset current polyline + polyline = Polyline(); + + // add both vertices of the move + polyline.append(Point(scale_(move.start_position.x), scale_(move.start_position.y))); + polyline.append(Point(scale_(move.end_position.x), scale_(move.end_position.y))); + + // update current values + data = move.data; + z = move.start_position.z; + height_range.update_from(move.data.height); + width_range.update_from(move.data.width); + feedrate_range.update_from(move.data.feedrate); + } + else + // append end vertex of the move to current polyline + polyline.append(Point(scale_(move.end_position.x), scale_(move.end_position.y))); + + // update current values + position = move.end_position; + } + + // store last polyline + Helper::store_polyline(polyline, data, z, print); + + // updates preview ranges data + print.gcode_preview.extrusion.ranges.height.set_from(height_range); + print.gcode_preview.extrusion.ranges.width.set_from(width_range); + print.gcode_preview.extrusion.ranges.feedrate.set_from(feedrate_range); +} + +void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) +{ + struct Helper + { + static void store_polyline(const Polyline3& polyline, PreviewData::Travel::EType type, PreviewData::Travel::Polyline::EDirection direction, Print& print) + { + // if the polyline is valid, store it + if (polyline.is_valid()) + print.gcode_preview.travel.polylines.emplace_back(type, direction, polyline); + } + }; + + TypeToMovesMap::iterator travel_moves = m_moves_map.find(GCodeMove::Move); + if (travel_moves == m_moves_map.end()) + return; + + Polyline3 polyline; + Pointf3 position(FLT_MAX, FLT_MAX, FLT_MAX); + PreviewData::Travel::EType type = PreviewData::Travel::Num_Types; + PreviewData::Travel::Polyline::EDirection direction = PreviewData::Travel::Polyline::Num_Directions; + + // constructs the polylines while traversing the moves + for (const GCodeMove& move : travel_moves->second) + { + PreviewData::Travel::EType move_type = (move.delta_extruder < 0.0f) ? PreviewData::Travel::Retract : ((move.delta_extruder > 0.0f) ? PreviewData::Travel::Extrude : PreviewData::Travel::Move); + PreviewData::Travel::Polyline::EDirection move_direction = ((move.start_position.x != move.end_position.x) || (move.start_position.y != move.end_position.y)) ? PreviewData::Travel::Polyline::Generic : PreviewData::Travel::Polyline::Vertical; + + if ((type != move_type) || (direction != move_direction) || (position != move.start_position)) + { + // store current polyline + Helper::store_polyline(polyline, type, direction, print); + + // reset current polyline + polyline = Polyline3(); + + // add both vertices of the move + polyline.append(Point3(scale_(move.start_position.x), scale_(move.start_position.y), scale_(move.start_position.z))); + polyline.append(Point3(scale_(move.end_position.x), scale_(move.end_position.y), scale_(move.end_position.z))); + } + else + // append end vertex of the move to current polyline + polyline.append(Point3(scale_(move.end_position.x), scale_(move.end_position.y), scale_(move.end_position.z))); + + // update current values + position = move.end_position; + type = move_type; + } + + // store last polyline + Helper::store_polyline(polyline, type, direction, print); +} + +void GCodeAnalyzer::_calc_gcode_preview_retractions(Print& print) +{ + TypeToMovesMap::iterator retraction_moves = m_moves_map.find(GCodeMove::Retract); + if (retraction_moves == m_moves_map.end()) + return; + + for (const GCodeMove& move : retraction_moves->second) + { + print.gcode_preview.retraction.positions.emplace_back(scale_(move.start_position.x), scale_(move.start_position.y), scale_(move.start_position.z)); + } + + int a = 0; +} + +GCodeAnalyzer::PreviewData::Color operator + (const GCodeAnalyzer::PreviewData::Color& c1, const GCodeAnalyzer::PreviewData::Color& c2) +{ + return GCodeAnalyzer::PreviewData::Color(clamp(0.0f, 1.0f, c1.rgba[0] + c2.rgba[0]), + clamp(0.0f, 1.0f, c1.rgba[1] + c2.rgba[1]), + clamp(0.0f, 1.0f, c1.rgba[2] + c2.rgba[2]), + clamp(0.0f, 1.0f, c1.rgba[3] + c2.rgba[3])); +} + +GCodeAnalyzer::PreviewData::Color operator * (float f, const GCodeAnalyzer::PreviewData::Color& color) +{ + return GCodeAnalyzer::PreviewData::Color(clamp(0.0f, 1.0f, f * color.rgba[0]), + clamp(0.0f, 1.0f, f * color.rgba[1]), + clamp(0.0f, 1.0f, f * color.rgba[2]), + clamp(0.0f, 1.0f, f * color.rgba[3])); +} +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ } // namespace Slic3r diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index 9e84e33c4..8236772fb 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -1,12 +1,28 @@ -#ifndef slic3r_GCode_PressureEqualizer_hpp_ -#define slic3r_GCode_PressureEqualizer_hpp_ +#ifndef slic3r_GCode_Analyzer_hpp_ +#define slic3r_GCode_Analyzer_hpp_ #include "../libslic3r.h" #include "../PrintConfig.hpp" #include "../ExtrusionEntity.hpp" +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +#include "Point.hpp" +#include "GCodeReader.hpp" +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + namespace Slic3r { +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + class Print; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + +//############################################################################################################ +#if !ENRICO_GCODE_PREVIEW +//############################################################################################################ enum GCodeMoveType { GCODE_MOVE_TYPE_NOOP, @@ -146,7 +162,367 @@ private: // Push the text to the end of the output_buffer. void push_to_output(const char *text, const size_t len, bool add_eol = true); }; +//############################################################################################################ +#endif // !ENRICO_GCODE_PREVIEW +//############################################################################################################ + +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +class GCodeAnalyzer +{ +public: + static const std::string Extrusion_Role_Tag; + static const std::string Mm3_Per_Mm_Tag; + static const std::string Width_Tag; + static const std::string Height_Tag; + + static const double Default_mm3_per_mm; + static const float Default_Width; + static const float Default_Height; + + enum EUnits : unsigned char + { + Millimeters, + Inches + }; + + enum EAxis : unsigned char + { + X, + Y, + Z, + E, + Num_Axis + }; + + enum EPositioningType : unsigned char + { + Absolute, + Relative + }; + + struct Metadata + { + ExtrusionRole extrusion_role; + unsigned int extruder_id; + double mm3_per_mm; + float width; + float height; + float feedrate; + + Metadata(); + Metadata(ExtrusionRole extrusion_role, unsigned int extruder_id, double mm3_per_mm, float width, float height, float feedrate); + + bool operator != (const Metadata& other) const; + }; + + struct GCodeMove + { + enum EType : unsigned char + { + Noop, + Retract, + Unretract, + Tool_change, + Move, + Extrude, + Num_Types + }; + + EType type; + Metadata data; + Pointf3 start_position; + Pointf3 end_position; + float delta_extruder; + + GCodeMove(EType type, ExtrusionRole extrusion_role, unsigned int extruder_id, double mm3_per_mm, float width, float height, float feedrate, const Pointf3& start_position, const Pointf3& end_position, float delta_extruder); + GCodeMove(EType type, const Metadata& data, const Pointf3& start_position, const Pointf3& end_position, float delta_extruder); + }; + + typedef std::vector GCodeMovesList; + typedef std::map TypeToMovesMap; + +private: + struct State + { + EUnits units; + EPositioningType positioning_xyz_type; + EPositioningType positioning_e_type; + Metadata data; + Pointf3 start_position; + float start_extrusion; + float position[Num_Axis]; + }; + +public: + struct PreviewData + { + struct Color + { + float rgba[4]; + + Color(); + Color(float r, float g, float b, float a); + + static const Color Dummy; + }; + + struct Range + { + static const unsigned int Colors_Count = 10; + static const Color Default_Colors[Colors_Count]; + + Color colors[Colors_Count]; + float min; + float max; + + Range(); + + void reset(); + bool empty() const; + void update_from(float value); + void set_from(const Range& other); + + const Color& get_color_at(float value) const; + const Color& get_color_at_max() const; + + private: + float _step() const; + }; + + struct Extrusion + { + enum EViewType : unsigned char + { + FeatureType, + Height, + Width, + Feedrate, + Num_View_Types + }; + + static const unsigned int Num_Extrusion_Roles = (unsigned int)erMixed + 1; + static const Color Default_Extrusion_Role_Colors[Num_Extrusion_Roles]; + static const EViewType Default_View_Type; + + struct Ranges + { + Range height; + Range width; + Range feedrate; + }; + + struct Layer + { + float z; + ExtrusionPaths paths; + + Layer(float z, const ExtrusionPaths& paths); + }; + + typedef std::vector LayersList; + + EViewType view_type; + Color role_colors[Num_Extrusion_Roles]; + Ranges ranges; + LayersList layers; + unsigned int role_flags; + + void set_default(); + bool is_role_flag_set(ExtrusionRole role) const; + }; + + struct Travel + { + enum EType : unsigned char + { + Move, + Extrude, + Retract, + Num_Types + }; + + static const float Default_Width; + static const float Default_Height; + static const Color Default_Type_Colors[Num_Types]; + + struct Polyline + { + enum EDirection + { + Vertical, + Generic, + Num_Directions + }; + + EType type; + EDirection direction; + Polyline3 polyline; + + Polyline(EType type, EDirection direction, const Polyline3& polyline); + }; + + typedef std::vector PolylinesList; + + PolylinesList polylines; + float width; + float height; + Color type_colors[Num_Types]; + bool is_visible; + + void set_default(); + }; + + struct Retraction + { + Points3 positions; + bool is_visible; + + void set_default(); + }; + + Extrusion extrusion; + Travel travel; + Retraction retraction; + + PreviewData(); + + void set_default(); + void reset(); + + const Color& get_extrusion_role_color(ExtrusionRole role) const; + const Color& get_extrusion_height_color(float height) const; + const Color& get_extrusion_width_color(float width) const; + const Color& get_extrusion_feedrate_color(float feedrate) const; + }; + +private: + State m_state; + GCodeReader m_parser; + TypeToMovesMap m_moves_map; + + // The output of process_layer() + std::string m_process_output; + +public: + GCodeAnalyzer(); + + // Reinitialize the analyzer + void reset(); + + // Adds the gcode contained in the given string to the analysis and returns it after removing the workcodes + const std::string& process_gcode(const std::string& gcode); + + // Calculates all data needed for gcode visualization + void calc_gcode_preview_data(Print& print); + +private: + // Processes the given gcode line + void _process_gcode_line(GCodeReader& reader, const GCodeReader::GCodeLine& line); + + // Move + void _processG1(const GCodeReader::GCodeLine& line); + + // Firmware controlled Retract + void _processG22(const GCodeReader::GCodeLine& line); + + // Firmware controlled Unretract + void _processG23(const GCodeReader::GCodeLine& line); + + // Set to Absolute Positioning + void _processG90(const GCodeReader::GCodeLine& line); + + // Set to Relative Positioning + void _processG91(const GCodeReader::GCodeLine& line); + + // Set Position + void _processG92(const GCodeReader::GCodeLine& line); + + // Set extruder to absolute mode + void _processM82(const GCodeReader::GCodeLine& line); + + // Set extruder to relative mode + void _processM83(const GCodeReader::GCodeLine& line); + + // Processes T line (Select Tool) + void _processT(const GCodeReader::GCodeLine& line); + + // Processes the tags + // Returns true if any tag has been processed + bool _process_tags(const GCodeReader::GCodeLine& line); + + // Processes extrusion role tag + void _process_extrusion_role_tag(const std::string& comment, size_t pos); + + // Processes mm3_per_mm tag + void _process_mm3_per_mm_tag(const std::string& comment, size_t pos); + + // Processes width tag + void _process_width_tag(const std::string& comment, size_t pos); + + // Processes height tag + void _process_height_tag(const std::string& comment, size_t pos); + + void _set_units(EUnits units); + EUnits _get_units() const; + + void _set_positioning_xyz_type(EPositioningType type); + EPositioningType _get_positioning_xyz_type() const; + + void _set_positioning_e_type(EPositioningType type); + EPositioningType _get_positioning_e_type() const; + + void _set_extrusion_role(ExtrusionRole extrusion_role); + ExtrusionRole _get_extrusion_role() const; + + void _set_extruder_id(unsigned int id); + unsigned int _get_extruder_id() const; + + void _set_mm3_per_mm(double value); + double _get_mm3_per_mm() const; + + void _set_width(float width); + float _get_width() const; + + void _set_height(float height); + float _get_height() const; + + void _set_feedrate(float feedrate_mm_sec); + float _get_feedrate() const; + + void _set_axis_position(EAxis axis, float position); + float _get_axis_position(EAxis axis) const; + + // Sets axes position to zero + void _reset_axes_position(); + + void _set_start_position(const Pointf3& position); + const Pointf3& _get_start_position() const; + + void _set_start_extrusion(float extrusion); + float _get_start_extrusion() const; + float _get_delta_extrusion() const; + + // Returns current xyz position (from m_state.position[]) + Pointf3 _get_end_position() const; + + // Adds a new move with the given data + void _store_move(GCodeMove::EType type); + + // Checks if the given int is a valid extrusion role (contained into enum ExtrusionRole) + bool _is_valid_extrusion_role(int value) const; + + void _calc_gcode_preview_extrusion_layers(Print& print); + void _calc_gcode_preview_travel(Print& print); + void _calc_gcode_preview_retractions(Print& print); +}; + +GCodeAnalyzer::PreviewData::Color operator + (const GCodeAnalyzer::PreviewData::Color& c1, const GCodeAnalyzer::PreviewData::Color& c2); +GCodeAnalyzer::PreviewData::Color operator * (float f, const GCodeAnalyzer::PreviewData::Color& color); + +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ } // namespace Slic3r -#endif /* slic3r_GCode_PressureEqualizer_hpp_ */ +#endif /* slic3r_GCode_Analyzer_hpp_ */ diff --git a/xs/src/libslic3r/Line.cpp b/xs/src/libslic3r/Line.cpp index c7afc80c7..a4d36d38b 100644 --- a/xs/src/libslic3r/Line.cpp +++ b/xs/src/libslic3r/Line.cpp @@ -218,6 +218,20 @@ Line::ccw(const Point& point) const return point.ccw(*this); } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +double Line3::length() const +{ + return a.distance_to(b); +} + +Vector3 Line3::vector() const +{ + return Vector3(b.x - a.x, b.y - a.y, b.z - a.z); +} +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + Pointf3 Linef3::intersect_plane(double z) const { diff --git a/xs/src/libslic3r/Line.hpp b/xs/src/libslic3r/Line.hpp index 1be508f11..514a9ca04 100644 --- a/xs/src/libslic3r/Line.hpp +++ b/xs/src/libslic3r/Line.hpp @@ -7,10 +7,20 @@ namespace Slic3r { class Line; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +class Line3; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ class Linef3; class Polyline; class ThickLine; typedef std::vector Lines; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +typedef std::vector Lines3; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ typedef std::vector ThickLines; class Line @@ -56,6 +66,23 @@ class ThickLine : public Line ThickLine(Point _a, Point _b) : Line(_a, _b), a_width(0), b_width(0) {}; }; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +class Line3 +{ +public: + Point3 a; + Point3 b; + + Line3() {} + Line3(const Point3& _a, const Point3& _b) : a(_a), b(_b) {} + + double length() const; + Vector3 vector() const; +}; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + class Linef { public: diff --git a/xs/src/libslic3r/MultiPoint.cpp b/xs/src/libslic3r/MultiPoint.cpp index 7929747a0..54c639a96 100644 --- a/xs/src/libslic3r/MultiPoint.cpp +++ b/xs/src/libslic3r/MultiPoint.cpp @@ -214,6 +214,65 @@ MultiPoint::_douglas_peucker(const Points &points, const double tolerance) return results; } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +void MultiPoint3::translate(double x, double y) +{ + for (Point3& p : points) + { + p.translate(x, y); + } +} + +void MultiPoint3::translate(const Point& vector) +{ + translate(vector.x, vector.y); +} + +double MultiPoint3::length() const +{ + Lines3 lines = this->lines(); + double len = 0.0; + for (const Line3& line : lines) + { + len += line.length(); + } + return len; +} + +BoundingBox3 MultiPoint3::bounding_box() const +{ + return BoundingBox3(points); +} + +bool MultiPoint3::remove_duplicate_points() +{ + size_t j = 0; + for (size_t i = 1; i < points.size(); ++i) + { + if (points[j].coincides_with(points[i])) + { + // Just increase index i. + } + else + { + ++j; + if (j < i) + points[j] = points[i]; + } + } + + if (++j < points.size()) + { + points.erase(points.begin() + j, points.end()); + return true; + } + + return false; +} +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + BoundingBox get_extents(const MultiPoint &mp) { return BoundingBox(mp.points); diff --git a/xs/src/libslic3r/MultiPoint.hpp b/xs/src/libslic3r/MultiPoint.hpp index 3d1346e4c..ed5bad3a8 100644 --- a/xs/src/libslic3r/MultiPoint.hpp +++ b/xs/src/libslic3r/MultiPoint.hpp @@ -10,6 +10,11 @@ namespace Slic3r { class BoundingBox; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +class BoundingBox3; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ class MultiPoint { @@ -79,6 +84,29 @@ public: static Points _douglas_peucker(const Points &points, const double tolerance); }; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +class MultiPoint3 +{ +public: + Points3 points; + + void append(const Point3& point) { this->points.push_back(point); } + + void translate(double x, double y); + void translate(const Point& vector); + virtual Lines3 lines() const = 0; + double length() const; + bool is_valid() const { return this->points.size() >= 2; } + + BoundingBox3 bounding_box() const; + + // Remove exact duplicates, return true if any duplicate has been removed. + bool remove_duplicate_points(); +}; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + extern BoundingBox get_extents(const MultiPoint &mp); extern BoundingBox get_extents_rotated(const std::vector &points, double angle); extern BoundingBox get_extents_rotated(const MultiPoint &mp, double angle); diff --git a/xs/src/libslic3r/Point.hpp b/xs/src/libslic3r/Point.hpp index 77e07bec8..a322bc4fa 100644 --- a/xs/src/libslic3r/Point.hpp +++ b/xs/src/libslic3r/Point.hpp @@ -14,14 +14,29 @@ class Line; class Linef; class MultiPoint; class Point; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +class Point3; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ class Pointf; class Pointf3; typedef Point Vector; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +typedef Point3 Vector3; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ typedef Pointf Vectorf; typedef Pointf3 Vectorf3; typedef std::vector Points; typedef std::vector PointPtrs; typedef std::vector PointConstPtrs; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +typedef std::vector Points3; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ typedef std::vector Pointfs; typedef std::vector Pointf3s; @@ -186,10 +201,24 @@ public: static Point3 new_scale(coordf_t x, coordf_t y, coordf_t z) { return Point3(coord_t(scale_(x)), coord_t(scale_(y)), coord_t(scale_(z))); } bool operator==(const Point3 &rhs) const { return this->x == rhs.x && this->y == rhs.y && this->z == rhs.z; } bool operator!=(const Point3 &rhs) const { return ! (*this == rhs); } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + bool coincides_with(const Point3& rhs) const { return this->x == rhs.x && this->y == rhs.y && this->z == rhs.z; } +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ private: // Hide the following inherited methods: +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + bool operator==(const Point &rhs) const; + bool operator!=(const Point &rhs) const; +#else +//############################################################################################################ bool operator==(const Point &rhs); bool operator!=(const Point &rhs); +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ }; std::ostream& operator<<(std::ostream &stm, const Pointf &pointf); @@ -244,6 +273,11 @@ public: static Pointf3 new_unscale(coord_t x, coord_t y, coord_t z) { return Pointf3(unscale(x), unscale(y), unscale(z)); }; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + static Pointf3 new_unscale(const Point3& p) { return Pointf3(unscale(p.x), unscale(p.y), unscale(p.z)); } +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ void scale(double factor); void translate(const Vectorf3 &vector); void translate(double x, double y, double z); @@ -256,10 +290,36 @@ public: private: // Hide the following inherited methods: +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + bool operator==(const Pointf &rhs) const; + bool operator!=(const Pointf &rhs) const; +#else +//############################################################################################################ bool operator==(const Pointf &rhs); bool operator!=(const Pointf &rhs); +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ }; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +inline Pointf3 operator+(const Pointf3& p1, const Pointf3& p2) { return Pointf3(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z); } +inline Pointf3 operator-(const Pointf3& p1, const Pointf3& p2) { return Pointf3(p1.x - p2.x, p1.y - p2.y, p1.z - p2.z); } +inline Pointf3 operator-(const Pointf3& p) { return Pointf3(-p.x, -p.y, -p.z); } +inline Pointf3 operator*(double scalar, const Pointf3& p) { return Pointf3(scalar * p.x, scalar * p.y, scalar * p.z); } +inline Pointf3 operator*(const Pointf3& p, double scalar) { return Pointf3(scalar * p.x, scalar * p.y, scalar * p.z); } +inline Pointf3 cross(const Pointf3& v1, const Pointf3& v2) { return Pointf3(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x); } +inline coordf_t dot(const Pointf3& v1, const Pointf3& v2) { return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; } +inline Pointf3 normalize(const Pointf3& v) +{ + coordf_t len = ::sqrt(sqr(v.x) + sqr(v.y) + sqr(v.z)); + return (len != 0.0) ? 1.0 / len * v : Pointf3(0.0, 0.0, 0.0); +} +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + template inline TO convert_to(const Point &src) { return TO(typename TO::coord_type(src.x), typename TO::coord_type(src.y)); } template inline TO convert_to(const Pointf &src) { return TO(typename TO::coord_type(src.x), typename TO::coord_type(src.y)); } template inline TO convert_to(const Point3 &src) { return TO(typename TO::coord_type(src.x), typename TO::coord_type(src.y), typename TO::coord_type(src.z)); } diff --git a/xs/src/libslic3r/Polyline.cpp b/xs/src/libslic3r/Polyline.cpp index 672777ce1..9462332ff 100644 --- a/xs/src/libslic3r/Polyline.cpp +++ b/xs/src/libslic3r/Polyline.cpp @@ -278,4 +278,22 @@ ThickPolyline::reverse() std::swap(this->endpoints.first, this->endpoints.second); } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +Lines3 Polyline3::lines() const +{ + Lines3 lines; + if (points.size() >= 2) + { + lines.reserve(points.size() - 1); + for (Points3::const_iterator it = points.begin(); it != points.end() - 1; ++it) + { + lines.emplace_back(*it, *(it + 1)); + } + } + return lines; +} +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + } diff --git a/xs/src/libslic3r/Polyline.hpp b/xs/src/libslic3r/Polyline.hpp index ac59c6378..95ee72d0c 100644 --- a/xs/src/libslic3r/Polyline.hpp +++ b/xs/src/libslic3r/Polyline.hpp @@ -129,6 +129,18 @@ class ThickPolyline : public Polyline { void reverse(); }; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +class Polyline3 : public MultiPoint3 +{ +public: + virtual Lines3 lines() const; +}; + +typedef std::vector Polylines3; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + } #endif diff --git a/xs/src/libslic3r/Print.cpp b/xs/src/libslic3r/Print.cpp index 773998394..a6cb09e6d 100644 --- a/xs/src/libslic3r/Print.cpp +++ b/xs/src/libslic3r/Print.cpp @@ -66,6 +66,41 @@ bool Print::reload_model_instances() return invalidated; } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +void Print::clear_gcode_preview_data() +{ + gcode_preview.reset(); +} + +void Print::set_gcode_preview_type(unsigned char type) +{ + if ((0 <= type) && (type < GCodeAnalyzer::PreviewData::Extrusion::Num_View_Types)) + gcode_preview.extrusion.view_type = (GCodeAnalyzer::PreviewData::Extrusion::EViewType)type; +} + +void Print::set_gcode_preview_extrusion_flags(unsigned int flags) +{ + gcode_preview.extrusion.role_flags = flags; +} + +bool Print::is_gcode_preview_extrusion_role_enabled(ExtrusionRole role) +{ + return gcode_preview.extrusion.is_role_flag_set(role); +} + +void Print::set_gcode_preview_travel_visible(bool visible) +{ + gcode_preview.travel.is_visible = visible; +} + +void Print::set_gcode_preview_retractions_visible(bool visible) +{ + gcode_preview.retraction.is_visible = visible; +} +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + PrintRegion* Print::add_region() { regions.push_back(new PrintRegion(this)); diff --git a/xs/src/libslic3r/Print.hpp b/xs/src/libslic3r/Print.hpp index c56e64c6c..7a69973de 100644 --- a/xs/src/libslic3r/Print.hpp +++ b/xs/src/libslic3r/Print.hpp @@ -15,6 +15,11 @@ #include "Slicing.hpp" #include "GCode/ToolOrdering.hpp" #include "GCode/WipeTower.hpp" +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +#include "GCode/Analyzer.hpp" +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ #include "tbb/atomic.h" @@ -240,6 +245,11 @@ public: // ordered collections of extrusion paths to build skirt loops and brim ExtrusionEntityCollection skirt, brim; +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + GCodeAnalyzer::PreviewData gcode_preview; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ Print() : total_used_filament(0), total_extruded_volume(0) { restart(); } ~Print() { clear_objects(); } @@ -253,6 +263,17 @@ public: void reload_object(size_t idx); bool reload_model_instances(); +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + void clear_gcode_preview_data(); + void set_gcode_preview_type(unsigned char type); + void set_gcode_preview_extrusion_flags(unsigned int flags); + bool is_gcode_preview_extrusion_role_enabled(ExtrusionRole role); + void set_gcode_preview_travel_visible(bool visible); + void set_gcode_preview_retractions_visible(bool visible); +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + // methods for handling regions PrintRegion* get_region(size_t idx) { return regions.at(idx); } const PrintRegion* get_region(size_t idx) const { return regions.at(idx); } diff --git a/xs/src/libslic3r/libslic3r.h b/xs/src/libslic3r/libslic3r.h index 7c694b05e..24d7f4889 100644 --- a/xs/src/libslic3r/libslic3r.h +++ b/xs/src/libslic3r/libslic3r.h @@ -163,12 +163,29 @@ static inline T clamp(const T low, const T high, const T value) return std::max(low, std::min(high, value)); } +//############################################################################################################ +#define ENRICO_GCODE_PREVIEW 1 +//############################################################################################################ + +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +template +static inline T lerp(const T& a, const T& b, Number t) +{ + assert((t >= Number(-EPSILON)) && (t <= Number(1) + Number(EPSILON))); + return (Number(1) - t) * a + t * b; +} +#else +//############################################################################################################ template static inline T lerp(const T a, const T b, const T t) { assert(t >= T(-EPSILON) && t <= T(1.+EPSILON)); return (1. - t) * a + t * b; } +//############################################################################################################ +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ } // namespace Slic3r diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index 81dbcdacc..85c044db8 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -8,6 +8,11 @@ #include "../../libslic3r/Geometry.hpp" #include "../../libslic3r/Print.hpp" #include "../../libslic3r/Slicing.hpp" +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +#include "GCode/Analyzer.hpp" +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ #include #include @@ -605,6 +610,279 @@ static void thick_lines_to_indexed_vertex_array( #undef BOTTOM } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +// caller is responsible for supplying NO lines with zero length +static void thick_lines_to_indexed_vertex_array(const Lines3& lines, + const std::vector& widths, + const std::vector& heights, + bool closed, + GLIndexedVertexArray& volume) +{ + assert(!lines.empty()); + if (lines.empty()) + return; + +#define LEFT 0 +#define RIGHT 1 +#define TOP 2 +#define BOTTOM 3 + + // left, right, top, bottom + int idx_initial[4] = { -1, -1, -1, -1 }; + int idx_prev[4] = { -1, -1, -1, -1 }; + double z_prev = 0.0; + Vectorf3 n_right_prev; + Vectorf3 n_top_prev; + Vectorf3 unit_v_prev; + double width_initial = 0.0; + + // new vertices around the line endpoints + // left, right, top, bottom + Pointf3 a[4]; + Pointf3 b[4]; + + // loop once more in case of closed loops + size_t lines_end = closed ? (lines.size() + 1) : lines.size(); + for (size_t ii = 0; ii < lines_end; ++ii) + { + size_t i = (ii == lines.size()) ? 0 : ii; + + const Line3& line = lines[i]; + double height = heights[i]; + double width = widths[i]; + + Vectorf3 unit_v = normalize(Vectorf3::new_unscale(line.vector())); + + Vectorf3 n_top; + Vectorf3 n_right; + Vectorf3 unit_positive_z(0.0, 0.0, 1.0); + +// float dot_z = dot(unit_v, unit_positive_z); +// bool is_vertical = ::fabs(dot_z) > 0.99999; + + if ((line.a.x == line.b.x) && (line.a.y == line.b.y)) +// if (is_vertical) + { + // vertical segment + n_right = (line.a.z < line.b.z) ? Vectorf3(-1.0, 0.0, 0.0) : Vectorf3(1.0, 0.0, 0.0); + n_top = Vectorf3(0.0, 1.0, 0.0); + } + else + { + // generic segment + n_right = normalize(cross(unit_v, unit_positive_z)); + n_top = normalize(cross(n_right, unit_v)); + } + + Vectorf3 rl_displacement = 0.5 * width * n_right; + Vectorf3 tb_displacement = 0.5 * height * n_top; + Pointf3 l_a = Pointf3::new_unscale(line.a); + Pointf3 l_b = Pointf3::new_unscale(line.b); + + a[RIGHT] = l_a + rl_displacement; + a[LEFT] = l_a - rl_displacement; + a[TOP] = l_a + tb_displacement; + a[BOTTOM] = l_a - tb_displacement; + b[RIGHT] = l_b + rl_displacement; + b[LEFT] = l_b - rl_displacement; + b[TOP] = l_b + tb_displacement; + b[BOTTOM] = l_b - tb_displacement; + + Vectorf3 n_bottom = -n_top; + Vectorf3 n_left = -n_right; + + int idx_a[4]; + int idx_b[4]; + int idx_last = int(volume.vertices_and_normals_interleaved.size() / 6); + + bool z_different = (z_prev != l_a.z); + z_prev = l_b.z; + + // Share top / bottom vertices if possible. + if (ii == 0) + { + idx_a[TOP] = idx_last++; + volume.push_geometry(a[TOP], n_top); + } + else + idx_a[TOP] = idx_prev[TOP]; + + if ((ii == 0) || z_different) + { + // Start of the 1st line segment or a change of the layer thickness while maintaining the print_z. + idx_a[BOTTOM] = idx_last++; + volume.push_geometry(a[BOTTOM], n_bottom); + idx_a[LEFT] = idx_last++; + volume.push_geometry(a[LEFT], n_left); + idx_a[RIGHT] = idx_last++; + volume.push_geometry(a[RIGHT], n_right); + } + else + idx_a[BOTTOM] = idx_prev[BOTTOM]; + + if (ii == 0) + { + // Start of the 1st line segment. + width_initial = width; + ::memcpy(idx_initial, idx_a, sizeof(int) * 4); + } + else + { + // Continuing a previous segment. + // Share left / right vertices if possible. + double v_dot = dot(unit_v_prev, unit_v); + bool is_sharp = v_dot < 0.707; // sin(45 degrees) + bool is_right_turn = dot(n_top_prev, cross(unit_v_prev, unit_v)) > 0.0; + + if (is_sharp) + { + // Allocate new left / right points for the start of this segment as these points will receive their own normals to indicate a sharp turn. + idx_a[RIGHT] = idx_last++; + volume.push_geometry(a[RIGHT], n_right); + idx_a[LEFT] = idx_last++; + volume.push_geometry(a[LEFT], n_left); + } + + if (v_dot > 0.9) + { + // The two successive segments are nearly collinear. + idx_a[LEFT] = idx_prev[LEFT]; + idx_a[RIGHT] = idx_prev[RIGHT]; + } + else if (!is_sharp) + { + // Create a sharp corner with an overshot and average the left / right normals. + // At the crease angle of 45 degrees, the overshot at the corner will be less than (1-1/cos(PI/8)) = 8.2% over an arc. + + // averages normals + Vectorf3 average_n_right = normalize(0.5 * (n_right + n_right_prev)); + Vectorf3 average_n_left = -average_n_right; + Vectorf3 average_rl_displacement = 0.5 * width * average_n_right; + + // updates vertices around a + a[RIGHT] = l_a + average_rl_displacement; + a[LEFT] = l_a - average_rl_displacement; + + // updates previous line normals + float* normal_left_prev = volume.vertices_and_normals_interleaved.data() + idx_prev[LEFT] * 6; + normal_left_prev[0] = float(average_n_left.x); + normal_left_prev[1] = float(average_n_left.y); + normal_left_prev[2] = float(average_n_left.z); + + float* normal_right_prev = volume.vertices_and_normals_interleaved.data() + idx_prev[RIGHT] * 6; + normal_right_prev[0] = float(average_n_right.x); + normal_right_prev[1] = float(average_n_right.y); + normal_right_prev[2] = float(average_n_right.z); + + // updates previous line's vertices around b + float* b_left_prev = normal_left_prev + 3; + b_left_prev[0] = float(a[LEFT].x); + b_left_prev[1] = float(a[LEFT].y); + b_left_prev[2] = float(a[LEFT].z); + + float* b_right_prev = normal_right_prev + 3; + b_right_prev[0] = float(a[RIGHT].x); + b_right_prev[1] = float(a[RIGHT].y); + b_right_prev[2] = float(a[RIGHT].z); + + idx_a[LEFT] = idx_prev[LEFT]; + idx_a[RIGHT] = idx_prev[RIGHT]; + } + else if (is_right_turn) + { + // Right turn. Fill in the right turn wedge. + volume.push_triangle(idx_prev[RIGHT], idx_a[RIGHT], idx_prev[TOP]); + volume.push_triangle(idx_prev[RIGHT], idx_prev[BOTTOM], idx_a[RIGHT]); + } + else + { + // Left turn. Fill in the left turn wedge. + volume.push_triangle(idx_prev[LEFT], idx_prev[TOP], idx_a[LEFT]); + volume.push_triangle(idx_prev[LEFT], idx_a[LEFT], idx_prev[BOTTOM]); + } + + if (ii == lines.size()) + { + if (!is_sharp) + { + // Closing a loop with smooth transition. Unify the closing left / right vertices. + ::memcpy(volume.vertices_and_normals_interleaved.data() + idx_initial[LEFT] * 6, volume.vertices_and_normals_interleaved.data() + idx_prev[LEFT] * 6, sizeof(float) * 6); + ::memcpy(volume.vertices_and_normals_interleaved.data() + idx_initial[RIGHT] * 6, volume.vertices_and_normals_interleaved.data() + idx_prev[RIGHT] * 6, sizeof(float) * 6); + volume.vertices_and_normals_interleaved.erase(volume.vertices_and_normals_interleaved.end() - 12, volume.vertices_and_normals_interleaved.end()); + // Replace the left / right vertex indices to point to the start of the loop. + for (size_t u = volume.quad_indices.size() - 16; u < volume.quad_indices.size(); ++u) + { + if (volume.quad_indices[u] == idx_prev[LEFT]) + volume.quad_indices[u] = idx_initial[LEFT]; + else if (volume.quad_indices[u] == idx_prev[RIGHT]) + volume.quad_indices[u] = idx_initial[RIGHT]; + } + } + + // This is the last iteration, only required to solve the transition. + break; + } + } + + // Only new allocate top / bottom vertices, if not closing a loop. + if (closed && (ii + 1 == lines.size())) + idx_b[TOP] = idx_initial[TOP]; + else + { + idx_b[TOP] = idx_last++; + volume.push_geometry(b[TOP], n_top); + } + + if (closed && (ii + 1 == lines.size()) && (width == width_initial)) + idx_b[BOTTOM] = idx_initial[BOTTOM]; + else + { + idx_b[BOTTOM] = idx_last++; + volume.push_geometry(b[BOTTOM], n_bottom); + } + + // Generate new vertices for the end of this line segment. + idx_b[LEFT] = idx_last++; + volume.push_geometry(b[LEFT], n_left); + idx_b[RIGHT] = idx_last++; + volume.push_geometry(b[RIGHT], n_right); + + ::memcpy(idx_prev, idx_b, 4 * sizeof(int)); + n_right_prev = n_right; + n_top_prev = n_top; + unit_v_prev = unit_v; + + if (!closed) + { + // Terminate open paths with caps. + if (i == 0) + volume.push_quad(idx_a[BOTTOM], idx_a[RIGHT], idx_a[TOP], idx_a[LEFT]); + + // We don't use 'else' because both cases are true if we have only one line. + if (i + 1 == lines.size()) + volume.push_quad(idx_b[BOTTOM], idx_b[LEFT], idx_b[TOP], idx_b[RIGHT]); + } + + // Add quads for a straight hollow tube-like segment. + // bottom-right face + volume.push_quad(idx_a[BOTTOM], idx_b[BOTTOM], idx_b[RIGHT], idx_a[RIGHT]); + // top-right face + volume.push_quad(idx_a[RIGHT], idx_b[RIGHT], idx_b[TOP], idx_a[TOP]); + // top-left face + volume.push_quad(idx_a[TOP], idx_b[TOP], idx_b[LEFT], idx_a[LEFT]); + // bottom-left face + volume.push_quad(idx_a[LEFT], idx_b[LEFT], idx_b[BOTTOM], idx_a[BOTTOM]); + } + +#undef LEFT +#undef RIGHT +#undef TOP +#undef BOTTOM +} +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + static void thick_lines_to_verts( const Lines &lines, const std::vector &widths, @@ -616,6 +894,19 @@ static void thick_lines_to_verts( thick_lines_to_indexed_vertex_array(lines, widths, heights, closed, top_z, volume.indexed_vertex_array); } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +static void thick_lines_to_verts(const Lines3& lines, + const std::vector& widths, + const std::vector& heights, + bool closed, + GLVolume& volume) +{ + thick_lines_to_indexed_vertex_array(lines, widths, heights, closed, volume.indexed_vertex_array); +} +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + // Fill in the qverts and tverts with quads and triangles for the extrusion_path. static inline void extrusionentity_to_verts(const ExtrusionPath &extrusion_path, float print_z, const Point ©, GLVolume &volume) { @@ -699,6 +990,21 @@ static void extrusionentity_to_verts(const ExtrusionEntity *extrusion_entity, fl } } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +static void polyline3_to_verts(const Polyline3& polyline, double width, double height, const Point& copy, GLVolume& volume) +{ + Polyline3 p = polyline; + p.remove_duplicate_points(); + p.translate(copy); + Lines3 lines = polyline.lines(); + std::vector widths(lines.size(), width); + std::vector heights(lines.size(), height); + thick_lines_to_verts(lines, widths, heights, false, volume); +} +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + void _3DScene::_glew_init() { glewInit(); @@ -731,6 +1037,17 @@ static inline std::vector parse_colors(const std::vector &sc return output; } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volumes, bool use_VBOs) +{ + _load_gcode_extrusion_paths(*print, *volumes, use_VBOs); + _load_gcode_travel_paths(*print, *volumes, use_VBOs); + _load_gcode_retractions(*print, *volumes, use_VBOs); +} +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + // Create 3D thick extrusion lines for a skirt and brim. // Adds a new Slic3r::GUI::3DScene::Volume to volumes. void _3DScene::_load_print_toolpaths( @@ -739,7 +1056,7 @@ void _3DScene::_load_print_toolpaths( const std::vector &tool_colors, bool use_VBOs) { - if (! print->has_skirt() && print->config.brim_width.value == 0) + if (!print->has_skirt() && print->config.brim_width.value == 0) return; const float color[] = { 0.5f, 1.0f, 0.5f, 1.f }; // greenish @@ -1088,4 +1405,164 @@ void _3DScene::_load_wipe_tower_toolpaths( BOOST_LOG_TRIVIAL(debug) << "Loading wipe tower toolpaths in parallel - end"; } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) +{ + // helper functions to extract data from path in dependence of the selected extrusion view type + struct PathHelper + { + static float path_filter(GCodeAnalyzer::PreviewData::Extrusion::EViewType type, const ExtrusionPath& path) + { + switch (type) + { + case GCodeAnalyzer::PreviewData::Extrusion::FeatureType: + return (float)path.role(); + case GCodeAnalyzer::PreviewData::Extrusion::Height: + return path.height; + case GCodeAnalyzer::PreviewData::Extrusion::Width: + return path.width; + case GCodeAnalyzer::PreviewData::Extrusion::Feedrate: + return path.feedrate; + } + + return 0.0f; + } + + static const GCodeAnalyzer::PreviewData::Color& path_color(const GCodeAnalyzer::PreviewData& data, const ExtrusionPath& path) + { + switch (data.extrusion.view_type) + { + case GCodeAnalyzer::PreviewData::Extrusion::FeatureType: + return data.get_extrusion_role_color(path.role()); + case GCodeAnalyzer::PreviewData::Extrusion::Height: + return data.get_extrusion_height_color(path.height); + case GCodeAnalyzer::PreviewData::Extrusion::Width: + return data.get_extrusion_width_color(path.width); + case GCodeAnalyzer::PreviewData::Extrusion::Feedrate: + return data.get_extrusion_feedrate_color(path.feedrate); + } + + return GCodeAnalyzer::PreviewData::Color::Dummy; + } + }; + + Point origin(0, 0); + for (const GCodeAnalyzer::PreviewData::Extrusion::Layer& layer : print.gcode_preview.extrusion.layers) + { + float filter = FLT_MAX; + GLVolume* volume = nullptr; + + for (const ExtrusionPath& path : layer.paths) + { + if (print.gcode_preview.extrusion.is_role_flag_set(path.role())) + { + float path_filter = PathHelper::path_filter(print.gcode_preview.extrusion.view_type, path); + if (filter == path_filter) + { + // adds path to current volume + if (volume != nullptr) + extrusionentity_to_verts(path, layer.z, origin, *volume); + } + else + { + if (volume != nullptr) + { + // finalizes current volume + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + volume->indexed_vertex_array.finalize_geometry(use_VBOs); + volume = nullptr; + } + + // adds new volume + volumes.volumes.emplace_back(new GLVolume(PathHelper::path_color(print.gcode_preview, path).rgba)); + volume = volumes.volumes.back(); + if (volume != nullptr) + { + volume->print_zs.push_back(layer.z); + volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); + volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); + + // adds path to current volume + extrusionentity_to_verts(path, layer.z, origin, *volume); + } + + // updates current filter + filter = path_filter; + } + } + } + + if (volume != nullptr) + { + // finalizes last volume on layer + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + volume->indexed_vertex_array.finalize_geometry(use_VBOs); + } + } +} + +void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) +{ + struct TypeMatch + { + GCodeAnalyzer::PreviewData::Travel::EType type; + + TypeMatch(GCodeAnalyzer::PreviewData::Travel::EType type) + : type(type) + { + } + + bool operator () (const GCodeAnalyzer::PreviewData::Travel::Polyline& p) const + { + return p.type == type; + } + }; + + if (print.gcode_preview.travel.is_visible) + { + Point origin(0, 0); + for (unsigned int i = (unsigned int)GCodeAnalyzer::PreviewData::Travel::Move; i < (unsigned int)GCodeAnalyzer::PreviewData::Travel::Num_Types; ++i) + { + GCodeAnalyzer::PreviewData::Travel::EType type = (GCodeAnalyzer::PreviewData::Travel::EType)i; + if (std::count_if(print.gcode_preview.travel.polylines.begin(), print.gcode_preview.travel.polylines.end(), TypeMatch(type)) > 0) + { + volumes.volumes.emplace_back(new GLVolume(print.gcode_preview.travel.type_colors[i].rgba)); + GLVolume* volume = volumes.volumes.back(); + + if (volume != nullptr) + { + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + { + if (polyline.type == type) + { + const BoundingBox3& bbox = polyline.polyline.bounding_box(); + coordf_t print_z = unscale(bbox.max.z); + volume->print_zs.push_back(print_z); + volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); + volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); + + // adds polyline to volume + polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, origin, *volume); + } + } + + // finalizes volume + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + volume->indexed_vertex_array.finalize_geometry(use_VBOs); + } + } + } + } +} + +void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) +{ + if (print.gcode_preview.retraction.is_visible) + { + } +} +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + } diff --git a/xs/src/slic3r/GUI/3DScene.hpp b/xs/src/slic3r/GUI/3DScene.hpp index 27eeb7ca8..d4fc0ed67 100644 --- a/xs/src/slic3r/GUI/3DScene.hpp +++ b/xs/src/slic3r/GUI/3DScene.hpp @@ -106,6 +106,14 @@ public: push_geometry(float(x), float(y), float(z), float(nx), float(ny), float(nz)); } +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + inline void push_geometry(const Pointf3& p, const Vectorf3& n) { + push_geometry(p.x, p.y, p.z, n.x, n.y, n.z); + } +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + inline void push_triangle(int idx1, int idx2, int idx3) { if (this->triangle_indices.size() + 3 > this->vertices_and_normals_interleaved.capacity()) this->triangle_indices.reserve(next_highest_power_of_2(this->triangle_indices.size() + 3)); @@ -344,6 +352,12 @@ class _3DScene public: static void _glew_init(); +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + static void load_gcode_preview(const Print* print, GLVolumeCollection* volumes, bool use_VBOs); +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + static void _load_print_toolpaths( const Print *print, GLVolumeCollection *volumes, @@ -362,6 +376,15 @@ public: GLVolumeCollection *volumes, const std::vector &tool_colors_str, bool use_VBOs); + +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +private: + static void _load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); + static void _load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); + static void _load_gcode_retractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ }; } diff --git a/xs/xsp/GUI_3DScene.xsp b/xs/xsp/GUI_3DScene.xsp index 13f0d42f2..186511cc4 100644 --- a/xs/xsp/GUI_3DScene.xsp +++ b/xs/xsp/GUI_3DScene.xsp @@ -168,4 +168,12 @@ _load_wipe_tower_toolpaths(print, volumes, tool_colors, use_VBOs) CODE: _3DScene::_load_wipe_tower_toolpaths(print, volumes, tool_colors, use_VBOs != 0); +void +load_gcode_preview(print, volumes, use_VBOs) + Print *print; + GLVolumeCollection *volumes; + int use_VBOs; + CODE: + _3DScene::load_gcode_preview(print, volumes, use_VBOs != 0); + %} diff --git a/xs/xsp/Print.xsp b/xs/xsp/Print.xsp index cbc04a804..e3e1704fe 100644 --- a/xs/xsp/Print.xsp +++ b/xs/xsp/Print.xsp @@ -165,6 +165,14 @@ _constant() size_t object_count() %code%{ RETVAL = THIS->objects.size(); %}; +// ===================== ENRICO_GCODE_PREVIEW ================================================== + void clear_gcode_preview_data(); + void set_gcode_preview_type(unsigned char type); + void set_gcode_preview_extrusion_flags(unsigned int flags); + void set_gcode_preview_travel_visible(bool visible); + void set_gcode_preview_retractions_visible(bool visible); +// ===================== ENRICO_GCODE_PREVIEW ================================================== + PrintRegionPtrs* regions() %code%{ RETVAL = &THIS->regions; %}; Ref get_region(int idx); From 6a744238b9a4d266b1028d1b86998553c0f61df8 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Mon, 8 Jan 2018 16:05:01 +0100 Subject: [PATCH 02/57] Added preview of retractions and unretractions --- lib/Slic3r/GUI/Plater/3DPreview.pm | 9 ++- xs/src/libslic3r/GCode/Analyzer.cpp | 33 +++++++- xs/src/libslic3r/GCode/Analyzer.hpp | 18 ++++- xs/src/libslic3r/Print.cpp | 5 ++ xs/src/libslic3r/Print.hpp | 1 + xs/src/slic3r/GUI/3DScene.cpp | 115 ++++++++++++++++++++++++++++ xs/src/slic3r/GUI/3DScene.hpp | 1 + xs/xsp/Print.xsp | 1 + 8 files changed, 179 insertions(+), 4 deletions(-) diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index 9ff3461e0..488938267 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -94,8 +94,9 @@ sub new { $checklist_features->Check($i, 1); } - my $checkbox_travel = Wx::CheckBox->new($self, -1, "Travel"); + my $checkbox_travel = Wx::CheckBox->new($self, -1, "Travel"); my $checkbox_retractions = Wx::CheckBox->new($self, -1, "Retractions"); + my $checkbox_unretractions = Wx::CheckBox->new($self, -1, "Unretractions"); # ===================== ENRICO_GCODE_PREVIEW ================================================== my $hsizer = Wx::BoxSizer->new(wxHORIZONTAL); @@ -116,6 +117,7 @@ sub new { $vsizer_outer->Add($checklist_features, 0, wxTOP | wxALL | wxALIGN_CENTER_HORIZONTAL, 5); $vsizer_outer->Add($checkbox_travel, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); $vsizer_outer->Add($checkbox_retractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); + $vsizer_outer->Add($checkbox_unretractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); # ===================== ENRICO_GCODE_PREVIEW ================================================== my $sizer = Wx::BoxSizer->new(wxHORIZONTAL); @@ -228,6 +230,11 @@ sub new { $self->auto_zoom(0); $self->reload_print; }); + EVT_CHECKBOX($self, $checkbox_unretractions, sub { + $self->print->set_gcode_preview_unretractions_visible($checkbox_unretractions->IsChecked()); + $self->auto_zoom(0); + $self->reload_print; + }); # ===================== ENRICO_GCODE_PREVIEW ================================================== $self->SetSizer($sizer); diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index 467e2b6ae..e00bd5daf 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -567,8 +567,18 @@ void GCodeAnalyzer::PreviewData::Travel::set_default() is_visible = false; } +const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Retraction::Default_Color = GCodeAnalyzer::PreviewData::Color(1.0f, 1.0f, 1.0f, 1.0f); + +GCodeAnalyzer::PreviewData::Retraction::Position::Position(const Point3& position, float width, float height) + : position(position) + , width(width) + , height(height) +{ +} + void GCodeAnalyzer::PreviewData::Retraction::set_default() { + color = Default_Color; is_visible = false; }; @@ -582,6 +592,7 @@ void GCodeAnalyzer::PreviewData::set_default() extrusion.set_default(); travel.set_default(); retraction.set_default(); + unretraction.set_default(); } void GCodeAnalyzer::PreviewData::reset() @@ -589,6 +600,7 @@ void GCodeAnalyzer::PreviewData::reset() extrusion.layers.clear(); travel.polylines.clear(); retraction.positions.clear(); + unretraction.positions.clear(); } const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::get_extrusion_role_color(ExtrusionRole role) const @@ -658,6 +670,9 @@ void GCodeAnalyzer::calc_gcode_preview_data(Print& print) // calculates retractions _calc_gcode_preview_retractions(print); + + // calculates unretractions + _calc_gcode_preview_unretractions(print); } void GCodeAnalyzer::_process_gcode_line(GCodeReader&, const GCodeReader::GCodeLine& line) @@ -1259,10 +1274,24 @@ void GCodeAnalyzer::_calc_gcode_preview_retractions(Print& print) for (const GCodeMove& move : retraction_moves->second) { - print.gcode_preview.retraction.positions.emplace_back(scale_(move.start_position.x), scale_(move.start_position.y), scale_(move.start_position.z)); + // store position + Point3 position(scale_(move.start_position.x), scale_(move.start_position.y), scale_(move.start_position.z)); + print.gcode_preview.retraction.positions.emplace_back(position, move.data.width, move.data.height); } +} - int a = 0; +void GCodeAnalyzer::_calc_gcode_preview_unretractions(Print& print) +{ + TypeToMovesMap::iterator unretraction_moves = m_moves_map.find(GCodeMove::Unretract); + if (unretraction_moves == m_moves_map.end()) + return; + + for (const GCodeMove& move : unretraction_moves->second) + { + // store position + Point3 position(scale_(move.start_position.x), scale_(move.start_position.y), scale_(move.start_position.z)); + print.gcode_preview.unretraction.positions.emplace_back(position, move.data.width, move.data.height); + } } GCodeAnalyzer::PreviewData::Color operator + (const GCodeAnalyzer::PreviewData::Color& c1, const GCodeAnalyzer::PreviewData::Color& c2) diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index 8236772fb..afc863998 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -375,7 +375,21 @@ public: struct Retraction { - Points3 positions; + static const Color Default_Color; + + struct Position + { + Point3 position; + float width; + float height; + + Position(const Point3& position, float width, float height); + }; + + typedef std::vector PositionsList; + + PositionsList positions; + Color color; bool is_visible; void set_default(); @@ -384,6 +398,7 @@ public: Extrusion extrusion; Travel travel; Retraction retraction; + Retraction unretraction; PreviewData(); @@ -515,6 +530,7 @@ private: void _calc_gcode_preview_extrusion_layers(Print& print); void _calc_gcode_preview_travel(Print& print); void _calc_gcode_preview_retractions(Print& print); + void _calc_gcode_preview_unretractions(Print& print); }; GCodeAnalyzer::PreviewData::Color operator + (const GCodeAnalyzer::PreviewData::Color& c1, const GCodeAnalyzer::PreviewData::Color& c2); diff --git a/xs/src/libslic3r/Print.cpp b/xs/src/libslic3r/Print.cpp index 0d984d6da..2173ae9b1 100644 --- a/xs/src/libslic3r/Print.cpp +++ b/xs/src/libslic3r/Print.cpp @@ -98,6 +98,11 @@ void Print::set_gcode_preview_retractions_visible(bool visible) { gcode_preview.retraction.is_visible = visible; } + +void Print::set_gcode_preview_unretractions_visible(bool visible) +{ + gcode_preview.unretraction.is_visible = visible; +} #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ diff --git a/xs/src/libslic3r/Print.hpp b/xs/src/libslic3r/Print.hpp index 7a69973de..2ded86ee9 100644 --- a/xs/src/libslic3r/Print.hpp +++ b/xs/src/libslic3r/Print.hpp @@ -271,6 +271,7 @@ public: bool is_gcode_preview_extrusion_role_enabled(ExtrusionRole role); void set_gcode_preview_travel_visible(bool visible); void set_gcode_preview_retractions_visible(bool visible); + void set_gcode_preview_unretractions_visible(bool visible); #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index 85c044db8..4429d7449 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -880,6 +880,56 @@ static void thick_lines_to_indexed_vertex_array(const Lines3& lines, #undef TOP #undef BOTTOM } + +static void point_to_indexed_vertex_array(const Point3& point, + double width, + double height, + GLIndexedVertexArray& volume) +{ + // builds a double piramid, with vertices on the local axes, around the point + + Pointf3 center = Pointf3::new_unscale(point); + + double scale_factor = 1.0; + double w = scale_factor * width; + double h = scale_factor * height; + + // new vertices ids + int idx_last = int(volume.vertices_and_normals_interleaved.size() / 6); + int idxs[6]; + for (int i = 0; i < 6; ++i) + { + idxs[i] = idx_last + i; + } + + Vectorf3 displacement_x(w, 0.0, 0.0); + Vectorf3 displacement_y(0.0, w, 0.0); + Vectorf3 displacement_z(0.0, 0.0, h); + + Vectorf3 unit_x(1.0, 0.0, 0.0); + Vectorf3 unit_y(0.0, 1.0, 0.0); + Vectorf3 unit_z(0.0, 0.0, 1.0); + + // vertices + volume.push_geometry(center - displacement_x, -unit_x); // idxs[0] + volume.push_geometry(center + displacement_x, unit_x); // idxs[1] + volume.push_geometry(center - displacement_y, -unit_y); // idxs[2] + volume.push_geometry(center + displacement_y, unit_y); // idxs[3] + volume.push_geometry(center - displacement_z, -unit_z); // idxs[4] + volume.push_geometry(center + displacement_z, unit_z); // idxs[5] + + // top piramid faces + volume.push_triangle(idxs[0], idxs[2], idxs[5]); + volume.push_triangle(idxs[2], idxs[1], idxs[5]); + volume.push_triangle(idxs[1], idxs[3], idxs[5]); + volume.push_triangle(idxs[3], idxs[0], idxs[5]); + + // bottom piramid faces + volume.push_triangle(idxs[2], idxs[0], idxs[4]); + volume.push_triangle(idxs[1], idxs[2], idxs[4]); + volume.push_triangle(idxs[3], idxs[1], idxs[4]); + volume.push_triangle(idxs[0], idxs[3], idxs[4]); +} #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ @@ -904,6 +954,14 @@ static void thick_lines_to_verts(const Lines3& lines, { thick_lines_to_indexed_vertex_array(lines, widths, heights, closed, volume.indexed_vertex_array); } + +static void point_to_verts(const Point3& point, + double width, + double height, + GLVolume& volume) +{ + point_to_indexed_vertex_array(point, width, height, volume.indexed_vertex_array); +} #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ @@ -1002,6 +1060,13 @@ static void polyline3_to_verts(const Polyline3& polyline, double width, double h std::vector heights(lines.size(), height); thick_lines_to_verts(lines, widths, heights, false, volume); } + +static void point3_to_verts(const Point3& point, double width, double height, const Point& copy, GLVolume& volume) +{ + Point3 p = point; + p.translate(copy); + point_to_verts(p, width, height, volume); +} #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ @@ -1044,6 +1109,7 @@ void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volume _load_gcode_extrusion_paths(*print, *volumes, use_VBOs); _load_gcode_travel_paths(*print, *volumes, use_VBOs); _load_gcode_retractions(*print, *volumes, use_VBOs); + _load_gcode_unretractions(*print, *volumes, use_VBOs); } #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ @@ -1560,6 +1626,55 @@ void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& v { if (print.gcode_preview.retraction.is_visible) { + volumes.volumes.emplace_back(new GLVolume(print.gcode_preview.retraction.color.rgba)); + GLVolume* volume = volumes.volumes.back(); + + if (volume != nullptr) + { + Point origin(0, 0); + for (const GCodeAnalyzer::PreviewData::Retraction::Position& position : print.gcode_preview.retraction.positions) + { + coordf_t print_z = unscale(position.position.z); + volume->print_zs.push_back(print_z); + volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); + volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); + + // adds point to volume + point3_to_verts(position.position, position.width, position.height, origin, *volume); + } + + // finalizes volume + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + volume->indexed_vertex_array.finalize_geometry(use_VBOs); + } + } +} + +void _3DScene::_load_gcode_unretractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) +{ + if (print.gcode_preview.unretraction.is_visible) + { + volumes.volumes.emplace_back(new GLVolume(print.gcode_preview.unretraction.color.rgba)); + GLVolume* volume = volumes.volumes.back(); + + if (volume != nullptr) + { + Point origin(0, 0); + for (const GCodeAnalyzer::PreviewData::Retraction::Position& position : print.gcode_preview.unretraction.positions) + { + coordf_t print_z = unscale(position.position.z); + volume->print_zs.push_back(print_z); + volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); + volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); + + // adds point to volume + point3_to_verts(position.position, position.width, position.height, origin, *volume); + } + + // finalizes volume + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + volume->indexed_vertex_array.finalize_geometry(use_VBOs); + } } } #endif // ENRICO_GCODE_PREVIEW diff --git a/xs/src/slic3r/GUI/3DScene.hpp b/xs/src/slic3r/GUI/3DScene.hpp index d4fc0ed67..35c41ec2f 100644 --- a/xs/src/slic3r/GUI/3DScene.hpp +++ b/xs/src/slic3r/GUI/3DScene.hpp @@ -383,6 +383,7 @@ private: static void _load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); static void _load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); static void _load_gcode_retractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); + static void _load_gcode_unretractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ }; diff --git a/xs/xsp/Print.xsp b/xs/xsp/Print.xsp index e3e1704fe..d29e087c0 100644 --- a/xs/xsp/Print.xsp +++ b/xs/xsp/Print.xsp @@ -171,6 +171,7 @@ _constant() void set_gcode_preview_extrusion_flags(unsigned int flags); void set_gcode_preview_travel_visible(bool visible); void set_gcode_preview_retractions_visible(bool visible); + void set_gcode_preview_unretractions_visible(bool visible); // ===================== ENRICO_GCODE_PREVIEW ================================================== PrintRegionPtrs* regions() From bbc9a0abe6a318a27ff3b18b23f4ae18f845946d Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Wed, 10 Jan 2018 13:43:00 +0100 Subject: [PATCH 03/57] Parallelization of extrude path render geometry generation --- lib/Slic3r/GUI/Plater/3DPreview.pm | 6 +- xs/src/libslic3r/GCode/Analyzer.cpp | 4 + xs/src/slic3r/GUI/3DScene.cpp | 257 ++++++++++++++++++---------- 3 files changed, 171 insertions(+), 96 deletions(-) diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index 488938267..e7fb2aa22 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -205,6 +205,7 @@ sub new { $self->print->set_gcode_preview_type($selection); $self->auto_zoom(0); $self->reload_print; + $self->auto_zoom(1); }); EVT_CHECKLISTBOX($self, $checklist_features, sub { my $flags = 0; @@ -219,21 +220,25 @@ sub new { $self->print->set_gcode_preview_extrusion_flags($flags); $self->auto_zoom(0); $self->reload_print; + $self->auto_zoom(1); }); EVT_CHECKBOX($self, $checkbox_travel, sub { $self->print->set_gcode_preview_travel_visible($checkbox_travel->IsChecked()); $self->auto_zoom(0); $self->reload_print; + $self->auto_zoom(1); }); EVT_CHECKBOX($self, $checkbox_retractions, sub { $self->print->set_gcode_preview_retractions_visible($checkbox_retractions->IsChecked()); $self->auto_zoom(0); $self->reload_print; + $self->auto_zoom(1); }); EVT_CHECKBOX($self, $checkbox_unretractions, sub { $self->print->set_gcode_preview_unretractions_visible($checkbox_unretractions->IsChecked()); $self->auto_zoom(0); $self->reload_print; + $self->auto_zoom(1); }); # ===================== ENRICO_GCODE_PREVIEW ================================================== @@ -363,7 +368,6 @@ sub load_print { # ===================== ENRICO_GCODE_PREVIEW ================================================== $self->canvas->zoom_to_volumes; # ===================== ENRICO_GCODE_PREVIEW ================================================== - $self->auto_zoom(1); } # ===================== ENRICO_GCODE_PREVIEW ================================================== $self->_loaded(1); diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index e00bd5daf..b7d1e742f 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -1181,6 +1181,7 @@ void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(Print& print) if ((data != move.data) || (data.feedrate != move.data.feedrate) || (z != move.start_position.z) || (position != move.start_position)) { // store current polyline + polyline.remove_duplicate_points(); Helper::store_polyline(polyline, data, z, print); // reset current polyline @@ -1206,6 +1207,7 @@ void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(Print& print) } // store last polyline + polyline.remove_duplicate_points(); Helper::store_polyline(polyline, data, z, print); // updates preview ranges data @@ -1244,6 +1246,7 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) if ((type != move_type) || (direction != move_direction) || (position != move.start_position)) { // store current polyline + polyline.remove_duplicate_points(); Helper::store_polyline(polyline, type, direction, print); // reset current polyline @@ -1263,6 +1266,7 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) } // store last polyline + polyline.remove_duplicate_points(); Helper::store_polyline(polyline, type, direction, print); } diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index 4429d7449..8af45e6b2 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -658,11 +658,7 @@ static void thick_lines_to_indexed_vertex_array(const Lines3& lines, Vectorf3 n_right; Vectorf3 unit_positive_z(0.0, 0.0, 1.0); -// float dot_z = dot(unit_v, unit_positive_z); -// bool is_vertical = ::fabs(dot_z) > 0.99999; - if ((line.a.x == line.b.x) && (line.a.y == line.b.y)) -// if (is_vertical) { // vertical segment n_right = (line.a.z < line.b.z) ? Vectorf3(-1.0, 0.0, 0.0) : Vectorf3(1.0, 0.0, 0.0); @@ -955,13 +951,22 @@ static void thick_lines_to_verts(const Lines3& lines, thick_lines_to_indexed_vertex_array(lines, widths, heights, closed, volume.indexed_vertex_array); } -static void point_to_verts(const Point3& point, +static void thick_point_to_verts(const Point3& point, double width, double height, GLVolume& volume) { point_to_indexed_vertex_array(point, width, height, volume.indexed_vertex_array); } + +// Fill in the qverts and tverts with quads and triangles for the extrusion_path. +static inline void extrusionentity_to_verts(const ExtrusionPath &extrusion_path, float print_z, GLVolume &volume) +{ + Lines lines = extrusion_path.polyline.lines(); + std::vector widths(lines.size(), extrusion_path.width); + std::vector heights(lines.size(), extrusion_path.height); + thick_lines_to_verts(lines, widths, heights, false, print_z, volume); +} #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ @@ -1050,22 +1055,17 @@ static void extrusionentity_to_verts(const ExtrusionEntity *extrusion_entity, fl //############################################################################################################ #if ENRICO_GCODE_PREVIEW -static void polyline3_to_verts(const Polyline3& polyline, double width, double height, const Point& copy, GLVolume& volume) +static void polyline3_to_verts(const Polyline3& polyline, double width, double height, GLVolume& volume) { - Polyline3 p = polyline; - p.remove_duplicate_points(); - p.translate(copy); Lines3 lines = polyline.lines(); std::vector widths(lines.size(), width); std::vector heights(lines.size(), height); thick_lines_to_verts(lines, widths, heights, false, volume); } -static void point3_to_verts(const Point3& point, double width, double height, const Point& copy, GLVolume& volume) +static void point3_to_verts(const Point3& point, double width, double height, GLVolume& volume) { - Point3 p = point; - p.translate(copy); - point_to_verts(p, width, height, volume); + thick_point_to_verts(point, width, height, volume); } #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ @@ -1513,58 +1513,92 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio } }; - Point origin(0, 0); - for (const GCodeAnalyzer::PreviewData::Extrusion::Layer& layer : print.gcode_preview.extrusion.layers) + // temporary structure to contain data needed for parallelization + struct Ctxt { - float filter = FLT_MAX; - GLVolume* volume = nullptr; + const Print* print; + const GCodeAnalyzer::PreviewData::Extrusion::LayersList* layers; + } ctxt; - for (const ExtrusionPath& path : layer.paths) - { - if (print.gcode_preview.extrusion.is_role_flag_set(path.role())) - { - float path_filter = PathHelper::path_filter(print.gcode_preview.extrusion.view_type, path); - if (filter == path_filter) - { - // adds path to current volume - if (volume != nullptr) - extrusionentity_to_verts(path, layer.z, origin, *volume); - } - else - { - if (volume != nullptr) - { - // finalizes current volume - volume->bounding_box = volume->indexed_vertex_array.bounding_box(); - volume->indexed_vertex_array.finalize_geometry(use_VBOs); - volume = nullptr; - } - - // adds new volume - volumes.volumes.emplace_back(new GLVolume(PathHelper::path_color(print.gcode_preview, path).rgba)); - volume = volumes.volumes.back(); - if (volume != nullptr) - { - volume->print_zs.push_back(layer.z); - volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); - volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); - - // adds path to current volume - extrusionentity_to_verts(path, layer.z, origin, *volume); - } - - // updates current filter - filter = path_filter; - } - } - } + // fills data in temporary variable + ctxt.print = &print; + ctxt.layers = &print.gcode_preview.extrusion.layers; + // lambda for creating new volumes in a thread-safe way + tbb::spin_mutex new_volume_mutex; + auto new_volume = [&volumes, &new_volume_mutex](const float* color) -> GLVolume* + { + // allocate a new volume + GLVolume* volume = new GLVolume(color); if (volume != nullptr) { - // finalizes last volume on layer - volume->bounding_box = volume->indexed_vertex_array.bounding_box(); - volume->indexed_vertex_array.finalize_geometry(use_VBOs); + // adds the new volume to the collection + new_volume_mutex.lock(); + volumes.volumes.emplace_back(volume); + new_volume_mutex.unlock(); } + return volume; + }; + + size_t initial_volumes_count = volumes.volumes.size(); + + // generates volumes using parallelization + tbb::parallel_for(tbb::blocked_range(0, ctxt.layers->size()), [&ctxt, &new_volume](const tbb::blocked_range& range) + { + for (size_t idx_layer = range.begin(); idx_layer < range.end(); ++idx_layer) + { + const GCodeAnalyzer::PreviewData::Extrusion::Layer& layer = ctxt.layers->operator[](idx_layer); + float filter = FLT_MAX; + GLVolume* volume = nullptr; + + for (const ExtrusionPath& path : layer.paths) + { + if (ctxt.print->gcode_preview.extrusion.is_role_flag_set(path.role())) + { + float path_filter = PathHelper::path_filter(ctxt.print->gcode_preview.extrusion.view_type, path); + if (filter == path_filter) + { + // adds path to current volume + if (volume != nullptr) + extrusionentity_to_verts(path, layer.z, *volume); + } + else + { + if (volume != nullptr) + { + // finalizes current volume + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + volume = nullptr; + } + + // adds new volume + volume = new_volume(PathHelper::path_color(ctxt.print->gcode_preview, path).rgba); + if (volume != nullptr) + { + volume->print_zs.push_back(layer.z); + volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); + volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); + + // adds path to current volume + extrusionentity_to_verts(path, layer.z, *volume); + } + + // updates current filter + filter = path_filter; + } + } + } + + if (volume != nullptr) + // finalizes last volume on layer + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + } + }); + + // sends geometry to gpu + for (size_t i = initial_volumes_count; i < volumes.volumes.size(); ++i) + { + volumes.volumes[i]->indexed_vertex_array.finalize_geometry(use_VBOs); } } @@ -1587,36 +1621,71 @@ void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& if (print.gcode_preview.travel.is_visible) { - Point origin(0, 0); - for (unsigned int i = (unsigned int)GCodeAnalyzer::PreviewData::Travel::Move; i < (unsigned int)GCodeAnalyzer::PreviewData::Travel::Num_Types; ++i) + size_t initial_volumes_count = volumes.volumes.size(); + unsigned int types_count = (unsigned int)GCodeAnalyzer::PreviewData::Travel::Num_Types; + + // creates a new volume for each travel type + for (unsigned int i = 0; i < types_count; ++i) { - GCodeAnalyzer::PreviewData::Travel::EType type = (GCodeAnalyzer::PreviewData::Travel::EType)i; - if (std::count_if(print.gcode_preview.travel.polylines.begin(), print.gcode_preview.travel.polylines.end(), TypeMatch(type)) > 0) + GLVolume* volume = new GLVolume(print.gcode_preview.travel.type_colors[i].rgba); + if (volume != nullptr) + volumes.volumes.emplace_back(volume); + else { - volumes.volumes.emplace_back(new GLVolume(print.gcode_preview.travel.type_colors[i].rgba)); - GLVolume* volume = volumes.volumes.back(); - - if (volume != nullptr) + // an error occourred - restore to previous state and return + std::vector::iterator begin = volumes.volumes.begin() + initial_volumes_count; + std::vector::iterator end = volumes.volumes.end(); + for (std::vector::iterator it = begin; it < end; ++it) { - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) - { - if (polyline.type == type) - { - const BoundingBox3& bbox = polyline.polyline.bounding_box(); - coordf_t print_z = unscale(bbox.max.z); - volume->print_zs.push_back(print_z); - volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); - volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); - - // adds polyline to volume - polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, origin, *volume); - } - } - - // finalizes volume - volume->bounding_box = volume->indexed_vertex_array.bounding_box(); - volume->indexed_vertex_array.finalize_geometry(use_VBOs); + GLVolume* volume = *it; + delete volume; } + volumes.volumes.erase(begin, end); + return; + } + } + + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + { + unsigned int type = (unsigned int)polyline.type; + if (type < types_count) + { + const BoundingBox3& bbox = polyline.polyline.bounding_box(); + coordf_t print_z = unscale(bbox.max.z); + + // selects volume from polyline type + GLVolume* volume = volumes.volumes[initial_volumes_count + type]; + volume->print_zs.push_back(print_z); + volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); + volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); + + // adds polyline to volume + polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *volume); + } + } + + // removes empty volumes + std::vector::iterator it = volumes.volumes.begin() + initial_volumes_count; + while (it != volumes.volumes.end()) + { + GLVolume* volume = *it; + if (volume->print_zs.empty()) + { + delete volume; + it = volumes.volumes.erase(it); + } + else + ++it; + } + + // finalize volumes and sends geometry to gpu + if (volumes.volumes.size() > initial_volumes_count) + { + for (size_t i = initial_volumes_count; i < volumes.volumes.size(); ++i) + { + GLVolume* volume = volumes.volumes[i]; + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + volume->indexed_vertex_array.finalize_geometry(use_VBOs); } } } @@ -1626,12 +1695,11 @@ void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& v { if (print.gcode_preview.retraction.is_visible) { - volumes.volumes.emplace_back(new GLVolume(print.gcode_preview.retraction.color.rgba)); - GLVolume* volume = volumes.volumes.back(); - + GLVolume* volume = new GLVolume(print.gcode_preview.retraction.color.rgba); if (volume != nullptr) { - Point origin(0, 0); + volumes.volumes.emplace_back(volume); + for (const GCodeAnalyzer::PreviewData::Retraction::Position& position : print.gcode_preview.retraction.positions) { coordf_t print_z = unscale(position.position.z); @@ -1640,7 +1708,7 @@ void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& v volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); // adds point to volume - point3_to_verts(position.position, position.width, position.height, origin, *volume); + point3_to_verts(position.position, position.width, position.height, *volume); } // finalizes volume @@ -1654,12 +1722,11 @@ void _3DScene::_load_gcode_unretractions(const Print& print, GLVolumeCollection& { if (print.gcode_preview.unretraction.is_visible) { - volumes.volumes.emplace_back(new GLVolume(print.gcode_preview.unretraction.color.rgba)); - GLVolume* volume = volumes.volumes.back(); - + GLVolume* volume = new GLVolume(print.gcode_preview.unretraction.color.rgba); if (volume != nullptr) { - Point origin(0, 0); + volumes.volumes.emplace_back(volume); + for (const GCodeAnalyzer::PreviewData::Retraction::Position& position : print.gcode_preview.unretraction.positions) { coordf_t print_z = unscale(position.position.z); @@ -1668,7 +1735,7 @@ void _3DScene::_load_gcode_unretractions(const Print& print, GLVolumeCollection& volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); // adds point to volume - point3_to_verts(position.position, position.width, position.height, origin, *volume); + point3_to_verts(position.position, position.width, position.height, *volume); } // finalizes volume From a8a4c11b5bcffa431304f1a9879619b08be21f7e Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Thu, 11 Jan 2018 14:09:54 +0100 Subject: [PATCH 04/57] New algorithm for GLVolumes generation and reuse of already generated geometry --- lib/Slic3r/GUI/Plater/3DPreview.pm | 38 +- xs/src/libslic3r/GCode/Analyzer.cpp | 7 +- xs/src/libslic3r/GCode/Analyzer.hpp | 2 + xs/src/slic3r/GUI/3DScene.cpp | 530 ++++++++++++++++++---------- xs/src/slic3r/GUI/3DScene.hpp | 48 +++ 5 files changed, 426 insertions(+), 199 deletions(-) diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index e7fb2aa22..0af7a2ebf 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -209,35 +209,33 @@ sub new { }); EVT_CHECKLISTBOX($self, $checklist_features, sub { my $flags = 0; - for (my $i = 0; $i < $checklist_features->GetCount(); $i += 1) - { - if ($checklist_features->IsChecked($i)) - { + for (my $i = 0; $i < $checklist_features->GetCount(); $i += 1) { + if ($checklist_features->IsChecked($i)) { $flags += 2 ** $i; } } $self->print->set_gcode_preview_extrusion_flags($flags); $self->auto_zoom(0); - $self->reload_print; + $self->refresh_print; $self->auto_zoom(1); }); EVT_CHECKBOX($self, $checkbox_travel, sub { $self->print->set_gcode_preview_travel_visible($checkbox_travel->IsChecked()); $self->auto_zoom(0); - $self->reload_print; + $self->refresh_print; $self->auto_zoom(1); }); EVT_CHECKBOX($self, $checkbox_retractions, sub { $self->print->set_gcode_preview_retractions_visible($checkbox_retractions->IsChecked()); $self->auto_zoom(0); - $self->reload_print; + $self->refresh_print; $self->auto_zoom(1); }); EVT_CHECKBOX($self, $checkbox_unretractions, sub { $self->print->set_gcode_preview_unretractions_visible($checkbox_unretractions->IsChecked()); $self->auto_zoom(0); - $self->reload_print; + $self->refresh_print; $self->auto_zoom(1); }); # ===================== ENRICO_GCODE_PREVIEW ================================================== @@ -260,13 +258,29 @@ sub reload_print { $self->_loaded(0); if (! $self->IsShown && ! $force) { - $self->{reload_delayed} = 1; +# ===================== ENRICO_GCODE_PREVIEW ================================================== +# $self->{reload_delayed} = 1; +# ===================== ENRICO_GCODE_PREVIEW ================================================== return; } $self->load_print; } +# ===================== ENRICO_GCODE_PREVIEW ================================================== +sub refresh_print { + my ($self) = @_; + + $self->_loaded(0); + + if (! $self->IsShown) { + return; + } + + $self->load_print; +} +# ===================== ENRICO_GCODE_PREVIEW ================================================== + sub load_print { my ($self) = @_; @@ -431,8 +445,10 @@ sub set_number_extruders { # Called by the Platter wxNotebook when this page is activated. sub OnActivate { - my ($self) = @_; - $self->reload_print(1) if ($self->{reload_delayed}); +# ===================== ENRICO_GCODE_PREVIEW ================================================== +# my ($self) = @_; +# $self->reload_print(1) if ($self->{reload_delayed}); +# ===================== ENRICO_GCODE_PREVIEW ================================================== } 1; diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index b7d1e742f..07f047923 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -542,12 +542,17 @@ void GCodeAnalyzer::PreviewData::Extrusion::set_default() } bool GCodeAnalyzer::PreviewData::Extrusion::is_role_flag_set(ExtrusionRole role) const +{ + return is_role_flag_set(role_flags, role); +} + +bool GCodeAnalyzer::PreviewData::Extrusion::is_role_flag_set(unsigned int flags, ExtrusionRole role) { if ((role < erPerimeter) || (erSupportMaterialInterface < role)) return false; unsigned int flag = (unsigned int)::exp2((double)(role - erPerimeter)); - return (role_flags & flag) == flag; + return (flags & flag) == flag; } const float GCodeAnalyzer::PreviewData::Travel::Default_Width = 0.075f; diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index afc863998..567892b8e 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -330,6 +330,8 @@ public: void set_default(); bool is_role_flag_set(ExtrusionRole role) const; + + static bool is_role_flag_set(unsigned int flags, ExtrusionRole role); }; struct Travel diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index 8af45e6b2..f79d210a4 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -8,11 +8,13 @@ #include "../../libslic3r/Geometry.hpp" #include "../../libslic3r/Print.hpp" #include "../../libslic3r/Slicing.hpp" -//############################################################################################################ #if ENRICO_GCODE_PREVIEW #include "GCode/Analyzer.hpp" #endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ + +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +#include "enrico/wintimer.h" +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ #include #include @@ -206,6 +208,13 @@ void GLVolume::set_range(double min_z, double max_z) void GLVolume::render() const { +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +#if ENRICO_GCODE_PREVIEW + if (!is_active) + return; +#endif // ENRICO_GCODE_PREVIEW +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + glCullFace(GL_BACK); glPushMatrix(); glTranslated(this->origin.x, this->origin.y, this->origin.z); @@ -336,7 +345,13 @@ void GLVolumeCollection::render_VBOs() const GLint color_id = (current_program_id > 0) ? glGetUniformLocation(current_program_id, "uniform_color") : -1; for (GLVolume *volume : this->volumes) { - if (! volume->indexed_vertex_array.vertices_and_normals_interleaved_VBO_id) +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +#if ENRICO_GCODE_PREVIEW + if (!volume->is_active) + continue; +#endif // ENRICO_GCODE_PREVIEW +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + if (!volume->indexed_vertex_array.vertices_and_normals_interleaved_VBO_id) continue; GLsizei n_triangles = GLsizei(std::min(volume->indexed_vertex_array.triangle_indices_size, volume->tverts_range.second - volume->tverts_range.first)); GLsizei n_quads = GLsizei(std::min(volume->indexed_vertex_array.quad_indices_size, volume->qverts_range.second - volume->qverts_range.first)); @@ -374,6 +389,12 @@ void GLVolumeCollection::render_legacy() const for (GLVolume *volume : this->volumes) { assert(! volume->indexed_vertex_array.vertices_and_normals_interleaved_VBO_id); +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +#if ENRICO_GCODE_PREVIEW + if (!volume->is_active) + continue; +#endif // ENRICO_GCODE_PREVIEW +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GLsizei n_triangles = GLsizei(std::min(volume->indexed_vertex_array.triangle_indices_size, volume->tverts_range.second - volume->tverts_range.first)); GLsizei n_quads = GLsizei(std::min(volume->indexed_vertex_array.quad_indices_size, volume->qverts_range.second - volume->qverts_range.first)); if (n_triangles + n_quads == 0) @@ -1067,6 +1088,20 @@ static void point3_to_verts(const Point3& point, double width, double height, GL { thick_point_to_verts(point, width, height, volume); } + +_3DScene::GCodePreviewData::FirstVolume::FirstVolume(_3DScene::GCodePreviewData::EType type, unsigned int flag, unsigned int id) + : type(type) + , flag(flag) + , id(id) +{ +} + +void _3DScene::GCodePreviewData::reset() +{ + first_volumes.clear(); +} + +_3DScene::GCodePreviewData _3DScene::s_gcode_preview_data; #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ @@ -1106,10 +1141,30 @@ static inline std::vector parse_colors(const std::vector &sc #if ENRICO_GCODE_PREVIEW void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volumes, bool use_VBOs) { - _load_gcode_extrusion_paths(*print, *volumes, use_VBOs); - _load_gcode_travel_paths(*print, *volumes, use_VBOs); - _load_gcode_retractions(*print, *volumes, use_VBOs); - _load_gcode_unretractions(*print, *volumes, use_VBOs); +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + WinTimer timer; + timer.Start(); + + std::cout << "#############################################################################" << std::endl; +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + + if (volumes->empty()) + { + s_gcode_preview_data.reset(); + + _load_gcode_extrusion_paths(*print, *volumes, use_VBOs); + _load_gcode_travel_paths(*print, *volumes, use_VBOs); + _load_gcode_retractions(*print, *volumes, use_VBOs); + _load_gcode_unretractions(*print, *volumes, use_VBOs); + } + + _update_gcode_volumes_visibility(*print, *volumes); + +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + std::cout << "VOLUMES COUNT = " << volumes->volumes.size() << std::endl; + std::cout << "FIRST VOLUMES COUNT = " << s_gcode_preview_data.first_volumes.size() << std::endl; + std::cout << "load_gcode_preview() = " << timer.GetElapsedTimeMillisec() << " ms" << std::endl; +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ } #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ @@ -1475,8 +1530,13 @@ void _3DScene::_load_wipe_tower_toolpaths( #if ENRICO_GCODE_PREVIEW void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) { - // helper functions to extract data from path in dependence of the selected extrusion view type - struct PathHelper +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + WinTimer timer; + timer.Start(); +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + + // helper functions to select data in dependence of the extrusion view type + struct Helper { static float path_filter(GCodeAnalyzer::PreviewData::Extrusion::EViewType type, const ExtrusionPath& path) { @@ -1495,144 +1555,88 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio return 0.0f; } - static const GCodeAnalyzer::PreviewData::Color& path_color(const GCodeAnalyzer::PreviewData& data, const ExtrusionPath& path) + static const GCodeAnalyzer::PreviewData::Color& path_color(const GCodeAnalyzer::PreviewData& data, float value) { switch (data.extrusion.view_type) { case GCodeAnalyzer::PreviewData::Extrusion::FeatureType: - return data.get_extrusion_role_color(path.role()); + return data.get_extrusion_role_color((ExtrusionRole)(int)value); case GCodeAnalyzer::PreviewData::Extrusion::Height: - return data.get_extrusion_height_color(path.height); + return data.get_extrusion_height_color(value); case GCodeAnalyzer::PreviewData::Extrusion::Width: - return data.get_extrusion_width_color(path.width); + return data.get_extrusion_width_color(value); case GCodeAnalyzer::PreviewData::Extrusion::Feedrate: - return data.get_extrusion_feedrate_color(path.feedrate); + return data.get_extrusion_feedrate_color(value); } return GCodeAnalyzer::PreviewData::Color::Dummy; } }; - // temporary structure to contain data needed for parallelization - struct Ctxt + // Helper structure for filters + struct Filter { - const Print* print; - const GCodeAnalyzer::PreviewData::Extrusion::LayersList* layers; - } ctxt; + float value; + ExtrusionRole role; + GLVolume* volume; - // fills data in temporary variable - ctxt.print = &print; - ctxt.layers = &print.gcode_preview.extrusion.layers; - - // lambda for creating new volumes in a thread-safe way - tbb::spin_mutex new_volume_mutex; - auto new_volume = [&volumes, &new_volume_mutex](const float* color) -> GLVolume* - { - // allocate a new volume - GLVolume* volume = new GLVolume(color); - if (volume != nullptr) + Filter(float value, ExtrusionRole role) + : value(value) + , role(role) + , volume(nullptr) { - // adds the new volume to the collection - new_volume_mutex.lock(); - volumes.volumes.emplace_back(volume); - new_volume_mutex.unlock(); } - return volume; + + bool operator == (const Filter& other) const + { + if (value != other.value) + return false; + + if (role != other.role) + return false; + + return true; + } }; + typedef std::vector FiltersList; + size_t initial_volumes_count = volumes.volumes.size(); - // generates volumes using parallelization - tbb::parallel_for(tbb::blocked_range(0, ctxt.layers->size()), [&ctxt, &new_volume](const tbb::blocked_range& range) + // detects filters + FiltersList filters; + for (const GCodeAnalyzer::PreviewData::Extrusion::Layer& layer : print.gcode_preview.extrusion.layers) { - for (size_t idx_layer = range.begin(); idx_layer < range.end(); ++idx_layer) + for (const ExtrusionPath& path : layer.paths) { - const GCodeAnalyzer::PreviewData::Extrusion::Layer& layer = ctxt.layers->operator[](idx_layer); - float filter = FLT_MAX; - GLVolume* volume = nullptr; - - for (const ExtrusionPath& path : layer.paths) - { - if (ctxt.print->gcode_preview.extrusion.is_role_flag_set(path.role())) - { - float path_filter = PathHelper::path_filter(ctxt.print->gcode_preview.extrusion.view_type, path); - if (filter == path_filter) - { - // adds path to current volume - if (volume != nullptr) - extrusionentity_to_verts(path, layer.z, *volume); - } - else - { - if (volume != nullptr) - { - // finalizes current volume - volume->bounding_box = volume->indexed_vertex_array.bounding_box(); - volume = nullptr; - } - - // adds new volume - volume = new_volume(PathHelper::path_color(ctxt.print->gcode_preview, path).rgba); - if (volume != nullptr) - { - volume->print_zs.push_back(layer.z); - volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); - volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); - - // adds path to current volume - extrusionentity_to_verts(path, layer.z, *volume); - } - - // updates current filter - filter = path_filter; - } - } - } - - if (volume != nullptr) - // finalizes last volume on layer - volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + ExtrusionRole role = path.role(); + float path_filter = Helper::path_filter(print.gcode_preview.extrusion.view_type, path); + if (std::find(filters.begin(), filters.end(), Filter(path_filter, role)) == filters.end()) + filters.emplace_back(path_filter, role); } - }); - - // sends geometry to gpu - for (size_t i = initial_volumes_count; i < volumes.volumes.size(); ++i) - { - volumes.volumes[i]->indexed_vertex_array.finalize_geometry(use_VBOs); } -} -void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) -{ - struct TypeMatch + // nothing to render, return + if (filters.empty()) + return; + + // creates a new volume for each filter + for (Filter& filter : filters) { - GCodeAnalyzer::PreviewData::Travel::EType type; + s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Extrusion, (unsigned int)filter.role, (unsigned int)volumes.volumes.size()); - TypeMatch(GCodeAnalyzer::PreviewData::Travel::EType type) - : type(type) + GLVolume* volume = new GLVolume(Helper::path_color(print.gcode_preview, filter.value).rgba); + if (volume != nullptr) { + filter.volume = volume; + volumes.volumes.emplace_back(volume); } - - bool operator () (const GCodeAnalyzer::PreviewData::Travel::Polyline& p) const + else { - return p.type == type; - } - }; - - if (print.gcode_preview.travel.is_visible) - { - size_t initial_volumes_count = volumes.volumes.size(); - unsigned int types_count = (unsigned int)GCodeAnalyzer::PreviewData::Travel::Num_Types; - - // creates a new volume for each travel type - for (unsigned int i = 0; i < types_count; ++i) - { - GLVolume* volume = new GLVolume(print.gcode_preview.travel.type_colors[i].rgba); - if (volume != nullptr) - volumes.volumes.emplace_back(volume); - else + // an error occourred - restore to previous state and return + s_gcode_preview_data.first_volumes.pop_back(); + if (initial_volumes_count != volumes.volumes.size()) { - // an error occourred - restore to previous state and return std::vector::iterator begin = volumes.volumes.begin() + initial_volumes_count; std::vector::iterator end = volumes.volumes.end(); for (std::vector::iterator it = begin; it < end; ++it) @@ -1644,103 +1648,255 @@ void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& return; } } + } - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + // populates volumes + for (const GCodeAnalyzer::PreviewData::Extrusion::Layer& layer : print.gcode_preview.extrusion.layers) + { + for (const ExtrusionPath& path : layer.paths) { - unsigned int type = (unsigned int)polyline.type; - if (type < types_count) + float path_filter = Helper::path_filter(print.gcode_preview.extrusion.view_type, path); + FiltersList::iterator filter = std::find(filters.begin(), filters.end(), Filter(path_filter, path.role())); + if (filter != filters.end()) { - const BoundingBox3& bbox = polyline.polyline.bounding_box(); - coordf_t print_z = unscale(bbox.max.z); + filter->volume->print_zs.push_back(layer.z); + filter->volume->offsets.push_back(filter->volume->indexed_vertex_array.quad_indices.size()); + filter->volume->offsets.push_back(filter->volume->indexed_vertex_array.triangle_indices.size()); - // selects volume from polyline type - GLVolume* volume = volumes.volumes[initial_volumes_count + type]; - volume->print_zs.push_back(print_z); - volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); - volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); - - // adds polyline to volume - polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *volume); - } - } - - // removes empty volumes - std::vector::iterator it = volumes.volumes.begin() + initial_volumes_count; - while (it != volumes.volumes.end()) - { - GLVolume* volume = *it; - if (volume->print_zs.empty()) - { - delete volume; - it = volumes.volumes.erase(it); - } - else - ++it; - } - - // finalize volumes and sends geometry to gpu - if (volumes.volumes.size() > initial_volumes_count) - { - for (size_t i = initial_volumes_count; i < volumes.volumes.size(); ++i) - { - GLVolume* volume = volumes.volumes[i]; - volume->bounding_box = volume->indexed_vertex_array.bounding_box(); - volume->indexed_vertex_array.finalize_geometry(use_VBOs); + extrusionentity_to_verts(path, layer.z, *filter->volume); } } } + + // finalize volumes and sends geometry to gpu + if (volumes.volumes.size() > initial_volumes_count) + { + for (size_t i = initial_volumes_count; i < volumes.volumes.size(); ++i) + { + GLVolume* volume = volumes.volumes[i]; + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + volume->indexed_vertex_array.finalize_geometry(use_VBOs); + } + } + +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + std::cout << "_load_gcode_extrusion_paths() = " << timer.GetElapsedTimeMillisec() << " ms" << std::endl; +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +} + +void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) +{ +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + WinTimer timer; + timer.Start(); +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + + // Helper structure for types + struct Type + { + GCodeAnalyzer::PreviewData::Travel::EType value; + GLVolume* volume; + + explicit Type(GCodeAnalyzer::PreviewData::Travel::EType value) + : value(value) + , volume(nullptr) + { + } + + bool operator == (const Type& other) const + { + return value == other.value; + } + }; + + typedef std::vector TypesList; + + size_t initial_volumes_count = volumes.volumes.size(); + s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Travel, 0, (unsigned int)initial_volumes_count); + + // detects types + TypesList types; + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + { + if (std::find(types.begin(), types.end(), Type(polyline.type)) == types.end()) + types.emplace_back(polyline.type); + } + + // nothing to render, return + if (types.empty()) + return; + + // creates a new volume for each type + for (Type& type : types) + { + GLVolume* volume = new GLVolume(print.gcode_preview.travel.type_colors[type.value].rgba); + if (volume != nullptr) + { + type.volume = volume; + volumes.volumes.emplace_back(volume); + } + else + { + // an error occourred - restore to previous state and return + if (initial_volumes_count != volumes.volumes.size()) + { + std::vector::iterator begin = volumes.volumes.begin() + initial_volumes_count; + std::vector::iterator end = volumes.volumes.end(); + for (std::vector::iterator it = begin; it < end; ++it) + { + GLVolume* volume = *it; + delete volume; + } + volumes.volumes.erase(begin, end); + return; + } + } + } + + // populates volumes + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + { + TypesList::iterator type = std::find(types.begin(), types.end(), Type(polyline.type)); + if (type != types.end()) + { + type->volume->print_zs.push_back(unscale(polyline.polyline.bounding_box().max.z)); + type->volume->offsets.push_back(type->volume->indexed_vertex_array.quad_indices.size()); + type->volume->offsets.push_back(type->volume->indexed_vertex_array.triangle_indices.size()); + + polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *type->volume); + } + } + + // finalize volumes and sends geometry to gpu + if (volumes.volumes.size() > initial_volumes_count) + { + for (size_t i = initial_volumes_count; i < volumes.volumes.size(); ++i) + { + GLVolume* volume = volumes.volumes[i]; + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + volume->indexed_vertex_array.finalize_geometry(use_VBOs); + } + } + +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + std::cout << "_load_gcode_travel_paths() = " << timer.GetElapsedTimeMillisec() << " ms" << std::endl; +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ } void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) { - if (print.gcode_preview.retraction.is_visible) +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + WinTimer timer; + timer.Start(); +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + + s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Retraction, 0, (unsigned int)volumes.volumes.size()); + + // nothing to render, return + if (print.gcode_preview.retraction.positions.empty()) + return; + + GLVolume* volume = new GLVolume(print.gcode_preview.retraction.color.rgba); + if (volume != nullptr) { - GLVolume* volume = new GLVolume(print.gcode_preview.retraction.color.rgba); - if (volume != nullptr) + volumes.volumes.emplace_back(volume); + + for (const GCodeAnalyzer::PreviewData::Retraction::Position& position : print.gcode_preview.retraction.positions) { - volumes.volumes.emplace_back(volume); + volume->print_zs.push_back(unscale(position.position.z)); + volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); + volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); - for (const GCodeAnalyzer::PreviewData::Retraction::Position& position : print.gcode_preview.retraction.positions) - { - coordf_t print_z = unscale(position.position.z); - volume->print_zs.push_back(print_z); - volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); - volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); - - // adds point to volume - point3_to_verts(position.position, position.width, position.height, *volume); - } - - // finalizes volume - volume->bounding_box = volume->indexed_vertex_array.bounding_box(); - volume->indexed_vertex_array.finalize_geometry(use_VBOs); + point3_to_verts(position.position, position.width, position.height, *volume); } + + // finalize volumes and sends geometry to gpu + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + volume->indexed_vertex_array.finalize_geometry(use_VBOs); } + +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + std::cout << "_load_gcode_retractions() = " << timer.GetElapsedTimeMillisec() << " ms" << std::endl; +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ } void _3DScene::_load_gcode_unretractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) { - if (print.gcode_preview.unretraction.is_visible) +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + WinTimer timer; + timer.Start(); +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + + s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Unretraction, 0, (unsigned int)volumes.volumes.size()); + + // nothing to render, return + if (print.gcode_preview.unretraction.positions.empty()) + return; + + GLVolume* volume = new GLVolume(print.gcode_preview.unretraction.color.rgba); + if (volume != nullptr) { - GLVolume* volume = new GLVolume(print.gcode_preview.unretraction.color.rgba); - if (volume != nullptr) + volumes.volumes.emplace_back(volume); + + for (const GCodeAnalyzer::PreviewData::Retraction::Position& position : print.gcode_preview.unretraction.positions) { - volumes.volumes.emplace_back(volume); + volume->print_zs.push_back(unscale(position.position.z)); + volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); + volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); - for (const GCodeAnalyzer::PreviewData::Retraction::Position& position : print.gcode_preview.unretraction.positions) + point3_to_verts(position.position, position.width, position.height, *volume); + } + + // finalize volumes and sends geometry to gpu + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + volume->indexed_vertex_array.finalize_geometry(use_VBOs); + } + +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + std::cout << "_load_gcode_unretractions() = " << timer.GetElapsedTimeMillisec() << " ms" << std::endl; +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +} + +void _3DScene::_update_gcode_volumes_visibility(const Print& print, GLVolumeCollection& volumes) +{ + unsigned int size = (unsigned int)s_gcode_preview_data.first_volumes.size(); + for (unsigned int i = 0; i < size; ++i) + { + std::vector::iterator begin = volumes.volumes.begin() + s_gcode_preview_data.first_volumes[i].id; + std::vector::iterator end = (i + 1 < size) ? volumes.volumes.begin() + s_gcode_preview_data.first_volumes[i + 1].id : volumes.volumes.end(); + + for (std::vector::iterator it = begin; it != end; ++it) + { + GLVolume* volume = *it; + + switch (s_gcode_preview_data.first_volumes[i].type) { - coordf_t print_z = unscale(position.position.z); - volume->print_zs.push_back(print_z); - volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); - volume->offsets.push_back(volume->indexed_vertex_array.triangle_indices.size()); - - // adds point to volume - point3_to_verts(position.position, position.width, position.height, *volume); + case GCodePreviewData::Extrusion: + { + volume->is_active = print.gcode_preview.extrusion.is_role_flag_set((ExtrusionRole)s_gcode_preview_data.first_volumes[i].flag); + break; + } + case GCodePreviewData::Travel: + { + volume->is_active = print.gcode_preview.travel.is_visible; + break; + } + case GCodePreviewData::Retraction: + { + volume->is_active = print.gcode_preview.retraction.is_visible; + break; + } + case GCodePreviewData::Unretraction: + { + volume->is_active = print.gcode_preview.unretraction.is_visible; + break; + } + default: + { + volume->is_active = false; + break; + } } - - // finalizes volume - volume->bounding_box = volume->indexed_vertex_array.bounding_box(); - volume->indexed_vertex_array.finalize_geometry(use_VBOs); } } } diff --git a/xs/src/slic3r/GUI/3DScene.hpp b/xs/src/slic3r/GUI/3DScene.hpp index 35c41ec2f..ba8a6a977 100644 --- a/xs/src/slic3r/GUI/3DScene.hpp +++ b/xs/src/slic3r/GUI/3DScene.hpp @@ -215,6 +215,11 @@ public: select_group_id(-1), drag_group_id(-1), selected(false), +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +#if ENRICO_GCODE_PREVIEW + is_active(true), +#endif // ENRICO_GCODE_PREVIEW +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hover(false), tverts_range(0, size_t(-1)), qverts_range(0, size_t(-1)) @@ -251,6 +256,12 @@ public: int drag_group_id; // Is this object selected? bool selected; +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +#if ENRICO_GCODE_PREVIEW + // Whether or not this volume is active for rendering + bool is_active; +#endif // ENRICO_GCODE_PREVIEW +//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // Boolean: Is mouse over this object? bool hover; @@ -266,6 +277,7 @@ public: // Offset into qverts & tverts, or offsets into indices stored into an OpenGL name_index_buffer. std::vector offsets; + int object_idx() const { return this->composite_id / 1000000; } int volume_idx() const { return (this->composite_id / 1000) % 1000; } int instance_idx() const { return this->composite_id % 1000; } @@ -349,6 +361,36 @@ private: class _3DScene { +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW + struct GCodePreviewData + { + enum EType + { + Extrusion, + Travel, + Retraction, + Unretraction, + Num_Geometry_Types + }; + + struct FirstVolume + { + EType type; + unsigned int flag; + unsigned int id; + + FirstVolume(EType type, unsigned int flag, unsigned int id); + }; + + std::vector first_volumes; + + void reset(); + }; + + static GCodePreviewData s_gcode_preview_data; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ public: static void _glew_init(); @@ -380,10 +422,16 @@ public: //############################################################################################################ #if ENRICO_GCODE_PREVIEW private: + // generates gcode extrusion paths geometry static void _load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); + // generates gcode travel paths geometry static void _load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); + // generates gcode retractions geometry static void _load_gcode_retractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); + // generates gcode unretractions geometry static void _load_gcode_unretractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); + // sets gcode geometry visibility according to user selection + static void _update_gcode_volumes_visibility(const Print& print, GLVolumeCollection& volumes); #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ }; From 473bd024fed525aa048aee789cdf8d49f0a33d31 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Fri, 12 Jan 2018 08:55:55 +0100 Subject: [PATCH 05/57] removed debug code --- xs/src/slic3r/GUI/3DScene.cpp | 65 ++++------------------------------- xs/src/slic3r/GUI/3DScene.hpp | 8 ++--- 2 files changed, 10 insertions(+), 63 deletions(-) diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index f79d210a4..60e3ac722 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -12,10 +12,6 @@ #include "GCode/Analyzer.hpp" #endif // ENRICO_GCODE_PREVIEW -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -#include "enrico/wintimer.h" -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - #include #include #include @@ -208,12 +204,12 @@ void GLVolume::set_range(double min_z, double max_z) void GLVolume::render() const { -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +//############################################################################################################ #if ENRICO_GCODE_PREVIEW if (!is_active) return; #endif // ENRICO_GCODE_PREVIEW -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +//############################################################################################################ glCullFace(GL_BACK); glPushMatrix(); @@ -345,12 +341,12 @@ void GLVolumeCollection::render_VBOs() const GLint color_id = (current_program_id > 0) ? glGetUniformLocation(current_program_id, "uniform_color") : -1; for (GLVolume *volume : this->volumes) { -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +//############################################################################################################ #if ENRICO_GCODE_PREVIEW if (!volume->is_active) continue; #endif // ENRICO_GCODE_PREVIEW -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +//############################################################################################################ if (!volume->indexed_vertex_array.vertices_and_normals_interleaved_VBO_id) continue; GLsizei n_triangles = GLsizei(std::min(volume->indexed_vertex_array.triangle_indices_size, volume->tverts_range.second - volume->tverts_range.first)); @@ -389,12 +385,12 @@ void GLVolumeCollection::render_legacy() const for (GLVolume *volume : this->volumes) { assert(! volume->indexed_vertex_array.vertices_and_normals_interleaved_VBO_id); -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +//############################################################################################################ #if ENRICO_GCODE_PREVIEW if (!volume->is_active) continue; #endif // ENRICO_GCODE_PREVIEW -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +//############################################################################################################ GLsizei n_triangles = GLsizei(std::min(volume->indexed_vertex_array.triangle_indices_size, volume->tverts_range.second - volume->tverts_range.first)); GLsizei n_quads = GLsizei(std::min(volume->indexed_vertex_array.quad_indices_size, volume->qverts_range.second - volume->qverts_range.first)); if (n_triangles + n_quads == 0) @@ -1141,13 +1137,6 @@ static inline std::vector parse_colors(const std::vector &sc #if ENRICO_GCODE_PREVIEW void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volumes, bool use_VBOs) { -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - WinTimer timer; - timer.Start(); - - std::cout << "#############################################################################" << std::endl; -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - if (volumes->empty()) { s_gcode_preview_data.reset(); @@ -1159,12 +1148,6 @@ void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volume } _update_gcode_volumes_visibility(*print, *volumes); - -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - std::cout << "VOLUMES COUNT = " << volumes->volumes.size() << std::endl; - std::cout << "FIRST VOLUMES COUNT = " << s_gcode_preview_data.first_volumes.size() << std::endl; - std::cout << "load_gcode_preview() = " << timer.GetElapsedTimeMillisec() << " ms" << std::endl; -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ } #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ @@ -1530,11 +1513,6 @@ void _3DScene::_load_wipe_tower_toolpaths( #if ENRICO_GCODE_PREVIEW void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) { -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - WinTimer timer; - timer.Start(); -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - // helper functions to select data in dependence of the extrusion view type struct Helper { @@ -1678,19 +1656,10 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio volume->indexed_vertex_array.finalize_geometry(use_VBOs); } } - -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - std::cout << "_load_gcode_extrusion_paths() = " << timer.GetElapsedTimeMillisec() << " ms" << std::endl; -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ } void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) { -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - WinTimer timer; - timer.Start(); -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - // Helper structure for types struct Type { @@ -1777,19 +1746,10 @@ void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& volume->indexed_vertex_array.finalize_geometry(use_VBOs); } } - -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - std::cout << "_load_gcode_travel_paths() = " << timer.GetElapsedTimeMillisec() << " ms" << std::endl; -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ } void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) { -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - WinTimer timer; - timer.Start(); -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Retraction, 0, (unsigned int)volumes.volumes.size()); // nothing to render, return @@ -1814,19 +1774,10 @@ void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& v volume->bounding_box = volume->indexed_vertex_array.bounding_box(); volume->indexed_vertex_array.finalize_geometry(use_VBOs); } - -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - std::cout << "_load_gcode_retractions() = " << timer.GetElapsedTimeMillisec() << " ms" << std::endl; -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ } void _3DScene::_load_gcode_unretractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) { -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - WinTimer timer; - timer.Start(); -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Unretraction, 0, (unsigned int)volumes.volumes.size()); // nothing to render, return @@ -1851,10 +1802,6 @@ void _3DScene::_load_gcode_unretractions(const Print& print, GLVolumeCollection& volume->bounding_box = volume->indexed_vertex_array.bounding_box(); volume->indexed_vertex_array.finalize_geometry(use_VBOs); } - -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - std::cout << "_load_gcode_unretractions() = " << timer.GetElapsedTimeMillisec() << " ms" << std::endl; -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ } void _3DScene::_update_gcode_volumes_visibility(const Print& print, GLVolumeCollection& volumes) diff --git a/xs/src/slic3r/GUI/3DScene.hpp b/xs/src/slic3r/GUI/3DScene.hpp index ba8a6a977..8e16136d5 100644 --- a/xs/src/slic3r/GUI/3DScene.hpp +++ b/xs/src/slic3r/GUI/3DScene.hpp @@ -215,11 +215,11 @@ public: select_group_id(-1), drag_group_id(-1), selected(false), -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +//############################################################################################################ #if ENRICO_GCODE_PREVIEW is_active(true), #endif // ENRICO_GCODE_PREVIEW -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +//############################################################################################################ hover(false), tverts_range(0, size_t(-1)), qverts_range(0, size_t(-1)) @@ -256,12 +256,12 @@ public: int drag_group_id; // Is this object selected? bool selected; -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +//############################################################################################################ #if ENRICO_GCODE_PREVIEW // Whether or not this volume is active for rendering bool is_active; #endif // ENRICO_GCODE_PREVIEW -//@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +//############################################################################################################ // Boolean: Is mouse over this object? bool hover; From f62c66f460f24d85054e3aff420333ea0dc56b0a Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Fri, 12 Jan 2018 10:26:01 +0100 Subject: [PATCH 06/57] merge with master --- xs/src/libslic3r/GCode/Analyzer.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index 567892b8e..2f5dafb3c 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -303,7 +303,7 @@ public: static const unsigned int Num_Extrusion_Roles = (unsigned int)erMixed + 1; static const Color Default_Extrusion_Role_Colors[Num_Extrusion_Roles]; - static const EViewType Default_View_Type; + static const EViewType Default_View_Type; struct Ranges { From cc1aaceea6ade49413df01d3dee42ff8c56b2441 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Fri, 12 Jan 2018 11:09:53 +0100 Subject: [PATCH 07/57] fixed compile on linux and osx --- xs/src/libslic3r/BoundingBox.hpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xs/src/libslic3r/BoundingBox.hpp b/xs/src/libslic3r/BoundingBox.hpp index f1782805b..1a15315fb 100644 --- a/xs/src/libslic3r/BoundingBox.hpp +++ b/xs/src/libslic3r/BoundingBox.hpp @@ -30,7 +30,7 @@ public: if (points.empty()) CONFESS("Empty point set supplied to BoundingBoxBase constructor"); - std::vector::const_iterator it = points.begin(); + typename std::vector::const_iterator it = points.begin(); this->min.x = this->max.x = it->x; this->min.y = this->max.y = it->y; for (++it; it != points.end(); ++it) @@ -86,7 +86,7 @@ public: if (points.empty()) CONFESS("Empty point set supplied to BoundingBox3Base constructor"); - std::vector::const_iterator it = points.begin(); + typename std::vector::const_iterator it = points.begin(); this->min.z = this->max.z = it->z; for (++it; it != points.end(); ++it) { From 9e0dd2a96a12bb187767a702145c776ab5ea9d19 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Fri, 12 Jan 2018 11:42:50 +0100 Subject: [PATCH 08/57] fix-attempt to build on linux and osx --- xs/src/libslic3r/GCode/Analyzer.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index 07f047923..5372ff302 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -498,7 +498,7 @@ const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::Range::get_ const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::Range::get_color_at(float value) const { - return empty() ? get_color_at_max() : colors[clamp((unsigned int)0, Colors_Count - 1, unsigned int((value - min) / _step()))]; + return empty() ? get_color_at_max() : colors[clamp((unsigned int)0, Colors_Count - 1, (unsigned int)((value - min) / _step()))]; } float GCodeAnalyzer::PreviewData::Range::_step() const @@ -910,7 +910,7 @@ void GCodeAnalyzer::_processT(const GCodeReader::GCodeLine& line) { int id = (int)::strtol(cmd.substr(1).c_str(), nullptr, 10); // todo - add id validity check ? - if (_get_extruder_id() != id) + if (_get_extruder_id() != (unsigned int)id) { _set_extruder_id(id); From c63e6b74fa15d69bb0ca9ab5b62f8cfd3129d616 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Tue, 16 Jan 2018 14:59:06 +0100 Subject: [PATCH 09/57] GCode Preview - Added legend texture --- lib/Slic3r/GUI/3DScene.pm | 119 ++++++++++++++- lib/Slic3r/GUI/Plater.pm | 13 +- xs/src/libslic3r/GCode/Analyzer.cpp | 112 +++++++++++++- xs/src/libslic3r/GCode/Analyzer.hpp | 29 +++- xs/src/slic3r/GUI/3DScene.cpp | 224 ++++++++++++++++++++++++++++ xs/src/slic3r/GUI/3DScene.hpp | 43 ++++++ xs/xsp/GUI_3DScene.xsp | 21 +++ 7 files changed, 548 insertions(+), 13 deletions(-) diff --git a/lib/Slic3r/GUI/3DScene.pm b/lib/Slic3r/GUI/3DScene.pm index f97586073..ddd18f88d 100644 --- a/lib/Slic3r/GUI/3DScene.pm +++ b/lib/Slic3r/GUI/3DScene.pm @@ -30,6 +30,7 @@ use Slic3r::Geometry qw(PI); # _dirty: boolean flag indicating, that the screen has to be redrawn on EVT_IDLE. # volumes: reference to vector of Slic3r::GUI::3DScene::Volume. # _camera_type: 'perspective' or 'ortho' +# ===================== ENRICO_GCODE_PREVIEW ================================================== __PACKAGE__->mk_accessors( qw(_quat _dirty init enable_picking enable_moving @@ -66,7 +67,50 @@ __PACKAGE__->mk_accessors( qw(_quat _dirty init _camera_target _camera_distance _zoom + + _legend_enabled + ) ); + +#__PACKAGE__->mk_accessors( qw(_quat _dirty init +# enable_picking +# enable_moving +# use_plain_shader +# on_viewport_changed +# on_hover +# on_select +# on_double_click +# on_right_click +# on_move +# on_model_update +# volumes +# _sphi _stheta +# cutting_plane_z +# cut_lines_vertices +# bed_shape +# bed_triangles +# bed_grid_lines +# bed_polygon +# background +# origin +# _mouse_pos +# _hover_volume_idx +# +# _drag_volume_idx +# _drag_start_pos +# _drag_volume_center_offset +# _drag_start_xy +# _dragged +# +# _layer_height_edited +# +# _camera_type +# _camera_target +# _camera_distance +# _zoom +# +# ) ); +# ===================== ENRICO_GCODE_PREVIEW ================================================== use constant TRACKBALLSIZE => 0.8; use constant TURNTABLE_MODE => 1; @@ -137,6 +181,9 @@ sub new { $self->_stheta(45); $self->_sphi(45); $self->_zoom(1); +# ===================== ENRICO_GCODE_PREVIEW ================================================== + $self->_legend_enabled(0); +# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->use_plain_shader(0); # Collection of GLVolume objects @@ -209,6 +256,13 @@ sub new { return $self; } +# ===================== ENRICO_GCODE_PREVIEW ================================================== +sub set_legend_enabled { + my ($self, $value) = @_; + $self->_legend_enabled($value); +} +# ===================== ENRICO_GCODE_PREVIEW ================================================== + sub Destroy { my ($self) = @_; $self->{layer_height_edit_timer}->Stop; @@ -1316,6 +1370,11 @@ sub Render { glDisable(GL_BLEND); } +# ===================== ENRICO_GCODE_PREVIEW ================================================== + # draw gcode preview legend + $self->draw_legend; +# ===================== ENRICO_GCODE_PREVIEW ================================================== + $self->draw_active_object_annotations; $self->SwapBuffers(); @@ -1449,12 +1508,38 @@ sub _variable_layer_thickness_load_reset_image { # Paint the tooltip. sub _render_image { my ($self, $image, $l, $r, $b, $t) = @_; +# ===================== ENRICO_GCODE_PREVIEW ================================================== + $self->_render_texture($image->{texture_id}, $l, $r, $b, $t); + +# glColor4f(1.,1.,1.,1.); +# glDisable(GL_LIGHTING); +# glEnable(GL_BLEND); +# glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); +# glEnable(GL_TEXTURE_2D); +# glBindTexture(GL_TEXTURE_2D, $image->{texture_id}); +# glBegin(GL_QUADS); +# glTexCoord2d(0.,1.); glVertex3f($l, $b, 0); +# glTexCoord2d(1.,1.); glVertex3f($r, $b, 0); +# glTexCoord2d(1.,0.); glVertex3f($r, $t, 0); +# glTexCoord2d(0.,0.); glVertex3f($l, $t, 0); +# glEnd(); +# glBindTexture(GL_TEXTURE_2D, 0); +# glDisable(GL_TEXTURE_2D); +# glDisable(GL_BLEND); +# glEnable(GL_LIGHTING); +# ===================== ENRICO_GCODE_PREVIEW ================================================== +} + +# ===================== ENRICO_GCODE_PREVIEW ================================================== +sub _render_texture { + my ($self, $tex_id, $l, $r, $b, $t) = @_; + glColor4f(1.,1.,1.,1.); glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, $image->{texture_id}); + glBindTexture(GL_TEXTURE_2D, $tex_id); glBegin(GL_QUADS); glTexCoord2d(0.,1.); glVertex3f($l, $b, 0); glTexCoord2d(1.,1.); glVertex3f($r, $b, 0); @@ -1466,6 +1551,7 @@ sub _render_image { glDisable(GL_BLEND); glEnable(GL_LIGHTING); } +# ===================== ENRICO_GCODE_PREVIEW ================================================== sub draw_active_object_annotations { # $fakecolor is a boolean indicating, that the objects shall be rendered in a color coding the object index for picking. @@ -1579,6 +1665,37 @@ sub draw_active_object_annotations { glEnable(GL_DEPTH_TEST); } +# ===================== ENRICO_GCODE_PREVIEW ================================================== +sub draw_legend { + my ($self) = @_; + + if ($self->_legend_enabled) + { + my $tex_id = Slic3r::GUI::_3DScene::get_legend_texture_id; + if ($tex_id > 0) + { + glDisable(GL_DEPTH_TEST); + glPushMatrix(); + glLoadIdentity(); + + my $tex_w = Slic3r::GUI::_3DScene::get_legend_texture_width; + my $tex_h = Slic3r::GUI::_3DScene::get_legend_texture_height; + + my ($cw, $ch) = $self->GetSizeWH; + + my $l = (-0.5 * $cw) / $self->_zoom; + my $t = (0.5 * $ch) / $self->_zoom; + my $r = $l + $tex_w / $self->_zoom; + my $b = $t - $tex_h / $self->_zoom; + $self->_render_texture($tex_id, $l, $r, $b, $t); + + glPopMatrix(); + glEnable(GL_DEPTH_TEST); + } + } +} +# ===================== ENRICO_GCODE_PREVIEW ================================================== + sub opengl_info { my ($self, %params) = @_; diff --git a/lib/Slic3r/GUI/Plater.pm b/lib/Slic3r/GUI/Plater.pm index 63e628f3e..d7afe0e30 100644 --- a/lib/Slic3r/GUI/Plater.pm +++ b/lib/Slic3r/GUI/Plater.pm @@ -153,8 +153,17 @@ sub new { EVT_NOTEBOOK_PAGE_CHANGED($self, $self->{preview_notebook}, sub { my $preview = $self->{preview_notebook}->GetCurrentPage; - $self->{preview3D}->load_print(1) if ($preview == $self->{preview3D}); - $preview->OnActivate if $preview->can('OnActivate'); +# ===================== ENRICO_GCODE_PREVIEW ================================================== + if ($preview == $self->{preview3D}) + { + $self->{preview3D}->canvas->set_legend_enabled(1); + $self->{preview3D}->load_print(1); + } else { + $self->{preview3D}->canvas->set_legend_enabled(0); + } +# $self->{preview3D}->load_print(1) if ($preview == $self->{preview3D}); +# ===================== ENRICO_GCODE_PREVIEW ================================================== + $preview->OnActivate if $preview->can('OnActivate'); }); # toolbar for object manipulation diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index 5372ff302..ae857e37e 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -436,6 +436,16 @@ GCodeAnalyzer::PreviewData::Color::Color(float r, float g, float b, float a) rgba[3] = a; } +std::vector GCodeAnalyzer::PreviewData::Color::as_bytes() const +{ + std::vector ret; + for (unsigned int i = 0; i < 4; ++i) + { + ret.push_back((unsigned char)(255.0f * rgba[i])); + } + return ret; +} + GCodeAnalyzer::PreviewData::Extrusion::Layer::Layer(float z, const ExtrusionPaths& paths) : z(z) , paths(paths) @@ -491,6 +501,11 @@ void GCodeAnalyzer::PreviewData::Range::set_from(const Range& other) max = other.max; } +float GCodeAnalyzer::PreviewData::Range::step_size() const +{ + return (max - min) / (float)Colors_Count; +} + const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::Range::get_color_at_max() const { return colors[Colors_Count - 1]; @@ -498,12 +513,13 @@ const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::Range::get_ const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::Range::get_color_at(float value) const { - return empty() ? get_color_at_max() : colors[clamp((unsigned int)0, Colors_Count - 1, (unsigned int)((value - min) / _step()))]; + return empty() ? get_color_at_max() : colors[clamp((unsigned int)0, Colors_Count - 1, (unsigned int)((value - min) / step_size()))]; } -float GCodeAnalyzer::PreviewData::Range::_step() const +GCodeAnalyzer::PreviewData::LegendItem::LegendItem(const std::string& text, const GCodeAnalyzer::PreviewData::Color& color) + : text(text) + , color(color) { - return (max - min) / (float)Colors_Count; } const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Extrusion::Default_Extrusion_Role_Colors[Num_Extrusion_Roles] = @@ -523,6 +539,23 @@ const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Extrusion::D Color(0.0f, 0.0f, 0.0f, 1.0f) // erMixed }; +const std::string GCodeAnalyzer::PreviewData::Extrusion::Default_Extrusion_Role_Names[Num_Extrusion_Roles] +{ + "None", + "Perimeter", + "External perimeter", + "Overhang perimeter", + "Internal infill", + "Solid infill", + "Top solid infill", + "Bridge infill", + "Gap fill", + "Skirt", + "Support material", + "Support material interface", + "Mixed" +}; + const GCodeAnalyzer::PreviewData::Extrusion::EViewType GCodeAnalyzer::PreviewData::Extrusion::Default_View_Type = GCodeAnalyzer::PreviewData::Extrusion::FeatureType; void GCodeAnalyzer::PreviewData::Extrusion::set_default() @@ -534,6 +567,11 @@ void GCodeAnalyzer::PreviewData::Extrusion::set_default() ::memcpy((void*)ranges.width.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color)); ::memcpy((void*)ranges.feedrate.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color)); + for (unsigned int i = 0; i < Num_Extrusion_Roles; ++i) + { + role_names[i] = Default_Extrusion_Role_Names[i]; + } + role_flags = 0; for (unsigned int i = 0; i < Num_Extrusion_Roles; ++i) { @@ -628,6 +666,74 @@ const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::get_extrusi return extrusion.ranges.feedrate.get_color_at(feedrate); } +std::string GCodeAnalyzer::PreviewData::get_legend_title() const +{ + switch (extrusion.view_type) + { + case Extrusion::FeatureType: + return "Feature type"; + case Extrusion::Height: + return "Height (mm)"; + case Extrusion::Width: + return "Width (mm)"; + case Extrusion::Feedrate: + return "Speed (mm/min)"; + } + + return ""; +} + +GCodeAnalyzer::PreviewData::LegendItemsList GCodeAnalyzer::PreviewData::get_legend_items() const +{ + struct Helper + { + static void FillListFromRange(LegendItemsList& list, const Range& range, unsigned int decimals, float scale_factor) + { + list.reserve(Range::Colors_Count); + float step = range.step_size(); + for (unsigned int i = 0; i < Range::Colors_Count; ++i) + { + char buf[32]; + sprintf(buf, "%.*f/%.*f", decimals, scale_factor * (range.min + (float)i * step), decimals, scale_factor * (range.min + (float)(i + 1) * step)); + list.emplace_back(buf, range.colors[i]); + } + } + }; + + LegendItemsList items; + + switch (extrusion.view_type) + { + case Extrusion::FeatureType: + { + items.reserve(erMixed - erPerimeter + 1); + for (unsigned int i = (unsigned int)erPerimeter; i < (unsigned int)erMixed; ++i) + { + items.emplace_back(extrusion.role_names[i], extrusion.role_colors[i]); + } + + break; + } + case Extrusion::Height: + { + Helper::FillListFromRange(items, extrusion.ranges.height, 3, 1.0f); + break; + } + case Extrusion::Width: + { + Helper::FillListFromRange(items, extrusion.ranges.width, 3, 1.0f); + break; + } + case Extrusion::Feedrate: + { + Helper::FillListFromRange(items, extrusion.ranges.feedrate, 0, 60.0f); + break; + } + } + + return items; +} + GCodeAnalyzer::GCodeAnalyzer() { reset(); diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index 2f5dafb3c..26c525b4c 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -206,9 +206,9 @@ public: ExtrusionRole extrusion_role; unsigned int extruder_id; double mm3_per_mm; - float width; - float height; - float feedrate; + float width; // mm + float height; // mm + float feedrate; // mm/s Metadata(); Metadata(ExtrusionRole extrusion_role, unsigned int extruder_id, double mm3_per_mm, float width, float height, float feedrate); @@ -264,6 +264,8 @@ public: Color(); Color(float r, float g, float b, float a); + std::vector as_bytes() const; + static const Color Dummy; }; @@ -282,14 +284,22 @@ public: bool empty() const; void update_from(float value); void set_from(const Range& other); + float step_size() const; const Color& get_color_at(float value) const; const Color& get_color_at_max() const; - - private: - float _step() const; }; + struct LegendItem + { + std::string text; + Color color; + + LegendItem(const std::string& text, const Color& color); + }; + + typedef std::vector LegendItemsList; + struct Extrusion { enum EViewType : unsigned char @@ -303,7 +313,8 @@ public: static const unsigned int Num_Extrusion_Roles = (unsigned int)erMixed + 1; static const Color Default_Extrusion_Role_Colors[Num_Extrusion_Roles]; - static const EViewType Default_View_Type; + static const std::string Default_Extrusion_Role_Names[Num_Extrusion_Roles]; + static const EViewType Default_View_Type; struct Ranges { @@ -324,6 +335,7 @@ public: EViewType view_type; Color role_colors[Num_Extrusion_Roles]; + std::string role_names[Num_Extrusion_Roles]; Ranges ranges; LayersList layers; unsigned int role_flags; @@ -411,6 +423,9 @@ public: const Color& get_extrusion_height_color(float height) const; const Color& get_extrusion_width_color(float width) const; const Color& get_extrusion_feedrate_color(float feedrate) const; + + std::string get_legend_title() const; + LegendItemsList get_legend_items() const; }; private: diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index 60e3ac722..676d75c2f 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -8,9 +8,11 @@ #include "../../libslic3r/Geometry.hpp" #include "../../libslic3r/Print.hpp" #include "../../libslic3r/Slicing.hpp" +//############################################################################################################ #if ENRICO_GCODE_PREVIEW #include "GCode/Analyzer.hpp" #endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ #include #include @@ -23,6 +25,15 @@ #include #include +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +#include +#include +#include +#include +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + namespace Slic3r { void GLIndexedVertexArray::load_mesh_flat_shading(const TriangleMesh &mesh) @@ -1098,6 +1109,197 @@ void _3DScene::GCodePreviewData::reset() } _3DScene::GCodePreviewData _3DScene::s_gcode_preview_data; +_3DScene::LegendTexture _3DScene::s_legend_texture; + +const unsigned char _3DScene::LegendTexture::Squares_Border_Color[3] = { 64, 64, 64 }; +const unsigned char _3DScene::LegendTexture::Background_Color[3] = { 9, 91, 134 }; +const unsigned char _3DScene::LegendTexture::Opacity = 255; + +_3DScene::LegendTexture::LegendTexture() + : m_tex_id(0) + , m_tex_width(0) + , m_tex_height(0) +{ +} + +_3DScene::LegendTexture::~LegendTexture() +{ + _destroy_texture(); +} + +bool _3DScene::LegendTexture::generate_texture(const Print& print) +{ + _destroy_texture(); + + // collects items to render + const std::string& title = print.gcode_preview.get_legend_title(); + const GCodeAnalyzer::PreviewData::LegendItemsList& items = print.gcode_preview.get_legend_items(); + + unsigned int items_count = (unsigned int)items.size(); + if (items_count == 0) + // nothing to render, return + return false; + + wxMemoryDC memDC; + // select default font + memDC.SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT)); + + // calculates texture size + wxCoord w, h; + memDC.GetTextExtent(title, &w, &h); + unsigned int title_width = (unsigned int)w; + unsigned int title_height = (unsigned int)h; + + unsigned int max_text_width = 0; + unsigned int max_text_height = 0; + for (const GCodeAnalyzer::PreviewData::LegendItem& item : items) + { + memDC.GetTextExtent(item.text, &w, &h); + max_text_width = std::max(max_text_width, (unsigned int)w); + max_text_height = std::max(max_text_height, (unsigned int)h); + } + + m_tex_width = std::max(2 * Px_Border + title_width, 2 * (Px_Border + Px_Square_Contour) + Px_Square + Px_Text_Offset + max_text_width); + m_tex_height = 2 * (Px_Border + Px_Square_Contour) + title_height + Px_Title_Offset + items_count * Px_Square; + if (items_count > 1) + m_tex_height += (items_count - 1) * Px_Square_Contour; + + // generates bitmap + wxBitmap bitmap(m_tex_width, m_tex_height); + +#if defined(__APPLE__) || defined(_MSC_VER) + bitmap.UseAlpha(); +#endif + + memDC.SelectObject(bitmap); + memDC.SetBackground(wxBrush(wxColour(Background_Color[0], Background_Color[1], Background_Color[2]))); + memDC.Clear(); + + memDC.SetTextForeground(*wxWHITE); + + // draw title + unsigned int title_x = Px_Border; + unsigned int title_y = Px_Border; + memDC.DrawText(title, title_x, title_y); + + // draw icons contours as background + unsigned int squares_contour_x = Px_Border; + unsigned int squares_contour_y = Px_Border + title_height + Px_Title_Offset; + unsigned int squares_contour_width = Px_Square + 2 * Px_Square_Contour; + unsigned int squares_contour_height = items_count * Px_Square + 2 * Px_Square_Contour; + if (items_count > 1) + squares_contour_height += (items_count - 1) * Px_Square_Contour; + + wxColour color(Squares_Border_Color[0], Squares_Border_Color[1], Squares_Border_Color[2]); + wxPen pen(color); + wxBrush brush(color); + memDC.SetPen(pen); + memDC.SetBrush(brush); + memDC.DrawRectangle(wxRect(squares_contour_x, squares_contour_y, squares_contour_width, squares_contour_height)); + + // draw items (colored icon + text) + unsigned int icon_x = squares_contour_x + Px_Square_Contour; + unsigned int icon_x_inner = icon_x + 1; + unsigned int icon_y = squares_contour_y + Px_Square_Contour; + unsigned int icon_y_step = Px_Square + Px_Square_Contour; + + unsigned int text_x = icon_x + Px_Square + Px_Text_Offset; + unsigned int text_y_offset = (Px_Square - max_text_height) / 2; + + unsigned int px_inner_square = Px_Square - 2; + + for (const GCodeAnalyzer::PreviewData::LegendItem& item : items) + { + // draw darker icon perimeter + const std::vector& item_color_bytes = item.color.as_bytes(); + wxImage::HSVValue dark_hsv = wxImage::RGBtoHSV(wxImage::RGBValue(item_color_bytes[0], item_color_bytes[1], item_color_bytes[2])); + dark_hsv.value *= 0.75; + wxImage::RGBValue dark_rgb = wxImage::HSVtoRGB(dark_hsv); + color.Set(dark_rgb.red, dark_rgb.green, dark_rgb.blue, item_color_bytes[3]); + pen.SetColour(color); + brush.SetColour(color); + memDC.SetPen(pen); + memDC.SetBrush(brush); + memDC.DrawRectangle(wxRect(icon_x, icon_y, Px_Square, Px_Square)); + + // draw icon interior + color.Set(item_color_bytes[0], item_color_bytes[1], item_color_bytes[2], item_color_bytes[3]); + pen.SetColour(color); + brush.SetColour(color); + memDC.SetPen(pen); + memDC.SetBrush(brush); + memDC.DrawRectangle(wxRect(icon_x_inner, icon_y + 1, px_inner_square, px_inner_square)); + + // draw text + memDC.DrawText(item.text, text_x, icon_y + text_y_offset); + + // update y + icon_y += icon_y_step; + } + + memDC.SelectObject(wxNullBitmap); + + return _create_texture(print, bitmap); +} + +unsigned int _3DScene::LegendTexture::get_texture_id() const +{ + return m_tex_id; +} + +unsigned int _3DScene::LegendTexture::get_texture_width() const +{ + return m_tex_width; +} + +unsigned int _3DScene::LegendTexture::get_texture_height() const +{ + return m_tex_height; +} + +bool _3DScene::LegendTexture::_create_texture(const Print& print, const wxBitmap& bitmap) +{ + if ((m_tex_width == 0) || (m_tex_height == 0)) + return false; + + wxImage image = bitmap.ConvertToImage(); + image.SetMaskColour(Background_Color[0], Background_Color[1], Background_Color[2]); + + // prepare buffer + std::vector buffer(4 * m_tex_width * m_tex_height, 0); + for (unsigned int h = 0; h < m_tex_height; ++h) + { + unsigned int hh = h * m_tex_width; + for (unsigned int w = 0; w < m_tex_width; ++w) + { + unsigned char* px_ptr = buffer.data() + 4 * (hh + w); + *px_ptr++ = image.GetRed(w, h); + *px_ptr++ = image.GetGreen(w, h); + *px_ptr++ = image.GetBlue(w, h); + *px_ptr++ = image.IsTransparent(w, h) ? 0 : Opacity; + } + } + + // sends buffer to gpu + ::glGenTextures(1, &m_tex_id); + ::glBindTexture(GL_TEXTURE_2D, m_tex_id); + ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, (GLsizei)m_tex_width, (GLsizei)m_tex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (const GLvoid*)buffer.data()); + ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1); + ::glBindTexture(GL_TEXTURE_2D, 0); + + return true; +} + +void _3DScene::LegendTexture::_destroy_texture() +{ + if (m_tex_id > 0) + { + ::glDeleteTextures(1, &m_tex_id); + m_tex_id = 0; + } +} #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ @@ -1145,10 +1347,27 @@ void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volume _load_gcode_travel_paths(*print, *volumes, use_VBOs); _load_gcode_retractions(*print, *volumes, use_VBOs); _load_gcode_unretractions(*print, *volumes, use_VBOs); + + _generate_legend_texture(*print); } _update_gcode_volumes_visibility(*print, *volumes); } + +unsigned int _3DScene::get_legend_texture_id() +{ + return s_legend_texture.get_texture_id(); +} + +unsigned int _3DScene::get_legend_texture_width() +{ + return s_legend_texture.get_texture_width(); +} + +unsigned int _3DScene::get_legend_texture_height() +{ + return s_legend_texture.get_texture_height(); +} #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ @@ -1847,6 +2066,11 @@ void _3DScene::_update_gcode_volumes_visibility(const Print& print, GLVolumeColl } } } + +void _3DScene::_generate_legend_texture(const Print& print) +{ + s_legend_texture.generate_texture(print); +} #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ diff --git a/xs/src/slic3r/GUI/3DScene.hpp b/xs/src/slic3r/GUI/3DScene.hpp index 8e16136d5..f869304aa 100644 --- a/xs/src/slic3r/GUI/3DScene.hpp +++ b/xs/src/slic3r/GUI/3DScene.hpp @@ -7,6 +7,12 @@ #include "../../libslic3r/TriangleMesh.hpp" #include "../../libslic3r/Utils.hpp" +//############################################################################################################ +#if ENRICO_GCODE_PREVIEW +class wxBitmap; +#endif // ENRICO_GCODE_PREVIEW +//############################################################################################################ + namespace Slic3r { class Print; @@ -389,6 +395,38 @@ class _3DScene }; static GCodePreviewData s_gcode_preview_data; + + class LegendTexture + { + static const unsigned int Px_Title_Offset = 5; + static const unsigned int Px_Text_Offset = 5; + static const unsigned int Px_Square = 20; + static const unsigned int Px_Square_Contour = 1; + static const unsigned int Px_Border = Px_Square / 2; + static const unsigned char Squares_Border_Color[3]; + static const unsigned char Background_Color[3]; + static const unsigned char Opacity; + + unsigned int m_tex_id; + unsigned int m_tex_width; + unsigned int m_tex_height; + + public: + LegendTexture(); + ~LegendTexture(); + + bool generate_texture(const Print& print); + + unsigned int get_texture_id() const; + unsigned int get_texture_width() const; + unsigned int get_texture_height() const; + + private: + bool _create_texture(const Print& print, const wxBitmap& bitmap); + void _destroy_texture(); + }; + + static LegendTexture s_legend_texture; #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ public: @@ -397,6 +435,9 @@ public: //############################################################################################################ #if ENRICO_GCODE_PREVIEW static void load_gcode_preview(const Print* print, GLVolumeCollection* volumes, bool use_VBOs); + static unsigned int get_legend_texture_id(); + static unsigned int get_legend_texture_width(); + static unsigned int get_legend_texture_height(); #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ @@ -432,6 +473,8 @@ private: static void _load_gcode_unretractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); // sets gcode geometry visibility according to user selection static void _update_gcode_volumes_visibility(const Print& print, GLVolumeCollection& volumes); + // generates the legend texture in dependence of the current shown view type + static void _generate_legend_texture(const Print& print); #endif // ENRICO_GCODE_PREVIEW //############################################################################################################ }; diff --git a/xs/xsp/GUI_3DScene.xsp b/xs/xsp/GUI_3DScene.xsp index 186511cc4..f6d729f98 100644 --- a/xs/xsp/GUI_3DScene.xsp +++ b/xs/xsp/GUI_3DScene.xsp @@ -141,6 +141,27 @@ _glew_init() CODE: _3DScene::_glew_init(); +unsigned int +get_legend_texture_id() + CODE: + RETVAL = _3DScene::get_legend_texture_id(); + OUTPUT: + RETVAL + +unsigned int +get_legend_texture_width() + CODE: + RETVAL = _3DScene::get_legend_texture_width(); + OUTPUT: + RETVAL + +unsigned int +get_legend_texture_height() + CODE: + RETVAL = _3DScene::get_legend_texture_height(); + OUTPUT: + RETVAL + void _load_print_toolpaths(print, volumes, tool_colors, use_VBOs) Print *print; From a417cf955d1300558f8bfa231984656f69a6d52d Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Wed, 17 Jan 2018 10:39:05 +0100 Subject: [PATCH 10/57] GCode Preview - Code cleanup --- lib/Slic3r/GUI/3DScene.pm | 72 ------ lib/Slic3r/GUI/Plater.pm | 10 +- lib/Slic3r/GUI/Plater/3DPreview.pm | 32 +-- lib/Slic3r/GUI/Plater/3DToolpaths.pm | 3 +- xs/src/libslic3r/BoundingBox.cpp | 41 ---- xs/src/libslic3r/BoundingBox.hpp | 24 -- xs/src/libslic3r/ExtrusionEntity.hpp | 25 -- xs/src/libslic3r/GCode.cpp | 65 +----- xs/src/libslic3r/GCode.hpp | 47 ---- xs/src/libslic3r/GCode/Analyzer.cpp | 333 +-------------------------- xs/src/libslic3r/GCode/Analyzer.hpp | 161 +------------ xs/src/libslic3r/Line.cpp | 4 - xs/src/libslic3r/Line.hpp | 12 - xs/src/libslic3r/MultiPoint.cpp | 4 - xs/src/libslic3r/MultiPoint.hpp | 8 - xs/src/libslic3r/Point.hpp | 42 ---- xs/src/libslic3r/Polyline.cpp | 4 - xs/src/libslic3r/Polyline.hpp | 4 - xs/src/libslic3r/Print.cpp | 4 - xs/src/libslic3r/Print.hpp | 12 - xs/src/libslic3r/libslic3r.h | 17 -- xs/src/slic3r/GUI/3DScene.cpp | 42 +--- xs/src/slic3r/GUI/3DScene.hpp | 31 +-- xs/xsp/Print.xsp | 2 - 24 files changed, 12 insertions(+), 987 deletions(-) diff --git a/lib/Slic3r/GUI/3DScene.pm b/lib/Slic3r/GUI/3DScene.pm index ddd18f88d..daceb8c49 100644 --- a/lib/Slic3r/GUI/3DScene.pm +++ b/lib/Slic3r/GUI/3DScene.pm @@ -30,7 +30,6 @@ use Slic3r::Geometry qw(PI); # _dirty: boolean flag indicating, that the screen has to be redrawn on EVT_IDLE. # volumes: reference to vector of Slic3r::GUI::3DScene::Volume. # _camera_type: 'perspective' or 'ortho' -# ===================== ENRICO_GCODE_PREVIEW ================================================== __PACKAGE__->mk_accessors( qw(_quat _dirty init enable_picking enable_moving @@ -72,46 +71,6 @@ __PACKAGE__->mk_accessors( qw(_quat _dirty init ) ); -#__PACKAGE__->mk_accessors( qw(_quat _dirty init -# enable_picking -# enable_moving -# use_plain_shader -# on_viewport_changed -# on_hover -# on_select -# on_double_click -# on_right_click -# on_move -# on_model_update -# volumes -# _sphi _stheta -# cutting_plane_z -# cut_lines_vertices -# bed_shape -# bed_triangles -# bed_grid_lines -# bed_polygon -# background -# origin -# _mouse_pos -# _hover_volume_idx -# -# _drag_volume_idx -# _drag_start_pos -# _drag_volume_center_offset -# _drag_start_xy -# _dragged -# -# _layer_height_edited -# -# _camera_type -# _camera_target -# _camera_distance -# _zoom -# -# ) ); -# ===================== ENRICO_GCODE_PREVIEW ================================================== - use constant TRACKBALLSIZE => 0.8; use constant TURNTABLE_MODE => 1; use constant GROUND_Z => -0.02; @@ -181,9 +140,7 @@ sub new { $self->_stheta(45); $self->_sphi(45); $self->_zoom(1); -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->_legend_enabled(0); -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->use_plain_shader(0); # Collection of GLVolume objects @@ -256,12 +213,10 @@ sub new { return $self; } -# ===================== ENRICO_GCODE_PREVIEW ================================================== sub set_legend_enabled { my ($self, $value) = @_; $self->_legend_enabled($value); } -# ===================== ENRICO_GCODE_PREVIEW ================================================== sub Destroy { my ($self) = @_; @@ -1370,10 +1325,8 @@ sub Render { glDisable(GL_BLEND); } -# ===================== ENRICO_GCODE_PREVIEW ================================================== # draw gcode preview legend $self->draw_legend; -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->draw_active_object_annotations; @@ -1508,29 +1461,9 @@ sub _variable_layer_thickness_load_reset_image { # Paint the tooltip. sub _render_image { my ($self, $image, $l, $r, $b, $t) = @_; -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->_render_texture($image->{texture_id}, $l, $r, $b, $t); - -# glColor4f(1.,1.,1.,1.); -# glDisable(GL_LIGHTING); -# glEnable(GL_BLEND); -# glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); -# glEnable(GL_TEXTURE_2D); -# glBindTexture(GL_TEXTURE_2D, $image->{texture_id}); -# glBegin(GL_QUADS); -# glTexCoord2d(0.,1.); glVertex3f($l, $b, 0); -# glTexCoord2d(1.,1.); glVertex3f($r, $b, 0); -# glTexCoord2d(1.,0.); glVertex3f($r, $t, 0); -# glTexCoord2d(0.,0.); glVertex3f($l, $t, 0); -# glEnd(); -# glBindTexture(GL_TEXTURE_2D, 0); -# glDisable(GL_TEXTURE_2D); -# glDisable(GL_BLEND); -# glEnable(GL_LIGHTING); -# ===================== ENRICO_GCODE_PREVIEW ================================================== } -# ===================== ENRICO_GCODE_PREVIEW ================================================== sub _render_texture { my ($self, $tex_id, $l, $r, $b, $t) = @_; @@ -1551,7 +1484,6 @@ sub _render_texture { glDisable(GL_BLEND); glEnable(GL_LIGHTING); } -# ===================== ENRICO_GCODE_PREVIEW ================================================== sub draw_active_object_annotations { # $fakecolor is a boolean indicating, that the objects shall be rendered in a color coding the object index for picking. @@ -1665,7 +1597,6 @@ sub draw_active_object_annotations { glEnable(GL_DEPTH_TEST); } -# ===================== ENRICO_GCODE_PREVIEW ================================================== sub draw_legend { my ($self) = @_; @@ -1694,7 +1625,6 @@ sub draw_legend { } } } -# ===================== ENRICO_GCODE_PREVIEW ================================================== sub opengl_info { @@ -2096,14 +2026,12 @@ sub load_wipe_tower_toolpaths { if ($print->step_done(STEP_WIPE_TOWER)); } -# ===================== ENRICO_GCODE_PREVIEW ================================================== sub load_gcode_preview { my ($self, $print) = @_; $self->SetCurrent($self->GetContext) if $self->UseVBOs; Slic3r::GUI::_3DScene::load_gcode_preview($print, $self->volumes, $self->UseVBOs); } -# ===================== ENRICO_GCODE_PREVIEW ================================================== sub set_toolpaths_range { my ($self, $min_z, $max_z) = @_; diff --git a/lib/Slic3r/GUI/Plater.pm b/lib/Slic3r/GUI/Plater.pm index d7afe0e30..321bb7112 100644 --- a/lib/Slic3r/GUI/Plater.pm +++ b/lib/Slic3r/GUI/Plater.pm @@ -153,7 +153,6 @@ sub new { EVT_NOTEBOOK_PAGE_CHANGED($self, $self->{preview_notebook}, sub { my $preview = $self->{preview_notebook}->GetCurrentPage; -# ===================== ENRICO_GCODE_PREVIEW ================================================== if ($preview == $self->{preview3D}) { $self->{preview3D}->canvas->set_legend_enabled(1); @@ -161,8 +160,7 @@ sub new { } else { $self->{preview3D}->canvas->set_legend_enabled(0); } -# $self->{preview3D}->load_print(1) if ($preview == $self->{preview3D}); -# ===================== ENRICO_GCODE_PREVIEW ================================================== + $preview->OnActivate if $preview->can('OnActivate'); }); @@ -785,9 +783,7 @@ sub remove { splice @{$self->{objects}}, $obj_idx, 1; $self->{model}->delete_object($obj_idx); $self->{print}->delete_object($obj_idx); -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->{print}->clear_gcode_preview_data; -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->{list}->DeleteItem($obj_idx); $self->object_list_changed; @@ -808,9 +804,7 @@ sub reset { @{$self->{objects}} = (); $self->{model}->clear_objects; $self->{print}->clear_objects; -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->{print}->clear_gcode_preview_data; -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->{list}->DeleteAllItems; $self->object_list_changed; @@ -1451,11 +1445,9 @@ sub on_export_completed { # this updates buttons status $self->object_list_changed; -# ===================== ENRICO_GCODE_PREVIEW ================================================== # refresh preview $self->{toolpaths2D}->reload_print if $self->{toolpaths2D}; $self->{preview3D}->reload_print if $self->{preview3D}; -# ===================== ENRICO_GCODE_PREVIEW ================================================== } sub do_print { diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index 0af7a2ebf..379c557b6 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -5,16 +5,10 @@ use utf8; use Slic3r::Print::State ':steps'; use Wx qw(:misc :sizer :slider :statictext :keycode wxWHITE); -# ===================== ENRICO_GCODE_PREVIEW ================================================== use Wx::Event qw(EVT_SLIDER EVT_KEY_DOWN EVT_CHECKBOX EVT_CHOICE EVT_CHECKLISTBOX); -#use Wx::Event qw(EVT_SLIDER EVT_KEY_DOWN EVT_CHECKBOX); -# ===================== ENRICO_GCODE_PREVIEW ================================================== use base qw(Wx::Panel Class::Accessor); -# ===================== ENRICO_GCODE_PREVIEW ================================================== __PACKAGE__->mk_accessors(qw(print enabled _loaded canvas slider_low slider_high single_layer auto_zoom)); -#__PACKAGE__->mk_accessors(qw(print enabled _loaded canvas slider_low slider_high single_layer)); -# ===================== ENRICO_GCODE_PREVIEW ================================================== sub new { my $class = shift; @@ -24,9 +18,7 @@ sub new { $self->{config} = $config; $self->{number_extruders} = 1; $self->{preferred_color_mode} = 'feature'; -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->auto_zoom(1); -# ===================== ENRICO_GCODE_PREVIEW ================================================== # init GUI elements my $canvas = Slic3r::GUI::3DScene->new($self); @@ -69,7 +61,6 @@ sub new { my $checkbox_singlelayer = $self->{checkbox_singlelayer} = Wx::CheckBox->new($self, -1, "1 Layer"); my $checkbox_color_by_extruder = $self->{checkbox_color_by_extruder} = Wx::CheckBox->new($self, -1, "Tool"); -# ===================== ENRICO_GCODE_PREVIEW ================================================== my $choice_view_type = Wx::Choice->new($self, -1); $choice_view_type->Append("Feature type"); $choice_view_type->Append("Height"); @@ -96,8 +87,7 @@ sub new { my $checkbox_travel = Wx::CheckBox->new($self, -1, "Travel"); my $checkbox_retractions = Wx::CheckBox->new($self, -1, "Retractions"); - my $checkbox_unretractions = Wx::CheckBox->new($self, -1, "Unretractions"); -# ===================== ENRICO_GCODE_PREVIEW ================================================== + my $checkbox_unretractions = Wx::CheckBox->new($self, -1, "Unretractions"); my $hsizer = Wx::BoxSizer->new(wxHORIZONTAL); my $vsizer = Wx::BoxSizer->new(wxVERTICAL); @@ -112,13 +102,11 @@ sub new { $vsizer_outer->Add($hsizer, 3, wxALIGN_CENTER_HORIZONTAL, 0); $vsizer_outer->Add($checkbox_singlelayer, 0, wxTOP | wxALIGN_CENTER_HORIZONTAL, 5); $vsizer_outer->Add($checkbox_color_by_extruder, 0, wxTOP | wxALIGN_CENTER_HORIZONTAL, 5); -# ===================== ENRICO_GCODE_PREVIEW ================================================== $vsizer_outer->Add($choice_view_type, 0, wxEXPAND | wxALL | wxALIGN_CENTER_HORIZONTAL, 5); $vsizer_outer->Add($checklist_features, 0, wxTOP | wxALL | wxALIGN_CENTER_HORIZONTAL, 5); $vsizer_outer->Add($checkbox_travel, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); $vsizer_outer->Add($checkbox_retractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); $vsizer_outer->Add($checkbox_unretractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); -# ===================== ENRICO_GCODE_PREVIEW ================================================== my $sizer = Wx::BoxSizer->new(wxHORIZONTAL); $sizer->Add($canvas, 1, wxALL | wxEXPAND, 0); @@ -199,7 +187,6 @@ sub new { $self->reload_print; }); -# ===================== ENRICO_GCODE_PREVIEW ================================================== EVT_CHOICE($self, $choice_view_type, sub { my $selection = $choice_view_type->GetCurrentSelection(); $self->print->set_gcode_preview_type($selection); @@ -238,7 +225,6 @@ sub new { $self->refresh_print; $self->auto_zoom(1); }); -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->SetSizer($sizer); $self->SetMinSize($self->GetSize); @@ -258,16 +244,13 @@ sub reload_print { $self->_loaded(0); if (! $self->IsShown && ! $force) { -# ===================== ENRICO_GCODE_PREVIEW ================================================== # $self->{reload_delayed} = 1; -# ===================== ENRICO_GCODE_PREVIEW ================================================== return; } $self->load_print; } -# ===================== ENRICO_GCODE_PREVIEW ================================================== sub refresh_print { my ($self) = @_; @@ -279,7 +262,6 @@ sub refresh_print { $self->load_print; } -# ===================== ENRICO_GCODE_PREVIEW ================================================== sub load_print { my ($self) = @_; @@ -361,10 +343,9 @@ sub load_print { } if ($self->IsShown) { -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->canvas->load_gcode_preview($self->print); - # load skirt and brim +# # load skirt and brim # $self->canvas->load_print_toolpaths($self->print, \@colors); # $self->canvas->load_wipe_tower_toolpaths($self->print, \@colors); # @@ -375,15 +356,10 @@ sub load_print { # #my @volume_ids = $self->canvas->load_object($object->model_object); # #$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids; # } -# ===================== ENRICO_GCODE_PREVIEW ================================================== -# ===================== ENRICO_GCODE_PREVIEW ================================================== if ($self->auto_zoom) { -# ===================== ENRICO_GCODE_PREVIEW ================================================== - $self->canvas->zoom_to_volumes; -# ===================== ENRICO_GCODE_PREVIEW ================================================== + $self->canvas->zoom_to_volumes; } -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->_loaded(1); } @@ -445,10 +421,8 @@ sub set_number_extruders { # Called by the Platter wxNotebook when this page is activated. sub OnActivate { -# ===================== ENRICO_GCODE_PREVIEW ================================================== # my ($self) = @_; # $self->reload_print(1) if ($self->{reload_delayed}); -# ===================== ENRICO_GCODE_PREVIEW ================================================== } 1; diff --git a/lib/Slic3r/GUI/Plater/3DToolpaths.pm b/lib/Slic3r/GUI/Plater/3DToolpaths.pm index 3dbe59d57..776d8217b 100644 --- a/lib/Slic3r/GUI/Plater/3DToolpaths.pm +++ b/lib/Slic3r/GUI/Plater/3DToolpaths.pm @@ -122,7 +122,6 @@ sub load_print { } if ($self->IsShown) { -# ===================== ENRICO_GCODE_PREVIEW ================================================== $self->canvas->load_gcode_preview($self->print); # # load skirt and brim @@ -135,7 +134,7 @@ sub load_print { # #my @volume_ids = $self->canvas->load_object($object->model_object); # #$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids; # } -# ===================== ENRICO_GCODE_PREVIEW ================================================== + $self->canvas->zoom_to_volumes; $self->_loaded(1); } diff --git a/xs/src/libslic3r/BoundingBox.cpp b/xs/src/libslic3r/BoundingBox.cpp index 929488a3a..91ba88d84 100644 --- a/xs/src/libslic3r/BoundingBox.cpp +++ b/xs/src/libslic3r/BoundingBox.cpp @@ -4,50 +4,9 @@ namespace Slic3r { -//############################################################################################################ -#if !ENRICO_GCODE_PREVIEW -//############################################################################################################ -template -BoundingBoxBase::BoundingBoxBase(const std::vector &points) -{ - if (points.empty()) - CONFESS("Empty point set supplied to BoundingBoxBase constructor"); - typename std::vector::const_iterator it = points.begin(); - this->min.x = this->max.x = it->x; - this->min.y = this->max.y = it->y; - for (++it; it != points.end(); ++it) { - this->min.x = std::min(it->x, this->min.x); - this->min.y = std::min(it->y, this->min.y); - this->max.x = std::max(it->x, this->max.x); - this->max.y = std::max(it->y, this->max.y); - } - this->defined = true; -} -//############################################################################################################ -#endif // !ENRICO_GCODE_PREVIEW -//############################################################################################################ template BoundingBoxBase::BoundingBoxBase(const std::vector &points); template BoundingBoxBase::BoundingBoxBase(const std::vector &points); -//############################################################################################################ -#if !ENRICO_GCODE_PREVIEW -//############################################################################################################ -template -BoundingBox3Base::BoundingBox3Base(const std::vector &points) - : BoundingBoxBase(points) -{ - if (points.empty()) - CONFESS("Empty point set supplied to BoundingBox3Base constructor"); - typename std::vector::const_iterator it = points.begin(); - this->min.z = this->max.z = it->z; - for (++it; it != points.end(); ++it) { - this->min.z = std::min(it->z, this->min.z); - this->max.z = std::max(it->z, this->max.z); - } -} -//############################################################################################################ -#endif // !ENRICO_GCODE_PREVIEW -//############################################################################################################ template BoundingBox3Base::BoundingBox3Base(const std::vector &points); BoundingBox::BoundingBox(const Lines &lines) diff --git a/xs/src/libslic3r/BoundingBox.hpp b/xs/src/libslic3r/BoundingBox.hpp index 1a15315fb..a7334308c 100644 --- a/xs/src/libslic3r/BoundingBox.hpp +++ b/xs/src/libslic3r/BoundingBox.hpp @@ -23,8 +23,6 @@ public: BoundingBoxBase() : defined(false) {}; BoundingBoxBase(const PointClass &pmin, const PointClass &pmax) : min(pmin), max(pmax), defined(pmin.x < pmax.x && pmin.y < pmax.y) {} -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW BoundingBoxBase(const std::vector& points) { if (points.empty()) @@ -42,12 +40,6 @@ public: } this->defined = (this->min.x < this->max.x) && (this->min.y < this->max.y); } -#else -//############################################################################################################ - BoundingBoxBase(const std::vector &points); -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ void merge(const PointClass &point); void merge(const std::vector &points); void merge(const BoundingBoxBase &bb); @@ -78,8 +70,6 @@ public: BoundingBox3Base(const PointClass &pmin, const PointClass &pmax) : BoundingBoxBase(pmin, pmax) { if (pmin.z >= pmax.z) BoundingBoxBase::defined = false; } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW BoundingBox3Base(const std::vector& points) : BoundingBoxBase(points) { @@ -95,12 +85,6 @@ public: } this->defined &= (this->min.z < this->max.z); } -#else -//############################################################################################################ - BoundingBox3Base(const std::vector &points); -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ void merge(const PointClass &point); void merge(const std::vector &points); void merge(const BoundingBox3Base &bb); @@ -138,15 +122,7 @@ class BoundingBox3 : public BoundingBox3Base public: BoundingBox3() : BoundingBox3Base() {}; BoundingBox3(const Point3 &pmin, const Point3 &pmax) : BoundingBox3Base(pmin, pmax) {}; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW BoundingBox3(const Points3& points) : BoundingBox3Base(points) {}; -#else -//############################################################################################################ - BoundingBox3(const std::vector &points) : BoundingBox3Base(points) {}; -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ }; class BoundingBoxf : public BoundingBoxBase diff --git a/xs/src/libslic3r/ExtrusionEntity.hpp b/xs/src/libslic3r/ExtrusionEntity.hpp index 282a0b5d4..a85ccda06 100644 --- a/xs/src/libslic3r/ExtrusionEntity.hpp +++ b/xs/src/libslic3r/ExtrusionEntity.hpp @@ -104,42 +104,17 @@ public: float width; // Height of the extrusion, used for visualization purposed. float height; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW // Feedrate of the extrusion, used for visualization purposed. float feedrate; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW ExtrusionPath(ExtrusionRole role) : mm3_per_mm(-1), width(-1), height(-1), feedrate(0.0f), m_role(role) {}; ExtrusionPath(ExtrusionRole role, double mm3_per_mm, float width, float height) : mm3_per_mm(mm3_per_mm), width(width), height(height), feedrate(0.0f), m_role(role) {}; ExtrusionPath(const ExtrusionPath &rhs) : polyline(rhs.polyline), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), feedrate(rhs.feedrate), m_role(rhs.m_role) {} ExtrusionPath(ExtrusionPath &&rhs) : polyline(std::move(rhs.polyline)), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), feedrate(rhs.feedrate), m_role(rhs.m_role) {} // ExtrusionPath(ExtrusionRole role, const Flow &flow) : m_role(role), mm3_per_mm(flow.mm3_per_mm()), width(flow.width), height(flow.height), feedrate(0.0f) {}; -#else -//############################################################################################################ - ExtrusionPath(ExtrusionRole role) : mm3_per_mm(-1), width(-1), height(-1), m_role(role) {}; - ExtrusionPath(ExtrusionRole role, double mm3_per_mm, float width, float height) : mm3_per_mm(mm3_per_mm), width(width), height(height), m_role(role) {}; - ExtrusionPath(const ExtrusionPath &rhs) : polyline(rhs.polyline), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), m_role(rhs.m_role) {} - ExtrusionPath(ExtrusionPath &&rhs) : polyline(std::move(rhs.polyline)), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), m_role(rhs.m_role) {} -// ExtrusionPath(ExtrusionRole role, const Flow &flow) : m_role(role), mm3_per_mm(flow.mm3_per_mm()), width(flow.width), height(flow.height) {}; -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW ExtrusionPath& operator=(const ExtrusionPath &rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->feedrate = rhs.feedrate, this->polyline = rhs.polyline; return *this; } ExtrusionPath& operator=(ExtrusionPath &&rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->feedrate = rhs.feedrate, this->polyline = std::move(rhs.polyline); return *this; } -#else -//############################################################################################################ - ExtrusionPath& operator=(const ExtrusionPath &rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->polyline = rhs.polyline; return *this; } - ExtrusionPath& operator=(ExtrusionPath &&rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->polyline = std::move(rhs.polyline); return *this; } -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ ExtrusionPath* clone() const { return new ExtrusionPath (*this); } void reverse() { this->polyline.reverse(); } diff --git a/xs/src/libslic3r/GCode.cpp b/xs/src/libslic3r/GCode.cpp index a15318239..14402a1e1 100644 --- a/xs/src/libslic3r/GCode.cpp +++ b/xs/src/libslic3r/GCode.cpp @@ -402,8 +402,6 @@ void GCode::_do_export(Print &print, FILE *file) m_time_estimator.reset(); m_time_estimator.set_dialect(print.config.gcode_flavor); -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW // resets analyzer m_analyzer.reset(); @@ -411,8 +409,6 @@ void GCode::_do_export(Print &print, FILE *file) m_last_mm3_per_mm = GCodeAnalyzer::Default_mm3_per_mm; m_last_width = GCodeAnalyzer::Default_Width; m_last_height = GCodeAnalyzer::Default_Height; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ // How many times will be change_layer() called? // change_layer() in turn increments the progress bar status. @@ -823,12 +819,8 @@ void GCode::_do_export(Print &print, FILE *file) } } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW // starts analizer calculations m_analyzer.calc_gcode_preview_data(print); -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ } std::string GCode::placeholder_parser_process(const std::string &name, const std::string &templ, unsigned int current_extruder_id, const DynamicConfig *config_override) @@ -1320,18 +1312,7 @@ void GCode::process_layer( if (print_object == nullptr) // This layer is empty for this particular object, it has neither object extrusions nor support extrusions at this print_z. continue; -//############################################################################################################ -#if !ENRICO_GCODE_PREVIEW -//############################################################################################################ - if (m_enable_analyzer_markers) { - // Store the binary pointer to the layer object directly into the G-code to be accessed by the GCodeAnalyzer. - char buf[64]; - sprintf(buf, ";_LAYEROBJ:%p\n", m_layer); - gcode += buf; - } -//############################################################################################################ -#endif // !ENRICO_GCODE_PREVIEW -//############################################################################################################ + m_config.apply(print_object->config, true); m_layer = layers[layer_id].layer(); if (m_config.avoid_crossing_perimeters) @@ -2023,18 +2004,8 @@ std::string GCode::extrude_support(const ExtrusionEntityCollection &support_fill return gcode; } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW void GCode::_write(FILE* file, const char *what) -#else -//############################################################################################################ -void GCode::_write(FILE* file, const char *what, size_t size) -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ { -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW if (what != nullptr) { // apply analyzer, if enabled const char* gcode = m_enable_analyzer ? m_analyzer.process_gcode(what).c_str() : what; @@ -2043,16 +2014,6 @@ void GCode::_write(FILE* file, const char *what, size_t size) fwrite(gcode, 1, ::strlen(gcode), file); // updates time estimator and gcode lines vector m_time_estimator.add_gcode_block(gcode); -#else -//############################################################################################################ - if (size > 0) { - // writes string to file - fwrite(what, 1, size, file); - // updates time estimator and gcode lines vector - m_time_estimator.add_gcode_block(what); -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ } } @@ -2086,15 +2047,8 @@ void GCode::_write_format(FILE* file, const char* format, ...) char *bufptr = buffer_dynamic ? (char*)malloc(buflen) : buffer; int res = ::vsnprintf(bufptr, buflen, format, args); if (res > 0) -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW _write(file, bufptr); -#else -//############################################################################################################ - _write(file, bufptr, res); -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ + if (buffer_dynamic) free(bufptr); @@ -2179,8 +2133,6 @@ std::string GCode::_extrude(const ExtrusionPath &path, std::string description, double F = speed * 60; // convert mm/sec to mm/min // extrude arc or line -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW if (m_enable_extrusion_role_markers || m_enable_analyzer) { if (path.role() != m_last_extrusion_role) @@ -2231,19 +2183,6 @@ std::string GCode::_extrude(const ExtrusionPath &path, std::string description, gcode += buf; } } -#else -//############################################################################################################ - if (m_enable_extrusion_role_markers || m_enable_analyzer_markers) { - if (path.role() != m_last_extrusion_role) { - m_last_extrusion_role = path.role(); - char buf[32]; - sprintf(buf, ";_EXTRUSION_ROLE:%d\n", int(path.role())); - gcode += buf; - } - } -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ std::string comment; if (m_enable_cooling_markers) { diff --git a/xs/src/libslic3r/GCode.hpp b/xs/src/libslic3r/GCode.hpp index 97d6d6927..6e42c52d0 100644 --- a/xs/src/libslic3r/GCode.hpp +++ b/xs/src/libslic3r/GCode.hpp @@ -17,11 +17,7 @@ #include "GCode/WipeTower.hpp" #include "GCodeTimeEstimator.hpp" #include "EdgeGrid.hpp" -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW #include "GCode/Analyzer.hpp" -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ #include #include @@ -123,28 +119,16 @@ public: m_enable_loop_clipping(true), m_enable_cooling_markers(false), m_enable_extrusion_role_markers(false), -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW m_enable_analyzer(true), -#else -//############################################################################################################ - m_enable_analyzer_markers(false), -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ m_layer_count(0), m_layer_index(-1), m_layer(nullptr), m_volumetric_speed(0), m_last_pos_defined(false), m_last_extrusion_role(erNone), -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW m_last_mm3_per_mm(GCodeAnalyzer::Default_mm3_per_mm), m_last_width(GCodeAnalyzer::Default_Width), m_last_height(GCodeAnalyzer::Default_Height), -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ m_brim_done(false), m_second_layer_things_done(false), m_last_obj_copy(nullptr, Point(std::numeric_limits::max(), std::numeric_limits::max())) @@ -169,12 +153,8 @@ public: // inside the generated string and after the G-code export finishes. std::string placeholder_parser_process(const std::string &name, const std::string &templ, unsigned int current_extruder_id, const DynamicConfig *config_override = nullptr); bool enable_cooling_markers() const { return m_enable_cooling_markers; } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW bool enable_analyzer() const { return m_enable_analyzer; } void enable_analyzer(bool enable) { m_enable_analyzer = enable; } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ // For Perl bindings, to be used exclusively by unit tests. unsigned int layer_count() const { return m_layer_count; } @@ -267,20 +247,10 @@ protected: // Markers for the Pressure Equalizer to recognize the extrusion type. // The Pressure Equalizer removes the markers from the final G-code. bool m_enable_extrusion_role_markers; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW // Enableds the G-code Analyzer. // Extended markers will be added during G-code generation. // The G-code Analyzer will remove these comments from the final G-code. bool m_enable_analyzer; -#else -//############################################################################################################ - // Extended markers for the G-code Analyzer. - // The G-code Analyzer will remove these comments from the final G-code. - bool m_enable_analyzer_markers; -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ // How many times will change_layer() be called? // change_layer() will update the progress bar. unsigned int m_layer_count; @@ -293,14 +263,10 @@ protected: double m_volumetric_speed; // Support for the extrusion role markers. Which marker is active? ExtrusionRole m_last_extrusion_role; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW // Support for G-Code Analyzer double m_last_mm3_per_mm; float m_last_width; float m_last_height; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ Point m_last_pos; bool m_last_pos_defined; @@ -322,25 +288,12 @@ protected: // Time estimator GCodeTimeEstimator m_time_estimator; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW // Analyzer GCodeAnalyzer m_analyzer; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ // Write a string into a file. -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW void _write(FILE* file, const std::string& what) { this->_write(file, what.c_str()); } void _write(FILE* file, const char *what); -#else -//############################################################################################################ - void _write(FILE* file, const std::string& what) { this->_write(file, what.c_str(), what.size()); } - void _write(FILE* file, const char *what, size_t size); -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ // Write a string into a file. // Add a newline, if the string does not end with a newline already. diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index ae857e37e..49b709ec2 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -4,16 +4,10 @@ #include "../libslic3r.h" #include "../PrintConfig.hpp" -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW #include "Print.hpp" -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ #include "Analyzer.hpp" -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW static const std::string AXIS_STR = "XYZE"; static const float MMMIN_TO_MMSEC = 1.0f / 60.0f; static const float INCHES_TO_MM = 25.4f; @@ -21,333 +15,9 @@ static const float DEFAULT_FEEDRATE = 0.0f; static const unsigned int DEFAULT_EXTRUDER_ID = 0; static const Slic3r::Pointf3 DEFAULT_START_POSITION = Slic3r::Pointf3(0.0f, 0.0f, 0.0f); static const float DEFAULT_START_EXTRUSION = 0.0f; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ namespace Slic3r { -//############################################################################################################ -#if !ENRICO_GCODE_PREVIEW -//############################################################################################################ -void GCodeMovesDB::reset() -{ - for (size_t i = 0; i < m_layers.size(); ++ i) - delete m_layers[i]; - m_layers.clear(); -} - -GCodeAnalyzer::GCodeAnalyzer(const Slic3r::GCodeConfig *config) : - m_config(config) -{ - reset(); - m_moves = new GCodeMovesDB(); -} - -GCodeAnalyzer::~GCodeAnalyzer() -{ - delete m_moves; -} - -void GCodeAnalyzer::reset() -{ - output_buffer.clear(); - output_buffer_length = 0; - - m_current_extruder = 0; - // Zero the position of the XYZE axes + the current feed - memset(m_current_pos, 0, sizeof(float) * 5); - m_current_extrusion_role = erNone; - m_current_extrusion_width = 0; - m_current_extrusion_height = 0; - // Expect the first command to fill the nozzle (deretract). - m_retracted = true; - m_moves->reset(); -} - -const char* GCodeAnalyzer::process(const char *szGCode, bool flush) -{ - // Reset length of the output_buffer. - output_buffer_length = 0; - - if (szGCode != 0) { - const char *p = szGCode; - while (*p != 0) { - // Find end of the line. - const char *endl = p; - // Slic3r always generates end of lines in a Unix style. - for (; *endl != 0 && *endl != '\n'; ++ endl) ; - // Process a G-code line, store it into the provided GCodeLine object. - bool should_output = process_line(p, endl - p); - if (*endl == '\n') - ++ endl; - if (should_output) - push_to_output(p, endl - p); - p = endl; - } - } - - return output_buffer.data(); -} - -// Is a white space? -static inline bool is_ws(const char c) { return c == ' ' || c == '\t'; } -// Is it an end of line? Consider a comment to be an end of line as well. -static inline bool is_eol(const char c) { return c == 0 || c == '\r' || c == '\n' || c == ';'; }; -// Is it a white space or end of line? -static inline bool is_ws_or_eol(const char c) { return is_ws(c) || is_eol(c); }; - -// Eat whitespaces. -static void eatws(const char *&line) -{ - while (is_ws(*line)) - ++ line; -} - -// Parse an int starting at the current position of a line. -// If succeeded, the line pointer is advanced. -static inline int parse_int(const char *&line) -{ - char *endptr = NULL; - long result = strtol(line, &endptr, 10); - if (endptr == NULL || !is_ws_or_eol(*endptr)) - throw std::runtime_error("GCodeAnalyzer: Error parsing an int"); - line = endptr; - return int(result); -}; - -// Parse an int starting at the current position of a line. -// If succeeded, the line pointer is advanced. -static inline float parse_float(const char *&line) -{ - char *endptr = NULL; - float result = strtof(line, &endptr); - if (endptr == NULL || !is_ws_or_eol(*endptr)) - throw std::runtime_error("GCodeAnalyzer: Error parsing a float"); - line = endptr; - return result; -}; - -#define EXTRUSION_ROLE_TAG ";_EXTRUSION_ROLE:" -bool GCodeAnalyzer::process_line(const char *line, const size_t len) -{ - if (strncmp(line, EXTRUSION_ROLE_TAG, strlen(EXTRUSION_ROLE_TAG)) == 0) { - line += strlen(EXTRUSION_ROLE_TAG); - int role = atoi(line); - this->m_current_extrusion_role = ExtrusionRole(role); - return false; - } - -/* - // Set the type, copy the line to the buffer. - buf.type = GCODE_MOVE_TYPE_OTHER; - buf.modified = false; - if (buf.raw.size() < len + 1) - buf.raw.assign(line, line + len + 1); - else - memcpy(buf.raw.data(), line, len); - buf.raw[len] = 0; - buf.raw_length = len; - - memcpy(buf.pos_start, m_current_pos, sizeof(float)*5); - memcpy(buf.pos_end, m_current_pos, sizeof(float)*5); - memset(buf.pos_provided, 0, 5); - - buf.volumetric_extrusion_rate = 0.f; - buf.volumetric_extrusion_rate_start = 0.f; - buf.volumetric_extrusion_rate_end = 0.f; - buf.max_volumetric_extrusion_rate_slope_positive = 0.f; - buf.max_volumetric_extrusion_rate_slope_negative = 0.f; - buf.extrusion_role = m_current_extrusion_role; - - // Parse the G-code line, store the result into the buf. - switch (toupper(*line ++)) { - case 'G': { - int gcode = parse_int(line); - eatws(line); - switch (gcode) { - case 0: - case 1: - { - // G0, G1: A FFF 3D printer does not make a difference between the two. - float new_pos[5]; - memcpy(new_pos, m_current_pos, sizeof(float)*5); - bool changed[5] = { false, false, false, false, false }; - while (!is_eol(*line)) { - char axis = toupper(*line++); - int i = -1; - switch (axis) { - case 'X': - case 'Y': - case 'Z': - i = axis - 'X'; - break; - case 'E': - i = 3; - break; - case 'F': - i = 4; - break; - default: - assert(false); - } - if (i == -1) - throw std::runtime_error(std::string("GCodeAnalyzer: Invalid axis for G0/G1: ") + axis); - buf.pos_provided[i] = true; - new_pos[i] = parse_float(line); - if (i == 3 && m_config->use_relative_e_distances.value) - new_pos[i] += m_current_pos[i]; - changed[i] = new_pos[i] != m_current_pos[i]; - eatws(line); - } - if (changed[3]) { - // Extrusion, retract or unretract. - float diff = new_pos[3] - m_current_pos[3]; - if (diff < 0) { - buf.type = GCODE_MOVE_TYPE_RETRACT; - m_retracted = true; - } else if (! changed[0] && ! changed[1] && ! changed[2]) { - // assert(m_retracted); - buf.type = GCODE_MOVE_TYPE_UNRETRACT; - m_retracted = false; - } else { - assert(changed[0] || changed[1]); - // Moving in XY plane. - buf.type = GCODE_MOVE_TYPE_EXTRUDE; - // Calculate the volumetric extrusion rate. - float diff[4]; - for (size_t i = 0; i < 4; ++ i) - diff[i] = new_pos[i] - m_current_pos[i]; - // volumetric extrusion rate = A_filament * F_xyz * L_e / L_xyz [mm^3/min] - float len2 = diff[0]*diff[0]+diff[1]*diff[1]+diff[2]*diff[2]; - float rate = m_filament_crossections[m_current_extruder] * new_pos[4] * sqrt((diff[3]*diff[3])/len2); - buf.volumetric_extrusion_rate = rate; - buf.volumetric_extrusion_rate_start = rate; - buf.volumetric_extrusion_rate_end = rate; - m_stat.update(rate, sqrt(len2)); - if (rate < 10.f) { - printf("Extremely low flow rate: %f\n", rate); - } - } - } else if (changed[0] || changed[1] || changed[2]) { - // Moving without extrusion. - buf.type = GCODE_MOVE_TYPE_MOVE; - } - memcpy(m_current_pos, new_pos, sizeof(float) * 5); - break; - } - case 92: - { - // G92 : Set Position - // Set a logical coordinate position to a new value without actually moving the machine motors. - // Which axes to set? - bool set = false; - while (!is_eol(*line)) { - char axis = toupper(*line++); - switch (axis) { - case 'X': - case 'Y': - case 'Z': - m_current_pos[axis - 'X'] = (!is_ws_or_eol(*line)) ? parse_float(line) : 0.f; - set = true; - break; - case 'E': - m_current_pos[3] = (!is_ws_or_eol(*line)) ? parse_float(line) : 0.f; - set = true; - break; - default: - throw std::runtime_error(std::string("GCodeAnalyzer: Incorrect axis in a G92 G-code: ") + axis); - } - eatws(line); - } - assert(set); - break; - } - case 10: - case 22: - // Firmware retract. - buf.type = GCODE_MOVE_TYPE_RETRACT; - m_retracted = true; - break; - case 11: - case 23: - // Firmware unretract. - buf.type = GCODE_MOVE_TYPE_UNRETRACT; - m_retracted = false; - break; - default: - // Ignore the rest. - break; - } - break; - } - case 'M': { - int mcode = parse_int(line); - eatws(line); - switch (mcode) { - default: - // Ignore the rest of the M-codes. - break; - } - break; - } - case 'T': - { - // Activate an extruder head. - int new_extruder = parse_int(line); - if (new_extruder != m_current_extruder) { - m_current_extruder = new_extruder; - m_retracted = true; - buf.type = GCODE_MOVE_TYPE_TOOL_CHANGE; - } else { - buf.type = GCODE_MOVE_TYPE_NOOP; - } - break; - } - } - - buf.extruder_id = m_current_extruder; - memcpy(buf.pos_end, m_current_pos, sizeof(float)*5); -*/ - return true; -} - -void GCodeAnalyzer::push_to_output(const char *text, const size_t len, bool add_eol) -{ - // New length of the output buffer content. - size_t len_new = output_buffer_length + len + 1; - if (add_eol) - ++ len_new; - - // Resize the output buffer to a power of 2 higher than the required memory. - if (output_buffer.size() < len_new) { - size_t v = len_new; - // Compute the next highest power of 2 of 32-bit v - // http://graphics.stanford.edu/~seander/bithacks.html - v--; - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - v++; - output_buffer.resize(v); - } - - // Copy the text to the output. - if (len != 0) { - memcpy(output_buffer.data() + output_buffer_length, text, len); - output_buffer_length += len; - } - if (add_eol) - output_buffer[output_buffer_length ++] = '\n'; - output_buffer[output_buffer_length] = 0; -} -//############################################################################################################ -#endif // !ENRICO_GCODE_PREVIEW -//############################################################################################################ - -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW const std::string GCodeAnalyzer::Extrusion_Role_Tag = "_ANALYZER_EXTR_ROLE:"; const std::string GCodeAnalyzer::Mm3_Per_Mm_Tag = "_ANALYZER_MM3_PER_MM:"; const std::string GCodeAnalyzer::Width_Tag = "_ANALYZER_WIDTH:"; @@ -539,6 +209,7 @@ const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Extrusion::D Color(0.0f, 0.0f, 0.0f, 1.0f) // erMixed }; +// todo: merge with Slic3r::ExtrusionRole2String() from GCode.cpp const std::string GCodeAnalyzer::PreviewData::Extrusion::Default_Extrusion_Role_Names[Num_Extrusion_Roles] { "None", @@ -1424,7 +1095,5 @@ GCodeAnalyzer::PreviewData::Color operator * (float f, const GCodeAnalyzer::Prev clamp(0.0f, 1.0f, f * color.rgba[2]), clamp(0.0f, 1.0f, f * color.rgba[3])); } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ } // namespace Slic3r diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index 26c525b4c..c4e71799b 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -5,169 +5,13 @@ #include "../PrintConfig.hpp" #include "../ExtrusionEntity.hpp" -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW #include "Point.hpp" #include "GCodeReader.hpp" -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ namespace Slic3r { -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW - class Print; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ +class Print; -//############################################################################################################ -#if !ENRICO_GCODE_PREVIEW -//############################################################################################################ -enum GCodeMoveType -{ - GCODE_MOVE_TYPE_NOOP, - GCODE_MOVE_TYPE_RETRACT, - GCODE_MOVE_TYPE_UNRETRACT, - GCODE_MOVE_TYPE_TOOL_CHANGE, - GCODE_MOVE_TYPE_MOVE, - GCODE_MOVE_TYPE_EXTRUDE, -}; - -// For visualization purposes, for the purposes of the G-code analysis and timing. -// The size of this structure is 56B. -// Keep the size of this structure as small as possible, because all moves of a complete print -// may be held in RAM. -struct GCodeMove -{ - bool moving_xy(const float* pos_start) const { return fabs(pos_end[0] - pos_start[0]) > 0.f || fabs(pos_end[1] - pos_start[1]) > 0.f; } - bool moving_xy() const { return moving_xy(get_pos_start()); } - bool moving_z (const float* pos_start) const { return fabs(pos_end[2] - pos_start[2]) > 0.f; } - bool moving_z () const { return moving_z(get_pos_start()); } - bool extruding(const float* pos_start) const { return moving_xy() && pos_end[3] > pos_start[3]; } - bool extruding() const { return extruding(get_pos_start()); } - bool retracting(const float* pos_start) const { return pos_end[3] < pos_start[3]; } - bool retracting() const { return retracting(get_pos_start()); } - bool deretracting(const float* pos_start) const { return ! moving_xy() && pos_end[3] > pos_start[3]; } - bool deretracting() const { return deretracting(get_pos_start()); } - - float dist_xy2(const float* pos_start) const { return (pos_end[0] - pos_start[0]) * (pos_end[0] - pos_start[0]) + (pos_end[1] - pos_start[1]) * (pos_end[1] - pos_start[1]); } - float dist_xy2() const { return dist_xy2(get_pos_start()); } - float dist_xyz2(const float* pos_start) const { return (pos_end[0] - pos_start[0]) * (pos_end[0] - pos_start[0]) + (pos_end[1] - pos_start[1]) * (pos_end[1] - pos_start[1]) + (pos_end[2] - pos_start[2]) * (pos_end[2] - pos_start[2]); } - float dist_xyz2() const { return dist_xyz2(get_pos_start()); } - - float dist_xy(const float* pos_start) const { return sqrt(dist_xy2(pos_start)); } - float dist_xy() const { return dist_xy(get_pos_start()); } - float dist_xyz(const float* pos_start) const { return sqrt(dist_xyz2(pos_start)); } - float dist_xyz() const { return dist_xyz(get_pos_start()); } - - float dist_e(const float* pos_start) const { return fabs(pos_end[3] - pos_start[3]); } - float dist_e() const { return dist_e(get_pos_start()); } - - float feedrate() const { return pos_end[4]; } - float time(const float* pos_start) const { return dist_xyz(pos_start) / feedrate(); } - float time() const { return time(get_pos_start()); } - float time_inv(const float* pos_start) const { return feedrate() / dist_xyz(pos_start); } - float time_inv() const { return time_inv(get_pos_start()); } - - const float* get_pos_start() const { assert(type != GCODE_MOVE_TYPE_NOOP); return this[-1].pos_end; } - - // Pack the enums to conserve space. With C++x11 the allocation size could be declared for enums, but for old C++ this is the only portable way. - // GCodeLineType - uint8_t type; - // Index of the active extruder. - uint8_t extruder_id; - // ExtrusionRole - uint8_t extrusion_role; - // For example, is it a bridge flow? Is the fan on? - uint8_t flags; - // X,Y,Z,E,F. Storing the state of the currently active extruder only. - float pos_end[5]; - // Extrusion width, height for this segment in um. - uint16_t extrusion_width; - uint16_t extrusion_height; -}; - -typedef std::vector GCodeMoves; - -struct GCodeLayer -{ - // Index of an object printed. - size_t object_idx; - // Index of an object instance printed. - size_t object_instance_idx; - // Index of the layer printed. - size_t layer_idx; - // Top z coordinate of the layer printed. - float layer_z_top; - - // Moves over this layer. The 0th move is always of type GCODELINETYPE_NOOP and - // it sets the initial position and tool for the layer. - GCodeMoves moves; - - // Indices into m_moves, where the tool changes happen. - // This is useful, if one wants to display just only a piece of the path quickly. - std::vector tool_changes; -}; - -typedef std::vector GCodeLayerPtrs; - -class GCodeMovesDB -{ -public: - GCodeMovesDB() {}; - ~GCodeMovesDB() { reset(); } - void reset(); - GCodeLayerPtrs m_layers; -}; - -// Processes a G-code to extract moves and their types. -// This information is then used to render the print simulation colored by the extrusion type -// or various speeds. -// The GCodeAnalyzer is employed as a G-Code filter. It reads the G-code as it is generated, -// parses the comments generated by Slic3r just for the analyzer, and removes these comments. -class GCodeAnalyzer -{ -public: - GCodeAnalyzer(const Slic3r::GCodeConfig *config); - ~GCodeAnalyzer(); - - void reset(); - - // Process a next batch of G-code lines. Flush the internal buffers if asked for. - const char* process(const char *szGCode, bool flush); - // Length of the buffer returned by process(). - size_t get_output_buffer_length() const { return output_buffer_length; } - -private: - // Keeps the reference, does not own the config. - const Slic3r::GCodeConfig *m_config; - - // Internal data. - // X,Y,Z,E,F - float m_current_pos[5]; - size_t m_current_extruder; - ExtrusionRole m_current_extrusion_role; - uint16_t m_current_extrusion_width; - uint16_t m_current_extrusion_height; - bool m_retracted; - - GCodeMovesDB *m_moves; - - // Output buffer will only grow. It will not be reallocated over and over. - std::vector output_buffer; - size_t output_buffer_length; - - bool process_line(const char *line, const size_t len); - - // Push the text to the end of the output_buffer. - void push_to_output(const char *text, const size_t len, bool add_eol = true); -}; -//############################################################################################################ -#endif // !ENRICO_GCODE_PREVIEW -//############################################################################################################ - -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW class GCodeAnalyzer { public: @@ -553,9 +397,6 @@ private: GCodeAnalyzer::PreviewData::Color operator + (const GCodeAnalyzer::PreviewData::Color& c1, const GCodeAnalyzer::PreviewData::Color& c2); GCodeAnalyzer::PreviewData::Color operator * (float f, const GCodeAnalyzer::PreviewData::Color& color); -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ - } // namespace Slic3r #endif /* slic3r_GCode_Analyzer_hpp_ */ diff --git a/xs/src/libslic3r/Line.cpp b/xs/src/libslic3r/Line.cpp index a4d36d38b..e9d5d7742 100644 --- a/xs/src/libslic3r/Line.cpp +++ b/xs/src/libslic3r/Line.cpp @@ -218,8 +218,6 @@ Line::ccw(const Point& point) const return point.ccw(*this); } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW double Line3::length() const { return a.distance_to(b); @@ -229,8 +227,6 @@ Vector3 Line3::vector() const { return Vector3(b.x - a.x, b.y - a.y, b.z - a.z); } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ Pointf3 Linef3::intersect_plane(double z) const diff --git a/xs/src/libslic3r/Line.hpp b/xs/src/libslic3r/Line.hpp index 514a9ca04..4826017ab 100644 --- a/xs/src/libslic3r/Line.hpp +++ b/xs/src/libslic3r/Line.hpp @@ -7,20 +7,12 @@ namespace Slic3r { class Line; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW class Line3; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ class Linef3; class Polyline; class ThickLine; typedef std::vector Lines; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW typedef std::vector Lines3; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ typedef std::vector ThickLines; class Line @@ -66,8 +58,6 @@ class ThickLine : public Line ThickLine(Point _a, Point _b) : Line(_a, _b), a_width(0), b_width(0) {}; }; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW class Line3 { public: @@ -80,8 +70,6 @@ public: double length() const; Vector3 vector() const; }; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ class Linef { diff --git a/xs/src/libslic3r/MultiPoint.cpp b/xs/src/libslic3r/MultiPoint.cpp index 54c639a96..2e65492cd 100644 --- a/xs/src/libslic3r/MultiPoint.cpp +++ b/xs/src/libslic3r/MultiPoint.cpp @@ -214,8 +214,6 @@ MultiPoint::_douglas_peucker(const Points &points, const double tolerance) return results; } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW void MultiPoint3::translate(double x, double y) { for (Point3& p : points) @@ -270,8 +268,6 @@ bool MultiPoint3::remove_duplicate_points() return false; } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ BoundingBox get_extents(const MultiPoint &mp) { diff --git a/xs/src/libslic3r/MultiPoint.hpp b/xs/src/libslic3r/MultiPoint.hpp index ed5bad3a8..0970e9a67 100644 --- a/xs/src/libslic3r/MultiPoint.hpp +++ b/xs/src/libslic3r/MultiPoint.hpp @@ -10,11 +10,7 @@ namespace Slic3r { class BoundingBox; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW class BoundingBox3; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ class MultiPoint { @@ -84,8 +80,6 @@ public: static Points _douglas_peucker(const Points &points, const double tolerance); }; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW class MultiPoint3 { public: @@ -104,8 +98,6 @@ public: // Remove exact duplicates, return true if any duplicate has been removed. bool remove_duplicate_points(); }; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ extern BoundingBox get_extents(const MultiPoint &mp); extern BoundingBox get_extents_rotated(const std::vector &points, double angle); diff --git a/xs/src/libslic3r/Point.hpp b/xs/src/libslic3r/Point.hpp index a322bc4fa..efed236c8 100644 --- a/xs/src/libslic3r/Point.hpp +++ b/xs/src/libslic3r/Point.hpp @@ -14,29 +14,17 @@ class Line; class Linef; class MultiPoint; class Point; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW class Point3; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ class Pointf; class Pointf3; typedef Point Vector; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW typedef Point3 Vector3; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ typedef Pointf Vectorf; typedef Pointf3 Vectorf3; typedef std::vector Points; typedef std::vector PointPtrs; typedef std::vector PointConstPtrs; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW typedef std::vector Points3; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ typedef std::vector Pointfs; typedef std::vector Pointf3s; @@ -201,24 +189,11 @@ public: static Point3 new_scale(coordf_t x, coordf_t y, coordf_t z) { return Point3(coord_t(scale_(x)), coord_t(scale_(y)), coord_t(scale_(z))); } bool operator==(const Point3 &rhs) const { return this->x == rhs.x && this->y == rhs.y && this->z == rhs.z; } bool operator!=(const Point3 &rhs) const { return ! (*this == rhs); } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW bool coincides_with(const Point3& rhs) const { return this->x == rhs.x && this->y == rhs.y && this->z == rhs.z; } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ private: // Hide the following inherited methods: -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW bool operator==(const Point &rhs) const; bool operator!=(const Point &rhs) const; -#else -//############################################################################################################ - bool operator==(const Point &rhs); - bool operator!=(const Point &rhs); -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ }; std::ostream& operator<<(std::ostream &stm, const Pointf &pointf); @@ -273,11 +248,7 @@ public: static Pointf3 new_unscale(coord_t x, coord_t y, coord_t z) { return Pointf3(unscale(x), unscale(y), unscale(z)); }; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW static Pointf3 new_unscale(const Point3& p) { return Pointf3(unscale(p.x), unscale(p.y), unscale(p.z)); } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ void scale(double factor); void translate(const Vectorf3 &vector); void translate(double x, double y, double z); @@ -290,21 +261,10 @@ public: private: // Hide the following inherited methods: -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW bool operator==(const Pointf &rhs) const; bool operator!=(const Pointf &rhs) const; -#else -//############################################################################################################ - bool operator==(const Pointf &rhs); - bool operator!=(const Pointf &rhs); -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ }; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW inline Pointf3 operator+(const Pointf3& p1, const Pointf3& p2) { return Pointf3(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z); } inline Pointf3 operator-(const Pointf3& p1, const Pointf3& p2) { return Pointf3(p1.x - p2.x, p1.y - p2.y, p1.z - p2.z); } inline Pointf3 operator-(const Pointf3& p) { return Pointf3(-p.x, -p.y, -p.z); } @@ -317,8 +277,6 @@ inline Pointf3 normalize(const Pointf3& v) coordf_t len = ::sqrt(sqr(v.x) + sqr(v.y) + sqr(v.z)); return (len != 0.0) ? 1.0 / len * v : Pointf3(0.0, 0.0, 0.0); } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ template inline TO convert_to(const Point &src) { return TO(typename TO::coord_type(src.x), typename TO::coord_type(src.y)); } template inline TO convert_to(const Pointf &src) { return TO(typename TO::coord_type(src.x), typename TO::coord_type(src.y)); } diff --git a/xs/src/libslic3r/Polyline.cpp b/xs/src/libslic3r/Polyline.cpp index 9462332ff..3432506c6 100644 --- a/xs/src/libslic3r/Polyline.cpp +++ b/xs/src/libslic3r/Polyline.cpp @@ -278,8 +278,6 @@ ThickPolyline::reverse() std::swap(this->endpoints.first, this->endpoints.second); } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW Lines3 Polyline3::lines() const { Lines3 lines; @@ -293,7 +291,5 @@ Lines3 Polyline3::lines() const } return lines; } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ } diff --git a/xs/src/libslic3r/Polyline.hpp b/xs/src/libslic3r/Polyline.hpp index 95ee72d0c..a1d777692 100644 --- a/xs/src/libslic3r/Polyline.hpp +++ b/xs/src/libslic3r/Polyline.hpp @@ -129,8 +129,6 @@ class ThickPolyline : public Polyline { void reverse(); }; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW class Polyline3 : public MultiPoint3 { public: @@ -138,8 +136,6 @@ public: }; typedef std::vector Polylines3; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ } diff --git a/xs/src/libslic3r/Print.cpp b/xs/src/libslic3r/Print.cpp index 2173ae9b1..d0af38327 100644 --- a/xs/src/libslic3r/Print.cpp +++ b/xs/src/libslic3r/Print.cpp @@ -66,8 +66,6 @@ bool Print::reload_model_instances() return invalidated; } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW void Print::clear_gcode_preview_data() { gcode_preview.reset(); @@ -103,8 +101,6 @@ void Print::set_gcode_preview_unretractions_visible(bool visible) { gcode_preview.unretraction.is_visible = visible; } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ PrintRegion* Print::add_region() { diff --git a/xs/src/libslic3r/Print.hpp b/xs/src/libslic3r/Print.hpp index 2ded86ee9..4c2284446 100644 --- a/xs/src/libslic3r/Print.hpp +++ b/xs/src/libslic3r/Print.hpp @@ -15,11 +15,7 @@ #include "Slicing.hpp" #include "GCode/ToolOrdering.hpp" #include "GCode/WipeTower.hpp" -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW #include "GCode/Analyzer.hpp" -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ #include "tbb/atomic.h" @@ -245,11 +241,7 @@ public: // ordered collections of extrusion paths to build skirt loops and brim ExtrusionEntityCollection skirt, brim; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW GCodeAnalyzer::PreviewData gcode_preview; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ Print() : total_used_filament(0), total_extruded_volume(0) { restart(); } ~Print() { clear_objects(); } @@ -263,8 +255,6 @@ public: void reload_object(size_t idx); bool reload_model_instances(); -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW void clear_gcode_preview_data(); void set_gcode_preview_type(unsigned char type); void set_gcode_preview_extrusion_flags(unsigned int flags); @@ -272,8 +262,6 @@ public: void set_gcode_preview_travel_visible(bool visible); void set_gcode_preview_retractions_visible(bool visible); void set_gcode_preview_unretractions_visible(bool visible); -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ // methods for handling regions PrintRegion* get_region(size_t idx) { return regions.at(idx); } diff --git a/xs/src/libslic3r/libslic3r.h b/xs/src/libslic3r/libslic3r.h index 24d7f4889..5a6a0eaeb 100644 --- a/xs/src/libslic3r/libslic3r.h +++ b/xs/src/libslic3r/libslic3r.h @@ -163,29 +163,12 @@ static inline T clamp(const T low, const T high, const T value) return std::max(low, std::min(high, value)); } -//############################################################################################################ -#define ENRICO_GCODE_PREVIEW 1 -//############################################################################################################ - -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW template static inline T lerp(const T& a, const T& b, Number t) { assert((t >= Number(-EPSILON)) && (t <= Number(1) + Number(EPSILON))); return (Number(1) - t) * a + t * b; } -#else -//############################################################################################################ -template -static inline T lerp(const T a, const T b, const T t) -{ - assert(t >= T(-EPSILON) && t <= T(1.+EPSILON)); - return (1. - t) * a + t * b; -} -//############################################################################################################ -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ } // namespace Slic3r diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index 676d75c2f..a79e38035 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -8,11 +8,7 @@ #include "../../libslic3r/Geometry.hpp" #include "../../libslic3r/Print.hpp" #include "../../libslic3r/Slicing.hpp" -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW #include "GCode/Analyzer.hpp" -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ #include #include @@ -25,14 +21,10 @@ #include #include -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW #include #include #include #include -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ namespace Slic3r { @@ -215,12 +207,8 @@ void GLVolume::set_range(double min_z, double max_z) void GLVolume::render() const { -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW if (!is_active) return; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ glCullFace(GL_BACK); glPushMatrix(); @@ -352,12 +340,9 @@ void GLVolumeCollection::render_VBOs() const GLint color_id = (current_program_id > 0) ? glGetUniformLocation(current_program_id, "uniform_color") : -1; for (GLVolume *volume : this->volumes) { -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW if (!volume->is_active) continue; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ + if (!volume->indexed_vertex_array.vertices_and_normals_interleaved_VBO_id) continue; GLsizei n_triangles = GLsizei(std::min(volume->indexed_vertex_array.triangle_indices_size, volume->tverts_range.second - volume->tverts_range.first)); @@ -396,12 +381,9 @@ void GLVolumeCollection::render_legacy() const for (GLVolume *volume : this->volumes) { assert(! volume->indexed_vertex_array.vertices_and_normals_interleaved_VBO_id); -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW if (!volume->is_active) continue; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ + GLsizei n_triangles = GLsizei(std::min(volume->indexed_vertex_array.triangle_indices_size, volume->tverts_range.second - volume->tverts_range.first)); GLsizei n_quads = GLsizei(std::min(volume->indexed_vertex_array.quad_indices_size, volume->qverts_range.second - volume->qverts_range.first)); if (n_triangles + n_quads == 0) @@ -638,8 +620,6 @@ static void thick_lines_to_indexed_vertex_array( #undef BOTTOM } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW // caller is responsible for supplying NO lines with zero length static void thick_lines_to_indexed_vertex_array(const Lines3& lines, const std::vector& widths, @@ -954,8 +934,6 @@ static void point_to_indexed_vertex_array(const Point3& point, volume.push_triangle(idxs[3], idxs[1], idxs[4]); volume.push_triangle(idxs[0], idxs[3], idxs[4]); } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ static void thick_lines_to_verts( const Lines &lines, @@ -968,8 +946,6 @@ static void thick_lines_to_verts( thick_lines_to_indexed_vertex_array(lines, widths, heights, closed, top_z, volume.indexed_vertex_array); } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW static void thick_lines_to_verts(const Lines3& lines, const std::vector& widths, const std::vector& heights, @@ -995,8 +971,6 @@ static inline void extrusionentity_to_verts(const ExtrusionPath &extrusion_path, std::vector heights(lines.size(), extrusion_path.height); thick_lines_to_verts(lines, widths, heights, false, print_z, volume); } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ // Fill in the qverts and tverts with quads and triangles for the extrusion_path. static inline void extrusionentity_to_verts(const ExtrusionPath &extrusion_path, float print_z, const Point ©, GLVolume &volume) @@ -1081,8 +1055,6 @@ static void extrusionentity_to_verts(const ExtrusionEntity *extrusion_entity, fl } } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW static void polyline3_to_verts(const Polyline3& polyline, double width, double height, GLVolume& volume) { Lines3 lines = polyline.lines(); @@ -1300,8 +1272,6 @@ void _3DScene::LegendTexture::_destroy_texture() m_tex_id = 0; } } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ void _3DScene::_glew_init() { @@ -1335,8 +1305,6 @@ static inline std::vector parse_colors(const std::vector &sc return output; } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volumes, bool use_VBOs) { if (volumes->empty()) @@ -1368,8 +1336,6 @@ unsigned int _3DScene::get_legend_texture_height() { return s_legend_texture.get_texture_height(); } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ // Create 3D thick extrusion lines for a skirt and brim. // Adds a new Slic3r::GUI::3DScene::Volume to volumes. @@ -1728,8 +1694,6 @@ void _3DScene::_load_wipe_tower_toolpaths( BOOST_LOG_TRIVIAL(debug) << "Loading wipe tower toolpaths in parallel - end"; } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) { // helper functions to select data in dependence of the extrusion view type @@ -2071,7 +2035,5 @@ void _3DScene::_generate_legend_texture(const Print& print) { s_legend_texture.generate_texture(print); } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ } diff --git a/xs/src/slic3r/GUI/3DScene.hpp b/xs/src/slic3r/GUI/3DScene.hpp index f869304aa..ba1a9af71 100644 --- a/xs/src/slic3r/GUI/3DScene.hpp +++ b/xs/src/slic3r/GUI/3DScene.hpp @@ -7,11 +7,7 @@ #include "../../libslic3r/TriangleMesh.hpp" #include "../../libslic3r/Utils.hpp" -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW class wxBitmap; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ namespace Slic3r { @@ -112,13 +108,9 @@ public: push_geometry(float(x), float(y), float(z), float(nx), float(ny), float(nz)); } -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW inline void push_geometry(const Pointf3& p, const Vectorf3& n) { push_geometry(p.x, p.y, p.z, n.x, n.y, n.z); } -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ inline void push_triangle(int idx1, int idx2, int idx3) { if (this->triangle_indices.size() + 3 > this->vertices_and_normals_interleaved.capacity()) @@ -221,11 +213,7 @@ public: select_group_id(-1), drag_group_id(-1), selected(false), -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW is_active(true), -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ hover(false), tverts_range(0, size_t(-1)), qverts_range(0, size_t(-1)) @@ -262,12 +250,8 @@ public: int drag_group_id; // Is this object selected? bool selected; -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW // Whether or not this volume is active for rendering - bool is_active; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ + bool is_active; // Boolean: Is mouse over this object? bool hover; @@ -367,8 +351,6 @@ private: class _3DScene { -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW struct GCodePreviewData { enum EType @@ -427,19 +409,13 @@ class _3DScene }; static LegendTexture s_legend_texture; -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ public: static void _glew_init(); -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW static void load_gcode_preview(const Print* print, GLVolumeCollection* volumes, bool use_VBOs); static unsigned int get_legend_texture_id(); static unsigned int get_legend_texture_width(); static unsigned int get_legend_texture_height(); -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ static void _load_print_toolpaths( const Print *print, @@ -453,15 +429,12 @@ public: const std::vector &tool_colors, bool use_VBOs); - static void _load_wipe_tower_toolpaths( const Print *print, GLVolumeCollection *volumes, const std::vector &tool_colors_str, bool use_VBOs); -//############################################################################################################ -#if ENRICO_GCODE_PREVIEW private: // generates gcode extrusion paths geometry static void _load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); @@ -475,8 +448,6 @@ private: static void _update_gcode_volumes_visibility(const Print& print, GLVolumeCollection& volumes); // generates the legend texture in dependence of the current shown view type static void _generate_legend_texture(const Print& print); -#endif // ENRICO_GCODE_PREVIEW -//############################################################################################################ }; } diff --git a/xs/xsp/Print.xsp b/xs/xsp/Print.xsp index d29e087c0..4df4a5865 100644 --- a/xs/xsp/Print.xsp +++ b/xs/xsp/Print.xsp @@ -165,14 +165,12 @@ _constant() size_t object_count() %code%{ RETVAL = THIS->objects.size(); %}; -// ===================== ENRICO_GCODE_PREVIEW ================================================== void clear_gcode_preview_data(); void set_gcode_preview_type(unsigned char type); void set_gcode_preview_extrusion_flags(unsigned int flags); void set_gcode_preview_travel_visible(bool visible); void set_gcode_preview_retractions_visible(bool visible); void set_gcode_preview_unretractions_visible(bool visible); -// ===================== ENRICO_GCODE_PREVIEW ================================================== PrintRegionPtrs* regions() %code%{ RETVAL = &THIS->regions; %}; From 893201d3d98be5ca19a04a0132705ef1480483f5 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Tue, 30 Jan 2018 08:48:58 +0100 Subject: [PATCH 11/57] 3mf Importer - Added miniz library --- xs/CMakeLists.txt | 16 +- xs/src/miniz/miniz.cpp | 594 +++++ xs/src/miniz/miniz.h | 462 ++++ xs/src/miniz/miniz_common.h | 83 + xs/src/miniz/miniz_tdef.cpp | 1555 ++++++++++++ xs/src/miniz/miniz_tdef.h | 181 ++ xs/src/miniz/miniz_tinfl.cpp | 725 ++++++ xs/src/miniz/miniz_tinfl.h | 137 + xs/src/miniz/miniz_zip.cpp | 4659 ++++++++++++++++++++++++++++++++++ xs/src/miniz/miniz_zip.h | 429 ++++ 10 files changed, 8839 insertions(+), 2 deletions(-) create mode 100644 xs/src/miniz/miniz.cpp create mode 100644 xs/src/miniz/miniz.h create mode 100644 xs/src/miniz/miniz_common.h create mode 100644 xs/src/miniz/miniz_tdef.cpp create mode 100644 xs/src/miniz/miniz_tdef.h create mode 100644 xs/src/miniz/miniz_tinfl.cpp create mode 100644 xs/src/miniz/miniz_tinfl.h create mode 100644 xs/src/miniz/miniz_zip.cpp create mode 100644 xs/src/miniz/miniz_zip.h diff --git a/xs/CMakeLists.txt b/xs/CMakeLists.txt index 9e23112c5..4c1f2bb8c 100644 --- a/xs/CMakeLists.txt +++ b/xs/CMakeLists.txt @@ -189,6 +189,18 @@ add_library(admesh STATIC ${LIBDIR}/admesh/util.cpp ) +add_library(miniz STATIC + ${LIBDIR}/miniz/miniz.h + ${LIBDIR}/miniz/miniz_common.h + ${LIBDIR}/miniz/miniz_tdef.h + ${LIBDIR}/miniz/miniz_tinfl.h + ${LIBDIR}/miniz/miniz_zip.h + ${LIBDIR}/miniz/miniz.cpp + ${LIBDIR}/miniz/miniz_tdef.cpp + ${LIBDIR}/miniz/miniz_tinfl.cpp + ${LIBDIR}/miniz/miniz_zip.cpp +) + add_library(clipper STATIC ${LIBDIR}/clipper.cpp ${LIBDIR}/clipper.hpp @@ -348,7 +360,7 @@ if(APPLE) # Ignore undefined symbols of the perl interpreter, they will be found in the caller image. target_link_libraries(XS "-undefined dynamic_lookup") endif() -target_link_libraries(XS libslic3r libslic3r_gui admesh clipper nowide polypartition poly2tri) +target_link_libraries(XS libslic3r libslic3r_gui admesh miniz clipper nowide polypartition poly2tri) if(SLIC3R_PROFILE) target_link_libraries(XS Shiny) endif() @@ -551,7 +563,7 @@ endif() # Create a slic3r executable add_executable(slic3r ${PROJECT_SOURCE_DIR}/src/slic3r.cpp) target_include_directories(XS PRIVATE src src/libslic3r) -target_link_libraries(slic3r libslic3r libslic3r_gui admesh ${Boost_LIBRARIES} clipper ${EXPAT_LIBRARIES} ${GLEW_LIBRARIES} polypartition poly2tri ${TBB_LIBRARIES} ${wxWidgets_LIBRARIES}) +target_link_libraries(slic3r libslic3r libslic3r_gui admesh miniz ${Boost_LIBRARIES} clipper ${EXPAT_LIBRARIES} ${GLEW_LIBRARIES} polypartition poly2tri ${TBB_LIBRARIES} ${wxWidgets_LIBRARIES}) if(SLIC3R_PROFILE) target_link_libraries(Shiny) endif() diff --git a/xs/src/miniz/miniz.cpp b/xs/src/miniz/miniz.cpp new file mode 100644 index 000000000..318a86da9 --- /dev/null +++ b/xs/src/miniz/miniz.cpp @@ -0,0 +1,594 @@ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + +#include "miniz.h" + +typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; + +/* ------------------- zlib-style API's */ + +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) +{ + mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); + size_t block_len = buf_len % 5552; + if (!ptr) + return MZ_ADLER32_INIT; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + return (s2 << 16) + s1; +} + +/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */ +#if 0 + mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) + { + static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; + mz_uint32 crcu32 = (mz_uint32)crc; + if (!ptr) + return MZ_CRC32_INIT; + crcu32 = ~crcu32; + while (buf_len--) + { + mz_uint8 b = *ptr++; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; + } + return ~crcu32; + } +#else +/* Faster, but larger CPU cache footprint. + */ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) +{ + static const mz_uint32 s_crc_table[256] = + { + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, + 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, + 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, + 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, + 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, + 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, + 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, + 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, + 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, + 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, + 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, + 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, + 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, + 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, + 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, + 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, + 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, + 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, + 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, + 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, + 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, + 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, + 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, + 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, + 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, + 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, + 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, + 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, + 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, + 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, + 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D + }; + + mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; + const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr; + + while (buf_len >= 4) + { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF]; + pByte_buf += 4; + buf_len -= 4; + } + + while (buf_len) + { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + ++pByte_buf; + --buf_len; + } + + return ~crc32; +} +#endif + +void mz_free(void *p) +{ + MZ_FREE(p); +} + +void *miniz_def_alloc_func(void *opaque, size_t items, size_t size) +{ + (void)opaque, (void)items, (void)size; + return MZ_MALLOC(items * size); +} +void miniz_def_free_func(void *opaque, void *address) +{ + (void)opaque, (void)address; + MZ_FREE(address); +} +void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size) +{ + (void)opaque, (void)address, (void)items, (void)size; + return MZ_REALLOC(address, items * size); +} + +const char *mz_version(void) +{ + return MZ_VERSION; +} + +#ifndef MINIZ_NO_ZLIB_APIS + +int mz_deflateInit(mz_streamp pStream, int level) +{ + return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); +} + +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) +{ + tdefl_compressor *pComp; + mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); + + if (!pStream) + return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = MZ_ADLER32_INIT; + pStream->msg = NULL; + pStream->reserved = 0; + pStream->total_in = 0; + pStream->total_out = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pComp; + + if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) + { + mz_deflateEnd(pStream); + return MZ_PARAM_ERROR; + } + + return MZ_OK; +} + +int mz_deflateReset(mz_streamp pStream) +{ + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) + return MZ_STREAM_ERROR; + pStream->total_in = pStream->total_out = 0; + tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); + return MZ_OK; +} + +int mz_deflate(mz_streamp pStream, int flush) +{ + size_t in_bytes, out_bytes; + mz_ulong orig_total_in, orig_total_out; + int mz_status = MZ_OK; + + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) + return MZ_STREAM_ERROR; + if (!pStream->avail_out) + return MZ_BUF_ERROR; + + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + + if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) + return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; + + orig_total_in = pStream->total_in; + orig_total_out = pStream->total_out; + for (;;) + { + tdefl_status defl_status; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + + defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); + + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (defl_status < 0) + { + mz_status = MZ_STREAM_ERROR; + break; + } + else if (defl_status == TDEFL_STATUS_DONE) + { + mz_status = MZ_STREAM_END; + break; + } + else if (!pStream->avail_out) + break; + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) + { + if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) + break; + return MZ_BUF_ERROR; /* Can't make forward progress without some input. + */ + } + } + return mz_status; +} + +int mz_deflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) +{ + (void)pStream; + /* This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) */ + return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); +} + +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) +{ + int status; + mz_stream stream; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_deflateInit(&stream, level); + if (status != MZ_OK) + return status; + + status = mz_deflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_deflateEnd(&stream); + return (status == MZ_OK) ? MZ_BUF_ERROR : status; + } + + *pDest_len = stream.total_out; + return mz_deflateEnd(&stream); +} + +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); +} + +mz_ulong mz_compressBound(mz_ulong source_len) +{ + return mz_deflateBound(NULL, source_len); +} + +typedef struct +{ + tinfl_decompressor m_decomp; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; + int m_window_bits; + mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; + tinfl_status m_last_status; +} inflate_state; + +int mz_inflateInit2(mz_streamp pStream, int window_bits) +{ + inflate_state *pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); + if (!pDecomp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pDecomp; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + pDecomp->m_window_bits = window_bits; + + return MZ_OK; +} + +int mz_inflateInit(mz_streamp pStream) +{ + return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); +} + +int mz_inflate(mz_streamp pStream, int flush) +{ + inflate_state *pState; + mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; + size_t in_bytes, out_bytes, orig_avail_in; + tinfl_status status; + + if ((!pStream) || (!pStream->state)) + return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + + pState = (inflate_state *)pStream->state; + if (pState->m_window_bits > 0) + decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + orig_avail_in = pStream->avail_in; + + first_call = pState->m_first_call; + pState->m_first_call = 0; + if (pState->m_last_status < 0) + return MZ_DATA_ERROR; + + if (pState->m_has_flushed && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + pState->m_has_flushed |= (flush == MZ_FINISH); + + if ((flush == MZ_FINISH) && (first_call)) + { + /* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */ + decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); + pState->m_last_status = status; + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (status < 0) + return MZ_DATA_ERROR; + else if (status != TINFL_STATUS_DONE) + { + pState->m_last_status = TINFL_STATUS_FAILED; + return MZ_BUF_ERROR; + } + return MZ_STREAM_END; + } + /* flush != MZ_FINISH then we must assume there's more input. */ + if (flush != MZ_FINISH) + decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + + if (pState->m_dict_avail) + { + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + for (;;) + { + in_bytes = pStream->avail_in; + out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; + + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); + pState->m_last_status = status; + + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + + pState->m_dict_avail = (mz_uint)out_bytes; + + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + + if (status < 0) + return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */ + else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) + return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */ + else if (flush == MZ_FINISH) + { + /* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */ + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */ + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } + else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) + break; + } + + return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; +} + +int mz_inflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + mz_stream stream; + int status; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_inflateInit(&stream); + if (status != MZ_OK) + return status; + + status = mz_inflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_inflateEnd(&stream); + return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; + } + *pDest_len = stream.total_out; + + return mz_inflateEnd(&stream); +} + +const char *mz_error(int err) +{ + static struct + { + int m_err; + const char *m_pDesc; + } s_error_descs[] = + { + { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } + }; + mz_uint i; + for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) + if (s_error_descs[i].m_err == err) + return s_error_descs[i].m_pDesc; + return NULL; +} + +#endif /*MINIZ_NO_ZLIB_APIS */ + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + For more information, please refer to +*/ diff --git a/xs/src/miniz/miniz.h b/xs/src/miniz/miniz.h new file mode 100644 index 000000000..6e7d5fde0 --- /dev/null +++ b/xs/src/miniz/miniz.h @@ -0,0 +1,462 @@ +/* miniz.c 2.0.6 beta - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing + See "unlicense" statement at the end of this file. + Rich Geldreich , last updated Oct. 13, 2013 + Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + + Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define + MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + + * Low-level Deflate/Inflate implementation notes: + + Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or + greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses + approximately as well as zlib. + + Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function + coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory + block large enough to hold the entire file. + + The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. + + * zlib-style API notes: + + miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in + zlib replacement in many apps: + The z_stream struct, optional memory allocation callbacks + deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound + inflateInit/inflateInit2/inflate/inflateEnd + compress, compress2, compressBound, uncompress + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. + Supports raw deflate streams or standard zlib streams with adler-32 checking. + + Limitations: + The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. + I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but + there are no guarantees that miniz.c pulls this off perfectly. + + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by + Alex Evans. Supports 1-4 bytes/pixel images. + + * ZIP archive API notes: + + The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to + get the job done with minimal fuss. There are simple API's to retrieve file information, read files from + existing archives, create new archives, append new files to existing archives, or clone archive data from + one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), + or you can specify custom file read/write callbacks. + + - Archive reading: Just call this function to read a single file from a disk archive: + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, + size_t *pSize, mz_uint zip_flags); + + For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central + directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. + + - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + + The locate operation can optionally check file comments too, which (as one example) can be used to identify + multiple versions of the same file in an archive. This function uses a simple linear search through the central + directory, so it's not very fast. + + Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and + retrieve detailed info on each file by calling mz_zip_reader_file_stat(). + + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data + to disk and builds an exact image of the central directory in memory. The central directory image is written + all at once at the end of the archive file when the archive is finalized. + + The archive writer can optionally align each file's local header and file data to any power of 2 alignment, + which can be useful when the archive will be read from optical media. Also, the writer supports placing + arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still + readable by any ZIP tool. + + - Archive appending: The simple way to add a single file to an archive is to call this function: + + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, + const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + + The archive will be created if it doesn't already exist, otherwise it'll be appended to. + Note the appending is done in-place and is not an atomic operation, so if something goes wrong + during the operation it's possible the archive could be left without a central directory (although the local + file headers and file data will be fine, so the archive will be recoverable). + + For more complex archive modification scenarios: + 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to + preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and + you're done. This is safe but requires a bunch of temporary disk space or heap memory. + + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), + append new files as needed, then finalize the archive which will write an updated central directory to the + original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a + possibility that the archive's central directory could be lost with this method if anything goes wrong, though. + + - ZIP archive support limitations: + No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. + Requires streams capable of seeking. + + * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the + below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + + * Important: For best perf. be sure to customize the below macros for your target platform: + #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 + #define MINIZ_LITTLE_ENDIAN 1 + #define MINIZ_HAS_64BIT_REGISTERS 1 + + * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz + uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files + (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). +*/ +#pragma once + +#include "miniz_common.h" +#include "miniz_tdef.h" +#include "miniz_tinfl.h" + +/* Defines to completely disable specific portions of miniz.c: + If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. */ + +/* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ +/*#define MINIZ_NO_STDIO */ + +/* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */ +/* get/set file times, and the C run-time funcs that get/set times won't be called. */ +/* The current downside is the times written to your archives will be from 1979. */ +/*#define MINIZ_NO_TIME */ + +/* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ +/*#define MINIZ_NO_ARCHIVE_APIS */ + +/* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */ +/*#define MINIZ_NO_ARCHIVE_WRITING_APIS */ + +/* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */ +/*#define MINIZ_NO_ZLIB_APIS */ + +/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ +/*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +/* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. + Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc + callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user + functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ +/*#define MINIZ_NO_MALLOC */ + +#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) +/* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */ +#define MINIZ_NO_TIME +#endif + +#include + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) +#include +#endif + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +/* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ +#define MINIZ_X86_OR_X64_CPU 1 +#else +#define MINIZ_X86_OR_X64_CPU 0 +#endif + +#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +/* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ +#define MINIZ_LITTLE_ENDIAN 1 +#else +#define MINIZ_LITTLE_ENDIAN 0 +#endif + +#if MINIZ_X86_OR_X64_CPU +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#else +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +/* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */ +#define MINIZ_HAS_64BIT_REGISTERS 1 +#else +#define MINIZ_HAS_64BIT_REGISTERS 0 +#endif + +/* ------------------- zlib-style API Definitions. */ + +/* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ +typedef unsigned long mz_ulong; + +/* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. */ +void mz_free(void *p); + +#define MZ_ADLER32_INIT (1) +/* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */ +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) +/* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */ +mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +/* Compression strategies. */ +enum +{ + MZ_DEFAULT_STRATEGY = 0, + MZ_FILTERED = 1, + MZ_HUFFMAN_ONLY = 2, + MZ_RLE = 3, + MZ_FIXED = 4 +}; + +/* Method */ +#define MZ_DEFLATED 8 + +/* Heap allocation callbacks. +Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. */ +typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void *opaque, void *address); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + +/* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ +enum +{ + MZ_NO_COMPRESSION = 0, + MZ_BEST_SPEED = 1, + MZ_BEST_COMPRESSION = 9, + MZ_UBER_COMPRESSION = 10, + MZ_DEFAULT_LEVEL = 6, + MZ_DEFAULT_COMPRESSION = -1 +}; + +#define MZ_VERSION "10.0.1" +#define MZ_VERNUM 0xA010 +#define MZ_VER_MAJOR 10 +#define MZ_VER_MINOR 0 +#define MZ_VER_REVISION 1 +#define MZ_VER_SUBREVISION 0 + +#ifndef MINIZ_NO_ZLIB_APIS + +/* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). */ +enum +{ + MZ_NO_FLUSH = 0, + MZ_PARTIAL_FLUSH = 1, + MZ_SYNC_FLUSH = 2, + MZ_FULL_FLUSH = 3, + MZ_FINISH = 4, + MZ_BLOCK = 5 +}; + +/* Return status codes. MZ_PARAM_ERROR is non-standard. */ +enum +{ + MZ_OK = 0, + MZ_STREAM_END = 1, + MZ_NEED_DICT = 2, + MZ_ERRNO = -1, + MZ_STREAM_ERROR = -2, + MZ_DATA_ERROR = -3, + MZ_MEM_ERROR = -4, + MZ_BUF_ERROR = -5, + MZ_VERSION_ERROR = -6, + MZ_PARAM_ERROR = -10000 +}; + +/* Window bits */ +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +/* Compression/decompression stream struct. */ +typedef struct mz_stream_s +{ + const unsigned char *next_in; /* pointer to next byte to read */ + unsigned int avail_in; /* number of bytes available at next_in */ + mz_ulong total_in; /* total number of bytes consumed so far */ + + unsigned char *next_out; /* pointer to next byte to write */ + unsigned int avail_out; /* number of bytes that can be written to next_out */ + mz_ulong total_out; /* total number of bytes produced so far */ + + char *msg; /* error msg (unused) */ + struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */ + + mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */ + mz_free_func zfree; /* optional heap free function (defaults to free) */ + void *opaque; /* heap alloc function user pointer */ + + int data_type; /* data_type (unused) */ + mz_ulong adler; /* adler32 of the source or uncompressed data */ + mz_ulong reserved; /* not used */ +} mz_stream; + +typedef mz_stream *mz_streamp; + +/* Returns the version string of miniz.c. */ +const char *mz_version(void); + +/* mz_deflateInit() initializes a compressor with default options: */ +/* Parameters: */ +/* pStream must point to an initialized mz_stream struct. */ +/* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ +/* level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. */ +/* (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ +/* Return values: */ +/* MZ_OK on success. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_PARAM_ERROR if the input parameters are bogus. */ +/* MZ_MEM_ERROR on out of memory. */ +int mz_deflateInit(mz_streamp pStream, int level); + +/* mz_deflateInit2() is like mz_deflate(), except with more control: */ +/* Additional parameters: */ +/* method must be MZ_DEFLATED */ +/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */ +/* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + +/* Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ +int mz_deflateReset(mz_streamp pStream); + +/* mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. */ +/* Parameters: */ +/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ +/* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */ +/* Return values: */ +/* MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). */ +/* MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_PARAM_ERROR if one of the parameters is invalid. */ +/* MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) */ +int mz_deflate(mz_streamp pStream, int flush); + +/* mz_deflateEnd() deinitializes a compressor: */ +/* Return values: */ +/* MZ_OK on success. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +int mz_deflateEnd(mz_streamp pStream); + +/* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */ +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +/* Single-call compression functions mz_compress() and mz_compress2(): */ +/* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */ +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + +/* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). */ +mz_ulong mz_compressBound(mz_ulong source_len); + +/* Initializes a decompressor. */ +int mz_inflateInit(mz_streamp pStream); + +/* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: */ +/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ +int mz_inflateInit2(mz_streamp pStream, int window_bits); + +/* Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. */ +/* Parameters: */ +/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ +/* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ +/* On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). */ +/* MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. */ +/* Return values: */ +/* MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. */ +/* MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_DATA_ERROR if the deflate stream is invalid. */ +/* MZ_PARAM_ERROR if one of the parameters is invalid. */ +/* MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again */ +/* with more input data, or with more room in the output buffer (except when using single call decompression, described above). */ +int mz_inflate(mz_streamp pStream, int flush); + +/* Deinitializes a decompressor. */ +int mz_inflateEnd(mz_streamp pStream); + +/* Single-call decompression. */ +/* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */ +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); + +/* Returns a string description of the specified error code, or NULL if the error code is invalid. */ +const char *mz_error(int err); + +/* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. */ +/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. */ +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES +typedef unsigned char Byte; +typedef unsigned int uInt; +typedef mz_ulong uLong; +typedef Byte Bytef; +typedef uInt uIntf; +typedef char charf; +typedef int intf; +typedef void *voidpf; +typedef uLong uLongf; +typedef void *voidp; +typedef void *const voidpc; +#define Z_NULL 0 +#define Z_NO_FLUSH MZ_NO_FLUSH +#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH +#define Z_SYNC_FLUSH MZ_SYNC_FLUSH +#define Z_FULL_FLUSH MZ_FULL_FLUSH +#define Z_FINISH MZ_FINISH +#define Z_BLOCK MZ_BLOCK +#define Z_OK MZ_OK +#define Z_STREAM_END MZ_STREAM_END +#define Z_NEED_DICT MZ_NEED_DICT +#define Z_ERRNO MZ_ERRNO +#define Z_STREAM_ERROR MZ_STREAM_ERROR +#define Z_DATA_ERROR MZ_DATA_ERROR +#define Z_MEM_ERROR MZ_MEM_ERROR +#define Z_BUF_ERROR MZ_BUF_ERROR +#define Z_VERSION_ERROR MZ_VERSION_ERROR +#define Z_PARAM_ERROR MZ_PARAM_ERROR +#define Z_NO_COMPRESSION MZ_NO_COMPRESSION +#define Z_BEST_SPEED MZ_BEST_SPEED +#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION +#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION +#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY +#define Z_FILTERED MZ_FILTERED +#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY +#define Z_RLE MZ_RLE +#define Z_FIXED MZ_FIXED +#define Z_DEFLATED MZ_DEFLATED +#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS +#define alloc_func mz_alloc_func +#define free_func mz_free_func +#define internal_state mz_internal_state +#define z_stream mz_stream +#define deflateInit mz_deflateInit +#define deflateInit2 mz_deflateInit2 +#define deflateReset mz_deflateReset +#define deflate mz_deflate +#define deflateEnd mz_deflateEnd +#define deflateBound mz_deflateBound +#define compress mz_compress +#define compress2 mz_compress2 +#define compressBound mz_compressBound +#define inflateInit mz_inflateInit +#define inflateInit2 mz_inflateInit2 +#define inflate mz_inflate +#define inflateEnd mz_inflateEnd +#define uncompress mz_uncompress +#define crc32 mz_crc32 +#define adler32 mz_adler32 +#define MAX_WBITS 15 +#define MAX_MEM_LEVEL 9 +#define zError mz_error +#define ZLIB_VERSION MZ_VERSION +#define ZLIB_VERNUM MZ_VERNUM +#define ZLIB_VER_MAJOR MZ_VER_MAJOR +#define ZLIB_VER_MINOR MZ_VER_MINOR +#define ZLIB_VER_REVISION MZ_VER_REVISION +#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION +#define zlibVersion mz_version +#define zlib_version mz_version() +#endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +#endif /* MINIZ_NO_ZLIB_APIS */ + diff --git a/xs/src/miniz/miniz_common.h b/xs/src/miniz/miniz_common.h new file mode 100644 index 000000000..d45bdfcb4 --- /dev/null +++ b/xs/src/miniz/miniz_common.h @@ -0,0 +1,83 @@ +#pragma once +#include +#include +#include +#include + +/* ------------------- Types and macros */ +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef int64_t mz_int64; +typedef uint64_t mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +/* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ +#ifdef _MSC_VER +#define MZ_MACRO_END while (0, 0) +#else +#define MZ_MACRO_END while (0) +#endif + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include +#define MZ_FILE FILE +#endif /* #ifdef MINIZ_NO_STDIO */ + +#ifdef MINIZ_NO_TIME +typedef struct mz_dummy_time_t_tag +{ + int m_dummy; +} mz_dummy_time_t; +#define MZ_TIME_T mz_dummy_time_t +#else +#define MZ_TIME_T time_t +#endif + +#define MZ_ASSERT(x) assert(x) + +#ifdef MINIZ_NO_MALLOC +#define MZ_MALLOC(x) NULL +#define MZ_FREE(x) (void)x, ((void)0) +#define MZ_REALLOC(p, x) NULL +#else +#define MZ_MALLOC(x) malloc(x) +#define MZ_FREE(x) free(x) +#define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +#define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) +#define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else +#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) +#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U)) + +#ifdef _MSC_VER +#define MZ_FORCEINLINE __forceinline +#elif defined(__GNUC__) +#define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) +#else +#define MZ_FORCEINLINE inline +#endif + +extern void *miniz_def_alloc_func(void *opaque, size_t items, size_t size); +extern void miniz_def_free_func(void *opaque, void *address); +extern void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size); + +#define MZ_UINT16_MAX (0xFFFFU) +#define MZ_UINT32_MAX (0xFFFFFFFFU) diff --git a/xs/src/miniz/miniz_tdef.cpp b/xs/src/miniz/miniz_tdef.cpp new file mode 100644 index 000000000..36207e64a --- /dev/null +++ b/xs/src/miniz/miniz_tdef.cpp @@ -0,0 +1,1555 @@ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + +#include "miniz_tdef.h" +#include "miniz.h" + +/* ------------------- Low-level Compression (independent from all decompression API's) */ + +/* Purposely making these tables static for faster init and thread safety. */ +static const mz_uint16 s_tdefl_len_sym[256] = + { + 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, + 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, + 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, + 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, + 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, + 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, + 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285 + }; + +static const mz_uint8 s_tdefl_len_extra[256] = + { + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 + }; + +static const mz_uint8 s_tdefl_small_dist_sym[512] = + { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 + }; + +static const mz_uint8 s_tdefl_small_dist_extra[512] = + { + 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7 + }; + +static const mz_uint8 s_tdefl_large_dist_sym[128] = + { + 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 + }; + +static const mz_uint8 s_tdefl_large_dist_extra[128] = + { + 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 + }; + +/* Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. */ +typedef struct +{ + mz_uint16 m_key, m_sym_index; +} tdefl_sym_freq; +static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) +{ + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; + tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; + MZ_CLEAR_OBJ(hist); + for (i = 0; i < num_syms; i++) + { + mz_uint freq = pSyms0[i].m_key; + hist[freq & 0xFF]++; + hist[256 + ((freq >> 8) & 0xFF)]++; + } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) + total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) + { + const mz_uint32 *pHist = &hist[pass << 8]; + mz_uint offsets[256], cur_ofs = 0; + for (i = 0; i < 256; i++) + { + offsets[i] = cur_ofs; + cur_ofs += pHist[i]; + } + for (i = 0; i < num_syms; i++) + pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; + { + tdefl_sym_freq *t = pCur_syms; + pCur_syms = pNew_syms; + pNew_syms = t; + } + } + return pCur_syms; +} + +/* tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. */ +static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) +{ + int root, leaf, next, avbl, used, dpth; + if (n == 0) + return; + else if (n == 1) + { + A[0].m_key = 1; + return; + } + A[0].m_key += A[1].m_key; + root = 0; + leaf = 2; + for (next = 1; next < n - 1; next++) + { + if (leaf >= n || A[root].m_key < A[leaf].m_key) + { + A[next].m_key = A[root].m_key; + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = A[leaf++].m_key; + if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) + { + A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); + } + A[n - 2].m_key = 0; + for (next = n - 3; next >= 0; next--) + A[next].m_key = A[A[next].m_key].m_key + 1; + avbl = 1; + used = dpth = 0; + root = n - 2; + next = n - 1; + while (avbl > 0) + { + while (root >= 0 && (int)A[root].m_key == dpth) + { + used++; + root--; + } + while (avbl > used) + { + A[next--].m_key = (mz_uint16)(dpth); + avbl--; + } + avbl = 2 * used; + dpth++; + used = 0; + } +} + +/* Limits canonical Huffman code table's max code size. */ +enum +{ + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 +}; +static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) +{ + int i; + mz_uint32 total = 0; + if (code_list_len <= 1) + return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) + pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) + total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) + { + pNum_codes[max_code_size]--; + for (i = max_code_size - 1; i > 0; i--) + if (pNum_codes[i]) + { + pNum_codes[i]--; + pNum_codes[i + 1] += 2; + break; + } + total--; + } +} + +static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) +{ + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; + mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; + MZ_CLEAR_OBJ(num_codes); + if (static_table) + { + for (i = 0; i < table_len; i++) + num_codes[d->m_huff_code_sizes[table_num][i]]++; + } + else + { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; + int num_used_syms = 0; + const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; + for (i = 0; i < table_len; i++) + if (pSym_count[i]) + { + syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; + syms0[num_used_syms++].m_sym_index = (mz_uint16)i; + } + + pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); + tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); + + for (i = 0; i < num_used_syms; i++) + num_codes[pSyms[i].m_key]++; + + tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); + + MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); + MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); + for (i = 1, j = num_used_syms; i <= code_size_limit; i++) + for (l = num_codes[i]; l > 0; l--) + d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); + } + + next_code[1] = 0; + for (j = 0, i = 2; i <= code_size_limit; i++) + next_code[i] = j = ((j + num_codes[i - 1]) << 1); + + for (i = 0; i < table_len; i++) + { + mz_uint rev_code = 0, code, code_size; + if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) + continue; + code = next_code[code_size]++; + for (l = code_size; l > 0; l--, code >>= 1) + rev_code = (rev_code << 1) | (code & 1); + d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; + } +} + +#define TDEFL_PUT_BITS(b, l) \ + do \ + { \ + mz_uint bits = b; \ + mz_uint len = l; \ + MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); \ + d->m_bits_in += len; \ + while (d->m_bits_in >= 8) \ + { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ + } \ + MZ_MACRO_END + +#define TDEFL_RLE_PREV_CODE_SIZE() \ + { \ + if (rle_repeat_count) \ + { \ + if (rle_repeat_count < 3) \ + { \ + d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ + while (rle_repeat_count--) \ + packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } \ + else \ + { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 16; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ + } \ + rle_repeat_count = 0; \ + } \ + } + +#define TDEFL_RLE_ZERO_CODE_SIZE() \ + { \ + if (rle_z_count) \ + { \ + if (rle_z_count < 3) \ + { \ + d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ + while (rle_z_count--) \ + packed_code_sizes[num_packed_code_sizes++] = 0; \ + } \ + else if (rle_z_count <= 10) \ + { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 17; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ + } \ + else \ + { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 18; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ + } \ + rle_z_count = 0; \ + } \ + } + +static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + +static void tdefl_start_dynamic_block(tdefl_compressor *d) +{ + int num_lit_codes, num_dist_codes, num_bit_lengths; + mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; + mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; + + d->m_huff_count[0][256] = 1; + + tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); + tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); + + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) + if (d->m_huff_code_sizes[0][num_lit_codes - 1]) + break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) + if (d->m_huff_code_sizes[1][num_dist_codes - 1]) + break; + + memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); + memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; + num_packed_code_sizes = 0; + rle_z_count = 0; + rle_repeat_count = 0; + + memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) + { + mz_uint8 code_size = code_sizes_to_pack[i]; + if (!code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + if (++rle_z_count == 138) + { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + if (code_size != prev_code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); + packed_code_sizes[num_packed_code_sizes++] = code_size; + } + else if (++rle_repeat_count == 6) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + } + prev_code_size = code_size; + } + if (rle_repeat_count) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + + tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); + + TDEFL_PUT_BITS(2, 2); + + TDEFL_PUT_BITS(num_lit_codes - 257, 5); + TDEFL_PUT_BITS(num_dist_codes - 1, 5); + + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) + if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) + break; + num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); + TDEFL_PUT_BITS(num_bit_lengths - 4, 4); + for (i = 0; (int)i < num_bit_lengths; i++) + TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); + + for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) + { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; + MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); + TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); + if (code >= 16) + TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); + } +} + +static void tdefl_start_static_block(tdefl_compressor *d) +{ + mz_uint i; + mz_uint8 *p = &d->m_huff_code_sizes[0][0]; + + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + + memset(d->m_huff_code_sizes[1], 5, 32); + + tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); + tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); + + TDEFL_PUT_BITS(1, 2); +} + +static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + mz_uint8 *pOutput_buf = d->m_pOutput_buf; + mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; + mz_uint64 bit_buffer = d->m_bit_buffer; + mz_uint bits_in = d->m_bits_in; + +#define TDEFL_PUT_BITS_FAST(b, l) \ + { \ + bit_buffer |= (((mz_uint64)(b)) << bits_in); \ + bits_in += (l); \ + } + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + + if (flags & 1) + { + mz_uint s0, s1, n0, n1, sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + /* This sequence coaxes MSVC into using cmov's vs. jmp's. */ + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + n0 = s_tdefl_small_dist_extra[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + n1 = s_tdefl_large_dist_extra[match_dist >> 8]; + sym = (match_dist < 512) ? s0 : s1; + num_extra_bits = (match_dist < 512) ? n0 : n1; + + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + } + + if (pOutput_buf >= d->m_pOutput_buf_end) + return MZ_FALSE; + + *(mz_uint64 *)pOutput_buf = bit_buffer; + pOutput_buf += (bits_in >> 3); + bit_buffer >>= (bits_in & ~7); + bits_in &= 7; + } + +#undef TDEFL_PUT_BITS_FAST + + d->m_pOutput_buf = pOutput_buf; + d->m_bits_in = 0; + d->m_bit_buffer = 0; + + while (bits_in) + { + mz_uint32 n = MZ_MIN(bits_in, 16); + TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); + bit_buffer >>= n; + bits_in -= n; + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#else +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + if (flags & 1) + { + mz_uint sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + if (match_dist < 512) + { + sym = s_tdefl_small_dist_sym[match_dist]; + num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } + else + { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; + num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; + } + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS */ + +static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) +{ + if (static_block) + tdefl_start_static_block(d); + else + tdefl_start_dynamic_block(d); + return tdefl_compress_lz_codes(d); +} + +static int tdefl_flush_block(tdefl_compressor *d, int flush) +{ + mz_uint saved_bit_buf, saved_bits_in; + mz_uint8 *pSaved_output_buf; + mz_bool comp_block_succeeded = MZ_FALSE; + int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; + + d->m_pOutput_buf = pOutput_buf_start; + d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; + + MZ_ASSERT(!d->m_output_flush_remaining); + d->m_output_flush_ofs = 0; + d->m_output_flush_remaining = 0; + + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); + d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); + + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) + { + TDEFL_PUT_BITS(0x78, 8); + TDEFL_PUT_BITS(0x01, 8); + } + + TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); + + pSaved_output_buf = d->m_pOutput_buf; + saved_bit_buf = d->m_bit_buffer; + saved_bits_in = d->m_bits_in; + + if (!use_raw_block) + comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); + + /* If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. */ + if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && + ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) + { + mz_uint i; + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + TDEFL_PUT_BITS(0, 2); + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) + { + TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); + } + for (i = 0; i < d->m_total_lz_bytes; ++i) + { + TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); + } + } + /* Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. */ + else if (!comp_block_succeeded) + { + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + tdefl_compress_block(d, MZ_TRUE); + } + + if (flush) + { + if (flush == TDEFL_FINISH) + { + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) + { + mz_uint i, a = d->m_adler32; + for (i = 0; i < 4; i++) + { + TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); + a <<= 8; + } + } + } + else + { + mz_uint i, z = 0; + TDEFL_PUT_BITS(0, 3); + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, z ^= 0xFFFF) + { + TDEFL_PUT_BITS(z & 0xFFFF, 16); + } + } + } + + MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); + + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; + d->m_total_lz_bytes = 0; + d->m_block_index++; + + if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) + { + if (d->m_pPut_buf_func) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) + return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); + } + else if (pOutput_buf_start == d->m_output_buf) + { + int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); + d->m_out_buf_ofs += bytes_to_copy; + if ((n -= bytes_to_copy) != 0) + { + d->m_output_flush_ofs = bytes_to_copy; + d->m_output_flush_remaining = n; + } + } + else + { + d->m_out_buf_ofs += n; + } + } + + return d->m_output_flush_remaining; +} + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES +#ifdef MINIZ_UNALIGNED_USE_MEMCPY +static inline mz_uint16 TDEFL_READ_UNALIGNED_WORD(const mz_uint8* p) +{ + mz_uint16 ret; + memcpy(&ret, p, sizeof(mz_uint16)); + return ret; +} +static inline mz_uint16 TDEFL_READ_UNALIGNED_WORD2(const mz_uint16* p) +{ + mz_uint16 ret; + memcpy(&ret, p, sizeof(mz_uint16)); + return ret; +} +#else +#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) +#define TDEFL_READ_UNALIGNED_WORD2(p) *(const mz_uint16 *)(p) +#endif +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; + mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD2(s); + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + q = (const mz_uint16 *)(d->m_dict + probe_pos); + if (TDEFL_READ_UNALIGNED_WORD2(q) != s01) + continue; + p = s; + probe_len = 32; + do + { + } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); + if (!probe_len) + { + *pMatch_dist = dist; + *pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN); + break; + } + else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) + break; + c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); + } + } +} +#else +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint8 *s = d->m_dict + pos, *p, *q; + mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + p = s; + q = d->m_dict + probe_pos; + for (probe_len = 0; probe_len < max_match_len; probe_len++) + if (*p++ != *q++) + break; + if (probe_len > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = probe_len) == max_match_len) + return; + c0 = d->m_dict[pos + match_len]; + c1 = d->m_dict[pos + match_len - 1]; + } + } +} +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES */ + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +static mz_bool tdefl_compress_fast(tdefl_compressor *d) +{ + /* Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. */ + mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; + mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; + mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) + { + const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; + mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); + d->m_src_buf_left -= num_bytes_to_process; + lookahead_size += num_bytes_to_process; + + while (num_bytes_to_process) + { + mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); + memcpy(d->m_dict + dst_pos, d->m_pSrc, n); + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + d->m_pSrc += n; + dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; + num_bytes_to_process -= n; + } + + dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); + if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) + break; + + while (lookahead_size >= 4) + { + mz_uint cur_match_dist, cur_match_len = 1; + mz_uint8 *pCur_dict = d->m_dict + cur_pos; + mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; + mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint probe_pos = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)lookahead_pos; + + if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) + { + const mz_uint16 *p = (const mz_uint16 *)pCur_dict; + const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); + mz_uint32 probe_len = 32; + do + { + } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && + (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && (--probe_len > 0)); + cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); + if (!probe_len) + cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; + + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) + { + cur_match_len = 1; + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + else + { + mz_uint32 s0, s1; + cur_match_len = MZ_MIN(cur_match_len, lookahead_size); + + MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + + cur_match_dist--; + + pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); + *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; + pLZ_code_buf += 3; + *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); + + s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; + s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; + d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; + } + } + else + { + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + total_lz_bytes += cur_match_len; + lookahead_pos += cur_match_len; + dict_size = MZ_MIN(dict_size + cur_match_len, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; + MZ_ASSERT(lookahead_size >= cur_match_len); + lookahead_size -= cur_match_len; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + + while (lookahead_size) + { + mz_uint8 lit = d->m_dict[cur_pos]; + + total_lz_bytes++; + *pLZ_code_buf++ = lit; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + d->m_huff_count[0][lit]++; + + lookahead_pos++; + dict_size = MZ_MIN(dict_size + 1, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + lookahead_size--; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + } + + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + return MZ_TRUE; +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + +static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) +{ + d->m_total_lz_bytes++; + *d->m_pLZ_code_buf++ = lit; + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + d->m_huff_count[0][lit]++; +} + +static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) +{ + mz_uint32 s0, s1; + + MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); + + d->m_total_lz_bytes += match_len; + + d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); + + match_dist -= 1; + d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); + d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); + d->m_pLZ_code_buf += 3; + + *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; + d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; + + if (match_len >= TDEFL_MIN_MATCH_LEN) + d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; +} + +static mz_bool tdefl_compress_normal(tdefl_compressor *d) +{ + const mz_uint8 *pSrc = d->m_pSrc; + size_t src_buf_left = d->m_src_buf_left; + tdefl_flush flush = d->m_flush; + + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) + { + mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; + /* Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. */ + if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) + { + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); + const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; + src_buf_left -= num_bytes_to_process; + d->m_lookahead_size += num_bytes_to_process; + while (pSrc != pSrc_end) + { + mz_uint8 c = *pSrc++; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + ins_pos++; + } + } + else + { + while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + src_buf_left--; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) + { + mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; + mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + } + } + } + d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + break; + + /* Simple lazy/greedy parsing state machine. */ + len_to_move = 1; + cur_match_dist = 0; + cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); + cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) + { + if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) + { + mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; + cur_match_len = 0; + while (cur_match_len < d->m_lookahead_size) + { + if (d->m_dict[cur_pos + cur_match_len] != c) + break; + cur_match_len++; + } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) + cur_match_len = 0; + else + cur_match_dist = 1; + } + } + else + { + tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); + } + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) + { + cur_match_dist = cur_match_len = 0; + } + if (d->m_saved_match_len) + { + if (cur_match_len > d->m_saved_match_len) + { + tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); + if (cur_match_len >= 128) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + d->m_saved_match_len = 0; + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[cur_pos]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + } + else + { + tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); + len_to_move = d->m_saved_match_len - 1; + d->m_saved_match_len = 0; + } + } + else if (!cur_match_dist) + tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + /* Move the lookahead forward by len_to_move bytes. */ + d->m_lookahead_pos += len_to_move; + MZ_ASSERT(d->m_lookahead_size >= len_to_move); + d->m_lookahead_size -= len_to_move; + d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); + /* Check if it's time to flush the current LZ codes to the internal output buffer. */ + if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) + { + int n; + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + } + } + + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + return MZ_TRUE; +} + +static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) +{ + if (d->m_pIn_buf_size) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + } + + if (d->m_pOut_buf_size) + { + size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); + d->m_output_flush_ofs += (mz_uint)n; + d->m_output_flush_remaining -= (mz_uint)n; + d->m_out_buf_ofs += n; + + *d->m_pOut_buf_size = d->m_out_buf_ofs; + } + + return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) +{ + if (!d) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return TDEFL_STATUS_BAD_PARAM; + } + + d->m_pIn_buf = pIn_buf; + d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; + d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8 *)(pIn_buf); + d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_out_buf_ofs = 0; + d->m_flush = flush; + + if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); + } + d->m_wants_to_finish |= (flush == TDEFL_FINISH); + + if ((d->m_output_flush_remaining) || (d->m_finished)) + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) + { + if (!tdefl_compress_fast(d)) + return d->m_prev_return_status; + } + else +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + { + if (!tdefl_compress_normal(d)) + return d->m_prev_return_status; + } + + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) + d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); + + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) + { + if (tdefl_flush_block(d, flush) < 0) + return d->m_prev_return_status; + d->m_finished = (flush == TDEFL_FINISH); + if (flush == TDEFL_FULL_FLUSH) + { + MZ_CLEAR_OBJ(d->m_hash); + MZ_CLEAR_OBJ(d->m_next); + d->m_dict_size = 0; + } + } + + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); +} + +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) +{ + MZ_ASSERT(d->m_pPut_buf_func); + return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); +} + +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + d->m_pPut_buf_func = pPut_buf_func; + d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint)(flags); + d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; + d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; + d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_OBJ(d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; + d->m_pOutput_buf_end = d->m_output_buf; + d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; + d->m_adler32 = 1; + d->m_pIn_buf = NULL; + d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; + d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; + d->m_pSrc = NULL; + d->m_src_buf_left = 0; + d->m_out_buf_ofs = 0; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_OBJ(d->m_dict); + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + return TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) +{ + return d->m_prev_return_status; +} + +mz_uint32 tdefl_get_adler32(tdefl_compressor *d) +{ + return d->m_adler32; +} + +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + tdefl_compressor *pComp; + mz_bool succeeded; + if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) + return MZ_FALSE; + pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + if (!pComp) + return MZ_FALSE; + succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); + succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); + MZ_FREE(pComp); + return succeeded; +} + +typedef struct +{ + size_t m_size, m_capacity; + mz_uint8 *m_pBuf; + mz_bool m_expandable; +} tdefl_output_buffer; + +static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) +{ + tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; + size_t new_size = p->m_size + len; + if (new_size > p->m_capacity) + { + size_t new_capacity = p->m_capacity; + mz_uint8 *pNew_buf; + if (!p->m_expandable) + return MZ_FALSE; + do + { + new_capacity = MZ_MAX(128U, new_capacity << 1U); + } while (new_size > new_capacity); + pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); + if (!pNew_buf) + return MZ_FALSE; + p->m_pBuf = pNew_buf; + p->m_capacity = new_capacity; + } + memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); + p->m_size = new_size; + return MZ_TRUE; +} + +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_len) + return MZ_FALSE; + else + *pOut_len = 0; + out_buf.m_expandable = MZ_TRUE; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return NULL; + *pOut_len = out_buf.m_size; + return out_buf.m_pBuf; +} + +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_buf) + return 0; + out_buf.m_pBuf = (mz_uint8 *)pOut_buf; + out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return 0; + return out_buf.m_size; +} + +static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + +/* level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). */ +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) +{ + mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); + if (window_bits > 0) + comp_flags |= TDEFL_WRITE_ZLIB_HEADER; + + if (!level) + comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) + comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) + comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) + comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) + comp_flags |= TDEFL_RLE_MATCHES; + + return comp_flags; +} + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4204) /* nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) */ +#endif + +/* Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at + http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. + This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. */ +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) +{ + /* Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. */ + static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + tdefl_output_buffer out_buf; + int i, bpl = w * num_chans, y, z; + mz_uint32 c; + *pLen_out = 0; + if (!pComp) + return NULL; + MZ_CLEAR_OBJ(out_buf); + out_buf.m_expandable = MZ_TRUE; + out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); + if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) + { + MZ_FREE(pComp); + return NULL; + } + /* write dummy header */ + for (z = 41; z; --z) + tdefl_output_buffer_putter(&z, 1, &out_buf); + /* compress image data */ + tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) + { + tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); + tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); + } + if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) + { + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + /* write real header */ + *pLen_out = out_buf.m_size - 41; + { + static const mz_uint8 chans[] = { 0x00, 0x00, 0x04, 0x02, 0x06 }; + mz_uint8 pnghdr[41] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, + 0x0a, 0x1a, 0x0a, 0x00, 0x00, + 0x00, 0x0d, 0x49, 0x48, 0x44, + 0x52, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x08, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x49, 0x44, 0x41, + 0x54 }; + pnghdr[18] = (mz_uint8)(w >> 8); + pnghdr[19] = (mz_uint8)w; + pnghdr[22] = (mz_uint8)(h >> 8); + pnghdr[23] = (mz_uint8)h; + pnghdr[25] = chans[num_chans]; + pnghdr[33] = (mz_uint8)(*pLen_out >> 24); + pnghdr[34] = (mz_uint8)(*pLen_out >> 16); + pnghdr[35] = (mz_uint8)(*pLen_out >> 8); + pnghdr[36] = (mz_uint8)*pLen_out; + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); + for (i = 0; i < 4; ++i, c <<= 8) + ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); + memcpy(out_buf.m_pBuf, pnghdr, 41); + } + /* write footer (IDAT CRC-32, followed by IEND chunk) */ + if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) + { + *pLen_out = 0; + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); + for (i = 0; i < 4; ++i, c <<= 8) + (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); + /* compute final size of file, grab compressed data buffer and return */ + *pLen_out += 57; + MZ_FREE(pComp); + return out_buf.m_pBuf; +} +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) +{ + /* Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) */ + return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); +} + +/* Allocate the tdefl_compressor and tinfl_decompressor structures in C so that */ +/* non-C language bindings to tdefL_ and tinfl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +tdefl_compressor *tdefl_compressor_alloc() +{ + return (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); +} + +void tdefl_compressor_free(tdefl_compressor *pComp) +{ + MZ_FREE(pComp); +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif diff --git a/xs/src/miniz/miniz_tdef.h b/xs/src/miniz/miniz_tdef.h new file mode 100644 index 000000000..ca63cfd42 --- /dev/null +++ b/xs/src/miniz/miniz_tdef.h @@ -0,0 +1,181 @@ +#pragma once +#include "miniz_common.h" + +/* ------------------- Low-level Compression API Definitions */ + +/* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). */ +#define TDEFL_LESS_MEMORY 0 + +/* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */ +/* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */ +enum +{ + TDEFL_HUFFMAN_ONLY = 0, + TDEFL_DEFAULT_MAX_PROBES = 128, + TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +/* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */ +/* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */ +/* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */ +/* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */ +/* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */ +/* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ +/* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ +/* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ +/* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ +enum +{ + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +/* High level compression functions: */ +/* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). */ +/* On entry: */ +/* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ +/* flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. */ +/* On return: */ +/* Function returns a pointer to the compressed data, or NULL on failure. */ +/* *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. */ +/* The caller must free() the returned block when it's no longer needed. */ +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +/* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */ +/* Returns 0 on failure. */ +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +/* Compresses an image to a compressed PNG file in memory. */ +/* On entry: */ +/* pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */ +/* The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. */ +/* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ +/* If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */ +/* On return: */ +/* Function returns a pointer to the compressed data, or NULL on failure. */ +/* *pLen_out will be set to the size of the PNG image file. */ +/* The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. */ +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + +/* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); + +/* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. */ +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +enum +{ + TDEFL_MAX_HUFF_TABLES = 3, + TDEFL_MAX_HUFF_SYMBOLS_0 = 288, + TDEFL_MAX_HUFF_SYMBOLS_1 = 32, + TDEFL_MAX_HUFF_SYMBOLS_2 = 19, + TDEFL_LZ_DICT_SIZE = 32768, + TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, + TDEFL_MIN_MATCH_LEN = 3, + TDEFL_MAX_MATCH_LEN = 258 +}; + +/* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). */ +#if TDEFL_LESS_MEMORY +enum +{ + TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 12, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#else +enum +{ + TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 15, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#endif + +/* The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. */ +typedef enum { + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1 +} tdefl_status; + +/* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ +typedef enum { + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +/* tdefl's compression state structure. */ +typedef struct +{ + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +/* Initializes the compressor. */ +/* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. */ +/* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. */ +/* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */ +/* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */ +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +/* Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. */ +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + +/* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. */ +/* tdefl_compress_buffer() always consumes the entire input buffer. */ +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); +mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + +/* Create tdefl_compress() flags given zlib-style compression parameters. */ +/* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) */ +/* window_bits may be -15 (raw deflate) or 15 (zlib) */ +/* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */ +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); + +/* Allocate the tdefl_compressor structure in C so that */ +/* non-C language bindings to tdefl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +tdefl_compressor *tdefl_compressor_alloc(); +void tdefl_compressor_free(tdefl_compressor *pComp); diff --git a/xs/src/miniz/miniz_tinfl.cpp b/xs/src/miniz/miniz_tinfl.cpp new file mode 100644 index 000000000..59b24d73f --- /dev/null +++ b/xs/src/miniz/miniz_tinfl.cpp @@ -0,0 +1,725 @@ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + +#include "miniz_tinfl.h" + +/* ------------------- Low-level Decompression (completely independent from all compression API's) */ + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN \ + switch (r->m_state) \ + { \ + case 0: +#define TINFL_CR_RETURN(state_index, result) \ + do \ + { \ + status = result; \ + r->m_state = state_index; \ + goto common_exit; \ + case state_index:; \ + } \ + MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) \ + do \ + { \ + for (;;) \ + { \ + TINFL_CR_RETURN(state_index, result); \ + } \ + } \ + MZ_MACRO_END +#define TINFL_CR_FINISH } + +#define TINFL_GET_BYTE(state_index, c) \ + do \ + { \ + while (pIn_buf_cur >= pIn_buf_end) \ + { \ + TINFL_CR_RETURN(state_index, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \ + } \ + c = *pIn_buf_cur++; \ + } \ + MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) \ + do \ + { \ + mz_uint c; \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) \ + do \ + { \ + if (num_bits < (mz_uint)(n)) \ + { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) \ + do \ + { \ + if (num_bits < (mz_uint)(n)) \ + { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + b = bit_buf & ((1 << (n)) - 1); \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END + +/* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. */ +/* It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a */ +/* Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the */ +/* bit buffer contains >=15 bits (deflate's max. Huffman code size). */ +#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ + do \ + { \ + temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) \ + { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } \ + else if (num_bits > TINFL_FAST_LOOKUP_BITS) \ + { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do \ + { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); \ + if (temp >= 0) \ + break; \ + } \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < 15); + +/* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read */ +/* beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully */ +/* decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. */ +/* The slow path is only executed at the very end of the input buffer. */ +/* v1.16: The original macro handled the case at the very end of the passed-in input buffer, but we also need to handle the case where the user passes in 1+zillion bytes */ +/* following the deflate data and our non-conservative read-ahead path won't kick in here on this code. This is much trickier. */ +#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ + do \ + { \ + int temp; \ + mz_uint code_len, c; \ + if (num_bits < 15) \ + { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) \ + { \ + TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ + } \ + else \ + { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ + pIn_buf_cur += 2; \ + num_bits += 16; \ + } \ + } \ + if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + code_len = temp >> 9, temp &= 511; \ + else \ + { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do \ + { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while (temp < 0); \ + } \ + sym = temp; \ + bit_buf >>= code_len; \ + num_bits -= code_len; \ + } \ + MZ_MACRO_END + +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) +{ + static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; + static const int s_length_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 }; + static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 }; + static const int s_dist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; + static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + static const int s_min_table_sizes[3] = { 257, 1, 4 }; + + tinfl_status status = TINFL_STATUS_FAILED; + mz_uint32 num_bits, dist, counter, num_extra; + tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; + size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; + + /* Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). */ + if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) + { + *pIn_buf_size = *pOut_buf_size = 0; + return TINFL_STATUS_BAD_PARAM; + } + + num_bits = r->m_num_bits; + bit_buf = r->m_bit_buf; + dist = r->m_dist; + counter = r->m_counter; + num_extra = r->m_num_extra; + dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; + r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_GET_BYTE(1, r->m_zhdr0); + TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); + if (counter) + { + TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); + } + } + + do + { + TINFL_GET_BITS(3, r->m_final, 3); + r->m_type = r->m_final >> 1; + if (r->m_type == 0) + { + TINFL_SKIP_BITS(5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) + { + if (num_bits) + TINFL_GET_BITS(6, r->m_raw_header[counter], 8); + else + TINFL_GET_BYTE(7, r->m_raw_header[counter]); + } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) + { + TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); + } + while ((counter) && (num_bits)) + { + TINFL_GET_BITS(51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)dist; + counter--; + } + while (counter) + { + size_t n; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); + } + while (pIn_buf_cur >= pIn_buf_end) + { + TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); + } + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); + pIn_buf_cur += n; + pOut_buf_cur += n; + counter -= (mz_uint)n; + } + } + else if (r->m_type == 3) + { + TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); + } + else + { + if (r->m_type == 1) + { + mz_uint8 *p = r->m_tables[0].m_code_size; + mz_uint i; + r->m_table_sizes[0] = 288; + r->m_table_sizes[1] = 32; + TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + } + else + { + for (counter = 0; counter < 3; counter++) + { + TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); + r->m_table_sizes[counter] += s_min_table_sizes[counter]; + } + MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); + for (counter = 0; counter < r->m_table_sizes[2]; counter++) + { + mz_uint s; + TINFL_GET_BITS(14, s, 3); + r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; + } + r->m_table_sizes[2] = 19; + } + for (; (int)r->m_type >= 0; r->m_type--) + { + int tree_next, tree_cur; + tinfl_huff_table *pTable; + mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; + pTable = &r->m_tables[r->m_type]; + MZ_CLEAR_OBJ(total_syms); + MZ_CLEAR_OBJ(pTable->m_look_up); + MZ_CLEAR_OBJ(pTable->m_tree); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) + total_syms[pTable->m_code_size[i]]++; + used_syms = 0, total = 0; + next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) + { + used_syms += total_syms[i]; + next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); + } + if ((65536 != total) && (used_syms > 1)) + { + TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + { + mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; + if (!code_size) + continue; + cur_code = next_code[code_size]++; + for (l = code_size; l > 0; l--, cur_code >>= 1) + rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) + { + mz_int16 k = (mz_int16)((code_size << 9) | sym_index); + while (rev_code < TINFL_FAST_LOOKUP_SIZE) + { + pTable->m_look_up[rev_code] = k; + rev_code += (1 << code_size); + } + continue; + } + if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) + { + pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTable->m_tree[-tree_cur - 1]) + { + pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + else + tree_cur = pTable->m_tree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); + pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; + } + if (r->m_type == 2) + { + for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) + { + mz_uint s; + TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); + if (dist < 16) + { + r->m_len_codes[counter++] = (mz_uint8)dist; + continue; + } + if ((dist == 16) && (!counter)) + { + TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; + TINFL_GET_BITS(18, s, num_extra); + s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); + counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) + { + TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); + TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); + } + } + for (;;) + { + mz_uint8 *pSrc; + for (;;) + { + if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) + { + TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)counter; + } + else + { + int sym2; + mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 4; + num_bits += 32; + } +#else + if (num_bits < 15) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + counter = sym2; + bit_buf >>= code_len; + num_bits -= code_len; + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + bit_buf >>= code_len; + num_bits -= code_len; + + pOut_buf_cur[0] = (mz_uint8)counter; + if (sym2 & 256) + { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8)sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) + break; + + num_extra = s_length_extra[counter - 257]; + counter = s_length_base[counter - 257]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS(25, extra_bits, num_extra); + counter += extra_bits; + } + + TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); + num_extra = s_dist_extra[dist]; + dist = s_dist_base[dist]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS(27, extra_bits, num_extra); + dist += extra_bits; + } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + { + TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); + } + + pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + { + while (counter--) + { + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) + { + const mz_uint8 *pSrc_end = pSrc + (counter & ~7); + do + { + ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; + ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; + pOut_buf_cur += 8; + } while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) + { + if (counter) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + do + { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; + pSrc += 3; + } while ((int)(counter -= 3) > 2); + if ((int)counter > 0) + { + pOut_buf_cur[0] = pSrc[0]; + if ((int)counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } while (!(r->m_final & 1)); + + /* Ensure byte alignment and put back any bytes from the bitbuf if we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ + /* I'm being super conservative here. A number of simplifications can be made to the byte alignment part, and the Adler32 check shouldn't ever need to worry about reading from the bitbuf now. */ + TINFL_SKIP_BITS(32, num_bits & 7); + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + { + --pIn_buf_cur; + num_bits -= 8; + } + bit_buf &= (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); + MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end of non-deflate/zlib streams with following data (such as gzip streams). */ + + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + for (counter = 0; counter < 4; ++counter) + { + mz_uint s; + if (num_bits) + TINFL_GET_BITS(41, s, 8); + else + TINFL_GET_BYTE(42, s); + r->m_z_adler32 = (r->m_z_adler32 << 8) | s; + } + } + TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); + + TINFL_CR_FINISH + +common_exit: + /* As long as we aren't telling the caller that we NEED more input to make forward progress: */ + /* Put back any bytes from the bitbuf in case we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ + /* We need to be very careful here to NOT push back any bytes we definitely know we need to make forward progress, though, or we'll lock the caller up into an inf loop. */ + if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) + { + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + { + --pIn_buf_cur; + num_bits -= 8; + } + } + r->m_num_bits = num_bits; + r->m_bit_buf = bit_buf & (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); + r->m_dist = dist; + r->m_counter = counter; + r->m_num_extra = num_extra; + r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; + *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) + { + const mz_uint8 *ptr = pOut_buf_next; + size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; + size_t block_len = buf_len % 5552; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; + if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) + status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; +} + +/* Higher level helper functions. */ +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tinfl_decompressor decomp; + void *pBuf = NULL, *pNew_buf; + size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init(&decomp); + for (;;) + { + size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) + break; + new_out_buf_capacity = out_buf_capacity * 2; + if (new_out_buf_capacity < 128) + new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); + if (!pNew_buf) + { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + pBuf = pNew_buf; + out_buf_capacity = new_out_buf_capacity; + } + return pBuf; +} + +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tinfl_decompressor decomp; + tinfl_status status; + tinfl_init(&decomp); + status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; +} + +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + int result = 0; + tinfl_decompressor decomp; + mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); + size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + tinfl_init(&decomp); + for (;;) + { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE(pDict); + *pIn_buf_size = in_buf_ofs; + return result; +} + +tinfl_decompressor *tinfl_decompressor_alloc() +{ + tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor)); + if (pDecomp) + tinfl_init(pDecomp); + return pDecomp; +} + +void tinfl_decompressor_free(tinfl_decompressor *pDecomp) +{ + MZ_FREE(pDecomp); +} diff --git a/xs/src/miniz/miniz_tinfl.h b/xs/src/miniz/miniz_tinfl.h new file mode 100644 index 000000000..b90f22749 --- /dev/null +++ b/xs/src/miniz/miniz_tinfl.h @@ -0,0 +1,137 @@ +#pragma once +#include "miniz_common.h" +/* ------------------- Low-level Decompression API Definitions */ + +/* Decompression flags used by tinfl_decompress(). */ +/* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */ +/* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */ +/* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */ +/* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */ +enum +{ + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +/* High level decompression functions: */ +/* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */ +/* On entry: */ +/* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */ +/* On return: */ +/* Function returns a pointer to the decompressed data, or NULL on failure. */ +/* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */ +/* The caller must call mz_free() on the returned block when it's no longer needed. */ +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +/* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */ +/* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */ +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +/* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */ +/* Returns 1 on success or 0 on failure. */ +typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; +typedef struct tinfl_decompressor_tag tinfl_decompressor; + +/* Allocate the tinfl_decompressor structure in C so that */ +/* non-C language bindings to tinfl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ + +tinfl_decompressor *tinfl_decompressor_alloc(); +void tinfl_decompressor_free(tinfl_decompressor *pDecomp); + +/* Max size of LZ dictionary. */ +#define TINFL_LZ_DICT_SIZE 32768 + +/* Return status. */ +typedef enum { + /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */ + /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */ + /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ + TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, + + /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */ + TINFL_STATUS_BAD_PARAM = -3, + + /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */ + TINFL_STATUS_ADLER32_MISMATCH = -2, + + /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */ + TINFL_STATUS_FAILED = -1, + + /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ + + /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */ + /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */ + TINFL_STATUS_DONE = 0, + + /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */ + /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */ + /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + + /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */ + /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */ + /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */ + /* so I may need to add some code to address this. */ + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +/* Initializes the decompressor to its initial state. */ +#define tinfl_init(r) \ + do \ + { \ + (r)->m_state = 0; \ + } \ + MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +/* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */ +/* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */ +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +/* Internal/private bits follow. */ +enum +{ + TINFL_MAX_HUFF_TABLES = 3, + TINFL_MAX_HUFF_SYMBOLS_0 = 288, + TINFL_MAX_HUFF_SYMBOLS_1 = 32, + TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, + TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct +{ + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS +#define TINFL_USE_64BIT_BITBUF 1 +#else +#define TINFL_USE_64BIT_BITBUF 0 +#endif + +#if TINFL_USE_64BIT_BITBUF +typedef mz_uint64 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (64) +#else +typedef mz_uint32 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag +{ + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + diff --git a/xs/src/miniz/miniz_zip.cpp b/xs/src/miniz/miniz_zip.cpp new file mode 100644 index 000000000..463660c1c --- /dev/null +++ b/xs/src/miniz/miniz_zip.cpp @@ -0,0 +1,4659 @@ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * Copyright 2016 Martin Raiber + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ +#include "miniz_zip.h" + +#include + +#ifndef MINIZ_NO_ARCHIVE_APIS + +/* ------------------- .ZIP archive reading */ + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include + +#if defined(_MSC_VER) || defined(__MINGW64__) + +static FILE *mz_fopen(const char *pFilename, const char *pMode) +{ + FILE *pFile = NULL; + pFile = boost::nowide::fopen(pFilename, pMode); + return pFile; +} +static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) +{ + FILE *pFile = NULL; + pFile = boost::nowide::freopen(pPath, pMode, pStream); + return pFile; +} +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN mz_fopen +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 _ftelli64 +#define MZ_FSEEK64 _fseeki64 +#define MZ_FILE_STAT_STRUCT _stat +#define MZ_FILE_STAT _stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN mz_freopen +#define MZ_DELETE_FILE remove +#elif defined(__MINGW32__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello64 +#define MZ_FSEEK64 fseeko64 +#define MZ_FILE_STAT_STRUCT _stat +#define MZ_FILE_STAT _stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__TINYC__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__GNUC__) && _LARGEFILE64_SOURCE +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen64(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello64 +#define MZ_FSEEK64 fseeko64 +#define MZ_FILE_STAT_STRUCT stat64 +#define MZ_FILE_STAT stat64 +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen64(p, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__APPLE__) && _LARGEFILE64_SOURCE +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen(p, m, s) +#define MZ_DELETE_FILE remove + +#else +#pragma message("Using fopen, ftello, fseeko, stat() etc. path for file I/O - this path may not support large files.") +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#ifdef __STRICT_ANSI__ +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#else +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#endif +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#endif /* #ifdef _MSC_VER */ +#endif /* #ifdef MINIZ_NO_STDIO */ + +#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) + +/* Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. */ +enum +{ + /* ZIP archive identifiers and record sizes */ + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, + MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + + /* ZIP64 archive identifier and record sizes */ + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20, + MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001, + MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50, + MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24, + MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16, + + /* Central directory header record offsets */ + MZ_ZIP_CDH_SIG_OFS = 0, + MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, + MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, + MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, + MZ_ZIP_CDH_FILE_TIME_OFS = 12, + MZ_ZIP_CDH_FILE_DATE_OFS = 14, + MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, + MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, + MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, + MZ_ZIP_CDH_DISK_START_OFS = 34, + MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, + MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + + /* Local directory header offsets */ + MZ_ZIP_LDH_SIG_OFS = 0, + MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, + MZ_ZIP_LDH_BIT_FLAG_OFS = 6, + MZ_ZIP_LDH_METHOD_OFS = 8, + MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, + MZ_ZIP_LDH_CRC32_OFS = 14, + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, + MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3, + + /* End of central directory offsets */ + MZ_ZIP_ECDH_SIG_OFS = 0, + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, + MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, + MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, + MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, + + /* ZIP64 End of central directory locator offsets */ + MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */ + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */ + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */ + + /* ZIP64 End of central directory header offsets */ + MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */ + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */ + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */ + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */ + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */ + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */ + MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0, + MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 11 +}; + +typedef struct +{ + void *m_p; + size_t m_size, m_capacity; + mz_uint m_element_size; +} mz_zip_array; + +struct mz_zip_internal_state_tag +{ + mz_zip_array m_central_dir; + mz_zip_array m_central_dir_offsets; + mz_zip_array m_sorted_central_dir_offsets; + + /* The flags passed in when the archive is initially opened. */ + uint32_t m_init_flags; + + /* MZ_TRUE if the archive has a zip64 end of central directory headers, etc. */ + mz_bool m_zip64; + + /* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64 will also be slammed to true too, even if we didn't find a zip64 end of central dir header, etc.) */ + mz_bool m_zip64_has_extended_info_fields; + + /* These fields are used by the file, FILE, memory, and memory/heap read/write helpers. */ + MZ_FILE *m_pFile; + mz_uint64 m_file_archive_start_ofs; + + void *m_pMem; + size_t m_mem_size; + size_t m_mem_capacity; +}; + +#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size + +#if defined(DEBUG) || defined(_DEBUG) || defined(NDEBUG) +static MZ_FORCEINLINE mz_uint mz_zip_array_range_check(const mz_zip_array *pArray, mz_uint index) +{ + MZ_ASSERT(index < pArray->m_size); + return index; +} +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[mz_zip_array_range_check(array_ptr, index)] +#else +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] +#endif + +static MZ_FORCEINLINE void mz_zip_array_init(mz_zip_array *pArray, mz_uint32 element_size) +{ + memset(pArray, 0, sizeof(mz_zip_array)); + pArray->m_element_size = element_size; +} + +static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) +{ + pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); + memset(pArray, 0, sizeof(mz_zip_array)); +} + +static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) +{ + void *pNew_p; + size_t new_capacity = min_new_capacity; + MZ_ASSERT(pArray->m_element_size); + if (pArray->m_capacity >= min_new_capacity) + return MZ_TRUE; + if (growing) + { + new_capacity = MZ_MAX(1, pArray->m_capacity); + while (new_capacity < min_new_capacity) + new_capacity *= 2; + } + if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) + return MZ_FALSE; + pArray->m_p = pNew_p; + pArray->m_capacity = new_capacity; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) +{ + if (new_capacity > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) + return MZ_FALSE; + } + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) +{ + if (new_size > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) + return MZ_FALSE; + } + pArray->m_size = new_size; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) +{ + return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) +{ + size_t orig_size = pArray->m_size; + if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) + return MZ_FALSE; + memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); + return MZ_TRUE; +} + +#ifndef MINIZ_NO_TIME +static MZ_TIME_T mz_zip_dos_to_time_t(int dos_time, int dos_date) +{ + struct tm tm; + memset(&tm, 0, sizeof(tm)); + tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; + tm.tm_mon = ((dos_date >> 5) & 15) - 1; + tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; + tm.tm_min = (dos_time >> 5) & 63; + tm.tm_sec = (dos_time << 1) & 62; + return mktime(&tm); +} + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS +static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ +#ifdef _MSC_VER + struct tm tm_struct; + struct tm *tm = &tm_struct; + errno_t err = localtime_s(tm, &time); + if (err) + { + *pDOS_date = 0; + *pDOS_time = 0; + return; + } +#else + struct tm *tm = localtime(&time); +#endif /* #ifdef _MSC_VER */ + + *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); + *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); +} +#endif /* MINIZ_NO_ARCHIVE_WRITING_APIS */ + +#ifndef MINIZ_NO_STDIO +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS +static mz_bool mz_zip_get_file_modified_time(const char *pFilename, MZ_TIME_T *pTime) +{ + struct MZ_FILE_STAT_STRUCT file_stat; + + /* On Linux with x86 glibc, this call will fail on large files (I think >= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */ + if (MZ_FILE_STAT(pFilename, &file_stat) != 0) + return MZ_FALSE; + + *pTime = file_stat.st_mtime; + + return MZ_TRUE; +} +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS*/ + +static mz_bool mz_zip_set_file_times(const char *pFilename, MZ_TIME_T access_time, MZ_TIME_T modified_time) +{ + struct utimbuf t; + + memset(&t, 0, sizeof(t)); + t.actime = access_time; + t.modtime = modified_time; + + return !utime(pFilename, &t); +} +#endif /* #ifndef MINIZ_NO_STDIO */ +#endif /* #ifndef MINIZ_NO_TIME */ + +static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, mz_zip_error err_num) +{ + if (pZip) + pZip->m_last_error = err_num; + return MZ_FALSE; +} + +static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint flags) +{ + (void)flags; + if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = 0; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + pZip->m_last_error = MZ_ZIP_NO_ERROR; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + pZip->m_pState->m_init_flags = flags; + pZip->m_pState->m_zip64 = MZ_FALSE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE; + + pZip->m_zip_mode = MZ_ZIP_MODE_READING; + + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (l_len < r_len) : (l < r); +} + +#define MZ_SWAP_UINT32(a, b) \ + do \ + { \ + mz_uint32 t = a; \ + a = b; \ + b = t; \ + } \ + MZ_MACRO_END + +/* Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) */ +static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices; + mz_uint32 start, end; + const mz_uint32 size = pZip->m_total_files; + + if (size <= 1U) + return; + + pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + + start = (size - 2U) >> 1U; + for (;;) + { + mz_uint64 child, root = start; + for (;;) + { + if ((child = (root << 1U) + 1U) >= size) + break; + child += (((child + 1U) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U]))); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + if (!start) + break; + start--; + } + + end = size - 1; + while (end > 0) + { + mz_uint64 child, root = 0; + MZ_SWAP_UINT32(pIndices[end], pIndices[0]); + for (;;) + { + if ((child = (root << 1U) + 1U) >= end) + break; + child += (((child + 1U) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U])); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + end--; + } +} + +static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip, mz_uint32 record_sig, mz_uint32 record_size, mz_int64 *pOfs) +{ + mz_int64 cur_file_ofs; + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + + /* Basic sanity checks - reject files which are too small */ + if (pZip->m_archive_size < record_size) + return MZ_FALSE; + + /* Find the record by scanning the file from the end towards the beginning. */ + cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); + for (;;) + { + int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); + + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) + return MZ_FALSE; + + for (i = n - 4; i >= 0; --i) + { + mz_uint s = MZ_READ_LE32(pBuf + i); + if (s == record_sig) + { + if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) + break; + } + } + + if (i >= 0) + { + cur_file_ofs += i; + break; + } + + /* Give up if we've searched the entire file, or we've gone back "too far" (~64kb) */ + if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (MZ_UINT16_MAX + record_size))) + return MZ_FALSE; + + cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); + } + + *pOfs = cur_file_ofs; + return MZ_TRUE; +} + +static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flags) +{ + mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0, cdir_disk_index = 0; + mz_uint64 cdir_ofs = 0; + mz_int64 cur_file_ofs = 0; + const mz_uint8 *p; + + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); + mz_uint32 zip64_end_of_central_dir_locator_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pZip64_locator = (mz_uint8 *)zip64_end_of_central_dir_locator_u32; + + mz_uint32 zip64_end_of_central_dir_header_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pZip64_end_of_central_dir = (mz_uint8 *)zip64_end_of_central_dir_header_u32; + + mz_uint64 zip64_end_of_central_dir_ofs = 0; + + /* Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. */ + if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_locate_header_sig(pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) + return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR); + + /* Read and verify the end of central directory record. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, pZip64_locator, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + { + if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) + { + zip64_end_of_central_dir_ofs = MZ_READ_LE64(pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS); + if (zip64_end_of_central_dir_ofs > (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, pZip64_end_of_central_dir, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + { + if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) + { + pZip->m_pState->m_zip64 = MZ_TRUE; + } + } + } + } + } + + pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS); + cdir_entries_on_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); + cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); + cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS); + cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); + + if (pZip->m_pState->m_zip64) + { + mz_uint32 zip64_total_num_of_disks = MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS); + mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS); + mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS); + mz_uint64 zip64_size_of_central_directory = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS); + + if (zip64_size_of_end_of_central_dir_record < (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (zip64_total_num_of_disks != 1U) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + /* Check for miniz's practical limits */ + if (zip64_cdir_total_entries > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries; + + if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + cdir_entries_on_this_disk = (mz_uint32)zip64_cdir_total_entries_on_this_disk; + + /* Check for miniz's current practical limits (sorry, this should be enough for millions of files) */ + if (zip64_size_of_central_directory > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + cdir_size = (mz_uint32)zip64_size_of_central_directory; + + num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS); + + cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS); + + cdir_ofs = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS); + } + + if (pZip->m_total_files != cdir_entries_on_this_disk) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pZip->m_central_directory_file_ofs = cdir_ofs; + + if (pZip->m_total_files) + { + mz_uint i, n; + /* Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and possibly another to hold the sorted indices. */ + if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (sort_central_dir) + { + if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + /* Now create an index into the central directory file records, do some basic sanity checking on each record */ + p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) + { + mz_uint total_header_size, disk_index, bit_flags, filename_size, ext_data_size; + mz_uint64 comp_size, decomp_size, local_header_ofs; + + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); + + if (sort_central_dir) + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if ((!pZip->m_pState->m_zip64_has_extended_info_fields) && + (ext_data_size) && + (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == MZ_UINT32_MAX)) + { + /* Attempt to find zip64 extended information field in the entry's extra data */ + mz_uint32 extra_size_remaining = ext_data_size; + + if (extra_size_remaining) + { + const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size; + + do + { + mz_uint32 field_id; + mz_uint32 field_data_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + /* Ok, the archive didn't have any zip64 headers but it uses a zip64 extended information field so mark it as zip64 anyway (this can occur with infozip's zip util when it reads compresses files from stdin). */ + pZip->m_pState->m_zip64 = MZ_TRUE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE; + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + } + } + + /* I've seen archives that aren't marked as zip64 that uses zip64 ext data, argh */ + if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) + { + if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); + if ((disk_index == MZ_UINT16_MAX) || ((disk_index != num_this_disk) && (disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (comp_size != MZ_UINT32_MAX) + { + if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + n -= total_header_size; + p += total_header_size; + } + } + + if (sort_central_dir) + mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); + + return MZ_TRUE; +} + +void mz_zip_zero_struct(mz_zip_archive *pZip) +{ + if (pZip) + MZ_CLEAR_OBJ(*pZip); +} + +static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) +{ + mz_bool status = MZ_TRUE; + + if (!pZip) + return MZ_FALSE; + + if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER; + + return MZ_FALSE; + } + + if (pZip->m_pState) + { + mz_zip_internal_state *pState = pZip->m_pState; + pZip->m_pState = NULL; + + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (MZ_FCLOSE(pState->m_pFile) == EOF) + { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED; + status = MZ_FALSE; + } + } + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + } + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + + return status; +} + +mz_bool mz_zip_reader_end(mz_zip_archive *pZip) +{ + return mz_zip_reader_end_internal(pZip, MZ_TRUE); +} +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags) +{ + if ((!pZip) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_archive_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); + memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); + return s; +} + +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags) +{ + if (!pMem) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY; + pZip->m_archive_size = size; + pZip->m_pRead = mz_zip_mem_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pNeeds_keepalive = NULL; + +#ifdef __cplusplus + pZip->m_pState->m_pMem = const_cast(pMem); +#else + pZip->m_pState->m_pMem = (void *)pMem; +#endif + + pZip->m_pState->m_mem_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + + return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) +{ + return mz_zip_reader_init_file_v2(pZip, pFilename, flags, 0, 0); +} + +mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size) +{ + mz_uint64 file_size; + MZ_FILE *pFile; + + if ((!pZip) || (!pFilename) || ((archive_size) && (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pFile = MZ_FOPEN(pFilename, "rb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + file_size = archive_size; + if (!file_size) + { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + } + + file_size = MZ_FTELL64(pFile); + } + + /* TODO: Better sanity check archive_size and the # of actual remaining bytes */ + + if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) + { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + pZip->m_pState->m_file_archive_start_ofs = file_start_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags) +{ + mz_uint64 cur_file_ofs; + + if ((!pZip) || (!pFile)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + cur_file_ofs = MZ_FTELL64(pFile); + + if (!archive_size) + { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + + archive_size = MZ_FTELL64(pFile) - cur_file_ofs; + + if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = archive_size; + pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +#endif /* #ifndef MINIZ_NO_STDIO */ + +static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip, mz_uint file_index) +{ + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) + return NULL; + return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); +} + +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint m_bit_flag; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + return (m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0; +} + +mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint bit_flag; + mz_uint method; + + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); + bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + + if ((method != 0) && (method != MZ_DEFLATED)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + return MZ_FALSE; + } + + if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + return MZ_FALSE; + } + + if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint filename_len, attribute_mapping_id, external_attr; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_len) + { + if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + return MZ_TRUE; + } + + /* Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. */ + /* Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. */ + /* FIXME: Remove this check? Is it necessary - we already check the filename. */ + attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8; + (void)attribute_mapping_id; + + external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) + { + return MZ_TRUE; + } + + return MZ_FALSE; +} + +static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_index, const mz_uint8 *pCentral_dir_header, mz_zip_archive_file_stat *pStat, mz_bool *pFound_zip64_extra_data) +{ + mz_uint n; + const mz_uint8 *p = pCentral_dir_header; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_FALSE; + + if ((!p) || (!pStat)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Extract fields from the central directory record. */ + pStat->m_file_index = file_index; + pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); + pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); + pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); + pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); +#ifndef MINIZ_NO_TIME + pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); +#endif + pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); + pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + + /* Copy as much of the filename and comment as possible. */ + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pStat->m_filename[n] = '\0'; + + n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + pStat->m_comment_size = n; + memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); + pStat->m_comment[n] = '\0'; + + /* Set some flags for convienance */ + pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index); + pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index); + pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index); + + /* See if we need to read any zip64 extended information fields. */ + /* Confusingly, these zip64 fields can be present even on non-zip64 archives (Debian zip on a huge files from stdin piped to stdout creates them). */ + if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), pStat->m_local_header_ofs) == MZ_UINT32_MAX) + { + /* Attempt to find zip64 extended information field in the entry's extra data */ + mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if (extra_size_remaining) + { + const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + + do + { + mz_uint32 field_id; + mz_uint32 field_data_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2; + mz_uint32 field_data_remaining = field_data_size; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_TRUE; + + if (pStat->m_uncomp_size == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_uncomp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_comp_size == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_comp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_local_header_ofs == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_local_header_ofs = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + } + } + + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) +{ + mz_uint i; + if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + return 0 == memcmp(pA, pB, len); + for (i = 0; i < len; ++i) + if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) + return MZ_FALSE; + return MZ_TRUE; +} + +static MZ_FORCEINLINE int mz_zip_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (int)(l_len - r_len) : (l - r); +} + +static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename, mz_uint32 *pIndex) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const uint32_t size = pZip->m_total_files; + const mz_uint filename_len = (mz_uint)strlen(pFilename); + + if (pIndex) + *pIndex = 0; + + if (size) + { + /* yes I could use uint32_t's, but then we would have to add some special case checks in the loop, argh, and */ + /* honestly the major expense here on 32-bit CPU's will still be the filename compare */ + mz_int64 l = 0, h = (mz_int64)size - 1; + + while (l <= h) + { + mz_int64 m = l + ((h - l) >> 1); + uint32_t file_index = pIndices[(uint32_t)m]; + + int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); + if (!comp) + { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + else if (comp < 0) + l = m + 1; + else + h = m - 1; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); +} + +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) +{ + mz_uint32 index; + if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) + return -1; + else + return (int)index; +} + +mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex) +{ + mz_uint file_index; + size_t name_len, comment_len; + + if (pIndex) + *pIndex = 0; + + if ((!pZip) || (!pZip->m_pState) || (!pName)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* See if we can use a binary search */ + if (((pZip->m_pState->m_init_flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && + (pZip->m_zip_mode == MZ_ZIP_MODE_READING) && + ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) + { + return mz_zip_locate_file_binary_search(pZip, pName, pIndex); + } + + /* Locate the entry by scanning the entire central directory */ + name_len = strlen(pName); + if (name_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + comment_len = pComment ? strlen(pComment) : 0; + if (comment_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + for (file_index = 0; file_index < pZip->m_total_files; file_index++) + { + const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + if (filename_len < name_len) + continue; + if (comment_len) + { + mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + const char *pFile_comment = pFilename + filename_len + file_extra_len; + if ((file_comment_len != comment_len) || (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, flags))) + continue; + } + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) + { + int ofs = filename_len - 1; + do + { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) + break; + } while (--ofs >= 0); + ofs++; + pFilename += ofs; + filename_len -= ofs; + } + if ((filename_len == name_len) && (mz_zip_string_equal(pName, pFilename, filename_len, flags))) + { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); +} + +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + int status = TINFL_STATUS_DONE; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + tinfl_decompressor inflator; + + if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Ensure supplied output buffer is large enough. */ + needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + if (buf_size < needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL); + + /* Read and parse the local directory entry. */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) + { + if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + } +#endif + + return MZ_TRUE; + } + + /* Decompress the file either directly from memory or from a file input buffer. */ + tinfl_init(&inflator); + + if (pZip->m_pState->m_pMem) + { + /* Read directly from the archive in memory. */ + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else if (pUser_read_buf) + { + /* Use a user provided read buffer. */ + if (!user_read_buf_size) + return MZ_FALSE; + pRead_buf = (mz_uint8 *)pUser_read_buf; + read_buf_size = user_read_buf_size; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + else + { + /* Temporarily allocate a read buffer. */ + read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + do + { + /* The size_t cast here should be OK because we've verified that the output buffer is >= file_stat.m_uncomp_size above */ + size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + out_buf_ofs += out_buf_size; + } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + + if (status == TINFL_STATUS_DONE) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); +} + +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); +} + +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); +} + +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) +{ + mz_uint64 comp_size, uncomp_size, alloc_size; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + void *pBuf; + + if (pSize) + *pSize = 0; + + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return NULL; + } + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + + alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; + if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) + { + mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + return NULL; + } + + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return NULL; + } + + if (pSize) + *pSize = (size_t)alloc_size; + return pBuf; +} + +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + { + if (pSize) + *pSize = 0; + return MZ_FALSE; + } + return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); +} + +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + int status = TINFL_STATUS_DONE; + mz_uint file_crc32 = MZ_CRC32_INIT; + mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf = NULL; + void *pWrite_buf = NULL; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Read and do some minimal validation of the local directory entry (this doesn't crack the zip64 stuff, which we already have from the central dir) */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + /* Decompress the file either directly from memory or from a file input buffer. */ + if (pZip->m_pState->m_pMem) + { + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pState->m_pMem) + { + if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + } + else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); +#endif + } + + cur_file_ofs += file_stat.m_comp_size; + out_buf_ofs += file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + while (comp_remaining) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); + } +#endif + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + + cur_file_ofs += read_buf_avail; + out_buf_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + } + } + } + else + { + tinfl_decompressor inflator; + tinfl_init(&inflator); + + if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + status = TINFL_STATUS_FAILED; + } + else + { + do + { + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + + if (out_buf_size) + { + if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); +#endif + if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + } + } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } + } + + if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (file_crc32 != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if (!pZip->m_pState->m_pMem) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + if (pWrite_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); +} + +mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) +{ + mz_zip_reader_extract_iter_state *pState; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + /* Argument sanity check */ + if ((!pZip) || (!pZip->m_pState)) + return NULL; + + /* Allocate an iterator status structure */ + pState = (mz_zip_reader_extract_iter_state*)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_reader_extract_iter_state)); + if (!pState) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + /* Fetch file details */ + if (!mz_zip_reader_file_stat(pZip, file_index, &pState->file_stat)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Encryption and patch files are not supported. */ + if (pState->file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (pState->file_stat.m_method != 0) && (pState->file_stat.m_method != MZ_DEFLATED)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Init state - save args */ + pState->pZip = pZip; + pState->flags = flags; + + /* Init state - reset variables to defaults */ + pState->status = TINFL_STATUS_DONE; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + pState->file_crc32 = MZ_CRC32_INIT; +#endif + pState->read_buf_ofs = 0; + pState->out_buf_ofs = 0; + pState->pRead_buf = NULL; + pState->pWrite_buf = NULL; + pState->out_blk_remain = 0; + + /* Read and parse the local directory entry. */ + pState->cur_file_ofs = pState->file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, pState->cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + pState->cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((pState->cur_file_ofs + pState->file_stat.m_comp_size) > pZip->m_archive_size) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + + /* Decompress the file either directly from memory or from a file input buffer. */ + if (pZip->m_pState->m_pMem) + { + pState->pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + pState->cur_file_ofs; + pState->read_buf_size = pState->read_buf_avail = pState->file_stat.m_comp_size; + pState->comp_remaining = pState->file_stat.m_comp_size; + } + else + { + if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) + { + /* Decompression required, therefore intermediate read buffer required */ + pState->read_buf_size = MZ_MIN(pState->file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pState->pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)pState->read_buf_size))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + } + else + { + /* Decompression not required - we will be reading directly into user buffer, no temp buf required */ + pState->read_buf_size = 0; + } + pState->read_buf_avail = 0; + pState->comp_remaining = pState->file_stat.m_comp_size; + } + + if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method))) + { + /* Decompression required, init decompressor */ + tinfl_init( &pState->inflator ); + + /* Allocate write buffer */ + if (NULL == (pState->pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + if (pState->pRead_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->pRead_buf); + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + return NULL; + } + } + + return pState; +} + +mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) +{ + mz_uint32 file_index; + + /* Locate file index by name */ + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return NULL; + + /* Construct iterator */ + return mz_zip_reader_extract_iter_new(pZip, file_index, flags); +} + +size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size) +{ + size_t copied_to_caller = 0; + + /* Argument sanity check */ + if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState) || (!pvBuf)) + return 0; + + if ((pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!pState->file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data, calc amount to return. */ + copied_to_caller = MZ_MIN( buf_size, pState->comp_remaining ); + + /* Zip is in memory....or requires reading from a file? */ + if (pState->pZip->m_pState->m_pMem) + { + /* Copy data to caller's buffer */ + memcpy( pvBuf, pState->pRead_buf, copied_to_caller ); + pState->pRead_buf = ((mz_uint8*)pState->pRead_buf) + copied_to_caller; + } + else + { + /* Read directly into caller's buffer */ + if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pvBuf, copied_to_caller) != copied_to_caller) + { + /* Failed to read all that was asked for, flag failure and alert user */ + mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); + pState->status = TINFL_STATUS_FAILED; + copied_to_caller = 0; + } + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + /* Compute CRC if not returning compressed data only */ + if (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, (const mz_uint8 *)pvBuf, copied_to_caller); +#endif + + /* Advance offsets, dec counters */ + pState->cur_file_ofs += copied_to_caller; + pState->out_buf_ofs += copied_to_caller; + pState->comp_remaining -= copied_to_caller; + } + else + { + do + { + /* Calc ptr to write buffer - given current output pos and block size */ + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pState->pWrite_buf + (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + + /* Calc max output size - given current output pos and block size */ + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + + if (!pState->out_blk_remain) + { + /* Read more data from file if none available (and reading from file) */ + if ((!pState->read_buf_avail) && (!pState->pZip->m_pState->m_pMem)) + { + /* Calc read size */ + pState->read_buf_avail = MZ_MIN(pState->read_buf_size, pState->comp_remaining); + if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, pState->cur_file_ofs, pState->pRead_buf, (size_t)pState->read_buf_avail) != pState->read_buf_avail) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); + pState->status = TINFL_STATUS_FAILED; + break; + } + + /* Advance offsets, dec counters */ + pState->cur_file_ofs += pState->read_buf_avail; + pState->comp_remaining -= pState->read_buf_avail; + pState->read_buf_ofs = 0; + } + + /* Perform decompression */ + in_buf_size = (size_t)pState->read_buf_avail; + pState->status = tinfl_decompress(&pState->inflator, (const mz_uint8 *)pState->pRead_buf + pState->read_buf_ofs, &in_buf_size, (mz_uint8 *)pState->pWrite_buf, pWrite_buf_cur, &out_buf_size, pState->comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + pState->read_buf_avail -= in_buf_size; + pState->read_buf_ofs += in_buf_size; + + /* Update current output block size remaining */ + pState->out_blk_remain = out_buf_size; + } + + if (pState->out_blk_remain) + { + /* Calc amount to return. */ + size_t to_copy = MZ_MIN( (buf_size - copied_to_caller), pState->out_blk_remain ); + + /* Copy data to caller's buffer */ + memcpy( (uint8_t*)pvBuf + copied_to_caller, pWrite_buf_cur, to_copy ); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + /* Perform CRC */ + pState->file_crc32 = (mz_uint32)mz_crc32(pState->file_crc32, pWrite_buf_cur, to_copy); +#endif + + /* Decrement data consumed from block */ + pState->out_blk_remain -= to_copy; + + /* Inc output offset, while performing sanity check */ + if ((pState->out_buf_ofs += to_copy) > pState->file_stat.m_uncomp_size) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); + pState->status = TINFL_STATUS_FAILED; + break; + } + + /* Increment counter of data copied to caller */ + copied_to_caller += to_copy; + } + } while ( (copied_to_caller < buf_size) && ((pState->status == TINFL_STATUS_NEEDS_MORE_INPUT) || (pState->status == TINFL_STATUS_HAS_MORE_OUTPUT)) ); + } + + /* Return how many bytes were copied into user buffer */ + return copied_to_caller; +} + +mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState) +{ + int status; + + /* Argument sanity check */ + if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState)) + return MZ_FALSE; + + /* Was decompression completed and requested? */ + if ((pState->status == TINFL_STATUS_DONE) && (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (pState->out_buf_ofs != pState->file_stat.m_uncomp_size) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + pState->status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (pState->file_crc32 != pState->file_stat.m_crc32) + { + mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); + pState->status = TINFL_STATUS_FAILED; + } +#endif + } + + /* Free buffers */ + if (!pState->pZip->m_pState->m_pMem) + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pRead_buf); + if (pState->pWrite_buf) + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pWrite_buf); + + /* Save status */ + status = pState->status; + + /* Free context */ + pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState); + + return status == TINFL_STATUS_DONE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) +{ + (void)ofs; + + return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); +} + +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) +{ + mz_bool status; + mz_zip_archive_file_stat file_stat; + MZ_FILE *pFile; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + pFile = MZ_FOPEN(pDst_filename, "wb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); + + if (MZ_FCLOSE(pFile) == EOF) + { + if (status) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + + status = MZ_FALSE; + } + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + if (status) + mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); +#endif + + return status; +} + +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); +} + +mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *pFile, mz_uint flags) +{ + mz_zip_archive_file_stat file_stat; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + return mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); +} + +mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags); +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +static size_t mz_zip_compute_crc32_callback(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_uint32 *p = (mz_uint32 *)pOpaque; + (void)file_ofs; + *p = (mz_uint32)mz_crc32(*p, (const mz_uint8 *)pBuf, n); + return n; +} + +mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) +{ + mz_zip_archive_file_stat file_stat; + mz_zip_internal_state *pState; + const mz_uint8 *pCentral_dir_header; + mz_bool found_zip64_ext_data_in_cdir = MZ_FALSE; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint64 local_header_ofs = 0; + mz_uint32 local_header_filename_len, local_header_extra_len, local_header_crc32; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_uint32 uncomp_crc32 = MZ_CRC32_INIT; + mz_bool has_data_descriptor; + mz_uint32 local_header_bit_flags; + + mz_zip_array file_data_array; + mz_zip_array_init(&file_data_array, 1); + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (file_index > pZip->m_total_files) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + pCentral_dir_header = mz_zip_get_cdh(pZip, file_index); + + if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, &file_stat, &found_zip64_ext_data_in_cdir)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_uncomp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_is_encrypted) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports stored and deflate. */ + if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + if (!file_stat.m_is_supported) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + /* Read and parse the local directory entry. */ + local_header_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + local_header_filename_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + local_header_crc32 = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_CRC32_OFS); + local_header_bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + has_data_descriptor = (local_header_bit_flags & 8) != 0; + + if (local_header_filename_len != strlen(file_stat.m_filename)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (!mz_zip_array_resize(pZip, &file_data_array, MZ_MAX(local_header_filename_len, local_header_extra_len), MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (local_header_filename_len) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, file_data_array.m_p, local_header_filename_len) != local_header_filename_len) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + /* I've seen 1 archive that had the same pathname, but used backslashes in the local dir and forward slashes in the central dir. Do we care about this? For now, this case will fail validation. */ + if (memcmp(file_stat.m_filename, file_data_array.m_p, local_header_filename_len) != 0) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + { + mz_uint32 extra_size_remaining = local_header_extra_len; + const mz_uint8 *pExtra_data = (const mz_uint8 *)file_data_array.m_p; + + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + /* TODO: parse local header extra data when local_header_comp_size is 0xFFFFFFFF! (big_descriptor.zip) */ + /* I've seen zips in the wild with the data descriptor bit set, but proper local header values and bogus data descriptors */ + if ((has_data_descriptor) && (!local_header_comp_size) && (!local_header_crc32)) + { + mz_uint8 descriptor_buf[32]; + mz_bool has_id; + const mz_uint8 *pSrc; + mz_uint32 file_crc32; + mz_uint64 comp_size = 0, uncomp_size = 0; + + mz_uint32 num_descriptor_uint32s = ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4; + + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size, descriptor_buf, sizeof(mz_uint32) * num_descriptor_uint32s) != (sizeof(mz_uint32) * num_descriptor_uint32s)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + has_id = (MZ_READ_LE32(descriptor_buf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + pSrc = has_id ? (descriptor_buf + sizeof(mz_uint32)) : descriptor_buf; + + file_crc32 = MZ_READ_LE32(pSrc); + + if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + { + comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64)); + } + else + { + comp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32)); + } + + if ((file_crc32 != file_stat.m_crc32) || (comp_size != file_stat.m_comp_size) || (uncomp_size != file_stat.m_uncomp_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + else + { + if ((local_header_crc32 != file_stat.m_crc32) || (local_header_comp_size != file_stat.m_comp_size) || (local_header_uncomp_size != file_stat.m_uncomp_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + mz_zip_array_clear(pZip, &file_data_array); + + if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) + { + if (!mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0)) + return MZ_FALSE; + + /* 1 more check to be sure, although the extract checks too. */ + if (uncomp_crc32 != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + return MZ_FALSE; + } + } + + return MZ_TRUE; + +handle_failure: + mz_zip_array_clear(pZip, &file_data_array); + return MZ_FALSE; +} + +mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags) +{ + mz_zip_internal_state *pState; + uint32_t i; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Basic sanity checks */ + if (!pState->m_zip64) + { + if (pZip->m_total_files > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (pZip->m_archive_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + else + { + if (pZip->m_total_files >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + for (i = 0; i < pZip->m_total_files; i++) + { + if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) + { + mz_uint32 found_index; + mz_zip_archive_file_stat stat; + + if (!mz_zip_reader_file_stat(pZip, i, &stat)) + return MZ_FALSE; + + if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, &found_index)) + return MZ_FALSE; + + /* This check can fail if there are duplicate filenames in the archive (which we don't check for when writing - that's up to the user) */ + if (found_index != i) + return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + } + + if (!mz_zip_validate_file(pZip, i, flags)) + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr) +{ + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if ((!pMem) || (!size)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_mem(&zip, pMem, size, flags)) + { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) + { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) + { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr) +{ + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if (!pFilename) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) + { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) + { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) + { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +/* ------------------- .ZIP archive writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +static MZ_FORCEINLINE void mz_write_le16(mz_uint8 *p, mz_uint16 v) +{ + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); +} +static MZ_FORCEINLINE void mz_write_le32(mz_uint8 *p, mz_uint32 v) +{ + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); + p[2] = (mz_uint8)(v >> 16); + p[3] = (mz_uint8)(v >> 24); +} +static MZ_FORCEINLINE void mz_write_le64(mz_uint8 *p, mz_uint64 v) +{ + mz_write_le32(p, (mz_uint32)v); + mz_write_le32(p + sizeof(mz_uint32), (mz_uint32)(v >> 32)); +} + +#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) +#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) +#define MZ_WRITE_LE64(p, v) mz_write_le64((mz_uint8 *)(p), (mz_uint64)(v)) + +static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); + + if (!n) + return 0; + + /* An allocation this big is likely to just fail on 32-bit systems, so don't even go there. */ + if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + return 0; + } + + if (new_size > pState->m_mem_capacity) + { + void *pNew_block; + size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); + + while (new_capacity < new_size) + new_capacity *= 2; + + if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return 0; + } + + pState->m_pMem = pNew_block; + pState->m_mem_capacity = new_capacity; + } + memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); + pState->m_mem_size = (size_t)new_size; + return n; +} + +static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) +{ + mz_zip_internal_state *pState; + mz_bool status = MZ_TRUE; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (MZ_FCLOSE(pState->m_pFile) == EOF) + { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + status = MZ_FALSE; + } + } + + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); + pState->m_pMem = NULL; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + return status; +} + +mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags) +{ + mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0; + + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + { + if (!pZip->m_pRead) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (pZip->m_file_offset_alignment) + { + /* Ensure user specified file offset alignment is a power of 2. */ + if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = existing_size; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + + pZip->m_pState->m_zip64 = zip64; + pZip->m_pState->m_zip64_has_extended_info_fields = zip64; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) +{ + return mz_zip_writer_init_v2(pZip, existing_size, 0); +} + +mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags) +{ + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_mem_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_HEAP; + + if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) + { + if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) + { + mz_zip_writer_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + pZip->m_pState->m_mem_capacity = initial_allocation_size; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) +{ + return mz_zip_writer_init_heap_v2(pZip, size_to_reserve_at_beginning, initial_allocation_size, 0); +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + return 0; + } + + return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) +{ + return mz_zip_writer_init_file_v2(pZip, pFilename, size_to_reserve_at_beginning, 0); +} + +mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags) +{ + MZ_FILE *pFile; + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + if (NULL == (pFile = MZ_FOPEN(pFilename, (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) + { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + + pZip->m_pState->m_pFile = pFile; + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + + if (size_to_reserve_at_beginning) + { + mz_uint64 cur_ofs = 0; + char buf[4096]; + + MZ_CLEAR_OBJ(buf); + + do + { + size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) + { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_ofs += n; + size_to_reserve_at_beginning -= n; + } while (size_to_reserve_at_beginning); + } + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags) +{ + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, 0, flags)) + return MZ_FALSE; + + pZip->m_pState->m_pFile = pFile; + pZip->m_pState->m_file_archive_start_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + + return MZ_TRUE; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) +{ + mz_zip_internal_state *pState; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) + { + /* We don't support converting a non-zip64 file to zip64 - this seems like more trouble than it's worth. (What about the existing 32-bit data descriptors that could follow the compressed data?) */ + if (!pZip->m_pState->m_zip64) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* No sense in trying to write to an archive that's already at the support max size */ + if (pZip->m_pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + pState = pZip->m_pState; + + if (pState->m_pFile) + { +#ifdef MINIZ_NO_STDIO + (void)pFilename; + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); +#else + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (!pFilename) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Archive is being read from stdio and was originally opened only for reading. Try to reopen as writable. */ + if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) + { + /* The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. */ + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + } + + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pNeeds_keepalive = NULL; +#endif /* #ifdef MINIZ_NO_STDIO */ + } + else if (pState->m_pMem) + { + /* Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. */ + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pNeeds_keepalive = NULL; + } + /* Archive is being read via a user provided read function - make sure the user has specified a write function too. */ + else if (!pZip->m_pWrite) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Start writing new files at the archive's current central directory location. */ + /* TODO: We could add a flag that lets the user start writing immediately AFTER the existing central dir - this would be safer. */ + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_central_directory_file_ofs = 0; + + /* Clear the sorted central dir offsets, they aren't useful or maintained now. */ + /* Even though we're now in write mode, files can still be extracted and verified, but file locates will be slow. */ + /* TODO: We could easily maintain the sorted central directory offsets. */ + mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) +{ + return mz_zip_writer_init_from_reader_v2(pZip, pFilename, 0); +} + +/* TODO: pArchive_name is a terrible name here! */ +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) +{ + return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); +} + +typedef struct +{ + mz_zip_archive *m_pZip; + mz_uint64 m_cur_archive_file_ofs; + mz_uint64 m_comp_size; +} mz_zip_writer_add_state; + +static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) +{ + mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; + if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) + return MZ_FALSE; + + pState->m_cur_archive_file_ofs += len; + pState->m_comp_size += len; + return MZ_TRUE; +} + +#define MZ_ZIP64_MAX_LOCAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 2) +#define MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 3) +static mz_uint32 mz_zip_writer_create_zip64_extra_data(mz_uint8 *pBuf, mz_uint64 *pUncomp_size, mz_uint64 *pComp_size, mz_uint64 *pLocal_header_ofs) +{ + mz_uint8 *pDst = pBuf; + mz_uint32 field_size = 0; + + MZ_WRITE_LE16(pDst + 0, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + MZ_WRITE_LE16(pDst + 2, 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) + { + MZ_WRITE_LE64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pComp_size) + { + MZ_WRITE_LE64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) + { + MZ_WRITE_LE64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + MZ_WRITE_LE16(pBuf + 2, field_size); + + return (mz_uint32)(pDst - pBuf); +} + +static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, + mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, + mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, + mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_MIN(local_header_ofs, MZ_UINT32_MAX)); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, + const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, + mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, + mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes, + const char *user_extra_data, mz_uint user_extra_data_len) +{ + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; + size_t orig_central_dir_size = pState->m_central_dir.m_size; + mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + + if (!pZip->m_pState->m_zip64) + { + if (local_header_ofs > 0xFFFFFFFF) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + user_extra_data_len + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size + user_extra_data_len, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data, user_extra_data_len)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) + { + /* Try to resize the central directory array back into its original state. */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) +{ + /* Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. */ + if (*pArchive_name == '/') + return MZ_FALSE; + + while (*pArchive_name) + { + if ((*pArchive_name == '\\') || (*pArchive_name == ':')) + return MZ_FALSE; + + pArchive_name++; + } + + return MZ_TRUE; +} + +static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) +{ + mz_uint32 n; + if (!pZip->m_file_offset_alignment) + return 0; + n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); + return (mz_uint)((pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1)); +} + +static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) +{ + char buf[4096]; + memset(buf, 0, MZ_MIN(sizeof(buf), n)); + while (n) + { + mz_uint32 s = MZ_MIN(sizeof(buf), n); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_file_ofs += s; + n -= s; + } + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) +{ + return mz_zip_writer_add_mem_ex_v2(pZip, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, uncomp_size, uncomp_crc32, NULL, NULL, 0, NULL, 0); +} + +mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + tdefl_compressor *pComp = NULL; + mz_bool store_data_uncompressed; + mz_zip_internal_state *pState; + mz_uint8 *pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_uint16 bit_flags = 0; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if (uncomp_size || (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + + if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) + bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + level = level_and_flags & 0xF; + store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + +#ifndef MINIZ_NO_TIME + if (last_modified != NULL) + { + mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date); + } + else + { + MZ_TIME_T cur_time; + time(&cur_time); + mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date); + } +#endif /* #ifndef MINIZ_NO_TIME */ + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) + { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + user_extra_data_len + + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + user_extra_data_central_len + + MZ_ZIP_DATA_DESCRIPTER_SIZE32) > 0xFFFFFFFF) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) + { + /* Set DOS Subdirectory attribute bit. */ + ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; + + /* Subdirectories cannot contain data. */ + if ((buf_size) || (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) */ + if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if ((!store_data_uncompressed) && (buf_size)) + { + if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + cur_archive_file_ofs += num_alignment_padding_bytes; + + MZ_CLEAR_OBJ(local_dir_header); + + if (!store_data_uncompressed || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + method = MZ_DEFLATED; + } + + if (pState->m_zip64) + { + if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + { + pExtra_data = extra_data; + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, extra_size + user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + + if (pExtra_data != NULL) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + } + else + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); + uncomp_size = buf_size; + if (uncomp_size <= 3) + { + level = 0; + store_data_uncompressed = MZ_TRUE; + } + } + + if (store_data_uncompressed) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += buf_size; + comp_size = buf_size; + } + else if (buf_size) + { + mz_zip_writer_add_state state; + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || + (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pComp = NULL; + + if (uncomp_size) + { + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR); + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) + { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else + { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, extra_size, pComment, + comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, + user_extra_data_central, user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + mz_uint16 gen_flags = MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; + mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; + mz_uint64 local_dir_header_ofs, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = size_to_add, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + mz_uint8 *pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_zip_internal_state *pState; + + if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) + gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if ((!pState->m_zip64) && (uncomp_size > MZ_UINT32_MAX)) + { + /* Source file is too large for non-zip64 */ + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + pState->m_zip64 = MZ_TRUE; + } + + /* We could support this, but why? */ + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + if (pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) + { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + + archive_name_size + comment_size + user_extra_data_len + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024 + + MZ_ZIP_DATA_DESCRIPTER_SIZE32 + user_extra_data_central_len) > 0xFFFFFFFF) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + +#ifndef MINIZ_NO_TIME + if (pFile_time) + { + mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date); + } +#endif + + if (uncomp_size <= 3) + level = 0; + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += num_alignment_padding_bytes; + local_dir_header_ofs = cur_archive_file_ofs; + + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + + if (uncomp_size && level) + { + method = MZ_DEFLATED; + } + + MZ_CLEAR_OBJ(local_dir_header); + if (pState->m_zip64) + { + if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + { + pExtra_data = extra_data; + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, extra_size + user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + else + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (uncomp_size) + { + mz_uint64 uncomp_remaining = uncomp_size; + void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) + { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!level) + { + while (uncomp_remaining) + { + mz_uint n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); + if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + uncomp_remaining -= n; + cur_archive_file_ofs += n; + } + comp_size = uncomp_size; + } + else + { + mz_bool result = MZ_FALSE; + mz_zip_writer_add_state state; + tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + } + + for (;;) + { + size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + tdefl_status status; + tdefl_flush flush = TDEFL_NO_FLUSH; + + if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + break; + } + + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); + uncomp_remaining -= in_buf_size; + + if (pZip->m_pNeeds_keepalive != NULL && pZip->m_pNeeds_keepalive(pZip->m_pIO_opaque)) + flush = TDEFL_FULL_FLUSH; + + status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? flush : TDEFL_FINISH); + if (status == TDEFL_STATUS_DONE) + { + result = MZ_TRUE; + break; + } + else if (status != TDEFL_STATUS_OKAY) + { + mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + break; + } + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + + if (!result) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + } + + { + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) + { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else + { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, extra_size, pComment, comment_size, + uncomp_size, comp_size, uncomp_crc32, method, gen_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, + user_extra_data_central, user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + MZ_FILE *pSrc_file = NULL; + mz_uint64 uncomp_size = 0; + MZ_TIME_T file_modified_time; + MZ_TIME_T *pFile_time = NULL; + mz_bool status; + + memset(&file_modified_time, 0, sizeof(file_modified_time)); + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + pFile_time = &file_modified_time; + if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED); +#endif + + pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); + if (!pSrc_file) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + MZ_FSEEK64(pSrc_file, 0, SEEK_END); + uncomp_size = MZ_FTELL64(pSrc_file); + MZ_FSEEK64(pSrc_file, 0, SEEK_SET); + + status = mz_zip_writer_add_cfile(pZip, pArchive_name, pSrc_file, uncomp_size, pFile_time, pComment, comment_size, level_and_flags, NULL, 0, NULL, 0); + + MZ_FCLOSE(pSrc_file); + + return status; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext, mz_zip_archive *pZip, const mz_uint8 *pExt, uint32_t ext_len, mz_uint64 *pComp_size, mz_uint64 *pUncomp_size, mz_uint64 *pLocal_header_ofs, mz_uint32 *pDisk_start) +{ + /* + 64 should be enough for any new zip64 data */ + if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE); + + if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) + { + mz_uint8 new_ext_block[64]; + mz_uint8 *pDst = new_ext_block; + mz_write_le16(pDst, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + mz_write_le16(pDst + sizeof(mz_uint16), 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) + { + mz_write_le64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + } + + if (pComp_size) + { + mz_write_le64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) + { + mz_write_le64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + } + + if (pDisk_start) + { + mz_write_le32(pDst, *pDisk_start); + pDst += sizeof(mz_uint32); + } + + mz_write_le16(new_ext_block + sizeof(mz_uint16), (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2)); + + if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, pDst - new_ext_block)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if ((pExt) && (ext_len)) + { + mz_uint32 extra_size_remaining = ext_len; + const mz_uint8 *pExtra_data = pExt; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, field_total_size)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + return MZ_TRUE; +} + +/* TODO: This func is now pretty freakin complex due to zip64, split it up? */ +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index) +{ + mz_uint n, bit_flags, num_alignment_padding_bytes, src_central_dir_following_data_size; + mz_uint64 src_archive_bytes_remaining, local_dir_header_ofs; + mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint8 new_central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + size_t orig_central_dir_size; + mz_zip_internal_state *pState; + void *pBuf; + const mz_uint8 *pSrc_central_header; + mz_zip_archive_file_stat src_file_stat; + mz_uint32 src_filename_len, src_comment_len, src_ext_len; + mz_uint32 local_header_filename_size, local_header_extra_len; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Don't support copying files from zip64 archives to non-zip64, even though in some cases this is possible */ + if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Get pointer to the source central dir header and crack it */ + if (NULL == (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + src_filename_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS); + src_comment_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + src_ext_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS); + src_central_dir_following_data_size = src_filename_len + src_ext_len + src_comment_len; + + /* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32 fudge factor in case we need to add more extra data) */ + if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + if (!pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + /* TODO: Our zip64 support still has some 32-bit limits that may not be worth fixing. */ + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + if (!mz_zip_file_stat_internal(pSource_zip, src_file_index, pSrc_central_header, &src_file_stat, NULL)) + return MZ_FALSE; + + cur_src_file_ofs = src_file_stat.m_local_header_ofs; + cur_dst_file_ofs = pZip->m_archive_size; + + /* Read the source archive's local dir header */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Compute the total size we need to copy (filename+extra data+compressed data) */ + local_header_filename_size = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + src_archive_bytes_remaining = local_header_filename_size + local_header_extra_len + src_file_stat.m_comp_size; + + /* Try to find a zip64 extended information field */ + if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + { + mz_zip_array file_data_array; + const mz_uint8 *pExtra_data; + mz_uint32 extra_size_remaining = local_header_extra_len; + + mz_zip_array_init(&file_data_array, 1); + if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, MZ_FALSE)) + { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, src_file_stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_size, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + pExtra_data = (const mz_uint8 *)file_data_array.m_p; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); /* may be 0 if there's a descriptor */ + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + + mz_zip_array_clear(pZip, &file_data_array); + } + + if (!pState->m_zip64) + { + /* Try to detect if the new archive will most likely wind up too big and bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which could be present, +64 is a fudge factor). */ + /* We also check when the archive is finalized so this doesn't need to be perfect. */ + mz_uint64 approx_new_archive_size = cur_dst_file_ofs + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining + (sizeof(mz_uint32) * 4) + + pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64; + + if (approx_new_archive_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + /* Write dest archive padding */ + if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + return MZ_FALSE; + + cur_dst_file_ofs += num_alignment_padding_bytes; + + local_dir_header_ofs = cur_dst_file_ofs; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + + /* The original zip's local header+ext block doesn't change, even with zip64, so we can just copy it over to the dest zip */ + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Copy over the source archive bytes to the dest archive, also ensure we have enough buf space to handle optional data descriptor */ + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining))))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + while (src_archive_bytes_remaining) + { + n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining); + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + cur_src_file_ofs += n; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_dst_file_ofs += n; + + src_archive_bytes_remaining -= n; + } + + /* Now deal with the optional data descriptor */ + bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + if (bit_flags & 8) + { + /* Copy data descriptor */ + if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + { + /* src is zip64, dest must be zip64 */ + + /* name uint32_t's */ + /* id 1 (optional in zip64?) */ + /* crc 1 */ + /* comp_size 2 */ + /* uncomp_size 2 */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, (sizeof(mz_uint32) * 6)) != (sizeof(mz_uint32) * 6)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) ? 6 : 5); + } + else + { + /* src is NOT zip64 */ + mz_bool has_id; + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + + if (pZip->m_pState->m_zip64) + { + /* dest is zip64, so upgrade the data descriptor */ + const mz_uint32 *pSrc_descriptor = (const mz_uint32 *)((const mz_uint8 *)pBuf + (has_id ? sizeof(mz_uint32) : 0)); + const mz_uint32 src_crc32 = pSrc_descriptor[0]; + const mz_uint64 src_comp_size = pSrc_descriptor[1]; + const mz_uint64 src_uncomp_size = pSrc_descriptor[2]; + + mz_write_le32((mz_uint8 *)pBuf, MZ_ZIP_DATA_DESCRIPTOR_ID); + mz_write_le32((mz_uint8 *)pBuf + sizeof(mz_uint32) * 1, src_crc32); + mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 2, src_comp_size); + mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 4, src_uncomp_size); + + n = sizeof(mz_uint32) * 6; + } + else + { + /* dest is NOT zip64, just copy it as-is */ + n = sizeof(mz_uint32) * (has_id ? 4 : 3); + } + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_src_file_ofs += n; + cur_dst_file_ofs += n; + } + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + + /* Finally, add the new central dir header */ + orig_central_dir_size = pState->m_central_dir.m_size; + + memcpy(new_central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + + if (pState->m_zip64) + { + /* This is the painful part: We need to write a new central dir header + ext block with updated zip64 fields, and ensure the old fields (if any) are not included. */ + const mz_uint8 *pSrc_ext = pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len; + mz_zip_array new_ext_block; + + mz_zip_array_init(&new_ext_block, sizeof(mz_uint8)); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_UINT32_MAX); + + if (!mz_zip_writer_update_zip64_extension_block(&new_ext_block, pZip, pSrc_ext, src_ext_len, &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, &local_dir_header_ofs, NULL)) + { + mz_zip_array_clear(pZip, &new_ext_block); + return MZ_FALSE; + } + + MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS, new_ext_block.m_size); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + { + mz_zip_array_clear(pZip, &new_ext_block); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_filename_len)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, new_ext_block.m_size)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len + src_ext_len, src_comment_len)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + mz_zip_array_clear(pZip, &new_ext_block); + } + else + { + /* sanity checks */ + if (cur_dst_file_ofs > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (local_dir_header_ofs >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_central_dir_following_data_size)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + } + + /* This shouldn't trigger unless we screwed up during the initial sanity checks */ + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + { + /* TODO: Support central dirs >= 32-bits in size */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + } + + n = (mz_uint32)orig_central_dir_size; + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pZip->m_total_files++; + pZip->m_archive_size = cur_dst_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_uint64 central_dir_ofs, central_dir_size; + mz_uint8 hdr[256]; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) + { + if ((pZip->m_total_files > MZ_UINT32_MAX) || (pState->m_central_dir.m_size >= MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if ((pZip->m_total_files > MZ_UINT16_MAX) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + central_dir_ofs = 0; + central_dir_size = 0; + if (pZip->m_total_files) + { + /* Write central directory */ + central_dir_ofs = pZip->m_archive_size; + central_dir_size = pState->m_central_dir.m_size; + pZip->m_central_directory_file_ofs = central_dir_ofs; + if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += central_dir_size; + } + + if (pState->m_zip64) + { + /* Write zip64 end of central directory header */ + mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size; + + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDH_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - sizeof(mz_uint32) - sizeof(mz_uint64)); + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS, 0x031E); /* TODO: always Unix */ + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS, 0x002D); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE; + + /* Write zip64 end of central directory locator */ + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS, rel_ofs_to_zip64_ecdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE; + } + + /* Write end of central directory record */ + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_size)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_ofs)); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + +#ifndef MINIZ_NO_STDIO + if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_archive_size += MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE; + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize) +{ + if ((!ppBuf) || (!pSize)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + *ppBuf = NULL; + *pSize = 0; + + if ((!pZip) || (!pZip->m_pState)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_pWrite != mz_zip_heap_write_func) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_finalize_archive(pZip)) + return MZ_FALSE; + + *ppBuf = pZip->m_pState->m_pMem; + *pSize = pZip->m_pState->m_mem_size; + pZip->m_pState->m_pMem = NULL; + pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_end(mz_zip_archive *pZip) +{ + return mz_zip_writer_end_internal(pZip, MZ_TRUE); +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + return mz_zip_add_mem_to_archive_file_in_place_v2(pZip_filename, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, NULL); +} + +mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr) +{ + mz_bool status, created_new_archive = MZ_FALSE; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + mz_zip_zero_struct(&zip_archive); + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_FILENAME; + return MZ_FALSE; + } + + /* Important: The regular non-64 bit version of stat() can fail here if the file is very large, which could cause the archive to be overwritten. */ + /* So be sure to compile with _LARGEFILE64_SOURCE 1 */ + if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) + { + /* Create a new archive. */ + if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, level_and_flags)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + created_new_archive = MZ_TRUE; + } + else + { + /* Append to an existing archive. */ + if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, level_and_flags)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + + mz_zip_reader_end_internal(&zip_archive, MZ_FALSE); + + return MZ_FALSE; + } + } + + status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); + actual_err = zip_archive.m_last_error; + + /* Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) */ + if (!mz_zip_writer_finalize_archive(&zip_archive)) + { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if (!mz_zip_writer_end_internal(&zip_archive, status)) + { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if ((!status) && (created_new_archive)) + { + /* It's a new archive and something went wrong, so just delete it. */ + int ignoredStatus = MZ_DELETE_FILE(pZip_filename); + (void)ignoredStatus; + } + + if (pErr) + *pErr = actual_err; + + return status; +} + +void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr) +{ + mz_uint32 file_index; + mz_zip_archive zip_archive; + void *p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!pArchive_name)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + + return NULL; + } + + mz_zip_zero_struct(&zip_archive); + if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + + return NULL; + } + + if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, &file_index)) + { + p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); + } + + mz_zip_reader_end_internal(&zip_archive, p != NULL); + + if (pErr) + *pErr = zip_archive.m_last_error; + + return p; +} + +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) +{ + return mz_zip_extract_archive_file_to_heap_v2(pZip_filename, pArchive_name, NULL, pSize, flags, NULL); +} + +#endif /* #ifndef MINIZ_NO_STDIO */ + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + +/* ------------------- Misc utils */ + +mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_zip_mode : MZ_ZIP_MODE_INVALID; +} + +mz_zip_type mz_zip_get_type(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_zip_type : MZ_ZIP_TYPE_INVALID; +} + +mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num) +{ + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = err_num; + return prev_err; +} + +mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip) +{ + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + return pZip->m_last_error; +} + +mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip) +{ + return mz_zip_set_last_error(pZip, MZ_ZIP_NO_ERROR); +} + +mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip) +{ + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = MZ_ZIP_NO_ERROR; + return prev_err; +} + +const char *mz_zip_get_error_string(mz_zip_error mz_err) +{ + switch (mz_err) + { + case MZ_ZIP_NO_ERROR: + return "no error"; + case MZ_ZIP_UNDEFINED_ERROR: + return "undefined error"; + case MZ_ZIP_TOO_MANY_FILES: + return "too many files"; + case MZ_ZIP_FILE_TOO_LARGE: + return "file too large"; + case MZ_ZIP_UNSUPPORTED_METHOD: + return "unsupported method"; + case MZ_ZIP_UNSUPPORTED_ENCRYPTION: + return "unsupported encryption"; + case MZ_ZIP_UNSUPPORTED_FEATURE: + return "unsupported feature"; + case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR: + return "failed finding central directory"; + case MZ_ZIP_NOT_AN_ARCHIVE: + return "not a ZIP archive"; + case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED: + return "invalid header or archive is corrupted"; + case MZ_ZIP_UNSUPPORTED_MULTIDISK: + return "unsupported multidisk archive"; + case MZ_ZIP_DECOMPRESSION_FAILED: + return "decompression failed or archive is corrupted"; + case MZ_ZIP_COMPRESSION_FAILED: + return "compression failed"; + case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE: + return "unexpected decompressed size"; + case MZ_ZIP_CRC_CHECK_FAILED: + return "CRC-32 check failed"; + case MZ_ZIP_UNSUPPORTED_CDIR_SIZE: + return "unsupported central directory size"; + case MZ_ZIP_ALLOC_FAILED: + return "allocation failed"; + case MZ_ZIP_FILE_OPEN_FAILED: + return "file open failed"; + case MZ_ZIP_FILE_CREATE_FAILED: + return "file create failed"; + case MZ_ZIP_FILE_WRITE_FAILED: + return "file write failed"; + case MZ_ZIP_FILE_READ_FAILED: + return "file read failed"; + case MZ_ZIP_FILE_CLOSE_FAILED: + return "file close failed"; + case MZ_ZIP_FILE_SEEK_FAILED: + return "file seek failed"; + case MZ_ZIP_FILE_STAT_FAILED: + return "file stat failed"; + case MZ_ZIP_INVALID_PARAMETER: + return "invalid parameter"; + case MZ_ZIP_INVALID_FILENAME: + return "invalid filename"; + case MZ_ZIP_BUF_TOO_SMALL: + return "buffer too small"; + case MZ_ZIP_INTERNAL_ERROR: + return "internal error"; + case MZ_ZIP_FILE_NOT_FOUND: + return "file not found"; + case MZ_ZIP_ARCHIVE_TOO_LARGE: + return "archive is too large"; + case MZ_ZIP_VALIDATION_FAILED: + return "validation failed"; + case MZ_ZIP_WRITE_CALLBACK_FAILED: + return "write calledback failed"; + default: + break; + } + + return "unknown error"; +} + +/* Note: Just because the archive is not zip64 doesn't necessarily mean it doesn't have Zip64 extended information extra field, argh. */ +mz_bool mz_zip_is_zip64(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return MZ_FALSE; + + return pZip->m_pState->m_zip64; +} + +size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + + return pZip->m_pState->m_central_dir.m_size; +} + +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_total_files : 0; +} + +mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip) +{ + if (!pZip) + return 0; + return pZip->m_archive_size; +} + +mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_file_archive_start_ofs; +} + +MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_pFile; +} + +size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n); +} + +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + if (filename_buf_size) + pFilename[0] = '\0'; + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return 0; + } + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_buf_size) + { + n = MZ_MIN(n, filename_buf_size - 1); + memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pFilename[n] = '\0'; + } + return n + 1; +} + +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) +{ + return mz_zip_file_stat_internal(pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL); +} + +mz_bool mz_zip_end(mz_zip_archive *pZip) +{ + if (!pZip) + return MZ_FALSE; + + if (pZip->m_zip_mode == MZ_ZIP_MODE_READING) + return mz_zip_reader_end(pZip); +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)) + return mz_zip_writer_end(pZip); +#endif + + return MZ_FALSE; +} + +#endif /*#ifndef MINIZ_NO_ARCHIVE_APIS*/ diff --git a/xs/src/miniz/miniz_zip.h b/xs/src/miniz/miniz_zip.h new file mode 100644 index 000000000..71ecb4ae2 --- /dev/null +++ b/xs/src/miniz/miniz_zip.h @@ -0,0 +1,429 @@ + +#pragma once +#include "miniz.h" + +/* ------------------- ZIP archive reading/writing */ + +#ifndef MINIZ_NO_ARCHIVE_APIS + +enum +{ + /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */ + MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 +}; + +typedef struct +{ + /* Central directory file index. */ + mz_uint32 m_file_index; + + /* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */ + mz_uint64 m_central_dir_ofs; + + /* These fields are copied directly from the zip's central dir. */ + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; + +#ifndef MINIZ_NO_TIME + MZ_TIME_T m_time; +#endif + + /* CRC-32 of uncompressed data. */ + mz_uint32 m_crc32; + + /* File's compressed size. */ + mz_uint64 m_comp_size; + + /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */ + mz_uint64 m_uncomp_size; + + /* Zip internal and external file attributes. */ + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + + /* Entry's local header file offset in bytes. */ + mz_uint64 m_local_header_ofs; + + /* Size of comment in bytes. */ + mz_uint32 m_comment_size; + + /* MZ_TRUE if the entry appears to be a directory. */ + mz_bool m_is_directory; + + /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */ + mz_bool m_is_encrypted; + + /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */ + mz_bool m_is_supported; + + /* Filename. If string ends in '/' it's a subdirectory entry. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + + /* Comment field. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; + +} mz_zip_archive_file_stat; + +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); +typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum { + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef enum { + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, + MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */ + MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */ + MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* always use the zip64 file format, instead of the original zip file format with automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */ + MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, + MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000 +} mz_zip_flags; + +typedef enum { + MZ_ZIP_TYPE_INVALID = 0, + MZ_ZIP_TYPE_USER, + MZ_ZIP_TYPE_MEMORY, + MZ_ZIP_TYPE_HEAP, + MZ_ZIP_TYPE_FILE, + MZ_ZIP_TYPE_CFILE, + MZ_ZIP_TOTAL_TYPES +} mz_zip_type; + +/* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */ +typedef enum { + MZ_ZIP_NO_ERROR = 0, + MZ_ZIP_UNDEFINED_ERROR, + MZ_ZIP_TOO_MANY_FILES, + MZ_ZIP_FILE_TOO_LARGE, + MZ_ZIP_UNSUPPORTED_METHOD, + MZ_ZIP_UNSUPPORTED_ENCRYPTION, + MZ_ZIP_UNSUPPORTED_FEATURE, + MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, + MZ_ZIP_NOT_AN_ARCHIVE, + MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, + MZ_ZIP_UNSUPPORTED_MULTIDISK, + MZ_ZIP_DECOMPRESSION_FAILED, + MZ_ZIP_COMPRESSION_FAILED, + MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, + MZ_ZIP_CRC_CHECK_FAILED, + MZ_ZIP_UNSUPPORTED_CDIR_SIZE, + MZ_ZIP_ALLOC_FAILED, + MZ_ZIP_FILE_OPEN_FAILED, + MZ_ZIP_FILE_CREATE_FAILED, + MZ_ZIP_FILE_WRITE_FAILED, + MZ_ZIP_FILE_READ_FAILED, + MZ_ZIP_FILE_CLOSE_FAILED, + MZ_ZIP_FILE_SEEK_FAILED, + MZ_ZIP_FILE_STAT_FAILED, + MZ_ZIP_INVALID_PARAMETER, + MZ_ZIP_INVALID_FILENAME, + MZ_ZIP_BUF_TOO_SMALL, + MZ_ZIP_INTERNAL_ERROR, + MZ_ZIP_FILE_NOT_FOUND, + MZ_ZIP_ARCHIVE_TOO_LARGE, + MZ_ZIP_VALIDATION_FAILED, + MZ_ZIP_WRITE_CALLBACK_FAILED, + MZ_ZIP_TOTAL_ERRORS +} mz_zip_error; + +typedef struct +{ + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + + /* We only support up to UINT32_MAX files in zip64 mode. */ + mz_uint32 m_total_files; + mz_zip_mode m_zip_mode; + mz_zip_type m_zip_type; + mz_zip_error m_last_error; + + mz_uint64 m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + mz_file_needs_keepalive m_pNeeds_keepalive; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + +} mz_zip_archive; + +typedef struct +{ + mz_zip_archive *pZip; + mz_uint flags; + + int status; +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + mz_uint file_crc32; +#endif + mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, out_buf_ofs, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + void *pWrite_buf; + + size_t out_blk_remain; + + tinfl_decompressor inflator; + +} mz_zip_reader_extract_iter_state; + +/* -------- ZIP reading */ + +/* Inits a ZIP archive reader. */ +/* These functions read and validate the archive's central directory. */ +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags); + +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +/* Read a archive from a disk file. */ +/* file_start_ofs is the file offset where the archive actually begins, or 0. */ +/* actual_archive_size is the true total size of the archive, which may be smaller than the file's actual size on disk. If zero the entire file is treated as the archive. */ +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size); + +/* Read an archive from an already opened FILE, beginning at the current file position. */ +/* The archive is assumed to be archive_size bytes long. If archive_size is < 0, then the entire rest of the file is assumed to contain the archive. */ +/* The FILE will NOT be closed when mz_zip_reader_end() is called. */ +mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags); +#endif + +/* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */ +mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + +/* -------- ZIP reading or writing */ + +/* Clears a mz_zip_archive struct to all zeros. */ +/* Important: This must be done before passing the struct to any mz_zip functions. */ +void mz_zip_zero_struct(mz_zip_archive *pZip); + +mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip); +mz_zip_type mz_zip_get_type(mz_zip_archive *pZip); + +/* Returns the total number of files in the archive. */ +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + +mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip); +mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip); +MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip); + +/* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */ +size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n); + +/* Attempts to locates a file in the archive's central directory. */ +/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ +/* Returns -1 if the file cannot be found. */ +int mz_zip_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); +/* Returns MZ_FALSE if the file cannot be found. */ +mz_bool mz_zip_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex); + +/* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions retrieve/manipulate this field. */ +/* Note that the m_last_error functionality is not thread safe. */ +mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num); +mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip); +mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip); +mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip); +const char *mz_zip_get_error_string(mz_zip_error mz_err); + +/* MZ_TRUE if the archive file entry is a directory entry. */ +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); + +/* MZ_TRUE if the file is encrypted/strong encrypted. */ +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + +/* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */ +mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index); + +/* Retrieves the filename of an archive file entry. */ +/* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */ +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + +/* Attempts to locates a file in the archive's central directory. */ +/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ +/* Returns -1 if the file cannot be found. */ +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); +int mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); + +/* Returns detailed information about an archive file entry. */ +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + +/* MZ_TRUE if the file is in zip64 format. */ +/* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it contained any zip64 extended file information fields in the central directory. */ +mz_bool mz_zip_is_zip64(mz_zip_archive *pZip); + +/* Returns the total central directory size in bytes. */ +/* The current max supported size is <= MZ_UINT32_MAX. */ +size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip); + +/* Extracts a archive file to a memory buffer using no memory allocation. */ +/* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */ +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + +/* Extracts a archive file to a memory buffer. */ +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + +/* Extracts a archive file to a dynamically allocated heap buffer. */ +/* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */ +/* Returns NULL and sets the last error on failure. */ +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + +/* Extracts a archive file using a callback function to output the file's data. */ +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + +/* Extract a file iteratively */ +mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); +mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); +size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size); +mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState); + +#ifndef MINIZ_NO_STDIO +/* Extracts a archive file to a disk file and sets its last accessed and modified times. */ +/* This function only extracts files, not archive directory records. */ +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); + +/* Extracts a archive file starting at the current position in the destination FILE stream. */ +mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags); +#endif + +#if 0 +/* TODO */ + typedef void *mz_zip_streaming_extract_state_ptr; + mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs); + size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); + mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); +#endif + +/* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */ +/* It also validates that each file can be successfully uncompressed unless the MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ +mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + +/* Validates an entire archive by calling mz_zip_validate_file() on each file. */ +mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags); + +/* Misc utils/helpers, valid for ZIP reading or writing */ +mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr); +mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr); + +/* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */ +mz_bool mz_zip_end(mz_zip_archive *pZip); + +/* -------- ZIP writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +/* Inits a ZIP archive writer. */ +/*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init or mz_zip_writer_init_v2*/ +/*The output is streamable, i.e. file_ofs in mz_file_write_func always increases only by n*/ +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); +mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags); + +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); +mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags); +mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags); +#endif + +/* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. */ +/* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. */ +/* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). */ +/* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. */ +/* Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before */ +/* the archive is finalized the file's central directory will be hosed. */ +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); +mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); + +/* Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. */ +/* To add a directory entry, call this method with an archive name ending in a forwardslash with an empty buffer. */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); + +/* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply the function with already compressed data. */ +/* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */ +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); + +#ifndef MINIZ_NO_STDIO +/* Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + +/* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */ +mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add, + const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); +#endif + +/* Adds a file to an archive by fully cloning the data from another archive. */ +/* This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data (it may add or modify the zip64 local header extra data field), and the optional descriptor following the compressed data. */ +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index); + +/* Finalizes the archive by writing the central directory records followed by the end of central directory record. */ +/* After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). */ +/* An archive must be manually finalized by calling this function for it to be valid. */ +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); + +/* Finalizes a heap archive, returning a poiner to the heap block and its size. */ +/* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */ +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize); + +/* Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. */ +/* Note for the archive to be valid, it *must* have been finalized before ending (this function will not do it for you). */ +mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + +/* -------- Misc. high-level helper functions: */ + +/* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. */ +/* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be left in a screwed up state (without a central directory). */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +/* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We could then truncate the file (so the old central dir would be at the end) if something goes wrong. */ +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr); + +/* Reads a single file from an archive into a heap block. */ +/* If pComment is not NULL, only the file with the specified comment will be extracted. */ +/* Returns NULL on failure. */ +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags); +void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr); + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + +#endif /* MINIZ_NO_ARCHIVE_APIS */ From 475f892413d888142dc098589fd7ae9f0ecec37f Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Tue, 30 Jan 2018 09:27:10 +0100 Subject: [PATCH 12/57] 3mf Importer - 1st installment --- lib/Slic3r/GUI.pm | 5 +- lib/Slic3r/GUI/MainFrame.pm | 2 +- lib/Slic3r/GUI/Plater.pm | 4 +- xs/CMakeLists.txt | 2 + xs/src/libslic3r/Format/3mf.cpp | 990 ++++++++++++++++++++++++++++++ xs/src/libslic3r/Format/3mf.hpp | 12 + xs/src/libslic3r/Model.cpp | 38 +- xs/src/libslic3r/Model.hpp | 2 + xs/src/libslic3r/TriangleMesh.cpp | 9 + xs/src/libslic3r/TriangleMesh.hpp | 1 + 10 files changed, 1058 insertions(+), 7 deletions(-) create mode 100644 xs/src/libslic3r/Format/3mf.cpp create mode 100644 xs/src/libslic3r/Format/3mf.hpp diff --git a/lib/Slic3r/GUI.pm b/lib/Slic3r/GUI.pm index 5d6d8e4a6..4063824e5 100644 --- a/lib/Slic3r/GUI.pm +++ b/lib/Slic3r/GUI.pm @@ -41,16 +41,17 @@ use Wx::Event qw(EVT_IDLE EVT_COMMAND EVT_MENU); use base 'Wx::App'; use constant FILE_WILDCARDS => { - known => 'Known files (*.stl, *.obj, *.amf, *.xml, *.prusa)|*.stl;*.STL;*.obj;*.OBJ;*.amf;*.AMF;*.xml;*.XML;*.prusa;*.PRUSA', + known => 'Known files (*.stl, *.obj, *.amf, *.xml, *.3mf, *.prusa)|*.stl;*.STL;*.obj;*.OBJ;*.amf;*.AMF;*.xml;*.XML;*.3mf;*.3MF;*.prusa;*.PRUSA', stl => 'STL files (*.stl)|*.stl;*.STL', obj => 'OBJ files (*.obj)|*.obj;*.OBJ', amf => 'AMF files (*.amf)|*.amf;*.AMF;*.xml;*.XML', + threemf => '3MF files (*.3mf)|*.3mf;*.3MF', prusa => 'Prusa Control files (*.prusa)|*.prusa;*.PRUSA', ini => 'INI files *.ini|*.ini;*.INI', gcode => 'G-code files (*.gcode, *.gco, *.g, *.ngc)|*.gcode;*.GCODE;*.gco;*.GCO;*.g;*.G;*.ngc;*.NGC', svg => 'SVG files *.svg|*.svg;*.SVG', }; -use constant MODEL_WILDCARD => join '|', @{&FILE_WILDCARDS}{qw(known stl obj amf prusa)}; +use constant MODEL_WILDCARD => join '|', @{&FILE_WILDCARDS}{qw(known stl obj amf threemf prusa)}; # Datadir provided on the command line. our $datadir; diff --git a/lib/Slic3r/GUI/MainFrame.pm b/lib/Slic3r/GUI/MainFrame.pm index c91c59ea7..3b82ee157 100644 --- a/lib/Slic3r/GUI/MainFrame.pm +++ b/lib/Slic3r/GUI/MainFrame.pm @@ -374,7 +374,7 @@ sub quick_slice { # select input file my $input_file; if (!$params{reslice}) { - my $dialog = Wx::FileDialog->new($self, 'Choose a file to slice (STL/OBJ/AMF/PRUSA):', + my $dialog = Wx::FileDialog->new($self, 'Choose a file to slice (STL/OBJ/AMF/3MF/PRUSA):', wxTheApp->{app_config}->get_last_dir, "", &Slic3r::GUI::MODEL_WILDCARD, wxFD_OPEN | wxFD_FILE_MUST_EXIST); if ($dialog->ShowModal != wxID_OK) { diff --git a/lib/Slic3r/GUI/Plater.pm b/lib/Slic3r/GUI/Plater.pm index 10d65475c..a5a98d649 100644 --- a/lib/Slic3r/GUI/Plater.pm +++ b/lib/Slic3r/GUI/Plater.pm @@ -2063,8 +2063,8 @@ sub OnDropFiles { # stop scalars leaking on older perl # https://rt.perl.org/rt3/Public/Bug/Display.html?id=70602 @_ = (); - # only accept STL, OBJ and AMF files - return 0 if grep !/\.(?:[sS][tT][lL]|[oO][bB][jJ]|[aA][mM][fF](?:\.[xX][mM][lL])?|[pP][rR][uU][sS][aA])$/, @$filenames; + # only accept STL, OBJ, AMF and 3MF files + return 0 if grep !/\.(?:[sS][tT][lL]|[oO][bB][jJ]|[aA][mM][fF]|[3][mM][fF](?:\.[xX][mM][lL])?|[pP][rR][uU][sS][aA])$/, @$filenames; $self->{window}->load_files($filenames); } diff --git a/xs/CMakeLists.txt b/xs/CMakeLists.txt index 4c1f2bb8c..fbddc31e6 100644 --- a/xs/CMakeLists.txt +++ b/xs/CMakeLists.txt @@ -74,6 +74,8 @@ add_library(libslic3r STATIC ${LIBDIR}/libslic3r/Fill/FillRectilinear3.hpp ${LIBDIR}/libslic3r/Flow.cpp ${LIBDIR}/libslic3r/Flow.hpp + ${LIBDIR}/libslic3r/Format/3MF.cpp + ${LIBDIR}/libslic3r/Format/3MF.hpp ${LIBDIR}/libslic3r/Format/AMF.cpp ${LIBDIR}/libslic3r/Format/AMF.hpp ${LIBDIR}/libslic3r/Format/OBJ.cpp diff --git a/xs/src/libslic3r/Format/3mf.cpp b/xs/src/libslic3r/Format/3mf.cpp new file mode 100644 index 000000000..6057e1c11 --- /dev/null +++ b/xs/src/libslic3r/Format/3mf.cpp @@ -0,0 +1,990 @@ +#include "../libslic3r.h" +#include "../Model.hpp" + +#include "3mf.hpp" + +#include +#include + +#include +#include +#include + +const std::string MODEL_FOLDER = "3d\\"; +const std::string MODEL_EXTENSION = ".model"; + +const char* MODEL_TAG = "model"; +const char* RESOURCES_TAG = "resources"; +const char* OBJECT_TAG = "object"; +const char* MESH_TAG = "mesh"; +const char* VERTICES_TAG = "vertices"; +const char* VERTEX_TAG = "vertex"; +const char* TRIANGLES_TAG = "triangles"; +const char* TRIANGLE_TAG = "triangle"; +const char* COMPONENTS_TAG = "components"; +const char* COMPONENT_TAG = "component"; +const char* BUILD_TAG = "build"; +const char* ITEM_TAG = "item"; + +const char* UNIT_ATTR = "unit"; +const char* NAME_ATTR = "name"; +const char* TYPE_ATTR = "type"; +const char* ID_ATTR = "id"; +const char* X_ATTR = "x"; +const char* Y_ATTR = "y"; +const char* Z_ATTR = "z"; +const char* V1_ATTR = "v1"; +const char* V2_ATTR = "v2"; +const char* V3_ATTR = "v3"; +const char* OBJECTID_ATTR = "objectid"; +const char* TRANSFORM_ATTR = "transform"; + +const unsigned int VALID_OBJECT_TYPES_COUNT = 1; +const char* VALID_OBJECT_TYPES[] = +{ + "model" +}; + +const unsigned int INVALID_OBJECT_TYPES_COUNT = 4; +const char* INVALID_OBJECT_TYPES[] = +{ + "solidsupport", + "support", + "surface", + "other" +}; + +typedef Eigen::Matrix Matrix4x4; + +const char* get_attribute_value_charptr(const char** attributes, unsigned int attributes_size, const char* attribute_key) +{ + if ((attributes == nullptr) || (attributes_size == 0) || (attributes_size % 2 != 0) || (attribute_key == nullptr)) + return nullptr; + + for (unsigned int a = 0; a < attributes_size; a += 2) + { + if (::strcmp(attributes[a], attribute_key) == 0) + return attributes[a + 1]; + } + + return nullptr; +} + +std::string get_attribute_value_string(const char** attributes, unsigned int attributes_size, const char* attribute_key) +{ + const char* text = get_attribute_value_charptr(attributes, attributes_size, attribute_key); + return (text != nullptr) ? text : ""; +} + +float get_attribute_value_float(const char** attributes, unsigned int attributes_size, const char* attribute_key) +{ + const char* text = get_attribute_value_charptr(attributes, attributes_size, attribute_key); + return (text != nullptr) ? (float)::atof(text) : 0.0f; +} + +int get_attribute_value_int(const char** attributes, unsigned int attributes_size, const char* attribute_key) +{ + const char* text = get_attribute_value_charptr(attributes, attributes_size, attribute_key); + return (text != nullptr) ? ::atoi(text) : 0; +} + +Matrix4x4 get_matrix_from_string(const std::string& mat_str) +{ + if (mat_str.empty()) + // empty string means default identity matrix + return Matrix4x4::Identity(); + + std::vector mat_elements_str; + boost::split(mat_elements_str, mat_str, boost::is_any_of(" "), boost::token_compress_on); + + unsigned int size = (unsigned int)mat_elements_str.size(); + if (size != 12) + // invalid data, return identity matrix + return Matrix4x4::Identity(); + + Matrix4x4 ret = Matrix4x4::Identity(); + unsigned int i = 0; + // matrices are stored into 3mf files as 4x3 + // we need to transpose them + for (unsigned int c = 0; c < 4; ++c) + { + for (unsigned int r = 0; r < 3; ++r) + { + ret(r, c) = (float)::atof(mat_elements_str[i++].c_str()); + } + } + return ret; +} + +float get_unit_factor(const std::string& unit) +{ + const char* text = unit.c_str(); + + if (::strcmp(text, "micron") == 0) + return 0.001f; + else if (::strcmp(text, "centimeter") == 0) + return 10.0f; + else if (::strcmp(text, "inch") == 0) + return 25.4f; + else if (::strcmp(text, "foot") == 0) + return 304.8f; + else if (::strcmp(text, "meter") == 0) + return 1000.0f; + else + // default "millimeters" (see specification) + return 1.0f; +} + +bool is_valid_object_type(const std::string& type) +{ + // if the type is empty defaults to "model" (see specification) + if (type.empty()) + return true; + + for (unsigned int i = 0; i < VALID_OBJECT_TYPES_COUNT; ++i) + { + if (::strcmp(type.c_str(), VALID_OBJECT_TYPES[i]) == 0) + return true; + } + + return false; +} + +namespace Slic3r { + + class _3MF_Importer + { + struct Component + { + int object_id; + Matrix4x4 matrix; + + explicit Component(int object_id); + Component(int object_id, const Matrix4x4& matrix); + }; + + typedef std::vector ComponentsList; + + struct CurrentObject + { + struct Geometry + { + std::vector vertices; + std::vector triangles; + + bool empty(); + void reset(); + }; + + int id; + Geometry geometry; + ModelObject* object; + TriangleMesh mesh; + ComponentsList components; + + CurrentObject(); + + void reset(); + }; + + struct Instance + { + ModelInstance* instance; + Matrix4x4 matrix; + + Instance(ModelInstance* instance, const Matrix4x4& matrix); + }; + + typedef std::map IdToModelObjectMap; + typedef std::map IdToAliasesMap; + typedef std::vector InstancesList; + + XML_Parser m_xml_parser; + Model* m_model; + float m_unit_factor; + CurrentObject m_curr_object; + IdToModelObjectMap m_objects; + IdToAliasesMap m_objects_aliases; + InstancesList m_instances; + std::vector m_errors; + + public: + _3MF_Importer(); + ~_3MF_Importer(); + + bool load_model_from_file(const std::string& filename, Model& model); + + const std::vector& get_errors() const; + + private: + void _destroy_xml_parser(); + void _stop_xml_parser(); + + bool _load_model_from_file_miniz(const std::string& filename, Model& model); + bool _extract_model_from_archive_miniz(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat); + + void _handle_start_xml_element(const char* name, const char** attributes); + void _handle_end_xml_element(const char* name); + + bool _handle_start_model(const char** attributes, unsigned int num_attributes); + bool _handle_end_model(); + + bool _handle_start_resources(const char** attributes, unsigned int num_attributes); + bool _handle_end_resources(); + + bool _handle_start_object(const char** attributes, unsigned int num_attributes); + bool _handle_end_object(); + + bool _handle_start_mesh(const char** attributes, unsigned int num_attributes); + bool _handle_end_mesh(); + + bool _handle_start_vertices(const char** attributes, unsigned int num_attributes); + bool _handle_end_vertices(); + + bool _handle_start_vertex(const char** attributes, unsigned int num_attributes); + bool _handle_end_vertex(); + + bool _handle_start_triangles(const char** attributes, unsigned int num_attributes); + bool _handle_end_triangles(); + + bool _handle_start_triangle(const char** attributes, unsigned int num_attributes); + bool _handle_end_triangle(); + + bool _handle_start_components(const char** attributes, unsigned int num_attributes); + bool _handle_end_components(); + + bool _handle_start_component(const char** attributes, unsigned int num_attributes); + bool _handle_end_component(); + + bool _handle_start_build(const char** attributes, unsigned int num_attributes); + bool _handle_end_build(); + + bool _handle_start_item(const char** attributes, unsigned int num_attributes); + bool _handle_end_item(); + + bool _create_object_instance(int object_id, const Matrix4x4& matrix, unsigned int recur_counter); + + void _apply_transform(ModelObject& object, const Matrix4x4& matrix); + void _apply_transform(ModelInstance& instance, const Matrix4x4& matrix); + + static void XMLCALL _handle_start_xml_element(void* userData, const char* name, const char** attributes); + static void XMLCALL _handle_end_xml_element(void* userData, const char* name); + }; + + _3MF_Importer::Component::Component(int object_id) + : object_id(object_id) + , matrix(Matrix4x4::Identity()) + { + } + + _3MF_Importer::Component::Component(int object_id, const Matrix4x4& matrix) + : object_id(object_id) + , matrix(matrix) + { + } + + bool _3MF_Importer::CurrentObject::Geometry::empty() + { + return vertices.empty() || triangles.empty(); + } + + void _3MF_Importer::CurrentObject::Geometry::reset() + { + vertices.clear(); + triangles.clear(); + } + + _3MF_Importer::CurrentObject::CurrentObject() + { + reset(); + } + + void _3MF_Importer::CurrentObject::reset() + { + id = -1; + geometry.reset(); + object = nullptr; + mesh = TriangleMesh(); + components.clear(); + } + + _3MF_Importer::Instance::Instance(ModelInstance* instance, const Matrix4x4& matrix) + : instance(instance) + , matrix(matrix) + { + } + + _3MF_Importer::_3MF_Importer() + : m_xml_parser(nullptr) + , m_model(nullptr) + , m_unit_factor(1.0f) + { + } + + _3MF_Importer::~_3MF_Importer() + { + _destroy_xml_parser(); + } + + bool _3MF_Importer::load_model_from_file(const std::string& filename, Model& model) + { + m_model = &model; + m_unit_factor = 1.0f; + m_curr_object.reset(); + m_objects.clear(); + m_objects_aliases.clear(); + m_instances.clear(); + m_errors.clear(); + + return _load_model_from_file_miniz(filename, model); + } + + const std::vector& _3MF_Importer::get_errors() const + { + return m_errors; + } + + void _3MF_Importer::_destroy_xml_parser() + { + if (m_xml_parser != nullptr) + { + XML_ParserFree(m_xml_parser); + m_xml_parser = nullptr; + } + } + + void _3MF_Importer::_stop_xml_parser() + { + if (m_xml_parser != nullptr) + XML_StopParser(m_xml_parser, false); + } + + bool _3MF_Importer::_load_model_from_file_miniz(const std::string& filename, Model& model) + { + mz_zip_archive archive; + mz_zip_zero_struct(&archive); + + mz_bool res = mz_zip_reader_init_file(&archive, filename.c_str(), 0); + if (res == 0) + { + m_errors.push_back("Unable to open the file"); + return false; + } + + mz_uint num_entries = mz_zip_reader_get_num_files(&archive); + + mz_zip_archive_file_stat stat; + for (mz_uint i = 0; i < num_entries; ++i) + { + if (mz_zip_reader_file_stat(&archive, i, &stat)) + { + std::string name(stat.m_filename); + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) -> unsigned char { return std::tolower(c); }); + std::replace(name.begin(), name.end(), '/', '\\'); + + if ((name.find(MODEL_FOLDER) == 0) && (name.rfind(MODEL_EXTENSION) == name.length() - MODEL_EXTENSION.length())) + { + if (!_extract_model_from_archive_miniz(archive, stat)) + { + mz_zip_reader_end(&archive); + m_errors.push_back("Archive does not contain a valid model"); + return false; + } + } + } + } + + mz_zip_reader_end(&archive); + return true; + } + + bool _3MF_Importer::_extract_model_from_archive_miniz(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat) + { + _destroy_xml_parser(); + + m_xml_parser = XML_ParserCreate(nullptr); + if (m_xml_parser == nullptr) + { + m_errors.push_back("Unable to create parser"); + return false; + } + + XML_SetUserData(m_xml_parser, (void*)this); + XML_SetElementHandler(m_xml_parser, _3MF_Importer::_handle_start_xml_element, _3MF_Importer::_handle_end_xml_element); + + void* parser_buffer = XML_GetBuffer(m_xml_parser, (int)stat.m_uncomp_size); + if (parser_buffer == nullptr) + { + m_errors.push_back("Unable to create buffer"); + return false; + } + + mz_bool res = mz_zip_reader_extract_file_to_mem(&archive, stat.m_filename, parser_buffer, (size_t)stat.m_uncomp_size, 0); + if (res == 0) + { + m_errors.push_back("Error while reading data to buffer"); + return false; + } + + if (!XML_ParseBuffer(m_xml_parser, (int)stat.m_uncomp_size, 1)) + { + char error_buf[1024]; + ::sprintf(error_buf, "Error (%s) while parsing xml file at line %d", XML_ErrorString(XML_GetErrorCode(m_xml_parser)), XML_GetCurrentLineNumber(m_xml_parser)); + m_errors.push_back(error_buf); + return false; + } + + return true; + } + + void _3MF_Importer::_handle_start_xml_element(const char* name, const char** attributes) + { + if (m_xml_parser == nullptr) + return; + + bool res = true; + unsigned int num_attributes = (unsigned int)XML_GetSpecifiedAttributeCount(m_xml_parser); + + if (::strcmp(MODEL_TAG, name) == 0) + res = _handle_start_model(attributes, num_attributes); + else if (::strcmp(RESOURCES_TAG, name) == 0) + res = _handle_start_resources(attributes, num_attributes); + else if (::strcmp(OBJECT_TAG, name) == 0) + res = _handle_start_object(attributes, num_attributes); + else if (::strcmp(MESH_TAG, name) == 0) + res = _handle_start_mesh(attributes, num_attributes); + else if (::strcmp(VERTICES_TAG, name) == 0) + res = _handle_start_vertices(attributes, num_attributes); + else if (::strcmp(VERTEX_TAG, name) == 0) + res = _handle_start_vertex(attributes, num_attributes); + else if (::strcmp(TRIANGLES_TAG, name) == 0) + res = _handle_start_triangles(attributes, num_attributes); + else if (::strcmp(TRIANGLE_TAG, name) == 0) + res = _handle_start_triangle(attributes, num_attributes); + else if (::strcmp(COMPONENTS_TAG, name) == 0) + res = _handle_start_components(attributes, num_attributes); + else if (::strcmp(COMPONENT_TAG, name) == 0) + res = _handle_start_component(attributes, num_attributes); + else if (::strcmp(BUILD_TAG, name) == 0) + res = _handle_start_build(attributes, num_attributes); + else if (::strcmp(ITEM_TAG, name) == 0) + res = _handle_start_item(attributes, num_attributes); + + if (!res) + _stop_xml_parser(); + } + + void _3MF_Importer::_handle_end_xml_element(const char* name) + { + if (m_xml_parser == nullptr) + return; + + bool res = true; + + if (::strcmp(MODEL_TAG, name) == 0) + res = _handle_end_model(); + else if (::strcmp(RESOURCES_TAG, name) == 0) + res = _handle_end_resources(); + else if (::strcmp(OBJECT_TAG, name) == 0) + res = _handle_end_object(); + else if (::strcmp(MESH_TAG, name) == 0) + res = _handle_end_mesh(); + else if (::strcmp(VERTICES_TAG, name) == 0) + res = _handle_end_vertices(); + else if (::strcmp(VERTEX_TAG, name) == 0) + res = _handle_end_vertex(); + else if (::strcmp(TRIANGLES_TAG, name) == 0) + res = _handle_end_triangles(); + else if (::strcmp(TRIANGLE_TAG, name) == 0) + res = _handle_end_triangle(); + else if (::strcmp(COMPONENTS_TAG, name) == 0) + res = _handle_end_components(); + else if (::strcmp(COMPONENT_TAG, name) == 0) + res = _handle_end_component(); + else if (::strcmp(BUILD_TAG, name) == 0) + res = _handle_end_build(); + else if (::strcmp(ITEM_TAG, name) == 0) + res = _handle_end_item(); + + if (!res) + _stop_xml_parser(); + } + + bool _3MF_Importer::_handle_start_model(const char** attributes, unsigned int num_attributes) + { + m_unit_factor = get_unit_factor(get_attribute_value_string(attributes, num_attributes, UNIT_ATTR)); + return true; + } + + bool _3MF_Importer::_handle_end_model() + { + // deletes all non-built or non-instanced objects + for (const IdToModelObjectMap::value_type& object : m_objects) + { + if ((object.second != nullptr) && (object.second->instances.size() == 0)) + m_model->delete_object(object.second); + } + + // applies instances' matrices + for (Instance& instance : m_instances) + { + if (instance.instance != nullptr) + { + ModelObject* object = instance.instance->get_object(); + if (object != nullptr) + { + if (object->instances.size() == 1) + { + // single instance -> apply the matrix to object geometry + _apply_transform(*object, instance.matrix); + } + else + { + // multiple instances -> apply the matrix to the instance + _apply_transform(*instance.instance, instance.matrix); + } + } + } + } + + return true; + } + + bool _3MF_Importer::_handle_start_resources(const char** attributes, unsigned int num_attributes) + { + // do nothing + return true; + } + + bool _3MF_Importer::_handle_end_resources() + { + // do nothing + return true; + } + + bool _3MF_Importer::_handle_start_object(const char** attributes, unsigned int num_attributes) + { + // reset current data + m_curr_object.reset(); + + if (is_valid_object_type(get_attribute_value_string(attributes, num_attributes, TYPE_ATTR))) + { + // create new object (it may be removed later if no instances are generated from it) + m_curr_object.object = m_model->add_object(); + if (m_curr_object.object == nullptr) + { + m_errors.push_back("Unable to create object"); + return false; + } + + // set object data + m_curr_object.object->name = get_attribute_value_string(attributes, num_attributes, NAME_ATTR); + m_curr_object.id = get_attribute_value_int(attributes, num_attributes, ID_ATTR); + } + + return true; + } + + bool _3MF_Importer::_handle_end_object() + { + if (m_curr_object.object != nullptr) + { + if (m_curr_object.geometry.empty()) + { + // no geometry defined + // remove the object from the model + m_model->delete_object(m_curr_object.object); + + if (m_curr_object.components.empty()) + { + // no components defined -> invalid object, delete it + IdToModelObjectMap::iterator object_item = m_objects.find(m_curr_object.id); + if (object_item != m_objects.end()) + m_objects.erase(object_item); + + IdToAliasesMap::iterator alias_item = m_objects_aliases.find(m_curr_object.id); + if (alias_item != m_objects_aliases.end()) + m_objects_aliases.erase(alias_item); + } + else + // adds components to aliases + m_objects_aliases.insert(IdToAliasesMap::value_type(m_curr_object.id, m_curr_object.components)); + } + else + { + // geometry defined, add it to the object + + ModelVolume* volume = m_curr_object.object->add_volume(m_curr_object.mesh); + if (volume == nullptr) + { + m_errors.push_back("Unable to add volume"); + return false; + } + + stl_file& stl = volume->mesh.stl; + stl.stats.type = inmemory; + stl.stats.number_of_facets = (uint32_t)m_curr_object.geometry.triangles.size() / 3; + stl.stats.original_num_facets = (int)stl.stats.number_of_facets; + stl_allocate(&stl); + for (size_t i = 0; i < m_curr_object.geometry.triangles.size(); /*nothing*/) + { + stl_facet& facet = stl.facet_start[i / 3]; + for (unsigned int v = 0; v < 3; ++v) + { + ::memcpy((void*)&facet.vertex[v].x, (const void*)&m_curr_object.geometry.vertices[m_curr_object.geometry.triangles[i++] * 3], 3 * sizeof(float)); + } + } + stl_get_size(&stl); + volume->mesh.repair(); + + // stores the object for later use + if (m_objects.find(m_curr_object.id) == m_objects.end()) + { + m_objects.insert(IdToModelObjectMap::value_type(m_curr_object.id, m_curr_object.object)); + m_objects_aliases.insert(IdToAliasesMap::value_type(m_curr_object.id, ComponentsList(1, Component(m_curr_object.id)))); // aliases itself + } + else + { + m_errors.push_back("Found object with duplicate id"); + return false; + } + } + } + + return true; + } + + bool _3MF_Importer::_handle_start_mesh(const char** attributes, unsigned int num_attributes) + { + // reset current geometry + m_curr_object.geometry.reset(); + return true; + } + + bool _3MF_Importer::_handle_end_mesh() + { + // do nothing + return true; + } + + bool _3MF_Importer::_handle_start_vertices(const char** attributes, unsigned int num_attributes) + { + // reset current vertices + m_curr_object.geometry.vertices.clear(); + return true; + } + + bool _3MF_Importer::_handle_end_vertices() + { + // do nothing + return true; + } + + bool _3MF_Importer::_handle_start_vertex(const char** attributes, unsigned int num_attributes) + { + // appends the vertex coordinates + // missing values are set equal to ZERO + m_curr_object.geometry.vertices.push_back(m_unit_factor * get_attribute_value_float(attributes, num_attributes, X_ATTR)); + m_curr_object.geometry.vertices.push_back(m_unit_factor * get_attribute_value_float(attributes, num_attributes, Y_ATTR)); + m_curr_object.geometry.vertices.push_back(m_unit_factor * get_attribute_value_float(attributes, num_attributes, Z_ATTR)); + return true; + } + + bool _3MF_Importer::_handle_end_vertex() + { + // do nothing + return true; + } + + bool _3MF_Importer::_handle_start_triangles(const char** attributes, unsigned int num_attributes) + { + // reset current triangles + m_curr_object.geometry.triangles.clear(); + return true; + } + + bool _3MF_Importer::_handle_end_triangles() + { + // do nothing + return true; + } + + bool _3MF_Importer::_handle_start_triangle(const char** attributes, unsigned int num_attributes) + { + // we are ignoring the following attributes: + // p1 + // p2 + // p3 + // pid + // see specifications + + // appends the triangle's vertices indices + // missing values are set equal to ZERO + m_curr_object.geometry.triangles.push_back((unsigned int)get_attribute_value_int(attributes, num_attributes, V1_ATTR)); + m_curr_object.geometry.triangles.push_back((unsigned int)get_attribute_value_int(attributes, num_attributes, V2_ATTR)); + m_curr_object.geometry.triangles.push_back((unsigned int)get_attribute_value_int(attributes, num_attributes, V3_ATTR)); + return true; + } + + bool _3MF_Importer::_handle_end_triangle() + { + // do nothing + return true; + } + + bool _3MF_Importer::_handle_start_components(const char** attributes, unsigned int num_attributes) + { + // reset current components + m_curr_object.components.clear(); + return true; + } + + bool _3MF_Importer::_handle_end_components() + { + // do nothing + return true; + } + + bool _3MF_Importer::_handle_start_component(const char** attributes, unsigned int num_attributes) + { + int object_id = get_attribute_value_int(attributes, num_attributes, OBJECTID_ATTR); + Matrix4x4 matrix = get_matrix_from_string(get_attribute_value_string(attributes, num_attributes, TRANSFORM_ATTR)); + + IdToModelObjectMap::iterator object_item = m_objects.find(object_id); + if (object_item == m_objects.end()) + { + IdToAliasesMap::iterator alias_item = m_objects_aliases.find(object_id); + if (alias_item == m_objects_aliases.end()) + { + m_errors.push_back("Found component with invalid object id"); + return false; + } + } + + m_curr_object.components.emplace_back(object_id, matrix); + + return true; + } + + bool _3MF_Importer::_handle_end_component() + { + // do nothing + return true; + } + + bool _3MF_Importer::_handle_start_build(const char** attributes, unsigned int num_attributes) + { + // do nothing + return true; + } + + bool _3MF_Importer::_handle_end_build() + { + // do nothing + return true; + } + + bool _3MF_Importer::_handle_start_item(const char** attributes, unsigned int num_attributes) + { + // we are ignoring the following attributes + // thumbnail + // partnumber + // pid + // pindex + // see specifications + + int object_id = get_attribute_value_int(attributes, num_attributes, OBJECTID_ATTR); + Matrix4x4 matrix = get_matrix_from_string(get_attribute_value_string(attributes, num_attributes, TRANSFORM_ATTR)); + + return _create_object_instance(object_id, matrix, 1); + } + + bool _3MF_Importer::_handle_end_item() + { + // do nothing + return true; + } + + bool _3MF_Importer::_create_object_instance(int object_id, const Matrix4x4& matrix, unsigned int recur_counter) + { + static const unsigned int MAX_RECURSIONS = 10; + + // escape from circular aliasing + if (recur_counter > MAX_RECURSIONS) + { + m_errors.push_back("Too many recursions"); + return false; + } + + IdToAliasesMap::iterator it = m_objects_aliases.find(object_id); + if (it == m_objects_aliases.end()) + { + m_errors.push_back("Found item with invalid object id"); + return false; + } + + if ((it->second.size() == 1) && (it->second[0].object_id == object_id)) + { + // aliasing to itself + + IdToModelObjectMap::iterator object_item = m_objects.find(object_id); + if ((object_item == m_objects.end()) || (object_item->second == nullptr)) + { + m_errors.push_back("Found invalid object"); + return false; + } + else + { + ModelInstance* instance = object_item->second->add_instance(); + if (instance == nullptr) + { + m_errors.push_back("Unable to add object instance"); + return false; + } + + m_instances.emplace_back(instance, matrix); + } + } + else + { + // recursively process nested components + for (const Component& component : it->second) + { + if (!_create_object_instance(component.object_id, matrix * component.matrix, recur_counter + 1)) + return false; + } + } + + return true; + } + + void _3MF_Importer::_apply_transform(ModelObject& object, const Matrix4x4& matrix) + { + float matrix3x4[12] = { matrix(0, 0), matrix(0, 1), matrix(0, 2), matrix(0, 3), + matrix(1, 0), matrix(1, 1), matrix(1, 2), matrix(1, 3), + matrix(2, 0), matrix(2, 1), matrix(2, 2), matrix(2, 3) }; + + object.transform(matrix3x4); + } + + void _3MF_Importer::_apply_transform(ModelInstance& instance, const Matrix4x4& matrix) + { + // slic3r ModelInstance cannot be transformed using a matrix + // we extract from the given matrix only the values currently used + + // translation + double offset_x = (double)matrix(0, 3); + double offset_y = (double)matrix(1, 3); + double offset_z = (double)matrix(2, 3); + + // scale + double sx = ::sqrt(sqr((double)matrix(0, 0)) + sqr((double)matrix(1, 0)) + sqr((double)matrix(2, 0))); + double sy = ::sqrt(sqr((double)matrix(0, 1)) + sqr((double)matrix(1, 1)) + sqr((double)matrix(2, 1))); + double sz = ::sqrt(sqr((double)matrix(0, 2)) + sqr((double)matrix(1, 2)) + sqr((double)matrix(2, 2))); + + // invalid scale value, return + if ((sx == 0.0) || (sy == 0.0) || (sz == 0.0)) + return; + + // non-uniform scale value, return + if ((std::abs(sx - sy) > 0.00001) || (std::abs(sx - sz) > 0.00001)) + return; + + // rotations (extracted using quaternion) + double inv_sx = 1.0 / sx; + double inv_sy = 1.0 / sy; + double inv_sz = 1.0 / sz; + + Eigen::Matrix m3x3; + m3x3 << (double)matrix(0, 0) * inv_sx, (double)matrix(0, 1) * inv_sy, (double)matrix(0, 2) * inv_sz, + (double)matrix(1, 0) * inv_sx, (double)matrix(1, 1) * inv_sy, (double)matrix(1, 2) * inv_sz, + (double)matrix(2, 0) * inv_sx, (double)matrix(2, 1) * inv_sy, (double)matrix(2, 2) * inv_sz; + + double qw = 0.5 * ::sqrt(std::max(0.0, 1.0 + m3x3(0, 0) + m3x3(1, 1) + m3x3(2, 2))); + double qx = 0.5 * ::sqrt(std::max(0.0, 1.0 + m3x3(0, 0) - m3x3(1, 1) - m3x3(2, 2))); + double qy = 0.5 * ::sqrt(std::max(0.0, 1.0 - m3x3(0, 0) + m3x3(1, 1) - m3x3(2, 2))); + double qz = 0.5 * ::sqrt(std::max(0.0, 1.0 - m3x3(0, 0) - m3x3(1, 1) + m3x3(2, 2))); + + double q_magnitude = ::sqrt(sqr(qw) + sqr(qx) + sqr(qy) + sqr(qz)); + + // invalid length, return + if (q_magnitude == 0.0) + return; + + double inv_q_magnitude = 1.0 / q_magnitude; + + qw *= inv_q_magnitude; + qx *= inv_q_magnitude; + qy *= inv_q_magnitude; + qz *= inv_q_magnitude; + + double test = qx * qy + qz * qw; + double angle_x, angle_y, angle_z; + + if (test > 0.499) + { + // singularity at north pole + angle_x = 0.0; + angle_y = 2.0 * ::atan2(qx, qw); + angle_z = 0.5 * PI; + } + else if (test < -0.499) + { + // singularity at south pole + angle_x = 0.0; + angle_y = -2.0 * ::atan2(qx, qw); + angle_z = -0.5 * PI; + } + else + { + angle_x = ::atan2(2.0 * qx * qw - 2.0 * qy * qz, 1.0 - 2.0 * sqr(qx) - 2.0 * sqr(qz)); + angle_y = ::atan2(2.0 * qy * qw - 2.0 * qx * qz, 1.0 - 2.0 * sqr(qy) - 2.0 * sqr(qz)); + angle_z = ::asin(2.0 * qx * qy + 2.0 * qz * qw); + + if (angle_x < 0.0) + angle_x += 2.0 * PI; + + if (angle_y < 0.0) + angle_y += 2.0 * PI; + + if (angle_z < 0.0) + angle_z += 2.0 * PI; + } + + instance.offset.x = offset_x; + instance.offset.y = offset_y; + instance.scaling_factor = sx; + instance.rotation = angle_z; + } + + void XMLCALL _3MF_Importer::_handle_start_xml_element(void* userData, const char* name, const char** attributes) + { + _3MF_Importer* importer = (_3MF_Importer*)userData; + if (importer != nullptr) + importer->_handle_start_xml_element(name, attributes); + } + + void XMLCALL _3MF_Importer::_handle_end_xml_element(void* userData, const char* name) + { + _3MF_Importer* importer = (_3MF_Importer*)userData; + if (importer != nullptr) + importer->_handle_end_xml_element(name); + } + + bool load_3mf(const char* path, Model* model, const char* object_name) + { + if ((path == nullptr) || (model == nullptr)) + return false; + + _3MF_Importer importer; + bool res = importer.load_model_from_file(path, *model); + + if (!res) + { + const std::vector& errors = importer.get_errors(); + int a = 0; + } + + return res; + } +} // namespace Slic3r diff --git a/xs/src/libslic3r/Format/3mf.hpp b/xs/src/libslic3r/Format/3mf.hpp new file mode 100644 index 000000000..11eb4c388 --- /dev/null +++ b/xs/src/libslic3r/Format/3mf.hpp @@ -0,0 +1,12 @@ +#ifndef slic3r_Format_3mf_hpp_ +#define slic3r_Format_3mf_hpp_ + +namespace Slic3r { + + class Model; + + // Load an 3mf file into a provided model. + extern bool load_3mf(const char* path, Model* model, const char* object_name = nullptr); +}; // namespace Slic3r + +#endif /* slic3r_Format_3mf_hpp_ */ diff --git a/xs/src/libslic3r/Model.cpp b/xs/src/libslic3r/Model.cpp index 88a0b8279..b86b7e55e 100644 --- a/xs/src/libslic3r/Model.cpp +++ b/xs/src/libslic3r/Model.cpp @@ -5,6 +5,7 @@ #include "Format/OBJ.hpp" #include "Format/PRUS.hpp" #include "Format/STL.hpp" +#include "Format/3mf.hpp" #include @@ -53,9 +54,11 @@ Model Model::read_from_file(const std::string &input_file, bool add_default_inst else if (boost::algorithm::iends_with(input_file, ".prusa")) result = load_prus(input_file.c_str(), &model); #endif /* SLIC3R_PRUS */ + else if (boost::algorithm::iends_with(input_file, ".3mf")) + result = load_3mf(input_file.c_str(), &model); else - throw std::runtime_error("Unknown file format. Input file must have .stl, .obj, .amf(.xml) or .prusa extension."); - + throw std::runtime_error("Unknown file format. Input file must have .stl, .obj, .amf(.xml), .3mf or .prusa extension."); + if (! result) throw std::runtime_error("Loading of a model file failed."); @@ -115,6 +118,23 @@ void Model::delete_object(size_t idx) this->objects.erase(i); } +void Model::delete_object(ModelObject* object) +{ + if (object == nullptr) + return; + + for (ModelObjectPtrs::iterator it = objects.begin(); it != objects.end(); ++it) + { + ModelObject* obj = *it; + if (obj == object) + { + delete obj; + objects.erase(it); + return; + } + } +} + void Model::clear_objects() { for (ModelObject *o : this->objects) @@ -607,6 +627,20 @@ void ModelObject::rotate(float angle, const Axis &axis) this->invalidate_bounding_box(); } +void ModelObject::transform(const float* matrix3x4) +{ + if (matrix3x4 == nullptr) + return; + + for (ModelVolume* v : volumes) + { + v->mesh.transform(matrix3x4); + } + + origin_translation = Pointf3(0.0f, 0.0f, 0.0f); + invalidate_bounding_box(); +} + void ModelObject::mirror(const Axis &axis) { for (ModelVolume *v : this->volumes) diff --git a/xs/src/libslic3r/Model.hpp b/xs/src/libslic3r/Model.hpp index 636dfa1f4..317d7ccbb 100644 --- a/xs/src/libslic3r/Model.hpp +++ b/xs/src/libslic3r/Model.hpp @@ -119,6 +119,7 @@ public: void translate(coordf_t x, coordf_t y, coordf_t z); void scale(const Pointf3 &versor); void rotate(float angle, const Axis &axis); + void transform(const float* matrix3x4); void mirror(const Axis &axis); size_t materials_count() const; size_t facets_count() const; @@ -244,6 +245,7 @@ public: ModelObject* add_object(const char *name, const char *path, TriangleMesh &&mesh); ModelObject* add_object(const ModelObject &other, bool copy_volumes = true); void delete_object(size_t idx); + void delete_object(ModelObject* object); void clear_objects(); ModelMaterial* add_material(t_model_material_id material_id); diff --git a/xs/src/libslic3r/TriangleMesh.cpp b/xs/src/libslic3r/TriangleMesh.cpp index 7afa4871c..c2c64e427 100644 --- a/xs/src/libslic3r/TriangleMesh.cpp +++ b/xs/src/libslic3r/TriangleMesh.cpp @@ -375,6 +375,15 @@ void TriangleMesh::mirror_z() this->mirror(Z); } +void TriangleMesh::transform(const float* matrix3x4) +{ + if (matrix3x4 == nullptr) + return; + + stl_transform(&stl, const_cast(matrix3x4)); + stl_invalidate_shared_vertices(&stl); +} + void TriangleMesh::align_to_origin() { this->translate( diff --git a/xs/src/libslic3r/TriangleMesh.hpp b/xs/src/libslic3r/TriangleMesh.hpp index b28f3a310..3192c90b6 100644 --- a/xs/src/libslic3r/TriangleMesh.hpp +++ b/xs/src/libslic3r/TriangleMesh.hpp @@ -47,6 +47,7 @@ public: void mirror_x(); void mirror_y(); void mirror_z(); + void transform(const float* matrix3x4); void align_to_origin(); void rotate(double angle, Point* center); TriangleMeshPtrs split() const; From d2d2a3fa8ec1dbd4b03e3a2de9f1afcd4b377a27 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Wed, 31 Jan 2018 10:34:00 +0100 Subject: [PATCH 13/57] speed in mm/s --- xs/src/libslic3r/GCode/Analyzer.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index 49b709ec2..8d27cf63c 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -348,7 +348,7 @@ std::string GCodeAnalyzer::PreviewData::get_legend_title() const case Extrusion::Width: return "Width (mm)"; case Extrusion::Feedrate: - return "Speed (mm/min)"; + return "Speed (mm/s)"; } return ""; @@ -397,7 +397,7 @@ GCodeAnalyzer::PreviewData::LegendItemsList GCodeAnalyzer::PreviewData::get_lege } case Extrusion::Feedrate: { - Helper::FillListFromRange(items, extrusion.ranges.feedrate, 0, 60.0f); + Helper::FillListFromRange(items, extrusion.ranges.feedrate, 0, 1.0f); break; } } From c550ad22683aea32a8df96afbf3d963408d0b4b7 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Wed, 31 Jan 2018 11:35:35 +0100 Subject: [PATCH 14/57] GCode Preview - Travel moves colored by speed --- xs/src/libslic3r/GCode/Analyzer.cpp | 15 +-- xs/src/libslic3r/GCode/Analyzer.hpp | 3 +- xs/src/slic3r/GUI/3DScene.cpp | 156 +++++++++++++++++++++------- 3 files changed, 130 insertions(+), 44 deletions(-) diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index 8d27cf63c..2ddb319fc 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -122,9 +122,10 @@ GCodeAnalyzer::PreviewData::Extrusion::Layer::Layer(float z, const ExtrusionPath { } -GCodeAnalyzer::PreviewData::Travel::Polyline::Polyline(EType type, EDirection direction, const Polyline3& polyline) +GCodeAnalyzer::PreviewData::Travel::Polyline::Polyline(EType type, EDirection direction, float feedrate, const Polyline3& polyline) : type(type) , direction(direction) + , feedrate(feedrate) , polyline(polyline) { } @@ -1002,11 +1003,11 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) { struct Helper { - static void store_polyline(const Polyline3& polyline, PreviewData::Travel::EType type, PreviewData::Travel::Polyline::EDirection direction, Print& print) + static void store_polyline(const Polyline3& polyline, PreviewData::Travel::EType type, PreviewData::Travel::Polyline::EDirection direction, float feedrate, Print& print) { // if the polyline is valid, store it if (polyline.is_valid()) - print.gcode_preview.travel.polylines.emplace_back(type, direction, polyline); + print.gcode_preview.travel.polylines.emplace_back(type, direction, feedrate, polyline); } }; @@ -1018,6 +1019,7 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) Pointf3 position(FLT_MAX, FLT_MAX, FLT_MAX); PreviewData::Travel::EType type = PreviewData::Travel::Num_Types; PreviewData::Travel::Polyline::EDirection direction = PreviewData::Travel::Polyline::Num_Directions; + float feedrate = FLT_MAX; // constructs the polylines while traversing the moves for (const GCodeMove& move : travel_moves->second) @@ -1025,11 +1027,11 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) PreviewData::Travel::EType move_type = (move.delta_extruder < 0.0f) ? PreviewData::Travel::Retract : ((move.delta_extruder > 0.0f) ? PreviewData::Travel::Extrude : PreviewData::Travel::Move); PreviewData::Travel::Polyline::EDirection move_direction = ((move.start_position.x != move.end_position.x) || (move.start_position.y != move.end_position.y)) ? PreviewData::Travel::Polyline::Generic : PreviewData::Travel::Polyline::Vertical; - if ((type != move_type) || (direction != move_direction) || (position != move.start_position)) + if ((type != move_type) || (direction != move_direction) || (feedrate != move.data.feedrate) || (position != move.start_position)) { // store current polyline polyline.remove_duplicate_points(); - Helper::store_polyline(polyline, type, direction, print); + Helper::store_polyline(polyline, type, direction, feedrate, print); // reset current polyline polyline = Polyline3(); @@ -1045,11 +1047,12 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) // update current values position = move.end_position; type = move_type; + feedrate = move.data.feedrate; } // store last polyline polyline.remove_duplicate_points(); - Helper::store_polyline(polyline, type, direction, print); + Helper::store_polyline(polyline, type, direction, feedrate, print); } void GCodeAnalyzer::_calc_gcode_preview_retractions(Print& print) diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index c4e71799b..a72874a35 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -215,9 +215,10 @@ public: EType type; EDirection direction; + float feedrate; Polyline3 polyline; - Polyline(EType type, EDirection direction, const Polyline3& polyline); + Polyline(EType type, EDirection direction, float feedrate, const Polyline3& polyline); }; typedef std::vector PolylinesList; diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index a79e38035..589a23e86 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -1863,59 +1863,141 @@ void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& typedef std::vector TypesList; + // Helper structure for feedrate + struct Feedrate + { + float value; + GLVolume* volume; + + explicit Feedrate(float value) + : value(value) + , volume(nullptr) + { + } + + bool operator == (const Feedrate& other) const + { + return value == other.value; + } + }; + + typedef std::vector FeedratesList; + size_t initial_volumes_count = volumes.volumes.size(); s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Travel, 0, (unsigned int)initial_volumes_count); - // detects types - TypesList types; - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + if (print.gcode_preview.extrusion.view_type == GCodeAnalyzer::PreviewData::Extrusion::Feedrate) { - if (std::find(types.begin(), types.end(), Type(polyline.type)) == types.end()) - types.emplace_back(polyline.type); - } + // colors travels by feedrate - // nothing to render, return - if (types.empty()) - return; - - // creates a new volume for each type - for (Type& type : types) - { - GLVolume* volume = new GLVolume(print.gcode_preview.travel.type_colors[type.value].rgba); - if (volume != nullptr) + // detects feedrates + FeedratesList feedrates; + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) { - type.volume = volume; - volumes.volumes.emplace_back(volume); + if (std::find(feedrates.begin(), feedrates.end(), Feedrate(polyline.feedrate)) == feedrates.end()) + feedrates.emplace_back(polyline.feedrate); } - else + + // nothing to render, return + if (feedrates.empty()) + return; + + // creates a new volume for each feedrate + for (Feedrate& feedrate : feedrates) { - // an error occourred - restore to previous state and return - if (initial_volumes_count != volumes.volumes.size()) + GLVolume* volume = new GLVolume(print.gcode_preview.get_extrusion_feedrate_color(feedrate.value).rgba); + if (volume != nullptr) { - std::vector::iterator begin = volumes.volumes.begin() + initial_volumes_count; - std::vector::iterator end = volumes.volumes.end(); - for (std::vector::iterator it = begin; it < end; ++it) + feedrate.volume = volume; + volumes.volumes.emplace_back(volume); + } + else + { + // an error occourred - restore to previous state and return + if (initial_volumes_count != volumes.volumes.size()) { - GLVolume* volume = *it; - delete volume; + std::vector::iterator begin = volumes.volumes.begin() + initial_volumes_count; + std::vector::iterator end = volumes.volumes.end(); + for (std::vector::iterator it = begin; it < end; ++it) + { + GLVolume* volume = *it; + delete volume; + } + volumes.volumes.erase(begin, end); + return; } - volumes.volumes.erase(begin, end); - return; + } + } + + // populates volumes + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + { + FeedratesList::iterator feedrate = std::find(feedrates.begin(), feedrates.end(), Feedrate(polyline.feedrate)); + if (feedrate != feedrates.end()) + { + feedrate->volume->print_zs.push_back(unscale(polyline.polyline.bounding_box().max.z)); + feedrate->volume->offsets.push_back(feedrate->volume->indexed_vertex_array.quad_indices.size()); + feedrate->volume->offsets.push_back(feedrate->volume->indexed_vertex_array.triangle_indices.size()); + + polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *feedrate->volume); } } } - - // populates volumes - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + else { - TypesList::iterator type = std::find(types.begin(), types.end(), Type(polyline.type)); - if (type != types.end()) - { - type->volume->print_zs.push_back(unscale(polyline.polyline.bounding_box().max.z)); - type->volume->offsets.push_back(type->volume->indexed_vertex_array.quad_indices.size()); - type->volume->offsets.push_back(type->volume->indexed_vertex_array.triangle_indices.size()); + // colors travels by travel type - polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *type->volume); + // detects types + TypesList types; + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + { + if (std::find(types.begin(), types.end(), Type(polyline.type)) == types.end()) + types.emplace_back(polyline.type); + } + + // nothing to render, return + if (types.empty()) + return; + + // creates a new volume for each type + for (Type& type : types) + { + GLVolume* volume = new GLVolume(print.gcode_preview.travel.type_colors[type.value].rgba); + if (volume != nullptr) + { + type.volume = volume; + volumes.volumes.emplace_back(volume); + } + else + { + // an error occourred - restore to previous state and return + if (initial_volumes_count != volumes.volumes.size()) + { + std::vector::iterator begin = volumes.volumes.begin() + initial_volumes_count; + std::vector::iterator end = volumes.volumes.end(); + for (std::vector::iterator it = begin; it < end; ++it) + { + GLVolume* volume = *it; + delete volume; + } + volumes.volumes.erase(begin, end); + return; + } + } + } + + // populates volumes + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + { + TypesList::iterator type = std::find(types.begin(), types.end(), Type(polyline.type)); + if (type != types.end()) + { + type->volume->print_zs.push_back(unscale(polyline.polyline.bounding_box().max.z)); + type->volume->offsets.push_back(type->volume->indexed_vertex_array.quad_indices.size()); + type->volume->offsets.push_back(type->volume->indexed_vertex_array.triangle_indices.size()); + + polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *type->volume); + } } } From 4f427f83876090cc970df17dce740084dd3520d9 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Fri, 2 Feb 2018 10:51:08 +0100 Subject: [PATCH 15/57] Updated the bundled Slic3r profiles to match the current stable release profiles, adjusted the speed / acceleration / jerk limits to match the current MK3 firmware. --- ...inal Prusa i3 MK2, MK2S, MK2MM and MK3.ini | 56 +++++++++---------- resources/profiles/Original Prusa i3 MK3.ini | 56 +++++++++---------- 2 files changed, 56 insertions(+), 56 deletions(-) diff --git a/resources/profiles/Original Prusa i3 MK2, MK2S, MK2MM and MK3.ini b/resources/profiles/Original Prusa i3 MK2, MK2S, MK2MM and MK3.ini index 5835cfdeb..64af7d9b2 100644 --- a/resources/profiles/Original Prusa i3 MK2, MK2S, MK2MM and MK3.ini +++ b/resources/profiles/Original Prusa i3 MK2, MK2S, MK2MM and MK3.ini @@ -1,4 +1,4 @@ -# generated by Slic3r Prusa Edition 1.39.0 on 2018-01-06 at 15:09:55 +# generated by Slic3r Prusa Edition 1.39.0.29-prusa3d-win64 on 2018-01-22 at 14:53:14 [print:0.05mm DETAIL] avoid_crossing_perimeters = 0 @@ -532,7 +532,7 @@ xy_size_compensation = 0 [print:0.10mm DETAIL MK3] avoid_crossing_perimeters = 0 -bottom_solid_layers = 4 +bottom_solid_layers = 7 bridge_acceleration = 1000 bridge_angle = 0 bridge_flow_ratio = 0.8 @@ -563,17 +563,17 @@ first_layer_height = 0.2 first_layer_speed = 30 gap_fill_speed = 40 gcode_comments = 0 -infill_acceleration = 3500 +infill_acceleration = 1500 infill_every_layers = 1 infill_extruder = 1 infill_extrusion_width = 0.45 infill_first = 0 infill_only_where_needed = 0 infill_overlap = 25% -infill_speed = 200 +infill_speed = 170 interface_shells = 0 layer_height = 0.1 -max_print_speed = 250 +max_print_speed = 170 max_volumetric_extrusion_rate_slope_negative = 0 max_volumetric_extrusion_rate_slope_positive = 0 max_volumetric_speed = 0 @@ -601,7 +601,7 @@ solid_infill_below_area = 0 solid_infill_every_layers = 0 solid_infill_extruder = 1 solid_infill_extrusion_width = 0.45 -solid_infill_speed = 200 +solid_infill_speed = 170 spiral_vase = 0 standby_temperature_delta = -5 support_material = 0 @@ -627,8 +627,8 @@ thin_walls = 0 threads = 4 top_infill_extrusion_width = 0.4 top_solid_infill_speed = 50 -top_solid_layers = 5 -travel_speed = 250 +top_solid_layers = 9 +travel_speed = 170 wipe_tower = 0 wipe_tower_per_color_wipe = 15 wipe_tower_width = 60 @@ -1062,7 +1062,7 @@ xy_size_compensation = 0 [print:0.15mm OPTIMAL MK3] avoid_crossing_perimeters = 0 -bottom_solid_layers = 4 +bottom_solid_layers = 5 bridge_acceleration = 1000 bridge_angle = 0 bridge_flow_ratio = 0.8 @@ -1093,17 +1093,17 @@ first_layer_height = 0.2 first_layer_speed = 30 gap_fill_speed = 40 gcode_comments = 0 -infill_acceleration = 3500 +infill_acceleration = 1500 infill_every_layers = 1 infill_extruder = 1 infill_extrusion_width = 0.45 infill_first = 0 infill_only_where_needed = 0 infill_overlap = 25% -infill_speed = 200 +infill_speed = 170 interface_shells = 0 layer_height = 0.15 -max_print_speed = 250 +max_print_speed = 170 max_volumetric_extrusion_rate_slope_negative = 0 max_volumetric_extrusion_rate_slope_positive = 0 max_volumetric_speed = 0 @@ -1131,7 +1131,7 @@ solid_infill_below_area = 0 solid_infill_every_layers = 0 solid_infill_extruder = 1 solid_infill_extrusion_width = 0.45 -solid_infill_speed = 200 +solid_infill_speed = 170 spiral_vase = 0 standby_temperature_delta = -5 support_material = 0 @@ -1157,8 +1157,8 @@ thin_walls = 0 threads = 4 top_infill_extrusion_width = 0.4 top_solid_infill_speed = 50 -top_solid_layers = 5 -travel_speed = 250 +top_solid_layers = 7 +travel_speed = 170 wipe_tower = 1 wipe_tower_per_color_wipe = 15 wipe_tower_width = 60 @@ -1517,17 +1517,17 @@ first_layer_height = 0.2 first_layer_speed = 30 gap_fill_speed = 40 gcode_comments = 0 -infill_acceleration = 3500 +infill_acceleration = 1500 infill_every_layers = 1 infill_extruder = 1 infill_extrusion_width = 0.45 infill_first = 0 infill_only_where_needed = 0 infill_overlap = 25% -infill_speed = 200 +infill_speed = 170 interface_shells = 0 layer_height = 0.2 -max_print_speed = 250 +max_print_speed = 170 max_volumetric_extrusion_rate_slope_negative = 0 max_volumetric_extrusion_rate_slope_positive = 0 max_volumetric_speed = 0 @@ -1555,7 +1555,7 @@ solid_infill_below_area = 0 solid_infill_every_layers = 0 solid_infill_extruder = 1 solid_infill_extrusion_width = 0.45 -solid_infill_speed = 200 +solid_infill_speed = 170 spiral_vase = 0 standby_temperature_delta = -5 support_material = 0 @@ -1582,7 +1582,7 @@ threads = 4 top_infill_extrusion_width = 0.4 top_solid_infill_speed = 50 top_solid_layers = 5 -travel_speed = 250 +travel_speed = 170 wipe_tower = 1 wipe_tower_per_color_wipe = 15 wipe_tower_width = 60 @@ -2807,13 +2807,13 @@ filament_settings_id = filament_soluble = 0 filament_type = PET first_layer_bed_temperature = 90 -first_layer_temperature = 260 -max_fan_speed = 80 -min_fan_speed = 80 +first_layer_temperature = 275 +max_fan_speed = 50 +min_fan_speed = 50 min_print_speed = 5 slowdown_below_layer_time = 20 start_filament_gcode = "M900 K{if printer_notes=~/.*PRINTER_HAS_BOWDEN.*/}200{else}45{endif}; Filament gcode" -temperature = 260 +temperature = 275 [filament:Fillamentum Timberfil] bed_temperature = 60 @@ -3120,19 +3120,19 @@ filament_colour = #00CA0A filament_cost = 0 filament_density = 0 filament_diameter = 1.75 -filament_max_volumetric_speed = 2.5 +filament_max_volumetric_speed = 1.5 filament_notes = "List of materials tested with FLEX print settings & FLEX material settings for MK2:\n\nFillamentum Flex 98A\nFillamentum Flex 92A\nPlasty Mladeč PP\nPlasty Mladeč TPE32 \nPlasty Mladeč TPE88" filament_settings_id = filament_soluble = 0 filament_type = FLEX first_layer_bed_temperature = 50 -first_layer_temperature = 220 +first_layer_temperature = 240 max_fan_speed = 90 min_fan_speed = 70 min_print_speed = 5 slowdown_below_layer_time = 20 start_filament_gcode = "M900 K{if printer_notes=~/.*PRINTER_HAS_BOWDEN.*/}200{else}10{endif}; Filament gcode" -temperature = 230 +temperature = 240 [filament:Taulman Bridge] bed_temperature = 50 @@ -3560,7 +3560,7 @@ retract_speed = 35 serial_port = serial_speed = 250000 single_extruder_multi_material = 0 -start_gcode = M115 U3.1.1-RC4 ; tell printer latest fw version\nM201 X1000 Y1000 Z200 E5000 ; sets maximum accelerations, mm/sec^2\nM203 X500 Y500 Z12 E120 ; sets maximum feedrates, mm/sec\nM204 S1250 T1250 ; sets acceleration (S) and retract acceleration (T)\nM205 X15 Y15 Z0.4 E2.5 ; sets the jerk limits, mm/sec\nM205 S0 T0 ; sets the minimum extruding and travel feed rate, mm/sec\nM83 ; extruder relative mode\nM104 S[first_layer_temperature] ; set extruder temp\nM140 S[first_layer_bed_temperature] ; set bed temp\nM190 S[first_layer_bed_temperature] ; wait for bed temp\nM109 S[first_layer_temperature] ; wait for extruder temp\nG28 W ; home all without mesh bed level\nG80 ; mesh bed leveling\nG1 Y-3.0 F1000.0 ; go outside print area\nG92 E0.0\nG1 X60.0 E9.0 F1000.0 ; intro line\nG1 X100.0 E12.5 F1000.0 ; intro line\nG92 E0.0\nM221 S95 +start_gcode = M115 U3.1.1-RC5 ; tell printer latest fw version\nM201 X1000 Y1000 Z200 E5000 ; sets maximum accelerations, mm/sec^2\nM203 X200 Y200 Z12 E120 ; sets maximum feedrates, mm/sec\nM204 S1250 T1250 ; sets acceleration (S) and retract acceleration (T)\nM205 X10 Y10 Z0.4 E2.5 ; sets the jerk limits, mm/sec\nM205 S0 T0 ; sets the minimum extruding and travel feed rate, mm/sec\nM83 ; extruder relative mode\nM104 S[first_layer_temperature] ; set extruder temp\nM140 S[first_layer_bed_temperature] ; set bed temp\nM190 S[first_layer_bed_temperature] ; wait for bed temp\nM109 S[first_layer_temperature] ; wait for extruder temp\nG28 W ; home all without mesh bed level\nG80 ; mesh bed leveling\nG1 Y-3.0 F1000.0 ; go outside print area\nG92 E0.0\nG1 X60.0 E9.0 F1000.0 ; intro line\nG1 X100.0 E12.5 F1000.0 ; intro line\nG92 E0.0\nM221 S{if layer_height==0.05}100{else}95{endif} toolchange_gcode = use_firmware_retraction = 0 use_relative_e_distances = 1 diff --git a/resources/profiles/Original Prusa i3 MK3.ini b/resources/profiles/Original Prusa i3 MK3.ini index 0afbb35cd..b53006b0f 100644 --- a/resources/profiles/Original Prusa i3 MK3.ini +++ b/resources/profiles/Original Prusa i3 MK3.ini @@ -1,4 +1,4 @@ -# generated by Slic3r Prusa Edition 1.39.0 on 2018-01-06 at 15:12:34 +# generated by Slic3r Prusa Edition 1.39.0 on 2018-02-02 at 10:48:46 [print:0.05mm DETAIL] avoid_crossing_perimeters = 0 @@ -532,7 +532,7 @@ xy_size_compensation = 0 [print:0.10mm DETAIL MK3] avoid_crossing_perimeters = 0 -bottom_solid_layers = 4 +bottom_solid_layers = 7 bridge_acceleration = 1000 bridge_angle = 0 bridge_flow_ratio = 0.8 @@ -563,17 +563,17 @@ first_layer_height = 0.2 first_layer_speed = 30 gap_fill_speed = 40 gcode_comments = 0 -infill_acceleration = 3500 +infill_acceleration = 1500 infill_every_layers = 1 infill_extruder = 1 infill_extrusion_width = 0.45 infill_first = 0 infill_only_where_needed = 0 infill_overlap = 25% -infill_speed = 200 +infill_speed = 170 interface_shells = 0 layer_height = 0.1 -max_print_speed = 250 +max_print_speed = 170 max_volumetric_extrusion_rate_slope_negative = 0 max_volumetric_extrusion_rate_slope_positive = 0 max_volumetric_speed = 0 @@ -601,7 +601,7 @@ solid_infill_below_area = 0 solid_infill_every_layers = 0 solid_infill_extruder = 1 solid_infill_extrusion_width = 0.45 -solid_infill_speed = 200 +solid_infill_speed = 170 spiral_vase = 0 standby_temperature_delta = -5 support_material = 0 @@ -627,8 +627,8 @@ thin_walls = 0 threads = 4 top_infill_extrusion_width = 0.4 top_solid_infill_speed = 50 -top_solid_layers = 5 -travel_speed = 250 +top_solid_layers = 9 +travel_speed = 170 wipe_tower = 0 wipe_tower_per_color_wipe = 15 wipe_tower_width = 60 @@ -1062,7 +1062,7 @@ xy_size_compensation = 0 [print:0.15mm OPTIMAL MK3] avoid_crossing_perimeters = 0 -bottom_solid_layers = 4 +bottom_solid_layers = 5 bridge_acceleration = 1000 bridge_angle = 0 bridge_flow_ratio = 0.8 @@ -1093,17 +1093,17 @@ first_layer_height = 0.2 first_layer_speed = 30 gap_fill_speed = 40 gcode_comments = 0 -infill_acceleration = 3500 +infill_acceleration = 1500 infill_every_layers = 1 infill_extruder = 1 infill_extrusion_width = 0.45 infill_first = 0 infill_only_where_needed = 0 infill_overlap = 25% -infill_speed = 200 +infill_speed = 170 interface_shells = 0 layer_height = 0.15 -max_print_speed = 250 +max_print_speed = 170 max_volumetric_extrusion_rate_slope_negative = 0 max_volumetric_extrusion_rate_slope_positive = 0 max_volumetric_speed = 0 @@ -1131,7 +1131,7 @@ solid_infill_below_area = 0 solid_infill_every_layers = 0 solid_infill_extruder = 1 solid_infill_extrusion_width = 0.45 -solid_infill_speed = 200 +solid_infill_speed = 170 spiral_vase = 0 standby_temperature_delta = -5 support_material = 0 @@ -1157,8 +1157,8 @@ thin_walls = 0 threads = 4 top_infill_extrusion_width = 0.4 top_solid_infill_speed = 50 -top_solid_layers = 5 -travel_speed = 250 +top_solid_layers = 7 +travel_speed = 170 wipe_tower = 1 wipe_tower_per_color_wipe = 15 wipe_tower_width = 60 @@ -1517,17 +1517,17 @@ first_layer_height = 0.2 first_layer_speed = 30 gap_fill_speed = 40 gcode_comments = 0 -infill_acceleration = 3500 +infill_acceleration = 1500 infill_every_layers = 1 infill_extruder = 1 infill_extrusion_width = 0.45 infill_first = 0 infill_only_where_needed = 0 infill_overlap = 25% -infill_speed = 200 +infill_speed = 170 interface_shells = 0 layer_height = 0.2 -max_print_speed = 250 +max_print_speed = 170 max_volumetric_extrusion_rate_slope_negative = 0 max_volumetric_extrusion_rate_slope_positive = 0 max_volumetric_speed = 0 @@ -1555,7 +1555,7 @@ solid_infill_below_area = 0 solid_infill_every_layers = 0 solid_infill_extruder = 1 solid_infill_extrusion_width = 0.45 -solid_infill_speed = 200 +solid_infill_speed = 170 spiral_vase = 0 standby_temperature_delta = -5 support_material = 0 @@ -1582,7 +1582,7 @@ threads = 4 top_infill_extrusion_width = 0.4 top_solid_infill_speed = 50 top_solid_layers = 5 -travel_speed = 250 +travel_speed = 170 wipe_tower = 1 wipe_tower_per_color_wipe = 15 wipe_tower_width = 60 @@ -2807,13 +2807,13 @@ filament_settings_id = filament_soluble = 0 filament_type = PET first_layer_bed_temperature = 90 -first_layer_temperature = 260 -max_fan_speed = 80 -min_fan_speed = 80 +first_layer_temperature = 275 +max_fan_speed = 50 +min_fan_speed = 50 min_print_speed = 5 slowdown_below_layer_time = 20 start_filament_gcode = "M900 K{if printer_notes=~/.*PRINTER_HAS_BOWDEN.*/}200{else}45{endif}; Filament gcode" -temperature = 260 +temperature = 275 [filament:Fillamentum Timberfil] bed_temperature = 60 @@ -3120,19 +3120,19 @@ filament_colour = #00CA0A filament_cost = 0 filament_density = 0 filament_diameter = 1.75 -filament_max_volumetric_speed = 2.5 +filament_max_volumetric_speed = 1.5 filament_notes = "List of materials tested with FLEX print settings & FLEX material settings for MK2:\n\nFillamentum Flex 98A\nFillamentum Flex 92A\nPlasty Mladeč PP\nPlasty Mladeč TPE32 \nPlasty Mladeč TPE88" filament_settings_id = filament_soluble = 0 filament_type = FLEX first_layer_bed_temperature = 50 -first_layer_temperature = 220 +first_layer_temperature = 240 max_fan_speed = 90 min_fan_speed = 70 min_print_speed = 5 slowdown_below_layer_time = 20 start_filament_gcode = "M900 K{if printer_notes=~/.*PRINTER_HAS_BOWDEN.*/}200{else}10{endif}; Filament gcode" -temperature = 230 +temperature = 240 [filament:Taulman Bridge] bed_temperature = 50 @@ -3280,7 +3280,7 @@ retract_speed = 35 serial_port = serial_speed = 250000 single_extruder_multi_material = 0 -start_gcode = M115 U3.1.1-RC4 ; tell printer latest fw version\nM201 X1000 Y1000 Z200 E5000 ; sets maximum accelerations, mm/sec^2\nM203 X500 Y500 Z12 E120 ; sets maximum feedrates, mm/sec\nM204 S1250 T1250 ; sets acceleration (S) and retract acceleration (T)\nM205 X15 Y15 Z0.4 E2.5 ; sets the jerk limits, mm/sec\nM205 S0 T0 ; sets the minimum extruding and travel feed rate, mm/sec\nM83 ; extruder relative mode\nM104 S[first_layer_temperature] ; set extruder temp\nM140 S[first_layer_bed_temperature] ; set bed temp\nM190 S[first_layer_bed_temperature] ; wait for bed temp\nM109 S[first_layer_temperature] ; wait for extruder temp\nG28 W ; home all without mesh bed level\nG80 ; mesh bed leveling\nG1 Y-3.0 F1000.0 ; go outside print area\nG92 E0.0\nG1 X60.0 E9.0 F1000.0 ; intro line\nG1 X100.0 E12.5 F1000.0 ; intro line\nG92 E0.0\nM221 S95 +start_gcode = M115 U3.1.1-RC5 ; tell printer latest fw version\nM201 X1000 Y1000 Z200 E5000 ; sets maximum accelerations, mm/sec^2\nM203 X200 Y200 Z12 E120 ; sets maximum feedrates, mm/sec\nM204 S1250 T1250 ; sets acceleration (S) and retract acceleration (T)\nM205 X10 Y10 Z0.4 E2.5 ; sets the jerk limits, mm/sec\nM205 S0 T0 ; sets the minimum extruding and travel feed rate, mm/sec\nM83 ; extruder relative mode\nM104 S[first_layer_temperature] ; set extruder temp\nM140 S[first_layer_bed_temperature] ; set bed temp\nM190 S[first_layer_bed_temperature] ; wait for bed temp\nM109 S[first_layer_temperature] ; wait for extruder temp\nG28 W ; home all without mesh bed level\nG80 ; mesh bed leveling\nG1 Y-3.0 F1000.0 ; go outside print area\nG92 E0.0\nG1 X60.0 E9.0 F1000.0 ; intro line\nG1 X100.0 E12.5 F1000.0 ; intro line\nG92 E0.0\nM221 S{if layer_height==0.05}100{else}95{endif} toolchange_gcode = use_firmware_retraction = 0 use_relative_e_distances = 1 From 36bbd6a73fdcb4d7b817674b6c827eda299fae6b Mon Sep 17 00:00:00 2001 From: bubnikv Date: Fri, 2 Feb 2018 11:32:32 +0100 Subject: [PATCH 16/57] Fix of https://github.com/prusa3d/Slic3r/issues/696 --- xs/xsp/GUI_Preset.xsp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xs/xsp/GUI_Preset.xsp b/xs/xsp/GUI_Preset.xsp index 67e1d5fc6..0033ebd0e 100644 --- a/xs/xsp/GUI_Preset.xsp +++ b/xs/xsp/GUI_Preset.xsp @@ -18,8 +18,8 @@ bool is_compatible_with_printer(Preset *active_printer) %code%{ RETVAL = THIS->is_compatible_with_printer(*active_printer); %}; - const char* name() %code%{ RETVAL = THIS->name.c_str(); %}; - const char* file() %code%{ RETVAL = THIS->file.c_str(); %}; + std::string name() %code%{ RETVAL = THIS->name; %}; + std::string file() %code%{ RETVAL = THIS->file; %}; bool loaded() %code%{ RETVAL = THIS->loaded; %}; From 8932055ed5262f43697cc0313059ca79a219f583 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Fri, 2 Feb 2018 11:38:30 +0100 Subject: [PATCH 17/57] Fixed spelling of Elephant foot compensation from Elefant to Elephant. Unfortunately the settings is out in the wild, so we did not fix the spelling of the config value name. --- xs/src/libslic3r/PrintConfig.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xs/src/libslic3r/PrintConfig.cpp b/xs/src/libslic3r/PrintConfig.cpp index 0dc6c9d43..5bbf20c4c 100644 --- a/xs/src/libslic3r/PrintConfig.cpp +++ b/xs/src/libslic3r/PrintConfig.cpp @@ -200,10 +200,10 @@ PrintConfigDef::PrintConfigDef() def->default_value = new ConfigOptionFloat(6); def = this->add("elefant_foot_compensation", coFloat); - def->label = "Elefant foot compensation"; + def->label = "Elephant foot compensation"; def->category = "Advanced"; def->tooltip = "The first layer will be shrunk in the XY plane by the configured value " - "to compensate for the 1st layer squish aka an Elefant Foot effect."; + "to compensate for the 1st layer squish aka an Elephant Foot effect."; def->sidetext = "mm"; def->cli = "elefant-foot-compensation=f"; def->min = 0; From b4483fdcbd28c537ccc7cdf786a317a0addfa3af Mon Sep 17 00:00:00 2001 From: bubnikv Date: Fri, 2 Feb 2018 11:49:09 +0100 Subject: [PATCH 18/57] Fix of "Conditional gcode with "<=" condition fails" https://github.com/prusa3d/Slic3r/issues/683 --- t/custom_gcode.t | 12 +++++++++--- xs/src/libslic3r/PlaceholderParser.cpp | 6 +++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/t/custom_gcode.t b/t/custom_gcode.t index 6a930a38a..bafcd4610 100644 --- a/t/custom_gcode.t +++ b/t/custom_gcode.t @@ -1,4 +1,4 @@ -use Test::More tests => 71; +use Test::More tests => 77; use strict; use warnings; @@ -91,8 +91,14 @@ use Slic3r::Test; is $parser->evaluate_boolean_expression('(12 == 2 * 6) ? (1 - 1 == 3) : (2 * 2 == 4)'), 0, 'boolean expression parser: ternary true'; is $parser->evaluate_boolean_expression('12 < 3'), 0, 'boolean expression parser: lower than - false'; is $parser->evaluate_boolean_expression('12 < 22'), 1, 'boolean expression parser: lower than - true'; - is $parser->evaluate_boolean_expression('12 > 3'), 1, 'boolean expression parser: lower than - true'; - is $parser->evaluate_boolean_expression('12 > 22'), 0, 'boolean expression parser: lower than - false'; + is $parser->evaluate_boolean_expression('12 > 3'), 1, 'boolean expression parser: greater than - true'; + is $parser->evaluate_boolean_expression('12 > 22'), 0, 'boolean expression parser: greater than - false'; + is $parser->evaluate_boolean_expression('12 <= 3'), 0, 'boolean expression parser: lower than or equal- false'; + is $parser->evaluate_boolean_expression('12 <= 22'), 1, 'boolean expression parser: lower than or equal - true'; + is $parser->evaluate_boolean_expression('12 >= 3'), 1, 'boolean expression parser: greater than or equal - true'; + is $parser->evaluate_boolean_expression('12 >= 22'), 0, 'boolean expression parser: greater than or equal - false'; + is $parser->evaluate_boolean_expression('12 <= 12'), 1, 'boolean expression parser: lower than or equal (same values) - true'; + is $parser->evaluate_boolean_expression('12 >= 12'), 1, 'boolean expression parser: greater than or equal (same values) - true'; is $parser->evaluate_boolean_expression('printer_notes=~/.*PRINTER_VENDOR_PRUSA3D.*/ and printer_notes=~/.*PRINTER_MODEL_MK2.*/ and nozzle_diameter[0]==0.6 and num_extruders>1'), 1, 'complex expression'; is $parser->evaluate_boolean_expression('printer_notes=~/.*PRINTER_VEwerfNDOR_PRUSA3D.*/ or printer_notes=~/.*PRINTertER_MODEL_MK2.*/ or (nozzle_diameter[0]==0.6 and num_extruders>1)'), 1, 'complex expression2'; diff --git a/xs/src/libslic3r/PlaceholderParser.cpp b/xs/src/libslic3r/PlaceholderParser.cpp index b91f4c99c..ba0efd6e4 100644 --- a/xs/src/libslic3r/PlaceholderParser.cpp +++ b/xs/src/libslic3r/PlaceholderParser.cpp @@ -974,10 +974,10 @@ namespace client relational_expression = additive_expression(_r1) [_val = _1] - >> *( (lit('<') > additive_expression(_r1) ) [px::bind(&expr::lower, _val, _1)] - | (lit('>') > additive_expression(_r1) ) [px::bind(&expr::greater, _val, _1)] - | ("<=" > additive_expression(_r1) ) [px::bind(&expr::leq, _val, _1)] + >> *( ("<=" > additive_expression(_r1) ) [px::bind(&expr::leq, _val, _1)] | (">=" > additive_expression(_r1) ) [px::bind(&expr::geq, _val, _1)] + | (lit('<') > additive_expression(_r1) ) [px::bind(&expr::lower, _val, _1)] + | (lit('>') > additive_expression(_r1) ) [px::bind(&expr::greater, _val, _1)] ); relational_expression.name("relational_expression"); From 787a5f1715ddba98f9df25e49dd5da653ad5e85f Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Fri, 2 Feb 2018 12:38:35 +0100 Subject: [PATCH 19/57] GCode Preview - New Layout --- lib/Slic3r/GUI/Plater/3DPreview.pm | 62 +++++++++++++------------ xs/CMakeLists.txt | 2 + xs/src/slic3r/GUI/GUI.cpp | 48 +++++++++++++++++++ xs/src/slic3r/GUI/GUI.hpp | 13 +++++- xs/src/slic3r/GUI/wxExtensions.cpp | 74 ++++++++++++++++++++++++++++++ xs/src/slic3r/GUI/wxExtensions.hpp | 27 +++++++++++ xs/xsp/GUI.xsp | 7 +++ 7 files changed, 202 insertions(+), 31 deletions(-) create mode 100644 xs/src/slic3r/GUI/wxExtensions.cpp create mode 100644 xs/src/slic3r/GUI/wxExtensions.hpp diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index 379c557b6..ed84135e2 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -4,7 +4,7 @@ use warnings; use utf8; use Slic3r::Print::State ':steps'; -use Wx qw(:misc :sizer :slider :statictext :keycode wxWHITE); +use Wx qw(:misc :sizer :slider :statictext :keycode wxWHITE wxCB_READONLY); use Wx::Event qw(EVT_SLIDER EVT_KEY_DOWN EVT_CHECKBOX EVT_CHOICE EVT_CHECKLISTBOX); use base qw(Wx::Panel Class::Accessor); @@ -61,29 +61,24 @@ sub new { my $checkbox_singlelayer = $self->{checkbox_singlelayer} = Wx::CheckBox->new($self, -1, "1 Layer"); my $checkbox_color_by_extruder = $self->{checkbox_color_by_extruder} = Wx::CheckBox->new($self, -1, "Tool"); + my $label_view_type = $self->{label_view_type} = Wx::StaticText->new($self, -1, "View"); + my $choice_view_type = Wx::Choice->new($self, -1); $choice_view_type->Append("Feature type"); $choice_view_type->Append("Height"); $choice_view_type->Append("Width"); $choice_view_type->Append("Speed"); $choice_view_type->SetSelection(0); + + my $label_show_features = $self->{label_show_features} = Wx::StaticText->new($self, -1, "Show"); - my $checklist_features = Wx::CheckListBox->new($self, -1, wxDefaultPosition, [-1, 150]); - $checklist_features->Append("Perimeter"); - $checklist_features->Append("External perimeter"); - $checklist_features->Append("Overhang perimeter"); - $checklist_features->Append("Internal infill"); - $checklist_features->Append("Solid infill"); - $checklist_features->Append("Top solid infill"); - $checklist_features->Append("Bridge infill"); - $checklist_features->Append("Gap fill"); - $checklist_features->Append("Skirt"); - $checklist_features->Append("Support material"); - $checklist_features->Append("Support material interface"); - for (my $i = 0; $i < $checklist_features->GetCount(); $i += 1) - { - $checklist_features->Check($i, 1); - } + my $combochecklist_features = Wx::ComboCtrl->new(); + $combochecklist_features->Create($self, -1, "Feature types", wxDefaultPosition, [200, -1], wxCB_READONLY); + $combochecklist_features->UseAltPopupWindow(); + $combochecklist_features->EnablePopupAnimation(0); + my $feature_text = "Feature types"; + my $feature_items = "Perimeter|External perimeter|Overhang perimeter|Internal infill|Solid infill|Top solid infill|Bridge infill|Gap fill|Skirt|Support material|Support material interface"; + Slic3r::GUI::create_combochecklist($combochecklist_features, $feature_text, $feature_items, 1); my $checkbox_travel = Wx::CheckBox->new($self, -1, "Travel"); my $checkbox_retractions = Wx::CheckBox->new($self, -1, "Retractions"); @@ -102,15 +97,27 @@ sub new { $vsizer_outer->Add($hsizer, 3, wxALIGN_CENTER_HORIZONTAL, 0); $vsizer_outer->Add($checkbox_singlelayer, 0, wxTOP | wxALIGN_CENTER_HORIZONTAL, 5); $vsizer_outer->Add($checkbox_color_by_extruder, 0, wxTOP | wxALIGN_CENTER_HORIZONTAL, 5); - $vsizer_outer->Add($choice_view_type, 0, wxEXPAND | wxALL | wxALIGN_CENTER_HORIZONTAL, 5); - $vsizer_outer->Add($checklist_features, 0, wxTOP | wxALL | wxALIGN_CENTER_HORIZONTAL, 5); - $vsizer_outer->Add($checkbox_travel, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); - $vsizer_outer->Add($checkbox_retractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); - $vsizer_outer->Add($checkbox_unretractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); + my $bottom_sizer = Wx::BoxSizer->new(wxHORIZONTAL); + $bottom_sizer->Add($label_view_type, 0, wxALIGN_CENTER_VERTICAL, 5); + $bottom_sizer->Add($choice_view_type, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); + $bottom_sizer->AddSpacer(10); + $bottom_sizer->Add($label_show_features, 0, wxALIGN_CENTER_VERTICAL, 5); + $bottom_sizer->Add($combochecklist_features, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); + $bottom_sizer->AddSpacer(20); + $bottom_sizer->Add($checkbox_travel, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); + $bottom_sizer->AddSpacer(10); + $bottom_sizer->Add($checkbox_retractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); + $bottom_sizer->AddSpacer(10); + $bottom_sizer->Add($checkbox_unretractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); + my $sizer = Wx::BoxSizer->new(wxHORIZONTAL); $sizer->Add($canvas, 1, wxALL | wxEXPAND, 0); $sizer->Add($vsizer_outer, 0, wxTOP | wxBOTTOM | wxEXPAND, 5); + + my $main_sizer = Wx::BoxSizer->new(wxVERTICAL); + $main_sizer->Add($sizer, 1, wxALL | wxEXPAND, 0); + $main_sizer->Add($bottom_sizer, 0, wxALL | wxEXPAND, 0); EVT_SLIDER($self, $slider_low, sub { $slider_high->SetValue($slider_low->GetValue) if $self->single_layer; @@ -194,13 +201,8 @@ sub new { $self->reload_print; $self->auto_zoom(1); }); - EVT_CHECKLISTBOX($self, $checklist_features, sub { - my $flags = 0; - for (my $i = 0; $i < $checklist_features->GetCount(); $i += 1) { - if ($checklist_features->IsChecked($i)) { - $flags += 2 ** $i; - } - } + EVT_CHECKLISTBOX($self, $combochecklist_features, sub { + my $flags = Slic3r::GUI::combochecklist_get_flags($combochecklist_features); $self->print->set_gcode_preview_extrusion_flags($flags); $self->auto_zoom(0); @@ -226,7 +228,7 @@ sub new { $self->auto_zoom(1); }); - $self->SetSizer($sizer); + $self->SetSizer($main_sizer); $self->SetMinSize($self->GetSize); $sizer->SetSizeHints($self); diff --git a/xs/CMakeLists.txt b/xs/CMakeLists.txt index 9e23112c5..de475eaa0 100644 --- a/xs/CMakeLists.txt +++ b/xs/CMakeLists.txt @@ -177,6 +177,8 @@ add_library(libslic3r_gui STATIC ${LIBDIR}/slic3r/GUI/PresetHints.hpp ${LIBDIR}/slic3r/GUI/GUI.cpp ${LIBDIR}/slic3r/GUI/GUI.hpp + ${LIBDIR}/slic3r/GUI/wxExtensions.cpp + ${LIBDIR}/slic3r/GUI/wxExtensions.hpp ) add_library(admesh STATIC diff --git a/xs/src/slic3r/GUI/GUI.cpp b/xs/src/slic3r/GUI/GUI.cpp index 8db0508f1..7d107ecbc 100644 --- a/xs/src/slic3r/GUI/GUI.cpp +++ b/xs/src/slic3r/GUI/GUI.cpp @@ -5,6 +5,9 @@ #include #include +#include +#include + #if __APPLE__ #import #elif _WIN32 @@ -20,6 +23,9 @@ #include #include #include +#include + +#include "slic3r/gui/wxextensions.hpp" namespace Slic3r { namespace GUI { @@ -183,4 +189,46 @@ void create_preset_tab(const char *name) g_wxTabPanel->AddPage(panel, name); } +void create_combochecklist(wxComboCtrl* comboCtrl, std::string text, std::string items, bool initial_value) +{ + wxCheckListBoxComboPopup* popup = new wxCheckListBoxComboPopup(-1); + if (popup != nullptr) + { + comboCtrl->SetPopupControl(popup); + popup->SetStringValue(text); + popup->Connect(-1, wxEVT_CHECKLISTBOX, wxCommandEventHandler(wxCheckListBoxComboPopup::OnCheckListBox), nullptr, popup); + popup->Connect(-1, wxEVT_LISTBOX, wxCommandEventHandler(wxCheckListBoxComboPopup::OnListBoxSelection), nullptr, popup); + + std::vector items_str; + boost::split(items_str, items, boost::is_any_of("|"), boost::token_compress_off); + + for (const std::string& item : items_str) + { + popup->Append(item); + } + + for (unsigned int i = 0; i < popup->GetCount(); ++i) + { + popup->Check(i, initial_value); + } + } +} + +int combochecklist_get_flags(wxComboCtrl* comboCtrl) +{ + int flags = 0; + + wxCheckListBoxComboPopup* popup = wxDynamicCast(comboCtrl->GetPopupControl(), wxCheckListBoxComboPopup); + if (popup != nullptr) + { + for (unsigned int i = 0; i < popup->GetCount(); ++i) + { + if (popup->IsChecked(i)) + flags += (int)std::pow(2.0f, (float)i); + } + } + + return flags; +} + } } diff --git a/xs/src/slic3r/GUI/GUI.hpp b/xs/src/slic3r/GUI/GUI.hpp index 3634e0bc8..f15ba15d6 100644 --- a/xs/src/slic3r/GUI/GUI.hpp +++ b/xs/src/slic3r/GUI/GUI.hpp @@ -8,6 +8,7 @@ class wxApp; class wxFrame; class wxMenuBar; class wxNotebook; +class wxComboCtrl; namespace Slic3r { namespace GUI { @@ -27,6 +28,16 @@ void add_debug_menu(wxMenuBar *menu); // add it at the end of the tab panel. void create_preset_tab(const char *name); -} } +// Creates a wxCheckListBoxComboPopup inside the given wxComboCtrl, filled with the given text and items. +// Items are all initialized to the given value. +// Items must be separated by '|', for example "Item1|Item2|Item3", and so on. +void create_combochecklist(wxComboCtrl* comboCtrl, std::string text, std::string items, bool initial_value); + +// Returns the current state of the items listed in the wxCheckListBoxComboPopup contained in the given wxComboCtrl, +// encoded inside an int. +int combochecklist_get_flags(wxComboCtrl* comboCtrl); + +} +} #endif diff --git a/xs/src/slic3r/GUI/wxExtensions.cpp b/xs/src/slic3r/GUI/wxExtensions.cpp new file mode 100644 index 000000000..d8f0434c7 --- /dev/null +++ b/xs/src/slic3r/GUI/wxExtensions.cpp @@ -0,0 +1,74 @@ +#include "wxExtensions.hpp" + +const unsigned int wxCheckListBoxComboPopup::Height = 200; + +wxCheckListBoxComboPopup::wxCheckListBoxComboPopup(wxWindowID id) + : m_id(id) + , m_text(wxEmptyString) +{ +} + +bool wxCheckListBoxComboPopup::Create(wxWindow* parent) +{ + return wxCheckListBox::Create(parent, m_id, wxPoint(0, 0)); +} + +wxWindow* wxCheckListBoxComboPopup::GetControl() +{ + return this; +} + +void wxCheckListBoxComboPopup::SetStringValue(const wxString& value) +{ + m_text = value; +} + +wxString wxCheckListBoxComboPopup::GetStringValue() const +{ + return m_text; +} + +wxSize wxCheckListBoxComboPopup::GetAdjustedSize(int minWidth, int prefHeight, int maxHeight) +{ + // matches owner wxComboCtrl's width + + wxComboCtrl* cmb = GetComboCtrl(); + if (cmb != nullptr) + { + wxSize size = GetComboCtrl()->GetSize(); + size.SetHeight(Height); + return size; + } + else + return wxSize(200, Height); +} + +void wxCheckListBoxComboPopup::OnCheckListBox(wxCommandEvent& evt) +{ + // forwards the checklistbox event to the owner wxComboCtrl + + wxComboCtrl* cmb = GetComboCtrl(); + if (cmb != nullptr) + { + wxCommandEvent event(wxEVT_CHECKLISTBOX, cmb->GetId()); + cmb->ProcessWindowEvent(event); + } +} + +void wxCheckListBoxComboPopup::OnListBoxSelection(wxCommandEvent& evt) +{ + // transforms list box item selection event into checklistbox item toggle event + + int selId = GetSelection(); + if (selId != wxNOT_FOUND) + { + Toggle((unsigned int)selId); + SetSelection(wxNOT_FOUND); + + wxCommandEvent event(wxEVT_CHECKLISTBOX, GetId()); + event.SetInt(selId); + event.SetEventObject(this); + event.SetString(GetString(selId)); + ProcessEvent(event); + } +} diff --git a/xs/src/slic3r/GUI/wxExtensions.hpp b/xs/src/slic3r/GUI/wxExtensions.hpp new file mode 100644 index 000000000..96d59069d --- /dev/null +++ b/xs/src/slic3r/GUI/wxExtensions.hpp @@ -0,0 +1,27 @@ +#ifndef slic3r_GUI_wxExtensions_hpp_ +#define slic3r_GUI_wxExtensions_hpp_ + +#include +#include + +class wxCheckListBoxComboPopup : public wxCheckListBox, public wxComboPopup +{ + static const unsigned int Height; + + wxWindowID m_id; + wxString m_text; + +public: + explicit wxCheckListBoxComboPopup(wxWindowID id); + + virtual bool Create(wxWindow* parent); + virtual wxWindow* GetControl(); + virtual void SetStringValue(const wxString& value); + virtual wxString GetStringValue() const; + virtual wxSize GetAdjustedSize(int minWidth, int prefHeight, int maxHeight); + + void OnCheckListBox(wxCommandEvent& evt); + void OnListBoxSelection(wxCommandEvent& evt); +}; + +#endif // slic3r_GUI_wxExtensions_hpp_ diff --git a/xs/xsp/GUI.xsp b/xs/xsp/GUI.xsp index d6b55dbf1..3b2c47e26 100644 --- a/xs/xsp/GUI.xsp +++ b/xs/xsp/GUI.xsp @@ -37,3 +37,10 @@ void add_debug_menu(SV *ui) void create_preset_tab(const char *name) %code%{ Slic3r::GUI::create_preset_tab(name); %}; + +void create_combochecklist(SV *ui, std::string text, std::string items, bool initial_value) + %code%{ Slic3r::GUI::create_combochecklist((wxComboCtrl*)wxPli_sv_2_object(aTHX_ ui, "Wx::ComboCtrl"), text, items, initial_value); %}; + +int combochecklist_get_flags(SV *ui) + %code%{ RETVAL=Slic3r::GUI::combochecklist_get_flags((wxComboCtrl*)wxPli_sv_2_object(aTHX_ ui, "Wx::ComboCtrl")); %}; + \ No newline at end of file From a5c47517183ca9721bd97d22830d52a294e59b63 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Fri, 2 Feb 2018 12:58:31 +0100 Subject: [PATCH 20/57] GCode Preview - void wxCheckListBoxComboPopup::OnListBoxSelection(wxCommandEvent& evt) fixed for OsX and Linux --- xs/src/slic3r/GUI/wxExtensions.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xs/src/slic3r/GUI/wxExtensions.cpp b/xs/src/slic3r/GUI/wxExtensions.cpp index d8f0434c7..7fe799019 100644 --- a/xs/src/slic3r/GUI/wxExtensions.cpp +++ b/xs/src/slic3r/GUI/wxExtensions.cpp @@ -62,7 +62,7 @@ void wxCheckListBoxComboPopup::OnListBoxSelection(wxCommandEvent& evt) int selId = GetSelection(); if (selId != wxNOT_FOUND) { - Toggle((unsigned int)selId); + Check((unsigned int)selId, !IsChecked((unsigned int)selId)); SetSelection(wxNOT_FOUND); wxCommandEvent event(wxEVT_CHECKLISTBOX, GetId()); From 556c9c236f2437a4733b783225a1edb7f85561ac Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Fri, 2 Feb 2018 13:28:37 +0100 Subject: [PATCH 21/57] GCode Preview - fixed Linux build (include in GUI.cpp) --- xs/src/slic3r/GUI/GUI.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xs/src/slic3r/GUI/GUI.cpp b/xs/src/slic3r/GUI/GUI.cpp index 7d107ecbc..1f09f19a8 100644 --- a/xs/src/slic3r/GUI/GUI.cpp +++ b/xs/src/slic3r/GUI/GUI.cpp @@ -25,7 +25,7 @@ #include #include -#include "slic3r/gui/wxextensions.hpp" +#include "../../slic3r/gui/wxextensions.hpp" namespace Slic3r { namespace GUI { From fe8dfb9c9b4a4bab5a5d1d19fe09750d2147ee6d Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Fri, 2 Feb 2018 13:56:25 +0100 Subject: [PATCH 22/57] GCode Preview - fixed Linux build (include in GUI.cpp) 2nd attempt --- xs/src/slic3r/GUI/GUI.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xs/src/slic3r/GUI/GUI.cpp b/xs/src/slic3r/GUI/GUI.cpp index 1f09f19a8..749ed0c69 100644 --- a/xs/src/slic3r/GUI/GUI.cpp +++ b/xs/src/slic3r/GUI/GUI.cpp @@ -25,7 +25,7 @@ #include #include -#include "../../slic3r/gui/wxextensions.hpp" +#include "wxExtensions.hpp" namespace Slic3r { namespace GUI { From f20beeab7adf1caa42b47ae6a70f516de18f2197 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Fri, 2 Feb 2018 15:03:06 +0100 Subject: [PATCH 23/57] 3mf Importer - fixed Linux build (makefile) --- xs/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xs/CMakeLists.txt b/xs/CMakeLists.txt index fbddc31e6..f1f0c692b 100644 --- a/xs/CMakeLists.txt +++ b/xs/CMakeLists.txt @@ -74,8 +74,8 @@ add_library(libslic3r STATIC ${LIBDIR}/libslic3r/Fill/FillRectilinear3.hpp ${LIBDIR}/libslic3r/Flow.cpp ${LIBDIR}/libslic3r/Flow.hpp - ${LIBDIR}/libslic3r/Format/3MF.cpp - ${LIBDIR}/libslic3r/Format/3MF.hpp + ${LIBDIR}/libslic3r/Format/3mf.cpp + ${LIBDIR}/libslic3r/Format/3mf.hpp ${LIBDIR}/libslic3r/Format/AMF.cpp ${LIBDIR}/libslic3r/Format/AMF.hpp ${LIBDIR}/libslic3r/Format/OBJ.cpp From ea9920e5d679e2deb19e553ee504cafea7b89714 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Fri, 2 Feb 2018 19:48:16 +0100 Subject: [PATCH 24/57] Fix of Negative Feedrates: G1 F-3.84007e+006 stops smoothie The problem was caused by the gap fill algorithm, which worked with square extrusion width values as with rounded extrusion widths, which sometimes lead to negative extrusion cross sections for high height to width ratios. The extrusion width logic has been changed to consider the input width to be the extrusion spacing, not the extrusion width. The change certainly removed the negative feed rates, but it also certainly increased the gap fill width to some exent. It needs to be verified now, whether the gap fill does not extrude too much. https://github.com/prusa3d/Slic3r/issues/677 --- xs/src/libslic3r/PerimeterGenerator.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/xs/src/libslic3r/PerimeterGenerator.cpp b/xs/src/libslic3r/PerimeterGenerator.cpp index bffd46d0f..ea9c73fa4 100644 --- a/xs/src/libslic3r/PerimeterGenerator.cpp +++ b/xs/src/libslic3r/PerimeterGenerator.cpp @@ -483,8 +483,9 @@ PerimeterGenerator::_variable_width(const ThickPolylines &polylines, ExtrusionRo if (path.polyline.points.empty()) { path.polyline.append(line.a); path.polyline.append(line.b); - - flow.width = unscale(w); + // Convert from spacing to extrusion width based on the extrusion model + // of a square extrusion ended with semi circles. + flow.width = unscale(w) + flow.height * (1. - 0.25 * PI); #ifdef SLIC3R_DEBUG printf(" filling %f gap\n", flow.width); #endif From f9dd251276c997b503c845ea9678291c1e3239b2 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Mon, 5 Feb 2018 13:16:08 +0100 Subject: [PATCH 25/57] GCode Preview - Added feature type for wipe tower --- lib/Slic3r/GUI/Plater/3DPreview.pm | 2 +- xs/src/libslic3r/ExtrusionEntity.hpp | 1 + xs/src/libslic3r/GCode.cpp | 2 ++ xs/src/libslic3r/GCode/Analyzer.cpp | 37 ++++++++++++--------- xs/src/libslic3r/GCode/Analyzer.hpp | 2 ++ xs/src/libslic3r/GCode/WipeTowerPrusaMM.cpp | 17 ++++++++++ 6 files changed, 45 insertions(+), 16 deletions(-) diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index ed84135e2..af0cb16c8 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -77,7 +77,7 @@ sub new { $combochecklist_features->UseAltPopupWindow(); $combochecklist_features->EnablePopupAnimation(0); my $feature_text = "Feature types"; - my $feature_items = "Perimeter|External perimeter|Overhang perimeter|Internal infill|Solid infill|Top solid infill|Bridge infill|Gap fill|Skirt|Support material|Support material interface"; + my $feature_items = "Perimeter|External perimeter|Overhang perimeter|Internal infill|Solid infill|Top solid infill|Bridge infill|Gap fill|Skirt|Support material|Support material interface|Wipe tower"; Slic3r::GUI::create_combochecklist($combochecklist_features, $feature_text, $feature_items, 1); my $checkbox_travel = Wx::CheckBox->new($self, -1, "Travel"); diff --git a/xs/src/libslic3r/ExtrusionEntity.hpp b/xs/src/libslic3r/ExtrusionEntity.hpp index a85ccda06..650a806f6 100644 --- a/xs/src/libslic3r/ExtrusionEntity.hpp +++ b/xs/src/libslic3r/ExtrusionEntity.hpp @@ -25,6 +25,7 @@ enum ExtrusionRole { erSkirt, erSupportMaterial, erSupportMaterialInterface, + erWipeTower, // Extrusion role for a collection with multiple extrusion roles. erMixed, }; diff --git a/xs/src/libslic3r/GCode.cpp b/xs/src/libslic3r/GCode.cpp index 14402a1e1..c256268e5 100644 --- a/xs/src/libslic3r/GCode.cpp +++ b/xs/src/libslic3r/GCode.cpp @@ -1454,7 +1454,9 @@ static inline const char* ExtrusionRole2String(const ExtrusionRole role) case erSkirt: return "erSkirt"; case erSupportMaterial: return "erSupportMaterial"; case erSupportMaterialInterface: return "erSupportMaterialInterface"; + case erWipeTower: return "erWipeTower"; case erMixed: return "erMixed"; + default: return "erInvalid"; }; } diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index 2ddb319fc..b4d7f2596 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -195,19 +195,20 @@ GCodeAnalyzer::PreviewData::LegendItem::LegendItem(const std::string& text, cons const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Extrusion::Default_Extrusion_Role_Colors[Num_Extrusion_Roles] = { - Color(0.0f, 0.0f, 0.0f, 1.0f), // erNone - Color(1.0f, 0.0f, 0.0f, 1.0f), // erPerimeter - Color(0.0f, 1.0f, 0.0f, 1.0f), // erExternalPerimeter - Color(0.0f, 0.0f, 1.0f, 1.0f), // erOverhangPerimeter - Color(1.0f, 1.0f, 0.0f, 1.0f), // erInternalInfill - Color(1.0f, 0.0f, 1.0f, 1.0f), // erSolidInfill - Color(0.0f, 1.0f, 1.0f, 1.0f), // erTopSolidInfill - Color(0.5f, 0.5f, 0.5f, 1.0f), // erBridgeInfill - Color(1.0f, 1.0f, 1.0f, 1.0f), // erGapFill - Color(0.5f, 0.0f, 0.0f, 1.0f), // erSkirt - Color(0.0f, 0.5f, 0.0f, 1.0f), // erSupportMaterial - Color(0.0f, 0.0f, 0.5f, 1.0f), // erSupportMaterialInterface - Color(0.0f, 0.0f, 0.0f, 1.0f) // erMixed + Color(0.0f, 0.0f, 0.0f, 1.0f), // erNone + Color(1.0f, 0.0f, 0.0f, 1.0f), // erPerimeter + Color(0.0f, 1.0f, 0.0f, 1.0f), // erExternalPerimeter + Color(0.0f, 0.0f, 1.0f, 1.0f), // erOverhangPerimeter + Color(1.0f, 1.0f, 0.0f, 1.0f), // erInternalInfill + Color(1.0f, 0.0f, 1.0f, 1.0f), // erSolidInfill + Color(0.0f, 1.0f, 1.0f, 1.0f), // erTopSolidInfill + Color(0.5f, 0.5f, 0.5f, 1.0f), // erBridgeInfill + Color(1.0f, 1.0f, 1.0f, 1.0f), // erGapFill + Color(0.5f, 0.0f, 0.0f, 1.0f), // erSkirt + Color(0.0f, 0.5f, 0.0f, 1.0f), // erSupportMaterial + Color(0.0f, 0.0f, 0.5f, 1.0f), // erSupportMaterialInterface + Color(0.7f, 0.89f, 0.67f, 1.0f), // erWipeTower + Color(0.0f, 0.0f, 0.0f, 1.0f) // erMixed }; // todo: merge with Slic3r::ExtrusionRole2String() from GCode.cpp @@ -225,6 +226,7 @@ const std::string GCodeAnalyzer::PreviewData::Extrusion::Default_Extrusion_Role_ "Skirt", "Support material", "Support material interface", + "Wipe tower", "Mixed" }; @@ -258,7 +260,7 @@ bool GCodeAnalyzer::PreviewData::Extrusion::is_role_flag_set(ExtrusionRole role) bool GCodeAnalyzer::PreviewData::Extrusion::is_role_flag_set(unsigned int flags, ExtrusionRole role) { - if ((role < erPerimeter) || (erSupportMaterialInterface < role)) + if (!is_valid_extrusion_role(role)) return false; unsigned int flag = (unsigned int)::exp2((double)(role - erPerimeter)); @@ -458,6 +460,11 @@ void GCodeAnalyzer::calc_gcode_preview_data(Print& print) _calc_gcode_preview_unretractions(print); } +bool GCodeAnalyzer::is_valid_extrusion_role(ExtrusionRole role) +{ + return ((erPerimeter <= role) && (role < erMixed)); +} + void GCodeAnalyzer::_process_gcode_line(GCodeReader&, const GCodeReader::GCodeLine& line) { // processes 'special' comments contained in line @@ -597,7 +604,7 @@ void GCodeAnalyzer::_processG1(const GCodeReader::GCodeLine& line) type = GCodeMove::Move; ExtrusionRole role = _get_extrusion_role(); - if ((type == GCodeMove::Extrude) && ((_get_width() == 0.0f) || (_get_height() == 0.0f) || (role < erPerimeter) || (erSupportMaterialInterface < role))) + if ((type == GCodeMove::Extrude) && ((_get_width() == 0.0f) || (_get_height() == 0.0f) || !is_valid_extrusion_role(role))) type = GCodeMove::Move; // updates axis positions diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index a72874a35..1671c35ca 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -293,6 +293,8 @@ public: // Calculates all data needed for gcode visualization void calc_gcode_preview_data(Print& print); + static bool is_valid_extrusion_role(ExtrusionRole role); + private: // Processes the given gcode line void _process_gcode_line(GCodeReader& reader, const GCodeReader::GCodeLine& line); diff --git a/xs/src/libslic3r/GCode/WipeTowerPrusaMM.cpp b/xs/src/libslic3r/GCode/WipeTowerPrusaMM.cpp index 858845e3d..99c6c757f 100644 --- a/xs/src/libslic3r/GCode/WipeTowerPrusaMM.cpp +++ b/xs/src/libslic3r/GCode/WipeTowerPrusaMM.cpp @@ -6,6 +6,8 @@ #include #include +#include "Analyzer.hpp" + #if defined(__linux) || defined(__GNUC__ ) #include #endif /* __linux */ @@ -419,6 +421,11 @@ WipeTower::ToolChangeResult WipeTowerPrusaMM::prime( // Increase the extruder driver current to allow fast ramming. .set_extruder_trimpot(750); + // adds tag for analyzer + char buf[32]; + sprintf(buf, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), erWipeTower); + writer.append(buf); + if (purpose == PURPOSE_EXTRUDE || purpose == PURPOSE_MOVE_TO_TOWER_AND_EXTRUDE) { float y_end = 0.f; for (size_t idx_tool = 0; idx_tool < tools.size(); ++ idx_tool) { @@ -554,6 +561,11 @@ WipeTower::ToolChangeResult WipeTowerPrusaMM::tool_change(unsigned int tool, boo writer.set_initial_position(initial_position); } + // adds tag for analyzer + char buf[32]; + sprintf(buf, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), erWipeTower); + writer.append(buf); + if (purpose == PURPOSE_EXTRUDE || purpose == PURPOSE_MOVE_TO_TOWER_AND_EXTRUDE) { // Increase the extruder driver current to allow fast ramming. writer.set_extruder_trimpot(750); @@ -637,6 +649,11 @@ WipeTower::ToolChangeResult WipeTowerPrusaMM::toolchange_Brim(Purpose purpose, b else writer.set_initial_position(initial_position); + // adds tag for analyzer + char buf[32]; + sprintf(buf, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), erWipeTower); + writer.append(buf); + if (purpose == PURPOSE_EXTRUDE || purpose == PURPOSE_MOVE_TO_TOWER_AND_EXTRUDE) { // Prime the extruder 10*m_perimeter_width left along the vertical edge of the wipe tower. writer.extrude_explicit(wipeTower_box.ld - xy(m_perimeter_width * 6.f, 0), From 6ff9021e040e9cc4ed7d20e5772600122f2af7de Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Tue, 6 Feb 2018 12:43:25 +0100 Subject: [PATCH 26/57] GCode Preview - Legend texture shown only when gcode is available --- lib/Slic3r/GUI/3DScene.pm | 32 ++++++++++++++++++------------ lib/Slic3r/GUI/Plater.pm | 2 ++ lib/Slic3r/GUI/Plater/3DPreview.pm | 3 +++ xs/src/slic3r/GUI/3DScene.cpp | 17 +++++++++++++++- xs/src/slic3r/GUI/3DScene.hpp | 6 ++++++ xs/src/slic3r/GUI/GUI.cpp | 9 ++++++--- xs/src/slic3r/GUI/wxExtensions.cpp | 12 +++-------- xs/src/slic3r/GUI/wxExtensions.hpp | 3 --- xs/xsp/GUI_3DScene.xsp | 7 ++++++- 9 files changed, 61 insertions(+), 30 deletions(-) diff --git a/lib/Slic3r/GUI/3DScene.pm b/lib/Slic3r/GUI/3DScene.pm index daceb8c49..f567c2f72 100644 --- a/lib/Slic3r/GUI/3DScene.pm +++ b/lib/Slic3r/GUI/3DScene.pm @@ -1605,23 +1605,25 @@ sub draw_legend { my $tex_id = Slic3r::GUI::_3DScene::get_legend_texture_id; if ($tex_id > 0) { - glDisable(GL_DEPTH_TEST); - glPushMatrix(); - glLoadIdentity(); - my $tex_w = Slic3r::GUI::_3DScene::get_legend_texture_width; my $tex_h = Slic3r::GUI::_3DScene::get_legend_texture_height; - - my ($cw, $ch) = $self->GetSizeWH; + if (($tex_w > 0) && ($tex_h > 0)) + { + glDisable(GL_DEPTH_TEST); + glPushMatrix(); + glLoadIdentity(); + + my ($cw, $ch) = $self->GetSizeWH; - my $l = (-0.5 * $cw) / $self->_zoom; - my $t = (0.5 * $ch) / $self->_zoom; - my $r = $l + $tex_w / $self->_zoom; - my $b = $t - $tex_h / $self->_zoom; - $self->_render_texture($tex_id, $l, $r, $b, $t); + my $l = (-0.5 * $cw) / $self->_zoom; + my $t = (0.5 * $ch) / $self->_zoom; + my $r = $l + $tex_w / $self->_zoom; + my $b = $t - $tex_h / $self->_zoom; + $self->_render_texture($tex_id, $l, $r, $b, $t); - glPopMatrix(); - glEnable(GL_DEPTH_TEST); + glPopMatrix(); + glEnable(GL_DEPTH_TEST); + } } } } @@ -2038,4 +2040,8 @@ sub set_toolpaths_range { $self->volumes->set_range($min_z, $max_z); } +sub reset_legend_texture { + Slic3r::GUI::_3DScene::reset_legend_texture(); +} + 1; diff --git a/lib/Slic3r/GUI/Plater.pm b/lib/Slic3r/GUI/Plater.pm index 321bb7112..014aee53c 100644 --- a/lib/Slic3r/GUI/Plater.pm +++ b/lib/Slic3r/GUI/Plater.pm @@ -1261,6 +1261,8 @@ sub reslice { $self->stop_background_process; # Rather perform one additional unnecessary update of the print object instead of skipping a pending async update. $self->async_apply_config; + # Reset gcode data + $self->{print}->clear_gcode_preview_data; $self->statusbar->SetCancelCallback(sub { $self->stop_background_process; $self->statusbar->SetStatusText("Slicing cancelled"); diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index af0cb16c8..9c3c95d1a 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -290,6 +290,9 @@ sub load_print { $self->set_z_range(0,0); $self->slider_low->Hide; $self->slider_high->Hide; + $self->{z_label_low}->SetLabel(""); + $self->{z_label_high}->SetLabel(""); + $self->canvas->reset_legend_texture(); $self->canvas->Refresh; # clears canvas return; } diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index 589a23e86..15e905ee4 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -1229,6 +1229,11 @@ unsigned int _3DScene::LegendTexture::get_texture_height() const return m_tex_height; } +void _3DScene::LegendTexture::reset_texture() +{ + _destroy_texture(); +} + bool _3DScene::LegendTexture::_create_texture(const Print& print, const wxBitmap& bitmap) { if ((m_tex_width == 0) || (m_tex_height == 0)) @@ -1270,6 +1275,8 @@ void _3DScene::LegendTexture::_destroy_texture() { ::glDeleteTextures(1, &m_tex_id); m_tex_id = 0; + m_tex_height = 0; + m_tex_width = 0; } } @@ -1316,7 +1323,10 @@ void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volume _load_gcode_retractions(*print, *volumes, use_VBOs); _load_gcode_unretractions(*print, *volumes, use_VBOs); - _generate_legend_texture(*print); + if (volumes->empty()) + reset_legend_texture(); + else + _generate_legend_texture(*print); } _update_gcode_volumes_visibility(*print, *volumes); @@ -1337,6 +1347,11 @@ unsigned int _3DScene::get_legend_texture_height() return s_legend_texture.get_texture_height(); } +void _3DScene::reset_legend_texture() +{ + s_legend_texture.reset_texture(); +} + // Create 3D thick extrusion lines for a skirt and brim. // Adds a new Slic3r::GUI::3DScene::Volume to volumes. void _3DScene::_load_print_toolpaths( diff --git a/xs/src/slic3r/GUI/3DScene.hpp b/xs/src/slic3r/GUI/3DScene.hpp index ba1a9af71..4c73bdb7d 100644 --- a/xs/src/slic3r/GUI/3DScene.hpp +++ b/xs/src/slic3r/GUI/3DScene.hpp @@ -403,20 +403,26 @@ class _3DScene unsigned int get_texture_width() const; unsigned int get_texture_height() const; + void reset_texture(); + private: bool _create_texture(const Print& print, const wxBitmap& bitmap); void _destroy_texture(); }; static LegendTexture s_legend_texture; + public: static void _glew_init(); static void load_gcode_preview(const Print* print, GLVolumeCollection* volumes, bool use_VBOs); + static unsigned int get_legend_texture_id(); static unsigned int get_legend_texture_width(); static unsigned int get_legend_texture_height(); + static void reset_legend_texture(); + static void _load_print_toolpaths( const Print *print, GLVolumeCollection *volumes, diff --git a/xs/src/slic3r/GUI/GUI.cpp b/xs/src/slic3r/GUI/GUI.cpp index 749ed0c69..775cfdcf6 100644 --- a/xs/src/slic3r/GUI/GUI.cpp +++ b/xs/src/slic3r/GUI/GUI.cpp @@ -191,13 +191,16 @@ void create_preset_tab(const char *name) void create_combochecklist(wxComboCtrl* comboCtrl, std::string text, std::string items, bool initial_value) { - wxCheckListBoxComboPopup* popup = new wxCheckListBoxComboPopup(-1); + if (comboCtrl == nullptr) + return; + + wxCheckListBoxComboPopup* popup = new wxCheckListBoxComboPopup; if (popup != nullptr) { comboCtrl->SetPopupControl(popup); popup->SetStringValue(text); - popup->Connect(-1, wxEVT_CHECKLISTBOX, wxCommandEventHandler(wxCheckListBoxComboPopup::OnCheckListBox), nullptr, popup); - popup->Connect(-1, wxEVT_LISTBOX, wxCommandEventHandler(wxCheckListBoxComboPopup::OnListBoxSelection), nullptr, popup); + popup->Connect(wxID_ANY, wxEVT_CHECKLISTBOX, wxCommandEventHandler(wxCheckListBoxComboPopup::OnCheckListBox), nullptr, popup); + popup->Connect(wxID_ANY, wxEVT_LISTBOX, wxCommandEventHandler(wxCheckListBoxComboPopup::OnListBoxSelection), nullptr, popup); std::vector items_str; boost::split(items_str, items, boost::is_any_of("|"), boost::token_compress_off); diff --git a/xs/src/slic3r/GUI/wxExtensions.cpp b/xs/src/slic3r/GUI/wxExtensions.cpp index 7fe799019..b5f0595f8 100644 --- a/xs/src/slic3r/GUI/wxExtensions.cpp +++ b/xs/src/slic3r/GUI/wxExtensions.cpp @@ -1,16 +1,10 @@ #include "wxExtensions.hpp" -const unsigned int wxCheckListBoxComboPopup::Height = 200; - -wxCheckListBoxComboPopup::wxCheckListBoxComboPopup(wxWindowID id) - : m_id(id) - , m_text(wxEmptyString) -{ -} +const unsigned int wxCheckListBoxComboPopup::Height = 210; bool wxCheckListBoxComboPopup::Create(wxWindow* parent) { - return wxCheckListBox::Create(parent, m_id, wxPoint(0, 0)); + return wxCheckListBox::Create(parent, wxID_HIGHEST + 1, wxPoint(0, 0)); } wxWindow* wxCheckListBoxComboPopup::GetControl() @@ -51,6 +45,7 @@ void wxCheckListBoxComboPopup::OnCheckListBox(wxCommandEvent& evt) if (cmb != nullptr) { wxCommandEvent event(wxEVT_CHECKLISTBOX, cmb->GetId()); + event.SetEventObject(cmb); cmb->ProcessWindowEvent(event); } } @@ -68,7 +63,6 @@ void wxCheckListBoxComboPopup::OnListBoxSelection(wxCommandEvent& evt) wxCommandEvent event(wxEVT_CHECKLISTBOX, GetId()); event.SetInt(selId); event.SetEventObject(this); - event.SetString(GetString(selId)); ProcessEvent(event); } } diff --git a/xs/src/slic3r/GUI/wxExtensions.hpp b/xs/src/slic3r/GUI/wxExtensions.hpp index 96d59069d..8e62f766c 100644 --- a/xs/src/slic3r/GUI/wxExtensions.hpp +++ b/xs/src/slic3r/GUI/wxExtensions.hpp @@ -8,12 +8,9 @@ class wxCheckListBoxComboPopup : public wxCheckListBox, public wxComboPopup { static const unsigned int Height; - wxWindowID m_id; wxString m_text; public: - explicit wxCheckListBoxComboPopup(wxWindowID id); - virtual bool Create(wxWindow* parent); virtual wxWindow* GetControl(); virtual void SetStringValue(const wxString& value); diff --git a/xs/xsp/GUI_3DScene.xsp b/xs/xsp/GUI_3DScene.xsp index f6d729f98..6c56a06d9 100644 --- a/xs/xsp/GUI_3DScene.xsp +++ b/xs/xsp/GUI_3DScene.xsp @@ -161,7 +161,12 @@ get_legend_texture_height() RETVAL = _3DScene::get_legend_texture_height(); OUTPUT: RETVAL - + +void +reset_legend_texture() + CODE: + _3DScene::reset_legend_texture(); + void _load_print_toolpaths(print, volumes, tool_colors, use_VBOs) Print *print; From 0d6a0136583850038f7e905daf674dececb6e00d Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Wed, 7 Feb 2018 09:07:37 +0100 Subject: [PATCH 27/57] GCode Preview - Coloring by tool --- lib/Slic3r/GUI/3DScene.pm | 4 +- lib/Slic3r/GUI/Plater/3DPreview.pm | 45 +--- xs/src/libslic3r/ExtrusionEntity.hpp | 16 +- xs/src/libslic3r/GCode/Analyzer.cpp | 42 +++- xs/src/libslic3r/GCode/Analyzer.hpp | 6 +- xs/src/slic3r/GUI/3DScene.cpp | 347 +++++++++++++++++---------- xs/src/slic3r/GUI/3DScene.hpp | 13 +- xs/xsp/GUI_3DScene.xsp | 11 +- 8 files changed, 289 insertions(+), 195 deletions(-) diff --git a/lib/Slic3r/GUI/3DScene.pm b/lib/Slic3r/GUI/3DScene.pm index f567c2f72..f63dad079 100644 --- a/lib/Slic3r/GUI/3DScene.pm +++ b/lib/Slic3r/GUI/3DScene.pm @@ -2029,10 +2029,10 @@ sub load_wipe_tower_toolpaths { } sub load_gcode_preview { - my ($self, $print) = @_; + my ($self, $print, $colors) = @_; $self->SetCurrent($self->GetContext) if $self->UseVBOs; - Slic3r::GUI::_3DScene::load_gcode_preview($print, $self->volumes, $self->UseVBOs); + Slic3r::GUI::_3DScene::load_gcode_preview($print, $self->volumes, $colors, $self->UseVBOs); } sub set_toolpaths_range { diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index 9c3c95d1a..2b853dbb3 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -17,7 +17,6 @@ sub new { my $self = $class->SUPER::new($parent, -1, wxDefaultPosition); $self->{config} = $config; $self->{number_extruders} = 1; - $self->{preferred_color_mode} = 'feature'; $self->auto_zoom(1); # init GUI elements @@ -57,9 +56,7 @@ sub new { $z_label_high->SetFont($Slic3r::GUI::small_font); $self->single_layer(0); - $self->{color_by_extruder} = 0; my $checkbox_singlelayer = $self->{checkbox_singlelayer} = Wx::CheckBox->new($self, -1, "1 Layer"); - my $checkbox_color_by_extruder = $self->{checkbox_color_by_extruder} = Wx::CheckBox->new($self, -1, "Tool"); my $label_view_type = $self->{label_view_type} = Wx::StaticText->new($self, -1, "View"); @@ -68,6 +65,7 @@ sub new { $choice_view_type->Append("Height"); $choice_view_type->Append("Width"); $choice_view_type->Append("Speed"); + $choice_view_type->Append("Tool"); $choice_view_type->SetSelection(0); my $label_show_features = $self->{label_show_features} = Wx::StaticText->new($self, -1, "Show"); @@ -96,7 +94,6 @@ sub new { $hsizer->Add($vsizer, 0, wxEXPAND, 0); $vsizer_outer->Add($hsizer, 3, wxALIGN_CENTER_HORIZONTAL, 0); $vsizer_outer->Add($checkbox_singlelayer, 0, wxTOP | wxALIGN_CENTER_HORIZONTAL, 5); - $vsizer_outer->Add($checkbox_color_by_extruder, 0, wxTOP | wxALIGN_CENTER_HORIZONTAL, 5); my $bottom_sizer = Wx::BoxSizer->new(wxHORIZONTAL); $bottom_sizer->Add($label_view_type, 0, wxALIGN_CENTER_VERTICAL, 5); @@ -188,12 +185,6 @@ sub new { $self->set_z_idx_high($slider_high->GetValue); } }); - EVT_CHECKBOX($self, $checkbox_color_by_extruder, sub { - $self->{color_by_extruder} = $checkbox_color_by_extruder->GetValue(); - $self->{preferred_color_mode} = $self->{color_by_extruder} ? 'tool' : 'feature'; - $self->reload_print; - }); - EVT_CHOICE($self, $choice_view_type, sub { my $selection = $choice_view_type->GetCurrentSelection(); $self->print->set_gcode_preview_type($selection); @@ -322,33 +313,19 @@ sub load_print { $self->slider_high->Show; $self->Layout; - my $by_tool = $self->{color_by_extruder}; - if ($self->{preferred_color_mode} eq 'tool_or_feature') { - # It is left to Slic3r to decide whether the print shall be colored by the tool or by the feature. - # Color by feature if it is a single extruder print. - my $extruders = $self->{print}->extruders; - $by_tool = scalar(@{$extruders}) > 1; - $self->{color_by_extruder} = $by_tool; - $self->{checkbox_color_by_extruder}->SetValue($by_tool); - $self->{preferred_color_mode} = 'tool_or_feature'; - } - # Collect colors per extruder. - # Leave it empty, if the print should be colored by a feature. my @colors = (); - if ($by_tool) { - my @extruder_colors = @{$self->{config}->extruder_colour}; - my @filament_colors = @{$self->{config}->filament_colour}; - for (my $i = 0; $i <= $#extruder_colors; $i += 1) { - my $color = $extruder_colors[$i]; - $color = $filament_colors[$i] if (! defined($color) || $color !~ m/^#[[:xdigit:]]{6}/); - $color = '#FFFFFF' if (! defined($color) || $color !~ m/^#[[:xdigit:]]{6}/); - push @colors, $color; - } + my @extruder_colors = @{$self->{config}->extruder_colour}; + my @filament_colors = @{$self->{config}->filament_colour}; + for (my $i = 0; $i <= $#extruder_colors; $i += 1) { + my $color = $extruder_colors[$i]; + $color = $filament_colors[$i] if (! defined($color) || $color !~ m/^#[[:xdigit:]]{6}/); + $color = '#FFFFFF' if (! defined($color) || $color !~ m/^#[[:xdigit:]]{6}/); + push @colors, $color; } if ($self->IsShown) { - $self->canvas->load_gcode_preview($self->print); + $self->canvas->load_gcode_preview($self->print, \@colors); # # load skirt and brim # $self->canvas->load_print_toolpaths($self->print, \@colors); @@ -417,10 +394,6 @@ sub set_number_extruders { my ($self, $number_extruders) = @_; if ($self->{number_extruders} != $number_extruders) { $self->{number_extruders} = $number_extruders; - my $by_tool = $number_extruders > 1; - $self->{color_by_extruder} = $by_tool; - $self->{checkbox_color_by_extruder}->SetValue($by_tool); - $self->{preferred_color_mode} = $by_tool ? 'tool_or_feature' : 'feature'; } } diff --git a/xs/src/libslic3r/ExtrusionEntity.hpp b/xs/src/libslic3r/ExtrusionEntity.hpp index 650a806f6..f5e243419 100644 --- a/xs/src/libslic3r/ExtrusionEntity.hpp +++ b/xs/src/libslic3r/ExtrusionEntity.hpp @@ -107,15 +107,17 @@ public: float height; // Feedrate of the extrusion, used for visualization purposed. float feedrate; + // Id of the extruder, used for visualization purposed. + unsigned int extruder_id; - ExtrusionPath(ExtrusionRole role) : mm3_per_mm(-1), width(-1), height(-1), feedrate(0.0f), m_role(role) {}; - ExtrusionPath(ExtrusionRole role, double mm3_per_mm, float width, float height) : mm3_per_mm(mm3_per_mm), width(width), height(height), feedrate(0.0f), m_role(role) {}; - ExtrusionPath(const ExtrusionPath &rhs) : polyline(rhs.polyline), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), feedrate(rhs.feedrate), m_role(rhs.m_role) {} - ExtrusionPath(ExtrusionPath &&rhs) : polyline(std::move(rhs.polyline)), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), feedrate(rhs.feedrate), m_role(rhs.m_role) {} -// ExtrusionPath(ExtrusionRole role, const Flow &flow) : m_role(role), mm3_per_mm(flow.mm3_per_mm()), width(flow.width), height(flow.height), feedrate(0.0f) {}; + ExtrusionPath(ExtrusionRole role) : mm3_per_mm(-1), width(-1), height(-1), feedrate(0.0f), extruder_id(0), m_role(role) {}; + ExtrusionPath(ExtrusionRole role, double mm3_per_mm, float width, float height) : mm3_per_mm(mm3_per_mm), width(width), height(height), feedrate(0.0f), extruder_id(0), m_role(role) {}; + ExtrusionPath(const ExtrusionPath &rhs) : polyline(rhs.polyline), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), feedrate(rhs.feedrate), extruder_id(rhs.extruder_id), m_role(rhs.m_role) {} + ExtrusionPath(ExtrusionPath &&rhs) : polyline(std::move(rhs.polyline)), mm3_per_mm(rhs.mm3_per_mm), width(rhs.width), height(rhs.height), feedrate(rhs.feedrate), extruder_id(rhs.extruder_id), m_role(rhs.m_role) {} +// ExtrusionPath(ExtrusionRole role, const Flow &flow) : m_role(role), mm3_per_mm(flow.mm3_per_mm()), width(flow.width), height(flow.height), feedrate(0.0f), extruder_id(0) {}; - ExtrusionPath& operator=(const ExtrusionPath &rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->feedrate = rhs.feedrate, this->polyline = rhs.polyline; return *this; } - ExtrusionPath& operator=(ExtrusionPath &&rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->feedrate = rhs.feedrate, this->polyline = std::move(rhs.polyline); return *this; } + ExtrusionPath& operator=(const ExtrusionPath &rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->feedrate = rhs.feedrate, this->extruder_id = rhs.extruder_id, this->polyline = rhs.polyline; return *this; } + ExtrusionPath& operator=(ExtrusionPath &&rhs) { this->m_role = rhs.m_role; this->mm3_per_mm = rhs.mm3_per_mm; this->width = rhs.width; this->height = rhs.height; this->feedrate = rhs.feedrate, this->extruder_id = rhs.extruder_id, this->polyline = std::move(rhs.polyline); return *this; } ExtrusionPath* clone() const { return new ExtrusionPath (*this); } void reverse() { this->polyline.reverse(); } diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index b4d7f2596..0288770b0 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -122,10 +122,11 @@ GCodeAnalyzer::PreviewData::Extrusion::Layer::Layer(float z, const ExtrusionPath { } -GCodeAnalyzer::PreviewData::Travel::Polyline::Polyline(EType type, EDirection direction, float feedrate, const Polyline3& polyline) +GCodeAnalyzer::PreviewData::Travel::Polyline::Polyline(EType type, EDirection direction, float feedrate, unsigned int extruder_id, const Polyline3& polyline) : type(type) , direction(direction) , feedrate(feedrate) + , extruder_id(extruder_id) , polyline(polyline) { } @@ -352,12 +353,14 @@ std::string GCodeAnalyzer::PreviewData::get_legend_title() const return "Width (mm)"; case Extrusion::Feedrate: return "Speed (mm/s)"; + case Extrusion::Tool: + return "Tool"; } return ""; } -GCodeAnalyzer::PreviewData::LegendItemsList GCodeAnalyzer::PreviewData::get_legend_items() const +GCodeAnalyzer::PreviewData::LegendItemsList GCodeAnalyzer::PreviewData::get_legend_items(const std::vector& tool_colors) const { struct Helper { @@ -401,6 +404,23 @@ GCodeAnalyzer::PreviewData::LegendItemsList GCodeAnalyzer::PreviewData::get_lege case Extrusion::Feedrate: { Helper::FillListFromRange(items, extrusion.ranges.feedrate, 0, 1.0f); + break; + } + case Extrusion::Tool: + { + unsigned int tools_colors_count = tool_colors.size() / 4; + items.reserve(tools_colors_count); + for (unsigned int i = 0; i < tools_colors_count; ++i) + { + char buf[32]; + sprintf(buf, "Extruder %d", i + 1); + + GCodeAnalyzer::PreviewData::Color color; + ::memcpy((void*)color.rgba, (const void*)(tool_colors.data() + i * 4), 4 * sizeof(float)); + + items.emplace_back(buf, color); + } + break; } } @@ -693,9 +713,8 @@ void GCodeAnalyzer::_processT(const GCodeReader::GCodeLine& line) std::string cmd = line.cmd(); if (cmd.length() > 1) { - int id = (int)::strtol(cmd.substr(1).c_str(), nullptr, 10); - // todo - add id validity check ? - if (_get_extruder_id() != (unsigned int)id) + unsigned int id = (unsigned int)::strtol(cmd.substr(1).c_str(), nullptr, 10); + if (_get_extruder_id() != id) { _set_extruder_id(id); @@ -947,6 +966,7 @@ void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(Print& print) ExtrusionPath path(data.extrusion_role, data.mm3_per_mm, data.width, data.height); path.polyline = polyline; path.feedrate = data.feedrate; + path.extruder_id = data.extruder_id; get_layer_at_z(print.gcode_preview.extrusion.layers, z).paths.push_back(path); } @@ -1010,11 +1030,11 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) { struct Helper { - static void store_polyline(const Polyline3& polyline, PreviewData::Travel::EType type, PreviewData::Travel::Polyline::EDirection direction, float feedrate, Print& print) + static void store_polyline(const Polyline3& polyline, PreviewData::Travel::EType type, PreviewData::Travel::Polyline::EDirection direction, float feedrate, unsigned int extruder_id, Print& print) { // if the polyline is valid, store it if (polyline.is_valid()) - print.gcode_preview.travel.polylines.emplace_back(type, direction, feedrate, polyline); + print.gcode_preview.travel.polylines.emplace_back(type, direction, feedrate, extruder_id, polyline); } }; @@ -1027,6 +1047,7 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) PreviewData::Travel::EType type = PreviewData::Travel::Num_Types; PreviewData::Travel::Polyline::EDirection direction = PreviewData::Travel::Polyline::Num_Directions; float feedrate = FLT_MAX; + unsigned int extruder_id = -1; // constructs the polylines while traversing the moves for (const GCodeMove& move : travel_moves->second) @@ -1034,11 +1055,11 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) PreviewData::Travel::EType move_type = (move.delta_extruder < 0.0f) ? PreviewData::Travel::Retract : ((move.delta_extruder > 0.0f) ? PreviewData::Travel::Extrude : PreviewData::Travel::Move); PreviewData::Travel::Polyline::EDirection move_direction = ((move.start_position.x != move.end_position.x) || (move.start_position.y != move.end_position.y)) ? PreviewData::Travel::Polyline::Generic : PreviewData::Travel::Polyline::Vertical; - if ((type != move_type) || (direction != move_direction) || (feedrate != move.data.feedrate) || (position != move.start_position)) + if ((type != move_type) || (direction != move_direction) || (feedrate != move.data.feedrate) || (position != move.start_position) || (extruder_id != move.data.extruder_id)) { // store current polyline polyline.remove_duplicate_points(); - Helper::store_polyline(polyline, type, direction, feedrate, print); + Helper::store_polyline(polyline, type, direction, feedrate, extruder_id, print); // reset current polyline polyline = Polyline3(); @@ -1055,11 +1076,12 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) position = move.end_position; type = move_type; feedrate = move.data.feedrate; + extruder_id = move.data.extruder_id; } // store last polyline polyline.remove_duplicate_points(); - Helper::store_polyline(polyline, type, direction, feedrate, print); + Helper::store_polyline(polyline, type, direction, feedrate, extruder_id, print); } void GCodeAnalyzer::_calc_gcode_preview_retractions(Print& print) diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index 1671c35ca..34f1537af 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -152,6 +152,7 @@ public: Height, Width, Feedrate, + Tool, Num_View_Types }; @@ -216,9 +217,10 @@ public: EType type; EDirection direction; float feedrate; + unsigned int extruder_id; Polyline3 polyline; - Polyline(EType type, EDirection direction, float feedrate, const Polyline3& polyline); + Polyline(EType type, EDirection direction, float feedrate, unsigned int extruder_id, const Polyline3& polyline); }; typedef std::vector PolylinesList; @@ -270,7 +272,7 @@ public: const Color& get_extrusion_feedrate_color(float feedrate) const; std::string get_legend_title() const; - LegendItemsList get_legend_items() const; + LegendItemsList get_legend_items(const std::vector& tool_colors) const; }; private: diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index 15e905ee4..96cbabbe9 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -1099,13 +1099,13 @@ _3DScene::LegendTexture::~LegendTexture() _destroy_texture(); } -bool _3DScene::LegendTexture::generate_texture(const Print& print) +bool _3DScene::LegendTexture::generate_texture(const Print& print, const std::vector& tool_colors) { _destroy_texture(); // collects items to render const std::string& title = print.gcode_preview.get_legend_title(); - const GCodeAnalyzer::PreviewData::LegendItemsList& items = print.gcode_preview.get_legend_items(); + const GCodeAnalyzer::PreviewData::LegendItemsList& items = print.gcode_preview.get_legend_items(tool_colors); unsigned int items_count = (unsigned int)items.size(); if (items_count == 0) @@ -1312,21 +1312,23 @@ static inline std::vector parse_colors(const std::vector &sc return output; } -void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volumes, bool use_VBOs) +void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volumes, const std::vector& str_tool_colors, bool use_VBOs) { if (volumes->empty()) { + std::vector tool_colors = parse_colors(str_tool_colors); + s_gcode_preview_data.reset(); - _load_gcode_extrusion_paths(*print, *volumes, use_VBOs); - _load_gcode_travel_paths(*print, *volumes, use_VBOs); + _load_gcode_extrusion_paths(*print, *volumes, tool_colors, use_VBOs); + _load_gcode_travel_paths(*print, *volumes, tool_colors, use_VBOs); _load_gcode_retractions(*print, *volumes, use_VBOs); _load_gcode_unretractions(*print, *volumes, use_VBOs); if (volumes->empty()) reset_legend_texture(); else - _generate_legend_texture(*print); + _generate_legend_texture(*print, tool_colors); } _update_gcode_volumes_visibility(*print, *volumes); @@ -1709,7 +1711,7 @@ void _3DScene::_load_wipe_tower_toolpaths( BOOST_LOG_TRIVIAL(debug) << "Loading wipe tower toolpaths in parallel - end"; } -void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) +void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs) { // helper functions to select data in dependence of the extrusion view type struct Helper @@ -1726,12 +1728,14 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio return path.width; case GCodeAnalyzer::PreviewData::Extrusion::Feedrate: return path.feedrate; + case GCodeAnalyzer::PreviewData::Extrusion::Tool: + return (float)path.extruder_id; } return 0.0f; } - static const GCodeAnalyzer::PreviewData::Color& path_color(const GCodeAnalyzer::PreviewData& data, float value) + static const GCodeAnalyzer::PreviewData::Color& path_color(const GCodeAnalyzer::PreviewData& data, const std::vector& tool_colors, float value) { switch (data.extrusion.view_type) { @@ -1743,6 +1747,12 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio return data.get_extrusion_width_color(value); case GCodeAnalyzer::PreviewData::Extrusion::Feedrate: return data.get_extrusion_feedrate_color(value); + case GCodeAnalyzer::PreviewData::Extrusion::Tool: + { + static GCodeAnalyzer::PreviewData::Color color; + ::memcpy((void*)color.rgba, (const void*)(tool_colors.data() + (unsigned int)value * 4), 4 * sizeof(float)); + return color; + } } return GCodeAnalyzer::PreviewData::Color::Dummy; @@ -1801,7 +1811,7 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio { s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Extrusion, (unsigned int)filter.role, (unsigned int)volumes.volumes.size()); - GLVolume* volume = new GLVolume(Helper::path_color(print.gcode_preview, filter.value).rgba); + GLVolume* volume = new GLVolume(Helper::path_color(print.gcode_preview, tool_colors, filter.value).rgba); if (volume != nullptr) { filter.volume = volume; @@ -1856,7 +1866,62 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio } } -void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) +void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs) +{ + size_t initial_volumes_count = volumes.volumes.size(); + s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Travel, 0, (unsigned int)initial_volumes_count); + + bool res = true; + switch (print.gcode_preview.extrusion.view_type) + { + case GCodeAnalyzer::PreviewData::Extrusion::Feedrate: + { + res = _travel_paths_by_feedrate(print, volumes); + break; + } + case GCodeAnalyzer::PreviewData::Extrusion::Tool: + { + res = _travel_paths_by_tool(print, volumes, tool_colors); + break; + } + default: + { + res = _travel_paths_by_type(print, volumes); + break; + } + } + + if (!res) + { + // an error occourred - restore to previous state and return + if (initial_volumes_count != volumes.volumes.size()) + { + std::vector::iterator begin = volumes.volumes.begin() + initial_volumes_count; + std::vector::iterator end = volumes.volumes.end(); + for (std::vector::iterator it = begin; it < end; ++it) + { + GLVolume* volume = *it; + delete volume; + } + volumes.volumes.erase(begin, end); + } + + return; + } + + // finalize volumes and sends geometry to gpu + if (volumes.volumes.size() > initial_volumes_count) + { + for (size_t i = initial_volumes_count; i < volumes.volumes.size(); ++i) + { + GLVolume* volume = volumes.volumes[i]; + volume->bounding_box = volume->indexed_vertex_array.bounding_box(); + volume->indexed_vertex_array.finalize_geometry(use_VBOs); + } + } +} + +bool _3DScene::_travel_paths_by_type(const Print& print, GLVolumeCollection& volumes) { // Helper structure for types struct Type @@ -1878,6 +1943,52 @@ void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& typedef std::vector TypesList; + // colors travels by travel type + + // detects types + TypesList types; + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + { + if (std::find(types.begin(), types.end(), Type(polyline.type)) == types.end()) + types.emplace_back(polyline.type); + } + + // nothing to render, return + if (types.empty()) + return true; + + // creates a new volume for each type + for (Type& type : types) + { + GLVolume* volume = new GLVolume(print.gcode_preview.travel.type_colors[type.value].rgba); + if (volume == nullptr) + return false; + else + { + type.volume = volume; + volumes.volumes.emplace_back(volume); + } + } + + // populates volumes + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + { + TypesList::iterator type = std::find(types.begin(), types.end(), Type(polyline.type)); + if (type != types.end()) + { + type->volume->print_zs.push_back(unscale(polyline.polyline.bounding_box().max.z)); + type->volume->offsets.push_back(type->volume->indexed_vertex_array.quad_indices.size()); + type->volume->offsets.push_back(type->volume->indexed_vertex_array.triangle_indices.size()); + + polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *type->volume); + } + } + + return true; +} + +bool _3DScene::_travel_paths_by_feedrate(const Print& print, GLVolumeCollection& volumes) +{ // Helper structure for feedrate struct Feedrate { @@ -1898,134 +2009,114 @@ void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& typedef std::vector FeedratesList; - size_t initial_volumes_count = volumes.volumes.size(); - s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Travel, 0, (unsigned int)initial_volumes_count); + // colors travels by feedrate - if (print.gcode_preview.extrusion.view_type == GCodeAnalyzer::PreviewData::Extrusion::Feedrate) + // detects feedrates + FeedratesList feedrates; + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) { - // colors travels by feedrate - - // detects feedrates - FeedratesList feedrates; - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) - { - if (std::find(feedrates.begin(), feedrates.end(), Feedrate(polyline.feedrate)) == feedrates.end()) - feedrates.emplace_back(polyline.feedrate); - } - - // nothing to render, return - if (feedrates.empty()) - return; - - // creates a new volume for each feedrate - for (Feedrate& feedrate : feedrates) - { - GLVolume* volume = new GLVolume(print.gcode_preview.get_extrusion_feedrate_color(feedrate.value).rgba); - if (volume != nullptr) - { - feedrate.volume = volume; - volumes.volumes.emplace_back(volume); - } - else - { - // an error occourred - restore to previous state and return - if (initial_volumes_count != volumes.volumes.size()) - { - std::vector::iterator begin = volumes.volumes.begin() + initial_volumes_count; - std::vector::iterator end = volumes.volumes.end(); - for (std::vector::iterator it = begin; it < end; ++it) - { - GLVolume* volume = *it; - delete volume; - } - volumes.volumes.erase(begin, end); - return; - } - } - } - - // populates volumes - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) - { - FeedratesList::iterator feedrate = std::find(feedrates.begin(), feedrates.end(), Feedrate(polyline.feedrate)); - if (feedrate != feedrates.end()) - { - feedrate->volume->print_zs.push_back(unscale(polyline.polyline.bounding_box().max.z)); - feedrate->volume->offsets.push_back(feedrate->volume->indexed_vertex_array.quad_indices.size()); - feedrate->volume->offsets.push_back(feedrate->volume->indexed_vertex_array.triangle_indices.size()); - - polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *feedrate->volume); - } - } + if (std::find(feedrates.begin(), feedrates.end(), Feedrate(polyline.feedrate)) == feedrates.end()) + feedrates.emplace_back(polyline.feedrate); } - else + + // nothing to render, return + if (feedrates.empty()) + return true; + + // creates a new volume for each feedrate + for (Feedrate& feedrate : feedrates) { - // colors travels by travel type - - // detects types - TypesList types; - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + GLVolume* volume = new GLVolume(print.gcode_preview.get_extrusion_feedrate_color(feedrate.value).rgba); + if (volume == nullptr) + return false; + else { - if (std::find(types.begin(), types.end(), Type(polyline.type)) == types.end()) - types.emplace_back(polyline.type); - } - - // nothing to render, return - if (types.empty()) - return; - - // creates a new volume for each type - for (Type& type : types) - { - GLVolume* volume = new GLVolume(print.gcode_preview.travel.type_colors[type.value].rgba); - if (volume != nullptr) - { - type.volume = volume; - volumes.volumes.emplace_back(volume); - } - else - { - // an error occourred - restore to previous state and return - if (initial_volumes_count != volumes.volumes.size()) - { - std::vector::iterator begin = volumes.volumes.begin() + initial_volumes_count; - std::vector::iterator end = volumes.volumes.end(); - for (std::vector::iterator it = begin; it < end; ++it) - { - GLVolume* volume = *it; - delete volume; - } - volumes.volumes.erase(begin, end); - return; - } - } - } - - // populates volumes - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) - { - TypesList::iterator type = std::find(types.begin(), types.end(), Type(polyline.type)); - if (type != types.end()) - { - type->volume->print_zs.push_back(unscale(polyline.polyline.bounding_box().max.z)); - type->volume->offsets.push_back(type->volume->indexed_vertex_array.quad_indices.size()); - type->volume->offsets.push_back(type->volume->indexed_vertex_array.triangle_indices.size()); - - polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *type->volume); - } + feedrate.volume = volume; + volumes.volumes.emplace_back(volume); } } - // finalize volumes and sends geometry to gpu - if (volumes.volumes.size() > initial_volumes_count) + // populates volumes + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) { - for (size_t i = initial_volumes_count; i < volumes.volumes.size(); ++i) + FeedratesList::iterator feedrate = std::find(feedrates.begin(), feedrates.end(), Feedrate(polyline.feedrate)); + if (feedrate != feedrates.end()) { - GLVolume* volume = volumes.volumes[i]; - volume->bounding_box = volume->indexed_vertex_array.bounding_box(); - volume->indexed_vertex_array.finalize_geometry(use_VBOs); + feedrate->volume->print_zs.push_back(unscale(polyline.polyline.bounding_box().max.z)); + feedrate->volume->offsets.push_back(feedrate->volume->indexed_vertex_array.quad_indices.size()); + feedrate->volume->offsets.push_back(feedrate->volume->indexed_vertex_array.triangle_indices.size()); + + polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *feedrate->volume); } } + + return true; +} + +bool _3DScene::_travel_paths_by_tool(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors) +{ + // Helper structure for tool + struct Tool + { + unsigned int value; + GLVolume* volume; + + explicit Tool(unsigned int value) + : value(value) + , volume(nullptr) + { + } + + bool operator == (const Tool& other) const + { + return value == other.value; + } + }; + + typedef std::vector ToolsList; + + // colors travels by tool + + // detects tools + ToolsList tools; + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + { + if (std::find(tools.begin(), tools.end(), Tool(polyline.extruder_id)) == tools.end()) + tools.emplace_back(polyline.extruder_id); + } + + // nothing to render, return + if (tools.empty()) + return true; + + // creates a new volume for each tool + for (Tool& tool : tools) + { + GLVolume* volume = new GLVolume(tool_colors.data() + tool.value * 4); + if (volume == nullptr) + return false; + else + { + tool.volume = volume; + volumes.volumes.emplace_back(volume); + } + } + + // populates volumes + for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + { + ToolsList::iterator tool = std::find(tools.begin(), tools.end(), Tool(polyline.extruder_id)); + if (tool != tools.end()) + { + tool->volume->print_zs.push_back(unscale(polyline.polyline.bounding_box().max.z)); + tool->volume->offsets.push_back(tool->volume->indexed_vertex_array.quad_indices.size()); + tool->volume->offsets.push_back(tool->volume->indexed_vertex_array.triangle_indices.size()); + + polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *tool->volume); + } + } + + return true; } void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) @@ -2128,9 +2219,9 @@ void _3DScene::_update_gcode_volumes_visibility(const Print& print, GLVolumeColl } } -void _3DScene::_generate_legend_texture(const Print& print) +void _3DScene::_generate_legend_texture(const Print& print, const std::vector& tool_colors) { - s_legend_texture.generate_texture(print); + s_legend_texture.generate_texture(print, tool_colors); } } diff --git a/xs/src/slic3r/GUI/3DScene.hpp b/xs/src/slic3r/GUI/3DScene.hpp index 4c73bdb7d..2b7f2de47 100644 --- a/xs/src/slic3r/GUI/3DScene.hpp +++ b/xs/src/slic3r/GUI/3DScene.hpp @@ -397,7 +397,7 @@ class _3DScene LegendTexture(); ~LegendTexture(); - bool generate_texture(const Print& print); + bool generate_texture(const Print& print, const std::vector& tool_colors); unsigned int get_texture_id() const; unsigned int get_texture_width() const; @@ -415,7 +415,7 @@ class _3DScene public: static void _glew_init(); - static void load_gcode_preview(const Print* print, GLVolumeCollection* volumes, bool use_VBOs); + static void load_gcode_preview(const Print* print, GLVolumeCollection* volumes, const std::vector& str_tool_colors, bool use_VBOs); static unsigned int get_legend_texture_id(); static unsigned int get_legend_texture_width(); @@ -443,9 +443,12 @@ public: private: // generates gcode extrusion paths geometry - static void _load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); + static void _load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs); // generates gcode travel paths geometry - static void _load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); + static void _load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs); + static bool _travel_paths_by_type(const Print& print, GLVolumeCollection& volumes); + static bool _travel_paths_by_feedrate(const Print& print, GLVolumeCollection& volumes); + static bool _travel_paths_by_tool(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors); // generates gcode retractions geometry static void _load_gcode_retractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); // generates gcode unretractions geometry @@ -453,7 +456,7 @@ private: // sets gcode geometry visibility according to user selection static void _update_gcode_volumes_visibility(const Print& print, GLVolumeCollection& volumes); // generates the legend texture in dependence of the current shown view type - static void _generate_legend_texture(const Print& print); + static void _generate_legend_texture(const Print& print, const std::vector& tool_colors); }; } diff --git a/xs/xsp/GUI_3DScene.xsp b/xs/xsp/GUI_3DScene.xsp index 6c56a06d9..7520ce6c2 100644 --- a/xs/xsp/GUI_3DScene.xsp +++ b/xs/xsp/GUI_3DScene.xsp @@ -195,11 +195,12 @@ _load_wipe_tower_toolpaths(print, volumes, tool_colors, use_VBOs) _3DScene::_load_wipe_tower_toolpaths(print, volumes, tool_colors, use_VBOs != 0); void -load_gcode_preview(print, volumes, use_VBOs) - Print *print; - GLVolumeCollection *volumes; - int use_VBOs; +load_gcode_preview(print, volumes, str_tool_colors, use_VBOs) + Print *print; + GLVolumeCollection *volumes; + std::vector str_tool_colors; + int use_VBOs; CODE: - _3DScene::load_gcode_preview(print, volumes, use_VBOs != 0); + _3DScene::load_gcode_preview(print, volumes, str_tool_colors, use_VBOs != 0); %} From 6b14e7cc5417c8f0b7477c0d86ac2e25a101a27c Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Wed, 7 Feb 2018 10:22:35 +0100 Subject: [PATCH 28/57] GCode Preview - Fixed behavior of the feature types combo --- lib/Slic3r/GUI/Plater/3DPreview.pm | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index 2b853dbb3..1f7408b7a 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -72,7 +72,6 @@ sub new { my $combochecklist_features = Wx::ComboCtrl->new(); $combochecklist_features->Create($self, -1, "Feature types", wxDefaultPosition, [200, -1], wxCB_READONLY); - $combochecklist_features->UseAltPopupWindow(); $combochecklist_features->EnablePopupAnimation(0); my $feature_text = "Feature types"; my $feature_items = "Perimeter|External perimeter|Overhang perimeter|Internal infill|Solid infill|Top solid infill|Bridge infill|Gap fill|Skirt|Support material|Support material interface|Wipe tower"; From 33553e1c5092f1b0e4fe68b209895d498e91ed66 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Thu, 8 Feb 2018 13:26:50 +0100 Subject: [PATCH 29/57] 3mf Exporter - 1st installment --- lib/Slic3r/GUI/MainFrame.pm | 3 + lib/Slic3r/GUI/Plater.pm | 30 ++- xs/src/libslic3r/Format/3mf.cpp | 353 +++++++++++++++++++++++++++++++- xs/src/libslic3r/Format/3mf.hpp | 8 +- xs/xsp/Model.xsp | 16 ++ 5 files changed, 400 insertions(+), 10 deletions(-) diff --git a/lib/Slic3r/GUI/MainFrame.pm b/lib/Slic3r/GUI/MainFrame.pm index 3b82ee157..35260011c 100644 --- a/lib/Slic3r/GUI/MainFrame.pm +++ b/lib/Slic3r/GUI/MainFrame.pm @@ -244,6 +244,9 @@ sub _init_menubar { $self->_append_menu_item($self->{plater_menu}, "Export plate as AMF...", 'Export current plate as AMF', sub { $plater->export_amf; }, undef, 'brick_go.png'); + $self->_append_menu_item($self->{plater_menu}, "Export plate as 3MF...", 'Export current plate as 3MF', sub { + $plater->export_3mf; + }, undef, 'brick_go.png'); $self->{object_menu} = $self->{plater}->object_menu; $self->on_plater_selection_changed(0); diff --git a/lib/Slic3r/GUI/Plater.pm b/lib/Slic3r/GUI/Plater.pm index a5a98d649..d9c586685 100644 --- a/lib/Slic3r/GUI/Plater.pm +++ b/lib/Slic3r/GUI/Plater.pm @@ -1550,11 +1550,39 @@ sub export_amf { $self->statusbar->SetStatusText("AMF file exported to $output_file"); } +sub export_3mf { + my ($self) = @_; + return if !@{$self->{objects}}; + # Ask user for a file name to write into. + my $output_file = $self->_get_export_file('3MF') or return; + my $res = $self->{model}->store_3mf($output_file); + if ($res) + { + $self->statusbar->SetStatusText("3MF file exported to $output_file"); + } + else + { + $self->statusbar->SetStatusText("Error exporting 3MF file $output_file"); + } +} + # Ask user to select an output file for a given file format (STl, AMF, 3MF). # Propose a default file name based on the 'output_filename_format' configuration value. sub _get_export_file { my ($self, $format) = @_; - my $suffix = $format eq 'STL' ? '.stl' : '.amf.xml'; + my $suffix = ''; + if ($format eq 'STL') + { + $suffix = '.stl'; + } + elsif ($format eq 'AMF') + { + $suffix = '.amf.xml'; + } + elsif ($format eq '3MF') + { + $suffix = '.3mf'; + } my $output_file = eval { $self->{print}->output_filepath($main::opt{output} // '') }; Slic3r::GUI::catch_error($self) and return undef; $output_file =~ s/\.[gG][cC][oO][dD][eE]$/$suffix/; diff --git a/xs/src/libslic3r/Format/3mf.cpp b/xs/src/libslic3r/Format/3mf.cpp index 6057e1c11..7fe9352b3 100644 --- a/xs/src/libslic3r/Format/3mf.cpp +++ b/xs/src/libslic3r/Format/3mf.cpp @@ -5,13 +5,18 @@ #include #include +#include +#include #include #include #include -const std::string MODEL_FOLDER = "3d\\"; +const std::string MODEL_FOLDER = "3D/"; const std::string MODEL_EXTENSION = ".model"; +const std::string MODEL_FILE = "3D/3dmodel.model"; // << this is the only format of the string which works with CURA +const std::string CONTENT_TYPES_FILE = "[Content_Types].xml"; +const std::string RELATIONSHIPS_FILE = "_rels/.rels"; const char* MODEL_TAG = "model"; const char* RESOURCES_TAG = "resources"; @@ -380,9 +385,12 @@ namespace Slic3r { { std::string name(stat.m_filename); std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) -> unsigned char { return std::tolower(c); }); - std::replace(name.begin(), name.end(), '/', '\\'); + std::replace(name.begin(), name.end(), '\\', '/'); - if ((name.find(MODEL_FOLDER) == 0) && (name.rfind(MODEL_EXTENSION) == name.length() - MODEL_EXTENSION.length())) + std::string lc_model_folder(MODEL_FOLDER); + std::transform(lc_model_folder.begin(), lc_model_folder.end(), lc_model_folder.begin(), [](unsigned char c) -> unsigned char { return std::tolower(c); }); + + if ((name.find(lc_model_folder) == 0) && (name.rfind(MODEL_EXTENSION) == name.length() - MODEL_EXTENSION.length())) { if (!_extract_model_from_archive_miniz(archive, stat)) { @@ -971,7 +979,326 @@ namespace Slic3r { importer->_handle_end_xml_element(name); } - bool load_3mf(const char* path, Model* model, const char* object_name) + class _3MF_Exporter + { + struct BuildItem + { + unsigned int id; + Matrix4x4 matrix; + + BuildItem(unsigned int id, const Matrix4x4& matrix); + }; + + typedef std::vector BuildItemsList; + + std::vector m_errors; + + public: + bool save_model_to_file(const std::string& filename, Model& model); + + const std::vector& get_errors() const; + + private: + bool _save_model_to_file_miniz(const std::string& filename, Model& model); + bool _add_content_types_file_to_archive_miniz(mz_zip_archive& archive); + bool _add_relationships_file_to_archive_miniz(mz_zip_archive& archive); + bool _add_model_file_to_archive_miniz(mz_zip_archive& archive, Model& model); + bool _add_object_to_model_stream(std::stringstream& stream, unsigned int& object_id, ModelObject& object, BuildItemsList& build_items); + bool _add_mesh_to_object_stream(std::stringstream& stream, ModelObject& object); + bool _add_build_to_model_stream(std::stringstream& stream, const BuildItemsList& build_items); + }; + + _3MF_Exporter::BuildItem::BuildItem(unsigned int id, const Matrix4x4& matrix) + : id(id) + , matrix(matrix) + { + } + + bool _3MF_Exporter::save_model_to_file(const std::string& filename, Model& model) + { + return _save_model_to_file_miniz(filename, model); + } + + const std::vector& _3MF_Exporter::get_errors() const + { + return m_errors; + } + + bool _3MF_Exporter::_save_model_to_file_miniz(const std::string& filename, Model& model) + { + mz_zip_archive archive; + mz_zip_zero_struct(&archive); + + mz_bool res = mz_zip_writer_init_file(&archive, filename.c_str(), 0); + if (res == 0) + { + m_errors.push_back("Unable to open the file"); + return false; + } + + // adds content types file + if (!_add_content_types_file_to_archive_miniz(archive)) + { + mz_zip_writer_end(&archive); + boost::filesystem::remove(filename); + return false; + } + + // adds relationships file + if (!_add_relationships_file_to_archive_miniz(archive)) + { + mz_zip_writer_end(&archive); + boost::filesystem::remove(filename); + return false; + } + + // adds model file + if (!_add_model_file_to_archive_miniz(archive, model)) + { + mz_zip_writer_end(&archive); + boost::filesystem::remove(filename); + return false; + } + + if (!mz_zip_writer_finalize_archive(&archive)) + { + mz_zip_writer_end(&archive); + boost::filesystem::remove(filename); + m_errors.push_back("Unable to finalize the archive"); + return false; + } + + mz_zip_writer_end(&archive); + + return true; + } + + bool _3MF_Exporter::_add_content_types_file_to_archive_miniz(mz_zip_archive& archive) + { + std::stringstream stream; + stream << "\n"; + stream << "\n"; + stream << " \n"; + stream << " \n"; + stream << ""; + + std::string out = stream.str(); + + if (!mz_zip_writer_add_mem(&archive, CONTENT_TYPES_FILE.c_str(), (const void*)out.data(), out.length(), MZ_DEFAULT_COMPRESSION)) + { + m_errors.push_back("Unable to add content types file to archive"); + return false; + } + + return true; + } + + bool _3MF_Exporter::_add_relationships_file_to_archive_miniz(mz_zip_archive& archive) + { + std::stringstream stream; + stream << "\n"; + stream << "\n"; + stream << " \n"; + stream << ""; + + std::string out = stream.str(); + + if (!mz_zip_writer_add_mem(&archive, RELATIONSHIPS_FILE.c_str(), (const void*)out.data(), out.length(), MZ_DEFAULT_COMPRESSION)) + { + m_errors.push_back("Unable to add relationships file to archive"); + return false; + } + + return true; + } + + bool _3MF_Exporter::_add_model_file_to_archive_miniz(mz_zip_archive& archive, Model& model) + { + std::stringstream stream; + stream << "\n"; + stream << "\n"; + stream << " \n"; + + BuildItemsList build_items; + + unsigned int object_id = 1; + for (ModelObject* obj : model.objects) + { + if (obj == nullptr) + continue; + + if (!_add_object_to_model_stream(stream, object_id, *obj, build_items)) + { + m_errors.push_back("Unable to add object to archive"); + return false; + } + } + + + stream << " \n"; + + if (!_add_build_to_model_stream(stream, build_items)) + { + m_errors.push_back("Unable to add build to archive"); + return false; + } + + stream << "\n"; + + std::string out = stream.str(); + + if (!mz_zip_writer_add_mem(&archive, MODEL_FILE.c_str(), (const void*)out.data(), out.length(), MZ_DEFAULT_COMPRESSION)) + { + m_errors.push_back("Unable to add model file to archive"); + return false; + } + + return true; + } + + bool _3MF_Exporter::_add_object_to_model_stream(std::stringstream& stream, unsigned int& object_id, ModelObject& object, BuildItemsList& build_items) + { + unsigned int id = 0; + for (const ModelInstance* instance : object.instances) + { + if (instance == nullptr) + continue; + + unsigned int instance_id = object_id + id; + stream << " \n"; + + if (id == 0) + { + if (!_add_mesh_to_object_stream(stream, object)) + { + m_errors.push_back("Unable to add mesh to archive"); + return false; + } + } + else + { + stream << " \n"; + stream << " \n"; + stream << " \n"; + } + + Eigen::Affine3f transform; + transform = Eigen::Translation3f((float)(instance->offset.x + object.origin_translation.x), (float)(instance->offset.y + object.origin_translation.y), (float)object.origin_translation.z) + * Eigen::AngleAxisf((float)instance->rotation, Eigen::Vector3f::UnitZ()) + * Eigen::Scaling((float)instance->scaling_factor); + build_items.emplace_back(instance_id, transform.matrix()); + + stream << " \n"; + + ++id; + } + + object_id += id; + return true; + } + + bool _3MF_Exporter::_add_mesh_to_object_stream(std::stringstream& stream, ModelObject& object) + { + stream << " \n"; + stream << " \n"; + + typedef std::map VolumeToOffsetMap; + VolumeToOffsetMap volumes_offset; + unsigned int vertices_count = 0; + for (ModelVolume* volume : object.volumes) + { + if (volume == nullptr) + continue; + + volumes_offset.insert(VolumeToOffsetMap::value_type(volume, vertices_count)); + + if (!volume->mesh.repaired) + volume->mesh.repair(); + + stl_file& stl = volume->mesh.stl; + if (stl.v_shared == nullptr) + stl_generate_shared_vertices(&stl); + + if (stl.stats.shared_vertices == 0) + { + m_errors.push_back("Found invalid mesh"); + return false; + } + + vertices_count += stl.stats.shared_vertices; + + for (int i = 0; i < stl.stats.shared_vertices; ++i) + { + stream << " \n"; + } + } + + stream << " \n"; + stream << " \n"; + + for (ModelVolume* volume : object.volumes) + { + if (volume == nullptr) + continue; + + VolumeToOffsetMap::const_iterator offset_it = volumes_offset.find(volume); + assert(offset_it != volumes_offset.end()); + + stl_file& stl = volume->mesh.stl; + + for (uint32_t i = 0; i < stl.stats.number_of_facets; ++i) + { + stream << " second << "\" "; + } + stream << "/>\n"; + } + + } + + stream << " \n"; + stream << " \n"; + + return true; + } + + bool _3MF_Exporter::_add_build_to_model_stream(std::stringstream& stream, const BuildItemsList& build_items) + { + if (build_items.size() == 0) + { + m_errors.push_back("No build item found"); + return false; + } + + stream << " \n"; + + for (const BuildItem& item : build_items) + { + stream << " \n"; + } + + stream << " \n"; + + return true; + } + + bool load_3mf(const char* path, Model* model) { if ((path == nullptr) || (model == nullptr)) return false; @@ -980,11 +1307,23 @@ namespace Slic3r { bool res = importer.load_model_from_file(path, *model); if (!res) - { const std::vector& errors = importer.get_errors(); - int a = 0; - } return res; } + + bool store_3mf(const char* path, Model* model) + { + if ((path == nullptr) || (model == nullptr)) + return false; + + _3MF_Exporter exporter; + bool res = exporter.save_model_to_file(path, *model); + + if (!res) + const std::vector& errors = exporter.get_errors(); + + return res; + } + } // namespace Slic3r diff --git a/xs/src/libslic3r/Format/3mf.hpp b/xs/src/libslic3r/Format/3mf.hpp index 11eb4c388..ff178e3de 100644 --- a/xs/src/libslic3r/Format/3mf.hpp +++ b/xs/src/libslic3r/Format/3mf.hpp @@ -5,8 +5,12 @@ namespace Slic3r { class Model; - // Load an 3mf file into a provided model. - extern bool load_3mf(const char* path, Model* model, const char* object_name = nullptr); + // Load a 3mf file into the given model. + extern bool load_3mf(const char* path, Model* model); + + // Save the given model into a 3mf file. + // The model could be modified during the export process if meshes are not repaired or have no shared vertices + extern bool store_3mf(const char* path, Model* model); }; // namespace Slic3r #endif /* slic3r_Format_3mf_hpp_ */ diff --git a/xs/xsp/Model.xsp b/xs/xsp/Model.xsp index c96c56386..9a2a50437 100644 --- a/xs/xsp/Model.xsp +++ b/xs/xsp/Model.xsp @@ -6,6 +6,7 @@ #include "libslic3r/PrintConfig.hpp" #include "libslic3r/Slicing.hpp" #include "libslic3r/Format/AMF.hpp" +#include "libslic3r/Format/3mf.hpp" #include "libslic3r/Format/OBJ.hpp" #include "libslic3r/Format/PRUS.hpp" #include "libslic3r/Format/STL.hpp" @@ -91,6 +92,8 @@ %code%{ TriangleMesh mesh = THIS->mesh(); RETVAL = Slic3r::store_stl(path, &mesh, binary); %}; bool store_amf(char *path) %code%{ RETVAL = Slic3r::store_amf(path, THIS); %}; + bool store_3mf(char *path) + %code%{ RETVAL = Slic3r::store_3mf(path, THIS); %}; %{ @@ -135,6 +138,19 @@ load_amf(CLASS, path) OUTPUT: RETVAL +Model* +load_3mf(CLASS, path) + char* CLASS; + char* path; + CODE: + RETVAL = new Model(); + if (! load_3mf(path, RETVAL)) { + delete RETVAL; + RETVAL = NULL; + } + OUTPUT: + RETVAL + Model* load_prus(CLASS, path) char* CLASS; From 3f006dc11a7f18fa9e5a9921432b8267e55ebdcb Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Mon, 12 Feb 2018 09:04:05 +0100 Subject: [PATCH 30/57] GCode Preview - Added objects and wipe tower transparent shells --- lib/Slic3r/GUI/Plater/3DPreview.pm | 9 +++ xs/src/libslic3r/GCode/Analyzer.cpp | 8 ++- xs/src/libslic3r/GCode/Analyzer.hpp | 8 +++ xs/src/libslic3r/Print.cpp | 5 ++ xs/src/libslic3r/Print.hpp | 1 + xs/src/slic3r/GUI/3DScene.cpp | 94 +++++++++++++++++++++++++++++ xs/src/slic3r/GUI/3DScene.hpp | 27 +++++++++ xs/xsp/Print.xsp | 1 + 8 files changed, 152 insertions(+), 1 deletion(-) diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index 1f7408b7a..fb1a9bbfc 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -80,6 +80,7 @@ sub new { my $checkbox_travel = Wx::CheckBox->new($self, -1, "Travel"); my $checkbox_retractions = Wx::CheckBox->new($self, -1, "Retractions"); my $checkbox_unretractions = Wx::CheckBox->new($self, -1, "Unretractions"); + my $checkbox_shells = Wx::CheckBox->new($self, -1, "Shells"); my $hsizer = Wx::BoxSizer->new(wxHORIZONTAL); my $vsizer = Wx::BoxSizer->new(wxVERTICAL); @@ -106,6 +107,8 @@ sub new { $bottom_sizer->Add($checkbox_retractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); $bottom_sizer->AddSpacer(10); $bottom_sizer->Add($checkbox_unretractions, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); + $bottom_sizer->AddSpacer(10); + $bottom_sizer->Add($checkbox_shells, 0, wxEXPAND | wxALL | wxALIGN_CENTER_VERTICAL, 5); my $sizer = Wx::BoxSizer->new(wxHORIZONTAL); $sizer->Add($canvas, 1, wxALL | wxEXPAND, 0); @@ -217,6 +220,12 @@ sub new { $self->refresh_print; $self->auto_zoom(1); }); + EVT_CHECKBOX($self, $checkbox_shells, sub { + $self->print->set_gcode_preview_shells_visible($checkbox_shells->IsChecked()); + $self->auto_zoom(0); + $self->refresh_print; + $self->auto_zoom(1); + }); $self->SetSizer($main_sizer); $self->SetMinSize($self->GetSize); diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index 0288770b0..c64857566 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -298,7 +298,12 @@ void GCodeAnalyzer::PreviewData::Retraction::set_default() { color = Default_Color; is_visible = false; -}; +} + +void GCodeAnalyzer::PreviewData::Shell::set_default() +{ + is_visible = false; +} GCodeAnalyzer::PreviewData::PreviewData() { @@ -311,6 +316,7 @@ void GCodeAnalyzer::PreviewData::set_default() travel.set_default(); retraction.set_default(); unretraction.set_default(); + shell.set_default(); } void GCodeAnalyzer::PreviewData::reset() diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index 34f1537af..6d0213422 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -256,10 +256,18 @@ public: void set_default(); }; + struct Shell + { + bool is_visible; + + void set_default(); + }; + Extrusion extrusion; Travel travel; Retraction retraction; Retraction unretraction; + Shell shell; PreviewData(); diff --git a/xs/src/libslic3r/Print.cpp b/xs/src/libslic3r/Print.cpp index d0af38327..172b26cc4 100644 --- a/xs/src/libslic3r/Print.cpp +++ b/xs/src/libslic3r/Print.cpp @@ -102,6 +102,11 @@ void Print::set_gcode_preview_unretractions_visible(bool visible) gcode_preview.unretraction.is_visible = visible; } +void Print::set_gcode_preview_shells_visible(bool visible) +{ + gcode_preview.shell.is_visible = visible; +} + PrintRegion* Print::add_region() { regions.push_back(new PrintRegion(this)); diff --git a/xs/src/libslic3r/Print.hpp b/xs/src/libslic3r/Print.hpp index 4c2284446..0a6c143b9 100644 --- a/xs/src/libslic3r/Print.hpp +++ b/xs/src/libslic3r/Print.hpp @@ -262,6 +262,7 @@ public: void set_gcode_preview_travel_visible(bool visible); void set_gcode_preview_retractions_visible(bool visible); void set_gcode_preview_unretractions_visible(bool visible); + void set_gcode_preview_shells_visible(bool visible); // methods for handling regions PrintRegion* get_region(size_t idx) { return regions.at(idx); } diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index 96cbabbe9..553239a6f 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -348,7 +348,32 @@ void GLVolumeCollection::render_VBOs() const GLsizei n_triangles = GLsizei(std::min(volume->indexed_vertex_array.triangle_indices_size, volume->tverts_range.second - volume->tverts_range.first)); GLsizei n_quads = GLsizei(std::min(volume->indexed_vertex_array.quad_indices_size, volume->qverts_range.second - volume->qverts_range.first)); if (n_triangles + n_quads == 0) + { + if (_render_interleaved_only_volumes.enabled) + { + ::glDisableClientState(GL_VERTEX_ARRAY); + ::glDisableClientState(GL_NORMAL_ARRAY); + ::glEnable(GL_BLEND); + ::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + if (color_id >= 0) + { + float color[4]; + ::memcpy((void*)color, (const void*)volume->color, 3 * sizeof(float)); + color[3] = _render_interleaved_only_volumes.alpha; + ::glUniform4fv(color_id, 1, (const GLfloat*)color); + } + else + ::glColor4f(volume->color[0], volume->color[1], volume->color[2], _render_interleaved_only_volumes.alpha); + + volume->render(); + + ::glDisable(GL_BLEND); + ::glEnableClientState(GL_VERTEX_ARRAY); + ::glEnableClientState(GL_NORMAL_ARRAY); + } continue; + } if (color_id >= 0) glUniform4fv(color_id, 1, (const GLfloat*)volume->color); else @@ -387,7 +412,23 @@ void GLVolumeCollection::render_legacy() const GLsizei n_triangles = GLsizei(std::min(volume->indexed_vertex_array.triangle_indices_size, volume->tverts_range.second - volume->tverts_range.first)); GLsizei n_quads = GLsizei(std::min(volume->indexed_vertex_array.quad_indices_size, volume->qverts_range.second - volume->qverts_range.first)); if (n_triangles + n_quads == 0) + { + if (_render_interleaved_only_volumes.enabled) + { + ::glDisableClientState(GL_VERTEX_ARRAY); + ::glDisableClientState(GL_NORMAL_ARRAY); + ::glEnable(GL_BLEND); + ::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + ::glColor4f(volume->color[0], volume->color[1], volume->color[2], _render_interleaved_only_volumes.alpha); + volume->render(); + + ::glDisable(GL_BLEND); + ::glEnableClientState(GL_VERTEX_ARRAY); + ::glEnableClientState(GL_NORMAL_ARRAY); + } continue; + } glColor4f(volume->color[0], volume->color[1], volume->color[2], volume->color[3]); glVertexPointer(3, GL_FLOAT, 6 * sizeof(float), volume->indexed_vertex_array.vertices_and_normals_interleaved.data() + 3); glNormalPointer(GL_FLOAT, 6 * sizeof(float), volume->indexed_vertex_array.vertices_and_normals_interleaved.data()); @@ -1314,6 +1355,9 @@ static inline std::vector parse_colors(const std::vector &sc void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volumes, const std::vector& str_tool_colors, bool use_VBOs) { + if ((print == nullptr) || (volumes == nullptr)) + return; + if (volumes->empty()) { std::vector tool_colors = parse_colors(str_tool_colors); @@ -1326,9 +1370,17 @@ void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volume _load_gcode_unretractions(*print, *volumes, use_VBOs); if (volumes->empty()) + { reset_legend_texture(); + volumes->set_render_interleaved_only_volumes(GLVolumeCollection::RenderInterleavedOnlyVolumes(false, 0.0f)); + } else + { _generate_legend_texture(*print, tool_colors); + + _load_shells(*print, *volumes, use_VBOs); + volumes->set_render_interleaved_only_volumes(GLVolumeCollection::RenderInterleavedOnlyVolumes(true, 0.25f)); + } } _update_gcode_volumes_visibility(*print, *volumes); @@ -2209,6 +2261,11 @@ void _3DScene::_update_gcode_volumes_visibility(const Print& print, GLVolumeColl volume->is_active = print.gcode_preview.unretraction.is_visible; break; } + case GCodePreviewData::Shell: + { + volume->is_active = print.gcode_preview.shell.is_visible; + break; + } default: { volume->is_active = false; @@ -2224,4 +2281,41 @@ void _3DScene::_generate_legend_texture(const Print& print, const std::vectormodel_object(); + + std::vector instance_ids(model_obj->instances.size()); + for (int i = 0; i < model_obj->instances.size(); ++i) + { + instance_ids[i] = i; + } + + for (ModelInstance* instance : model_obj->instances) + { + volumes.load_object(model_obj, object_id, instance_ids, "object", "object", "object", use_VBOs); + } + + ++object_id; + } + + // adds wipe tower's volume + coordf_t max_z = print.objects[0]->model_object()->get_model()->bounding_box().max.z; + const PrintConfig& config = print.config; + unsigned int extruders_count = config.nozzle_diameter.size(); + if ((extruders_count > 1) && config.single_extruder_multi_material && config.wipe_tower && !config.complete_objects) + volumes.load_wipe_tower_preview(1000, config.wipe_tower_x, config.wipe_tower_y, config.wipe_tower_width, config.wipe_tower_per_color_wipe * (extruders_count - 1), max_z, use_VBOs); +} + } diff --git a/xs/src/slic3r/GUI/3DScene.hpp b/xs/src/slic3r/GUI/3DScene.hpp index 2b7f2de47..44e5dbea3 100644 --- a/xs/src/slic3r/GUI/3DScene.hpp +++ b/xs/src/slic3r/GUI/3DScene.hpp @@ -309,6 +309,28 @@ public: class GLVolumeCollection { +public: + struct RenderInterleavedOnlyVolumes + { + bool enabled; + float alpha; // [0..1] + + RenderInterleavedOnlyVolumes() + : enabled(false) + , alpha(0.0f) + { + } + + RenderInterleavedOnlyVolumes(bool enabled, float alpha) + : enabled(enabled) + , alpha(alpha) + { + } + }; + +private: + RenderInterleavedOnlyVolumes _render_interleaved_only_volumes; + public: std::vector volumes; @@ -344,6 +366,8 @@ public: bool empty() const { return volumes.empty(); } void set_range(double low, double high) { for (GLVolume *vol : this->volumes) vol->set_range(low, high); } + void set_render_interleaved_only_volumes(const RenderInterleavedOnlyVolumes& render_interleaved_only_volumes) { _render_interleaved_only_volumes = render_interleaved_only_volumes; } + private: GLVolumeCollection(const GLVolumeCollection &other); GLVolumeCollection& operator=(const GLVolumeCollection &); @@ -359,6 +383,7 @@ class _3DScene Travel, Retraction, Unretraction, + Shell, Num_Geometry_Types }; @@ -457,6 +482,8 @@ private: static void _update_gcode_volumes_visibility(const Print& print, GLVolumeCollection& volumes); // generates the legend texture in dependence of the current shown view type static void _generate_legend_texture(const Print& print, const std::vector& tool_colors); + // generates objects and wipe tower geometry + static void _load_shells(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); }; } diff --git a/xs/xsp/Print.xsp b/xs/xsp/Print.xsp index 4df4a5865..4f870df68 100644 --- a/xs/xsp/Print.xsp +++ b/xs/xsp/Print.xsp @@ -171,6 +171,7 @@ _constant() void set_gcode_preview_travel_visible(bool visible); void set_gcode_preview_retractions_visible(bool visible); void set_gcode_preview_unretractions_visible(bool visible); + void set_gcode_preview_shells_visible(bool visible); PrintRegionPtrs* regions() %code%{ RETVAL = &THIS->regions; %}; From 0571d22d5f6faf807857e9cc3ff7a60acfab6c86 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Mon, 12 Feb 2018 15:37:42 +0100 Subject: [PATCH 31/57] Fix of https://github.com/prusa3d/Slic3r/issues/707 This is a crash due to the recommended thin wall thickness hint. --- xs/src/slic3r/GUI/PresetHints.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/xs/src/slic3r/GUI/PresetHints.cpp b/xs/src/slic3r/GUI/PresetHints.cpp index 36f574329..4553ba476 100644 --- a/xs/src/slic3r/GUI/PresetHints.cpp +++ b/xs/src/slic3r/GUI/PresetHints.cpp @@ -238,6 +238,9 @@ std::string PresetHints::recommended_thin_wall_thickness(const PresetBundle &pre bool thin_walls = print_config.opt_bool("thin_walls"); float nozzle_diameter = float(printer_config.opt_float("nozzle_diameter", 0)); + if (layer_height <= 0.f) + return "Recommended object thin wall thickness: Not available due to invalid layer height."; + Flow external_perimeter_flow = Flow::new_from_config_width( frExternalPerimeter, *print_config.opt("external_perimeter_extrusion_width"), From adc9e749c4b6d82314a3693555991db19809fd94 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Mon, 12 Feb 2018 16:34:39 +0100 Subject: [PATCH 32/57] Clipper should always throw clipperExceptions, not strings. --- xs/src/clipper.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/xs/src/clipper.cpp b/xs/src/clipper.cpp index 5c63a6afe..e865288fb 100644 --- a/xs/src/clipper.cpp +++ b/xs/src/clipper.cpp @@ -561,7 +561,7 @@ inline void RangeTest(const IntPoint& Pt, bool& useFullRange) if (useFullRange) { if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange) - throw "Coordinate outside allowed range"; + throw clipperException("Coordinate outside allowed range"); } else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange) { @@ -2386,8 +2386,8 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge) void Clipper::UpdateEdgeIntoAEL(TEdge *&e) { - if( !e->NextInLML ) throw - clipperException("UpdateEdgeIntoAEL: invalid call"); + if( !e->NextInLML ) + throw clipperException("UpdateEdgeIntoAEL: invalid call"); e->NextInLML->OutIdx = e->OutIdx; TEdge* AelPrev = e->PrevInAEL; From 47d904a628ec35a1a0f08ab2ad7bd664cc0c601f Mon Sep 17 00:00:00 2001 From: bubnikv Date: Mon, 12 Feb 2018 18:16:10 +0100 Subject: [PATCH 33/57] Changed the Slic3r coordinate type from long to int32 to match the point type on Windows / Linux / OSX to achieve the same behavior on all the 32 / 64bit systems. (Windows always treats the long as 32bit int, while Linux treats long as a 64bit int). --- xs/src/admesh/util.cpp | 6 ++---- xs/src/libslic3r/Point.hpp | 20 +------------------- xs/src/libslic3r/libslic3r.h | 4 ++-- xs/xsp/BoundingBox.xsp | 8 ++++---- xs/xsp/BridgeDetector.xsp | 4 ++-- xs/xsp/Flow.xsp | 4 ++-- xs/xsp/Point.xsp | 18 +++++++++--------- 7 files changed, 22 insertions(+), 42 deletions(-) diff --git a/xs/src/admesh/util.cpp b/xs/src/admesh/util.cpp index b0c31469d..f3bf59b56 100644 --- a/xs/src/admesh/util.cpp +++ b/xs/src/admesh/util.cpp @@ -171,12 +171,11 @@ stl_scale(stl_file *stl, float factor) { } static void calculate_normals(stl_file *stl) { - long i; float normal[3]; if (stl->error) return; - for(i = 0; i < stl->stats.number_of_facets; i++) { + for(uint32_t i = 0; i < stl->stats.number_of_facets; i++) { stl_calculate_normal(normal, &stl->facet_start[i]); stl_normalize_vector(normal); stl->facet_start[i].normal.x = normal[0]; @@ -381,7 +380,6 @@ stl_mirror_xz(stl_file *stl) { } static float get_volume(stl_file *stl) { - long i; stl_vertex p0; stl_vertex p; stl_normal n; @@ -396,7 +394,7 @@ static float get_volume(stl_file *stl) { p0.y = stl->facet_start[0].vertex[0].y; p0.z = stl->facet_start[0].vertex[0].z; - for(i = 0; i < stl->stats.number_of_facets; i++) { + for(uint32_t i = 0; i < stl->stats.number_of_facets; i++) { p.x = stl->facet_start[i].vertex[0].x - p0.x; p.y = stl->facet_start[i].vertex[0].y - p0.y; p.z = stl->facet_start[i].vertex[0].z - p0.z; diff --git a/xs/src/libslic3r/Point.hpp b/xs/src/libslic3r/Point.hpp index 77e07bec8..09c292b5a 100644 --- a/xs/src/libslic3r/Point.hpp +++ b/xs/src/libslic3r/Point.hpp @@ -32,8 +32,7 @@ public: coord_t x; coord_t y; Point(coord_t _x = 0, coord_t _y = 0): x(_x), y(_y) {}; - Point(int _x, int _y): x(_x), y(_y) {}; - Point(long long _x, long long _y): x(coord_t(_x)), y(coord_t(_y)) {}; // for Clipper + Point(int64_t _x, int64_t _y): x(coord_t(_x)), y(coord_t(_y)) {}; // for Clipper Point(double x, double y); static Point new_scale(coordf_t x, coordf_t y) { return Point(coord_t(scale_(x)), coord_t(scale_(y))); } @@ -271,23 +270,6 @@ template inline TO convert_to(const Pointf3 &src) { return TO(typen #include #include namespace boost { namespace polygon { - template <> - struct geometry_concept { typedef coordinate_concept type; }; - -/* Boost.Polygon already defines a specialization for coordinate_traits as of 1.60: - https://github.com/boostorg/polygon/commit/0ac7230dd1f8f34cb12b86c8bb121ae86d3d9b97 */ -#if BOOST_VERSION < 106000 - template <> - struct coordinate_traits { - typedef coord_t coordinate_type; - typedef long double area_type; - typedef long long manhattan_area_type; - typedef unsigned long long unsigned_area_type; - typedef long long coordinate_difference; - typedef long double coordinate_distance; - }; -#endif - template <> struct geometry_concept { typedef point_concept type; }; diff --git a/xs/src/libslic3r/libslic3r.h b/xs/src/libslic3r/libslic3r.h index 7c694b05e..e58b01582 100644 --- a/xs/src/libslic3r/libslic3r.h +++ b/xs/src/libslic3r/libslic3r.h @@ -17,8 +17,8 @@ #define SLIC3R_VERSION "1.39.0" #define SLIC3R_BUILD "UNKNOWN" -typedef long coord_t; -typedef double coordf_t; +typedef int32_t coord_t; +typedef double coordf_t; //FIXME This epsilon value is used for many non-related purposes: // For a threshold of a squared Euclidean distance, diff --git a/xs/xsp/BoundingBox.xsp b/xs/xsp/BoundingBox.xsp index a326c7501..df8e6baea 100644 --- a/xs/xsp/BoundingBox.xsp +++ b/xs/xsp/BoundingBox.xsp @@ -25,10 +25,10 @@ double radius(); Clone min_point() %code{% RETVAL = THIS->min; %}; Clone max_point() %code{% RETVAL = THIS->max; %}; - long x_min() %code{% RETVAL = THIS->min.x; %}; - long x_max() %code{% RETVAL = THIS->max.x; %}; - long y_min() %code{% RETVAL = THIS->min.y; %}; - long y_max() %code{% RETVAL = THIS->max.y; %}; + int x_min() %code{% RETVAL = THIS->min.x; %}; + int x_max() %code{% RETVAL = THIS->max.x; %}; + int y_min() %code{% RETVAL = THIS->min.y; %}; + int y_max() %code{% RETVAL = THIS->max.y; %}; std::string serialize() %code{% char buf[2048]; sprintf(buf, "%ld,%ld;%ld,%ld", THIS->min.x, THIS->min.y, THIS->max.x, THIS->max.y); RETVAL = buf; %}; bool defined() %code{% RETVAL = THIS->defined; %}; diff --git a/xs/xsp/BridgeDetector.xsp b/xs/xsp/BridgeDetector.xsp index c7ac409df..0039d3579 100644 --- a/xs/xsp/BridgeDetector.xsp +++ b/xs/xsp/BridgeDetector.xsp @@ -23,7 +23,7 @@ BridgeDetector* BridgeDetector::new(expolygon, lower_slices, extrusion_width) ExPolygon* expolygon; ExPolygonCollection* lower_slices; - long extrusion_width; + int extrusion_width; CODE: RETVAL = new BridgeDetector(*expolygon, *lower_slices, extrusion_width); OUTPUT: @@ -33,7 +33,7 @@ BridgeDetector* BridgeDetector::new_expolygons(expolygons, lower_slices, extrusion_width) ExPolygonCollection* expolygons; ExPolygonCollection* lower_slices; - long extrusion_width; + int extrusion_width; CODE: RETVAL = new BridgeDetector(expolygons->expolygons, *lower_slices, extrusion_width); OUTPUT: diff --git a/xs/xsp/Flow.xsp b/xs/xsp/Flow.xsp index d9b7a45c0..b57df5e37 100644 --- a/xs/xsp/Flow.xsp +++ b/xs/xsp/Flow.xsp @@ -26,8 +26,8 @@ float spacing(); float spacing_to(Flow* other) %code{% RETVAL = THIS->spacing(*other); %}; - long scaled_width(); - long scaled_spacing(); + int scaled_width(); + int scaled_spacing(); double mm3_per_mm(); %{ diff --git a/xs/xsp/Point.xsp b/xs/xsp/Point.xsp index d0f9260c7..b7aded6a0 100644 --- a/xs/xsp/Point.xsp +++ b/xs/xsp/Point.xsp @@ -8,7 +8,7 @@ %} %name{Slic3r::Point} class Point { - Point(long _x = 0, long _y = 0); + Point(int _x = 0, int _y = 0); ~Point(); Clone clone() %code{% RETVAL=THIS; %}; @@ -18,13 +18,13 @@ %code{% RETVAL = to_SV_pureperl(THIS); %}; SV* pp() %code{% RETVAL = to_SV_pureperl(THIS); %}; - long x() + int x() %code{% RETVAL = THIS->x; %}; - long y() + int y() %code{% RETVAL = THIS->y; %}; - void set_x(long val) + void set_x(int val) %code{% THIS->x = val; %}; - void set_y(long val) + void set_y(int val) %code{% THIS->y = val; %}; int nearest_point_index(Points points); Clone nearest_point(Points points) @@ -77,15 +77,15 @@ Point::coincides_with(point_sv) }; %name{Slic3r::Point3} class Point3 { - Point3(long _x = 0, long _y = 0, long _z = 0); + Point3(int _x = 0, int _y = 0, int _z = 0); ~Point3(); Clone clone() %code{% RETVAL = THIS; %}; - long x() + int x() %code{% RETVAL = THIS->x; %}; - long y() + int y() %code{% RETVAL = THIS->y; %}; - long z() + int z() %code{% RETVAL = THIS->z; %}; std::string serialize() %code{% char buf[2048]; sprintf(buf, "%ld,%ld,%ld", THIS->x, THIS->y, THIS->z); RETVAL = buf; %}; }; From 6f92424bab82f1795697b21e074e4652529271ff Mon Sep 17 00:00:00 2001 From: bubnikv Date: Mon, 12 Feb 2018 19:06:05 +0100 Subject: [PATCH 34/57] Fix of https://github.com/prusa3d/Slic3r/issues/709 A regression error has been introduced into Slic3r 1.38.xx series for the float/percent config value, where the value was considered unchanged if the percent sign has been added or removed. --- xs/src/libslic3r/Config.hpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/xs/src/libslic3r/Config.hpp b/xs/src/libslic3r/Config.hpp index e04f4df82..a58bb613a 100644 --- a/xs/src/libslic3r/Config.hpp +++ b/xs/src/libslic3r/Config.hpp @@ -582,6 +582,13 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionFloatOrPercent(*this); } ConfigOptionFloatOrPercent& operator=(const ConfigOption *opt) { this->set(opt); return *this; } + bool operator==(const ConfigOption &rhs) const override + { + if (rhs.type() != this->type()) + throw std::runtime_error("ConfigOptionFloatOrPercent: Comparing incompatible types"); + assert(dynamic_cast(&rhs)); + return *this == *static_cast(&rhs); + } bool operator==(const ConfigOptionFloatOrPercent &rhs) const { return this->value == rhs.value && this->percent == rhs.percent; } double get_abs_value(double ratio_over) const From 81a80ebd618ada3494e6c996d0b607bf522dddb0 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Mon, 12 Feb 2018 20:44:06 +0100 Subject: [PATCH 35/57] Synchronized the GCodeSender with the upstream Slic3r, thanks @alexrj. Fixes https://github.com/prusa3d/Slic3r/issues/654 --- xs/src/libslic3r/GCodeSender.cpp | 120 ++++++++++++++++++------------- 1 file changed, 70 insertions(+), 50 deletions(-) diff --git a/xs/src/libslic3r/GCodeSender.cpp b/xs/src/libslic3r/GCodeSender.cpp index 504171288..bbeaf836d 100644 --- a/xs/src/libslic3r/GCodeSender.cpp +++ b/xs/src/libslic3r/GCodeSender.cpp @@ -7,16 +7,36 @@ #include #include -#if defined(__APPLE__) || defined(__linux) || defined(__OpenBSD__) +#if defined(__APPLE__) || defined(__OpenBSD__) #include #endif -#if __APPLE__ +#ifdef __APPLE__ #include #include #endif -#ifdef __linux +#ifdef __linux__ #include -#include +#include +#include "/usr/include/asm-generic/ioctls.h" + +/* The following definitions are kindly borrowed from: + /usr/include/asm-generic/termbits.h + Unfortunately we cannot just include that one because + it would redefine the "struct termios" already defined + the already included by Boost.ASIO. */ +#define K_NCCS 19 +struct termios2 { + tcflag_t c_iflag; + tcflag_t c_oflag; + tcflag_t c_cflag; + tcflag_t c_lflag; + cc_t c_line; + cc_t c_cc[K_NCCS]; + speed_t c_ispeed; + speed_t c_ospeed; +}; +#define BOTHER CBAUDEX + #endif //#define DEBUG_SERIAL @@ -47,26 +67,26 @@ GCodeSender::connect(std::string devname, unsigned int baud_rate) this->set_error_status(false); try { this->serial.open(devname); + + this->serial.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::odd)); + this->serial.set_option(boost::asio::serial_port_base::character_size(boost::asio::serial_port_base::character_size(8))); + this->serial.set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none)); + this->serial.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one)); + this->set_baud_rate(baud_rate); + + this->serial.close(); + this->serial.open(devname); + this->serial.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none)); + + // set baud rate again because set_option overwrote it + this->set_baud_rate(baud_rate); + this->open = true; + this->reset(); } catch (boost::system::system_error &) { this->set_error_status(true); return false; } - this->serial.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::odd)); - this->serial.set_option(boost::asio::serial_port_base::character_size(boost::asio::serial_port_base::character_size(8))); - this->serial.set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::none)); - this->serial.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one)); - this->set_baud_rate(baud_rate); - - this->serial.close(); - this->serial.open(devname); - this->serial.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none)); - - // set baud rate again because set_option overwrote it - this->set_baud_rate(baud_rate); - this->open = true; - this->reset(); - // a reset firmware expect line numbers to start again from 1 this->sent = 0; this->last_sent.clear(); @@ -84,6 +104,11 @@ GCodeSender::connect(std::string devname, unsigned int baud_rate) boost::thread t(boost::bind(&boost::asio::io_service::run, &this->io)); this->background_thread.swap(t); + // always send a M105 to check for connection because firmware might be silent on connect + //FIXME Vojtech: This is being sent too early, leading to line number synchronization issues, + // from which the GCodeSender never recovers. + // this->send("M105", true); + return true; } @@ -104,27 +129,17 @@ GCodeSender::set_baud_rate(unsigned int baud_rate) ioctl(handle, IOSSIOSPEED, &newSpeed); ::tcsetattr(handle, TCSANOW, &ios); #elif __linux - termios ios; - ::tcgetattr(handle, &ios); - ::cfsetispeed(&ios, B38400); - ::cfsetospeed(&ios, B38400); - ::tcflush(handle, TCIFLUSH); - ::tcsetattr(handle, TCSANOW, &ios); - - struct serial_struct ss; - ioctl(handle, TIOCGSERIAL, &ss); - ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST; - ss.custom_divisor = (ss.baud_base + (baud_rate / 2)) / baud_rate; - //cout << "bbase " << ss.baud_base << " div " << ss.custom_divisor; - long closestSpeed = ss.baud_base / ss.custom_divisor; - //cout << " Closest speed " << closestSpeed << endl; - ss.reserved_char[0] = 0; - if (closestSpeed < baud_rate * 98 / 100 || closestSpeed > baud_rate * 102 / 100) { - printf("Failed to set baud rate\n"); - } - - ioctl(handle, TIOCSSERIAL, &ss); - printf("< set_baud_rate: %u\n", baud_rate); + termios2 ios; + if (ioctl(handle, TCGETS2, &ios)) + printf("Error in TCGETS2: %s\n", strerror(errno)); + ios.c_ispeed = ios.c_ospeed = baud_rate; + ios.c_cflag &= ~CBAUD; + ios.c_cflag |= BOTHER | CLOCAL | CREAD; + ios.c_cc[VMIN] = 1; // Minimum of characters to read, prevents eof errors when 0 bytes are read + ios.c_cc[VTIME] = 1; + if (ioctl(handle, TCSETS2, &ios)) + printf("Error in TCSETS2: %s\n", strerror(errno)); + #elif __OpenBSD__ struct termios ios; ::tcgetattr(handle, &ios); @@ -154,6 +169,7 @@ GCodeSender::disconnect() */ #ifdef DEBUG_SERIAL + fs << "DISCONNECTED" << std::endl << std::flush; fs.close(); #endif } @@ -292,17 +308,20 @@ GCodeSender::on_read(const boost::system::error_code& error, { this->set_error_status(false); if (error) { + #ifdef __APPLE__ if (error.value() == 45) { // OS X bug: http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html this->do_read(); - } else { - // printf("ERROR: [%d] %s\n", error.value(), error.message().c_str()); - // error can be true even because the serial port was closed. - // In this case it is not a real error, so ignore. - if (this->open) { - this->do_close(); - this->set_error_status(true); - } + return; + } + #endif + + // printf("ERROR: [%d] %s\n", error.value(), error.message().c_str()); + // error can be true even because the serial port was closed. + // In this case it is not a real error, so ignore. + if (this->open) { + this->do_close(); + this->set_error_status(true); } return; } @@ -339,7 +358,8 @@ GCodeSender::on_read(const boost::system::error_code& error, // extract the first number from line boost::algorithm::trim_left_if(line, !boost::algorithm::is_digit()); size_t toresend = boost::lexical_cast(line.substr(0, line.find_first_not_of("0123456789"))); - if (toresend >= this->sent - this->last_sent.size()) { + ++ toresend; // N is 0-based + if (toresend >= this->sent - this->last_sent.size() && toresend < this->last_sent.size()) { { boost::lock_guard l(this->queue_mutex); @@ -457,8 +477,8 @@ GCodeSender::do_send() if (line.empty()) return; // compute full line - this->sent++; std::string full_line = "N" + boost::lexical_cast(this->sent) + " " + line; + ++ this->sent; // calculate checksum int cs = 0; From e77111bf9891df61abbd1130d5aa8165a52a9058 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Tue, 13 Feb 2018 10:25:55 +0100 Subject: [PATCH 36/57] Fixed crash when importing .prusa files --- xs/src/libslic3r/Format/PRUS.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xs/src/libslic3r/Format/PRUS.cpp b/xs/src/libslic3r/Format/PRUS.cpp index b7ef33774..1809eaead 100644 --- a/xs/src/libslic3r/Format/PRUS.cpp +++ b/xs/src/libslic3r/Format/PRUS.cpp @@ -148,7 +148,7 @@ bool load_prus(const char *path, Model *model) if (scene_xml_data.size() < size_last + size_incr) scene_xml_data.resize(size_last + size_incr); } - size_last += size_last + zip.LastRead(); + size_last += zip.LastRead(); if (scene_xml_data.size() == size_last) scene_xml_data.resize(size_last + 1); else if (scene_xml_data.size() > size_last + 1) From e7f05f8516e5e7ab52bfc4af0d5bbbd1bc5ae43c Mon Sep 17 00:00:00 2001 From: bubnikv Date: Tue, 13 Feb 2018 11:18:58 +0100 Subject: [PATCH 37/57] Fix of "Crash while trying to slice with a raft" #686 This was an issue specific to multi-material print with raft and no support. --- xs/src/libslic3r/Print.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/xs/src/libslic3r/Print.cpp b/xs/src/libslic3r/Print.cpp index 0bc63f2f3..c689929c6 100644 --- a/xs/src/libslic3r/Print.cpp +++ b/xs/src/libslic3r/Print.cpp @@ -997,7 +997,8 @@ void Print::_make_wipe_tower() // Find the position in this->objects.first()->support_layers to insert these new support layers. double wipe_tower_new_layer_print_z_first = m_tool_ordering.layer_tools()[idx_begin].print_z; SupportLayerPtrs::iterator it_layer = this->objects.front()->support_layers.begin(); - for (; (*it_layer)->print_z - EPSILON < wipe_tower_new_layer_print_z_first; ++ it_layer) ; + SupportLayerPtrs::iterator it_end = this->objects.front()->support_layers.end(); + for (; it_layer != it_end && (*it_layer)->print_z - EPSILON < wipe_tower_new_layer_print_z_first; ++ it_layer); // Find the stopper of the sequence of wipe tower layers, which do not have a counterpart in an object or a support layer. for (size_t i = idx_begin; i < idx_end; ++ i) { ToolOrdering::LayerTools < = const_cast(m_tool_ordering.layer_tools()[i]); @@ -1005,9 +1006,9 @@ void Print::_make_wipe_tower() break; lt.has_support = true; // Insert the new support layer. - //FIXME the support layer ID is duplicated, but Vojtech hopes it is not being used anywhere anyway. double height = lt.print_z - m_tool_ordering.layer_tools()[i-1].print_z; - auto *new_layer = new SupportLayer((*it_layer)->id(), this->objects.front(), + //FIXME the support layer ID is set to -1, as Vojtech hopes it is not being used anyway. + auto *new_layer = new SupportLayer(size_t(-1), this->objects.front(), height, lt.print_z, lt.print_z - 0.5 * height); it_layer = this->objects.front()->support_layers.insert(it_layer, new_layer); ++ it_layer; From f4522cd2fc193d747fbbce566b028ba62ffd0ddd Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Tue, 13 Feb 2018 13:16:23 +0100 Subject: [PATCH 38/57] GCode Preview - Customizable extrusion role colors by editing 3DPreview.pm --- lib/Slic3r/GUI/Plater/3DPreview.pm | 18 +++++++++++++ xs/src/libslic3r/GCode/Analyzer.cpp | 12 +++++++++ xs/src/libslic3r/GCode/Analyzer.hpp | 2 ++ xs/src/libslic3r/Print.cpp | 42 +++++++++++++++++++++++++++++ xs/src/libslic3r/Print.hpp | 12 +++++++++ xs/xsp/Print.xsp | 1 + 6 files changed, 87 insertions(+) diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index fb1a9bbfc..f0175f5a4 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -233,6 +233,24 @@ sub new { # init canvas $self->print($print); + + # sets colors for gcode preview extrusion roles + my @extrusion_roles_colors = ( + 'Perimeter' => 'FF0000', + 'External perimeter' => '00FF00', + 'Overhang perimeter' => '0000FF', + 'Internal infill' => 'FFFF00', + 'Solid infill' => 'FF00FF', + 'Top solid infill' => '00FFFF', + 'Bridge infill' => '7F7F7F', + 'Gap fill' => 'FFFFFF', + 'Skirt' => '7F0000', + 'Support material' => '007F00', + 'Support material interface' => '00007F', + 'Wipe tower' => 'B3E3AB', + ); + $self->print->set_gcode_extrusion_paths_colors(\@extrusion_roles_colors); + $self->reload_print; return $self; diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index c64857566..02e999bb4 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -347,6 +347,18 @@ const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::get_extrusi return extrusion.ranges.feedrate.get_color_at(feedrate); } +void GCodeAnalyzer::PreviewData::set_extrusion_role_color(const std::string& role_name, float red, float green, float blue, float alpha) +{ + for (unsigned int i = 0; i < Extrusion::Num_Extrusion_Roles; ++i) + { + if (role_name == extrusion.role_names[i]) + { + extrusion.role_colors[i] = Color(red, green, blue, alpha); + break; + } + } +} + std::string GCodeAnalyzer::PreviewData::get_legend_title() const { switch (extrusion.view_type) diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index 6d0213422..121360dbc 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -279,6 +279,8 @@ public: const Color& get_extrusion_width_color(float width) const; const Color& get_extrusion_feedrate_color(float feedrate) const; + void set_extrusion_role_color(const std::string& role_name, float red, float green, float blue, float alpha); + std::string get_legend_title() const; LegendItemsList get_legend_items(const std::vector& tool_colors) const; }; diff --git a/xs/src/libslic3r/Print.cpp b/xs/src/libslic3r/Print.cpp index 172b26cc4..bf0951f11 100644 --- a/xs/src/libslic3r/Print.cpp +++ b/xs/src/libslic3r/Print.cpp @@ -107,6 +107,48 @@ void Print::set_gcode_preview_shells_visible(bool visible) gcode_preview.shell.is_visible = visible; } +void Print::set_gcode_extrusion_paths_colors(const std::vector& colors) +{ + unsigned int size = (unsigned int)colors.size(); + + if (size % 2 != 0) + return; + + for (unsigned int i = 0; i < size; i += 2) + { + const std::string& color_str = colors[i + 1]; + + if (color_str.size() == 6) + { + bool valid = true; + for (int c = 0; c < 6; ++c) + { + if (::isxdigit(color_str[c]) == 0) + { + valid = false; + break; + } + } + + if (valid) + { + unsigned int color; + std::stringstream ss; + ss << std::hex << color_str; + ss >> color; + + float den = 1.0f / 255.0f; + + float r = (float)((color & 0xFF0000) >> 16) * den; + float g = (float)((color & 0x00FF00) >> 8) * den; + float b = (float)(color & 0x0000FF) * den; + + gcode_preview.set_extrusion_role_color(colors[i], r, g, b, 1.0f); + } + } + } +} + PrintRegion* Print::add_region() { regions.push_back(new PrintRegion(this)); diff --git a/xs/src/libslic3r/Print.hpp b/xs/src/libslic3r/Print.hpp index 0a6c143b9..da94917fc 100644 --- a/xs/src/libslic3r/Print.hpp +++ b/xs/src/libslic3r/Print.hpp @@ -264,6 +264,18 @@ public: void set_gcode_preview_unretractions_visible(bool visible); void set_gcode_preview_shells_visible(bool visible); + // Sets the extrusion path colors from the given strings vector. + // Data in the vector should be formatted as follows: + // std::vector role_colors = + // { , , + // , , + // , , + // ... + // , }; + // where should be a string from GCodeAnalyzer::PreviewData::Extrusion::Default_Extrusion_Role_Names[] + // and an RGB color in hex format (i.e. red = FF0000) + void set_gcode_extrusion_paths_colors(const std::vector& colors); + // methods for handling regions PrintRegion* get_region(size_t idx) { return regions.at(idx); } const PrintRegion* get_region(size_t idx) const { return regions.at(idx); } diff --git a/xs/xsp/Print.xsp b/xs/xsp/Print.xsp index 4f870df68..5749c20db 100644 --- a/xs/xsp/Print.xsp +++ b/xs/xsp/Print.xsp @@ -172,6 +172,7 @@ _constant() void set_gcode_preview_retractions_visible(bool visible); void set_gcode_preview_unretractions_visible(bool visible); void set_gcode_preview_shells_visible(bool visible); + void set_gcode_extrusion_paths_colors(std::vector colors); PrintRegionPtrs* regions() %code%{ RETVAL = &THIS->regions; %}; From 8885f5e3447d83e333cf30185189befdee3e9f92 Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Tue, 13 Feb 2018 15:19:55 +0100 Subject: [PATCH 39/57] 3mf import/export of config data --- lib/Slic3r/GUI/Plater.pm | 17 +++- xs/src/libslic3r/Config.cpp | 46 ++++++----- xs/src/libslic3r/Config.hpp | 3 +- xs/src/libslic3r/Format/3mf.cpp | 126 +++++++++++++++++++++-------- xs/src/libslic3r/Format/3mf.hpp | 11 ++- xs/src/libslic3r/GCode.cpp | 29 +++++-- xs/src/libslic3r/GCode.hpp | 3 + xs/src/libslic3r/Model.cpp | 29 ++++++- xs/src/libslic3r/Model.hpp | 2 + xs/src/slic3r/GUI/PresetBundle.cpp | 16 +++- xs/src/slic3r/GUI/PresetBundle.hpp | 5 ++ xs/xsp/Model.xsp | 20 ++++- 12 files changed, 231 insertions(+), 76 deletions(-) diff --git a/lib/Slic3r/GUI/Plater.pm b/lib/Slic3r/GUI/Plater.pm index d9c586685..be94095c9 100644 --- a/lib/Slic3r/GUI/Plater.pm +++ b/lib/Slic3r/GUI/Plater.pm @@ -628,8 +628,19 @@ sub load_files { my $input_file = $input_files->[$i]; $process_dialog->Update(100. * $i / @$input_files, "Processing input file\n" . basename($input_file)); - my $model = eval { Slic3r::Model->read_from_file($input_file, 0) }; - Slic3r::GUI::show_error($self, $@) if $@; + my $model; + if ($input_file =~ /.3[mM][fF]$/) + { + $model = eval { Slic3r::Model->read_from_archive($input_file, wxTheApp->{preset_bundle}, 0) }; + Slic3r::GUI::show_error($self, $@) if $@; + $_->load_current_preset for (values %{$self->GetFrame->{options_tabs}}); + wxTheApp->{app_config}->update_config_dir(dirname($input_file)); + } + else + { + $model = eval { Slic3r::Model->read_from_file($input_file, 0) }; + Slic3r::GUI::show_error($self, $@) if $@; + } next if ! defined $model; @@ -1555,7 +1566,7 @@ sub export_3mf { return if !@{$self->{objects}}; # Ask user for a file name to write into. my $output_file = $self->_get_export_file('3MF') or return; - my $res = $self->{model}->store_3mf($output_file); + my $res = $self->{model}->store_3mf($output_file, $self->{print}); if ($res) { $self->statusbar->SetStatusText("3MF file exported to $output_file"); diff --git a/xs/src/libslic3r/Config.cpp b/xs/src/libslic3r/Config.cpp index 474be7237..1a0b8fb4a 100644 --- a/xs/src/libslic3r/Config.cpp +++ b/xs/src/libslic3r/Config.cpp @@ -324,7 +324,7 @@ void ConfigBase::setenv_() void ConfigBase::load(const std::string &file) { if (boost::iends_with(file, ".gcode") || boost::iends_with(file, ".g")) - this->load_from_gcode(file); + this->load_from_gcode_file(file); else this->load_from_ini(file); } @@ -349,10 +349,10 @@ void ConfigBase::load(const boost::property_tree::ptree &tree) } } -// Load the config keys from the tail of a G-code. -void ConfigBase::load_from_gcode(const std::string &file) +// Load the config keys from the tail of a G-code file. +void ConfigBase::load_from_gcode_file(const std::string &file) { - // 1) Read a 64k block from the end of the G-code. + // Read a 64k block from the end of the G-code. boost::nowide::ifstream ifs(file); { const char slic3r_gcode_header[] = "; generated by Slic3r "; @@ -365,30 +365,39 @@ void ConfigBase::load_from_gcode(const std::string &file) auto file_length = ifs.tellg(); auto data_length = std::min(65535, file_length); ifs.seekg(file_length - data_length, ifs.beg); - std::vector data(size_t(data_length) + 1, 0); - ifs.read(data.data(), data_length); + std::vector data(size_t(data_length) + 1, 0); + ifs.read(data.data(), data_length); ifs.close(); - // 2) Walk line by line in reverse until a non-configuration key appears. - char *data_start = data.data(); + load_from_gcode_string(data.data()); +} + +// Load the config keys from the given string. +void ConfigBase::load_from_gcode_string(const char* str) +{ + if (str == nullptr) + return; + + // Walk line by line in reverse until a non-configuration key appears. + char *data_start = const_cast(str); // boost::nowide::ifstream seems to cook the text data somehow, so less then the 64k of characters may be retrieved. - char *end = data_start + strlen(data.data()); + char *end = data_start + strlen(str); size_t num_key_value_pairs = 0; for (;;) { // Extract next line. - for (-- end; end > data_start && (*end == '\r' || *end == '\n'); -- end); + for (--end; end > data_start && (*end == '\r' || *end == '\n'); --end); if (end == data_start) break; char *start = end; - *(++ end) = 0; - for (; start > data_start && *start != '\r' && *start != '\n'; -- start); + *(++end) = 0; + for (; start > data_start && *start != '\r' && *start != '\n'; --start); if (start == data_start) break; // Extracted a line from start to end. Extract the key = value pair. - if (end - (++ start) < 10 || start[0] != ';' || start[1] != ' ') + if (end - (++start) < 10 || start[0] != ';' || start[1] != ' ') break; char *key = start + 2; - if (! (*key >= 'a' && *key <= 'z') || (*key >= 'A' && *key <= 'Z')) + if (!(*key >= 'a' && *key <= 'z') || (*key >= 'A' && *key <= 'Z')) // A key must start with a letter. break; char *sep = strchr(key, '='); @@ -402,8 +411,8 @@ void ConfigBase::load_from_gcode(const std::string &file) break; *key_end = 0; // The key may contain letters, digits and underscores. - for (char *c = key; c != key_end; ++ c) - if (! ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <= 'Z') || (*c >= '0' && *c <= '9') || *c == '_')) { + for (char *c = key; c != key_end; ++c) + if (!((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <= 'Z') || (*c >= '0' && *c <= '9') || *c == '_')) { key = nullptr; break; } @@ -411,8 +420,9 @@ void ConfigBase::load_from_gcode(const std::string &file) break; try { this->set_deserialize(key, value); - ++ num_key_value_pairs; - } catch (UnknownOptionException & /* e */) { + ++num_key_value_pairs; + } + catch (UnknownOptionException & /* e */) { // ignore } end = start; diff --git a/xs/src/libslic3r/Config.hpp b/xs/src/libslic3r/Config.hpp index e04f4df82..db4b155e8 100644 --- a/xs/src/libslic3r/Config.hpp +++ b/xs/src/libslic3r/Config.hpp @@ -1049,7 +1049,8 @@ public: void setenv_(); void load(const std::string &file); void load_from_ini(const std::string &file); - void load_from_gcode(const std::string &file); + void load_from_gcode_file(const std::string &file); + void load_from_gcode_string(const char* str); void load(const boost::property_tree::ptree &tree); void save(const std::string &file) const; diff --git a/xs/src/libslic3r/Format/3mf.cpp b/xs/src/libslic3r/Format/3mf.cpp index 7fe9352b3..e8c9cfb32 100644 --- a/xs/src/libslic3r/Format/3mf.cpp +++ b/xs/src/libslic3r/Format/3mf.cpp @@ -1,10 +1,14 @@ #include "../libslic3r.h" #include "../Model.hpp" +#include "../Utils.hpp" +#include "../GCode.hpp" +#include "../slic3r/GUI/PresetBundle.hpp" #include "3mf.hpp" #include #include +#include #include #include @@ -17,6 +21,7 @@ const std::string MODEL_EXTENSION = ".model"; const std::string MODEL_FILE = "3D/3dmodel.model"; // << this is the only format of the string which works with CURA const std::string CONTENT_TYPES_FILE = "[Content_Types].xml"; const std::string RELATIONSHIPS_FILE = "_rels/.rels"; +const std::string CONFIG_FILE = "Metadata/Slic3r_PE.config"; const char* MODEL_TAG = "model"; const char* RESOURCES_TAG = "resources"; @@ -217,7 +222,7 @@ namespace Slic3r { _3MF_Importer(); ~_3MF_Importer(); - bool load_model_from_file(const std::string& filename, Model& model); + bool load_model_from_file(const std::string& filename, Model& model, PresetBundle& bundle); const std::vector& get_errors() const; @@ -225,8 +230,9 @@ namespace Slic3r { void _destroy_xml_parser(); void _stop_xml_parser(); - bool _load_model_from_file_miniz(const std::string& filename, Model& model); - bool _extract_model_from_archive_miniz(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat); + bool _load_model_from_file(const std::string& filename, Model& model, PresetBundle& bundle); + bool _extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat); + bool _extract_config_from_archive(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat, PresetBundle& bundle, const std::string& archive_filename); void _handle_start_xml_element(const char* name, const char** attributes); void _handle_end_xml_element(const char* name); @@ -331,7 +337,7 @@ namespace Slic3r { _destroy_xml_parser(); } - bool _3MF_Importer::load_model_from_file(const std::string& filename, Model& model) + bool _3MF_Importer::load_model_from_file(const std::string& filename, Model& model, PresetBundle& bundle) { m_model = &model; m_unit_factor = 1.0f; @@ -341,7 +347,7 @@ namespace Slic3r { m_instances.clear(); m_errors.clear(); - return _load_model_from_file_miniz(filename, model); + return _load_model_from_file(filename, model, bundle); } const std::vector& _3MF_Importer::get_errors() const @@ -364,7 +370,7 @@ namespace Slic3r { XML_StopParser(m_xml_parser, false); } - bool _3MF_Importer::_load_model_from_file_miniz(const std::string& filename, Model& model) + bool _3MF_Importer::_load_model_from_file(const std::string& filename, Model& model, PresetBundle& bundle) { mz_zip_archive archive; mz_zip_zero_struct(&archive); @@ -384,21 +390,28 @@ namespace Slic3r { if (mz_zip_reader_file_stat(&archive, i, &stat)) { std::string name(stat.m_filename); - std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) -> unsigned char { return std::tolower(c); }); std::replace(name.begin(), name.end(), '\\', '/'); - std::string lc_model_folder(MODEL_FOLDER); - std::transform(lc_model_folder.begin(), lc_model_folder.end(), lc_model_folder.begin(), [](unsigned char c) -> unsigned char { return std::tolower(c); }); - - if ((name.find(lc_model_folder) == 0) && (name.rfind(MODEL_EXTENSION) == name.length() - MODEL_EXTENSION.length())) + if (boost::algorithm::istarts_with(name, MODEL_FOLDER) && boost::algorithm::iends_with(name, MODEL_EXTENSION)) { - if (!_extract_model_from_archive_miniz(archive, stat)) + // valid model name -> extract model + if (!_extract_model_from_archive(archive, stat)) { mz_zip_reader_end(&archive); m_errors.push_back("Archive does not contain a valid model"); return false; } } + else if (boost::algorithm::iequals(name, CONFIG_FILE)) + { + // extract slic3r config file + if (!_extract_config_from_archive(archive, stat, bundle, filename)) + { + mz_zip_reader_end(&archive); + m_errors.push_back("Archive does not contain a valid config"); + return false; + } + } } } @@ -406,7 +419,7 @@ namespace Slic3r { return true; } - bool _3MF_Importer::_extract_model_from_archive_miniz(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat) + bool _3MF_Importer::_extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat) { _destroy_xml_parser(); @@ -430,7 +443,7 @@ namespace Slic3r { mz_bool res = mz_zip_reader_extract_file_to_mem(&archive, stat.m_filename, parser_buffer, (size_t)stat.m_uncomp_size, 0); if (res == 0) { - m_errors.push_back("Error while reading data to buffer"); + m_errors.push_back("Error while reading model data to buffer"); return false; } @@ -445,6 +458,25 @@ namespace Slic3r { return true; } + bool _3MF_Importer::_extract_config_from_archive(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat, PresetBundle& bundle, const std::string& archive_filename) + { + if (stat.m_uncomp_size > 0) + { + std::vector buffer((size_t)stat.m_uncomp_size + 1, 0); + mz_bool res = mz_zip_reader_extract_file_to_mem(&archive, stat.m_filename, (void*)buffer.data(), (size_t)stat.m_uncomp_size, 0); + if (res == 0) + { + m_errors.push_back("Error while reading config data to buffer"); + return false; + } + + buffer.back() = '\0'; + bundle.load_config_string(buffer.data(), archive_filename.c_str()); + } + + return true; + } + void _3MF_Importer::_handle_start_xml_element(const char* name, const char** attributes) { if (m_xml_parser == nullptr) @@ -994,18 +1026,19 @@ namespace Slic3r { std::vector m_errors; public: - bool save_model_to_file(const std::string& filename, Model& model); + bool save_model_to_file(const std::string& filename, Model& model, const Print& print); const std::vector& get_errors() const; private: - bool _save_model_to_file_miniz(const std::string& filename, Model& model); - bool _add_content_types_file_to_archive_miniz(mz_zip_archive& archive); - bool _add_relationships_file_to_archive_miniz(mz_zip_archive& archive); - bool _add_model_file_to_archive_miniz(mz_zip_archive& archive, Model& model); + bool _save_model_to_file(const std::string& filename, Model& model, const Print& print); + bool _add_content_types_file_to_archive(mz_zip_archive& archive); + bool _add_relationships_file_to_archive(mz_zip_archive& archive); + bool _add_model_file_to_archive(mz_zip_archive& archive, Model& model); bool _add_object_to_model_stream(std::stringstream& stream, unsigned int& object_id, ModelObject& object, BuildItemsList& build_items); bool _add_mesh_to_object_stream(std::stringstream& stream, ModelObject& object); bool _add_build_to_model_stream(std::stringstream& stream, const BuildItemsList& build_items); + bool _add_config_file_to_archive(mz_zip_archive& archive, const Print& print); }; _3MF_Exporter::BuildItem::BuildItem(unsigned int id, const Matrix4x4& matrix) @@ -1014,9 +1047,9 @@ namespace Slic3r { { } - bool _3MF_Exporter::save_model_to_file(const std::string& filename, Model& model) + bool _3MF_Exporter::save_model_to_file(const std::string& filename, Model& model, const Print& print) { - return _save_model_to_file_miniz(filename, model); + return _save_model_to_file(filename, model, print); } const std::vector& _3MF_Exporter::get_errors() const @@ -1024,7 +1057,7 @@ namespace Slic3r { return m_errors; } - bool _3MF_Exporter::_save_model_to_file_miniz(const std::string& filename, Model& model) + bool _3MF_Exporter::_save_model_to_file(const std::string& filename, Model& model, const Print& print) { mz_zip_archive archive; mz_zip_zero_struct(&archive); @@ -1037,7 +1070,7 @@ namespace Slic3r { } // adds content types file - if (!_add_content_types_file_to_archive_miniz(archive)) + if (!_add_content_types_file_to_archive(archive)) { mz_zip_writer_end(&archive); boost::filesystem::remove(filename); @@ -1045,7 +1078,7 @@ namespace Slic3r { } // adds relationships file - if (!_add_relationships_file_to_archive_miniz(archive)) + if (!_add_relationships_file_to_archive(archive)) { mz_zip_writer_end(&archive); boost::filesystem::remove(filename); @@ -1053,7 +1086,15 @@ namespace Slic3r { } // adds model file - if (!_add_model_file_to_archive_miniz(archive, model)) + if (!_add_model_file_to_archive(archive, model)) + { + mz_zip_writer_end(&archive); + boost::filesystem::remove(filename); + return false; + } + + // adds slic3r config file + if (!_add_config_file_to_archive(archive, print)) { mz_zip_writer_end(&archive); boost::filesystem::remove(filename); @@ -1073,7 +1114,7 @@ namespace Slic3r { return true; } - bool _3MF_Exporter::_add_content_types_file_to_archive_miniz(mz_zip_archive& archive) + bool _3MF_Exporter::_add_content_types_file_to_archive(mz_zip_archive& archive) { std::stringstream stream; stream << "\n"; @@ -1093,7 +1134,7 @@ namespace Slic3r { return true; } - bool _3MF_Exporter::_add_relationships_file_to_archive_miniz(mz_zip_archive& archive) + bool _3MF_Exporter::_add_relationships_file_to_archive(mz_zip_archive& archive) { std::stringstream stream; stream << "\n"; @@ -1112,7 +1153,7 @@ namespace Slic3r { return true; } - bool _3MF_Exporter::_add_model_file_to_archive_miniz(mz_zip_archive& archive, Model& model) + bool _3MF_Exporter::_add_model_file_to_archive(mz_zip_archive& archive, Model& model) { std::stringstream stream; stream << "\n"; @@ -1298,13 +1339,30 @@ namespace Slic3r { return true; } - bool load_3mf(const char* path, Model* model) + bool _3MF_Exporter::_add_config_file_to_archive(mz_zip_archive& archive, const Print& print) { - if ((path == nullptr) || (model == nullptr)) + char buffer[1024]; + sprintf(buffer, "; %s\n\n", header_slic3r_generated().c_str()); + std::string out = buffer; + + GCode::append_full_config(print, out); + + if (!mz_zip_writer_add_mem(&archive, CONFIG_FILE.c_str(), (const void*)out.data(), out.length(), MZ_DEFAULT_COMPRESSION)) + { + m_errors.push_back("Unable to add config file to archive"); + return false; + } + + return true; + } + + bool load_3mf(const char* path, PresetBundle* bundle, Model* model) + { + if ((path == nullptr) || (bundle == nullptr) || (model == nullptr)) return false; _3MF_Importer importer; - bool res = importer.load_model_from_file(path, *model); + bool res = importer.load_model_from_file(path, *model, *bundle); if (!res) const std::vector& errors = importer.get_errors(); @@ -1312,13 +1370,13 @@ namespace Slic3r { return res; } - bool store_3mf(const char* path, Model* model) + bool store_3mf(const char* path, Model* model, Print* print) { - if ((path == nullptr) || (model == nullptr)) + if ((path == nullptr) || (model == nullptr) || (print == nullptr)) return false; _3MF_Exporter exporter; - bool res = exporter.save_model_to_file(path, *model); + bool res = exporter.save_model_to_file(path, *model, *print); if (!res) const std::vector& errors = exporter.get_errors(); diff --git a/xs/src/libslic3r/Format/3mf.hpp b/xs/src/libslic3r/Format/3mf.hpp index ff178e3de..9b48c860b 100644 --- a/xs/src/libslic3r/Format/3mf.hpp +++ b/xs/src/libslic3r/Format/3mf.hpp @@ -4,13 +4,16 @@ namespace Slic3r { class Model; + class Print; + class PresetBundle; - // Load a 3mf file into the given model. - extern bool load_3mf(const char* path, Model* model); + // Load the content of a 3mf file into the given model and preset bundle. + extern bool load_3mf(const char* path, PresetBundle* bundle, Model* model); - // Save the given model into a 3mf file. + // Save the given model and the config data contained in the given Print into a 3mf file. // The model could be modified during the export process if meshes are not repaired or have no shared vertices - extern bool store_3mf(const char* path, Model* model); + extern bool store_3mf(const char* path, Model* model, Print* print); + }; // namespace Slic3r #endif /* slic3r_Format_3mf_hpp_ */ diff --git a/xs/src/libslic3r/GCode.cpp b/xs/src/libslic3r/GCode.cpp index d22040799..d42a61290 100644 --- a/xs/src/libslic3r/GCode.cpp +++ b/xs/src/libslic3r/GCode.cpp @@ -802,13 +802,10 @@ void GCode::_do_export(Print &print, FILE *file) // Append full config. _write(file, "\n"); { - StaticPrintConfig *configs[] = { &print.config, &print.default_object_config, &print.default_region_config }; - for (size_t i = 0; i < sizeof(configs) / sizeof(configs[0]); ++ i) { - StaticPrintConfig *cfg = configs[i]; - for (const std::string &key : cfg->keys()) - if (key != "compatible_printers") - _write_format(file, "; %s = %s\n", key.c_str(), cfg->serialize(key).c_str()); - } + std::string full_config = ""; + append_full_config(print, full_config); + if (!full_config.empty()) + _write(file, full_config); } } @@ -1372,6 +1369,24 @@ void GCode::apply_print_config(const PrintConfig &print_config) m_config.apply(print_config); } +void GCode::append_full_config(const Print& print, std::string& str) +{ + char buff[1024]; + + const StaticPrintConfig *configs[] = { &print.config, &print.default_object_config, &print.default_region_config }; + for (size_t i = 0; i < sizeof(configs) / sizeof(configs[0]); ++i) { + const StaticPrintConfig *cfg = configs[i]; + for (const std::string &key : cfg->keys()) + { + if (key != "compatible_printers") + { + sprintf(buff, "; %s = %s\n", key.c_str(), cfg->serialize(key).c_str()); + str += buff; + } + } + } +} + void GCode::set_extruders(const std::vector &extruder_ids) { m_writer.set_extruders(extruder_ids); diff --git a/xs/src/libslic3r/GCode.hpp b/xs/src/libslic3r/GCode.hpp index 5c622ec2d..8129ca1c5 100644 --- a/xs/src/libslic3r/GCode.hpp +++ b/xs/src/libslic3r/GCode.hpp @@ -155,6 +155,9 @@ public: void set_layer_count(unsigned int value) { m_layer_count = value; } void apply_print_config(const PrintConfig &print_config); + // append full config to the given string + static void append_full_config(const Print& print, std::string& str); + protected: void _do_export(Print &print, FILE *file); diff --git a/xs/src/libslic3r/Model.cpp b/xs/src/libslic3r/Model.cpp index b86b7e55e..891438407 100644 --- a/xs/src/libslic3r/Model.cpp +++ b/xs/src/libslic3r/Model.cpp @@ -54,10 +54,8 @@ Model Model::read_from_file(const std::string &input_file, bool add_default_inst else if (boost::algorithm::iends_with(input_file, ".prusa")) result = load_prus(input_file.c_str(), &model); #endif /* SLIC3R_PRUS */ - else if (boost::algorithm::iends_with(input_file, ".3mf")) - result = load_3mf(input_file.c_str(), &model); else - throw std::runtime_error("Unknown file format. Input file must have .stl, .obj, .amf(.xml), .3mf or .prusa extension."); + throw std::runtime_error("Unknown file format. Input file must have .stl, .obj, .amf(.xml) or .prusa extension."); if (! result) throw std::runtime_error("Loading of a model file failed."); @@ -74,6 +72,31 @@ Model Model::read_from_file(const std::string &input_file, bool add_default_inst return model; } +Model Model::read_from_archive(const std::string &input_file, PresetBundle* bundle, bool add_default_instances) +{ + Model model; + + bool result = false; + if (boost::algorithm::iends_with(input_file, ".3mf")) + result = load_3mf(input_file.c_str(), bundle, &model); + else + throw std::runtime_error("Unknown file format. Input file must have .3mf extension."); + + if (!result) + throw std::runtime_error("Loading of a model file failed."); + + if (model.objects.empty()) + throw std::runtime_error("The supplied file couldn't be read because it's empty"); + + for (ModelObject *o : model.objects) + o->input_file = input_file; + + if (add_default_instances) + model.add_default_instances(); + + return model; +} + ModelObject* Model::add_object() { this->objects.emplace_back(new ModelObject(this)); diff --git a/xs/src/libslic3r/Model.hpp b/xs/src/libslic3r/Model.hpp index 317d7ccbb..cf9bfd85a 100644 --- a/xs/src/libslic3r/Model.hpp +++ b/xs/src/libslic3r/Model.hpp @@ -19,6 +19,7 @@ class ModelInstance; class ModelMaterial; class ModelObject; class ModelVolume; +class PresetBundle; typedef std::string t_model_material_id; typedef std::string t_model_material_attribute; @@ -239,6 +240,7 @@ public: ~Model() { this->clear_objects(); this->clear_materials(); } static Model read_from_file(const std::string &input_file, bool add_default_instances = true); + static Model read_from_archive(const std::string &input_file, PresetBundle* bundle, bool add_default_instances = true); ModelObject* add_object(); ModelObject* add_object(const char *name, const char *path, const TriangleMesh &mesh); diff --git a/xs/src/slic3r/GUI/PresetBundle.cpp b/xs/src/slic3r/GUI/PresetBundle.cpp index decc5d00b..3b4bf097f 100644 --- a/xs/src/slic3r/GUI/PresetBundle.cpp +++ b/xs/src/slic3r/GUI/PresetBundle.cpp @@ -280,8 +280,8 @@ void PresetBundle::load_config_file(const std::string &path) if (boost::iends_with(path, ".gcode") || boost::iends_with(path, ".g")) { DynamicPrintConfig config; config.apply(FullPrintConfig::defaults()); - config.load_from_gcode(path); - Preset::normalize(config); + config.load_from_gcode_file(path); + Preset::normalize(config); load_config_file_config(path, true, std::move(config)); return; } @@ -320,6 +320,18 @@ void PresetBundle::load_config_file(const std::string &path) } } +void PresetBundle::load_config_string(const char* str, const char* source_filename) +{ + if (str != nullptr) + { + DynamicPrintConfig config; + config.apply(FullPrintConfig::defaults()); + config.load_from_gcode_string(str); + Preset::normalize(config); + load_config_file_config((source_filename == nullptr) ? "" : source_filename, true, std::move(config)); + } +} + // Load a config file from a boost property_tree. This is a private method called from load_config_file. void PresetBundle::load_config_file_config(const std::string &name_or_path, bool is_external, DynamicPrintConfig &&config) { diff --git a/xs/src/slic3r/GUI/PresetBundle.hpp b/xs/src/slic3r/GUI/PresetBundle.hpp index df04efd73..e6aea206d 100644 --- a/xs/src/slic3r/GUI/PresetBundle.hpp +++ b/xs/src/slic3r/GUI/PresetBundle.hpp @@ -55,6 +55,11 @@ public: // If the file is loaded successfully, its print / filament / printer profiles will be activated. void load_config_file(const std::string &path); + // Load an external config source containing the print, filament and printer presets. + // The given string must contain the full set of parameters (same as those exported to gcode). + // If the string is parsed successfully, its print / filament / printer profiles will be activated. + void load_config_string(const char* str, const char* source_filename = nullptr); + // Load a config bundle file, into presets and store the loaded presets into separate files // of the local configuration directory. // Load settings into the provided settings instance. diff --git a/xs/xsp/Model.xsp b/xs/xsp/Model.xsp index 9a2a50437..ae0621057 100644 --- a/xs/xsp/Model.xsp +++ b/xs/xsp/Model.xsp @@ -3,6 +3,7 @@ %{ #include #include "libslic3r/Model.hpp" +#include "libslic3r/Print.hpp" #include "libslic3r/PrintConfig.hpp" #include "libslic3r/Slicing.hpp" #include "libslic3r/Format/AMF.hpp" @@ -10,6 +11,7 @@ #include "libslic3r/Format/OBJ.hpp" #include "libslic3r/Format/PRUS.hpp" #include "libslic3r/Format/STL.hpp" +#include "slic3r/GUI/PresetBundle.hpp" %} %name{Slic3r::Model} class Model { @@ -25,6 +27,15 @@ } %}; + %name{read_from_archive} Model(std::string input_file, PresetBundle* bundle, bool add_default_instances = true) + %code%{ + try { + RETVAL = new Model(Model::read_from_archive(input_file, bundle, add_default_instances)); + } catch (std::exception& e) { + croak("Error while opening %s: %s\n", input_file.c_str(), e.what()); + } + %}; + Clone clone() %code%{ RETVAL = THIS; %}; @@ -92,8 +103,8 @@ %code%{ TriangleMesh mesh = THIS->mesh(); RETVAL = Slic3r::store_stl(path, &mesh, binary); %}; bool store_amf(char *path) %code%{ RETVAL = Slic3r::store_amf(path, THIS); %}; - bool store_3mf(char *path) - %code%{ RETVAL = Slic3r::store_3mf(path, THIS); %}; + bool store_3mf(char *path, Print* print) + %code%{ RETVAL = Slic3r::store_3mf(path, THIS, print); %}; %{ @@ -139,12 +150,13 @@ load_amf(CLASS, path) RETVAL Model* -load_3mf(CLASS, path) +load_3mf(CLASS, bundle, path) char* CLASS; + PresetBundle* bundle; char* path; CODE: RETVAL = new Model(); - if (! load_3mf(path, RETVAL)) { + if (! load_3mf(path, bundle, RETVAL)) { delete RETVAL; RETVAL = NULL; } From bacb36eb10848b4759c75a5d13a1de6fad7edfec Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Tue, 13 Feb 2018 15:33:45 +0100 Subject: [PATCH 40/57] 3mf - Fixed include for Linux build --- xs/src/libslic3r/Format/3mf.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xs/src/libslic3r/Format/3mf.cpp b/xs/src/libslic3r/Format/3mf.cpp index e8c9cfb32..60ddf5d02 100644 --- a/xs/src/libslic3r/Format/3mf.cpp +++ b/xs/src/libslic3r/Format/3mf.cpp @@ -13,7 +13,7 @@ #include #include -#include +#include #include const std::string MODEL_FOLDER = "3D/"; From 6cf82643626c1d8196694cf1cf7f0657fc2134bb Mon Sep 17 00:00:00 2001 From: bubnikv Date: Tue, 13 Feb 2018 17:46:23 +0100 Subject: [PATCH 41/57] Re-enabled $combochecklist_features->UseAltPopupWindow(), without this line the combo box popup was not reacting to mouse events on Windows 10. --- lib/Slic3r/GUI/Plater/3DPreview.pm | 3 +++ xs/src/slic3r/GUI/GUI.cpp | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index f0175f5a4..6f96b8a96 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -72,6 +72,9 @@ sub new { my $combochecklist_features = Wx::ComboCtrl->new(); $combochecklist_features->Create($self, -1, "Feature types", wxDefaultPosition, [200, -1], wxCB_READONLY); + #FIXME If the following line is removed, the combo box popup list will not react to mouse clicks. + # On the other side, with this line the combo box popup cannot be closed by clicking on the combo button on Windows 10. + $combochecklist_features->UseAltPopupWindow(); $combochecklist_features->EnablePopupAnimation(0); my $feature_text = "Feature types"; my $feature_items = "Perimeter|External perimeter|Overhang perimeter|Internal infill|Solid infill|Top solid infill|Bridge infill|Gap fill|Skirt|Support material|Support material interface|Wipe tower"; diff --git a/xs/src/slic3r/GUI/GUI.cpp b/xs/src/slic3r/GUI/GUI.cpp index 775cfdcf6..809ee8508 100644 --- a/xs/src/slic3r/GUI/GUI.cpp +++ b/xs/src/slic3r/GUI/GUI.cpp @@ -227,7 +227,7 @@ int combochecklist_get_flags(wxComboCtrl* comboCtrl) for (unsigned int i = 0; i < popup->GetCount(); ++i) { if (popup->IsChecked(i)) - flags += (int)std::pow(2.0f, (float)i); + flags |= 1 << i; } } From 6e80a9111c3faa5e976e56169ad133bdd82637a1 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Tue, 13 Feb 2018 18:31:34 +0100 Subject: [PATCH 42/57] Reworked the plater UI messages to standard wxWidgets wxCommandEvent messages to support receiving status line updates from the C++ code. --- lib/Slic3r/GUI/Plater.pm | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/lib/Slic3r/GUI/Plater.pm b/lib/Slic3r/GUI/Plater.pm index 10d65475c..8902a5513 100644 --- a/lib/Slic3r/GUI/Plater.pm +++ b/lib/Slic3r/GUI/Plater.pm @@ -63,7 +63,10 @@ sub new { $self->{print}->set_status_cb(sub { my ($percent, $message) = @_; - Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $PROGRESS_BAR_EVENT, shared_clone([$percent, $message]))); + my $event = Wx::CommandEvent->new($PROGRESS_BAR_EVENT); + $event->SetString($message); + $event->SetInt($percent); + Wx::PostEvent($self, $event); }); # Initialize preview notebook @@ -307,23 +310,22 @@ sub new { EVT_COMMAND($self, -1, $PROGRESS_BAR_EVENT, sub { my ($self, $event) = @_; - my ($percent, $message) = @{$event->GetData}; - $self->on_progress_event($percent, $message); + $self->on_progress_event($event->GetInt, $event->GetString); }); EVT_COMMAND($self, -1, $ERROR_EVENT, sub { my ($self, $event) = @_; - Slic3r::GUI::show_error($self, @{$event->GetData}); + Slic3r::GUI::show_error($self, $event->GetString); }); EVT_COMMAND($self, -1, $EXPORT_COMPLETED_EVENT, sub { my ($self, $event) = @_; - $self->on_export_completed($event->GetData); + $self->on_export_completed($event->GetInt); }); EVT_COMMAND($self, -1, $PROCESS_COMPLETED_EVENT, sub { my ($self, $event) = @_; - $self->on_process_completed($event->GetData); + $self->on_process_completed($event->GetInt ? undef : $event->GetString); }); { @@ -1184,12 +1186,15 @@ sub start_background_process { eval { $self->{print}->process; }; + my $event = Wx::CommandEvent->new($PROCESS_COMPLETED_EVENT); if ($@) { Slic3r::debugf "Background process error: $@\n"; - Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $PROCESS_COMPLETED_EVENT, $@)); + $event->SetInt(0); + $event->SetString($@); } else { - Wx::PostEvent($self, Wx::PlThreadEvent->new(-1, $PROCESS_COMPLETED_EVENT, undef)); + $event->SetInt(1); } + Wx::PostEvent($self, $event); Slic3r::thread_cleanup(); }); Slic3r::debugf "Background processing started.\n"; @@ -1367,12 +1372,19 @@ sub on_process_completed { eval { $_thread_self->{print}->export_gcode(output_file => $_thread_self->{export_gcode_output_file}); }; + my $export_completed_event = Wx::CommandEvent->new($EXPORT_COMPLETED_EVENT); if ($@) { - Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $ERROR_EVENT, shared_clone([ $@ ]))); - Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $EXPORT_COMPLETED_EVENT, 0)); + { + my $error_event = Wx::CommandEvent->new($ERROR_EVENT); + $error_event->SetString($@); + Wx::PostEvent($_thread_self, $error_event); + } + $export_completed_event->SetInt(0); + $export_completed_event->SetString($@); } else { - Wx::PostEvent($_thread_self, Wx::PlThreadEvent->new(-1, $EXPORT_COMPLETED_EVENT, 1)); + $export_completed_event->SetInt(1); } + Wx::PostEvent($_thread_self, $export_completed_event); Slic3r::thread_cleanup(); }); Slic3r::debugf "Background G-code export started.\n"; From f5f27859e026876de2501f11219f29702483b20f Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Wed, 14 Feb 2018 14:30:03 +0100 Subject: [PATCH 43/57] AMF I/O - Embedded config data + zip formatting --- lib/Slic3r/GUI/Plater.pm | 21 ++- xs/src/libslic3r/Format/3mf.cpp | 107 +++++++------ xs/src/libslic3r/Format/AMF.cpp | 265 +++++++++++++++++++++++++------- xs/src/libslic3r/Format/AMF.hpp | 10 +- xs/src/libslic3r/Model.cpp | 10 +- xs/xsp/Model.xsp | 9 +- 6 files changed, 299 insertions(+), 123 deletions(-) diff --git a/lib/Slic3r/GUI/Plater.pm b/lib/Slic3r/GUI/Plater.pm index be94095c9..82b4e3cfb 100644 --- a/lib/Slic3r/GUI/Plater.pm +++ b/lib/Slic3r/GUI/Plater.pm @@ -610,7 +610,7 @@ sub load_files { # One of the files is potentionally a bundle of files. Don't bundle them, but load them one by one. # Only bundle .stls or .objs if the printer has multiple extruders. my $one_by_one = (@$nozzle_dmrs <= 1) || (@$input_files == 1) || - defined(first { $_ =~ /.[aA][mM][fF]$/ || $_ =~ /.3[mM][fF]$/ || $_ =~ /.[pP][rR][uI][sS][aA]$/ } @$input_files); + defined(first { $_ =~ /.[aA][mM][fF]$/ || $_ =~ /.[aA][mM][fF].[xX][mM][lL]$/ || $_ =~ /.[zZ][iI][pP].[aA][mM][fF]$/ || $_ =~ /.3[mM][fF]$/ || $_ =~ /.[pP][rR][uI][sS][aA]$/ } @$input_files); my $process_dialog = Wx::ProgressDialog->new('Loading…', "Processing input file\n" . basename($input_files->[0]), 100, $self, 0); $process_dialog->Pulse; @@ -629,7 +629,7 @@ sub load_files { $process_dialog->Update(100. * $i / @$input_files, "Processing input file\n" . basename($input_file)); my $model; - if ($input_file =~ /.3[mM][fF]$/) + if (($input_file =~ /.3[mM][fF]$/) || ($input_file =~ /.[zZ][iI][pP].[aA][mM][fF]$/)) { $model = eval { Slic3r::Model->read_from_archive($input_file, wxTheApp->{preset_bundle}, 0) }; Slic3r::GUI::show_error($self, $@) if $@; @@ -1557,8 +1557,15 @@ sub export_amf { return if !@{$self->{objects}}; # Ask user for a file name to write into. my $output_file = $self->_get_export_file('AMF') or return; - $self->{model}->store_amf($output_file); - $self->statusbar->SetStatusText("AMF file exported to $output_file"); + my $res = $self->{model}->store_amf($output_file, $self->{print}); + if ($res) + { + $self->statusbar->SetStatusText("AMF file exported to $output_file"); + } + else + { + $self->statusbar->SetStatusText("Error exporting AMF file $output_file"); + } } sub export_3mf { @@ -1588,7 +1595,7 @@ sub _get_export_file { } elsif ($format eq 'AMF') { - $suffix = '.amf.xml'; + $suffix = '.zip.amf'; } elsif ($format eq '3MF') { @@ -2102,8 +2109,8 @@ sub OnDropFiles { # stop scalars leaking on older perl # https://rt.perl.org/rt3/Public/Bug/Display.html?id=70602 @_ = (); - # only accept STL, OBJ, AMF and 3MF files - return 0 if grep !/\.(?:[sS][tT][lL]|[oO][bB][jJ]|[aA][mM][fF]|[3][mM][fF](?:\.[xX][mM][lL])?|[pP][rR][uU][sS][aA])$/, @$filenames; + # only accept STL, OBJ, AMF, 3MF and PRUSA files + return 0 if grep !/\.(?:[sS][tT][lL]|[oO][bB][jJ]|[aA][mM][fF]|[3][mM][fF]|[aA][mM][fF].[xX][mM][lL]|[zZ][iI][pP].[aA][mM][lL]|[pP][rR][uU][sS][aA])$/, @$filenames; $self->{window}->load_files($filenames); } diff --git a/xs/src/libslic3r/Format/3mf.cpp b/xs/src/libslic3r/Format/3mf.cpp index 60ddf5d02..029debf72 100644 --- a/xs/src/libslic3r/Format/3mf.cpp +++ b/xs/src/libslic3r/Format/3mf.cpp @@ -162,7 +162,26 @@ bool is_valid_object_type(const std::string& type) namespace Slic3r { - class _3MF_Importer + // Base class with error messages management + class _3MF_Base + { + std::vector m_errors; + + protected: + void add_error(const std::string& error) { m_errors.push_back(error); } + void clear_errors() { m_errors.clear(); } + + public: + void log_errors() + { + for (const std::string& error : m_errors) + { + printf("%s\n", error.c_str()); + } + } + }; + + class _3MF_Importer : public _3MF_Base { struct Component { @@ -216,7 +235,6 @@ namespace Slic3r { IdToModelObjectMap m_objects; IdToAliasesMap m_objects_aliases; InstancesList m_instances; - std::vector m_errors; public: _3MF_Importer(); @@ -224,8 +242,6 @@ namespace Slic3r { bool load_model_from_file(const std::string& filename, Model& model, PresetBundle& bundle); - const std::vector& get_errors() const; - private: void _destroy_xml_parser(); void _stop_xml_parser(); @@ -345,16 +361,11 @@ namespace Slic3r { m_objects.clear(); m_objects_aliases.clear(); m_instances.clear(); - m_errors.clear(); + clear_errors(); return _load_model_from_file(filename, model, bundle); } - const std::vector& _3MF_Importer::get_errors() const - { - return m_errors; - } - void _3MF_Importer::_destroy_xml_parser() { if (m_xml_parser != nullptr) @@ -378,7 +389,7 @@ namespace Slic3r { mz_bool res = mz_zip_reader_init_file(&archive, filename.c_str(), 0); if (res == 0) { - m_errors.push_back("Unable to open the file"); + add_error("Unable to open the file"); return false; } @@ -398,7 +409,7 @@ namespace Slic3r { if (!_extract_model_from_archive(archive, stat)) { mz_zip_reader_end(&archive); - m_errors.push_back("Archive does not contain a valid model"); + add_error("Archive does not contain a valid model"); return false; } } @@ -408,7 +419,7 @@ namespace Slic3r { if (!_extract_config_from_archive(archive, stat, bundle, filename)) { mz_zip_reader_end(&archive); - m_errors.push_back("Archive does not contain a valid config"); + add_error("Archive does not contain a valid config"); return false; } } @@ -421,12 +432,18 @@ namespace Slic3r { bool _3MF_Importer::_extract_model_from_archive(mz_zip_archive& archive, const mz_zip_archive_file_stat& stat) { + if (stat.m_uncomp_size == 0) + { + add_error("Found invalid size"); + return false; + } + _destroy_xml_parser(); m_xml_parser = XML_ParserCreate(nullptr); if (m_xml_parser == nullptr) { - m_errors.push_back("Unable to create parser"); + add_error("Unable to create parser"); return false; } @@ -436,14 +453,14 @@ namespace Slic3r { void* parser_buffer = XML_GetBuffer(m_xml_parser, (int)stat.m_uncomp_size); if (parser_buffer == nullptr) { - m_errors.push_back("Unable to create buffer"); + add_error("Unable to create buffer"); return false; } mz_bool res = mz_zip_reader_extract_file_to_mem(&archive, stat.m_filename, parser_buffer, (size_t)stat.m_uncomp_size, 0); if (res == 0) { - m_errors.push_back("Error while reading model data to buffer"); + add_error("Error while reading model data to buffer"); return false; } @@ -451,7 +468,7 @@ namespace Slic3r { { char error_buf[1024]; ::sprintf(error_buf, "Error (%s) while parsing xml file at line %d", XML_ErrorString(XML_GetErrorCode(m_xml_parser)), XML_GetCurrentLineNumber(m_xml_parser)); - m_errors.push_back(error_buf); + add_error(error_buf); return false; } @@ -466,7 +483,7 @@ namespace Slic3r { mz_bool res = mz_zip_reader_extract_file_to_mem(&archive, stat.m_filename, (void*)buffer.data(), (size_t)stat.m_uncomp_size, 0); if (res == 0) { - m_errors.push_back("Error while reading config data to buffer"); + add_error("Error while reading config data to buffer"); return false; } @@ -613,7 +630,7 @@ namespace Slic3r { m_curr_object.object = m_model->add_object(); if (m_curr_object.object == nullptr) { - m_errors.push_back("Unable to create object"); + add_error("Unable to create object"); return false; } @@ -657,7 +674,7 @@ namespace Slic3r { ModelVolume* volume = m_curr_object.object->add_volume(m_curr_object.mesh); if (volume == nullptr) { - m_errors.push_back("Unable to add volume"); + add_error("Unable to add volume"); return false; } @@ -685,7 +702,7 @@ namespace Slic3r { } else { - m_errors.push_back("Found object with duplicate id"); + add_error("Found object with duplicate id"); return false; } } @@ -796,7 +813,7 @@ namespace Slic3r { IdToAliasesMap::iterator alias_item = m_objects_aliases.find(object_id); if (alias_item == m_objects_aliases.end()) { - m_errors.push_back("Found component with invalid object id"); + add_error("Found component with invalid object id"); return false; } } @@ -852,14 +869,14 @@ namespace Slic3r { // escape from circular aliasing if (recur_counter > MAX_RECURSIONS) { - m_errors.push_back("Too many recursions"); + add_error("Too many recursions"); return false; } IdToAliasesMap::iterator it = m_objects_aliases.find(object_id); if (it == m_objects_aliases.end()) { - m_errors.push_back("Found item with invalid object id"); + add_error("Found item with invalid object id"); return false; } @@ -870,7 +887,7 @@ namespace Slic3r { IdToModelObjectMap::iterator object_item = m_objects.find(object_id); if ((object_item == m_objects.end()) || (object_item->second == nullptr)) { - m_errors.push_back("Found invalid object"); + add_error("Found invalid object"); return false; } else @@ -878,7 +895,7 @@ namespace Slic3r { ModelInstance* instance = object_item->second->add_instance(); if (instance == nullptr) { - m_errors.push_back("Unable to add object instance"); + add_error("Unable to add object instance"); return false; } @@ -1011,7 +1028,7 @@ namespace Slic3r { importer->_handle_end_xml_element(name); } - class _3MF_Exporter + class _3MF_Exporter : public _3MF_Base { struct BuildItem { @@ -1023,13 +1040,9 @@ namespace Slic3r { typedef std::vector BuildItemsList; - std::vector m_errors; - public: bool save_model_to_file(const std::string& filename, Model& model, const Print& print); - const std::vector& get_errors() const; - private: bool _save_model_to_file(const std::string& filename, Model& model, const Print& print); bool _add_content_types_file_to_archive(mz_zip_archive& archive); @@ -1049,14 +1062,10 @@ namespace Slic3r { bool _3MF_Exporter::save_model_to_file(const std::string& filename, Model& model, const Print& print) { + clear_errors(); return _save_model_to_file(filename, model, print); } - const std::vector& _3MF_Exporter::get_errors() const - { - return m_errors; - } - bool _3MF_Exporter::_save_model_to_file(const std::string& filename, Model& model, const Print& print) { mz_zip_archive archive; @@ -1065,7 +1074,7 @@ namespace Slic3r { mz_bool res = mz_zip_writer_init_file(&archive, filename.c_str(), 0); if (res == 0) { - m_errors.push_back("Unable to open the file"); + add_error("Unable to open the file"); return false; } @@ -1105,7 +1114,7 @@ namespace Slic3r { { mz_zip_writer_end(&archive); boost::filesystem::remove(filename); - m_errors.push_back("Unable to finalize the archive"); + add_error("Unable to finalize the archive"); return false; } @@ -1127,7 +1136,7 @@ namespace Slic3r { if (!mz_zip_writer_add_mem(&archive, CONTENT_TYPES_FILE.c_str(), (const void*)out.data(), out.length(), MZ_DEFAULT_COMPRESSION)) { - m_errors.push_back("Unable to add content types file to archive"); + add_error("Unable to add content types file to archive"); return false; } @@ -1146,7 +1155,7 @@ namespace Slic3r { if (!mz_zip_writer_add_mem(&archive, RELATIONSHIPS_FILE.c_str(), (const void*)out.data(), out.length(), MZ_DEFAULT_COMPRESSION)) { - m_errors.push_back("Unable to add relationships file to archive"); + add_error("Unable to add relationships file to archive"); return false; } @@ -1170,7 +1179,7 @@ namespace Slic3r { if (!_add_object_to_model_stream(stream, object_id, *obj, build_items)) { - m_errors.push_back("Unable to add object to archive"); + add_error("Unable to add object to archive"); return false; } } @@ -1180,7 +1189,7 @@ namespace Slic3r { if (!_add_build_to_model_stream(stream, build_items)) { - m_errors.push_back("Unable to add build to archive"); + add_error("Unable to add build to archive"); return false; } @@ -1190,7 +1199,7 @@ namespace Slic3r { if (!mz_zip_writer_add_mem(&archive, MODEL_FILE.c_str(), (const void*)out.data(), out.length(), MZ_DEFAULT_COMPRESSION)) { - m_errors.push_back("Unable to add model file to archive"); + add_error("Unable to add model file to archive"); return false; } @@ -1212,7 +1221,7 @@ namespace Slic3r { { if (!_add_mesh_to_object_stream(stream, object)) { - m_errors.push_back("Unable to add mesh to archive"); + add_error("Unable to add mesh to archive"); return false; } } @@ -1262,7 +1271,7 @@ namespace Slic3r { if (stl.stats.shared_vertices == 0) { - m_errors.push_back("Found invalid mesh"); + add_error("Found invalid mesh"); return false; } @@ -1313,7 +1322,7 @@ namespace Slic3r { { if (build_items.size() == 0) { - m_errors.push_back("No build item found"); + add_error("No build item found"); return false; } @@ -1349,7 +1358,7 @@ namespace Slic3r { if (!mz_zip_writer_add_mem(&archive, CONFIG_FILE.c_str(), (const void*)out.data(), out.length(), MZ_DEFAULT_COMPRESSION)) { - m_errors.push_back("Unable to add config file to archive"); + add_error("Unable to add config file to archive"); return false; } @@ -1365,7 +1374,7 @@ namespace Slic3r { bool res = importer.load_model_from_file(path, *model, *bundle); if (!res) - const std::vector& errors = importer.get_errors(); + importer.log_errors(); return res; } @@ -1379,7 +1388,7 @@ namespace Slic3r { bool res = exporter.save_model_to_file(path, *model, *print); if (!res) - const std::vector& errors = exporter.get_errors(); + exporter.log_errors(); return res; } diff --git a/xs/src/libslic3r/Format/AMF.cpp b/xs/src/libslic3r/Format/AMF.cpp index b8abf038b..06ba20120 100644 --- a/xs/src/libslic3r/Format/AMF.cpp +++ b/xs/src/libslic3r/Format/AMF.cpp @@ -7,8 +7,14 @@ #include "../libslic3r.h" #include "../Model.hpp" +#include "../GCode.hpp" +#include "../slic3r/GUI/PresetBundle.hpp" #include "AMF.hpp" +#include +#include +#include + #if 0 // Enable debugging and assert in this file. #define DEBUG @@ -18,18 +24,22 @@ #include +const char* SLIC3R_CONFIG_TYPE = "slic3rpe_config"; + namespace Slic3r { struct AMFParserContext { - AMFParserContext(XML_Parser parser, Model *model) : + AMFParserContext(XML_Parser parser, const std::string& archive_filename, PresetBundle* preset_bundle, Model *model) : m_parser(parser), m_model(*model), m_object(nullptr), m_volume(nullptr), m_material(nullptr), - m_instance(nullptr) + m_instance(nullptr), + m_preset_bundle(preset_bundle), + m_archive_filename(archive_filename) { m_path.reserve(12); } @@ -149,6 +159,10 @@ struct AMFParserContext Instance *m_instance; // Generic string buffer for vertices, face indices, metadata etc. std::string m_value[3]; + // Pointer to preset bundle to update if config data are stored inside the amf file + PresetBundle* m_preset_bundle; + // Fullpath name of the amf file + std::string m_archive_filename; private: AMFParserContext& operator=(AMFParserContext&); @@ -403,7 +417,10 @@ void AMFParserContext::endElement(const char * /* name */) break; case NODE_TYPE_METADATA: - if (strncmp(m_value[0].c_str(), "slic3r.", 7) == 0) { + if ((m_preset_bundle != nullptr) && strncmp(m_value[0].c_str(), SLIC3R_CONFIG_TYPE, strlen(SLIC3R_CONFIG_TYPE)) == 0) { + m_preset_bundle->load_config_string(m_value[1].c_str(), m_archive_filename.c_str()); + } + else if (strncmp(m_value[0].c_str(), "slic3r.", 7) == 0) { const char *opt_key = m_value[0].c_str() + 7; if (print_config_def.options.find(opt_key) != print_config_def.options.end()) { DynamicPrintConfig *config = nullptr; @@ -474,10 +491,13 @@ void AMFParserContext::endDocument() } // Load an AMF file into a provided model. -bool load_amf(const char *path, Model *model) +bool load_amf_file(const char *path, PresetBundle* bundle, Model *model) { + if ((path == nullptr) || (model == nullptr)) + return false; + XML_Parser parser = XML_ParserCreate(nullptr); // encoding - if (! parser) { + if (!parser) { printf("Couldn't allocate memory for parser\n"); return false; } @@ -488,7 +508,7 @@ bool load_amf(const char *path, Model *model) return false; } - AMFParserContext ctx(parser, model); + AMFParserContext ctx(parser, path, bundle, model); XML_SetUserData(parser, (void*)&ctx); XML_SetElementHandler(parser, AMFParserContext::startElement, AMFParserContext::endElement); XML_SetCharacterDataHandler(parser, AMFParserContext::characters); @@ -519,49 +539,163 @@ bool load_amf(const char *path, Model *model) if (result) ctx.endDocument(); + return result; } -bool store_amf(const char *path, Model *model) +// Load an AMF archive into a provided model. +bool load_amf_archive(const char *path, PresetBundle* bundle, Model *model) { - FILE *file = boost::nowide::fopen(path, "wb"); - if (file == nullptr) + if ((path == nullptr) || (model == nullptr)) return false; - fprintf(file, "\n"); - fprintf(file, "\n"); - fprintf(file, "Slic3r %s\n", SLIC3R_VERSION); + mz_zip_archive archive; + mz_zip_zero_struct(&archive); + + mz_bool res = mz_zip_reader_init_file(&archive, path, 0); + if (res == 0) + { + printf("Unable to init zip reader\n"); + return false; + } + + mz_uint num_entries = mz_zip_reader_get_num_files(&archive); + if (num_entries != 1) + { + printf("Found invalid number of entries\n"); + mz_zip_reader_end(&archive); + return false; + } + + mz_zip_archive_file_stat stat; + res = mz_zip_reader_file_stat(&archive, 0, &stat); + if (res == 0) + { + printf("Unable to extract entry statistics\n"); + mz_zip_reader_end(&archive); + return false; + } + + std::string internal_aml_filename = boost::ireplace_last_copy(boost::filesystem::path(path).filename().string(), ".zip.amf", ".amf"); + if (internal_aml_filename != stat.m_filename) + { + printf("Found invalid internal filename\n"); + mz_zip_reader_end(&archive); + return false; + } + + if (stat.m_uncomp_size == 0) + { + printf("Found invalid size\n"); + mz_zip_reader_end(&archive); + return false; + } + + XML_Parser parser = XML_ParserCreate(nullptr); // encoding + if (!parser) { + printf("Couldn't allocate memory for parser\n"); + mz_zip_reader_end(&archive); + return false; + } + + AMFParserContext ctx(parser, path, bundle, model); + XML_SetUserData(parser, (void*)&ctx); + XML_SetElementHandler(parser, AMFParserContext::startElement, AMFParserContext::endElement); + XML_SetCharacterDataHandler(parser, AMFParserContext::characters); + + void* parser_buffer = XML_GetBuffer(parser, (int)stat.m_uncomp_size); + if (parser_buffer == nullptr) + { + printf("Unable to create buffer"); + mz_zip_reader_end(&archive); + return false; + } + + res = mz_zip_reader_extract_file_to_mem(&archive, stat.m_filename, parser_buffer, (size_t)stat.m_uncomp_size, 0); + if (res == 0) + { + printf("Error while reading model data to buffer"); + mz_zip_reader_end(&archive); + return false; + } + + if (!XML_ParseBuffer(parser, (int)stat.m_uncomp_size, 1)) + { + printf("Error (%s) while parsing xml file at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser)); + mz_zip_reader_end(&archive); + return false; + } + + ctx.endDocument(); + + mz_zip_reader_end(&archive); + return true; +} + +// Load an AMF file into a provided model. +// If bundle is not a null pointer, updates it if the amf file/archive contains config data +bool load_amf(const char *path, PresetBundle* bundle, Model *model) +{ + if (boost::iends_with(path, ".zip.amf")) + return load_amf_archive(path, bundle, model); + else if (boost::iends_with(path, ".amf") || boost::iends_with(path, ".amf.xml")) + return load_amf_file(path, bundle, model); + else + return false; +} + +bool store_amf(const char *path, Model *model, Print* print) +{ + if ((path == nullptr) || (model == nullptr) || (print == nullptr)) + return false; + + mz_zip_archive archive; + mz_zip_zero_struct(&archive); + + mz_bool res = mz_zip_writer_init_file(&archive, path, 0); + if (res == 0) + return false; + + std::stringstream stream; + stream << "\n"; + stream << "\n"; + stream << "Slic3r " << SLIC3R_VERSION << "\n"; + + std::string config = "\n"; + GCode::append_full_config(*print, config); + stream << "" << config << "\n"; + for (const auto &material : model->materials) { if (material.first.empty()) continue; // note that material-id must never be 0 since it's reserved by the AMF spec - fprintf(file, " \n", material.first.c_str()); + stream << " \n"; for (const auto &attr : material.second->attributes) - fprintf(file, " %s\n", attr.first.c_str(), attr.second.c_str()); + stream << " " << attr.second << "\n"; for (const std::string &key : material.second->config.keys()) - fprintf(file, " %s\n", key.c_str(), material.second->config.serialize(key).c_str()); - fprintf(file, " \n"); + stream << " " << material.second->config.serialize(key) << "\n"; + stream << " \n"; } std::string instances; for (size_t object_id = 0; object_id < model->objects.size(); ++ object_id) { ModelObject *object = model->objects[object_id]; - fprintf(file, " \n", object_id); + stream << " \n"; for (const std::string &key : object->config.keys()) - fprintf(file, " %s\n", key.c_str(), object->config.serialize(key).c_str()); - if (! object->name.empty()) - fprintf(file, " %s\n", object->name.c_str()); + stream << " " << object->config.serialize(key) << "\n"; + if (!object->name.empty()) + stream << " " << object->name << "\n"; std::vector layer_height_profile = object->layer_height_profile_valid ? object->layer_height_profile : std::vector(); if (layer_height_profile.size() >= 4 && (layer_height_profile.size() % 2) == 0) { // Store the layer height profile as a single semicolon separated list. - fprintf(file, " "); - fprintf(file, "%f", layer_height_profile.front()); - for (size_t i = 1; i < layer_height_profile.size(); ++ i) - fprintf(file, ";%f", layer_height_profile[i]); - fprintf(file, "\n \n"); + stream << " "; + stream << layer_height_profile.front(); + for (size_t i = 1; i < layer_height_profile.size(); ++i) + stream << ";" << layer_height_profile[i]; + stream << "\n \n"; } //FIXME Store the layer height ranges (ModelObject::layer_height_ranges) - fprintf(file, " \n"); - fprintf(file, " \n"); + stream << " \n"; + stream << " \n"; std::vector vertices_offsets; int num_vertices = 0; for (ModelVolume *volume : object->volumes) { @@ -572,41 +706,41 @@ bool store_amf(const char *path, Model *model) if (stl.v_shared == nullptr) stl_generate_shared_vertices(&stl); for (size_t i = 0; i < stl.stats.shared_vertices; ++ i) { - fprintf(file, " \n"); - fprintf(file, " \n"); - fprintf(file, " %f\n", stl.v_shared[i].x); - fprintf(file, " %f\n", stl.v_shared[i].y); - fprintf(file, " %f\n", stl.v_shared[i].z); - fprintf(file, " \n"); - fprintf(file, " \n"); + stream << " \n"; + stream << " \n"; + stream << " " << stl.v_shared[i].x << "\n"; + stream << " " << stl.v_shared[i].y << "\n"; + stream << " " << stl.v_shared[i].z << "\n"; + stream << " \n"; + stream << " \n"; } num_vertices += stl.stats.shared_vertices; } - fprintf(file, " \n"); - for (size_t i_volume = 0; i_volume < object->volumes.size(); ++ i_volume) { + stream << " \n"; + for (size_t i_volume = 0; i_volume < object->volumes.size(); ++i_volume) { ModelVolume *volume = object->volumes[i_volume]; int vertices_offset = vertices_offsets[i_volume]; if (volume->material_id().empty()) - fprintf(file, " \n"); + stream << " \n"; else - fprintf(file, " \n", volume->material_id().c_str()); + stream << " material_id() << "\">\n"; for (const std::string &key : volume->config.keys()) - fprintf(file, " %s\n", key.c_str(), volume->config.serialize(key).c_str()); - if (! volume->name.empty()) - fprintf(file, " %s\n", volume->name.c_str()); + stream << " " << volume->config.serialize(key) << "\n"; + if (!volume->name.empty()) + stream << " " << volume->name << "\n"; if (volume->modifier) - fprintf(file, " 1\n"); - for (int i = 0; i < volume->mesh.stl.stats.number_of_facets; ++ i) { - fprintf(file, " \n"); - for (int j = 0; j < 3; ++ j) - fprintf(file, " %d\n", j+1, volume->mesh.stl.v_indices[i].vertex[j] + vertices_offset, j+1); - fprintf(file, " \n"); + stream << " 1\n"; + for (int i = 0; i < volume->mesh.stl.stats.number_of_facets; ++i) { + stream << " \n"; + for (int j = 0; j < 3; ++j) + stream << " " << volume->mesh.stl.v_indices[i].vertex[j] + vertices_offset << "\n"; + stream << " \n"; } - fprintf(file, " \n"); + stream << " \n"; } - fprintf(file, " \n"); - fprintf(file, " \n"); - if (! object->instances.empty()) { + stream << " \n"; + stream << " \n"; + if (!object->instances.empty()) { for (ModelInstance *instance : object->instances) { char buf[512]; sprintf(buf, @@ -627,12 +761,31 @@ bool store_amf(const char *path, Model *model) } } if (! instances.empty()) { - fprintf(file, " \n"); - fwrite(instances.data(), instances.size(), 1, file); - fprintf(file, " \n"); + stream << " \n"; + stream << instances; + stream << " \n"; } - fprintf(file, "\n"); - fclose(file); + stream << "\n"; + + std::string internal_aml_filename = boost::ireplace_last_copy(boost::filesystem::path(path).filename().string(), ".zip.amf", ".amf"); + std::string out = stream.str(); + + if (!mz_zip_writer_add_mem(&archive, internal_aml_filename.c_str(), (const void*)out.data(), out.length(), MZ_DEFAULT_COMPRESSION)) + { + mz_zip_writer_end(&archive); + boost::filesystem::remove(path); + return false; + } + + if (!mz_zip_writer_finalize_archive(&archive)) + { + mz_zip_writer_end(&archive); + boost::filesystem::remove(path); + return false; + } + + mz_zip_writer_end(&archive); + return true; } diff --git a/xs/src/libslic3r/Format/AMF.hpp b/xs/src/libslic3r/Format/AMF.hpp index e58ce2f0f..027ebdab3 100644 --- a/xs/src/libslic3r/Format/AMF.hpp +++ b/xs/src/libslic3r/Format/AMF.hpp @@ -4,11 +4,15 @@ namespace Slic3r { class Model; +class Print; +class PresetBundle; -// Load an AMF file into a provided model. -extern bool load_amf(const char *path, Model *model); +// Load the content of an amf file into the given model and preset bundle. +extern bool load_amf(const char *path, PresetBundle* bundle, Model *model); -extern bool store_amf(const char *path, Model *model); +// Save the given model and the config data contained in the given Print into an amf file. +// The model could be modified during the export process if meshes are not repaired or have no shared vertices +extern bool store_amf(const char *path, Model *model, Print* print); }; // namespace Slic3r diff --git a/xs/src/libslic3r/Model.cpp b/xs/src/libslic3r/Model.cpp index 891438407..f65707ccb 100644 --- a/xs/src/libslic3r/Model.cpp +++ b/xs/src/libslic3r/Model.cpp @@ -47,9 +47,9 @@ Model Model::read_from_file(const std::string &input_file, bool add_default_inst result = load_stl(input_file.c_str(), &model); else if (boost::algorithm::iends_with(input_file, ".obj")) result = load_obj(input_file.c_str(), &model); - else if (boost::algorithm::iends_with(input_file, ".amf") || - boost::algorithm::iends_with(input_file, ".amf.xml")) - result = load_amf(input_file.c_str(), &model); + else if (!boost::algorithm::iends_with(input_file, ".zip.amf") && (boost::algorithm::iends_with(input_file, ".amf") || + boost::algorithm::iends_with(input_file, ".amf.xml"))) + result = load_amf(input_file.c_str(), nullptr, &model); #ifdef SLIC3R_PRUS else if (boost::algorithm::iends_with(input_file, ".prusa")) result = load_prus(input_file.c_str(), &model); @@ -79,8 +79,10 @@ Model Model::read_from_archive(const std::string &input_file, PresetBundle* bund bool result = false; if (boost::algorithm::iends_with(input_file, ".3mf")) result = load_3mf(input_file.c_str(), bundle, &model); + else if (boost::algorithm::iends_with(input_file, ".zip.amf")) + result = load_amf(input_file.c_str(), bundle, &model); else - throw std::runtime_error("Unknown file format. Input file must have .3mf extension."); + throw std::runtime_error("Unknown file format. Input file must have .3mf or .zip.amf extension."); if (!result) throw std::runtime_error("Loading of a model file failed."); diff --git a/xs/xsp/Model.xsp b/xs/xsp/Model.xsp index ae0621057..c0271ae75 100644 --- a/xs/xsp/Model.xsp +++ b/xs/xsp/Model.xsp @@ -101,8 +101,8 @@ bool store_stl(char *path, bool binary) %code%{ TriangleMesh mesh = THIS->mesh(); RETVAL = Slic3r::store_stl(path, &mesh, binary); %}; - bool store_amf(char *path) - %code%{ RETVAL = Slic3r::store_amf(path, THIS); %}; + bool store_amf(char *path, Print* print) + %code%{ RETVAL = Slic3r::store_amf(path, THIS, print); %}; bool store_3mf(char *path, Print* print) %code%{ RETVAL = Slic3r::store_3mf(path, THIS, print); %}; @@ -137,12 +137,13 @@ load_obj(CLASS, path, object_name) RETVAL Model* -load_amf(CLASS, path) +load_amf(CLASS, bundle, path) char* CLASS; + PresetBundle* bundle; char* path; CODE: RETVAL = new Model(); - if (! load_amf(path, RETVAL)) { + if (! load_amf(path, bundle, RETVAL)) { delete RETVAL; RETVAL = NULL; } From dcc667cdc7e051c71952565739527c34c07ee06a Mon Sep 17 00:00:00 2001 From: Enrico Turri Date: Wed, 14 Feb 2018 15:52:39 +0100 Subject: [PATCH 44/57] AMF I/O - Fixed error messages --- xs/src/libslic3r/Format/AMF.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/xs/src/libslic3r/Format/AMF.cpp b/xs/src/libslic3r/Format/AMF.cpp index 06ba20120..a52dd532a 100644 --- a/xs/src/libslic3r/Format/AMF.cpp +++ b/xs/src/libslic3r/Format/AMF.cpp @@ -576,8 +576,8 @@ bool load_amf_archive(const char *path, PresetBundle* bundle, Model *model) return false; } - std::string internal_aml_filename = boost::ireplace_last_copy(boost::filesystem::path(path).filename().string(), ".zip.amf", ".amf"); - if (internal_aml_filename != stat.m_filename) + std::string internal_amf_filename = boost::ireplace_last_copy(boost::filesystem::path(path).filename().string(), ".zip.amf", ".amf"); + if (internal_amf_filename != stat.m_filename) { printf("Found invalid internal filename\n"); mz_zip_reader_end(&archive); @@ -606,7 +606,7 @@ bool load_amf_archive(const char *path, PresetBundle* bundle, Model *model) void* parser_buffer = XML_GetBuffer(parser, (int)stat.m_uncomp_size); if (parser_buffer == nullptr) { - printf("Unable to create buffer"); + printf("Unable to create buffer\n"); mz_zip_reader_end(&archive); return false; } @@ -614,14 +614,14 @@ bool load_amf_archive(const char *path, PresetBundle* bundle, Model *model) res = mz_zip_reader_extract_file_to_mem(&archive, stat.m_filename, parser_buffer, (size_t)stat.m_uncomp_size, 0); if (res == 0) { - printf("Error while reading model data to buffer"); + printf("Error while reading model data to buffer\n"); mz_zip_reader_end(&archive); return false; } if (!XML_ParseBuffer(parser, (int)stat.m_uncomp_size, 1)) { - printf("Error (%s) while parsing xml file at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser)); + printf("Error (%s) while parsing xml file at line %d\n", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser)); mz_zip_reader_end(&archive); return false; } @@ -767,10 +767,10 @@ bool store_amf(const char *path, Model *model, Print* print) } stream << "\n"; - std::string internal_aml_filename = boost::ireplace_last_copy(boost::filesystem::path(path).filename().string(), ".zip.amf", ".amf"); + std::string internal_amf_filename = boost::ireplace_last_copy(boost::filesystem::path(path).filename().string(), ".zip.amf", ".amf"); std::string out = stream.str(); - if (!mz_zip_writer_add_mem(&archive, internal_aml_filename.c_str(), (const void*)out.data(), out.length(), MZ_DEFAULT_COMPRESSION)) + if (!mz_zip_writer_add_mem(&archive, internal_amf_filename.c_str(), (const void*)out.data(), out.length(), MZ_DEFAULT_COMPRESSION)) { mz_zip_writer_end(&archive); boost::filesystem::remove(path); From 3a6436f6f0369e57708c2174d7974eb6e4047b94 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Wed, 14 Feb 2018 18:42:09 +0100 Subject: [PATCH 45/57] Split the GCodePreviewData from the GCodeAnalyzer, as in the next step the GCodePreviewData will be exported to Perl. --- xs/CMakeLists.txt | 2 + xs/src/libslic3r/GCode/Analyzer.cpp | 387 ++-------------------------- xs/src/libslic3r/GCode/Analyzer.hpp | 190 -------------- xs/src/libslic3r/Print.cpp | 4 +- xs/src/libslic3r/Print.hpp | 6 +- xs/src/slic3r/GUI/3DScene.cpp | 110 ++++---- xs/src/slic3r/GUI/3DScene.hpp | 9 +- 7 files changed, 76 insertions(+), 632 deletions(-) diff --git a/xs/CMakeLists.txt b/xs/CMakeLists.txt index de475eaa0..a1848a67a 100644 --- a/xs/CMakeLists.txt +++ b/xs/CMakeLists.txt @@ -90,6 +90,8 @@ add_library(libslic3r STATIC ${LIBDIR}/libslic3r/GCode/CoolingBuffer.hpp ${LIBDIR}/libslic3r/GCode/PressureEqualizer.cpp ${LIBDIR}/libslic3r/GCode/PressureEqualizer.hpp + ${LIBDIR}/libslic3r/GCode/PreviewData.cpp + ${LIBDIR}/libslic3r/GCode/PreviewData.hpp ${LIBDIR}/libslic3r/GCode/PrintExtents.cpp ${LIBDIR}/libslic3r/GCode/PrintExtents.hpp ${LIBDIR}/libslic3r/GCode/SpiralVase.cpp diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index 02e999bb4..938f0371d 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -7,6 +7,7 @@ #include "Print.hpp" #include "Analyzer.hpp" +#include "PreviewData.hpp" static const std::string AXIS_STR = "XYZE"; static const float MMMIN_TO_MMSEC = 1.0f / 60.0f; @@ -88,364 +89,6 @@ GCodeAnalyzer::GCodeMove::GCodeMove(GCodeMove::EType type, const GCodeAnalyzer:: { } -const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Color::Dummy(0.0f, 0.0f, 0.0f, 0.0f); - -GCodeAnalyzer::PreviewData::Color::Color() -{ - rgba[0] = 1.0f; - rgba[1] = 1.0f; - rgba[2] = 1.0f; - rgba[3] = 1.0f; -} - -GCodeAnalyzer::PreviewData::Color::Color(float r, float g, float b, float a) -{ - rgba[0] = r; - rgba[1] = g; - rgba[2] = b; - rgba[3] = a; -} - -std::vector GCodeAnalyzer::PreviewData::Color::as_bytes() const -{ - std::vector ret; - for (unsigned int i = 0; i < 4; ++i) - { - ret.push_back((unsigned char)(255.0f * rgba[i])); - } - return ret; -} - -GCodeAnalyzer::PreviewData::Extrusion::Layer::Layer(float z, const ExtrusionPaths& paths) - : z(z) - , paths(paths) -{ -} - -GCodeAnalyzer::PreviewData::Travel::Polyline::Polyline(EType type, EDirection direction, float feedrate, unsigned int extruder_id, const Polyline3& polyline) - : type(type) - , direction(direction) - , feedrate(feedrate) - , extruder_id(extruder_id) - , polyline(polyline) -{ -} - -const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Range::Default_Colors[Colors_Count] = -{ - Color(0.043f, 0.173f, 0.478f, 1.0f), - Color(0.075f, 0.349f, 0.522f, 1.0f), - Color(0.110f, 0.533f, 0.569f, 1.0f), - Color(0.016f, 0.839f, 0.059f, 1.0f), - Color(0.667f, 0.949f, 0.000f, 1.0f), - Color(0.988f, 0.975f, 0.012f, 1.0f), - Color(0.961f, 0.808f, 0.039f, 1.0f), - Color(0.890f, 0.533f, 0.125f, 1.0f), - Color(0.820f, 0.408f, 0.188f, 1.0f), - Color(0.761f, 0.322f, 0.235f, 1.0f) -}; - -GCodeAnalyzer::PreviewData::Range::Range() -{ - reset(); -} - -void GCodeAnalyzer::PreviewData::Range::reset() -{ - min = FLT_MAX; - max = -FLT_MAX; -} - -bool GCodeAnalyzer::PreviewData::Range::empty() const -{ - return min == max; -} - -void GCodeAnalyzer::PreviewData::Range::update_from(float value) -{ - min = std::min(min, value); - max = std::max(max, value); -} - -void GCodeAnalyzer::PreviewData::Range::set_from(const Range& other) -{ - min = other.min; - max = other.max; -} - -float GCodeAnalyzer::PreviewData::Range::step_size() const -{ - return (max - min) / (float)Colors_Count; -} - -const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::Range::get_color_at_max() const -{ - return colors[Colors_Count - 1]; -} - -const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::Range::get_color_at(float value) const -{ - return empty() ? get_color_at_max() : colors[clamp((unsigned int)0, Colors_Count - 1, (unsigned int)((value - min) / step_size()))]; -} - -GCodeAnalyzer::PreviewData::LegendItem::LegendItem(const std::string& text, const GCodeAnalyzer::PreviewData::Color& color) - : text(text) - , color(color) -{ -} - -const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Extrusion::Default_Extrusion_Role_Colors[Num_Extrusion_Roles] = -{ - Color(0.0f, 0.0f, 0.0f, 1.0f), // erNone - Color(1.0f, 0.0f, 0.0f, 1.0f), // erPerimeter - Color(0.0f, 1.0f, 0.0f, 1.0f), // erExternalPerimeter - Color(0.0f, 0.0f, 1.0f, 1.0f), // erOverhangPerimeter - Color(1.0f, 1.0f, 0.0f, 1.0f), // erInternalInfill - Color(1.0f, 0.0f, 1.0f, 1.0f), // erSolidInfill - Color(0.0f, 1.0f, 1.0f, 1.0f), // erTopSolidInfill - Color(0.5f, 0.5f, 0.5f, 1.0f), // erBridgeInfill - Color(1.0f, 1.0f, 1.0f, 1.0f), // erGapFill - Color(0.5f, 0.0f, 0.0f, 1.0f), // erSkirt - Color(0.0f, 0.5f, 0.0f, 1.0f), // erSupportMaterial - Color(0.0f, 0.0f, 0.5f, 1.0f), // erSupportMaterialInterface - Color(0.7f, 0.89f, 0.67f, 1.0f), // erWipeTower - Color(0.0f, 0.0f, 0.0f, 1.0f) // erMixed -}; - -// todo: merge with Slic3r::ExtrusionRole2String() from GCode.cpp -const std::string GCodeAnalyzer::PreviewData::Extrusion::Default_Extrusion_Role_Names[Num_Extrusion_Roles] -{ - "None", - "Perimeter", - "External perimeter", - "Overhang perimeter", - "Internal infill", - "Solid infill", - "Top solid infill", - "Bridge infill", - "Gap fill", - "Skirt", - "Support material", - "Support material interface", - "Wipe tower", - "Mixed" -}; - -const GCodeAnalyzer::PreviewData::Extrusion::EViewType GCodeAnalyzer::PreviewData::Extrusion::Default_View_Type = GCodeAnalyzer::PreviewData::Extrusion::FeatureType; - -void GCodeAnalyzer::PreviewData::Extrusion::set_default() -{ - view_type = Default_View_Type; - - ::memcpy((void*)role_colors, (const void*)Default_Extrusion_Role_Colors, Num_Extrusion_Roles * sizeof(Color)); - ::memcpy((void*)ranges.height.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color)); - ::memcpy((void*)ranges.width.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color)); - ::memcpy((void*)ranges.feedrate.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color)); - - for (unsigned int i = 0; i < Num_Extrusion_Roles; ++i) - { - role_names[i] = Default_Extrusion_Role_Names[i]; - } - - role_flags = 0; - for (unsigned int i = 0; i < Num_Extrusion_Roles; ++i) - { - role_flags += (unsigned int)::exp2((double)i); - } -} - -bool GCodeAnalyzer::PreviewData::Extrusion::is_role_flag_set(ExtrusionRole role) const -{ - return is_role_flag_set(role_flags, role); -} - -bool GCodeAnalyzer::PreviewData::Extrusion::is_role_flag_set(unsigned int flags, ExtrusionRole role) -{ - if (!is_valid_extrusion_role(role)) - return false; - - unsigned int flag = (unsigned int)::exp2((double)(role - erPerimeter)); - return (flags & flag) == flag; -} - -const float GCodeAnalyzer::PreviewData::Travel::Default_Width = 0.075f; -const float GCodeAnalyzer::PreviewData::Travel::Default_Height = 0.075f; -const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Travel::Default_Type_Colors[Num_Types] = -{ - Color(0.0f, 0.0f, 0.75f, 1.0f), // Move - Color(0.0f, 0.75f, 0.0f, 1.0f), // Extrude - Color(0.75f, 0.0f, 0.0f, 1.0f), // Retract -}; - -void GCodeAnalyzer::PreviewData::Travel::set_default() -{ - width = Default_Width; - height = Default_Height; - ::memcpy((void*)type_colors, (const void*)Default_Type_Colors, Num_Types * sizeof(Color)); - is_visible = false; -} - -const GCodeAnalyzer::PreviewData::Color GCodeAnalyzer::PreviewData::Retraction::Default_Color = GCodeAnalyzer::PreviewData::Color(1.0f, 1.0f, 1.0f, 1.0f); - -GCodeAnalyzer::PreviewData::Retraction::Position::Position(const Point3& position, float width, float height) - : position(position) - , width(width) - , height(height) -{ -} - -void GCodeAnalyzer::PreviewData::Retraction::set_default() -{ - color = Default_Color; - is_visible = false; -} - -void GCodeAnalyzer::PreviewData::Shell::set_default() -{ - is_visible = false; -} - -GCodeAnalyzer::PreviewData::PreviewData() -{ - set_default(); -} - -void GCodeAnalyzer::PreviewData::set_default() -{ - extrusion.set_default(); - travel.set_default(); - retraction.set_default(); - unretraction.set_default(); - shell.set_default(); -} - -void GCodeAnalyzer::PreviewData::reset() -{ - extrusion.layers.clear(); - travel.polylines.clear(); - retraction.positions.clear(); - unretraction.positions.clear(); -} - -const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::get_extrusion_role_color(ExtrusionRole role) const -{ - return extrusion.role_colors[role]; -} - -const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::get_extrusion_height_color(float height) const -{ - return extrusion.ranges.height.get_color_at(height); -} - -const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::get_extrusion_width_color(float width) const -{ - return extrusion.ranges.width.get_color_at(width); -} - -const GCodeAnalyzer::PreviewData::Color& GCodeAnalyzer::PreviewData::get_extrusion_feedrate_color(float feedrate) const -{ - return extrusion.ranges.feedrate.get_color_at(feedrate); -} - -void GCodeAnalyzer::PreviewData::set_extrusion_role_color(const std::string& role_name, float red, float green, float blue, float alpha) -{ - for (unsigned int i = 0; i < Extrusion::Num_Extrusion_Roles; ++i) - { - if (role_name == extrusion.role_names[i]) - { - extrusion.role_colors[i] = Color(red, green, blue, alpha); - break; - } - } -} - -std::string GCodeAnalyzer::PreviewData::get_legend_title() const -{ - switch (extrusion.view_type) - { - case Extrusion::FeatureType: - return "Feature type"; - case Extrusion::Height: - return "Height (mm)"; - case Extrusion::Width: - return "Width (mm)"; - case Extrusion::Feedrate: - return "Speed (mm/s)"; - case Extrusion::Tool: - return "Tool"; - } - - return ""; -} - -GCodeAnalyzer::PreviewData::LegendItemsList GCodeAnalyzer::PreviewData::get_legend_items(const std::vector& tool_colors) const -{ - struct Helper - { - static void FillListFromRange(LegendItemsList& list, const Range& range, unsigned int decimals, float scale_factor) - { - list.reserve(Range::Colors_Count); - float step = range.step_size(); - for (unsigned int i = 0; i < Range::Colors_Count; ++i) - { - char buf[32]; - sprintf(buf, "%.*f/%.*f", decimals, scale_factor * (range.min + (float)i * step), decimals, scale_factor * (range.min + (float)(i + 1) * step)); - list.emplace_back(buf, range.colors[i]); - } - } - }; - - LegendItemsList items; - - switch (extrusion.view_type) - { - case Extrusion::FeatureType: - { - items.reserve(erMixed - erPerimeter + 1); - for (unsigned int i = (unsigned int)erPerimeter; i < (unsigned int)erMixed; ++i) - { - items.emplace_back(extrusion.role_names[i], extrusion.role_colors[i]); - } - - break; - } - case Extrusion::Height: - { - Helper::FillListFromRange(items, extrusion.ranges.height, 3, 1.0f); - break; - } - case Extrusion::Width: - { - Helper::FillListFromRange(items, extrusion.ranges.width, 3, 1.0f); - break; - } - case Extrusion::Feedrate: - { - Helper::FillListFromRange(items, extrusion.ranges.feedrate, 0, 1.0f); - break; - } - case Extrusion::Tool: - { - unsigned int tools_colors_count = tool_colors.size() / 4; - items.reserve(tools_colors_count); - for (unsigned int i = 0; i < tools_colors_count; ++i) - { - char buf[32]; - sprintf(buf, "Extruder %d", i + 1); - - GCodeAnalyzer::PreviewData::Color color; - ::memcpy((void*)color.rgba, (const void*)(tool_colors.data() + i * 4), 4 * sizeof(float)); - - items.emplace_back(buf, color); - } - - break; - } - } - - return items; -} - GCodeAnalyzer::GCodeAnalyzer() { reset(); @@ -962,9 +605,9 @@ void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(Print& print) { struct Helper { - static PreviewData::Extrusion::Layer& get_layer_at_z(PreviewData::Extrusion::LayersList& layers, float z) + static GCodePreviewData::Extrusion::Layer& get_layer_at_z(GCodePreviewData::Extrusion::LayersList& layers, float z) { - for (PreviewData::Extrusion::Layer& layer : layers) + for (GCodePreviewData::Extrusion::Layer& layer : layers) { // if layer found, return it if (layer.z == z) @@ -999,9 +642,9 @@ void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(Print& print) float z = FLT_MAX; Polyline polyline; Pointf3 position(FLT_MAX, FLT_MAX, FLT_MAX); - PreviewData::Range height_range; - PreviewData::Range width_range; - PreviewData::Range feedrate_range; + GCodePreviewData::Range height_range; + GCodePreviewData::Range width_range; + GCodePreviewData::Range feedrate_range; // constructs the polylines while traversing the moves for (const GCodeMove& move : extrude_moves->second) @@ -1048,7 +691,7 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) { struct Helper { - static void store_polyline(const Polyline3& polyline, PreviewData::Travel::EType type, PreviewData::Travel::Polyline::EDirection direction, float feedrate, unsigned int extruder_id, Print& print) + static void store_polyline(const Polyline3& polyline, GCodePreviewData::Travel::EType type, GCodePreviewData::Travel::Polyline::EDirection direction, float feedrate, unsigned int extruder_id, Print& print) { // if the polyline is valid, store it if (polyline.is_valid()) @@ -1062,16 +705,16 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) Polyline3 polyline; Pointf3 position(FLT_MAX, FLT_MAX, FLT_MAX); - PreviewData::Travel::EType type = PreviewData::Travel::Num_Types; - PreviewData::Travel::Polyline::EDirection direction = PreviewData::Travel::Polyline::Num_Directions; + GCodePreviewData::Travel::EType type = GCodePreviewData::Travel::Num_Types; + GCodePreviewData::Travel::Polyline::EDirection direction = GCodePreviewData::Travel::Polyline::Num_Directions; float feedrate = FLT_MAX; unsigned int extruder_id = -1; // constructs the polylines while traversing the moves for (const GCodeMove& move : travel_moves->second) { - PreviewData::Travel::EType move_type = (move.delta_extruder < 0.0f) ? PreviewData::Travel::Retract : ((move.delta_extruder > 0.0f) ? PreviewData::Travel::Extrude : PreviewData::Travel::Move); - PreviewData::Travel::Polyline::EDirection move_direction = ((move.start_position.x != move.end_position.x) || (move.start_position.y != move.end_position.y)) ? PreviewData::Travel::Polyline::Generic : PreviewData::Travel::Polyline::Vertical; + GCodePreviewData::Travel::EType move_type = (move.delta_extruder < 0.0f) ? GCodePreviewData::Travel::Retract : ((move.delta_extruder > 0.0f) ? GCodePreviewData::Travel::Extrude : GCodePreviewData::Travel::Move); + GCodePreviewData::Travel::Polyline::EDirection move_direction = ((move.start_position.x != move.end_position.x) || (move.start_position.y != move.end_position.y)) ? GCodePreviewData::Travel::Polyline::Generic : GCodePreviewData::Travel::Polyline::Vertical; if ((type != move_type) || (direction != move_direction) || (feedrate != move.data.feedrate) || (position != move.start_position) || (extruder_id != move.data.extruder_id)) { @@ -1130,17 +773,17 @@ void GCodeAnalyzer::_calc_gcode_preview_unretractions(Print& print) } } -GCodeAnalyzer::PreviewData::Color operator + (const GCodeAnalyzer::PreviewData::Color& c1, const GCodeAnalyzer::PreviewData::Color& c2) +GCodePreviewData::Color operator + (const GCodePreviewData::Color& c1, const GCodePreviewData::Color& c2) { - return GCodeAnalyzer::PreviewData::Color(clamp(0.0f, 1.0f, c1.rgba[0] + c2.rgba[0]), + return GCodePreviewData::Color(clamp(0.0f, 1.0f, c1.rgba[0] + c2.rgba[0]), clamp(0.0f, 1.0f, c1.rgba[1] + c2.rgba[1]), clamp(0.0f, 1.0f, c1.rgba[2] + c2.rgba[2]), clamp(0.0f, 1.0f, c1.rgba[3] + c2.rgba[3])); } -GCodeAnalyzer::PreviewData::Color operator * (float f, const GCodeAnalyzer::PreviewData::Color& color) +GCodePreviewData::Color operator * (float f, const GCodePreviewData::Color& color) { - return GCodeAnalyzer::PreviewData::Color(clamp(0.0f, 1.0f, f * color.rgba[0]), + return GCodePreviewData::Color(clamp(0.0f, 1.0f, f * color.rgba[0]), clamp(0.0f, 1.0f, f * color.rgba[1]), clamp(0.0f, 1.0f, f * color.rgba[2]), clamp(0.0f, 1.0f, f * color.rgba[3])); diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index 121360dbc..bfb2d668c 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -98,193 +98,6 @@ private: float position[Num_Axis]; }; -public: - struct PreviewData - { - struct Color - { - float rgba[4]; - - Color(); - Color(float r, float g, float b, float a); - - std::vector as_bytes() const; - - static const Color Dummy; - }; - - struct Range - { - static const unsigned int Colors_Count = 10; - static const Color Default_Colors[Colors_Count]; - - Color colors[Colors_Count]; - float min; - float max; - - Range(); - - void reset(); - bool empty() const; - void update_from(float value); - void set_from(const Range& other); - float step_size() const; - - const Color& get_color_at(float value) const; - const Color& get_color_at_max() const; - }; - - struct LegendItem - { - std::string text; - Color color; - - LegendItem(const std::string& text, const Color& color); - }; - - typedef std::vector LegendItemsList; - - struct Extrusion - { - enum EViewType : unsigned char - { - FeatureType, - Height, - Width, - Feedrate, - Tool, - Num_View_Types - }; - - static const unsigned int Num_Extrusion_Roles = (unsigned int)erMixed + 1; - static const Color Default_Extrusion_Role_Colors[Num_Extrusion_Roles]; - static const std::string Default_Extrusion_Role_Names[Num_Extrusion_Roles]; - static const EViewType Default_View_Type; - - struct Ranges - { - Range height; - Range width; - Range feedrate; - }; - - struct Layer - { - float z; - ExtrusionPaths paths; - - Layer(float z, const ExtrusionPaths& paths); - }; - - typedef std::vector LayersList; - - EViewType view_type; - Color role_colors[Num_Extrusion_Roles]; - std::string role_names[Num_Extrusion_Roles]; - Ranges ranges; - LayersList layers; - unsigned int role_flags; - - void set_default(); - bool is_role_flag_set(ExtrusionRole role) const; - - static bool is_role_flag_set(unsigned int flags, ExtrusionRole role); - }; - - struct Travel - { - enum EType : unsigned char - { - Move, - Extrude, - Retract, - Num_Types - }; - - static const float Default_Width; - static const float Default_Height; - static const Color Default_Type_Colors[Num_Types]; - - struct Polyline - { - enum EDirection - { - Vertical, - Generic, - Num_Directions - }; - - EType type; - EDirection direction; - float feedrate; - unsigned int extruder_id; - Polyline3 polyline; - - Polyline(EType type, EDirection direction, float feedrate, unsigned int extruder_id, const Polyline3& polyline); - }; - - typedef std::vector PolylinesList; - - PolylinesList polylines; - float width; - float height; - Color type_colors[Num_Types]; - bool is_visible; - - void set_default(); - }; - - struct Retraction - { - static const Color Default_Color; - - struct Position - { - Point3 position; - float width; - float height; - - Position(const Point3& position, float width, float height); - }; - - typedef std::vector PositionsList; - - PositionsList positions; - Color color; - bool is_visible; - - void set_default(); - }; - - struct Shell - { - bool is_visible; - - void set_default(); - }; - - Extrusion extrusion; - Travel travel; - Retraction retraction; - Retraction unretraction; - Shell shell; - - PreviewData(); - - void set_default(); - void reset(); - - const Color& get_extrusion_role_color(ExtrusionRole role) const; - const Color& get_extrusion_height_color(float height) const; - const Color& get_extrusion_width_color(float width) const; - const Color& get_extrusion_feedrate_color(float feedrate) const; - - void set_extrusion_role_color(const std::string& role_name, float red, float green, float blue, float alpha); - - std::string get_legend_title() const; - LegendItemsList get_legend_items(const std::vector& tool_colors) const; - }; - private: State m_state; GCodeReader m_parser; @@ -409,9 +222,6 @@ private: void _calc_gcode_preview_unretractions(Print& print); }; -GCodeAnalyzer::PreviewData::Color operator + (const GCodeAnalyzer::PreviewData::Color& c1, const GCodeAnalyzer::PreviewData::Color& c2); -GCodeAnalyzer::PreviewData::Color operator * (float f, const GCodeAnalyzer::PreviewData::Color& color); - } // namespace Slic3r #endif /* slic3r_GCode_Analyzer_hpp_ */ diff --git a/xs/src/libslic3r/Print.cpp b/xs/src/libslic3r/Print.cpp index fd0964e57..5fb81124c 100644 --- a/xs/src/libslic3r/Print.cpp +++ b/xs/src/libslic3r/Print.cpp @@ -73,8 +73,8 @@ void Print::clear_gcode_preview_data() void Print::set_gcode_preview_type(unsigned char type) { - if ((0 <= type) && (type < GCodeAnalyzer::PreviewData::Extrusion::Num_View_Types)) - gcode_preview.extrusion.view_type = (GCodeAnalyzer::PreviewData::Extrusion::EViewType)type; + if ((0 <= type) && (type < GCodePreviewData::Extrusion::Num_View_Types)) + gcode_preview.extrusion.view_type = (GCodePreviewData::Extrusion::EViewType)type; } void Print::set_gcode_preview_extrusion_flags(unsigned int flags) diff --git a/xs/src/libslic3r/Print.hpp b/xs/src/libslic3r/Print.hpp index da94917fc..f08b4ec15 100644 --- a/xs/src/libslic3r/Print.hpp +++ b/xs/src/libslic3r/Print.hpp @@ -15,7 +15,7 @@ #include "Slicing.hpp" #include "GCode/ToolOrdering.hpp" #include "GCode/WipeTower.hpp" -#include "GCode/Analyzer.hpp" +#include "GCode/PreviewData.hpp" #include "tbb/atomic.h" @@ -241,7 +241,7 @@ public: // ordered collections of extrusion paths to build skirt loops and brim ExtrusionEntityCollection skirt, brim; - GCodeAnalyzer::PreviewData gcode_preview; + GCodePreviewData gcode_preview; Print() : total_used_filament(0), total_extruded_volume(0) { restart(); } ~Print() { clear_objects(); } @@ -272,7 +272,7 @@ public: // , , // ... // , }; - // where should be a string from GCodeAnalyzer::PreviewData::Extrusion::Default_Extrusion_Role_Names[] + // where should be a string from GCodePreviewData::Extrusion::Default_Extrusion_Role_Names[] // and an RGB color in hex format (i.e. red = FF0000) void set_gcode_extrusion_paths_colors(const std::vector& colors); diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index 553239a6f..b5fc9245e 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -1109,19 +1109,7 @@ static void point3_to_verts(const Point3& point, double width, double height, GL thick_point_to_verts(point, width, height, volume); } -_3DScene::GCodePreviewData::FirstVolume::FirstVolume(_3DScene::GCodePreviewData::EType type, unsigned int flag, unsigned int id) - : type(type) - , flag(flag) - , id(id) -{ -} - -void _3DScene::GCodePreviewData::reset() -{ - first_volumes.clear(); -} - -_3DScene::GCodePreviewData _3DScene::s_gcode_preview_data; +_3DScene::GCodePreviewVolumeIndex _3DScene::s_gcode_preview_volume_index; _3DScene::LegendTexture _3DScene::s_legend_texture; const unsigned char _3DScene::LegendTexture::Squares_Border_Color[3] = { 64, 64, 64 }; @@ -1146,7 +1134,7 @@ bool _3DScene::LegendTexture::generate_texture(const Print& print, const std::ve // collects items to render const std::string& title = print.gcode_preview.get_legend_title(); - const GCodeAnalyzer::PreviewData::LegendItemsList& items = print.gcode_preview.get_legend_items(tool_colors); + const GCodePreviewData::LegendItemsList& items = print.gcode_preview.get_legend_items(tool_colors); unsigned int items_count = (unsigned int)items.size(); if (items_count == 0) @@ -1165,7 +1153,7 @@ bool _3DScene::LegendTexture::generate_texture(const Print& print, const std::ve unsigned int max_text_width = 0; unsigned int max_text_height = 0; - for (const GCodeAnalyzer::PreviewData::LegendItem& item : items) + for (const GCodePreviewData::LegendItem& item : items) { memDC.GetTextExtent(item.text, &w, &h); max_text_width = std::max(max_text_width, (unsigned int)w); @@ -1221,7 +1209,7 @@ bool _3DScene::LegendTexture::generate_texture(const Print& print, const std::ve unsigned int px_inner_square = Px_Square - 2; - for (const GCodeAnalyzer::PreviewData::LegendItem& item : items) + for (const GCodePreviewData::LegendItem& item : items) { // draw darker icon perimeter const std::vector& item_color_bytes = item.color.as_bytes(); @@ -1362,7 +1350,7 @@ void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volume { std::vector tool_colors = parse_colors(str_tool_colors); - s_gcode_preview_data.reset(); + s_gcode_preview_volume_index.reset(); _load_gcode_extrusion_paths(*print, *volumes, tool_colors, use_VBOs); _load_gcode_travel_paths(*print, *volumes, tool_colors, use_VBOs); @@ -1768,46 +1756,46 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio // helper functions to select data in dependence of the extrusion view type struct Helper { - static float path_filter(GCodeAnalyzer::PreviewData::Extrusion::EViewType type, const ExtrusionPath& path) + static float path_filter(GCodePreviewData::Extrusion::EViewType type, const ExtrusionPath& path) { switch (type) { - case GCodeAnalyzer::PreviewData::Extrusion::FeatureType: + case GCodePreviewData::Extrusion::FeatureType: return (float)path.role(); - case GCodeAnalyzer::PreviewData::Extrusion::Height: + case GCodePreviewData::Extrusion::Height: return path.height; - case GCodeAnalyzer::PreviewData::Extrusion::Width: + case GCodePreviewData::Extrusion::Width: return path.width; - case GCodeAnalyzer::PreviewData::Extrusion::Feedrate: + case GCodePreviewData::Extrusion::Feedrate: return path.feedrate; - case GCodeAnalyzer::PreviewData::Extrusion::Tool: + case GCodePreviewData::Extrusion::Tool: return (float)path.extruder_id; } return 0.0f; } - static const GCodeAnalyzer::PreviewData::Color& path_color(const GCodeAnalyzer::PreviewData& data, const std::vector& tool_colors, float value) + static const GCodePreviewData::Color& path_color(const GCodePreviewData& data, const std::vector& tool_colors, float value) { switch (data.extrusion.view_type) { - case GCodeAnalyzer::PreviewData::Extrusion::FeatureType: + case GCodePreviewData::Extrusion::FeatureType: return data.get_extrusion_role_color((ExtrusionRole)(int)value); - case GCodeAnalyzer::PreviewData::Extrusion::Height: + case GCodePreviewData::Extrusion::Height: return data.get_extrusion_height_color(value); - case GCodeAnalyzer::PreviewData::Extrusion::Width: + case GCodePreviewData::Extrusion::Width: return data.get_extrusion_width_color(value); - case GCodeAnalyzer::PreviewData::Extrusion::Feedrate: + case GCodePreviewData::Extrusion::Feedrate: return data.get_extrusion_feedrate_color(value); - case GCodeAnalyzer::PreviewData::Extrusion::Tool: + case GCodePreviewData::Extrusion::Tool: { - static GCodeAnalyzer::PreviewData::Color color; + static GCodePreviewData::Color color; ::memcpy((void*)color.rgba, (const void*)(tool_colors.data() + (unsigned int)value * 4), 4 * sizeof(float)); return color; } } - return GCodeAnalyzer::PreviewData::Color::Dummy; + return GCodePreviewData::Color::Dummy; } }; @@ -1843,7 +1831,7 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio // detects filters FiltersList filters; - for (const GCodeAnalyzer::PreviewData::Extrusion::Layer& layer : print.gcode_preview.extrusion.layers) + for (const GCodePreviewData::Extrusion::Layer& layer : print.gcode_preview.extrusion.layers) { for (const ExtrusionPath& path : layer.paths) { @@ -1861,7 +1849,7 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio // creates a new volume for each filter for (Filter& filter : filters) { - s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Extrusion, (unsigned int)filter.role, (unsigned int)volumes.volumes.size()); + s_gcode_preview_volume_index.first_volumes.emplace_back(GCodePreviewVolumeIndex::Extrusion, (unsigned int)filter.role, (unsigned int)volumes.volumes.size()); GLVolume* volume = new GLVolume(Helper::path_color(print.gcode_preview, tool_colors, filter.value).rgba); if (volume != nullptr) @@ -1872,7 +1860,7 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio else { // an error occourred - restore to previous state and return - s_gcode_preview_data.first_volumes.pop_back(); + s_gcode_preview_volume_index.first_volumes.pop_back(); if (initial_volumes_count != volumes.volumes.size()) { std::vector::iterator begin = volumes.volumes.begin() + initial_volumes_count; @@ -1889,7 +1877,7 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio } // populates volumes - for (const GCodeAnalyzer::PreviewData::Extrusion::Layer& layer : print.gcode_preview.extrusion.layers) + for (const GCodePreviewData::Extrusion::Layer& layer : print.gcode_preview.extrusion.layers) { for (const ExtrusionPath& path : layer.paths) { @@ -1921,17 +1909,17 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs) { size_t initial_volumes_count = volumes.volumes.size(); - s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Travel, 0, (unsigned int)initial_volumes_count); + s_gcode_preview_volume_index.first_volumes.emplace_back(GCodePreviewVolumeIndex::Travel, 0, (unsigned int)initial_volumes_count); bool res = true; switch (print.gcode_preview.extrusion.view_type) { - case GCodeAnalyzer::PreviewData::Extrusion::Feedrate: + case GCodePreviewData::Extrusion::Feedrate: { res = _travel_paths_by_feedrate(print, volumes); break; } - case GCodeAnalyzer::PreviewData::Extrusion::Tool: + case GCodePreviewData::Extrusion::Tool: { res = _travel_paths_by_tool(print, volumes, tool_colors); break; @@ -1978,10 +1966,10 @@ bool _3DScene::_travel_paths_by_type(const Print& print, GLVolumeCollection& vol // Helper structure for types struct Type { - GCodeAnalyzer::PreviewData::Travel::EType value; + GCodePreviewData::Travel::EType value; GLVolume* volume; - explicit Type(GCodeAnalyzer::PreviewData::Travel::EType value) + explicit Type(GCodePreviewData::Travel::EType value) : value(value) , volume(nullptr) { @@ -1999,7 +1987,7 @@ bool _3DScene::_travel_paths_by_type(const Print& print, GLVolumeCollection& vol // detects types TypesList types; - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + for (const GCodePreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) { if (std::find(types.begin(), types.end(), Type(polyline.type)) == types.end()) types.emplace_back(polyline.type); @@ -2023,7 +2011,7 @@ bool _3DScene::_travel_paths_by_type(const Print& print, GLVolumeCollection& vol } // populates volumes - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + for (const GCodePreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) { TypesList::iterator type = std::find(types.begin(), types.end(), Type(polyline.type)); if (type != types.end()) @@ -2065,7 +2053,7 @@ bool _3DScene::_travel_paths_by_feedrate(const Print& print, GLVolumeCollection& // detects feedrates FeedratesList feedrates; - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + for (const GCodePreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) { if (std::find(feedrates.begin(), feedrates.end(), Feedrate(polyline.feedrate)) == feedrates.end()) feedrates.emplace_back(polyline.feedrate); @@ -2089,7 +2077,7 @@ bool _3DScene::_travel_paths_by_feedrate(const Print& print, GLVolumeCollection& } // populates volumes - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + for (const GCodePreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) { FeedratesList::iterator feedrate = std::find(feedrates.begin(), feedrates.end(), Feedrate(polyline.feedrate)); if (feedrate != feedrates.end()) @@ -2131,7 +2119,7 @@ bool _3DScene::_travel_paths_by_tool(const Print& print, GLVolumeCollection& vol // detects tools ToolsList tools; - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + for (const GCodePreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) { if (std::find(tools.begin(), tools.end(), Tool(polyline.extruder_id)) == tools.end()) tools.emplace_back(polyline.extruder_id); @@ -2155,7 +2143,7 @@ bool _3DScene::_travel_paths_by_tool(const Print& print, GLVolumeCollection& vol } // populates volumes - for (const GCodeAnalyzer::PreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + for (const GCodePreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) { ToolsList::iterator tool = std::find(tools.begin(), tools.end(), Tool(polyline.extruder_id)); if (tool != tools.end()) @@ -2173,7 +2161,7 @@ bool _3DScene::_travel_paths_by_tool(const Print& print, GLVolumeCollection& vol void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) { - s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Retraction, 0, (unsigned int)volumes.volumes.size()); + s_gcode_preview_volume_index.first_volumes.emplace_back(GCodePreviewVolumeIndex::Retraction, 0, (unsigned int)volumes.volumes.size()); // nothing to render, return if (print.gcode_preview.retraction.positions.empty()) @@ -2184,7 +2172,7 @@ void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& v { volumes.volumes.emplace_back(volume); - for (const GCodeAnalyzer::PreviewData::Retraction::Position& position : print.gcode_preview.retraction.positions) + for (const GCodePreviewData::Retraction::Position& position : print.gcode_preview.retraction.positions) { volume->print_zs.push_back(unscale(position.position.z)); volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); @@ -2201,7 +2189,7 @@ void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& v void _3DScene::_load_gcode_unretractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) { - s_gcode_preview_data.first_volumes.emplace_back(GCodePreviewData::Unretraction, 0, (unsigned int)volumes.volumes.size()); + s_gcode_preview_volume_index.first_volumes.emplace_back(GCodePreviewVolumeIndex::Unretraction, 0, (unsigned int)volumes.volumes.size()); // nothing to render, return if (print.gcode_preview.unretraction.positions.empty()) @@ -2212,7 +2200,7 @@ void _3DScene::_load_gcode_unretractions(const Print& print, GLVolumeCollection& { volumes.volumes.emplace_back(volume); - for (const GCodeAnalyzer::PreviewData::Retraction::Position& position : print.gcode_preview.unretraction.positions) + for (const GCodePreviewData::Retraction::Position& position : print.gcode_preview.unretraction.positions) { volume->print_zs.push_back(unscale(position.position.z)); volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); @@ -2229,39 +2217,39 @@ void _3DScene::_load_gcode_unretractions(const Print& print, GLVolumeCollection& void _3DScene::_update_gcode_volumes_visibility(const Print& print, GLVolumeCollection& volumes) { - unsigned int size = (unsigned int)s_gcode_preview_data.first_volumes.size(); + unsigned int size = (unsigned int)s_gcode_preview_volume_index.first_volumes.size(); for (unsigned int i = 0; i < size; ++i) { - std::vector::iterator begin = volumes.volumes.begin() + s_gcode_preview_data.first_volumes[i].id; - std::vector::iterator end = (i + 1 < size) ? volumes.volumes.begin() + s_gcode_preview_data.first_volumes[i + 1].id : volumes.volumes.end(); + std::vector::iterator begin = volumes.volumes.begin() + s_gcode_preview_volume_index.first_volumes[i].id; + std::vector::iterator end = (i + 1 < size) ? volumes.volumes.begin() + s_gcode_preview_volume_index.first_volumes[i + 1].id : volumes.volumes.end(); for (std::vector::iterator it = begin; it != end; ++it) { GLVolume* volume = *it; - switch (s_gcode_preview_data.first_volumes[i].type) + switch (s_gcode_preview_volume_index.first_volumes[i].type) { - case GCodePreviewData::Extrusion: + case GCodePreviewVolumeIndex::Extrusion: { - volume->is_active = print.gcode_preview.extrusion.is_role_flag_set((ExtrusionRole)s_gcode_preview_data.first_volumes[i].flag); + volume->is_active = print.gcode_preview.extrusion.is_role_flag_set((ExtrusionRole)s_gcode_preview_volume_index.first_volumes[i].flag); break; } - case GCodePreviewData::Travel: + case GCodePreviewVolumeIndex::Travel: { volume->is_active = print.gcode_preview.travel.is_visible; break; } - case GCodePreviewData::Retraction: + case GCodePreviewVolumeIndex::Retraction: { volume->is_active = print.gcode_preview.retraction.is_visible; break; } - case GCodePreviewData::Unretraction: + case GCodePreviewVolumeIndex::Unretraction: { volume->is_active = print.gcode_preview.unretraction.is_visible; break; } - case GCodePreviewData::Shell: + case GCodePreviewVolumeIndex::Shell: { volume->is_active = print.gcode_preview.shell.is_visible; break; @@ -2284,7 +2272,7 @@ void _3DScene::_generate_legend_texture(const Print& print, const std::vector first_volumes; - void reset(); + void reset() { first_volumes.clear(); } }; - static GCodePreviewData s_gcode_preview_data; + static GCodePreviewVolumeIndex s_gcode_preview_volume_index; class LegendTexture { From b1f5e7e8fa9713066c909c86ac4bf4f5d719b56e Mon Sep 17 00:00:00 2001 From: bubnikv Date: Wed, 14 Feb 2018 20:35:59 +0100 Subject: [PATCH 46/57] Removed the GCodePreviewData from the Print class, it does not belong here, as the GCode is generated outside of the Print class. Exported the GCodePreviewData as GCode::PreviewData to Perl. When exporting the G-code with a command line Slic3r, the GCodeAnalyzer is now supressed for performance reasons. Removed obsolete Perl module Slic3r::GUI::Plater::3DToolpaths. --- lib/Slic3r.pm | 1 + lib/Slic3r/GUI/3DScene.pm | 6 +- lib/Slic3r/GUI/Plater.pm | 11 +- lib/Slic3r/GUI/Plater/3DPreview.pm | 21 ++-- lib/Slic3r/GUI/Plater/3DToolpaths.pm | 159 --------------------------- lib/Slic3r/Print.pm | 2 +- xs/src/libslic3r/GCode.cpp | 10 +- xs/src/libslic3r/GCode.hpp | 9 +- xs/src/libslic3r/GCode/Analyzer.cpp | 47 ++++---- xs/src/libslic3r/GCode/Analyzer.hpp | 12 +- xs/src/libslic3r/Print.cpp | 83 -------------- xs/src/libslic3r/Print.hpp | 23 ---- xs/src/perlglue.cpp | 1 + xs/src/slic3r/GUI/3DScene.cpp | 109 +++++++++--------- xs/src/slic3r/GUI/3DScene.hpp | 25 +++-- xs/xsp/GCode.xsp | 27 ++++- xs/xsp/GUI_3DScene.xsp | 5 +- xs/xsp/Print.xsp | 9 -- xs/xsp/my.map | 4 + xs/xsp/typemap.xspt | 3 + 20 files changed, 166 insertions(+), 401 deletions(-) delete mode 100644 lib/Slic3r/GUI/Plater/3DToolpaths.pm diff --git a/lib/Slic3r.pm b/lib/Slic3r.pm index 66039ddf0..30d516217 100644 --- a/lib/Slic3r.pm +++ b/lib/Slic3r.pm @@ -136,6 +136,7 @@ sub thread_cleanup { *Slic3r::Flow::DESTROY = sub {}; *Slic3r::GCode::DESTROY = sub {}; *Slic3r::GCode::PlaceholderParser::DESTROY = sub {}; + *Slic3r::GCode::PreviewData::DESTROY = sub {}; *Slic3r::GCode::Sender::DESTROY = sub {}; *Slic3r::Geometry::BoundingBox::DESTROY = sub {}; *Slic3r::Geometry::BoundingBoxf::DESTROY = sub {}; diff --git a/lib/Slic3r/GUI/3DScene.pm b/lib/Slic3r/GUI/3DScene.pm index f63dad079..03055a582 100644 --- a/lib/Slic3r/GUI/3DScene.pm +++ b/lib/Slic3r/GUI/3DScene.pm @@ -4,7 +4,7 @@ # Slic3r::GUI::3DScene; # # Slic3r::GUI::Plater::3D derives from Slic3r::GUI::3DScene, -# Slic3r::GUI::Plater::3DPreview, Slic3r::GUI::Plater::3DToolpaths, +# Slic3r::GUI::Plater::3DPreview, # Slic3r::GUI::Plater::ObjectCutDialog and Slic3r::GUI::Plater::ObjectPartsPanel # own $self->{canvas} of the Slic3r::GUI::3DScene type. # @@ -2029,10 +2029,10 @@ sub load_wipe_tower_toolpaths { } sub load_gcode_preview { - my ($self, $print, $colors) = @_; + my ($self, $print, $gcode_preview_data, $colors) = @_; $self->SetCurrent($self->GetContext) if $self->UseVBOs; - Slic3r::GUI::_3DScene::load_gcode_preview($print, $self->volumes, $colors, $self->UseVBOs); + Slic3r::GUI::_3DScene::load_gcode_preview($print, $gcode_preview_data, $self->volumes, $colors, $self->UseVBOs); } sub set_toolpaths_range { diff --git a/lib/Slic3r/GUI/Plater.pm b/lib/Slic3r/GUI/Plater.pm index ba59e89be..17a39184d 100644 --- a/lib/Slic3r/GUI/Plater.pm +++ b/lib/Slic3r/GUI/Plater.pm @@ -60,6 +60,7 @@ sub new { $self->{print} = Slic3r::Print->new; # List of Perl objects Slic3r::GUI::Plater::Object, representing a 2D preview of the platter. $self->{objects} = []; + $self->{gcode_preview_data} = Slic3r::GCode::PreviewData->new; $self->{print}->set_status_cb(sub { my ($percent, $message) = @_; @@ -140,7 +141,7 @@ sub new { # Initialize 3D toolpaths preview if ($Slic3r::GUI::have_OpenGL) { - $self->{preview3D} = Slic3r::GUI::Plater::3DPreview->new($self->{preview_notebook}, $self->{print}, $self->{config}); + $self->{preview3D} = Slic3r::GUI::Plater::3DPreview->new($self->{preview_notebook}, $self->{print}, $self->{gcode_preview_data}, $self->{config}); $self->{preview3D}->canvas->on_viewport_changed(sub { $self->{canvas3D}->set_viewport_from_scene($self->{preview3D}->canvas); }); @@ -785,7 +786,7 @@ sub remove { splice @{$self->{objects}}, $obj_idx, 1; $self->{model}->delete_object($obj_idx); $self->{print}->delete_object($obj_idx); - $self->{print}->clear_gcode_preview_data; + $self->{gcode_preview_data}->reset; $self->{list}->DeleteItem($obj_idx); $self->object_list_changed; @@ -806,7 +807,7 @@ sub reset { @{$self->{objects}} = (); $self->{model}->clear_objects; $self->{print}->clear_objects; - $self->{print}->clear_gcode_preview_data; + $self->{gcode_preview_data}->reset; $self->{list}->DeleteAllItems; $self->object_list_changed; @@ -1267,7 +1268,7 @@ sub reslice { # Rather perform one additional unnecessary update of the print object instead of skipping a pending async update. $self->async_apply_config; # Reset gcode data - $self->{print}->clear_gcode_preview_data; + $self->{gcode_preview_data}->reset; $self->statusbar->SetCancelCallback(sub { $self->stop_background_process; $self->statusbar->SetStatusText("Slicing cancelled"); @@ -1381,7 +1382,7 @@ sub on_process_completed { $self->{export_thread} = Slic3r::spawn_thread(sub { eval { - $_thread_self->{print}->export_gcode(output_file => $_thread_self->{export_gcode_output_file}); + $_thread_self->{print}->export_gcode(output_file => $_thread_self->{export_gcode_output_file}, gcode_preview_data => $_thread_self->{gcode_preview_data}); }; my $export_completed_event = Wx::CommandEvent->new($EXPORT_COMPLETED_EVENT); if ($@) { diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index 6f96b8a96..10232b31d 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -8,11 +8,11 @@ use Wx qw(:misc :sizer :slider :statictext :keycode wxWHITE wxCB_READONLY); use Wx::Event qw(EVT_SLIDER EVT_KEY_DOWN EVT_CHECKBOX EVT_CHOICE EVT_CHECKLISTBOX); use base qw(Wx::Panel Class::Accessor); -__PACKAGE__->mk_accessors(qw(print enabled _loaded canvas slider_low slider_high single_layer auto_zoom)); +__PACKAGE__->mk_accessors(qw(print gcode_preview_data enabled _loaded canvas slider_low slider_high single_layer auto_zoom)); sub new { my $class = shift; - my ($parent, $print, $config) = @_; + my ($parent, $print, $gcode_preview_data, $config) = @_; my $self = $class->SUPER::new($parent, -1, wxDefaultPosition); $self->{config} = $config; @@ -192,7 +192,7 @@ sub new { }); EVT_CHOICE($self, $choice_view_type, sub { my $selection = $choice_view_type->GetCurrentSelection(); - $self->print->set_gcode_preview_type($selection); + $self->gcode_preview_data->set_type($selection); $self->auto_zoom(0); $self->reload_print; $self->auto_zoom(1); @@ -200,31 +200,31 @@ sub new { EVT_CHECKLISTBOX($self, $combochecklist_features, sub { my $flags = Slic3r::GUI::combochecklist_get_flags($combochecklist_features); - $self->print->set_gcode_preview_extrusion_flags($flags); + $self->gcode_preview_data->set_extrusion_flags($flags); $self->auto_zoom(0); $self->refresh_print; $self->auto_zoom(1); }); EVT_CHECKBOX($self, $checkbox_travel, sub { - $self->print->set_gcode_preview_travel_visible($checkbox_travel->IsChecked()); + $self->gcode_preview_data->set_travel_visible($checkbox_travel->IsChecked()); $self->auto_zoom(0); $self->refresh_print; $self->auto_zoom(1); }); EVT_CHECKBOX($self, $checkbox_retractions, sub { - $self->print->set_gcode_preview_retractions_visible($checkbox_retractions->IsChecked()); + $self->gcode_preview_data->set_retractions_visible($checkbox_retractions->IsChecked()); $self->auto_zoom(0); $self->refresh_print; $self->auto_zoom(1); }); EVT_CHECKBOX($self, $checkbox_unretractions, sub { - $self->print->set_gcode_preview_unretractions_visible($checkbox_unretractions->IsChecked()); + $self->gcode_preview_data->set_unretractions_visible($checkbox_unretractions->IsChecked()); $self->auto_zoom(0); $self->refresh_print; $self->auto_zoom(1); }); EVT_CHECKBOX($self, $checkbox_shells, sub { - $self->print->set_gcode_preview_shells_visible($checkbox_shells->IsChecked()); + $self->gcode_preview_data->set_shells_visible($checkbox_shells->IsChecked()); $self->auto_zoom(0); $self->refresh_print; $self->auto_zoom(1); @@ -236,6 +236,7 @@ sub new { # init canvas $self->print($print); + $self->gcode_preview_data($gcode_preview_data); # sets colors for gcode preview extrusion roles my @extrusion_roles_colors = ( @@ -252,7 +253,7 @@ sub new { 'Support material interface' => '00007F', 'Wipe tower' => 'B3E3AB', ); - $self->print->set_gcode_extrusion_paths_colors(\@extrusion_roles_colors); + $self->gcode_preview_data->set_extrusion_paths_colors(\@extrusion_roles_colors); $self->reload_print; @@ -354,7 +355,7 @@ sub load_print { } if ($self->IsShown) { - $self->canvas->load_gcode_preview($self->print, \@colors); + $self->canvas->load_gcode_preview($self->print, $self->gcode_preview_data, \@colors); # # load skirt and brim # $self->canvas->load_print_toolpaths($self->print, \@colors); diff --git a/lib/Slic3r/GUI/Plater/3DToolpaths.pm b/lib/Slic3r/GUI/Plater/3DToolpaths.pm deleted file mode 100644 index 776d8217b..000000000 --- a/lib/Slic3r/GUI/Plater/3DToolpaths.pm +++ /dev/null @@ -1,159 +0,0 @@ -package Slic3r::GUI::Plater::3DToolpaths; -use strict; -use warnings; -use utf8; - -use Slic3r::Print::State ':steps'; -use Wx qw(:misc :sizer :slider :statictext wxWHITE); -use Wx::Event qw(EVT_SLIDER EVT_KEY_DOWN); -use base qw(Wx::Panel Class::Accessor); - -__PACKAGE__->mk_accessors(qw(print enabled _loaded canvas slider)); - -sub new { - my $class = shift; - my ($parent, $print) = @_; - - my $self = $class->SUPER::new($parent, -1, wxDefaultPosition); - - # init GUI elements - my $canvas = Slic3r::GUI::3DScene->new($self); - $self->canvas($canvas); - my $slider = Wx::Slider->new( - $self, -1, - 0, # default - 0, # min - # we set max to a bogus non-zero value because the MSW implementation of wxSlider - # will skip drawing the slider if max <= min: - 1, # max - wxDefaultPosition, - wxDefaultSize, - wxVERTICAL | wxSL_INVERSE, - ); - $self->slider($slider); - - my $z_label = $self->{z_label} = Wx::StaticText->new($self, -1, "", wxDefaultPosition, - [40,-1], wxALIGN_CENTRE_HORIZONTAL); - $z_label->SetFont($Slic3r::GUI::small_font); - - my $vsizer = Wx::BoxSizer->new(wxVERTICAL); - $vsizer->Add($slider, 1, wxALL | wxEXPAND | wxALIGN_CENTER, 3); - $vsizer->Add($z_label, 0, wxALL | wxEXPAND | wxALIGN_CENTER, 3); - - my $sizer = Wx::BoxSizer->new(wxHORIZONTAL); - $sizer->Add($canvas, 1, wxALL | wxEXPAND, 0); - $sizer->Add($vsizer, 0, wxTOP | wxBOTTOM | wxEXPAND, 5); - - EVT_SLIDER($self, $slider, sub { - $self->set_z($self->{layers_z}[$slider->GetValue]) - if $self->enabled; - }); - EVT_KEY_DOWN($canvas, sub { - my ($s, $event) = @_; - if ($event->HasModifiers) { - $event->Skip; - } else { - my $key = $event->GetKeyCode; - if ($key == 85 || $key == 315) { - $slider->SetValue($slider->GetValue + 1); - $self->set_z($self->{layers_z}[$slider->GetValue]); - } elsif ($key == 68 || $key == 317) { - $slider->SetValue($slider->GetValue - 1); - $self->set_z($self->{layers_z}[$slider->GetValue]); - } else { - $event->Skip; - } - } - }); - - $self->SetSizer($sizer); - $self->SetMinSize($self->GetSize); - $sizer->SetSizeHints($self); - - # init canvas - $self->print($print); - $self->reload_print; - - return $self; -} - -sub reload_print { - my ($self) = @_; - - $self->canvas->reset_objects; - $self->_loaded(0); - $self->load_print; -} - -sub load_print { - my ($self) = @_; - - return if $self->_loaded; - - # we require that there's at least one object and the posSlice step - # is performed on all of them (this ensures that _shifted_copies was - # populated and we know the number of layers) - if (!$self->print->object_step_done(STEP_SLICE)) { - $self->enabled(0); - $self->slider->Hide; - $self->canvas->Refresh; # clears canvas - return; - } - - my $z_idx; - { - my %z = (); # z => 1 - foreach my $object (@{$self->{print}->objects}) { - foreach my $layer (@{$object->layers}, @{$object->support_layers}) { - $z{$layer->print_z} = 1; - } - } - $self->enabled(1); - $self->{layers_z} = [ sort { $a <=> $b } keys %z ]; - $self->slider->SetRange(0, scalar(@{$self->{layers_z}})-1); - if (($z_idx = $self->slider->GetValue) <= $#{$self->{layers_z}} && $self->slider->GetValue != 0) { - # use $z_idx - } else { - $self->slider->SetValue(scalar(@{$self->{layers_z}})-1); - $z_idx = @{$self->{layers_z}} ? -1 : undef; - } - $self->slider->Show; - $self->Layout; - } - - if ($self->IsShown) { - $self->canvas->load_gcode_preview($self->print); - -# # load skirt and brim -# $self->canvas->load_print_toolpaths($self->print); -# -# foreach my $object (@{$self->print->objects}) { -# $self->canvas->load_print_object_toolpaths($object); -# -# # Show the objects in very transparent color. -# #my @volume_ids = $self->canvas->load_object($object->model_object); -# #$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids; -# } - - $self->canvas->zoom_to_volumes; - $self->_loaded(1); - } - - $self->set_z($self->{layers_z}[$z_idx]); -} - -sub set_z { - my ($self, $z) = @_; - - return if !$self->enabled; - $self->{z_label}->SetLabel(sprintf '%.2f', $z); - $self->canvas->set_toolpaths_range(0, $z); - $self->canvas->Refresh if $self->IsShown; -} - -sub set_bed_shape { - my ($self, $bed_shape) = @_; - $self->canvas->set_bed_shape($bed_shape); -} - -1; diff --git a/lib/Slic3r/Print.pm b/lib/Slic3r/Print.pm index 12ad2f12f..4d112536a 100644 --- a/lib/Slic3r/Print.pm +++ b/lib/Slic3r/Print.pm @@ -81,7 +81,7 @@ sub export_gcode { $self->status_cb->(90, "Exporting G-code" . ($output_file ? " to $output_file" : "")); # The following line may die for multiple reasons. - Slic3r::GCode->new->do_export($self, $output_file); + Slic3r::GCode->new->do_export($self, $output_file, $params{gcode_preview_data}); # run post-processing scripts if (@{$self->config->post_process}) { diff --git a/xs/src/libslic3r/GCode.cpp b/xs/src/libslic3r/GCode.cpp index c256268e5..8c14b4adb 100644 --- a/xs/src/libslic3r/GCode.cpp +++ b/xs/src/libslic3r/GCode.cpp @@ -348,7 +348,7 @@ std::vector>> GCode::collec return layers_to_print; } -void GCode::do_export(Print *print, const char *path) +void GCode::do_export(Print *print, const char *path, GCodePreviewData *preview_data) { PROFILE_CLEAR(); @@ -363,7 +363,7 @@ void GCode::do_export(Print *print, const char *path) throw std::runtime_error(std::string("G-code export to ") + path + " failed.\nCannot open the file for writing.\n"); this->m_placeholder_parser_failed_templates.clear(); - this->_do_export(*print, file); + this->_do_export(*print, file, preview_data); fflush(file); if (ferror(file)) { fclose(file); @@ -394,7 +394,7 @@ void GCode::do_export(Print *print, const char *path) PROFILE_OUTPUT(debug_out_path("gcode-export-profile.txt").c_str()); } -void GCode::_do_export(Print &print, FILE *file) +void GCode::_do_export(Print &print, FILE *file, GCodePreviewData *preview_data) { PROFILE_FUNC(); @@ -404,6 +404,7 @@ void GCode::_do_export(Print &print, FILE *file) // resets analyzer m_analyzer.reset(); + m_enable_analyzer = preview_data != nullptr; // resets analyzer's tracking data m_last_mm3_per_mm = GCodeAnalyzer::Default_mm3_per_mm; @@ -820,7 +821,8 @@ void GCode::_do_export(Print &print, FILE *file) } // starts analizer calculations - m_analyzer.calc_gcode_preview_data(print); + if (preview_data != nullptr) + m_analyzer.calc_gcode_preview_data(*preview_data); } std::string GCode::placeholder_parser_process(const std::string &name, const std::string &templ, unsigned int current_extruder_id, const DynamicConfig *config_override) diff --git a/xs/src/libslic3r/GCode.hpp b/xs/src/libslic3r/GCode.hpp index 6e42c52d0..f35f2d5e9 100644 --- a/xs/src/libslic3r/GCode.hpp +++ b/xs/src/libslic3r/GCode.hpp @@ -26,6 +26,7 @@ namespace Slic3r { // Forward declarations. class GCode; +class GCodePreviewData; class AvoidCrossingPerimeters { public: @@ -119,7 +120,7 @@ public: m_enable_loop_clipping(true), m_enable_cooling_markers(false), m_enable_extrusion_role_markers(false), - m_enable_analyzer(true), + m_enable_analyzer(false), m_layer_count(0), m_layer_index(-1), m_layer(nullptr), @@ -136,7 +137,7 @@ public: ~GCode() {} // throws std::runtime_exception - void do_export(Print *print, const char *path); + void do_export(Print *print, const char *path, GCodePreviewData *preview_data = nullptr); // Exported for the helper classes (OozePrevention, Wipe) and for the Perl binding for unit tests. const Pointf& origin() const { return m_origin; } @@ -153,8 +154,6 @@ public: // inside the generated string and after the G-code export finishes. std::string placeholder_parser_process(const std::string &name, const std::string &templ, unsigned int current_extruder_id, const DynamicConfig *config_override = nullptr); bool enable_cooling_markers() const { return m_enable_cooling_markers; } - bool enable_analyzer() const { return m_enable_analyzer; } - void enable_analyzer(bool enable) { m_enable_analyzer = enable; } // For Perl bindings, to be used exclusively by unit tests. unsigned int layer_count() const { return m_layer_count; } @@ -162,7 +161,7 @@ public: void apply_print_config(const PrintConfig &print_config); protected: - void _do_export(Print &print, FILE *file); + void _do_export(Print &print, FILE *file, GCodePreviewData *preview_data); // Object and support extrusions of the same PrintObject at the same print_z. struct LayerToPrint diff --git a/xs/src/libslic3r/GCode/Analyzer.cpp b/xs/src/libslic3r/GCode/Analyzer.cpp index 938f0371d..f8d196f23 100644 --- a/xs/src/libslic3r/GCode/Analyzer.cpp +++ b/xs/src/libslic3r/GCode/Analyzer.cpp @@ -123,22 +123,22 @@ const std::string& GCodeAnalyzer::process_gcode(const std::string& gcode) return m_process_output; } -void GCodeAnalyzer::calc_gcode_preview_data(Print& print) +void GCodeAnalyzer::calc_gcode_preview_data(GCodePreviewData& preview_data) { // resets preview data - print.gcode_preview.reset(); + preview_data.reset(); // calculates extrusion layers - _calc_gcode_preview_extrusion_layers(print); + _calc_gcode_preview_extrusion_layers(preview_data); // calculates travel - _calc_gcode_preview_travel(print); + _calc_gcode_preview_travel(preview_data); // calculates retractions - _calc_gcode_preview_retractions(print); + _calc_gcode_preview_retractions(preview_data); // calculates unretractions - _calc_gcode_preview_unretractions(print); + _calc_gcode_preview_unretractions(preview_data); } bool GCodeAnalyzer::is_valid_extrusion_role(ExtrusionRole role) @@ -601,7 +601,7 @@ bool GCodeAnalyzer::_is_valid_extrusion_role(int value) const return ((int)erNone <= value) && (value <= (int)erMixed); } -void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(Print& print) +void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(GCodePreviewData& preview_data) { struct Helper { @@ -619,7 +619,7 @@ void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(Print& print) return layers.back(); } - static void store_polyline(const Polyline& polyline, const Metadata& data, float z, Print& print) + static void store_polyline(const Polyline& polyline, const Metadata& data, float z, GCodePreviewData& preview_data) { // if the polyline is valid, create the extrusion path from it and store it if (polyline.is_valid()) @@ -629,7 +629,7 @@ void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(Print& print) path.feedrate = data.feedrate; path.extruder_id = data.extruder_id; - get_layer_at_z(print.gcode_preview.extrusion.layers, z).paths.push_back(path); + get_layer_at_z(preview_data.extrusion.layers, z).paths.push_back(path); } } }; @@ -653,7 +653,7 @@ void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(Print& print) { // store current polyline polyline.remove_duplicate_points(); - Helper::store_polyline(polyline, data, z, print); + Helper::store_polyline(polyline, data, z, preview_data); // reset current polyline polyline = Polyline(); @@ -679,23 +679,24 @@ void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(Print& print) // store last polyline polyline.remove_duplicate_points(); - Helper::store_polyline(polyline, data, z, print); + Helper::store_polyline(polyline, data, z, preview_data); // updates preview ranges data - print.gcode_preview.extrusion.ranges.height.set_from(height_range); - print.gcode_preview.extrusion.ranges.width.set_from(width_range); - print.gcode_preview.extrusion.ranges.feedrate.set_from(feedrate_range); + preview_data.extrusion.ranges.height.set_from(height_range); + preview_data.extrusion.ranges.width.set_from(width_range); + preview_data.extrusion.ranges.feedrate.set_from(feedrate_range); } -void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) +void GCodeAnalyzer::_calc_gcode_preview_travel(GCodePreviewData& preview_data) { struct Helper { - static void store_polyline(const Polyline3& polyline, GCodePreviewData::Travel::EType type, GCodePreviewData::Travel::Polyline::EDirection direction, float feedrate, unsigned int extruder_id, Print& print) + static void store_polyline(const Polyline3& polyline, GCodePreviewData::Travel::EType type, GCodePreviewData::Travel::Polyline::EDirection direction, + float feedrate, unsigned int extruder_id, GCodePreviewData& preview_data) { // if the polyline is valid, store it if (polyline.is_valid()) - print.gcode_preview.travel.polylines.emplace_back(type, direction, feedrate, extruder_id, polyline); + preview_data.travel.polylines.emplace_back(type, direction, feedrate, extruder_id, polyline); } }; @@ -720,7 +721,7 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) { // store current polyline polyline.remove_duplicate_points(); - Helper::store_polyline(polyline, type, direction, feedrate, extruder_id, print); + Helper::store_polyline(polyline, type, direction, feedrate, extruder_id, preview_data); // reset current polyline polyline = Polyline3(); @@ -742,10 +743,10 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(Print& print) // store last polyline polyline.remove_duplicate_points(); - Helper::store_polyline(polyline, type, direction, feedrate, extruder_id, print); + Helper::store_polyline(polyline, type, direction, feedrate, extruder_id, preview_data); } -void GCodeAnalyzer::_calc_gcode_preview_retractions(Print& print) +void GCodeAnalyzer::_calc_gcode_preview_retractions(GCodePreviewData& preview_data) { TypeToMovesMap::iterator retraction_moves = m_moves_map.find(GCodeMove::Retract); if (retraction_moves == m_moves_map.end()) @@ -755,11 +756,11 @@ void GCodeAnalyzer::_calc_gcode_preview_retractions(Print& print) { // store position Point3 position(scale_(move.start_position.x), scale_(move.start_position.y), scale_(move.start_position.z)); - print.gcode_preview.retraction.positions.emplace_back(position, move.data.width, move.data.height); + preview_data.retraction.positions.emplace_back(position, move.data.width, move.data.height); } } -void GCodeAnalyzer::_calc_gcode_preview_unretractions(Print& print) +void GCodeAnalyzer::_calc_gcode_preview_unretractions(GCodePreviewData& preview_data) { TypeToMovesMap::iterator unretraction_moves = m_moves_map.find(GCodeMove::Unretract); if (unretraction_moves == m_moves_map.end()) @@ -769,7 +770,7 @@ void GCodeAnalyzer::_calc_gcode_preview_unretractions(Print& print) { // store position Point3 position(scale_(move.start_position.x), scale_(move.start_position.y), scale_(move.start_position.z)); - print.gcode_preview.unretraction.positions.emplace_back(position, move.data.width, move.data.height); + preview_data.unretraction.positions.emplace_back(position, move.data.width, move.data.height); } } diff --git a/xs/src/libslic3r/GCode/Analyzer.hpp b/xs/src/libslic3r/GCode/Analyzer.hpp index bfb2d668c..7939d432d 100644 --- a/xs/src/libslic3r/GCode/Analyzer.hpp +++ b/xs/src/libslic3r/GCode/Analyzer.hpp @@ -10,7 +10,7 @@ namespace Slic3r { -class Print; +class GCodePreviewData; class GCodeAnalyzer { @@ -116,7 +116,7 @@ public: const std::string& process_gcode(const std::string& gcode); // Calculates all data needed for gcode visualization - void calc_gcode_preview_data(Print& print); + void calc_gcode_preview_data(GCodePreviewData& preview_data); static bool is_valid_extrusion_role(ExtrusionRole role); @@ -216,10 +216,10 @@ private: // Checks if the given int is a valid extrusion role (contained into enum ExtrusionRole) bool _is_valid_extrusion_role(int value) const; - void _calc_gcode_preview_extrusion_layers(Print& print); - void _calc_gcode_preview_travel(Print& print); - void _calc_gcode_preview_retractions(Print& print); - void _calc_gcode_preview_unretractions(Print& print); + void _calc_gcode_preview_extrusion_layers(GCodePreviewData& preview_data); + void _calc_gcode_preview_travel(GCodePreviewData& preview_data); + void _calc_gcode_preview_retractions(GCodePreviewData& preview_data); + void _calc_gcode_preview_unretractions(GCodePreviewData& preview_data); }; } // namespace Slic3r diff --git a/xs/src/libslic3r/Print.cpp b/xs/src/libslic3r/Print.cpp index 5fb81124c..c689929c6 100644 --- a/xs/src/libslic3r/Print.cpp +++ b/xs/src/libslic3r/Print.cpp @@ -66,89 +66,6 @@ bool Print::reload_model_instances() return invalidated; } -void Print::clear_gcode_preview_data() -{ - gcode_preview.reset(); -} - -void Print::set_gcode_preview_type(unsigned char type) -{ - if ((0 <= type) && (type < GCodePreviewData::Extrusion::Num_View_Types)) - gcode_preview.extrusion.view_type = (GCodePreviewData::Extrusion::EViewType)type; -} - -void Print::set_gcode_preview_extrusion_flags(unsigned int flags) -{ - gcode_preview.extrusion.role_flags = flags; -} - -bool Print::is_gcode_preview_extrusion_role_enabled(ExtrusionRole role) -{ - return gcode_preview.extrusion.is_role_flag_set(role); -} - -void Print::set_gcode_preview_travel_visible(bool visible) -{ - gcode_preview.travel.is_visible = visible; -} - -void Print::set_gcode_preview_retractions_visible(bool visible) -{ - gcode_preview.retraction.is_visible = visible; -} - -void Print::set_gcode_preview_unretractions_visible(bool visible) -{ - gcode_preview.unretraction.is_visible = visible; -} - -void Print::set_gcode_preview_shells_visible(bool visible) -{ - gcode_preview.shell.is_visible = visible; -} - -void Print::set_gcode_extrusion_paths_colors(const std::vector& colors) -{ - unsigned int size = (unsigned int)colors.size(); - - if (size % 2 != 0) - return; - - for (unsigned int i = 0; i < size; i += 2) - { - const std::string& color_str = colors[i + 1]; - - if (color_str.size() == 6) - { - bool valid = true; - for (int c = 0; c < 6; ++c) - { - if (::isxdigit(color_str[c]) == 0) - { - valid = false; - break; - } - } - - if (valid) - { - unsigned int color; - std::stringstream ss; - ss << std::hex << color_str; - ss >> color; - - float den = 1.0f / 255.0f; - - float r = (float)((color & 0xFF0000) >> 16) * den; - float g = (float)((color & 0x00FF00) >> 8) * den; - float b = (float)(color & 0x0000FF) * den; - - gcode_preview.set_extrusion_role_color(colors[i], r, g, b, 1.0f); - } - } - } -} - PrintRegion* Print::add_region() { regions.push_back(new PrintRegion(this)); diff --git a/xs/src/libslic3r/Print.hpp b/xs/src/libslic3r/Print.hpp index f08b4ec15..c56e64c6c 100644 --- a/xs/src/libslic3r/Print.hpp +++ b/xs/src/libslic3r/Print.hpp @@ -15,7 +15,6 @@ #include "Slicing.hpp" #include "GCode/ToolOrdering.hpp" #include "GCode/WipeTower.hpp" -#include "GCode/PreviewData.hpp" #include "tbb/atomic.h" @@ -241,7 +240,6 @@ public: // ordered collections of extrusion paths to build skirt loops and brim ExtrusionEntityCollection skirt, brim; - GCodePreviewData gcode_preview; Print() : total_used_filament(0), total_extruded_volume(0) { restart(); } ~Print() { clear_objects(); } @@ -255,27 +253,6 @@ public: void reload_object(size_t idx); bool reload_model_instances(); - void clear_gcode_preview_data(); - void set_gcode_preview_type(unsigned char type); - void set_gcode_preview_extrusion_flags(unsigned int flags); - bool is_gcode_preview_extrusion_role_enabled(ExtrusionRole role); - void set_gcode_preview_travel_visible(bool visible); - void set_gcode_preview_retractions_visible(bool visible); - void set_gcode_preview_unretractions_visible(bool visible); - void set_gcode_preview_shells_visible(bool visible); - - // Sets the extrusion path colors from the given strings vector. - // Data in the vector should be formatted as follows: - // std::vector role_colors = - // { , , - // , , - // , , - // ... - // , }; - // where should be a string from GCodePreviewData::Extrusion::Default_Extrusion_Role_Names[] - // and an RGB color in hex format (i.e. red = FF0000) - void set_gcode_extrusion_paths_colors(const std::vector& colors); - // methods for handling regions PrintRegion* get_region(size_t idx) { return regions.at(idx); } const PrintRegion* get_region(size_t idx) const { return regions.at(idx); } diff --git a/xs/src/perlglue.cpp b/xs/src/perlglue.cpp index 948fcfd93..5f3b5f691 100644 --- a/xs/src/perlglue.cpp +++ b/xs/src/perlglue.cpp @@ -15,6 +15,7 @@ REGISTER_CLASS(Filler, "Filler"); REGISTER_CLASS(Flow, "Flow"); REGISTER_CLASS(CoolingBuffer, "GCode::CoolingBuffer"); REGISTER_CLASS(GCode, "GCode"); +REGISTER_CLASS(GCodePreviewData, "GCode::PreviewData"); REGISTER_CLASS(GCodeSender, "GCode::Sender"); REGISTER_CLASS(Layer, "Layer"); REGISTER_CLASS(SupportLayer, "Layer::Support"); diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index b5fc9245e..616d43496 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -6,6 +6,7 @@ #include "../../libslic3r/ExtrusionEntity.hpp" #include "../../libslic3r/ExtrusionEntityCollection.hpp" #include "../../libslic3r/Geometry.hpp" +#include "../../libslic3r/GCode/PreviewData.hpp" #include "../../libslic3r/Print.hpp" #include "../../libslic3r/Slicing.hpp" #include "GCode/Analyzer.hpp" @@ -1128,13 +1129,13 @@ _3DScene::LegendTexture::~LegendTexture() _destroy_texture(); } -bool _3DScene::LegendTexture::generate_texture(const Print& print, const std::vector& tool_colors) +bool _3DScene::LegendTexture::generate_texture(const GCodePreviewData& preview_data, const std::vector& tool_colors) { _destroy_texture(); // collects items to render - const std::string& title = print.gcode_preview.get_legend_title(); - const GCodePreviewData::LegendItemsList& items = print.gcode_preview.get_legend_items(tool_colors); + const std::string& title = preview_data.get_legend_title(); + const GCodePreviewData::LegendItemsList& items = preview_data.get_legend_items(tool_colors); unsigned int items_count = (unsigned int)items.size(); if (items_count == 0) @@ -1240,7 +1241,7 @@ bool _3DScene::LegendTexture::generate_texture(const Print& print, const std::ve memDC.SelectObject(wxNullBitmap); - return _create_texture(print, bitmap); + return _create_texture(preview_data, bitmap); } unsigned int _3DScene::LegendTexture::get_texture_id() const @@ -1263,7 +1264,7 @@ void _3DScene::LegendTexture::reset_texture() _destroy_texture(); } -bool _3DScene::LegendTexture::_create_texture(const Print& print, const wxBitmap& bitmap) +bool _3DScene::LegendTexture::_create_texture(const GCodePreviewData& preview_data, const wxBitmap& bitmap) { if ((m_tex_width == 0) || (m_tex_height == 0)) return false; @@ -1341,9 +1342,9 @@ static inline std::vector parse_colors(const std::vector &sc return output; } -void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volumes, const std::vector& str_tool_colors, bool use_VBOs) +void _3DScene::load_gcode_preview(const Print* print, const GCodePreviewData* preview_data, GLVolumeCollection* volumes, const std::vector& str_tool_colors, bool use_VBOs) { - if ((print == nullptr) || (volumes == nullptr)) + if ((preview_data == nullptr) || (volumes == nullptr)) return; if (volumes->empty()) @@ -1352,10 +1353,10 @@ void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volume s_gcode_preview_volume_index.reset(); - _load_gcode_extrusion_paths(*print, *volumes, tool_colors, use_VBOs); - _load_gcode_travel_paths(*print, *volumes, tool_colors, use_VBOs); - _load_gcode_retractions(*print, *volumes, use_VBOs); - _load_gcode_unretractions(*print, *volumes, use_VBOs); + _load_gcode_extrusion_paths(*preview_data, *volumes, tool_colors, use_VBOs); + _load_gcode_travel_paths(*preview_data, *volumes, tool_colors, use_VBOs); + _load_gcode_retractions(*preview_data, *volumes, use_VBOs); + _load_gcode_unretractions(*preview_data, *volumes, use_VBOs); if (volumes->empty()) { @@ -1364,14 +1365,14 @@ void _3DScene::load_gcode_preview(const Print* print, GLVolumeCollection* volume } else { - _generate_legend_texture(*print, tool_colors); + _generate_legend_texture(*preview_data, tool_colors); _load_shells(*print, *volumes, use_VBOs); volumes->set_render_interleaved_only_volumes(GLVolumeCollection::RenderInterleavedOnlyVolumes(true, 0.25f)); } } - _update_gcode_volumes_visibility(*print, *volumes); + _update_gcode_volumes_visibility(*preview_data, *volumes); } unsigned int _3DScene::get_legend_texture_id() @@ -1751,7 +1752,7 @@ void _3DScene::_load_wipe_tower_toolpaths( BOOST_LOG_TRIVIAL(debug) << "Loading wipe tower toolpaths in parallel - end"; } -void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs) +void _3DScene::_load_gcode_extrusion_paths(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs) { // helper functions to select data in dependence of the extrusion view type struct Helper @@ -1831,12 +1832,12 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio // detects filters FiltersList filters; - for (const GCodePreviewData::Extrusion::Layer& layer : print.gcode_preview.extrusion.layers) + for (const GCodePreviewData::Extrusion::Layer& layer : preview_data.extrusion.layers) { for (const ExtrusionPath& path : layer.paths) { ExtrusionRole role = path.role(); - float path_filter = Helper::path_filter(print.gcode_preview.extrusion.view_type, path); + float path_filter = Helper::path_filter(preview_data.extrusion.view_type, path); if (std::find(filters.begin(), filters.end(), Filter(path_filter, role)) == filters.end()) filters.emplace_back(path_filter, role); } @@ -1851,7 +1852,7 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio { s_gcode_preview_volume_index.first_volumes.emplace_back(GCodePreviewVolumeIndex::Extrusion, (unsigned int)filter.role, (unsigned int)volumes.volumes.size()); - GLVolume* volume = new GLVolume(Helper::path_color(print.gcode_preview, tool_colors, filter.value).rgba); + GLVolume* volume = new GLVolume(Helper::path_color(preview_data, tool_colors, filter.value).rgba); if (volume != nullptr) { filter.volume = volume; @@ -1877,11 +1878,11 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio } // populates volumes - for (const GCodePreviewData::Extrusion::Layer& layer : print.gcode_preview.extrusion.layers) + for (const GCodePreviewData::Extrusion::Layer& layer : preview_data.extrusion.layers) { for (const ExtrusionPath& path : layer.paths) { - float path_filter = Helper::path_filter(print.gcode_preview.extrusion.view_type, path); + float path_filter = Helper::path_filter(preview_data.extrusion.view_type, path); FiltersList::iterator filter = std::find(filters.begin(), filters.end(), Filter(path_filter, path.role())); if (filter != filters.end()) { @@ -1906,27 +1907,27 @@ void _3DScene::_load_gcode_extrusion_paths(const Print& print, GLVolumeCollectio } } -void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs) +void _3DScene::_load_gcode_travel_paths(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs) { size_t initial_volumes_count = volumes.volumes.size(); s_gcode_preview_volume_index.first_volumes.emplace_back(GCodePreviewVolumeIndex::Travel, 0, (unsigned int)initial_volumes_count); bool res = true; - switch (print.gcode_preview.extrusion.view_type) + switch (preview_data.extrusion.view_type) { case GCodePreviewData::Extrusion::Feedrate: { - res = _travel_paths_by_feedrate(print, volumes); + res = _travel_paths_by_feedrate(preview_data, volumes); break; } case GCodePreviewData::Extrusion::Tool: { - res = _travel_paths_by_tool(print, volumes, tool_colors); + res = _travel_paths_by_tool(preview_data, volumes, tool_colors); break; } default: { - res = _travel_paths_by_type(print, volumes); + res = _travel_paths_by_type(preview_data, volumes); break; } } @@ -1961,7 +1962,7 @@ void _3DScene::_load_gcode_travel_paths(const Print& print, GLVolumeCollection& } } -bool _3DScene::_travel_paths_by_type(const Print& print, GLVolumeCollection& volumes) +bool _3DScene::_travel_paths_by_type(const GCodePreviewData& preview_data, GLVolumeCollection& volumes) { // Helper structure for types struct Type @@ -1987,7 +1988,7 @@ bool _3DScene::_travel_paths_by_type(const Print& print, GLVolumeCollection& vol // detects types TypesList types; - for (const GCodePreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + for (const GCodePreviewData::Travel::Polyline& polyline : preview_data.travel.polylines) { if (std::find(types.begin(), types.end(), Type(polyline.type)) == types.end()) types.emplace_back(polyline.type); @@ -2000,7 +2001,7 @@ bool _3DScene::_travel_paths_by_type(const Print& print, GLVolumeCollection& vol // creates a new volume for each type for (Type& type : types) { - GLVolume* volume = new GLVolume(print.gcode_preview.travel.type_colors[type.value].rgba); + GLVolume* volume = new GLVolume(preview_data.travel.type_colors[type.value].rgba); if (volume == nullptr) return false; else @@ -2011,7 +2012,7 @@ bool _3DScene::_travel_paths_by_type(const Print& print, GLVolumeCollection& vol } // populates volumes - for (const GCodePreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + for (const GCodePreviewData::Travel::Polyline& polyline : preview_data.travel.polylines) { TypesList::iterator type = std::find(types.begin(), types.end(), Type(polyline.type)); if (type != types.end()) @@ -2020,14 +2021,14 @@ bool _3DScene::_travel_paths_by_type(const Print& print, GLVolumeCollection& vol type->volume->offsets.push_back(type->volume->indexed_vertex_array.quad_indices.size()); type->volume->offsets.push_back(type->volume->indexed_vertex_array.triangle_indices.size()); - polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *type->volume); + polyline3_to_verts(polyline.polyline, preview_data.travel.width, preview_data.travel.height, *type->volume); } } return true; } -bool _3DScene::_travel_paths_by_feedrate(const Print& print, GLVolumeCollection& volumes) +bool _3DScene::_travel_paths_by_feedrate(const GCodePreviewData& preview_data, GLVolumeCollection& volumes) { // Helper structure for feedrate struct Feedrate @@ -2053,7 +2054,7 @@ bool _3DScene::_travel_paths_by_feedrate(const Print& print, GLVolumeCollection& // detects feedrates FeedratesList feedrates; - for (const GCodePreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + for (const GCodePreviewData::Travel::Polyline& polyline : preview_data.travel.polylines) { if (std::find(feedrates.begin(), feedrates.end(), Feedrate(polyline.feedrate)) == feedrates.end()) feedrates.emplace_back(polyline.feedrate); @@ -2066,7 +2067,7 @@ bool _3DScene::_travel_paths_by_feedrate(const Print& print, GLVolumeCollection& // creates a new volume for each feedrate for (Feedrate& feedrate : feedrates) { - GLVolume* volume = new GLVolume(print.gcode_preview.get_extrusion_feedrate_color(feedrate.value).rgba); + GLVolume* volume = new GLVolume(preview_data.get_extrusion_feedrate_color(feedrate.value).rgba); if (volume == nullptr) return false; else @@ -2077,7 +2078,7 @@ bool _3DScene::_travel_paths_by_feedrate(const Print& print, GLVolumeCollection& } // populates volumes - for (const GCodePreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + for (const GCodePreviewData::Travel::Polyline& polyline : preview_data.travel.polylines) { FeedratesList::iterator feedrate = std::find(feedrates.begin(), feedrates.end(), Feedrate(polyline.feedrate)); if (feedrate != feedrates.end()) @@ -2086,14 +2087,14 @@ bool _3DScene::_travel_paths_by_feedrate(const Print& print, GLVolumeCollection& feedrate->volume->offsets.push_back(feedrate->volume->indexed_vertex_array.quad_indices.size()); feedrate->volume->offsets.push_back(feedrate->volume->indexed_vertex_array.triangle_indices.size()); - polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *feedrate->volume); + polyline3_to_verts(polyline.polyline, preview_data.travel.width, preview_data.travel.height, *feedrate->volume); } } return true; } -bool _3DScene::_travel_paths_by_tool(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors) +bool _3DScene::_travel_paths_by_tool(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, const std::vector& tool_colors) { // Helper structure for tool struct Tool @@ -2119,7 +2120,7 @@ bool _3DScene::_travel_paths_by_tool(const Print& print, GLVolumeCollection& vol // detects tools ToolsList tools; - for (const GCodePreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + for (const GCodePreviewData::Travel::Polyline& polyline : preview_data.travel.polylines) { if (std::find(tools.begin(), tools.end(), Tool(polyline.extruder_id)) == tools.end()) tools.emplace_back(polyline.extruder_id); @@ -2143,7 +2144,7 @@ bool _3DScene::_travel_paths_by_tool(const Print& print, GLVolumeCollection& vol } // populates volumes - for (const GCodePreviewData::Travel::Polyline& polyline : print.gcode_preview.travel.polylines) + for (const GCodePreviewData::Travel::Polyline& polyline : preview_data.travel.polylines) { ToolsList::iterator tool = std::find(tools.begin(), tools.end(), Tool(polyline.extruder_id)); if (tool != tools.end()) @@ -2152,27 +2153,27 @@ bool _3DScene::_travel_paths_by_tool(const Print& print, GLVolumeCollection& vol tool->volume->offsets.push_back(tool->volume->indexed_vertex_array.quad_indices.size()); tool->volume->offsets.push_back(tool->volume->indexed_vertex_array.triangle_indices.size()); - polyline3_to_verts(polyline.polyline, print.gcode_preview.travel.width, print.gcode_preview.travel.height, *tool->volume); + polyline3_to_verts(polyline.polyline, preview_data.travel.width, preview_data.travel.height, *tool->volume); } } return true; } -void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) +void _3DScene::_load_gcode_retractions(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, bool use_VBOs) { s_gcode_preview_volume_index.first_volumes.emplace_back(GCodePreviewVolumeIndex::Retraction, 0, (unsigned int)volumes.volumes.size()); // nothing to render, return - if (print.gcode_preview.retraction.positions.empty()) + if (preview_data.retraction.positions.empty()) return; - GLVolume* volume = new GLVolume(print.gcode_preview.retraction.color.rgba); + GLVolume* volume = new GLVolume(preview_data.retraction.color.rgba); if (volume != nullptr) { volumes.volumes.emplace_back(volume); - for (const GCodePreviewData::Retraction::Position& position : print.gcode_preview.retraction.positions) + for (const GCodePreviewData::Retraction::Position& position : preview_data.retraction.positions) { volume->print_zs.push_back(unscale(position.position.z)); volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); @@ -2187,20 +2188,20 @@ void _3DScene::_load_gcode_retractions(const Print& print, GLVolumeCollection& v } } -void _3DScene::_load_gcode_unretractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) +void _3DScene::_load_gcode_unretractions(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, bool use_VBOs) { s_gcode_preview_volume_index.first_volumes.emplace_back(GCodePreviewVolumeIndex::Unretraction, 0, (unsigned int)volumes.volumes.size()); // nothing to render, return - if (print.gcode_preview.unretraction.positions.empty()) + if (preview_data.unretraction.positions.empty()) return; - GLVolume* volume = new GLVolume(print.gcode_preview.unretraction.color.rgba); + GLVolume* volume = new GLVolume(preview_data.unretraction.color.rgba); if (volume != nullptr) { volumes.volumes.emplace_back(volume); - for (const GCodePreviewData::Retraction::Position& position : print.gcode_preview.unretraction.positions) + for (const GCodePreviewData::Retraction::Position& position : preview_data.unretraction.positions) { volume->print_zs.push_back(unscale(position.position.z)); volume->offsets.push_back(volume->indexed_vertex_array.quad_indices.size()); @@ -2215,7 +2216,7 @@ void _3DScene::_load_gcode_unretractions(const Print& print, GLVolumeCollection& } } -void _3DScene::_update_gcode_volumes_visibility(const Print& print, GLVolumeCollection& volumes) +void _3DScene::_update_gcode_volumes_visibility(const GCodePreviewData& preview_data, GLVolumeCollection& volumes) { unsigned int size = (unsigned int)s_gcode_preview_volume_index.first_volumes.size(); for (unsigned int i = 0; i < size; ++i) @@ -2231,27 +2232,27 @@ void _3DScene::_update_gcode_volumes_visibility(const Print& print, GLVolumeColl { case GCodePreviewVolumeIndex::Extrusion: { - volume->is_active = print.gcode_preview.extrusion.is_role_flag_set((ExtrusionRole)s_gcode_preview_volume_index.first_volumes[i].flag); + volume->is_active = preview_data.extrusion.is_role_flag_set((ExtrusionRole)s_gcode_preview_volume_index.first_volumes[i].flag); break; } case GCodePreviewVolumeIndex::Travel: { - volume->is_active = print.gcode_preview.travel.is_visible; + volume->is_active = preview_data.travel.is_visible; break; } case GCodePreviewVolumeIndex::Retraction: { - volume->is_active = print.gcode_preview.retraction.is_visible; + volume->is_active = preview_data.retraction.is_visible; break; } case GCodePreviewVolumeIndex::Unretraction: { - volume->is_active = print.gcode_preview.unretraction.is_visible; + volume->is_active = preview_data.unretraction.is_visible; break; } case GCodePreviewVolumeIndex::Shell: { - volume->is_active = print.gcode_preview.shell.is_visible; + volume->is_active = preview_data.shell.is_visible; break; } default: @@ -2264,9 +2265,9 @@ void _3DScene::_update_gcode_volumes_visibility(const Print& print, GLVolumeColl } } -void _3DScene::_generate_legend_texture(const Print& print, const std::vector& tool_colors) +void _3DScene::_generate_legend_texture(const GCodePreviewData& preview_data, const std::vector& tool_colors) { - s_legend_texture.generate_texture(print, tool_colors); + s_legend_texture.generate_texture(preview_data, tool_colors); } void _3DScene::_load_shells(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) diff --git a/xs/src/slic3r/GUI/3DScene.hpp b/xs/src/slic3r/GUI/3DScene.hpp index 7566b284a..bf3515ac5 100644 --- a/xs/src/slic3r/GUI/3DScene.hpp +++ b/xs/src/slic3r/GUI/3DScene.hpp @@ -15,6 +15,7 @@ class Print; class PrintObject; class Model; class ModelObject; +class GCodePreviewData; // A container for interleaved arrays of 3D vertices and normals, // possibly indexed by triangles and / or quads. @@ -423,7 +424,7 @@ class _3DScene LegendTexture(); ~LegendTexture(); - bool generate_texture(const Print& print, const std::vector& tool_colors); + bool generate_texture(const GCodePreviewData& preview_data, const std::vector& tool_colors); unsigned int get_texture_id() const; unsigned int get_texture_width() const; @@ -432,7 +433,7 @@ class _3DScene void reset_texture(); private: - bool _create_texture(const Print& print, const wxBitmap& bitmap); + bool _create_texture(const GCodePreviewData& preview_data, const wxBitmap& bitmap); void _destroy_texture(); }; @@ -441,7 +442,7 @@ class _3DScene public: static void _glew_init(); - static void load_gcode_preview(const Print* print, GLVolumeCollection* volumes, const std::vector& str_tool_colors, bool use_VBOs); + static void load_gcode_preview(const Print* print, const GCodePreviewData* preview_data, GLVolumeCollection* volumes, const std::vector& str_tool_colors, bool use_VBOs); static unsigned int get_legend_texture_id(); static unsigned int get_legend_texture_width(); @@ -469,20 +470,20 @@ public: private: // generates gcode extrusion paths geometry - static void _load_gcode_extrusion_paths(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs); + static void _load_gcode_extrusion_paths(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs); // generates gcode travel paths geometry - static void _load_gcode_travel_paths(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs); - static bool _travel_paths_by_type(const Print& print, GLVolumeCollection& volumes); - static bool _travel_paths_by_feedrate(const Print& print, GLVolumeCollection& volumes); - static bool _travel_paths_by_tool(const Print& print, GLVolumeCollection& volumes, const std::vector& tool_colors); + static void _load_gcode_travel_paths(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, const std::vector& tool_colors, bool use_VBOs); + static bool _travel_paths_by_type(const GCodePreviewData& preview_data, GLVolumeCollection& volumes); + static bool _travel_paths_by_feedrate(const GCodePreviewData& preview_data, GLVolumeCollection& volumes); + static bool _travel_paths_by_tool(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, const std::vector& tool_colors); // generates gcode retractions geometry - static void _load_gcode_retractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); + static void _load_gcode_retractions(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, bool use_VBOs); // generates gcode unretractions geometry - static void _load_gcode_unretractions(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); + static void _load_gcode_unretractions(const GCodePreviewData& preview_data, GLVolumeCollection& volumes, bool use_VBOs); // sets gcode geometry visibility according to user selection - static void _update_gcode_volumes_visibility(const Print& print, GLVolumeCollection& volumes); + static void _update_gcode_volumes_visibility(const GCodePreviewData& preview_data, GLVolumeCollection& volumes); // generates the legend texture in dependence of the current shown view type - static void _generate_legend_texture(const Print& print, const std::vector& tool_colors); + static void _generate_legend_texture(const GCodePreviewData& preview_data, const std::vector& tool_colors); // generates objects and wipe tower geometry static void _load_shells(const Print& print, GLVolumeCollection& volumes, bool use_VBOs); }; diff --git a/xs/xsp/GCode.xsp b/xs/xsp/GCode.xsp index 9e6df85dc..4d62e3f81 100644 --- a/xs/xsp/GCode.xsp +++ b/xs/xsp/GCode.xsp @@ -4,6 +4,7 @@ #include #include "libslic3r/GCode.hpp" #include "libslic3r/GCode/CoolingBuffer.hpp" +#include "libslic3r/GCode/PreviewData.hpp" %} %name{Slic3r::GCode::CoolingBuffer} class CoolingBuffer { @@ -17,10 +18,10 @@ %name{Slic3r::GCode} class GCode { GCode(); ~GCode(); - void do_export(Print *print, const char *path) + void do_export(Print *print, const char *path, GCodePreviewData *preview_data) %code%{ try { - THIS->do_export(print, path); + THIS->do_export(print, path, preview_data); } catch (std::exception& e) { croak(e.what()); } @@ -50,3 +51,25 @@ Ref config() %code{% RETVAL = const_cast(static_cast(static_cast(&THIS->config()))); %}; }; + +%name{Slic3r::GCode::PreviewData} class GCodePreviewData { + GCodePreviewData(); + ~GCodePreviewData(); + void reset(); + void set_type(int type) + %code%{ + if ((0 <= type) && (type < GCodePreviewData::Extrusion::Num_View_Types)) + THIS->extrusion.view_type = (GCodePreviewData::Extrusion::EViewType)type; + %}; + void set_extrusion_flags(int flags) + %code%{ THIS->extrusion.role_flags = (unsigned int)flags; %}; + void set_travel_visible(bool visible) + %code%{ THIS->travel.is_visible = visible; %}; + void set_retractions_visible(bool visible) + %code%{ THIS->retraction.is_visible = visible; %}; + void set_unretractions_visible(bool visible) + %code%{ THIS->unretraction.is_visible = visible; %}; + void set_shells_visible(bool visible) + %code%{ THIS->shell.is_visible = visible; %}; + void set_extrusion_paths_colors(std::vector colors); +}; diff --git a/xs/xsp/GUI_3DScene.xsp b/xs/xsp/GUI_3DScene.xsp index 7520ce6c2..c06c659b1 100644 --- a/xs/xsp/GUI_3DScene.xsp +++ b/xs/xsp/GUI_3DScene.xsp @@ -195,12 +195,13 @@ _load_wipe_tower_toolpaths(print, volumes, tool_colors, use_VBOs) _3DScene::_load_wipe_tower_toolpaths(print, volumes, tool_colors, use_VBOs != 0); void -load_gcode_preview(print, volumes, str_tool_colors, use_VBOs) +load_gcode_preview(print, preview_data, volumes, str_tool_colors, use_VBOs) Print *print; + GCodePreviewData *preview_data; GLVolumeCollection *volumes; std::vector str_tool_colors; int use_VBOs; CODE: - _3DScene::load_gcode_preview(print, volumes, str_tool_colors, use_VBOs != 0); + _3DScene::load_gcode_preview(print, preview_data, volumes, str_tool_colors, use_VBOs != 0); %} diff --git a/xs/xsp/Print.xsp b/xs/xsp/Print.xsp index 5749c20db..cbc04a804 100644 --- a/xs/xsp/Print.xsp +++ b/xs/xsp/Print.xsp @@ -165,15 +165,6 @@ _constant() size_t object_count() %code%{ RETVAL = THIS->objects.size(); %}; - void clear_gcode_preview_data(); - void set_gcode_preview_type(unsigned char type); - void set_gcode_preview_extrusion_flags(unsigned int flags); - void set_gcode_preview_travel_visible(bool visible); - void set_gcode_preview_retractions_visible(bool visible); - void set_gcode_preview_unretractions_visible(bool visible); - void set_gcode_preview_shells_visible(bool visible); - void set_gcode_extrusion_paths_colors(std::vector colors); - PrintRegionPtrs* regions() %code%{ RETVAL = &THIS->regions; %}; Ref get_region(int idx); diff --git a/xs/xsp/my.map b/xs/xsp/my.map index ba4f52f46..64aa15f09 100644 --- a/xs/xsp/my.map +++ b/xs/xsp/my.map @@ -191,6 +191,10 @@ GCode* O_OBJECT_SLIC3R Ref O_OBJECT_SLIC3R_T Clone O_OBJECT_SLIC3R_T +GCodePreviewData* O_OBJECT_SLIC3R +Ref O_OBJECT_SLIC3R_T +Clone O_OBJECT_SLIC3R_T + MotionPlanner* O_OBJECT_SLIC3R Ref O_OBJECT_SLIC3R_T Clone O_OBJECT_SLIC3R_T diff --git a/xs/xsp/typemap.xspt b/xs/xsp/typemap.xspt index d6c74659c..33bcb2fd2 100644 --- a/xs/xsp/typemap.xspt +++ b/xs/xsp/typemap.xspt @@ -155,6 +155,9 @@ %typemap{Ref}{simple}; %typemap{Clone}{simple}; +%typemap{GCodePreviewData*}; +%typemap{Ref}{simple}; +%typemap{Clone}{simple}; %typemap{Points}; %typemap{Pointfs}; From 2caba9262303b87adfc3024b20731f9dd12f2856 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Wed, 14 Feb 2018 20:38:03 +0100 Subject: [PATCH 47/57] GCode/PreviewData.cpp,hpp has been split from GCode/Analyzer.cpp,hpp --- xs/src/libslic3r/GCode/PreviewData.cpp | 402 +++++++++++++++++++++++++ xs/src/libslic3r/GCode/PreviewData.hpp | 204 +++++++++++++ 2 files changed, 606 insertions(+) create mode 100644 xs/src/libslic3r/GCode/PreviewData.cpp create mode 100644 xs/src/libslic3r/GCode/PreviewData.hpp diff --git a/xs/src/libslic3r/GCode/PreviewData.cpp b/xs/src/libslic3r/GCode/PreviewData.cpp new file mode 100644 index 000000000..fc5e4f02b --- /dev/null +++ b/xs/src/libslic3r/GCode/PreviewData.cpp @@ -0,0 +1,402 @@ +#include "Analyzer.hpp" +#include "PreviewData.hpp" + +namespace Slic3r { + +const GCodePreviewData::Color GCodePreviewData::Color::Dummy(0.0f, 0.0f, 0.0f, 0.0f); + +GCodePreviewData::Color::Color() +{ + rgba[0] = 1.0f; + rgba[1] = 1.0f; + rgba[2] = 1.0f; + rgba[3] = 1.0f; +} + +GCodePreviewData::Color::Color(float r, float g, float b, float a) +{ + rgba[0] = r; + rgba[1] = g; + rgba[2] = b; + rgba[3] = a; +} + +std::vector GCodePreviewData::Color::as_bytes() const +{ + std::vector ret; + for (unsigned int i = 0; i < 4; ++i) + { + ret.push_back((unsigned char)(255.0f * rgba[i])); + } + return ret; +} + +GCodePreviewData::Extrusion::Layer::Layer(float z, const ExtrusionPaths& paths) + : z(z) + , paths(paths) +{ +} + +GCodePreviewData::Travel::Polyline::Polyline(EType type, EDirection direction, float feedrate, unsigned int extruder_id, const Polyline3& polyline) + : type(type) + , direction(direction) + , feedrate(feedrate) + , extruder_id(extruder_id) + , polyline(polyline) +{ +} + +const GCodePreviewData::Color GCodePreviewData::Range::Default_Colors[Colors_Count] = +{ + Color(0.043f, 0.173f, 0.478f, 1.0f), + Color(0.075f, 0.349f, 0.522f, 1.0f), + Color(0.110f, 0.533f, 0.569f, 1.0f), + Color(0.016f, 0.839f, 0.059f, 1.0f), + Color(0.667f, 0.949f, 0.000f, 1.0f), + Color(0.988f, 0.975f, 0.012f, 1.0f), + Color(0.961f, 0.808f, 0.039f, 1.0f), + Color(0.890f, 0.533f, 0.125f, 1.0f), + Color(0.820f, 0.408f, 0.188f, 1.0f), + Color(0.761f, 0.322f, 0.235f, 1.0f) +}; + +GCodePreviewData::Range::Range() +{ + reset(); +} + +void GCodePreviewData::Range::reset() +{ + min = FLT_MAX; + max = -FLT_MAX; +} + +bool GCodePreviewData::Range::empty() const +{ + return min == max; +} + +void GCodePreviewData::Range::update_from(float value) +{ + min = std::min(min, value); + max = std::max(max, value); +} + +void GCodePreviewData::Range::set_from(const Range& other) +{ + min = other.min; + max = other.max; +} + +float GCodePreviewData::Range::step_size() const +{ + return (max - min) / (float)Colors_Count; +} + +const GCodePreviewData::Color& GCodePreviewData::Range::get_color_at_max() const +{ + return colors[Colors_Count - 1]; +} + +const GCodePreviewData::Color& GCodePreviewData::Range::get_color_at(float value) const +{ + return empty() ? get_color_at_max() : colors[clamp((unsigned int)0, Colors_Count - 1, (unsigned int)((value - min) / step_size()))]; +} + +GCodePreviewData::LegendItem::LegendItem(const std::string& text, const GCodePreviewData::Color& color) + : text(text) + , color(color) +{ +} + +const GCodePreviewData::Color GCodePreviewData::Extrusion::Default_Extrusion_Role_Colors[Num_Extrusion_Roles] = +{ + Color(0.0f, 0.0f, 0.0f, 1.0f), // erNone + Color(1.0f, 0.0f, 0.0f, 1.0f), // erPerimeter + Color(0.0f, 1.0f, 0.0f, 1.0f), // erExternalPerimeter + Color(0.0f, 0.0f, 1.0f, 1.0f), // erOverhangPerimeter + Color(1.0f, 1.0f, 0.0f, 1.0f), // erInternalInfill + Color(1.0f, 0.0f, 1.0f, 1.0f), // erSolidInfill + Color(0.0f, 1.0f, 1.0f, 1.0f), // erTopSolidInfill + Color(0.5f, 0.5f, 0.5f, 1.0f), // erBridgeInfill + Color(1.0f, 1.0f, 1.0f, 1.0f), // erGapFill + Color(0.5f, 0.0f, 0.0f, 1.0f), // erSkirt + Color(0.0f, 0.5f, 0.0f, 1.0f), // erSupportMaterial + Color(0.0f, 0.0f, 0.5f, 1.0f), // erSupportMaterialInterface + Color(0.7f, 0.89f, 0.67f, 1.0f), // erWipeTower + Color(0.0f, 0.0f, 0.0f, 1.0f) // erMixed +}; + +// todo: merge with Slic3r::ExtrusionRole2String() from GCode.cpp +const std::string GCodePreviewData::Extrusion::Default_Extrusion_Role_Names[Num_Extrusion_Roles] +{ + "None", + "Perimeter", + "External perimeter", + "Overhang perimeter", + "Internal infill", + "Solid infill", + "Top solid infill", + "Bridge infill", + "Gap fill", + "Skirt", + "Support material", + "Support material interface", + "Wipe tower", + "Mixed" +}; + +const GCodePreviewData::Extrusion::EViewType GCodePreviewData::Extrusion::Default_View_Type = GCodePreviewData::Extrusion::FeatureType; + +void GCodePreviewData::Extrusion::set_default() +{ + view_type = Default_View_Type; + + ::memcpy((void*)role_colors, (const void*)Default_Extrusion_Role_Colors, Num_Extrusion_Roles * sizeof(Color)); + ::memcpy((void*)ranges.height.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color)); + ::memcpy((void*)ranges.width.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color)); + ::memcpy((void*)ranges.feedrate.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color)); + + for (unsigned int i = 0; i < Num_Extrusion_Roles; ++i) + { + role_names[i] = Default_Extrusion_Role_Names[i]; + } + + role_flags = 0; + for (unsigned int i = 0; i < Num_Extrusion_Roles; ++i) + { + role_flags |= 1 << i; + } +} + +bool GCodePreviewData::Extrusion::is_role_flag_set(ExtrusionRole role) const +{ + return is_role_flag_set(role_flags, role); +} + +bool GCodePreviewData::Extrusion::is_role_flag_set(unsigned int flags, ExtrusionRole role) +{ + return GCodeAnalyzer::is_valid_extrusion_role(role) && (flags & (1 << (role - erPerimeter))) != 0; +} + +const float GCodePreviewData::Travel::Default_Width = 0.075f; +const float GCodePreviewData::Travel::Default_Height = 0.075f; +const GCodePreviewData::Color GCodePreviewData::Travel::Default_Type_Colors[Num_Types] = +{ + Color(0.0f, 0.0f, 0.75f, 1.0f), // Move + Color(0.0f, 0.75f, 0.0f, 1.0f), // Extrude + Color(0.75f, 0.0f, 0.0f, 1.0f), // Retract +}; + +void GCodePreviewData::Travel::set_default() +{ + width = Default_Width; + height = Default_Height; + ::memcpy((void*)type_colors, (const void*)Default_Type_Colors, Num_Types * sizeof(Color)); + is_visible = false; +} + +const GCodePreviewData::Color GCodePreviewData::Retraction::Default_Color = GCodePreviewData::Color(1.0f, 1.0f, 1.0f, 1.0f); + +GCodePreviewData::Retraction::Position::Position(const Point3& position, float width, float height) + : position(position) + , width(width) + , height(height) +{ +} + +void GCodePreviewData::Retraction::set_default() +{ + color = Default_Color; + is_visible = false; +} + +void GCodePreviewData::Shell::set_default() +{ + is_visible = false; +} + +GCodePreviewData::GCodePreviewData() +{ + set_default(); +} + +void GCodePreviewData::set_default() +{ + extrusion.set_default(); + travel.set_default(); + retraction.set_default(); + unretraction.set_default(); + shell.set_default(); +} + +void GCodePreviewData::reset() +{ + extrusion.layers.clear(); + travel.polylines.clear(); + retraction.positions.clear(); + unretraction.positions.clear(); +} + +const GCodePreviewData::Color& GCodePreviewData::get_extrusion_role_color(ExtrusionRole role) const +{ + return extrusion.role_colors[role]; +} + +const GCodePreviewData::Color& GCodePreviewData::get_extrusion_height_color(float height) const +{ + return extrusion.ranges.height.get_color_at(height); +} + +const GCodePreviewData::Color& GCodePreviewData::get_extrusion_width_color(float width) const +{ + return extrusion.ranges.width.get_color_at(width); +} + +const GCodePreviewData::Color& GCodePreviewData::get_extrusion_feedrate_color(float feedrate) const +{ + return extrusion.ranges.feedrate.get_color_at(feedrate); +} + +void GCodePreviewData::set_extrusion_role_color(const std::string& role_name, float red, float green, float blue, float alpha) +{ + for (unsigned int i = 0; i < Extrusion::Num_Extrusion_Roles; ++i) + { + if (role_name == extrusion.role_names[i]) + { + extrusion.role_colors[i] = Color(red, green, blue, alpha); + break; + } + } +} + +void GCodePreviewData::set_extrusion_paths_colors(const std::vector& colors) +{ + unsigned int size = (unsigned int)colors.size(); + + if (size % 2 != 0) + return; + + for (unsigned int i = 0; i < size; i += 2) + { + const std::string& color_str = colors[i + 1]; + + if (color_str.size() == 6) + { + bool valid = true; + for (int c = 0; c < 6; ++c) + { + if (::isxdigit(color_str[c]) == 0) + { + valid = false; + break; + } + } + + if (valid) + { + unsigned int color; + std::stringstream ss; + ss << std::hex << color_str; + ss >> color; + + float den = 1.0f / 255.0f; + + float r = (float)((color & 0xFF0000) >> 16) * den; + float g = (float)((color & 0x00FF00) >> 8) * den; + float b = (float)(color & 0x0000FF) * den; + + this->set_extrusion_role_color(colors[i], r, g, b, 1.0f); + } + } + } +} + +std::string GCodePreviewData::get_legend_title() const +{ + switch (extrusion.view_type) + { + case Extrusion::FeatureType: + return "Feature type"; + case Extrusion::Height: + return "Height (mm)"; + case Extrusion::Width: + return "Width (mm)"; + case Extrusion::Feedrate: + return "Speed (mm/s)"; + case Extrusion::Tool: + return "Tool"; + } + + return ""; +} + +GCodePreviewData::LegendItemsList GCodePreviewData::get_legend_items(const std::vector& tool_colors) const +{ + struct Helper + { + static void FillListFromRange(LegendItemsList& list, const Range& range, unsigned int decimals, float scale_factor) + { + list.reserve(Range::Colors_Count); + float step = range.step_size(); + for (unsigned int i = 0; i < Range::Colors_Count; ++i) + { + char buf[32]; + sprintf(buf, "%.*f/%.*f", decimals, scale_factor * (range.min + (float)i * step), decimals, scale_factor * (range.min + (float)(i + 1) * step)); + list.emplace_back(buf, range.colors[i]); + } + } + }; + + LegendItemsList items; + + switch (extrusion.view_type) + { + case Extrusion::FeatureType: + { + items.reserve(erMixed - erPerimeter + 1); + for (unsigned int i = (unsigned int)erPerimeter; i < (unsigned int)erMixed; ++i) + { + items.emplace_back(extrusion.role_names[i], extrusion.role_colors[i]); + } + + break; + } + case Extrusion::Height: + { + Helper::FillListFromRange(items, extrusion.ranges.height, 3, 1.0f); + break; + } + case Extrusion::Width: + { + Helper::FillListFromRange(items, extrusion.ranges.width, 3, 1.0f); + break; + } + case Extrusion::Feedrate: + { + Helper::FillListFromRange(items, extrusion.ranges.feedrate, 0, 1.0f); + break; + } + case Extrusion::Tool: + { + unsigned int tools_colors_count = tool_colors.size() / 4; + items.reserve(tools_colors_count); + for (unsigned int i = 0; i < tools_colors_count; ++i) + { + char buf[32]; + sprintf(buf, "Extruder %d", i + 1); + + GCodePreviewData::Color color; + ::memcpy((void*)color.rgba, (const void*)(tool_colors.data() + i * 4), 4 * sizeof(float)); + + items.emplace_back(buf, color); + } + + break; + } + } + + return items; +} + +} // namespace Slic3r diff --git a/xs/src/libslic3r/GCode/PreviewData.hpp b/xs/src/libslic3r/GCode/PreviewData.hpp new file mode 100644 index 000000000..59d87a360 --- /dev/null +++ b/xs/src/libslic3r/GCode/PreviewData.hpp @@ -0,0 +1,204 @@ +#ifndef slic3r_GCode_PreviewData_hpp_ +#define slic3r_GCode_PreviewData_hpp_ + +#include "../libslic3r.h" +#include "../ExtrusionEntity.hpp" + +#include "Point.hpp" + +namespace Slic3r { + +class GCodePreviewData +{ +public: + struct Color + { + float rgba[4]; + + Color(); + Color(float r, float g, float b, float a); + + std::vector as_bytes() const; + + static const Color Dummy; + }; + + struct Range + { + static const unsigned int Colors_Count = 10; + static const Color Default_Colors[Colors_Count]; + + Color colors[Colors_Count]; + float min; + float max; + + Range(); + + void reset(); + bool empty() const; + void update_from(float value); + void set_from(const Range& other); + float step_size() const; + + const Color& get_color_at(float value) const; + const Color& get_color_at_max() const; + }; + + struct LegendItem + { + std::string text; + Color color; + + LegendItem(const std::string& text, const Color& color); + }; + + typedef std::vector LegendItemsList; + + struct Extrusion + { + enum EViewType : unsigned char + { + FeatureType, + Height, + Width, + Feedrate, + Tool, + Num_View_Types + }; + + static const unsigned int Num_Extrusion_Roles = (unsigned int)erMixed + 1; + static const Color Default_Extrusion_Role_Colors[Num_Extrusion_Roles]; + static const std::string Default_Extrusion_Role_Names[Num_Extrusion_Roles]; + static const EViewType Default_View_Type; + + struct Ranges + { + Range height; + Range width; + Range feedrate; + }; + + struct Layer + { + float z; + ExtrusionPaths paths; + + Layer(float z, const ExtrusionPaths& paths); + }; + + typedef std::vector LayersList; + + EViewType view_type; + Color role_colors[Num_Extrusion_Roles]; + std::string role_names[Num_Extrusion_Roles]; + Ranges ranges; + LayersList layers; + unsigned int role_flags; + + void set_default(); + bool is_role_flag_set(ExtrusionRole role) const; + + static bool is_role_flag_set(unsigned int flags, ExtrusionRole role); + }; + + struct Travel + { + enum EType : unsigned char + { + Move, + Extrude, + Retract, + Num_Types + }; + + static const float Default_Width; + static const float Default_Height; + static const Color Default_Type_Colors[Num_Types]; + + struct Polyline + { + enum EDirection + { + Vertical, + Generic, + Num_Directions + }; + + EType type; + EDirection direction; + float feedrate; + unsigned int extruder_id; + Polyline3 polyline; + + Polyline(EType type, EDirection direction, float feedrate, unsigned int extruder_id, const Polyline3& polyline); + }; + + typedef std::vector PolylinesList; + + PolylinesList polylines; + float width; + float height; + Color type_colors[Num_Types]; + bool is_visible; + + void set_default(); + }; + + struct Retraction + { + static const Color Default_Color; + + struct Position + { + Point3 position; + float width; + float height; + + Position(const Point3& position, float width, float height); + }; + + typedef std::vector PositionsList; + + PositionsList positions; + Color color; + bool is_visible; + + void set_default(); + }; + + struct Shell + { + bool is_visible; + + void set_default(); + }; + + Extrusion extrusion; + Travel travel; + Retraction retraction; + Retraction unretraction; + Shell shell; + + GCodePreviewData(); + + void set_default(); + void reset(); + + const Color& get_extrusion_role_color(ExtrusionRole role) const; + const Color& get_extrusion_height_color(float height) const; + const Color& get_extrusion_width_color(float width) const; + const Color& get_extrusion_feedrate_color(float feedrate) const; + + void set_extrusion_role_color(const std::string& role_name, float red, float green, float blue, float alpha); + void set_extrusion_paths_colors(const std::vector& colors); + + std::string get_legend_title() const; + LegendItemsList get_legend_items(const std::vector& tool_colors) const; +}; + +GCodePreviewData::Color operator + (const GCodePreviewData::Color& c1, const GCodePreviewData::Color& c2); +GCodePreviewData::Color operator * (float f, const GCodePreviewData::Color& color); + +} // namespace Slic3r + +#endif /* slic3r_GCode_PreviewData_hpp_ */ From ff3ae40aeb417d132ae8fd57fe2e58a08930edf6 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Wed, 14 Feb 2018 21:57:46 +0100 Subject: [PATCH 48/57] Fixed compilation issues caused by the previous commits --- lib/Slic3r/Print.pm | 7 ++++++- xs/src/libslic3r/GCode/PreviewData.cpp | 6 ++++++ xs/src/libslic3r/GCode/PreviewData.hpp | 1 + xs/xsp/GCode.xsp | 12 +++++++++++- 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/lib/Slic3r/Print.pm b/lib/Slic3r/Print.pm index 4d112536a..fa3d4a101 100644 --- a/lib/Slic3r/Print.pm +++ b/lib/Slic3r/Print.pm @@ -81,7 +81,12 @@ sub export_gcode { $self->status_cb->(90, "Exporting G-code" . ($output_file ? " to $output_file" : "")); # The following line may die for multiple reasons. - Slic3r::GCode->new->do_export($self, $output_file, $params{gcode_preview_data}); + my $gcode = Slic3r::GCode->new; + if (defined $params{gcode_preview_data}) { + $gcode->do_export_w_preview($self, $output_file, $params{gcode_preview_data}); + } else { + $gcode->do_export($self, $output_file); + } # run post-processing scripts if (@{$self->config->post_process}) { diff --git a/xs/src/libslic3r/GCode/PreviewData.cpp b/xs/src/libslic3r/GCode/PreviewData.cpp index fc5e4f02b..5a23d332d 100644 --- a/xs/src/libslic3r/GCode/PreviewData.cpp +++ b/xs/src/libslic3r/GCode/PreviewData.cpp @@ -1,5 +1,6 @@ #include "Analyzer.hpp" #include "PreviewData.hpp" +#include namespace Slic3r { @@ -238,6 +239,11 @@ void GCodePreviewData::reset() unretraction.positions.clear(); } +bool GCodePreviewData::empty() const +{ + return extrusion.layers.empty() && travel.polylines.empty() && retraction.positions.empty() && unretraction.positions.empty(); +} + const GCodePreviewData::Color& GCodePreviewData::get_extrusion_role_color(ExtrusionRole role) const { return extrusion.role_colors[role]; diff --git a/xs/src/libslic3r/GCode/PreviewData.hpp b/xs/src/libslic3r/GCode/PreviewData.hpp index 59d87a360..9fb2dc464 100644 --- a/xs/src/libslic3r/GCode/PreviewData.hpp +++ b/xs/src/libslic3r/GCode/PreviewData.hpp @@ -183,6 +183,7 @@ public: void set_default(); void reset(); + bool empty() const; const Color& get_extrusion_role_color(ExtrusionRole role) const; const Color& get_extrusion_height_color(float height) const; diff --git a/xs/xsp/GCode.xsp b/xs/xsp/GCode.xsp index 4d62e3f81..b4cb7c0e9 100644 --- a/xs/xsp/GCode.xsp +++ b/xs/xsp/GCode.xsp @@ -18,7 +18,15 @@ %name{Slic3r::GCode} class GCode { GCode(); ~GCode(); - void do_export(Print *print, const char *path, GCodePreviewData *preview_data) + void do_export(Print *print, const char *path) + %code%{ + try { + THIS->do_export(print, path); + } catch (std::exception& e) { + croak(e.what()); + } + %}; + void do_export_w_preview(Print *print, const char *path, GCodePreviewData *preview_data) %code%{ try { THIS->do_export(print, path, preview_data); @@ -56,11 +64,13 @@ GCodePreviewData(); ~GCodePreviewData(); void reset(); + bool empty() const; void set_type(int type) %code%{ if ((0 <= type) && (type < GCodePreviewData::Extrusion::Num_View_Types)) THIS->extrusion.view_type = (GCodePreviewData::Extrusion::EViewType)type; %}; + int type() %code%{ RETVAL = (int)THIS->extrusion.view_type; %}; void set_extrusion_flags(int flags) %code%{ THIS->extrusion.role_flags = (unsigned int)flags; %}; void set_travel_visible(bool visible) From 7f51b07f696fda95f1551b343693ca321959c186 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Wed, 14 Feb 2018 21:59:33 +0100 Subject: [PATCH 49/57] First take on restoring the old 3D path preview before the G-code preview is ready --- lib/Slic3r/GUI/Plater/3DPreview.pm | 71 +++++++++++++++++------------- 1 file changed, 40 insertions(+), 31 deletions(-) diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index 10232b31d..01321ccc5 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -17,6 +17,8 @@ sub new { my $self = $class->SUPER::new($parent, -1, wxDefaultPosition); $self->{config} = $config; $self->{number_extruders} = 1; + # Show by feature type by default. + $self->{preferred_color_mode} = 0; $self->auto_zoom(1); # init GUI elements @@ -60,7 +62,7 @@ sub new { my $label_view_type = $self->{label_view_type} = Wx::StaticText->new($self, -1, "View"); - my $choice_view_type = Wx::Choice->new($self, -1); + my $choice_view_type = $self->{choice_view_type} = Wx::Choice->new($self, -1); $choice_view_type->Append("Feature type"); $choice_view_type->Append("Height"); $choice_view_type->Append("Width"); @@ -192,6 +194,7 @@ sub new { }); EVT_CHOICE($self, $choice_view_type, sub { my $selection = $choice_view_type->GetCurrentSelection(); + $self->{preferred_color_mode} = $selection; $self->gcode_preview_data->set_type($selection); $self->auto_zoom(0); $self->reload_print; @@ -240,17 +243,17 @@ sub new { # sets colors for gcode preview extrusion roles my @extrusion_roles_colors = ( - 'Perimeter' => 'FF0000', - 'External perimeter' => '00FF00', + 'Perimeter' => 'FFA500', + 'External perimeter' => 'FFFF66', 'Overhang perimeter' => '0000FF', - 'Internal infill' => 'FFFF00', - 'Solid infill' => 'FF00FF', - 'Top solid infill' => '00FFFF', - 'Bridge infill' => '7F7F7F', + 'Internal infill' => 'FF0000', + 'Solid infill' => 'CD00CD', + 'Top solid infill' => 'FF3333', + 'Bridge infill' => '9999FF', 'Gap fill' => 'FFFFFF', 'Skirt' => '7F0000', - 'Support material' => '007F00', - 'Support material interface' => '00007F', + 'Support material' => '00FF00', + 'Support material interface' => '008000', 'Wipe tower' => 'B3E3AB', ); $self->gcode_preview_data->set_extrusion_paths_colors(\@extrusion_roles_colors); @@ -345,31 +348,32 @@ sub load_print { # Collect colors per extruder. my @colors = (); - my @extruder_colors = @{$self->{config}->extruder_colour}; - my @filament_colors = @{$self->{config}->filament_colour}; - for (my $i = 0; $i <= $#extruder_colors; $i += 1) { - my $color = $extruder_colors[$i]; - $color = $filament_colors[$i] if (! defined($color) || $color !~ m/^#[[:xdigit:]]{6}/); - $color = '#FFFFFF' if (! defined($color) || $color !~ m/^#[[:xdigit:]]{6}/); - push @colors, $color; + if (! $self->gcode_preview_data->empty() || $self->gcode_preview_data->type == 4) { + my @extruder_colors = @{$self->{config}->extruder_colour}; + my @filament_colors = @{$self->{config}->filament_colour}; + for (my $i = 0; $i <= $#extruder_colors; $i += 1) { + my $color = $extruder_colors[$i]; + $color = $filament_colors[$i] if (! defined($color) || $color !~ m/^#[[:xdigit:]]{6}/); + $color = '#FFFFFF' if (! defined($color) || $color !~ m/^#[[:xdigit:]]{6}/); + push @colors, $color; + } } if ($self->IsShown) { - $self->canvas->load_gcode_preview($self->print, $self->gcode_preview_data, \@colors); - -# # load skirt and brim -# $self->canvas->load_print_toolpaths($self->print, \@colors); -# $self->canvas->load_wipe_tower_toolpaths($self->print, \@colors); -# -# foreach my $object (@{$self->print->objects}) { -# $self->canvas->load_print_object_toolpaths($object, \@colors); -# -# # Show the objects in very transparent color. -# #my @volume_ids = $self->canvas->load_object($object->model_object); -# #$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids; -# } - if ($self->auto_zoom) - { + if ($self->gcode_preview_data->empty) { + # load skirt and brim + $self->canvas->load_print_toolpaths($self->print, \@colors); + $self->canvas->load_wipe_tower_toolpaths($self->print, \@colors); + foreach my $object (@{$self->print->objects}) { + $self->canvas->load_print_object_toolpaths($object, \@colors); + # Show the objects in very transparent color. + #my @volume_ids = $self->canvas->load_object($object->model_object); + #$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids; + } + } else { + $self->canvas->load_gcode_preview($self->print, $self->gcode_preview_data, \@colors); + } + if ($self->auto_zoom) { $self->canvas->zoom_to_volumes; } $self->_loaded(1); @@ -424,6 +428,11 @@ sub set_number_extruders { my ($self, $number_extruders) = @_; if ($self->{number_extruders} != $number_extruders) { $self->{number_extruders} = $number_extruders; + $self->{preferred_color_mode} = ($number_extruders > 1) ? + 4 # color by a tool number + : 0; # color by a feature type + $self->{choice_view_type}->SetSelection($self->{preferred_color_mode}); + $self->gcode_preview_data->set_type($self->{preferred_color_mode}); } } From b5bdb4626864277eaa7e68e0b98ea03ee73694b9 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Wed, 14 Feb 2018 22:25:09 +0100 Subject: [PATCH 50/57] Added logging of the G-code export. --- xs/src/libslic3r/GCode.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/xs/src/libslic3r/GCode.cpp b/xs/src/libslic3r/GCode.cpp index 8c14b4adb..39f1a4102 100644 --- a/xs/src/libslic3r/GCode.cpp +++ b/xs/src/libslic3r/GCode.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -352,6 +353,8 @@ void GCode::do_export(Print *print, const char *path, GCodePreviewData *preview_ { PROFILE_CLEAR(); + BOOST_LOG_TRIVIAL(info) << "Exporting G-code..."; + // Remove the old g-code if it exists. boost::nowide::remove(path); @@ -389,6 +392,8 @@ void GCode::do_export(Print *print, const char *path, GCodePreviewData *preview_ std::string("Failed to rename the output G-code file from ") + path_tmp + " to " + path + '\n' + "Is " + path_tmp + " locked?" + '\n'); + BOOST_LOG_TRIVIAL(info) << "Exporting G-code finished"; + // Write the profiler measurements to file PROFILE_UPDATE(); PROFILE_OUTPUT(debug_out_path("gcode-export-profile.txt").c_str()); From f9cdda7bfd14c6eb972b6c89079d983f4c742964 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Thu, 15 Feb 2018 14:37:53 +0100 Subject: [PATCH 51/57] Delayed loading of the opengl texture for the G-code preview legend, as the opengl context may not be ready on some platforms (Linux) at the time the window gets its focus for the first time. Changed the G-code preview invalidation to trigger when the print gets invalidated. At that time the 3D path preview switches to the old preview, if there is anything valid left. --- lib/Slic3r/GUI/3DScene.pm | 3 +- lib/Slic3r/GUI/Plater.pm | 5 +- xs/src/libslic3r/GCode.cpp | 2 +- xs/src/slic3r/GUI/3DScene.cpp | 110 ++++++++++++++-------------------- xs/src/slic3r/GUI/3DScene.hpp | 20 ++++--- xs/xsp/GUI_3DScene.xsp | 7 +++ 6 files changed, 68 insertions(+), 79 deletions(-) diff --git a/lib/Slic3r/GUI/3DScene.pm b/lib/Slic3r/GUI/3DScene.pm index 03055a582..4ca5b4188 100644 --- a/lib/Slic3r/GUI/3DScene.pm +++ b/lib/Slic3r/GUI/3DScene.pm @@ -1602,7 +1602,8 @@ sub draw_legend { if ($self->_legend_enabled) { - my $tex_id = Slic3r::GUI::_3DScene::get_legend_texture_id; + # If the legend texture has not been loaded into the GPU, do it now. + my $tex_id = Slic3r::GUI::_3DScene::finalize_legend_texture; if ($tex_id > 0) { my $tex_w = Slic3r::GUI::_3DScene::get_legend_texture_width; diff --git a/lib/Slic3r/GUI/Plater.pm b/lib/Slic3r/GUI/Plater.pm index 17a39184d..6eaa231a6 100644 --- a/lib/Slic3r/GUI/Plater.pm +++ b/lib/Slic3r/GUI/Plater.pm @@ -786,7 +786,6 @@ sub remove { splice @{$self->{objects}}, $obj_idx, 1; $self->{model}->delete_object($obj_idx); $self->{print}->delete_object($obj_idx); - $self->{gcode_preview_data}->reset; $self->{list}->DeleteItem($obj_idx); $self->object_list_changed; @@ -807,7 +806,6 @@ sub reset { @{$self->{objects}} = (); $self->{model}->clear_objects; $self->{print}->clear_objects; - $self->{gcode_preview_data}->reset; $self->{list}->DeleteAllItems; $self->object_list_changed; @@ -1161,6 +1159,7 @@ sub async_apply_config { # Reset preview canvases. If the print has been invalidated, the preview canvases will be cleared. # Otherwise they will be just refreshed. if ($invalidated) { + $self->{gcode_preview_data}->reset; $self->{toolpaths2D}->reload_print if $self->{toolpaths2D}; $self->{preview3D}->reload_print if $self->{preview3D}; } @@ -1267,8 +1266,6 @@ sub reslice { $self->stop_background_process; # Rather perform one additional unnecessary update of the print object instead of skipping a pending async update. $self->async_apply_config; - # Reset gcode data - $self->{gcode_preview_data}->reset; $self->statusbar->SetCancelCallback(sub { $self->stop_background_process; $self->statusbar->SetStatusText("Slicing cancelled"); diff --git a/xs/src/libslic3r/GCode.cpp b/xs/src/libslic3r/GCode.cpp index 39f1a4102..538f9fefa 100644 --- a/xs/src/libslic3r/GCode.cpp +++ b/xs/src/libslic3r/GCode.cpp @@ -776,7 +776,7 @@ void GCode::_do_export(Print &print, FILE *file, GCodePreviewData *preview_data) _writeln(file, this->placeholder_parser_process("end_filament_gcode", print.config.end_filament_gcode.get_at(m_writer.extruder()->id()), m_writer.extruder()->id())); } else { for (const std::string &end_gcode : print.config.end_filament_gcode.values) - _writeln(file, this->placeholder_parser_process("end_gcode", end_gcode, (unsigned int)(&end_gcode - &print.config.end_filament_gcode.values.front()))); + _writeln(file, this->placeholder_parser_process("end_filament_gcode", end_gcode, (unsigned int)(&end_gcode - &print.config.end_filament_gcode.values.front()))); } _writeln(file, this->placeholder_parser_process("end_gcode", print.config.end_gcode, m_writer.extruder()->id())); _write(file, m_writer.update_progress(m_layer_count, m_layer_count, true)); // 100% diff --git a/xs/src/slic3r/GUI/3DScene.cpp b/xs/src/slic3r/GUI/3DScene.cpp index 616d43496..3deadd105 100644 --- a/xs/src/slic3r/GUI/3DScene.cpp +++ b/xs/src/slic3r/GUI/3DScene.cpp @@ -1117,21 +1117,12 @@ const unsigned char _3DScene::LegendTexture::Squares_Border_Color[3] = { 64, 64, const unsigned char _3DScene::LegendTexture::Background_Color[3] = { 9, 91, 134 }; const unsigned char _3DScene::LegendTexture::Opacity = 255; -_3DScene::LegendTexture::LegendTexture() - : m_tex_id(0) - , m_tex_width(0) - , m_tex_height(0) +// Generate a texture data, but don't load it into the GPU yet, as the GPU context may not yet be valid. +bool _3DScene::LegendTexture::generate(const GCodePreviewData& preview_data, const std::vector& tool_colors) { -} - -_3DScene::LegendTexture::~LegendTexture() -{ - _destroy_texture(); -} - -bool _3DScene::LegendTexture::generate_texture(const GCodePreviewData& preview_data, const std::vector& tool_colors) -{ - _destroy_texture(); + // Mark the texture as released, but don't release the texture from the GPU yet. + m_tex_width = m_tex_height = 0; + m_data.clear(); // collects items to render const std::string& title = preview_data.get_legend_title(); @@ -1241,64 +1232,45 @@ bool _3DScene::LegendTexture::generate_texture(const GCodePreviewData& preview_d memDC.SelectObject(wxNullBitmap); - return _create_texture(preview_data, bitmap); -} - -unsigned int _3DScene::LegendTexture::get_texture_id() const -{ - return m_tex_id; -} - -unsigned int _3DScene::LegendTexture::get_texture_width() const -{ - return m_tex_width; -} - -unsigned int _3DScene::LegendTexture::get_texture_height() const -{ - return m_tex_height; -} - -void _3DScene::LegendTexture::reset_texture() -{ - _destroy_texture(); -} - -bool _3DScene::LegendTexture::_create_texture(const GCodePreviewData& preview_data, const wxBitmap& bitmap) -{ - if ((m_tex_width == 0) || (m_tex_height == 0)) - return false; - - wxImage image = bitmap.ConvertToImage(); - image.SetMaskColour(Background_Color[0], Background_Color[1], Background_Color[2]); - - // prepare buffer - std::vector buffer(4 * m_tex_width * m_tex_height, 0); - for (unsigned int h = 0; h < m_tex_height; ++h) + // Convert the bitmap into a linear data ready to be loaded into the GPU. { - unsigned int hh = h * m_tex_width; - for (unsigned int w = 0; w < m_tex_width; ++w) + wxImage image = bitmap.ConvertToImage(); + image.SetMaskColour(Background_Color[0], Background_Color[1], Background_Color[2]); + + // prepare buffer + m_data.assign(4 * m_tex_width * m_tex_height, 0); + for (unsigned int h = 0; h < m_tex_height; ++h) { - unsigned char* px_ptr = buffer.data() + 4 * (hh + w); - *px_ptr++ = image.GetRed(w, h); - *px_ptr++ = image.GetGreen(w, h); - *px_ptr++ = image.GetBlue(w, h); - *px_ptr++ = image.IsTransparent(w, h) ? 0 : Opacity; + unsigned int hh = h * m_tex_width; + unsigned char* px_ptr = m_data.data() + 4 * hh; + for (unsigned int w = 0; w < m_tex_width; ++w) + { + *px_ptr++ = image.GetRed(w, h); + *px_ptr++ = image.GetGreen(w, h); + *px_ptr++ = image.GetBlue(w, h); + *px_ptr++ = image.IsTransparent(w, h) ? 0 : Opacity; + } } } - - // sends buffer to gpu - ::glGenTextures(1, &m_tex_id); - ::glBindTexture(GL_TEXTURE_2D, m_tex_id); - ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, (GLsizei)m_tex_width, (GLsizei)m_tex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (const GLvoid*)buffer.data()); - ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1); - ::glBindTexture(GL_TEXTURE_2D, 0); - return true; } +unsigned int _3DScene::LegendTexture::finalize() +{ + if (! m_data.empty()) { + // sends buffer to gpu + ::glGenTextures(1, &m_tex_id); + ::glBindTexture(GL_TEXTURE_2D, m_tex_id); + ::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, (GLsizei)m_tex_width, (GLsizei)m_tex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (const GLvoid*)m_data.data()); + ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + ::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1); + ::glBindTexture(GL_TEXTURE_2D, 0); + m_data.clear(); + } + return (m_tex_width > 0 && m_tex_height > 0) ? m_tex_id : 0; +} + void _3DScene::LegendTexture::_destroy_texture() { if (m_tex_id > 0) @@ -1308,6 +1280,7 @@ void _3DScene::LegendTexture::_destroy_texture() m_tex_height = 0; m_tex_width = 0; } + m_data.clear(); } void _3DScene::_glew_init() @@ -2267,7 +2240,12 @@ void _3DScene::_update_gcode_volumes_visibility(const GCodePreviewData& preview_ void _3DScene::_generate_legend_texture(const GCodePreviewData& preview_data, const std::vector& tool_colors) { - s_legend_texture.generate_texture(preview_data, tool_colors); + s_legend_texture.generate(preview_data, tool_colors); +} + +unsigned int _3DScene::finalize_legend_texture() +{ + return s_legend_texture.finalize(); } void _3DScene::_load_shells(const Print& print, GLVolumeCollection& volumes, bool use_VBOs) diff --git a/xs/src/slic3r/GUI/3DScene.hpp b/xs/src/slic3r/GUI/3DScene.hpp index bf3515ac5..9cbcb6ebc 100644 --- a/xs/src/slic3r/GUI/3DScene.hpp +++ b/xs/src/slic3r/GUI/3DScene.hpp @@ -421,20 +421,25 @@ class _3DScene unsigned int m_tex_height; public: - LegendTexture(); - ~LegendTexture(); + LegendTexture() : m_tex_id(0), m_tex_width(0), m_tex_height(0) {} + ~LegendTexture() { _destroy_texture(); } - bool generate_texture(const GCodePreviewData& preview_data, const std::vector& tool_colors); + // Generate a texture data, but don't load it into the GPU yet, as the glcontext may not be valid yet. + bool generate(const GCodePreviewData& preview_data, const std::vector& tool_colors); + // If not loaded, load the texture data into the GPU. Return a texture ID or 0 if the texture has zero size. + unsigned int finalize(); - unsigned int get_texture_id() const; - unsigned int get_texture_width() const; - unsigned int get_texture_height() const; + unsigned int get_texture_id() const { return m_tex_id; } + unsigned int get_texture_width() const { return m_tex_width; } + unsigned int get_texture_height() const { return m_tex_height; } - void reset_texture(); + void reset_texture() { _destroy_texture(); } private: bool _create_texture(const GCodePreviewData& preview_data, const wxBitmap& bitmap); void _destroy_texture(); + // generate() fills in m_data with the pixels, while finalize() moves the data to the GPU before rendering. + std::vector m_data; }; static LegendTexture s_legend_texture; @@ -449,6 +454,7 @@ public: static unsigned int get_legend_texture_height(); static void reset_legend_texture(); + static unsigned int finalize_legend_texture(); static void _load_print_toolpaths( const Print *print, diff --git a/xs/xsp/GUI_3DScene.xsp b/xs/xsp/GUI_3DScene.xsp index c06c659b1..961c837d9 100644 --- a/xs/xsp/GUI_3DScene.xsp +++ b/xs/xsp/GUI_3DScene.xsp @@ -141,6 +141,13 @@ _glew_init() CODE: _3DScene::_glew_init(); +unsigned int +finalize_legend_texture() + CODE: + RETVAL = _3DScene::finalize_legend_texture(); + OUTPUT: + RETVAL + unsigned int get_legend_texture_id() CODE: From 4a35fd655cbc6edb9d6c8f1787b2c15988530842 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Thu, 15 Feb 2018 16:30:35 +0100 Subject: [PATCH 52/57] Disable some of the G-code preview controls for the old 3D path preview, re-enable them when the G-code preview is ready. Resurrected the old logic to automatically switch to the tool preview for a multi-material print, and to switch automatically to the feature preview for a single material print. --- lib/Slic3r/GUI/Plater/3DPreview.pm | 43 +++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/lib/Slic3r/GUI/Plater/3DPreview.pm b/lib/Slic3r/GUI/Plater/3DPreview.pm index 01321ccc5..554b9e35a 100644 --- a/lib/Slic3r/GUI/Plater/3DPreview.pm +++ b/lib/Slic3r/GUI/Plater/3DPreview.pm @@ -18,7 +18,7 @@ sub new { $self->{config} = $config; $self->{number_extruders} = 1; # Show by feature type by default. - $self->{preferred_color_mode} = 0; + $self->{preferred_color_mode} = 'feature'; $self->auto_zoom(1); # init GUI elements @@ -72,7 +72,7 @@ sub new { my $label_show_features = $self->{label_show_features} = Wx::StaticText->new($self, -1, "Show"); - my $combochecklist_features = Wx::ComboCtrl->new(); + my $combochecklist_features = $self->{combochecklist_features} = Wx::ComboCtrl->new(); $combochecklist_features->Create($self, -1, "Feature types", wxDefaultPosition, [200, -1], wxCB_READONLY); #FIXME If the following line is removed, the combo box popup list will not react to mouse clicks. # On the other side, with this line the combo box popup cannot be closed by clicking on the combo button on Windows 10. @@ -82,10 +82,10 @@ sub new { my $feature_items = "Perimeter|External perimeter|Overhang perimeter|Internal infill|Solid infill|Top solid infill|Bridge infill|Gap fill|Skirt|Support material|Support material interface|Wipe tower"; Slic3r::GUI::create_combochecklist($combochecklist_features, $feature_text, $feature_items, 1); - my $checkbox_travel = Wx::CheckBox->new($self, -1, "Travel"); - my $checkbox_retractions = Wx::CheckBox->new($self, -1, "Retractions"); - my $checkbox_unretractions = Wx::CheckBox->new($self, -1, "Unretractions"); - my $checkbox_shells = Wx::CheckBox->new($self, -1, "Shells"); + my $checkbox_travel = $self->{checkbox_travel} = Wx::CheckBox->new($self, -1, "Travel"); + my $checkbox_retractions = $self->{checkbox_retractions} = Wx::CheckBox->new($self, -1, "Retractions"); + my $checkbox_unretractions = $self->{checkbox_unretractions} = Wx::CheckBox->new($self, -1, "Unretractions"); + my $checkbox_shells = $self->{checkbox_shells} = Wx::CheckBox->new($self, -1, "Shells"); my $hsizer = Wx::BoxSizer->new(wxHORIZONTAL); my $vsizer = Wx::BoxSizer->new(wxVERTICAL); @@ -194,7 +194,7 @@ sub new { }); EVT_CHOICE($self, $choice_view_type, sub { my $selection = $choice_view_type->GetCurrentSelection(); - $self->{preferred_color_mode} = $selection; + $self->{preferred_color_mode} = ($selection == 4) ? 'tool' : 'feature'; $self->gcode_preview_data->set_type($selection); $self->auto_zoom(0); $self->reload_print; @@ -258,6 +258,7 @@ sub new { ); $self->gcode_preview_data->set_extrusion_paths_colors(\@extrusion_roles_colors); + $self->show_hide_ui_elements('none'); $self->reload_print; return $self; @@ -346,6 +347,17 @@ sub load_print { $self->slider_high->Show; $self->Layout; + if ($self->{preferred_color_mode} eq 'tool_or_feature') { + # It is left to Slic3r to decide whether the print shall be colored by the tool or by the feature. + # Color by feature if it is a single extruder print. + my $extruders = $self->{print}->extruders; + my $type = (scalar(@{$extruders}) > 1) ? 4 : 0; + $self->gcode_preview_data->set_type($type); + $self->{choice_view_type}->SetSelection($type); + # If the ->SetSelection changed the following line, revert it to "decide yourself". + $self->{preferred_color_mode} = 'tool_or_feature'; + } + # Collect colors per extruder. my @colors = (); if (! $self->gcode_preview_data->empty() || $self->gcode_preview_data->type == 4) { @@ -370,8 +382,10 @@ sub load_print { #my @volume_ids = $self->canvas->load_object($object->model_object); #$self->canvas->volumes->[$_]->color->[3] = 0.2 for @volume_ids; } + $self->show_hide_ui_elements('simple'); } else { $self->canvas->load_gcode_preview($self->print, $self->gcode_preview_data, \@colors); + $self->show_hide_ui_elements('full'); } if ($self->auto_zoom) { $self->canvas->zoom_to_volumes; @@ -428,14 +442,23 @@ sub set_number_extruders { my ($self, $number_extruders) = @_; if ($self->{number_extruders} != $number_extruders) { $self->{number_extruders} = $number_extruders; - $self->{preferred_color_mode} = ($number_extruders > 1) ? + my $type = ($number_extruders > 1) ? 4 # color by a tool number : 0; # color by a feature type - $self->{choice_view_type}->SetSelection($self->{preferred_color_mode}); - $self->gcode_preview_data->set_type($self->{preferred_color_mode}); + $self->{choice_view_type}->SetSelection($type); + $self->gcode_preview_data->set_type($type); + $self->{preferred_color_mode} = ($type == 4) ? 'tool_or_feature' : 'feature'; } } +sub show_hide_ui_elements { + my ($self, $what) = @_; + my $method = ($what eq 'full') ? 'Enable' : 'Disable'; + $self->{$_}->$method for qw(label_show_features combochecklist_features checkbox_travel checkbox_retractions checkbox_unretractions checkbox_shells); + $method = ($what eq 'none') ? 'Disable' : 'Enable'; + $self->{$_}->$method for qw(label_view_type choice_view_type); +} + # Called by the Platter wxNotebook when this page is activated. sub OnActivate { # my ($self) = @_; From 1fa3ffbf839c61e216ce5026a413b8b5ecf5e106 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Thu, 15 Feb 2018 16:41:26 +0100 Subject: [PATCH 53/57] Fixed a bug, when a color selection popped up when clicking on the print or printer combo box icon. --- lib/Slic3r/GUI/Plater.pm | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/Slic3r/GUI/Plater.pm b/lib/Slic3r/GUI/Plater.pm index 6eaa231a6..2b59068ee 100644 --- a/lib/Slic3r/GUI/Plater.pm +++ b/lib/Slic3r/GUI/Plater.pm @@ -375,7 +375,9 @@ sub new { my $text = Wx::StaticText->new($self, -1, "$group_labels{$group}:", wxDefaultPosition, wxDefaultSize, wxALIGN_RIGHT); $text->SetFont($Slic3r::GUI::small_font); my $choice = Wx::BitmapComboBox->new($self, -1, "", wxDefaultPosition, wxDefaultSize, [], wxCB_READONLY); - EVT_LEFT_DOWN($choice, sub { $self->filament_color_box_lmouse_down(0, @_); } ); + if ($group eq 'filament') { + EVT_LEFT_DOWN($choice, sub { $self->filament_color_box_lmouse_down(0, @_); } ); + } $self->{preset_choosers}{$group} = [$choice]; # setup the listener EVT_COMBOBOX($choice, $choice, sub { From 39100068c126c4dc0e452b5ece666e91986c6bf3 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Thu, 15 Feb 2018 18:16:19 +0100 Subject: [PATCH 54/57] Removed the Perl Tab & BedDialog as they were replaced by their C++ counterparts. --- lib/Slic3r/GUI/BedShapeDialog.pm | 316 ----- lib/Slic3r/GUI/Tab.pm | 1837 ------------------------------ xs/lib/Slic3r/XS.pm | 2 +- xs/src/perlglue.cpp | 2 +- xs/xsp/GUI_Tab.xsp | 2 +- 5 files changed, 3 insertions(+), 2156 deletions(-) delete mode 100644 lib/Slic3r/GUI/BedShapeDialog.pm delete mode 100644 lib/Slic3r/GUI/Tab.pm diff --git a/lib/Slic3r/GUI/BedShapeDialog.pm b/lib/Slic3r/GUI/BedShapeDialog.pm deleted file mode 100644 index 70c8e0256..000000000 --- a/lib/Slic3r/GUI/BedShapeDialog.pm +++ /dev/null @@ -1,316 +0,0 @@ -# The bed shape dialog. -# The dialog opens from Print Settins tab -> Bed Shape: Set... - -package Slic3r::GUI::BedShapeDialog; -use strict; -use warnings; -use utf8; - -use List::Util qw(min max); -use Slic3r::Geometry qw(X Y unscale); -use Wx qw(:dialog :id :misc :sizer :choicebook wxTAB_TRAVERSAL); -use Wx::Event qw(EVT_CLOSE); -use base 'Wx::Dialog'; - -sub new { - my $class = shift; - my ($parent, $default) = @_; - my $self = $class->SUPER::new($parent, -1, "Bed Shape", wxDefaultPosition, [350,700], wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER); - - $self->{panel} = my $panel = Slic3r::GUI::BedShapePanel->new($self, $default); - - my $main_sizer = Wx::BoxSizer->new(wxVERTICAL); - $main_sizer->Add($panel, 1, wxEXPAND); - $main_sizer->Add($self->CreateButtonSizer(wxOK | wxCANCEL), 0, wxEXPAND); - - $self->SetSizer($main_sizer); - $self->SetMinSize($self->GetSize); - $main_sizer->SetSizeHints($self); - - # needed to actually free memory - EVT_CLOSE($self, sub { - $self->EndModal(wxID_OK); - $self->Destroy; - }); - - return $self; -} - -sub GetValue { - my ($self) = @_; - return $self->{panel}->GetValue; -} - -package Slic3r::GUI::BedShapePanel; - -use List::Util qw(min max sum first); -use Scalar::Util qw(looks_like_number); -use Slic3r::Geometry qw(PI X Y unscale scaled_epsilon); -use Wx qw(:font :id :misc :sizer :choicebook :filedialog :pen :brush wxTAB_TRAVERSAL); -use Wx::Event qw(EVT_CLOSE EVT_CHOICEBOOK_PAGE_CHANGED EVT_BUTTON); -use base 'Wx::Panel'; - -use constant SHAPE_RECTANGULAR => 0; -use constant SHAPE_CIRCULAR => 1; -use constant SHAPE_CUSTOM => 2; - -sub new { - my $class = shift; - my ($parent, $default) = @_; - my $self = $class->SUPER::new($parent, -1); - - $self->on_change(undef); - - my $box = Wx::StaticBox->new($self, -1, "Shape"); - my $sbsizer = Wx::StaticBoxSizer->new($box, wxVERTICAL); - - # shape options - $self->{shape_options_book} = Wx::Choicebook->new($self, -1, wxDefaultPosition, [300,-1], wxCHB_TOP); - $sbsizer->Add($self->{shape_options_book}); - - $self->{optgroups} = []; - { - my $optgroup = $self->_init_shape_options_page('Rectangular'); - $optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new( - opt_id => 'rect_size', - type => 'point', - label => 'Size', - tooltip => 'Size in X and Y of the rectangular plate.', - default => [200,200], - )); - $optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new( - opt_id => 'rect_origin', - type => 'point', - label => 'Origin', - tooltip => 'Distance of the 0,0 G-code coordinate from the front left corner of the rectangle.', - default => [0,0], - )); - } - { - my $optgroup = $self->_init_shape_options_page('Circular'); - $optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new( - opt_id => 'diameter', - type => 'f', - label => 'Diameter', - tooltip => 'Diameter of the print bed. It is assumed that origin (0,0) is located in the center.', - sidetext => 'mm', - default => 200, - )); - } - { - my $optgroup = $self->_init_shape_options_page('Custom'); - $optgroup->append_line(Slic3r::GUI::OptionsGroup::Line->new( - full_width => 1, - widget => sub { - my ($parent) = @_; - - my $btn = Wx::Button->new($parent, -1, "Load shape from STL...", wxDefaultPosition, wxDefaultSize); - EVT_BUTTON($self, $btn, sub { $self->_load_stl }); - return $btn; - } - )); - } - - EVT_CHOICEBOOK_PAGE_CHANGED($self, -1, sub { - $self->_update_shape; - }); - - # right pane with preview canvas - my $canvas = $self->{canvas} = Slic3r::GUI::2DBed->new($self); - - # main sizer - my $top_sizer = Wx::BoxSizer->new(wxHORIZONTAL); - $top_sizer->Add($sbsizer, 0, wxEXPAND | wxTOP | wxBOTTOM, 10); - $top_sizer->Add($canvas, 1, wxEXPAND | wxALL, 10) if $canvas; - - $self->SetSizerAndFit($top_sizer); - - $self->_set_shape($default); - $self->_update_preview; - - return $self; -} - -sub on_change { - my ($self, $cb) = @_; - $self->{on_change} = $cb // sub {}; -} - -# Called from the constructor. -# Set the initial bed shape from a list of points. -# Deduce the bed shape type (rect, circle, custom) -# This routine shall be smart enough if the user messes up -# with the list of points in the ini file directly. -sub _set_shape { - my ($self, $points) = @_; - - # is this a rectangle? - if (@$points == 4) { - my $polygon = Slic3r::Polygon->new_scale(@$points); - my $lines = $polygon->lines; - if ($lines->[0]->parallel_to_line($lines->[2]) && $lines->[1]->parallel_to_line($lines->[3])) { - # okay, it's a rectangle - - # find origin - # the || 0 hack prevents "-0" which might confuse the user - my $x_min = min(map $_->[X], @$points) || 0; - my $x_max = max(map $_->[X], @$points) || 0; - my $y_min = min(map $_->[Y], @$points) || 0; - my $y_max = max(map $_->[Y], @$points) || 0; - my $origin = [-$x_min, -$y_min]; - - $self->{shape_options_book}->SetSelection(SHAPE_RECTANGULAR); - my $optgroup = $self->{optgroups}[SHAPE_RECTANGULAR]; - $optgroup->set_value('rect_size', [ $x_max-$x_min, $y_max-$y_min ]); - $optgroup->set_value('rect_origin', $origin); - $self->_update_shape; - return; - } - } - - # is this a circle? - { - # Analyze the array of points. Do they reside on a circle? - my $polygon = Slic3r::Polygon->new_scale(@$points); - my $center = $polygon->bounding_box->center; - my @vertex_distances = map $center->distance_to($_), @$polygon; - my $avg_dist = sum(@vertex_distances)/@vertex_distances; - if (!defined first { abs($_ - $avg_dist) > 10*scaled_epsilon } @vertex_distances) { - # all vertices are equidistant to center - $self->{shape_options_book}->SetSelection(SHAPE_CIRCULAR); - my $optgroup = $self->{optgroups}[SHAPE_CIRCULAR]; - $optgroup->set_value('diameter', sprintf("%.0f", unscale($avg_dist*2))); - $self->_update_shape; - return; - } - } - - if (@$points < 3) { - # Invalid polygon. Revert to default bed dimensions. - $self->{shape_options_book}->SetSelection(SHAPE_RECTANGULAR); - my $optgroup = $self->{optgroups}[SHAPE_RECTANGULAR]; - $optgroup->set_value('rect_size', [200, 200]); - $optgroup->set_value('rect_origin', [0, 0]); - $self->_update_shape; - return; - } - - # This is a custom bed shape, use the polygon provided. - $self->{shape_options_book}->SetSelection(SHAPE_CUSTOM); - # Copy the polygon to the canvas, make a copy of the array. - $self->{canvas}->bed_shape([@$points]); - $self->_update_shape; -} - -# Update the bed shape from the dialog fields. -sub _update_shape { - my ($self) = @_; - - my $page_idx = $self->{shape_options_book}->GetSelection; - if ($page_idx == SHAPE_RECTANGULAR) { - my $rect_size = $self->{optgroups}[SHAPE_RECTANGULAR]->get_value('rect_size'); - my $rect_origin = $self->{optgroups}[SHAPE_RECTANGULAR]->get_value('rect_origin'); - my ($x, $y) = @$rect_size; - return if !looks_like_number($x) || !looks_like_number($y); # empty strings or '-' or other things - return if !$x || !$y or $x == 0 or $y == 0; - my ($x0, $y0) = (0,0); - my ($x1, $y1) = ($x ,$y); - { - my ($dx, $dy) = @$rect_origin; - return if !looks_like_number($dx) || !looks_like_number($dy); # empty strings or '-' or other things - $x0 -= $dx; - $x1 -= $dx; - $y0 -= $dy; - $y1 -= $dy; - } - $self->{canvas}->bed_shape([ - [$x0,$y0], - [$x1,$y0], - [$x1,$y1], - [$x0,$y1], - ]); - } elsif ($page_idx == SHAPE_CIRCULAR) { - my $diameter = $self->{optgroups}[SHAPE_CIRCULAR]->get_value('diameter'); - return if !$diameter or $diameter == 0; - my $r = $diameter/2; - my $twopi = 2*PI; - my $edges = 60; - my $polygon = Slic3r::Polygon->new_scale( - map [ $r * cos $_, $r * sin $_ ], - map { $twopi/$edges*$_ } 1..$edges - ); - $self->{canvas}->bed_shape([ - map [ unscale($_->x), unscale($_->y) ], @$polygon #)) - ]); - } - - $self->{on_change}->(); - $self->_update_preview; -} - -sub _update_preview { - my ($self) = @_; - $self->{canvas}->Refresh if $self->{canvas}; - $self->Refresh; -} - -# Called from the constructor. -# Create a panel for a rectangular / circular / custom bed shape. -sub _init_shape_options_page { - my ($self, $title) = @_; - - my $panel = Wx::Panel->new($self->{shape_options_book}); - my $optgroup; - push @{$self->{optgroups}}, $optgroup = Slic3r::GUI::OptionsGroup->new( - parent => $panel, - title => 'Settings', - label_width => 100, - on_change => sub { - my ($opt_id) = @_; - #$self->{"_$opt_id"} = $optgroup->get_value($opt_id); - $self->_update_shape; - }, - ); - $panel->SetSizerAndFit($optgroup->sizer); - $self->{shape_options_book}->AddPage($panel, $title); - - return $optgroup; -} - -# Loads an stl file, projects it to the XY plane and calculates a polygon. -sub _load_stl { - my ($self) = @_; - - my $dialog = Wx::FileDialog->new($self, 'Choose a file to import bed shape from (STL/OBJ/AMF/PRUSA):', "", "", &Slic3r::GUI::MODEL_WILDCARD, wxFD_OPEN | wxFD_FILE_MUST_EXIST); - if ($dialog->ShowModal != wxID_OK) { - $dialog->Destroy; - return; - } - my $input_file = $dialog->GetPaths; - $dialog->Destroy; - - my $model = Slic3r::Model->read_from_file($input_file); - my $mesh = $model->mesh; - my $expolygons = $mesh->horizontal_projection; - - if (@$expolygons == 0) { - Slic3r::GUI::show_error($self, "The selected file contains no geometry."); - return; - } - if (@$expolygons > 1) { - Slic3r::GUI::show_error($self, "The selected file contains several disjoint areas. This is not supported."); - return; - } - - my $polygon = $expolygons->[0]->contour; - $self->{canvas}->bed_shape([ map [ unscale($_->x), unscale($_->y) ], @$polygon ]); - $self->_update_preview(); -} - -# Returns the resulting bed shape polygon. This value will be stored to the ini file. -sub GetValue { - my ($self) = @_; - return $self->{canvas}->bed_shape; -} - -1; diff --git a/lib/Slic3r/GUI/Tab.pm b/lib/Slic3r/GUI/Tab.pm deleted file mode 100644 index 4bd18366b..000000000 --- a/lib/Slic3r/GUI/Tab.pm +++ /dev/null @@ -1,1837 +0,0 @@ -# The "Expert" tab at the right of the main tabbed window. - -# This file implements following packages: -# Slic3r::GUI::Tab; -# Slic3r::GUI::Tab::Print; -# Slic3r::GUI::Tab::Filament; -# Slic3r::GUI::Tab::Printer; -# Slic3r::GUI::Tab::Page -# - Option page: For example, the Slic3r::GUI::Tab::Print has option pages "Layers and perimeters", "Infill", "Skirt and brim" ... -# Slic3r::GUI::SavePresetWindow -# - Dialog to select a new preset name to store the configuration. -# Slic3r::GUI::Tab::Preset; -# - Single preset item: name, file is default or external. - -package Slic3r::GUI::Tab; -use strict; -use warnings; -use utf8; - -use File::Basename qw(basename); -use List::Util qw(first); -use Wx qw(:bookctrl :dialog :keycode :icon :id :misc :panel :sizer :treectrl :window - :button wxTheApp wxCB_READONLY); -use Wx::Event qw(EVT_BUTTON EVT_COMBOBOX EVT_KEY_DOWN EVT_CHECKBOX EVT_TREE_SEL_CHANGED); -use base qw(Wx::Panel Class::Accessor); - -sub new { - my ($class, $parent, %params) = @_; - my $self = $class->SUPER::new($parent, -1, wxDefaultPosition, wxDefaultSize, wxBK_LEFT | wxTAB_TRAVERSAL); - - # Vertical sizer to hold the choice menu and the rest of the page. - $self->{sizer} = Wx::BoxSizer->new(wxVERTICAL); - $self->{sizer}->SetSizeHints($self); - $self->SetSizer($self->{sizer}); - - # preset chooser - { - - # choice menu - $self->{presets_choice} = Wx::BitmapComboBox->new($self, -1, "", wxDefaultPosition, [270, -1], [], wxCB_READONLY); - $self->{presets_choice}->SetFont($Slic3r::GUI::small_font); - - # buttons - $self->{btn_save_preset} = Wx::BitmapButton->new($self, -1, Wx::Bitmap->new(Slic3r::var("disk.png"), wxBITMAP_TYPE_PNG), - wxDefaultPosition, wxDefaultSize, wxBORDER_NONE); - $self->{btn_delete_preset} = Wx::BitmapButton->new($self, -1, Wx::Bitmap->new(Slic3r::var("delete.png"), wxBITMAP_TYPE_PNG), - wxDefaultPosition, wxDefaultSize, wxBORDER_NONE); - $self->{show_incompatible_presets} = 0; - $self->{bmp_show_incompatible_presets} = Wx::Bitmap->new(Slic3r::var("flag-red-icon.png"), wxBITMAP_TYPE_PNG); - $self->{bmp_hide_incompatible_presets} = Wx::Bitmap->new(Slic3r::var("flag-green-icon.png"), wxBITMAP_TYPE_PNG); - $self->{btn_hide_incompatible_presets} = Wx::BitmapButton->new($self, -1, - $self->{bmp_hide_incompatible_presets}, - wxDefaultPosition, wxDefaultSize, wxBORDER_NONE); - $self->{btn_save_preset}->SetToolTipString("Save current " . lc($self->title)); - $self->{btn_delete_preset}->SetToolTipString("Delete this preset"); - $self->{btn_delete_preset}->Disable; - - my $hsizer = Wx::BoxSizer->new(wxHORIZONTAL); - $self->{sizer}->Add($hsizer, 0, wxBOTTOM, 3); - $hsizer->Add($self->{presets_choice}, 1, wxLEFT | wxRIGHT | wxTOP | wxALIGN_CENTER_VERTICAL, 3); - $hsizer->AddSpacer(4); - $hsizer->Add($self->{btn_save_preset}, 0, wxALIGN_CENTER_VERTICAL); - $hsizer->AddSpacer(4); - $hsizer->Add($self->{btn_delete_preset}, 0, wxALIGN_CENTER_VERTICAL); - $hsizer->AddSpacer(16); - $hsizer->Add($self->{btn_hide_incompatible_presets}, 0, wxALIGN_CENTER_VERTICAL); - } - - # Horizontal sizer to hold the tree and the selected page. - $self->{hsizer} = Wx::BoxSizer->new(wxHORIZONTAL); - $self->{sizer}->Add($self->{hsizer}, 1, wxEXPAND, 0); - - # left vertical sizer - my $left_sizer = Wx::BoxSizer->new(wxVERTICAL); - $self->{hsizer}->Add($left_sizer, 0, wxEXPAND | wxLEFT | wxTOP | wxBOTTOM, 3); - - # tree - $self->{treectrl} = Wx::TreeCtrl->new($self, -1, wxDefaultPosition, [185, -1], wxTR_NO_BUTTONS | wxTR_HIDE_ROOT | wxTR_SINGLE | wxTR_NO_LINES | wxBORDER_SUNKEN | wxWANTS_CHARS); - $left_sizer->Add($self->{treectrl}, 1, wxEXPAND); - $self->{icons} = Wx::ImageList->new(16, 16, 1); - # Map from an icon file name to its index in $self->{icons}. - $self->{icon_index} = {}; - # Index of the last icon inserted into $self->{icons}. - $self->{icon_count} = -1; - $self->{treectrl}->AssignImageList($self->{icons}); - $self->{treectrl}->AddRoot("root"); - $self->{pages} = []; - $self->{treectrl}->SetIndent(0); - $self->{disable_tree_sel_changed_event} = 0; - EVT_TREE_SEL_CHANGED($parent, $self->{treectrl}, sub { - return if $self->{disable_tree_sel_changed_event}; - my $page = first { $_->{title} eq $self->{treectrl}->GetItemText($self->{treectrl}->GetSelection) } @{$self->{pages}} - or return; - $_->Hide for @{$self->{pages}}; - $page->Show; - $self->{hsizer}->Layout; - $self->Refresh; - }); - EVT_KEY_DOWN($self->{treectrl}, sub { - my ($treectrl, $event) = @_; - if ($event->GetKeyCode == WXK_TAB) { - $treectrl->Navigate($event->ShiftDown ? &Wx::wxNavigateBackward : &Wx::wxNavigateForward); - } else { - $event->Skip; - } - }); - - EVT_COMBOBOX($parent, $self->{presets_choice}, sub { - $self->select_preset($self->{presets_choice}->GetStringSelection); - }); - - EVT_BUTTON($self, $self->{btn_save_preset}, sub { $self->save_preset }); - EVT_BUTTON($self, $self->{btn_delete_preset}, sub { $self->delete_preset }); - EVT_BUTTON($self, $self->{btn_hide_incompatible_presets}, sub { $self->_toggle_show_hide_incompatible }); - - # Initialize the DynamicPrintConfig by default keys/values. - # Possible %params keys: no_controller - $self->build(%params); - $self->rebuild_page_tree; - $self->_update; - - return $self; -} - -# Save the current preset into file. -# This removes the "dirty" flag of the preset, possibly creates a new preset under a new name, -# and activates the new preset. -# Wizard calls save_preset with a name "My Settings", otherwise no name is provided and this method -# opens a Slic3r::GUI::SavePresetWindow dialog. -sub save_preset { - my ($self, $name) = @_; - - # since buttons (and choices too) don't get focus on Mac, we set focus manually - # to the treectrl so that the EVT_* events are fired for the input field having - # focus currently. is there anything better than this? - $self->{treectrl}->SetFocus; - - if (!defined $name) { - my $preset = $self->{presets}->get_selected_preset; - my $default_name = $preset->default ? 'Untitled' : $preset->name; - $default_name =~ s/\.[iI][nN][iI]$//; - my $dlg = Slic3r::GUI::SavePresetWindow->new($self, - title => lc($self->title), - default => $default_name, - values => [ map $_->name, grep !$_->default && !$_->external, @{$self->{presets}} ], - ); - return unless $dlg->ShowModal == wxID_OK; - $name = $dlg->get_name; - } - # Save the preset into Slic3r::data_dir/presets/section_name/preset_name.ini - eval { $self->{presets}->save_current_preset($name); }; - Slic3r::GUI::catch_error($self) and return; - # Mark the print & filament enabled if they are compatible with the currently selected preset. - wxTheApp->{preset_bundle}->update_compatible_with_printer(0); - # Add the new item into the UI component, remove dirty flags and activate the saved item. - $self->update_tab_ui; - # Update the selection boxes at the platter. - $self->_on_presets_changed; -} - -# Called for a currently selected preset. -sub delete_preset { - my ($self) = @_; - my $current_preset = $self->{presets}->get_selected_preset; - # Don't let the user delete the '- default -' configuration. - my $msg = 'Are you sure you want to ' . ($current_preset->external ? 'remove' : 'delete') . ' the selected preset?'; - my $title = ($current_preset->external ? 'Remove' : 'Delete') . ' Preset'; - return if $current_preset->default || - wxID_YES != Wx::MessageDialog->new($self, $msg, $title, wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION)->ShowModal; - # Delete the file and select some other reasonable preset. - # The 'external' presets will only be removed from the preset list, their files will not be deleted. - eval { $self->{presets}->delete_current_preset; }; - Slic3r::GUI::catch_error($self) and return; - # Load the newly selected preset into the UI, update selection combo boxes with their dirty flags. - $self->load_current_preset; -} - -sub _toggle_show_hide_incompatible { - my ($self) = @_; - $self->{show_incompatible_presets} = ! $self->{show_incompatible_presets}; - $self->_update_show_hide_incompatible_button; - $self->update_tab_ui; -} - -sub _update_show_hide_incompatible_button { - my ($self) = @_; - $self->{btn_hide_incompatible_presets}->SetBitmap($self->{show_incompatible_presets} ? - $self->{bmp_show_incompatible_presets} : $self->{bmp_hide_incompatible_presets}); - $self->{btn_hide_incompatible_presets}->SetToolTipString($self->{show_incompatible_presets} ? - "Both compatible an incompatible presets are shown. Click to hide presets not compatible with the current printer." : - "Only compatible presets are shown. Click to show both the presets compatible and not compatible with the current printer."); -} - -# Register the on_value_change callback. -sub on_value_change { - my ($self, $cb) = @_; - $self->{on_value_change} = $cb; -} - -# Register the on_presets_changed callback. -sub on_presets_changed { - my ($self, $cb) = @_; - $self->{on_presets_changed} = $cb; -} - -# This method is called whenever an option field is changed by the user. -# Propagate event to the parent through the 'on_value_change' callback -# and call _update. -# The on_value_change callback triggers Platter::on_config_change() to configure the 3D preview -# (colors, wipe tower positon etc) and to restart the background slicing process. -sub _on_value_change { - my ($self, $key, $value) = @_; - $self->{on_value_change}->($key, $value) if $self->{on_value_change}; - $self->_update; -} - -# Override this to capture changes of configuration caused either by loading or switching a preset, -# or by a user changing an option field. -# This callback is useful for cross-validating configuration values of a single preset. -sub _update {} - -# Call a callback to update the selection of presets on the platter: -# To update the content of the selection boxes, -# to update the filament colors of the selection boxes, -# to update the "dirty" flags of the selection boxes, -# to uddate number of "filament" selection boxes when the number of extruders change. -sub _on_presets_changed { - my ($self, $reload_dependent_tabs) = @_; - $self->{on_presets_changed}->($self->{presets}, $reload_dependent_tabs) - if $self->{on_presets_changed}; -} - -# For the printer profile, generate the extruder pages after a preset is loaded. -sub on_preset_loaded {} - -# If the current preset is dirty, the user is asked whether the changes may be discarded. -# if the current preset was not dirty, or the user agreed to discard the changes, 1 is returned. -sub may_discard_current_dirty_preset -{ - my ($self, $presets, $new_printer_name) = @_; - $presets //= $self->{presets}; - # Display a dialog showing the dirty options in a human readable form. - my $old_preset = $presets->get_current_preset; - my $type_name = $presets->name; - my $tab = ' '; - my $name = $old_preset->default ? - ('Default ' . $type_name . ' preset') : - ($type_name . " preset\n$tab" . $old_preset->name); - # Collect descriptions of the dirty options. - my @option_names = (); - foreach my $opt_key (@{$presets->current_dirty_options}) { - my $opt = $Slic3r::Config::Options->{$opt_key}; - my $name = $opt->{full_label} // $opt->{label}; - $name = $opt->{category} . " > $name" if $opt->{category}; - push @option_names, $name; - } - # Show a confirmation dialog with the list of dirty options. - my $changes = join "\n", map "$tab$_", @option_names; - my $message = (defined $new_printer_name) ? - "$name\n\nis not compatible with printer\n$tab$new_printer_name\n\nand it has the following unsaved changes:" : - "$name\n\nhas the following unsaved changes:"; - my $confirm = Wx::MessageDialog->new($self, - $message . "\n$changes\n\nDiscard changes and continue anyway?", - 'Unsaved Changes', wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION); - return $confirm->ShowModal == wxID_YES; -} - -# Called by the UI combo box when the user switches profiles. -# Select a preset by a name. If ! defined(name), then the default preset is selected. -# If the current profile is modified, user is asked to save the changes. -sub select_preset { - my ($self, $name, $force) = @_; - $force //= 0; - my $presets = $self->{presets}; - # If no name is provided, select the "-- default --" preset. - $name //= $presets->default_preset->name; - my $current_dirty = $presets->current_is_dirty; - my $canceled = 0; - my $printer_tab = $presets->name eq 'printer'; - my @reload_dependent_tabs = (); - if (! $force && $current_dirty && ! $self->may_discard_current_dirty_preset) { - $canceled = 1; - } elsif ($printer_tab) { - # Before switching the printer to a new one, verify, whether the currently active print and filament - # are compatible with the new printer. - # If they are not compatible and the the current print or filament are dirty, let user decide - # whether to discard the changes or keep the current printer selection. - my $new_printer_preset = $presets->find_preset($name, 1); - my $print_presets = wxTheApp->{preset_bundle}->print; - my $print_preset_dirty = $print_presets->current_is_dirty; - my $print_preset_compatible = $print_presets->get_edited_preset->is_compatible_with_printer($new_printer_preset); - $canceled = ! $force && $print_preset_dirty && ! $print_preset_compatible && - ! $self->may_discard_current_dirty_preset($print_presets, $name); - my $filament_presets = wxTheApp->{preset_bundle}->filament; - my $filament_preset_dirty = $filament_presets->current_is_dirty; - my $filament_preset_compatible = $filament_presets->get_edited_preset->is_compatible_with_printer($new_printer_preset); - if (! $canceled && ! $force) { - $canceled = $filament_preset_dirty && ! $filament_preset_compatible && - ! $self->may_discard_current_dirty_preset($filament_presets, $name); - } - if (! $canceled) { - if (! $print_preset_compatible) { - # The preset will be switched to a different, compatible preset, or the '-- default --'. - push @reload_dependent_tabs, 'print'; - $print_presets->discard_current_changes if $print_preset_dirty; - } - if (! $filament_preset_compatible) { - # The preset will be switched to a different, compatible preset, or the '-- default --'. - push @reload_dependent_tabs, 'filament'; - $filament_presets->discard_current_changes if $filament_preset_dirty; - } - } - } - if ($canceled) { - $self->update_tab_ui; - # Trigger the on_presets_changed event so that we also restore the previous value in the plater selector, - # if this action was initiated from the platter. - $self->_on_presets_changed; - } else { - $presets->discard_current_changes if $current_dirty; - $presets->select_preset_by_name($name); - # Mark the print & filament enabled if they are compatible with the currently selected preset. - # The following method should not discard changes of current print or filament presets on change of a printer profile, - # if they are compatible with the current printer. - wxTheApp->{preset_bundle}->update_compatible_with_printer(1) - if $current_dirty || $printer_tab; - # Initialize the UI from the current preset. - $self->load_current_preset(\@reload_dependent_tabs); - } -} - -# Initialize the UI from the current preset. -sub load_current_preset { - my ($self, $dependent_tab_names) = @_; - my $preset = $self->{presets}->get_current_preset; - eval { - local $SIG{__WARN__} = Slic3r::GUI::warning_catcher($self); - my $method = $preset->default ? 'Disable' : 'Enable'; - $self->{btn_delete_preset}->$method; - $self->_update; - # For the printer profile, generate the extruder pages. - $self->on_preset_loaded; - # Reload preset pages with the new configuration values. - $self->_reload_config; - }; - # use CallAfter because some field triggers schedule on_change calls using CallAfter, - # and we don't want them to be called after this update_dirty() as they would mark the - # preset dirty again - # (not sure this is true anymore now that update_dirty is idempotent) - wxTheApp->CallAfter(sub { - $self->update_tab_ui; - $self->_on_presets_changed($dependent_tab_names); - }); -} - -sub add_options_page { - my ($self, $title, $icon, %params) = @_; - # Index of $icon in an icon list $self->{icons}. - my $icon_idx = 0; - if ($icon) { - $icon_idx = $self->{icon_index}->{$icon}; - if (! defined $icon_idx) { - # Add a new icon to the icon list. - my $bitmap = Wx::Bitmap->new(Slic3r::var($icon), wxBITMAP_TYPE_PNG); - $self->{icons}->Add($bitmap); - $icon_idx = $self->{icon_count} + 1; - $self->{icon_count} = $icon_idx; - $self->{icon_index}->{$icon} = $icon_idx; - } - } - # Initialize the page. - my $page = Slic3r::GUI::Tab::Page->new($self, $title, $icon_idx); - $page->Hide; - $self->{hsizer}->Add($page, 1, wxEXPAND | wxLEFT, 5); - push @{$self->{pages}}, $page; - return $page; -} - -# Reload current $self->{config} (aka $self->{presets}->edited_preset->config) into the UI fields. -sub _reload_config { - my ($self) = @_; - $self->Freeze; - $_->reload_config for @{$self->{pages}}; - $self->Thaw; -} - -# Regerenerate content of the page tree. -sub rebuild_page_tree { - my ($self) = @_; - $self->Freeze; - # get label of the currently selected item - my $selected = $self->{treectrl}->GetItemText($self->{treectrl}->GetSelection); - my $rootItem = $self->{treectrl}->GetRootItem; - $self->{treectrl}->DeleteChildren($rootItem); - my $have_selection = 0; - foreach my $page (@{$self->{pages}}) { - my $itemId = $self->{treectrl}->AppendItem($rootItem, $page->{title}, $page->{iconID}); - if ($page->{title} eq $selected) { - $self->{disable_tree_sel_changed_event} = 1; - $self->{treectrl}->SelectItem($itemId); - $self->{disable_tree_sel_changed_event} = 0; - $have_selection = 1; - } - } - if (!$have_selection) { - # this is triggered on first load, so we don't disable the sel change event - $self->{treectrl}->SelectItem($self->{treectrl}->GetFirstChild($rootItem)); - } - $self->Thaw; -} - -# Update the combo box label of the selected preset based on its "dirty" state, -# comparing the selected preset config with $self->{config}. -sub update_dirty { - my ($self) = @_; - $self->{presets}->update_dirty_ui($self->{presets_choice}); - $self->_on_presets_changed; -} - -# Load a provied DynamicConfig into the tab, modifying the active preset. -# This could be used for example by setting a Wipe Tower position by interactive manipulation in the 3D view. -sub load_config { - my ($self, $config) = @_; - my $modified = 0; - foreach my $opt_key (@{$self->{config}->diff($config)}) { - $self->{config}->set($opt_key, $config->get($opt_key)); - $modified = 1; - } - if ($modified) { - $self->update_dirty; - # Initialize UI components with the config values. - $self->_reload_config; - $self->_update; - } -} - -# To be called by custom widgets, load a value into a config, -# update the preset selection boxes (the dirty flags) -sub _load_key_value { - my ($self, $opt_key, $value) = @_; - $self->{config}->set($opt_key, $value); - # Mark the print & filament enabled if they are compatible with the currently selected preset. - if ($opt_key eq 'compatible_printers') { -# $opt_key eq 'compatible_printers_condition') { - wxTheApp->{preset_bundle}->update_compatible_with_printer(0); - } - $self->{presets}->update_dirty_ui($self->{presets_choice}); - $self->_on_presets_changed; - $self->_update; -} - -# Find a field with an index over all pages of this tab. -# This method is used often and everywhere, therefore it shall be quick. -sub get_field { - my ($self, $opt_key, $opt_index) = @_; - foreach my $page (@{$self->{pages}}) { - my $field = $page->get_field($opt_key, $opt_index); - return $field if defined $field; - } - return undef; -} - -# Set a key/value pair on this page. Return true if the value has been modified. -# Currently used for distributing extruders_count over preset pages of Slic3r::GUI::Tab::Printer -# after a preset is loaded. -sub set_value { - my ($self, $opt_key, $value) = @_; - my $changed = 0; - foreach my $page (@{$self->{pages}}) { - $changed = 1 if $page->set_value($opt_key, $value); - } - return $changed; -} - -# Return a callback to create a Tab widget to mark the preferences as compatible / incompatible to the current printer. -sub _compatible_printers_widget { - my ($self) = @_; - - return sub { - my ($parent) = @_; - - my $checkbox = $self->{compatible_printers_checkbox} = Wx::CheckBox->new($parent, -1, "All"); - - my $btn = $self->{compatible_printers_btn} = Wx::Button->new($parent, -1, "Set…", wxDefaultPosition, wxDefaultSize, - wxBU_LEFT | wxBU_EXACTFIT); - $btn->SetFont($Slic3r::GUI::small_font); - $btn->SetBitmap(Wx::Bitmap->new(Slic3r::var("printer_empty.png"), wxBITMAP_TYPE_PNG)); - - my $sizer = Wx::BoxSizer->new(wxHORIZONTAL); - $sizer->Add($checkbox, 0, wxALIGN_CENTER_VERTICAL); - $sizer->Add($btn, 0, wxALIGN_CENTER_VERTICAL); - - EVT_CHECKBOX($self, $checkbox, sub { - my $method = $checkbox->GetValue ? 'Disable' : 'Enable'; - $btn->$method; - # All printers have been made compatible with this preset. - $self->_load_key_value('compatible_printers', []) if $checkbox->GetValue; - $self->get_field('compatible_printers_condition')->toggle($checkbox->GetValue); - }); - - EVT_BUTTON($self, $btn, sub { - # Collect names of non-default non-external printer profiles. - my @presets = map $_->name, grep !$_->default && !$_->external, - @{wxTheApp->{preset_bundle}->printer}; - my $dlg = Wx::MultiChoiceDialog->new($self, - "Select the printers this profile is compatible with.", - "Compatible printers", \@presets); - # Collect and set indices of printers marked as compatible. - my @selections = (); - foreach my $preset_name (@{ $self->{config}->get('compatible_printers') }) { - my $idx = first { $presets[$_] eq $preset_name } 0..$#presets; - push @selections, $idx if defined $idx; - } - $dlg->SetSelections(@selections); - # Show the dialog. - if ($dlg->ShowModal == wxID_OK) { - my $value = [ @presets[$dlg->GetSelections] ]; - if (!@$value) { - $checkbox->SetValue(1); - $self->get_field('compatible_printers_condition')->toggle(1); - $btn->Disable; - } - # All printers have been made compatible with this preset. - $self->_load_key_value('compatible_printers', $value); - } - }); - - return $sizer; - }; -} - -sub _reload_compatible_printers_widget { - my ($self) = @_; - my $has_any = int(@{$self->{config}->get('compatible_printers')}) > 0; - my $method = $has_any ? 'Enable' : 'Disable'; - $self->{compatible_printers_checkbox}->SetValue(! $has_any); - $self->{compatible_printers_btn}->$method; - $self->get_field('compatible_printers_condition')->toggle(! $has_any); -} - -sub update_ui_from_settings { - my ($self) = @_; - # Show the 'show / hide presets' button only for the print and filament tabs, and only if enabled - # in application preferences. - my $show = wxTheApp->{app_config}->get("show_incompatible_presets") && $self->{presets}->name ne 'printer'; - my $method = $show ? 'Show' : 'Hide'; - $self->{btn_hide_incompatible_presets}->$method; - # If the 'show / hide presets' button is hidden, hide the incompatible presets. - if ($show) { - $self->_update_show_hide_incompatible_button; - } else { - if ($self->{show_incompatible_presets}) { - $self->{show_incompatible_presets} = 0; - $self->update_tab_ui; - } - } -} -sub update_tab_ui { - my ($self) = @_; - $self->{presets}->update_tab_ui($self->{presets_choice}, $self->{show_incompatible_presets}) -} - -package Slic3r::GUI::Tab::Print; -use base 'Slic3r::GUI::Tab'; - -use List::Util qw(first); -use Wx qw(:icon :dialog :id wxTheApp); - -sub name { 'print' } -sub title { 'Print Settings' } - -sub build { - my $self = shift; - - $self->{presets} = wxTheApp->{preset_bundle}->print; - $self->{config} = $self->{presets}->get_edited_preset->config; - - { - my $page = $self->add_options_page('Layers and perimeters', 'layers.png'); - { - my $optgroup = $page->new_optgroup('Layer height'); - $optgroup->append_single_option_line('layer_height'); - $optgroup->append_single_option_line('first_layer_height'); - } - { - my $optgroup = $page->new_optgroup('Vertical shells'); - $optgroup->append_single_option_line('perimeters'); - $optgroup->append_single_option_line('spiral_vase'); - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => '', - full_width => 1, - widget => sub { - my ($parent) = @_; - return $self->{recommended_thin_wall_thickness_description_line} = Slic3r::GUI::OptionsGroup::StaticText->new($parent); - }, - ); - $optgroup->append_line($line); - } - { - my $optgroup = $page->new_optgroup('Horizontal shells'); - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => 'Solid layers', - ); - $line->append_option($optgroup->get_option('top_solid_layers')); - $line->append_option($optgroup->get_option('bottom_solid_layers')); - $optgroup->append_line($line); - } - { - my $optgroup = $page->new_optgroup('Quality (slower slicing)'); - $optgroup->append_single_option_line('extra_perimeters'); - $optgroup->append_single_option_line('ensure_vertical_shell_thickness'); - $optgroup->append_single_option_line('avoid_crossing_perimeters'); - $optgroup->append_single_option_line('thin_walls'); - $optgroup->append_single_option_line('overhangs'); - } - { - my $optgroup = $page->new_optgroup('Advanced'); - $optgroup->append_single_option_line('seam_position'); - $optgroup->append_single_option_line('external_perimeters_first'); - } - } - - { - my $page = $self->add_options_page('Infill', 'infill.png'); - { - my $optgroup = $page->new_optgroup('Infill'); - $optgroup->append_single_option_line('fill_density'); - $optgroup->append_single_option_line('fill_pattern'); - $optgroup->append_single_option_line('external_fill_pattern'); - } - { - my $optgroup = $page->new_optgroup('Reducing printing time'); - $optgroup->append_single_option_line('infill_every_layers'); - $optgroup->append_single_option_line('infill_only_where_needed'); - } - { - my $optgroup = $page->new_optgroup('Advanced'); - $optgroup->append_single_option_line('solid_infill_every_layers'); - $optgroup->append_single_option_line('fill_angle'); - $optgroup->append_single_option_line('solid_infill_below_area'); - $optgroup->append_single_option_line('bridge_angle'); - $optgroup->append_single_option_line('only_retract_when_crossing_perimeters'); - $optgroup->append_single_option_line('infill_first'); - } - } - - { - my $page = $self->add_options_page('Skirt and brim', 'box.png'); - { - my $optgroup = $page->new_optgroup('Skirt'); - $optgroup->append_single_option_line('skirts'); - $optgroup->append_single_option_line('skirt_distance'); - $optgroup->append_single_option_line('skirt_height'); - $optgroup->append_single_option_line('min_skirt_length'); - } - { - my $optgroup = $page->new_optgroup('Brim'); - $optgroup->append_single_option_line('brim_width'); - } - } - - { - my $page = $self->add_options_page('Support material', 'building.png'); - { - my $optgroup = $page->new_optgroup('Support material'); - $optgroup->append_single_option_line('support_material'); - $optgroup->append_single_option_line('support_material_threshold'); - $optgroup->append_single_option_line('support_material_enforce_layers'); - } - { - my $optgroup = $page->new_optgroup('Raft'); - $optgroup->append_single_option_line('raft_layers'); -# $optgroup->append_single_option_line('raft_contact_distance'); - } - { - my $optgroup = $page->new_optgroup('Options for support material and raft'); - $optgroup->append_single_option_line('support_material_contact_distance'); - $optgroup->append_single_option_line('support_material_pattern'); - $optgroup->append_single_option_line('support_material_with_sheath'); - $optgroup->append_single_option_line('support_material_spacing'); - $optgroup->append_single_option_line('support_material_angle'); - $optgroup->append_single_option_line('support_material_interface_layers'); - $optgroup->append_single_option_line('support_material_interface_spacing'); - $optgroup->append_single_option_line('support_material_interface_contact_loops'); - $optgroup->append_single_option_line('support_material_buildplate_only'); - $optgroup->append_single_option_line('support_material_xy_spacing'); - $optgroup->append_single_option_line('dont_support_bridges'); - $optgroup->append_single_option_line('support_material_synchronize_layers'); - } - } - - { - my $page = $self->add_options_page('Speed', 'time.png'); - { - my $optgroup = $page->new_optgroup('Speed for print moves'); - $optgroup->append_single_option_line('perimeter_speed'); - $optgroup->append_single_option_line('small_perimeter_speed'); - $optgroup->append_single_option_line('external_perimeter_speed'); - $optgroup->append_single_option_line('infill_speed'); - $optgroup->append_single_option_line('solid_infill_speed'); - $optgroup->append_single_option_line('top_solid_infill_speed'); - $optgroup->append_single_option_line('support_material_speed'); - $optgroup->append_single_option_line('support_material_interface_speed'); - $optgroup->append_single_option_line('bridge_speed'); - $optgroup->append_single_option_line('gap_fill_speed'); - } - { - my $optgroup = $page->new_optgroup('Speed for non-print moves'); - $optgroup->append_single_option_line('travel_speed'); - } - { - my $optgroup = $page->new_optgroup('Modifiers'); - $optgroup->append_single_option_line('first_layer_speed'); - } - { - my $optgroup = $page->new_optgroup('Acceleration control (advanced)'); - $optgroup->append_single_option_line('perimeter_acceleration'); - $optgroup->append_single_option_line('infill_acceleration'); - $optgroup->append_single_option_line('bridge_acceleration'); - $optgroup->append_single_option_line('first_layer_acceleration'); - $optgroup->append_single_option_line('default_acceleration'); - } - { - my $optgroup = $page->new_optgroup('Autospeed (advanced)'); - $optgroup->append_single_option_line('max_print_speed'); - $optgroup->append_single_option_line('max_volumetric_speed'); - $optgroup->append_single_option_line('max_volumetric_extrusion_rate_slope_positive'); - $optgroup->append_single_option_line('max_volumetric_extrusion_rate_slope_negative'); - } - } - - { - my $page = $self->add_options_page('Multiple Extruders', 'funnel.png'); - { - my $optgroup = $page->new_optgroup('Extruders'); - $optgroup->append_single_option_line('perimeter_extruder'); - $optgroup->append_single_option_line('infill_extruder'); - $optgroup->append_single_option_line('solid_infill_extruder'); - $optgroup->append_single_option_line('support_material_extruder'); - $optgroup->append_single_option_line('support_material_interface_extruder'); - } - { - my $optgroup = $page->new_optgroup('Ooze prevention'); - $optgroup->append_single_option_line('ooze_prevention'); - $optgroup->append_single_option_line('standby_temperature_delta'); - } - { - my $optgroup = $page->new_optgroup('Wipe tower'); - $optgroup->append_single_option_line('wipe_tower'); - $optgroup->append_single_option_line('wipe_tower_x'); - $optgroup->append_single_option_line('wipe_tower_y'); - $optgroup->append_single_option_line('wipe_tower_width'); - $optgroup->append_single_option_line('wipe_tower_per_color_wipe'); - } - { - my $optgroup = $page->new_optgroup('Advanced'); - $optgroup->append_single_option_line('interface_shells'); - } - } - - { - my $page = $self->add_options_page('Advanced', 'wrench.png'); - { - my $optgroup = $page->new_optgroup('Extrusion width', - label_width => 180, - ); - $optgroup->append_single_option_line('extrusion_width'); - $optgroup->append_single_option_line('first_layer_extrusion_width'); - $optgroup->append_single_option_line('perimeter_extrusion_width'); - $optgroup->append_single_option_line('external_perimeter_extrusion_width'); - $optgroup->append_single_option_line('infill_extrusion_width'); - $optgroup->append_single_option_line('solid_infill_extrusion_width'); - $optgroup->append_single_option_line('top_infill_extrusion_width'); - $optgroup->append_single_option_line('support_material_extrusion_width'); - } - { - my $optgroup = $page->new_optgroup('Overlap'); - $optgroup->append_single_option_line('infill_overlap'); - } - { - my $optgroup = $page->new_optgroup('Flow'); - $optgroup->append_single_option_line('bridge_flow_ratio'); - } - { - my $optgroup = $page->new_optgroup('Other'); - $optgroup->append_single_option_line('clip_multipart_objects'); - $optgroup->append_single_option_line('elefant_foot_compensation'); - $optgroup->append_single_option_line('xy_size_compensation'); -# $optgroup->append_single_option_line('threads'); - $optgroup->append_single_option_line('resolution'); - } - } - - { - my $page = $self->add_options_page('Output options', 'page_white_go.png'); - { - my $optgroup = $page->new_optgroup('Sequential printing'); - $optgroup->append_single_option_line('complete_objects'); - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => 'Extruder clearance (mm)', - ); - foreach my $opt_key (qw(extruder_clearance_radius extruder_clearance_height)) { - my $option = $optgroup->get_option($opt_key); - $option->width(60); - $line->append_option($option); - } - $optgroup->append_line($line); - } - { - my $optgroup = $page->new_optgroup('Output file'); - $optgroup->append_single_option_line('gcode_comments'); - - { - my $option = $optgroup->get_option('output_filename_format'); - $option->full_width(1); - $optgroup->append_single_option_line($option); - } - } - { - my $optgroup = $page->new_optgroup('Post-processing scripts', - label_width => 0, - ); - my $option = $optgroup->get_option('post_process'); - $option->full_width(1); - $option->height(50); - $optgroup->append_single_option_line($option); - } - } - - { - my $page = $self->add_options_page('Notes', 'note.png'); - { - my $optgroup = $page->new_optgroup('Notes', - label_width => 0, - ); - my $option = $optgroup->get_option('notes'); - $option->full_width(1); - $option->height(250); - $optgroup->append_single_option_line($option); - } - } - - { - my $page = $self->add_options_page('Dependencies', 'wrench.png'); - { - my $optgroup = $page->new_optgroup('Profile dependencies'); - { - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => 'Compatible printers', - widget => $self->_compatible_printers_widget, - ); - $optgroup->append_line($line); - - my $option = $optgroup->get_option('compatible_printers_condition'); - $option->full_width(1); - $optgroup->append_single_option_line($option); - } - } - } -} - -# Reload current $self->{config} (aka $self->{presets}->edited_preset->config) into the UI fields. -sub _reload_config { - my ($self) = @_; - $self->_reload_compatible_printers_widget; - $self->SUPER::_reload_config; -} - -# Slic3r::GUI::Tab::Print::_update is called after a configuration preset is loaded or switched, or when a single option is modifed by the user. -sub _update { - my ($self) = @_; - $self->Freeze; - - my $config = $self->{config}; - - if ($config->spiral_vase && !($config->perimeters == 1 && $config->top_solid_layers == 0 && $config->fill_density == 0)) { - my $dialog = Wx::MessageDialog->new($self, - "The Spiral Vase mode requires:\n" - . "- one perimeter\n" - . "- no top solid layers\n" - . "- 0% fill density\n" - . "- no support material\n" - . "- no ensure_vertical_shell_thickness\n" - . "\nShall I adjust those settings in order to enable Spiral Vase?", - 'Spiral Vase', wxICON_WARNING | wxYES | wxNO); - my $new_conf = Slic3r::Config->new; - if ($dialog->ShowModal() == wxID_YES) { - $new_conf->set("perimeters", 1); - $new_conf->set("top_solid_layers", 0); - $new_conf->set("fill_density", 0); - $new_conf->set("support_material", 0); - $new_conf->set("ensure_vertical_shell_thickness", 0); - } else { - $new_conf->set("spiral_vase", 0); - } - $self->load_config($new_conf); - } - - if ($config->wipe_tower && - ($config->first_layer_height != 0.2 || $config->layer_height < 0.15 || $config->layer_height > 0.35)) { - my $dialog = Wx::MessageDialog->new($self, - "The Wipe Tower currently supports only:\n" - . "- first layer height 0.2mm\n" - . "- layer height from 0.15mm to 0.35mm\n" - . "\nShall I adjust those settings in order to enable the Wipe Tower?", - 'Wipe Tower', wxICON_WARNING | wxYES | wxNO); - my $new_conf = Slic3r::Config->new; - if ($dialog->ShowModal() == wxID_YES) { - $new_conf->set("first_layer_height", 0.2); - $new_conf->set("layer_height", 0.15) if $config->layer_height < 0.15; - $new_conf->set("layer_height", 0.35) if $config->layer_height > 0.35; - } else { - $new_conf->set("wipe_tower", 0); - } - $self->load_config($new_conf); - } - - if ($config->wipe_tower && $config->support_material && $config->support_material_contact_distance > 0. && - ($config->support_material_extruder != 0 || $config->support_material_interface_extruder != 0)) { - my $dialog = Wx::MessageDialog->new($self, - "The Wipe Tower currently supports the non-soluble supports only\n" - . "if they are printed with the current extruder without triggering a tool change.\n" - . "(both support_material_extruder and support_material_interface_extruder need to be set to 0).\n" - . "\nShall I adjust those settings in order to enable the Wipe Tower?", - 'Wipe Tower', wxICON_WARNING | wxYES | wxNO); - my $new_conf = Slic3r::Config->new; - if ($dialog->ShowModal() == wxID_YES) { - $new_conf->set("support_material_extruder", 0); - $new_conf->set("support_material_interface_extruder", 0); - } else { - $new_conf->set("wipe_tower", 0); - } - $self->load_config($new_conf); - } - - if ($config->wipe_tower && $config->support_material && $config->support_material_contact_distance == 0 && - ! $config->support_material_synchronize_layers) { - my $dialog = Wx::MessageDialog->new($self, - "For the Wipe Tower to work with the soluble supports, the support layers\n" - . "need to be synchronized with the object layers.\n" - . "\nShall I synchronize support layers in order to enable the Wipe Tower?", - 'Wipe Tower', wxICON_WARNING | wxYES | wxNO); - my $new_conf = Slic3r::Config->new; - if ($dialog->ShowModal() == wxID_YES) { - $new_conf->set("support_material_synchronize_layers", 1); - } else { - $new_conf->set("wipe_tower", 0); - } - $self->load_config($new_conf); - } - - if ($config->support_material) { - # Ask only once. - if (! $self->{support_material_overhangs_queried}) { - $self->{support_material_overhangs_queried} = 1; - if ($config->overhangs != 1) { - my $dialog = Wx::MessageDialog->new($self, - "Supports work better, if the following feature is enabled:\n" - . "- Detect bridging perimeters\n" - . "\nShall I adjust those settings for supports?", - 'Support Generator', wxICON_WARNING | wxYES | wxNO | wxCANCEL); - my $answer = $dialog->ShowModal(); - my $new_conf = Slic3r::Config->new; - if ($answer == wxID_YES) { - # Enable "detect bridging perimeters". - $new_conf->set("overhangs", 1); - } elsif ($answer == wxID_NO) { - # Do nothing, leave supports on and "detect bridging perimeters" off. - } elsif ($answer == wxID_CANCEL) { - # Disable supports. - $new_conf->set("support_material", 0); - $self->{support_material_overhangs_queried} = 0; - } - $self->load_config($new_conf); - } - } - } else { - $self->{support_material_overhangs_queried} = 0; - } - - if ($config->fill_density == 100 - && !first { $_ eq $config->fill_pattern } @{$Slic3r::Config::Options->{external_fill_pattern}{values}}) { - my $dialog = Wx::MessageDialog->new($self, - "The " . $config->fill_pattern . " infill pattern is not supposed to work at 100% density.\n" - . "\nShall I switch to rectilinear fill pattern?", - 'Infill', wxICON_WARNING | wxYES | wxNO); - - my $new_conf = Slic3r::Config->new; - if ($dialog->ShowModal() == wxID_YES) { - $new_conf->set("fill_pattern", 'rectilinear'); - $new_conf->set("fill_density", 100); - } else { - $new_conf->set("fill_density", 40); - } - $self->load_config($new_conf); - } - - my $have_perimeters = $config->perimeters > 0; - $self->get_field($_)->toggle($have_perimeters) - for qw(extra_perimeters ensure_vertical_shell_thickness thin_walls overhangs seam_position external_perimeters_first - external_perimeter_extrusion_width - perimeter_speed small_perimeter_speed external_perimeter_speed); - - my $have_infill = $config->fill_density > 0; - # infill_extruder uses the same logic as in Print::extruders() - $self->get_field($_)->toggle($have_infill) - for qw(fill_pattern infill_every_layers infill_only_where_needed solid_infill_every_layers - solid_infill_below_area infill_extruder); - - my $have_solid_infill = ($config->top_solid_layers > 0) || ($config->bottom_solid_layers > 0); - # solid_infill_extruder uses the same logic as in Print::extruders() - $self->get_field($_)->toggle($have_solid_infill) - for qw(external_fill_pattern infill_first solid_infill_extruder solid_infill_extrusion_width - solid_infill_speed); - - $self->get_field($_)->toggle($have_infill || $have_solid_infill) - for qw(fill_angle bridge_angle infill_extrusion_width infill_speed bridge_speed); - - $self->get_field('gap_fill_speed')->toggle($have_perimeters && $have_infill); - - my $have_top_solid_infill = $config->top_solid_layers > 0; - $self->get_field($_)->toggle($have_top_solid_infill) - for qw(top_infill_extrusion_width top_solid_infill_speed); - - my $have_default_acceleration = $config->default_acceleration > 0; - $self->get_field($_)->toggle($have_default_acceleration) - for qw(perimeter_acceleration infill_acceleration bridge_acceleration first_layer_acceleration); - - my $have_skirt = $config->skirts > 0 || $config->min_skirt_length > 0; - $self->get_field($_)->toggle($have_skirt) - for qw(skirt_distance skirt_height); - - my $have_brim = $config->brim_width > 0; - # perimeter_extruder uses the same logic as in Print::extruders() - $self->get_field('perimeter_extruder')->toggle($have_perimeters || $have_brim); - - my $have_raft = $config->raft_layers > 0; - my $have_support_material = $config->support_material || $have_raft; - my $have_support_interface = $config->support_material_interface_layers > 0; - my $have_support_soluble = $have_support_material && $config->support_material_contact_distance == 0; - $self->get_field($_)->toggle($have_support_material) - for qw(support_material_threshold support_material_pattern support_material_with_sheath - support_material_spacing support_material_angle - support_material_interface_layers dont_support_bridges - support_material_extrusion_width support_material_contact_distance support_material_xy_spacing); - $self->get_field($_)->toggle($have_support_material && $have_support_interface) - for qw(support_material_interface_spacing support_material_interface_extruder - support_material_interface_speed support_material_interface_contact_loops); - $self->get_field('support_material_synchronize_layers')->toggle($have_support_soluble); - - $self->get_field('perimeter_extrusion_width')->toggle($have_perimeters || $have_skirt || $have_brim); - $self->get_field('support_material_extruder')->toggle($have_support_material || $have_skirt); - $self->get_field('support_material_speed')->toggle($have_support_material || $have_brim || $have_skirt); - - my $have_sequential_printing = $config->complete_objects; - $self->get_field($_)->toggle($have_sequential_printing) - for qw(extruder_clearance_radius extruder_clearance_height); - - my $have_ooze_prevention = $config->ooze_prevention; - $self->get_field($_)->toggle($have_ooze_prevention) - for qw(standby_temperature_delta); - - my $have_wipe_tower = $config->wipe_tower; - $self->get_field($_)->toggle($have_wipe_tower) - for qw(wipe_tower_x wipe_tower_y wipe_tower_width wipe_tower_per_color_wipe); - - $self->{recommended_thin_wall_thickness_description_line}->SetText( - Slic3r::GUI::PresetHints::recommended_thin_wall_thickness(wxTheApp->{preset_bundle})); - - $self->Thaw; -} - -# Update on activation to recalculate the estimates if the nozzle diameter changed -# and the extrusion width values were left to zero (automatic, nozzle dependent). -sub OnActivate { - my ($self) = @_; - $self->{recommended_thin_wall_thickness_description_line}->SetText( - Slic3r::GUI::PresetHints::recommended_thin_wall_thickness(wxTheApp->{preset_bundle})); -} - -package Slic3r::GUI::Tab::Filament; -use base 'Slic3r::GUI::Tab'; -use Wx qw(wxTheApp); - -sub name { 'filament' } -sub title { 'Filament Settings' } - -sub build { - my $self = shift; - - $self->{presets} = wxTheApp->{preset_bundle}->filament; - $self->{config} = $self->{presets}->get_edited_preset->config; - - { - my $page = $self->add_options_page('Filament', 'spool.png'); - { - my $optgroup = $page->new_optgroup('Filament'); - $optgroup->append_single_option_line('filament_colour', 0); - $optgroup->append_single_option_line('filament_diameter', 0); - $optgroup->append_single_option_line('extrusion_multiplier', 0); - $optgroup->append_single_option_line('filament_density', 0); - $optgroup->append_single_option_line('filament_cost', 0); - } - - { - my $optgroup = $page->new_optgroup('Temperature (°C)'); - - { - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => 'Extruder', - ); - $line->append_option($optgroup->get_option('first_layer_temperature', 0)); - $line->append_option($optgroup->get_option('temperature', 0)); - $optgroup->append_line($line); - } - - { - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => 'Bed', - ); - $line->append_option($optgroup->get_option('first_layer_bed_temperature', 0)); - $line->append_option($optgroup->get_option('bed_temperature', 0)); - $optgroup->append_line($line); - } - } - } - - { - my $page = $self->add_options_page('Cooling', 'hourglass.png'); - { - my $optgroup = $page->new_optgroup('Enable'); - $optgroup->append_single_option_line('fan_always_on', 0); - $optgroup->append_single_option_line('cooling', 0); - - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => '', - full_width => 1, - widget => sub { - my ($parent) = @_; - return $self->{cooling_description_line} = Slic3r::GUI::OptionsGroup::StaticText->new($parent); - }, - ); - $optgroup->append_line($line); - } - { - my $optgroup = $page->new_optgroup('Fan settings'); - - { - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => 'Fan speed', - ); - $line->append_option($optgroup->get_option('min_fan_speed', 0)); - $line->append_option($optgroup->get_option('max_fan_speed', 0)); - $optgroup->append_line($line); - } - - $optgroup->append_single_option_line('bridge_fan_speed', 0); - $optgroup->append_single_option_line('disable_fan_first_layers', 0); - } - { - my $optgroup = $page->new_optgroup('Cooling thresholds', - label_width => 250, - ); - $optgroup->append_single_option_line('fan_below_layer_time', 0); - $optgroup->append_single_option_line('slowdown_below_layer_time', 0); - $optgroup->append_single_option_line('min_print_speed', 0); - } - } - - { - my $page = $self->add_options_page('Advanced', 'wrench.png'); - { - my $optgroup = $page->new_optgroup('Filament properties'); - $optgroup->append_single_option_line('filament_type', 0); - $optgroup->append_single_option_line('filament_soluble', 0); - - $optgroup = $page->new_optgroup('Print speed override'); - $optgroup->append_single_option_line('filament_max_volumetric_speed', 0); - - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => '', - full_width => 1, - widget => sub { - my ($parent) = @_; - return $self->{volumetric_speed_description_line} = Slic3r::GUI::OptionsGroup::StaticText->new($parent); - }, - ); - $optgroup->append_line($line); - } - } - - { - my $page = $self->add_options_page('Custom G-code', 'cog.png'); - { - my $optgroup = $page->new_optgroup('Start G-code', - label_width => 0, - ); - my $option = $optgroup->get_option('start_filament_gcode', 0); - $option->full_width(1); - $option->height(150); - $optgroup->append_single_option_line($option); - } - { - my $optgroup = $page->new_optgroup('End G-code', - label_width => 0, - ); - my $option = $optgroup->get_option('end_filament_gcode', 0); - $option->full_width(1); - $option->height(150); - $optgroup->append_single_option_line($option); - } - } - - { - my $page = $self->add_options_page('Notes', 'note.png'); - { - my $optgroup = $page->new_optgroup('Notes', - label_width => 0, - ); - my $option = $optgroup->get_option('filament_notes', 0); - $option->full_width(1); - $option->height(250); - $optgroup->append_single_option_line($option); - } - } - - { - my $page = $self->add_options_page('Dependencies', 'wrench.png'); - { - my $optgroup = $page->new_optgroup('Profile dependencies'); - { - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => 'Compatible printers', - widget => $self->_compatible_printers_widget, - ); - $optgroup->append_line($line); - - my $option = $optgroup->get_option('compatible_printers_condition'); - $option->full_width(1); - $optgroup->append_single_option_line($option); - } - } - } -} - -# Reload current $self->{config} (aka $self->{presets}->edited_preset->config) into the UI fields. -sub _reload_config { - my ($self) = @_; - $self->_reload_compatible_printers_widget; - $self->SUPER::_reload_config; -} - -# Slic3r::GUI::Tab::Filament::_update is called after a configuration preset is loaded or switched, or when a single option is modifed by the user. -sub _update { - my ($self) = @_; - - $self->{cooling_description_line}->SetText( - Slic3r::GUI::PresetHints::cooling_description($self->{presets}->get_edited_preset)); - $self->{volumetric_speed_description_line}->SetText( - Slic3r::GUI::PresetHints::maximum_volumetric_flow_description(wxTheApp->{preset_bundle})); - - my $cooling = $self->{config}->cooling->[0]; - my $fan_always_on = $cooling || $self->{config}->fan_always_on->[0]; - $self->get_field($_, 0)->toggle($cooling) - for qw(max_fan_speed fan_below_layer_time slowdown_below_layer_time min_print_speed); - $self->get_field($_, 0)->toggle($fan_always_on) - for qw(min_fan_speed disable_fan_first_layers); -} - -sub OnActivate { - my ($self) = @_; - $self->{volumetric_speed_description_line}->SetText( - Slic3r::GUI::PresetHints::maximum_volumetric_flow_description(wxTheApp->{preset_bundle})); -} - -package Slic3r::GUI::Tab::Printer; -use base 'Slic3r::GUI::Tab'; -use Wx qw(wxTheApp :sizer :button :bitmap :misc :id :icon :dialog); -use Wx::Event qw(EVT_BUTTON); - -sub name { 'printer' } -sub title { 'Printer Settings' } - -sub build { - my ($self, %params) = @_; - - $self->{presets} = wxTheApp->{preset_bundle}->printer; - $self->{config} = $self->{presets}->get_edited_preset->config; - $self->{extruders_count} = scalar @{$self->{config}->nozzle_diameter}; - - my $bed_shape_widget = sub { - my ($parent) = @_; - - my $btn = Wx::Button->new($parent, -1, "Set…", wxDefaultPosition, wxDefaultSize, - wxBU_LEFT | wxBU_EXACTFIT); - $btn->SetFont($Slic3r::GUI::small_font); - $btn->SetBitmap(Wx::Bitmap->new(Slic3r::var("printer_empty.png"), wxBITMAP_TYPE_PNG)); - - my $sizer = Wx::BoxSizer->new(wxHORIZONTAL); - $sizer->Add($btn); - - EVT_BUTTON($self, $btn, sub { - my $dlg = Slic3r::GUI::BedShapeDialog->new($self, $self->{config}->bed_shape); - $self->_load_key_value('bed_shape', $dlg->GetValue) if $dlg->ShowModal == wxID_OK; - }); - - return $sizer; - }; - - { - my $page = $self->add_options_page('General', 'printer_empty.png'); - { - my $optgroup = $page->new_optgroup('Size and coordinates'); - - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => 'Bed shape', - widget => $bed_shape_widget, - ); - $optgroup->append_line($line); - - $optgroup->append_single_option_line('z_offset'); - } - { - my $optgroup = $page->new_optgroup('Capabilities'); - { - my $option = Slic3r::GUI::OptionsGroup::Option->new( - opt_id => 'extruders_count', - type => 'i', - default => 1, - label => 'Extruders', - tooltip => 'Number of extruders of the printer.', - min => 1, - ); - $optgroup->append_single_option_line($option); - $optgroup->append_single_option_line('single_extruder_multi_material'); - } - $optgroup->on_change(sub { - my ($opt_key, $value) = @_; - wxTheApp->CallAfter(sub { - if ($opt_key eq 'extruders_count') { - $self->_extruders_count_changed($optgroup->get_value('extruders_count')); - $self->update_dirty; - } else { - $self->update_dirty; - $self->_on_value_change($opt_key, $value); - } - }); - }); - } - if (!$params{no_controller}) - { - my $optgroup = $page->new_optgroup('USB/Serial connection'); - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => 'Serial port', - ); - my $serial_port = $optgroup->get_option('serial_port'); - $serial_port->side_widget(sub { - my ($parent) = @_; - - my $btn = Wx::BitmapButton->new($parent, -1, Wx::Bitmap->new(Slic3r::var("arrow_rotate_clockwise.png"), wxBITMAP_TYPE_PNG), - wxDefaultPosition, wxDefaultSize, &Wx::wxBORDER_NONE); - $btn->SetToolTipString("Rescan serial ports") - if $btn->can('SetToolTipString'); - EVT_BUTTON($self, $btn, \&_update_serial_ports); - - return $btn; - }); - my $serial_test = sub { - my ($parent) = @_; - - my $btn = $self->{serial_test_btn} = Wx::Button->new($parent, -1, - "Test", wxDefaultPosition, wxDefaultSize, wxBU_LEFT | wxBU_EXACTFIT); - $btn->SetFont($Slic3r::GUI::small_font); - $btn->SetBitmap(Wx::Bitmap->new(Slic3r::var("wrench.png"), wxBITMAP_TYPE_PNG)); - - EVT_BUTTON($self, $btn, sub { - my $sender = Slic3r::GCode::Sender->new; - my $res = $sender->connect( - $self->{config}->serial_port, - $self->{config}->serial_speed, - ); - if ($res && $sender->wait_connected) { - Slic3r::GUI::show_info($self, "Connection to printer works correctly.", "Success!"); - } else { - Slic3r::GUI::show_error($self, "Connection failed."); - } - }); - return $btn; - }; - $line->append_option($serial_port); - $line->append_option($optgroup->get_option('serial_speed')); - $line->append_widget($serial_test); - $optgroup->append_line($line); - } - { - my $optgroup = $page->new_optgroup('OctoPrint upload'); - - # append two buttons to the Host line - my $octoprint_host_browse = sub { - my ($parent) = @_; - - my $btn = Wx::Button->new($parent, -1, "Browse…", wxDefaultPosition, wxDefaultSize, wxBU_LEFT); - $btn->SetFont($Slic3r::GUI::small_font); - $btn->SetBitmap(Wx::Bitmap->new(Slic3r::var("zoom.png"), wxBITMAP_TYPE_PNG)); - - if (!eval "use Net::Bonjour; 1") { - $btn->Disable; - } - - EVT_BUTTON($self, $btn, sub { - # look for devices - my $entries; - { - my $res = Net::Bonjour->new('http'); - $res->discover; - $entries = [ $res->entries ]; - } - if (@{$entries}) { - my $dlg = Slic3r::GUI::BonjourBrowser->new($self, $entries); - $self->_load_key_value('octoprint_host', $dlg->GetValue . ":" . $dlg->GetPort) - if $dlg->ShowModal == wxID_OK; - } else { - Wx::MessageDialog->new($self, 'No Bonjour device found', 'Device Browser', wxOK | wxICON_INFORMATION)->ShowModal; - } - }); - - return $btn; - }; - my $octoprint_host_test = sub { - my ($parent) = @_; - - my $btn = $self->{octoprint_host_test_btn} = Wx::Button->new($parent, -1, - "Test", wxDefaultPosition, wxDefaultSize, wxBU_LEFT | wxBU_EXACTFIT); - $btn->SetFont($Slic3r::GUI::small_font); - $btn->SetBitmap(Wx::Bitmap->new(Slic3r::var("wrench.png"), wxBITMAP_TYPE_PNG)); - - EVT_BUTTON($self, $btn, sub { - my $ua = LWP::UserAgent->new; - $ua->timeout(10); - - my $res = $ua->get( - "http://" . $self->{config}->octoprint_host . "/api/version", - 'X-Api-Key' => $self->{config}->octoprint_apikey, - ); - if ($res->is_success) { - Slic3r::GUI::show_info($self, "Connection to OctoPrint works correctly.", "Success!"); - } else { - Slic3r::GUI::show_error($self, - "I wasn't able to connect to OctoPrint (" . $res->status_line . "). " - . "Check hostname and OctoPrint version (at least 1.1.0 is required)."); - } - }); - return $btn; - }; - - my $host_line = $optgroup->create_single_option_line('octoprint_host'); - $host_line->append_widget($octoprint_host_browse); - $host_line->append_widget($octoprint_host_test); - $optgroup->append_line($host_line); - $optgroup->append_single_option_line('octoprint_apikey'); - } - { - my $optgroup = $page->new_optgroup('Firmware'); - $optgroup->append_single_option_line('gcode_flavor'); - } - { - my $optgroup = $page->new_optgroup('Advanced'); - $optgroup->append_single_option_line('use_relative_e_distances'); - $optgroup->append_single_option_line('use_firmware_retraction'); - $optgroup->append_single_option_line('use_volumetric_e'); - $optgroup->append_single_option_line('variable_layer_height'); - } - } - { - my $page = $self->add_options_page('Custom G-code', 'cog.png'); - { - my $optgroup = $page->new_optgroup('Start G-code', - label_width => 0, - ); - my $option = $optgroup->get_option('start_gcode'); - $option->full_width(1); - $option->height(150); - $optgroup->append_single_option_line($option); - } - { - my $optgroup = $page->new_optgroup('End G-code', - label_width => 0, - ); - my $option = $optgroup->get_option('end_gcode'); - $option->full_width(1); - $option->height(150); - $optgroup->append_single_option_line($option); - } - { - my $optgroup = $page->new_optgroup('Before layer change G-code', - label_width => 0, - ); - my $option = $optgroup->get_option('before_layer_gcode'); - $option->full_width(1); - $option->height(150); - $optgroup->append_single_option_line($option); - } - { - my $optgroup = $page->new_optgroup('After layer change G-code', - label_width => 0, - ); - my $option = $optgroup->get_option('layer_gcode'); - $option->full_width(1); - $option->height(150); - $optgroup->append_single_option_line($option); - } - { - my $optgroup = $page->new_optgroup('Tool change G-code', - label_width => 0, - ); - my $option = $optgroup->get_option('toolchange_gcode'); - $option->full_width(1); - $option->height(150); - $optgroup->append_single_option_line($option); - } - { - my $optgroup = $page->new_optgroup('Between objects G-code (for sequential printing)', - label_width => 0, - ); - my $option = $optgroup->get_option('between_objects_gcode'); - $option->full_width(1); - $option->height(150); - $optgroup->append_single_option_line($option); - } - } - - { - my $page = $self->add_options_page('Notes', 'note.png'); - { - my $optgroup = $page->new_optgroup('Notes', - label_width => 0, - ); - my $option = $optgroup->get_option('printer_notes'); - $option->full_width(1); - $option->height(250); - $optgroup->append_single_option_line($option); - } - } - - $self->{extruder_pages} = []; - $self->_build_extruder_pages; - - $self->_update_serial_ports if (!$params{no_controller}); -} - -sub _update_serial_ports { - my ($self) = @_; - - $self->get_field('serial_port')->set_values([ Slic3r::GUI::scan_serial_ports ]); -} - -sub _extruders_count_changed { - my ($self, $extruders_count) = @_; - $self->{extruders_count} = $extruders_count; - wxTheApp->{preset_bundle}->printer->get_edited_preset->set_num_extruders($extruders_count); - wxTheApp->{preset_bundle}->update_multi_material_filament_presets; - $self->_build_extruder_pages; - $self->_on_value_change('extruders_count', $extruders_count); -} - -sub _build_extruder_pages { - my ($self) = @_; - my $default_config = Slic3r::Config::Full->new; - - foreach my $extruder_idx (@{$self->{extruder_pages}} .. $self->{extruders_count}-1) { - # build page - my $page = $self->{extruder_pages}[$extruder_idx] = $self->add_options_page("Extruder " . ($extruder_idx + 1), 'funnel.png'); - { - my $optgroup = $page->new_optgroup('Size'); - $optgroup->append_single_option_line('nozzle_diameter', $extruder_idx); - } - { - my $optgroup = $page->new_optgroup('Layer height limits'); - $optgroup->append_single_option_line($_, $extruder_idx) - for qw(min_layer_height max_layer_height); - } - { - my $optgroup = $page->new_optgroup('Position (for multi-extruder printers)'); - $optgroup->append_single_option_line('extruder_offset', $extruder_idx); - } - { - my $optgroup = $page->new_optgroup('Retraction'); - $optgroup->append_single_option_line($_, $extruder_idx) - for qw(retract_length retract_lift); - - { - my $line = Slic3r::GUI::OptionsGroup::Line->new( - label => 'Only lift Z', - ); - $line->append_option($optgroup->get_option('retract_lift_above', $extruder_idx)); - $line->append_option($optgroup->get_option('retract_lift_below', $extruder_idx)); - $optgroup->append_line($line); - } - - $optgroup->append_single_option_line($_, $extruder_idx) - for qw(retract_speed deretract_speed retract_restart_extra retract_before_travel retract_layer_change wipe retract_before_wipe); - } - { - my $optgroup = $page->new_optgroup('Retraction when tool is disabled (advanced settings for multi-extruder setups)'); - $optgroup->append_single_option_line($_, $extruder_idx) - for qw(retract_length_toolchange retract_restart_extra_toolchange); - } - { - my $optgroup = $page->new_optgroup('Preview'); - $optgroup->append_single_option_line('extruder_colour', $extruder_idx); - } - } - - # remove extra pages - if ($self->{extruders_count} <= $#{$self->{extruder_pages}}) { - $_->Destroy for @{$self->{extruder_pages}}[$self->{extruders_count}..$#{$self->{extruder_pages}}]; - splice @{$self->{extruder_pages}}, $self->{extruders_count}; - } - - # rebuild page list - my @pages_without_extruders = (grep $_->{title} !~ /^Extruder \d+/, @{$self->{pages}}); - my $page_notes = pop @pages_without_extruders; - @{$self->{pages}} = ( - @pages_without_extruders, - @{$self->{extruder_pages}}[ 0 .. $self->{extruders_count}-1 ], - $page_notes - ); - $self->rebuild_page_tree; -} - -# Slic3r::GUI::Tab::Printer::_update is called after a configuration preset is loaded or switched, or when a single option is modifed by the user. -sub _update { - my ($self) = @_; - $self->Freeze; - - my $config = $self->{config}; - - my $serial_speed = $self->get_field('serial_speed'); - if ($serial_speed) { - $self->get_field('serial_speed')->toggle($config->get('serial_port')); - if ($config->get('serial_speed') && $config->get('serial_port')) { - $self->{serial_test_btn}->Enable; - } else { - $self->{serial_test_btn}->Disable; - } - } - if ($config->get('octoprint_host') && eval "use LWP::UserAgent; 1") { - $self->{octoprint_host_test_btn}->Enable; - } else { - $self->{octoprint_host_test_btn}->Disable; - } - $self->get_field('octoprint_apikey')->toggle($config->get('octoprint_host')); - - my $have_multiple_extruders = $self->{extruders_count} > 1; - $self->get_field('toolchange_gcode')->toggle($have_multiple_extruders); - $self->get_field('single_extruder_multi_material')->toggle($have_multiple_extruders); - - for my $i (0 .. ($self->{extruders_count}-1)) { - my $have_retract_length = $config->get_at('retract_length', $i) > 0; - - # when using firmware retraction, firmware decides retraction length - $self->get_field('retract_length', $i)->toggle(!$config->use_firmware_retraction); - - # user can customize travel length if we have retraction length or we're using - # firmware retraction - $self->get_field('retract_before_travel', $i)->toggle($have_retract_length || $config->use_firmware_retraction); - - # user can customize other retraction options if retraction is enabled - my $retraction = ($have_retract_length || $config->use_firmware_retraction); - $self->get_field($_, $i)->toggle($retraction) - for qw(retract_lift retract_layer_change); - - # retract lift above/below only applies if using retract lift - $self->get_field($_, $i)->toggle($retraction && $config->get_at('retract_lift', $i) > 0) - for qw(retract_lift_above retract_lift_below); - - # some options only apply when not using firmware retraction - $self->get_field($_, $i)->toggle($retraction && !$config->use_firmware_retraction) - for qw(retract_speed deretract_speed retract_before_wipe retract_restart_extra wipe); - - my $wipe = $config->get_at('wipe', $i); - $self->get_field('retract_before_wipe', $i)->toggle($wipe); - - if ($config->use_firmware_retraction && $wipe) { - my $dialog = Wx::MessageDialog->new($self, - "The Wipe option is not available when using the Firmware Retraction mode.\n" - . "\nShall I disable it in order to enable Firmware Retraction?", - 'Firmware Retraction', wxICON_WARNING | wxYES | wxNO); - - my $new_conf = Slic3r::Config->new; - if ($dialog->ShowModal() == wxID_YES) { - my $wipe = $config->wipe; - $wipe->[$i] = 0; - $new_conf->set("wipe", $wipe); - } else { - $new_conf->set("use_firmware_retraction", 0); - } - $self->load_config($new_conf); - } - - $self->get_field('retract_length_toolchange', $i)->toggle($have_multiple_extruders); - - my $toolchange_retraction = $config->get_at('retract_length_toolchange', $i) > 0; - $self->get_field('retract_restart_extra_toolchange', $i)->toggle - ($have_multiple_extruders && $toolchange_retraction); - } - - $self->Thaw; -} - -# this gets executed after preset is loaded and before GUI fields are updated -sub on_preset_loaded { - my ($self) = @_; - # update the extruders count field - my $extruders_count = scalar @{ $self->{config}->nozzle_diameter }; - $self->set_value('extruders_count', $extruders_count); - # update the GUI field according to the number of nozzle diameters supplied - $self->_extruders_count_changed($extruders_count); -} - -# Single Tab page containing a {vsizer} of {optgroups} -package Slic3r::GUI::Tab::Page; -use Wx qw(wxTheApp :misc :panel :sizer); -use base 'Wx::ScrolledWindow'; - -sub new { - my ($class, $parent, $title, $iconID) = @_; - my $self = $class->SUPER::new($parent, -1, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); - $self->{optgroups} = []; - $self->{title} = $title; - $self->{iconID} = $iconID; - - $self->SetScrollbars(1, 1, 1, 1); - - $self->{vsizer} = Wx::BoxSizer->new(wxVERTICAL); - $self->SetSizer($self->{vsizer}); - - return $self; -} - -sub new_optgroup { - my ($self, $title, %params) = @_; - - my $optgroup = Slic3r::GUI::ConfigOptionsGroup->new( - parent => $self, - title => $title, - config => $self->GetParent->{config}, - label_width => $params{label_width} // 200, - on_change => sub { - my ($opt_key, $value) = @_; - wxTheApp->CallAfter(sub { - $self->GetParent->update_dirty; - $self->GetParent->_on_value_change($opt_key, $value); - }); - }, - ); - - push @{$self->{optgroups}}, $optgroup; - $self->{vsizer}->Add($optgroup->sizer, 0, wxEXPAND | wxALL, 10); - - return $optgroup; -} - -sub reload_config { - my ($self) = @_; - $_->reload_config for @{$self->{optgroups}}; -} - -sub get_field { - my ($self, $opt_key, $opt_index) = @_; - foreach my $optgroup (@{ $self->{optgroups} }) { - my $field = $optgroup->get_fieldc($opt_key, $opt_index); - return $field if defined $field; - } - return undef; -} - -sub set_value { - my ($self, $opt_key, $value) = @_; - my $changed = 0; - foreach my $optgroup (@{$self->{optgroups}}) { - $changed = 1 if $optgroup->set_value($opt_key, $value); - } - return $changed; -} - -# Dialog to select a new file name for a modified preset to be saved. -# Called from Tab::save_preset(). -package Slic3r::GUI::SavePresetWindow; -use Wx qw(:combobox :dialog :id :misc :sizer); -use Wx::Event qw(EVT_BUTTON EVT_TEXT_ENTER); -use base 'Wx::Dialog'; - -sub new { - my ($class, $parent, %params) = @_; - my $self = $class->SUPER::new($parent, -1, "Save preset", wxDefaultPosition, wxDefaultSize); - - my @values = @{$params{values}}; - - my $text = Wx::StaticText->new($self, -1, "Save " . lc($params{title}) . " as:", wxDefaultPosition, wxDefaultSize); - $self->{combo} = Wx::ComboBox->new($self, -1, $params{default}, wxDefaultPosition, wxDefaultSize, \@values, - wxTE_PROCESS_ENTER); - my $buttons = $self->CreateStdDialogButtonSizer(wxOK | wxCANCEL); - - my $sizer = Wx::BoxSizer->new(wxVERTICAL); - $sizer->Add($text, 0, wxEXPAND | wxTOP | wxLEFT | wxRIGHT, 10); - $sizer->Add($self->{combo}, 0, wxEXPAND | wxLEFT | wxRIGHT, 10); - $sizer->Add($buttons, 0, wxEXPAND | wxBOTTOM | wxLEFT | wxRIGHT, 10); - - EVT_BUTTON($self, wxID_OK, \&accept); - EVT_TEXT_ENTER($self, $self->{combo}, \&accept); - - $self->SetSizer($sizer); - $sizer->SetSizeHints($self); - - return $self; -} - -sub accept { - my ($self, $event) = @_; - if (($self->{chosen_name} = Slic3r::normalize_utf8_nfc($self->{combo}->GetValue))) { - if ($self->{chosen_name} !~ /^[^<>:\/\\|?*\"]+$/) { - Slic3r::GUI::show_error($self, "The supplied name is not valid; the following characters are not allowed: <>:/\|?*\""); - } elsif ($self->{chosen_name} eq '- default -') { - Slic3r::GUI::show_error($self, "The supplied name is not available."); - } else { - $self->EndModal(wxID_OK); - } - } -} - -sub get_name { - my ($self) = @_; - return $self->{chosen_name}; -} - -1; diff --git a/xs/lib/Slic3r/XS.pm b/xs/lib/Slic3r/XS.pm index c43b80eea..47a584343 100644 --- a/xs/lib/Slic3r/XS.pm +++ b/xs/lib/Slic3r/XS.pm @@ -283,7 +283,7 @@ for my $class (qw( Slic3r::GUI::_3DScene::GLVolume Slic3r::GUI::Preset Slic3r::GUI::PresetCollection - Slic3r::GUI::Tab2 + Slic3r::GUI::Tab Slic3r::Layer Slic3r::Layer::Region Slic3r::Layer::Support diff --git a/xs/src/perlglue.cpp b/xs/src/perlglue.cpp index f7b4bf0c0..cb2ef7368 100644 --- a/xs/src/perlglue.cpp +++ b/xs/src/perlglue.cpp @@ -63,7 +63,7 @@ REGISTER_CLASS(Preset, "GUI::Preset"); REGISTER_CLASS(PresetCollection, "GUI::PresetCollection"); REGISTER_CLASS(PresetBundle, "GUI::PresetBundle"); REGISTER_CLASS(PresetHints, "GUI::PresetHints"); -REGISTER_CLASS(TabIface, "GUI::Tab2"); +REGISTER_CLASS(TabIface, "GUI::Tab"); SV* ConfigBase__as_hash(ConfigBase* THIS) { diff --git a/xs/xsp/GUI_Tab.xsp b/xs/xsp/GUI_Tab.xsp index f38d63143..9cacac74f 100644 --- a/xs/xsp/GUI_Tab.xsp +++ b/xs/xsp/GUI_Tab.xsp @@ -5,7 +5,7 @@ #include "slic3r/GUI/TabIface.hpp" %} -%name{Slic3r::GUI::Tab2} class TabIface { +%name{Slic3r::GUI::Tab} class TabIface { TabIface(); ~TabIface(); void load_current_preset(); From 4ee620b57d686bd4bb860fdbc4d3d03892b85e54 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Thu, 15 Feb 2018 18:41:37 +0100 Subject: [PATCH 55/57] Fixed Perl dependencies after some obsolete modules were removed. --- lib/Slic3r/GUI.pm | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/Slic3r/GUI.pm b/lib/Slic3r/GUI.pm index 9d7adbc9d..0b4f9743a 100644 --- a/lib/Slic3r/GUI.pm +++ b/lib/Slic3r/GUI.pm @@ -8,7 +8,6 @@ use FindBin; use List::Util qw(first); use Slic3r::GUI::2DBed; use Slic3r::GUI::AboutDialog; -use Slic3r::GUI::BedShapeDialog; use Slic3r::GUI::BonjourBrowser; use Slic3r::GUI::ConfigWizard; use Slic3r::GUI::Controller; @@ -31,7 +30,6 @@ use Slic3r::GUI::ProgressStatusBar; use Slic3r::GUI::OptionsGroup; use Slic3r::GUI::OptionsGroup::Field; use Slic3r::GUI::SystemInfo; -use Slic3r::GUI::Tab; our $have_OpenGL = eval "use Slic3r::GUI::3DScene; 1"; our $have_LWP = eval "use LWP::UserAgent; 1"; From 8dd5fe83fcad2f46aedb1da29747c820a58ddb79 Mon Sep 17 00:00:00 2001 From: bubnikv Date: Fri, 16 Feb 2018 17:20:34 +0100 Subject: [PATCH 56/57] Humbly re-added the BedShapeDialog.pm. Even though we have a C++ implementation now, the Perl BedShapeDialog.pm is used by the wizard. --- lib/Slic3r/GUI.pm | 1 + lib/Slic3r/GUI/BedShapeDialog.pm | 316 +++++++++++++++++++++++++++++++ 2 files changed, 317 insertions(+) create mode 100644 lib/Slic3r/GUI/BedShapeDialog.pm diff --git a/lib/Slic3r/GUI.pm b/lib/Slic3r/GUI.pm index 0b4f9743a..54a27dc99 100644 --- a/lib/Slic3r/GUI.pm +++ b/lib/Slic3r/GUI.pm @@ -8,6 +8,7 @@ use FindBin; use List::Util qw(first); use Slic3r::GUI::2DBed; use Slic3r::GUI::AboutDialog; +use Slic3r::GUI::BedShapeDialog; use Slic3r::GUI::BonjourBrowser; use Slic3r::GUI::ConfigWizard; use Slic3r::GUI::Controller; diff --git a/lib/Slic3r/GUI/BedShapeDialog.pm b/lib/Slic3r/GUI/BedShapeDialog.pm new file mode 100644 index 000000000..70c8e0256 --- /dev/null +++ b/lib/Slic3r/GUI/BedShapeDialog.pm @@ -0,0 +1,316 @@ +# The bed shape dialog. +# The dialog opens from Print Settins tab -> Bed Shape: Set... + +package Slic3r::GUI::BedShapeDialog; +use strict; +use warnings; +use utf8; + +use List::Util qw(min max); +use Slic3r::Geometry qw(X Y unscale); +use Wx qw(:dialog :id :misc :sizer :choicebook wxTAB_TRAVERSAL); +use Wx::Event qw(EVT_CLOSE); +use base 'Wx::Dialog'; + +sub new { + my $class = shift; + my ($parent, $default) = @_; + my $self = $class->SUPER::new($parent, -1, "Bed Shape", wxDefaultPosition, [350,700], wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER); + + $self->{panel} = my $panel = Slic3r::GUI::BedShapePanel->new($self, $default); + + my $main_sizer = Wx::BoxSizer->new(wxVERTICAL); + $main_sizer->Add($panel, 1, wxEXPAND); + $main_sizer->Add($self->CreateButtonSizer(wxOK | wxCANCEL), 0, wxEXPAND); + + $self->SetSizer($main_sizer); + $self->SetMinSize($self->GetSize); + $main_sizer->SetSizeHints($self); + + # needed to actually free memory + EVT_CLOSE($self, sub { + $self->EndModal(wxID_OK); + $self->Destroy; + }); + + return $self; +} + +sub GetValue { + my ($self) = @_; + return $self->{panel}->GetValue; +} + +package Slic3r::GUI::BedShapePanel; + +use List::Util qw(min max sum first); +use Scalar::Util qw(looks_like_number); +use Slic3r::Geometry qw(PI X Y unscale scaled_epsilon); +use Wx qw(:font :id :misc :sizer :choicebook :filedialog :pen :brush wxTAB_TRAVERSAL); +use Wx::Event qw(EVT_CLOSE EVT_CHOICEBOOK_PAGE_CHANGED EVT_BUTTON); +use base 'Wx::Panel'; + +use constant SHAPE_RECTANGULAR => 0; +use constant SHAPE_CIRCULAR => 1; +use constant SHAPE_CUSTOM => 2; + +sub new { + my $class = shift; + my ($parent, $default) = @_; + my $self = $class->SUPER::new($parent, -1); + + $self->on_change(undef); + + my $box = Wx::StaticBox->new($self, -1, "Shape"); + my $sbsizer = Wx::StaticBoxSizer->new($box, wxVERTICAL); + + # shape options + $self->{shape_options_book} = Wx::Choicebook->new($self, -1, wxDefaultPosition, [300,-1], wxCHB_TOP); + $sbsizer->Add($self->{shape_options_book}); + + $self->{optgroups} = []; + { + my $optgroup = $self->_init_shape_options_page('Rectangular'); + $optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new( + opt_id => 'rect_size', + type => 'point', + label => 'Size', + tooltip => 'Size in X and Y of the rectangular plate.', + default => [200,200], + )); + $optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new( + opt_id => 'rect_origin', + type => 'point', + label => 'Origin', + tooltip => 'Distance of the 0,0 G-code coordinate from the front left corner of the rectangle.', + default => [0,0], + )); + } + { + my $optgroup = $self->_init_shape_options_page('Circular'); + $optgroup->append_single_option_line(Slic3r::GUI::OptionsGroup::Option->new( + opt_id => 'diameter', + type => 'f', + label => 'Diameter', + tooltip => 'Diameter of the print bed. It is assumed that origin (0,0) is located in the center.', + sidetext => 'mm', + default => 200, + )); + } + { + my $optgroup = $self->_init_shape_options_page('Custom'); + $optgroup->append_line(Slic3r::GUI::OptionsGroup::Line->new( + full_width => 1, + widget => sub { + my ($parent) = @_; + + my $btn = Wx::Button->new($parent, -1, "Load shape from STL...", wxDefaultPosition, wxDefaultSize); + EVT_BUTTON($self, $btn, sub { $self->_load_stl }); + return $btn; + } + )); + } + + EVT_CHOICEBOOK_PAGE_CHANGED($self, -1, sub { + $self->_update_shape; + }); + + # right pane with preview canvas + my $canvas = $self->{canvas} = Slic3r::GUI::2DBed->new($self); + + # main sizer + my $top_sizer = Wx::BoxSizer->new(wxHORIZONTAL); + $top_sizer->Add($sbsizer, 0, wxEXPAND | wxTOP | wxBOTTOM, 10); + $top_sizer->Add($canvas, 1, wxEXPAND | wxALL, 10) if $canvas; + + $self->SetSizerAndFit($top_sizer); + + $self->_set_shape($default); + $self->_update_preview; + + return $self; +} + +sub on_change { + my ($self, $cb) = @_; + $self->{on_change} = $cb // sub {}; +} + +# Called from the constructor. +# Set the initial bed shape from a list of points. +# Deduce the bed shape type (rect, circle, custom) +# This routine shall be smart enough if the user messes up +# with the list of points in the ini file directly. +sub _set_shape { + my ($self, $points) = @_; + + # is this a rectangle? + if (@$points == 4) { + my $polygon = Slic3r::Polygon->new_scale(@$points); + my $lines = $polygon->lines; + if ($lines->[0]->parallel_to_line($lines->[2]) && $lines->[1]->parallel_to_line($lines->[3])) { + # okay, it's a rectangle + + # find origin + # the || 0 hack prevents "-0" which might confuse the user + my $x_min = min(map $_->[X], @$points) || 0; + my $x_max = max(map $_->[X], @$points) || 0; + my $y_min = min(map $_->[Y], @$points) || 0; + my $y_max = max(map $_->[Y], @$points) || 0; + my $origin = [-$x_min, -$y_min]; + + $self->{shape_options_book}->SetSelection(SHAPE_RECTANGULAR); + my $optgroup = $self->{optgroups}[SHAPE_RECTANGULAR]; + $optgroup->set_value('rect_size', [ $x_max-$x_min, $y_max-$y_min ]); + $optgroup->set_value('rect_origin', $origin); + $self->_update_shape; + return; + } + } + + # is this a circle? + { + # Analyze the array of points. Do they reside on a circle? + my $polygon = Slic3r::Polygon->new_scale(@$points); + my $center = $polygon->bounding_box->center; + my @vertex_distances = map $center->distance_to($_), @$polygon; + my $avg_dist = sum(@vertex_distances)/@vertex_distances; + if (!defined first { abs($_ - $avg_dist) > 10*scaled_epsilon } @vertex_distances) { + # all vertices are equidistant to center + $self->{shape_options_book}->SetSelection(SHAPE_CIRCULAR); + my $optgroup = $self->{optgroups}[SHAPE_CIRCULAR]; + $optgroup->set_value('diameter', sprintf("%.0f", unscale($avg_dist*2))); + $self->_update_shape; + return; + } + } + + if (@$points < 3) { + # Invalid polygon. Revert to default bed dimensions. + $self->{shape_options_book}->SetSelection(SHAPE_RECTANGULAR); + my $optgroup = $self->{optgroups}[SHAPE_RECTANGULAR]; + $optgroup->set_value('rect_size', [200, 200]); + $optgroup->set_value('rect_origin', [0, 0]); + $self->_update_shape; + return; + } + + # This is a custom bed shape, use the polygon provided. + $self->{shape_options_book}->SetSelection(SHAPE_CUSTOM); + # Copy the polygon to the canvas, make a copy of the array. + $self->{canvas}->bed_shape([@$points]); + $self->_update_shape; +} + +# Update the bed shape from the dialog fields. +sub _update_shape { + my ($self) = @_; + + my $page_idx = $self->{shape_options_book}->GetSelection; + if ($page_idx == SHAPE_RECTANGULAR) { + my $rect_size = $self->{optgroups}[SHAPE_RECTANGULAR]->get_value('rect_size'); + my $rect_origin = $self->{optgroups}[SHAPE_RECTANGULAR]->get_value('rect_origin'); + my ($x, $y) = @$rect_size; + return if !looks_like_number($x) || !looks_like_number($y); # empty strings or '-' or other things + return if !$x || !$y or $x == 0 or $y == 0; + my ($x0, $y0) = (0,0); + my ($x1, $y1) = ($x ,$y); + { + my ($dx, $dy) = @$rect_origin; + return if !looks_like_number($dx) || !looks_like_number($dy); # empty strings or '-' or other things + $x0 -= $dx; + $x1 -= $dx; + $y0 -= $dy; + $y1 -= $dy; + } + $self->{canvas}->bed_shape([ + [$x0,$y0], + [$x1,$y0], + [$x1,$y1], + [$x0,$y1], + ]); + } elsif ($page_idx == SHAPE_CIRCULAR) { + my $diameter = $self->{optgroups}[SHAPE_CIRCULAR]->get_value('diameter'); + return if !$diameter or $diameter == 0; + my $r = $diameter/2; + my $twopi = 2*PI; + my $edges = 60; + my $polygon = Slic3r::Polygon->new_scale( + map [ $r * cos $_, $r * sin $_ ], + map { $twopi/$edges*$_ } 1..$edges + ); + $self->{canvas}->bed_shape([ + map [ unscale($_->x), unscale($_->y) ], @$polygon #)) + ]); + } + + $self->{on_change}->(); + $self->_update_preview; +} + +sub _update_preview { + my ($self) = @_; + $self->{canvas}->Refresh if $self->{canvas}; + $self->Refresh; +} + +# Called from the constructor. +# Create a panel for a rectangular / circular / custom bed shape. +sub _init_shape_options_page { + my ($self, $title) = @_; + + my $panel = Wx::Panel->new($self->{shape_options_book}); + my $optgroup; + push @{$self->{optgroups}}, $optgroup = Slic3r::GUI::OptionsGroup->new( + parent => $panel, + title => 'Settings', + label_width => 100, + on_change => sub { + my ($opt_id) = @_; + #$self->{"_$opt_id"} = $optgroup->get_value($opt_id); + $self->_update_shape; + }, + ); + $panel->SetSizerAndFit($optgroup->sizer); + $self->{shape_options_book}->AddPage($panel, $title); + + return $optgroup; +} + +# Loads an stl file, projects it to the XY plane and calculates a polygon. +sub _load_stl { + my ($self) = @_; + + my $dialog = Wx::FileDialog->new($self, 'Choose a file to import bed shape from (STL/OBJ/AMF/PRUSA):', "", "", &Slic3r::GUI::MODEL_WILDCARD, wxFD_OPEN | wxFD_FILE_MUST_EXIST); + if ($dialog->ShowModal != wxID_OK) { + $dialog->Destroy; + return; + } + my $input_file = $dialog->GetPaths; + $dialog->Destroy; + + my $model = Slic3r::Model->read_from_file($input_file); + my $mesh = $model->mesh; + my $expolygons = $mesh->horizontal_projection; + + if (@$expolygons == 0) { + Slic3r::GUI::show_error($self, "The selected file contains no geometry."); + return; + } + if (@$expolygons > 1) { + Slic3r::GUI::show_error($self, "The selected file contains several disjoint areas. This is not supported."); + return; + } + + my $polygon = $expolygons->[0]->contour; + $self->{canvas}->bed_shape([ map [ unscale($_->x), unscale($_->y) ], @$polygon ]); + $self->_update_preview(); +} + +# Returns the resulting bed shape polygon. This value will be stored to the ini file. +sub GetValue { + my ($self) = @_; + return $self->{canvas}->bed_shape; +} + +1; From ac904b273182506892f57cc9a08312550e24d80c Mon Sep 17 00:00:00 2001 From: fsantini Date: Fri, 16 Feb 2018 17:27:50 +0100 Subject: [PATCH 57/57] Error messages in parsing variables (#722) Making error messages more clear when a vector or scalar is found in macro parsing, and the other type is expected. --- xs/src/libslic3r/PlaceholderParser.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xs/src/libslic3r/PlaceholderParser.cpp b/xs/src/libslic3r/PlaceholderParser.cpp index ba0efd6e4..62b516935 100644 --- a/xs/src/libslic3r/PlaceholderParser.cpp +++ b/xs/src/libslic3r/PlaceholderParser.cpp @@ -623,7 +623,7 @@ namespace client expr &output) { if (opt.opt->is_vector()) - ctx->throw_exception("Referencing a scalar variable in a vector context", opt.it_range); + ctx->throw_exception("Referencing a vector variable when scalar is expected", opt.it_range); switch (opt.opt->type()) { case coFloat: output.set_d(opt.opt->getFloat()); break; case coInt: output.set_i(opt.opt->getInt()); break; @@ -648,7 +648,7 @@ namespace client expr &output) { if (opt.opt->is_scalar()) - ctx->throw_exception("Referencing a vector variable in a scalar context", opt.it_range); + ctx->throw_exception("Referencing a scalar variable when vector is expected", opt.it_range); const ConfigOptionVectorBase *vec = static_cast(opt.opt); if (vec->empty()) ctx->throw_exception("Indexing an empty vector variable", opt.it_range);