package Slic3r::Format::AMF; use Moo; use Slic3r::Geometry qw(X Y Z); sub read_file { my $self = shift; my ($file) = @_; eval "require Slic3r::Format::AMF::Parser; 1" or die "AMF parsing requires XML::SAX\n"; open my $fh, '<', $file or die "Failed to open $file\n"; my $model = Slic3r::Model->new; XML::SAX::PurePerl ->new(Handler => Slic3r::Format::AMF::Parser->new(_model => $model)) ->parse_file($fh); close $fh; return $model; } sub write_file { my $self = shift; my ($file, $model, %params) = @_; my %vertices_offset = (); open my $fh, '>', $file; binmode $fh, ':utf8'; printf $fh qq{\n}; printf $fh qq{\n}; printf $fh qq{ Slic3r %s\n}, $Slic3r::VERSION; for my $material_id (sort keys %{ $model->materials }) { my $material = $model->materials->{$material_id}; printf $fh qq{ \n}, $material_id; for (keys %$material) { printf $fh qq{ %s\n}, $_, $material->{$_}; } printf $fh qq{ \n}; } my $instances = ''; for my $object_id (0 .. $#{ $model->objects }) { my $object = $model->objects->[$object_id]; printf $fh qq{ \n}, $object_id; printf $fh qq{ \n}; printf $fh qq{ \n}; foreach my $vertex (@{$object->vertices}, ) { printf $fh qq{ \n}; printf $fh qq{ \n}; printf $fh qq{ %s\n}, $vertex->[X]; printf $fh qq{ %s\n}, $vertex->[Y]; printf $fh qq{ %s\n}, $vertex->[Z]; printf $fh qq{ \n}; printf $fh qq{ \n}; } printf $fh qq{ \n}; foreach my $volume (@{ $object->volumes }) { printf $fh qq{ \n}, (!defined $volume->material_id) ? '' : (sprintf ' materialid="%s"', $volume->material_id); foreach my $facet (@{$volume->facets}) { printf $fh qq{ \n}; printf $fh qq{ %d\n}, (4+$_), $facet->[$_], (4+$_) for -3..-1; printf $fh qq{ \n}; } printf $fh qq{ \n}; } printf $fh qq{ \n}; printf $fh qq{ \n}; if ($object->instances) { foreach my $instance (@{$object->instances}) { $instances .= sprintf qq{ \n}, $object_id; $instances .= sprintf qq{ %s\n}, $instance->offset->[X]; $instances .= sprintf qq{ %s\n}, $instance->offset->[Y]; $instances .= sprintf qq{ %s\n}, $instance->rotation; $instances .= sprintf qq{ \n}; } } } if ($instances) { printf $fh qq{ \n}; printf $fh $instances; printf $fh qq{ \n}; } printf $fh qq{\n}; close $fh; } 1;