<commit_before>package Slic3r::Layer::Region;
use Moo;

use Math::Clipper ':all';
use Slic3r::ExtrusionPath ':roles';
use Slic3r::Geometry qw(scale shortest_path);
use Slic3r::Geometry::Clipper qw(safety_offset union_ex diff_ex intersection_ex);
use Slic3r::Surface ':types';

has 'layer' => (
    is          => 'ro',
    weak_ref    => 1,
    required    => 1,
    trigger     => 1,
    handles     => [qw(id slice_z print_z height flow)],
);
has 'region'            => (is => 'ro', required => 1);
has 'perimeter_flow'    => (is => 'rw');
has 'infill_flow'       => (is => 'rw');

# collection of spare segments generated by slicing the original geometry;
# these need to be merged in continuos (closed) polylines
has 'lines' => (is => 'rw', default => sub { [] });

# collection of surfaces generated by slicing the original geometry
has 'slices' => (is => 'rw', default => sub { [] });

# collection of polygons or polylines representing thin walls contained 
# in the original geometry
has 'thin_walls' => (is => 'rw', default => sub { [] });

# collection of polygons or polylines representing thin infill regions that
# need to be filled with a medial axis
has 'thin_fills' => (is => 'rw', default => sub { [] });

# collection of expolygons generated by offsetting the innermost perimeter(s)
# they represent boundaries of areas to fill, typed (top/bottom/internal)
has 'surfaces' => (is => 'rw', default => sub { [] });

# collection of surfaces for infill generation. the difference between surfaces
# fill_surfaces is that this one honors fill_density == 0 and turns small internal
# surfaces into solid ones
has 'fill_surfaces' => (is => 'rw', default => sub { [] });

# ordered collection of extrusion paths/loops to build all perimeters
has 'perimeters' => (is => 'rw', default => sub { [] });

# ordered collection of extrusion paths to fill surfaces
has 'fills' => (is => 'rw', default => sub { [] });

sub BUILD {
    my $self = shift;
    $self->_update_flows;
}

sub _trigger_layer {
    my $self = shift;
    $self->_update_flows;
}

sub _update_flows {
    my $self = shift;
    return if !$self->region;
    
    $self->perimeter_flow($self->id == 0
        ? $self->region->first_layer_flows->{perimeter}
        : $self->region->flows->{perimeter});
    
    $self->infill_flow($self->id == 0
        ? $self->region->first_layer_flows->{infill}
        : $self->region->flows->{infill});
}

# build polylines from lines
sub make_surfaces {
    my $self = shift;
    my ($loops) = @_;
    
    return if !@$loops;    
    {
        my $safety_offset = scale 0.1;
        # merge everything
        my $expolygons = [ map $_->offset_ex(-$safety_offset), @{union_ex(safety_offset($loops, $safety_offset))} ];
        
        Slic3r::debugf "  %d surface(s) having %d holes detected from %d polylines\n",
            scalar(@$expolygons), scalar(map $_->holes, @$expolygons), scalar(@$loops);
        
        $self->slices([
            map Slic3r::Surface->new(expolygon => $_, surface_type => S_TYPE_INTERNAL),
                @$expolygons
        ]);
    }
    
    # the contours must be offsetted by half extrusion width inwards
    {
        my $distance = $self->perimeter_flow->scaled_width / 2;
        my @surfaces = @{$self->slices};
        @{$self->slices} = ();
        foreach my $surface (@surfaces) {
            push @{$self->slices}, map Slic3r::Surface->new
                (expolygon => $_, surface_type => S_TYPE_INTERNAL),
                @{union_ex([
                    Slic3r::Geometry::Clipper::offset(
                        [Slic3r::Geometry::Clipper::offset($surface->expolygon, -2*$distance)],
                        +$distance,
                    ),
                ])};
        }
        
        # now detect thin walls by re-outgrowing offsetted surfaces and subtracting
        # them from the original slices
        my $outgrown = Math::Clipper::offset([ map $_->p, @{$self->slices} ], $distance);
        my $diff = diff_ex(
            [ map $_->p, @surfaces ],
            $outgrown,
            1,
        );
        
        $self->thin_walls([]);
        if (@$diff) {
            my $area_threshold = $self->perimeter_flow->scaled_spacing ** 2;
            @$diff = grep $_->area > ($area_threshold), @$diff;
            
            @{$self->thin_walls} = map $_->medial_axis($self->perimeter_flow->scaled_width), @$diff;
            
            Slic3r::debugf "  %d thin walls detected\n", scalar(@{$self->thin_walls}) if @{$self->thin_walls};
        }
    }
    
    if (0) {
        require "Slic3r/SVG.pm";
        Slic3r::SVG::output(undef, "surfaces.svg",
            polygons        => [ map $_->contour, @{$self->slices} ],
            red_polygons    => [ map $_->p, map @{$_->holes}, @{$self->slices} ],
        );
    }
}

sub make_perimeters {
    my $self = shift;
    
    my $gap_area_threshold = $self->perimeter_flow->scaled_width ** 2;
    
    # this array will hold one arrayref per original surface (island);
    # each item of this arrayref is an arrayref representing a depth (from outer
    # perimeters to inner); each item of this arrayref is an ExPolygon:
    # @perimeters = (
    #    [ # first island
    #        [ Slic3r::ExPolygon, Slic3r::ExPolygon... ],  #depth 0: outer loop
    #        [ Slic3r::ExPolygon, Slic3r::ExPolygon... ],  #depth 1: inner loop
    #    ],
    #    [ # second island
    #        ...
    #    ]
    # )
    my @perimeters = ();  # one item per depth; each item
    
    # organize islands using a shortest path search
    my @surfaces = @{shortest_path([
        map [ $_->contour->[0], $_ ], @{$self->slices},
    ])};
    
    $self->perimeters([]);
    $self->surfaces([]);
    $self->thin_fills([]);
    
    # for each island:
    foreach my $surface (@surfaces) {
        my @last_offsets = ($surface->expolygon);
        
        # experimental hole compensation (see ArcCompensation in the RepRap wiki)
        if (0) {
            foreach my $hole ($last_offsets[0]->holes) {
                my $circumference = abs($hole->length);
                next unless $circumference <= &Slic3r::SMALL_PERIMETER_LENGTH;
                # this compensation only works for circular holes, while it would 
                # overcompensate for hexagons and other shapes having straight edges.
                # so we require a minimum number of vertices.
                next unless $circumference / @$hole >= 3 * $Slic3r::flow->scaled_width;
                
                # revert the compensation done in make_surfaces() and get the actual radius
                # of the hole
                my $radius = ($circumference / PI / 2) - $self->perimeter_flow->scaled_spacing/2;
                my $new_radius = ($self->perimeter_flow->scaled_width + sqrt(($self->perimeter_flow->scaled_width ** 2) + (4*($radius**2)))) / 2;
                # holes are always turned to contours, so reverse point order before and after
                $hole->reverse;
                my @offsetted = $hole->offset(+ ($new_radius - $radius));
                # skip arc compensation when hole is not round (thus leads to multiple offsets)
                @$hole = map Slic3r::Point->new($_), @{ $offsetted[0] } if @offsetted == 1;
                $hole->reverse;
            }
        }
        
        my $distance = $self->perimeter_flow->scaled_spacing;
        my @gaps = ();
        
        # generate perimeters inwards (loop 0 is the external one)
        my $loop_number = $Slic3r::Config->perimeters + ($surface->additional_inner_perimeters || 0);
        push @perimeters, [[@last_offsets]];
        for (my $loop = 1; $loop < $loop_number; $loop++) {
            # offsetting a polygon can result in one or many offset polygons
            my @new_offsets = ();<commit_msg>Fixed regression causing one perimeter to be generated even when perimeters where set to 0. #759<commit_after>package Slic3r::Layer::Region;
use Moo;

use Math::Clipper ':all';
use Slic3r::ExtrusionPath ':roles';
use Slic3r::Geometry qw(scale shortest_path);
use Slic3r::Geometry::Clipper qw(safety_offset union_ex diff_ex intersection_ex);
use Slic3r::Surface ':types';

has 'layer' => (
    is          => 'ro',
    weak_ref    => 1,
    required    => 1,
    trigger     => 1,
    handles     => [qw(id slice_z print_z height flow)],
);
has 'region'            => (is => 'ro', required => 1);
has 'perimeter_flow'    => (is => 'rw');
has 'infill_flow'       => (is => 'rw');

# collection of spare segments generated by slicing the original geometry;
# these need to be merged in continuos (closed) polylines
has 'lines' => (is => 'rw', default => sub { [] });

# collection of surfaces generated by slicing the original geometry
has 'slices' => (is => 'rw', default => sub { [] });

# collection of polygons or polylines representing thin walls contained 
# in the original geometry
has 'thin_walls' => (is => 'rw', default => sub { [] });

# collection of polygons or polylines representing thin infill regions that
# need to be filled with a medial axis
has 'thin_fills' => (is => 'rw', default => sub { [] });

# collection of expolygons generated by offsetting the innermost perimeter(s)
# they represent boundaries of areas to fill, typed (top/bottom/internal)
has 'surfaces' => (is => 'rw', default => sub { [] });

# collection of surfaces for infill generation. the difference between surfaces
# fill_surfaces is that this one honors fill_density == 0 and turns small internal
# surfaces into solid ones
has 'fill_surfaces' => (is => 'rw', default => sub { [] });

# ordered collection of extrusion paths/loops to build all perimeters
has 'perimeters' => (is => 'rw', default => sub { [] });

# ordered collection of extrusion paths to fill surfaces
has 'fills' => (is => 'rw', default => sub { [] });

sub BUILD {
    my $self = shift;
    $self->_update_flows;
}

sub _trigger_layer {
    my $self = shift;
    $self->_update_flows;
}

sub _update_flows {
    my $self = shift;
    return if !$self->region;
    
    $self->perimeter_flow($self->id == 0
        ? $self->region->first_layer_flows->{perimeter}
        : $self->region->flows->{perimeter});
    
    $self->infill_flow($self->id == 0
        ? $self->region->first_layer_flows->{infill}
        : $self->region->flows->{infill});
}

# build polylines from lines
sub make_surfaces {
    my $self = shift;
    my ($loops) = @_;
    
    return if !@$loops;    
    {
        my $safety_offset = scale 0.1;
        # merge everything
        my $expolygons = [ map $_->offset_ex(-$safety_offset), @{union_ex(safety_offset($loops, $safety_offset))} ];
        
        Slic3r::debugf "  %d surface(s) having %d holes detected from %d polylines\n",
            scalar(@$expolygons), scalar(map $_->holes, @$expolygons), scalar(@$loops);
        
        $self->slices([
            map Slic3r::Surface->new(expolygon => $_, surface_type => S_TYPE_INTERNAL),
                @$expolygons
        ]);
    }
    
    # the contours must be offsetted by half extrusion width inwards
    {
        my $distance = $self->perimeter_flow->scaled_width / 2;
        my @surfaces = @{$self->slices};
        @{$self->slices} = ();
        foreach my $surface (@surfaces) {
            push @{$self->slices}, map Slic3r::Surface->new
                (expolygon => $_, surface_type => S_TYPE_INTERNAL),
                @{union_ex([
                    Slic3r::Geometry::Clipper::offset(
                        [Slic3r::Geometry::Clipper::offset($surface->expolygon, -2*$distance)],
                        +$distance,
                    ),
                ])};
        }
        
        # now detect thin walls by re-outgrowing offsetted surfaces and subtracting
        # them from the original slices
        my $outgrown = Math::Clipper::offset([ map $_->p, @{$self->slices} ], $distance);
        my $diff = diff_ex(
            [ map $_->p, @surfaces ],
            $outgrown,
            1,
        );
        
        $self->thin_walls([]);
        if (@$diff) {
            my $area_threshold = $self->perimeter_flow->scaled_spacing ** 2;
            @$diff = grep $_->area > ($area_threshold), @$diff;
            
            @{$self->thin_walls} = map $_->medial_axis($self->perimeter_flow->scaled_width), @$diff;
            
            Slic3r::debugf "  %d thin walls detected\n", scalar(@{$self->thin_walls}) if @{$self->thin_walls};
        }
    }
    
    if (0) {
        require "Slic3r/SVG.pm";
        Slic3r::SVG::output(undef, "surfaces.svg",
            polygons        => [ map $_->contour, @{$self->slices} ],
            red_polygons    => [ map $_->p, map @{$_->holes}, @{$self->slices} ],
        );
    }
}

sub make_perimeters {
    my $self = shift;
    
    my $gap_area_threshold = $self->perimeter_flow->scaled_width ** 2;
    
    # this array will hold one arrayref per original surface (island);
    # each item of this arrayref is an arrayref representing a depth (from outer
    # perimeters to inner); each item of this arrayref is an ExPolygon:
    # @perimeters = (
    #    [ # first island
    #        [ Slic3r::ExPolygon, Slic3r::ExPolygon... ],  #depth 0: outer loop
    #        [ Slic3r::ExPolygon, Slic3r::ExPolygon... ],  #depth 1: inner loop
    #    ],
    #    [ # second island
    #        ...
    #    ]
    # )
    my @perimeters = ();  # one item per depth; each item
    
    # organize islands using a shortest path search
    my @surfaces = @{shortest_path([
        map [ $_->contour->[0], $_ ], @{$self->slices},
    ])};
    
    $self->perimeters([]);
    $self->surfaces([]);
    $self->thin_fills([]);
    
    # for each island:
    foreach my $surface (@surfaces) {
        my @last_offsets = ($surface->expolygon);
        
        # experimental hole compensation (see ArcCompensation in the RepRap wiki)
        if (0) {
            foreach my $hole ($last_offsets[0]->holes) {
                my $circumference = abs($hole->length);
                next unless $circumference <= &Slic3r::SMALL_PERIMETER_LENGTH;
                # this compensation only works for circular holes, while it would 
                # overcompensate for hexagons and other shapes having straight edges.
                # so we require a minimum number of vertices.
                next unless $circumference / @$hole >= 3 * $Slic3r::flow->scaled_width;
                
                # revert the compensation done in make_surfaces() and get the actual radius
                # of the hole
                my $radius = ($circumference / PI / 2) - $self->perimeter_flow->scaled_spacing/2;
                my $new_radius = ($self->perimeter_flow->scaled_width + sqrt(($self->perimeter_flow->scaled_width ** 2) + (4*($radius**2)))) / 2;
                # holes are always turned to contours, so reverse point order before and after
                $hole->reverse;
                my @offsetted = $hole->offset(+ ($new_radius - $radius));
                # skip arc compensation when hole is not round (thus leads to multiple offsets)
                @$hole = map Slic3r::Point->new($_), @{ $offsetted[0] } if @offsetted == 1;
                $hole->reverse;
            }
        }
        
        my $distance = $self->perimeter_flow->scaled_spacing;
        my @gaps = ();
        
        # generate perimeters inwards (loop 0 is the external one)
        my $loop_number = $Slic3r::Config->perimeters + ($surface->additional_inner_perimeters || 0);
        push @perimeters, [[@last_offsets]] if $loop_number > 0;
        for (my $loop = 1; $loop < $loop_number; $loop++) {
            # offsetting a polygon can result in one or many offset polygons
            my @new_offsets = ();
{'fraction_non_alphanumeric': 0.14002927884921393, 'fraction_numerical': 0.0070651136146648846, 'mean_word_length': 2.329518965882602, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 242, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3595969', 'n_tokens_mistral': 4987, 'n_tokens_neox': 4738, 'n_words': 1334}