Skip to content

SVG Renderer API Reference

svg

Module contains implementation of Gerber rendering backend outputting SVG files.

SvgRenderer2

Bases: Renderer2

Rendering backend class for rendering SVG images.

Source code in src\pygerber\gerberx3\renderer2\svg.py
class SvgRenderer2(Renderer2):
    """Rendering backend class for rendering SVG images."""

    def __init__(
        self,
        hooks: Optional[SvgRenderer2Hooks] = None,
    ) -> None:
        hooks = SvgRenderer2Hooks() if hooks is None else hooks
        super().__init__(hooks)

SvgRenderingFrame dataclass

Rendering variable container.

Source code in src\pygerber\gerberx3\renderer2\svg.py
@dataclass
class SvgRenderingFrame:
    """Rendering variable container."""

    bounding_box: BoundingBox
    normalize_origin_to_0_0: bool
    mask: drawsvg.Mask = field(default_factory=drawsvg.Mask)
    group: drawsvg.Group = field(default_factory=drawsvg.Group)
    polarity: Optional[Polarity] = None
    is_region: bool = False
    flip_y: bool = True

    def get_group_or_mask(
        self,
        is_group: bool,  # noqa: FBT001
    ) -> drawsvg.Group | drawsvg.Mask:
        """Get group or mask."""
        if is_group:
            return self.group
        return self.mask

get_group_or_mask

get_group_or_mask(
    is_group: bool,
) -> drawsvg.Group | drawsvg.Mask

Get group or mask.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def get_group_or_mask(
    self,
    is_group: bool,  # noqa: FBT001
) -> drawsvg.Group | drawsvg.Mask:
    """Get group or mask."""
    if is_group:
        return self.group
    return self.mask

SvgRenderer2Hooks

Bases: Renderer2HooksABC

Rendering backend hooks used to render SVG images.

Source code in src\pygerber\gerberx3\renderer2\svg.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
class SvgRenderer2Hooks(Renderer2HooksABC):
    """Rendering backend hooks used to render SVG images."""

    renderer: SvgRenderer2

    def __init__(
        self,
        color_scheme: ColorScheme = ColorScheme.DEBUG_1,
        scale: Decimal = Decimal("1"),
        *,
        flip_y: bool = True,
    ) -> None:
        if not IS_SVG_BACKEND_AVAILABLE:
            raise DRAWSVGNotAvailableError
        self.color_scheme = color_scheme
        self.scale = scale
        self.flip_y = flip_y

    def init(
        self,
        renderer: Renderer2,
        command_buffer: ReadonlyCommandBuffer2,
    ) -> None:
        """Initialize rendering hooks."""
        if not isinstance(renderer, SvgRenderer2):
            raise NotImplementedError

        self.renderer = renderer
        self.command_buffer = command_buffer
        self.rendering_stack: list[SvgRenderingFrame] = [
            SvgRenderingFrame(
                bounding_box=self.command_buffer.get_bounding_box(),
                normalize_origin_to_0_0=True,
                flip_y=self.flip_y,
            ),
        ]
        self.apertures: dict[str, drawsvg.Group] = {}

    def push_render_frame(
        self,
        bbox: BoundingBox,
        *,
        normalize_origin_to_0_0: bool,
        flip_y: bool,
    ) -> None:
        """Push new segment render frame."""
        self.rendering_stack.append(
            SvgRenderingFrame(
                bounding_box=bbox,
                normalize_origin_to_0_0=normalize_origin_to_0_0,
                flip_y=flip_y,
            ),
        )

    def pop_render_frame(self) -> SvgRenderingFrame:
        """Pop segment render frame."""
        if len(self.rendering_stack) <= 1:
            raise RuntimeError
        return self.rendering_stack.pop()

    @property
    def base_frame(self) -> SvgRenderingFrame:
        """Get base rendering stack frame."""
        return self.rendering_stack[0]

    @property
    def current_frame(self) -> SvgRenderingFrame:
        """Get current rendering stack frame."""
        return self.rendering_stack[-1]

    def add_element_to_frame(
        self,
        polarity: Polarity,
        element: drawsvg.DrawingBasicElement,
    ) -> None:
        """Add element to current frame."""
        self.get_layer(polarity).append(element)

    def get_layer(self, polarity: Polarity) -> drawsvg.Group | drawsvg.Mask:
        """Get SVG layer object corresponding to polarity."""
        # In general what we want to do is to have a layer made of group with mask.
        # First we fill the group with dark command, then after meeting first clear
        # command we start filling mask with consecutive clear command until
        # we meed dark command again. Then we create new group-mask layer to repeat the
        # cycle.

        # If frame is not initialized, initialize it.
        if self.current_frame.polarity is None:
            self.current_frame.polarity = polarity
            self.add_masked_group_to_frame()

            return self.current_frame.get_group_or_mask(polarity.is_solid())

        if polarity.is_solid() != self.current_frame.polarity.is_solid():
            # If polarity of frame is solid it means that mask for this group is still
            # empty and can be filled.
            if self.current_frame.polarity.is_solid():
                self.current_frame.polarity = polarity
                return self.current_frame.mask
            # If polarity of frame is clear, it means that we already filled
            # both group and mask and we need to create new group-mask layer.
            self.add_masked_group_to_frame()
            self.current_frame.polarity = polarity
            return self.current_frame.group

        # We have the same polarity as layer (and as previous commands) so we can
        # simply add it to current layer.
        return self.current_frame.get_group_or_mask(polarity.is_solid())

    def add_masked_group_to_frame(self) -> None:
        """Create new layer including previous layer."""
        self.current_frame.mask = self.create_full_mask()
        new_layer = drawsvg.Group(mask=self.current_frame.mask)
        new_layer.append(self.current_frame.group)
        self.current_frame.group = new_layer

    def create_full_mask(self) -> drawsvg.Mask:
        """Create mask covering whole image."""
        bbox = self.base_frame.bounding_box
        mask = drawsvg.Mask()
        mask.append(
            drawsvg.Rectangle(
                x=self.convert_size(-bbox.width / 2),
                y=self.convert_size(-bbox.height / 2),
                width=self.convert_size(bbox.width * 2),
                height=self.convert_size(bbox.height * 2),
                fill="white",
            ),
        )
        return mask

    def create_mask(self, bbox: BoundingBox) -> drawsvg.Mask:
        """Create mask covering specified bounding box."""
        mask = drawsvg.Mask()
        mask.append(
            drawsvg.Rectangle(
                x=self.convert_size(bbox.min_x),
                y=self.convert_size(bbox.min_y),
                width=self.convert_size(bbox.width),
                height=self.convert_size(bbox.height),
                fill="white",
            ),
        )
        return mask

    def convert_x(self, x: Offset) -> Decimal:
        """Convert y offset to y coordinate in image space."""
        if self.current_frame.normalize_origin_to_0_0:
            origin_offset_x = self.current_frame.bounding_box.min_x.as_millimeters()
        else:
            origin_offset_x = Decimal(0)

        corrected_position_x = x.as_millimeters() - origin_offset_x

        return corrected_position_x * self.scale

    def convert_y(self, y: Offset) -> Decimal:
        """Convert y offset to y coordinate in image space."""
        return self._convert_y(
            y,
            normalize_origin_to_0_0=self.current_frame.normalize_origin_to_0_0,
            flip_y=self.current_frame.flip_y,
        )

    def _convert_y(
        self,
        y: Offset,
        *,
        normalize_origin_to_0_0: bool,
        flip_y: bool,
    ) -> Decimal:
        """Convert y offset to pixel y coordinate."""
        if normalize_origin_to_0_0:
            origin_offset_y = self.current_frame.bounding_box.min_y.as_millimeters()
        else:
            origin_offset_y = Decimal(0)

        corrected_position_y = y.as_millimeters() - origin_offset_y

        if flip_y:
            flipped_position_y = (
                self.current_frame.bounding_box.height.as_millimeters()
                - corrected_position_y
            )
            return flipped_position_y * self.scale
        return corrected_position_y * self.scale

    def convert_size(self, diameter: Offset) -> Decimal:
        """Convert y offset to pixel y coordinate."""
        return diameter.as_millimeters() * self.scale

    def get_color(self, polarity: Polarity) -> str:
        """Get color for specified polarity."""
        if self.current_frame.is_region:
            if polarity.is_solid():
                return self.color_scheme.solid_region_color.to_hex()
            return "black"

        if polarity.is_solid():
            return self.color_scheme.solid_color.to_hex()
        return "black"

    def get_aperture_id(self, aperture: Aperture2, transform: ApertureTransform) -> str:
        """Get unique ID for aperture."""
        return (
            f"{aperture.identifier}%"
            f"{transform.get_transform_key()}%{transform.polarity}"
        )

    def get_aperture(self, aperture_id: str) -> Optional[drawsvg.Group]:
        """Get SVG group representing aperture."""
        return self.apertures.get(aperture_id)

    def set_aperture(
        self,
        aperture_id: str,
        aperture: drawsvg.Group,
    ) -> None:
        """Set SVG group representing aperture."""
        self.apertures[aperture_id] = aperture

    def render_line(self, command: Line2) -> None:
        """Render line to target image."""
        color = self.get_color(command.transform.polarity)

        command.aperture.render_flash(
            self.renderer,
            Flash2(
                transform=command.transform,
                attributes=command.attributes,
                aperture=command.aperture,
                flash_point=command.start_point,
            ),
        )

        parallel_vector = command.start_point - command.end_point
        perpendicular_vector = parallel_vector.perpendicular()
        normalized_perpendicular_vector = perpendicular_vector.normalize()
        point_offset = normalized_perpendicular_vector * (
            command.aperture.get_stroke_width() / 2.0
        )

        p0 = command.start_point - point_offset
        p1 = command.start_point + point_offset
        p2 = command.end_point + point_offset
        p3 = command.end_point - point_offset

        rectangle = drawsvg.Lines(
            f"{self.convert_x(p0.x):.8f}",
            f"{self.convert_y(p0.y):.8f}",
            f"{self.convert_x(p1.x):.8f}",
            f"{self.convert_y(p1.y):.8f}",
            f"{self.convert_x(p2.x):.8f}",
            f"{self.convert_y(p2.y):.8f}",
            f"{self.convert_x(p3.x):.8f}",
            f"{self.convert_y(p3.y):.8f}",
            fill=color,
            close=True,
        )
        self.add_element_to_frame(command.transform.polarity, rectangle)

        command.aperture.render_flash(
            self.renderer,
            Flash2(
                transform=command.transform,
                attributes=command.attributes,
                aperture=command.aperture,
                flash_point=command.end_point,
            ),
        )

    def render_arc(self, command: Arc2) -> None:
        """Render arc to target image."""
        color = self.get_color(command.transform.polarity)
        # Arcs which start and end point overlaps are completely invisible in SVG.
        # Therefore we need to replace them with two half-full-arcs.
        # THB spec recommends doing it when exporting Gerber files, to avoid problems
        # with floating point numbers, but I guess nobody does that.
        if command.start_point == command.end_point:
            # This is a vector from center to start point, so we can invert it and
            # apply it twice to get the point on the opposite side of the center point.
            relative = command.get_relative_start_point()
            # Now we cen recursively invoke self with two modified copies of this
            # command.
            self.render_arc(
                command.model_copy(
                    update={
                        "start_point": command.start_point,
                        "end_point": command.start_point - (relative * 2),
                    },
                ),
            )
            self.render_arc(
                command.model_copy(
                    update={
                        "start_point": command.start_point - (relative * 2),
                        "end_point": command.start_point,
                    },
                ),
            )
            return

        command.aperture.render_flash(
            self.renderer,
            Flash2(
                transform=command.transform,
                attributes=command.attributes,
                aperture=command.aperture,
                flash_point=command.start_point,
            ),
        )
        # First we calculate perpendicular vector. This vector is always pointing
        # from the center, thus it is perpendicular to arc.
        # Then we can normalize it and multiply by half of aperture diameter,
        # effectively giving us vector pointing to inner/outer edge of line.
        # We can ignore the fact that we don't know which point (inner/outer) we
        # have, as long as we get the same every time, then we can pair it with
        # corresponding vector made from end point and create single arc,
        # Then invert both vectors and draw second arc.
        start_perpendicular_vector = command.get_relative_start_point()
        start_normalized_perpendicular_vector = start_perpendicular_vector.normalize()
        start_point_offset = start_normalized_perpendicular_vector * (
            command.aperture.get_stroke_width() / 2.0
        )

        end_perpendicular_vector = command.get_relative_end_point()
        end_normalized_perpendicular_vector = end_perpendicular_vector.normalize()
        end_point_offset = end_normalized_perpendicular_vector * (
            command.aperture.get_stroke_width() / 2.0
        )

        arc_path = drawsvg.Path(fill=color)

        # Determine start point of inner arc.
        start_inner = command.start_point + start_point_offset
        end_inner = command.end_point + end_point_offset
        # Move path ptr to inner arc start point.
        arc_path.M(
            f"{self.convert_x(start_inner.x):.8f}",
            f"{self.convert_y(start_inner.y):.8f}",
        )
        self.render_arc_to_path(
            command.model_copy(
                update={
                    "start_point": start_inner,
                    "end_point": end_inner,
                },
            ),
            arc_path,
        )
        # Determine start point of outer arc.
        # This arc have to be in reverse direction, so we swap start/end points.
        start_outer = command.end_point - end_point_offset
        end_outer = command.start_point - start_point_offset
        # Draw line between end of inner arc and start of outer arc.
        arc_path.L(
            f"{self.convert_x(start_outer.x):.8f}",
            f"{self.convert_y(start_outer.y):.8f}",
        )
        self.render_cc_arc_to_path(
            CCArc2(
                transform=command.transform,
                attributes=command.attributes,
                aperture=command.aperture,
                start_point=start_outer,
                center_point=command.center_point,
                end_point=end_outer,
            ),
            arc_path,
        )
        # Close arc box by drawing line between end of outer arc and start of inner
        arc_path.Z()
        self.add_element_to_frame(command.transform.polarity, arc_path)

        command.aperture.render_flash(
            self.renderer,
            Flash2(
                transform=command.transform,
                attributes=command.attributes,
                aperture=command.aperture,
                flash_point=command.end_point,
            ),
        )

    def render_cc_arc(self, command: CCArc2) -> None:
        """Render arc to target image."""
        self.render_arc(
            command.model_copy(
                update={
                    "start_point": command.end_point,
                    "end_point": command.start_point,
                },
            ),
        )

    def render_flash_circle(self, command: Flash2, aperture: Circle2) -> None:
        """Render flash circle to target image."""
        color = self.get_color(command.transform.polarity)
        transform = command.transform
        aperture_id = self.get_aperture_id(aperture, transform)
        aperture_group = self.get_aperture(aperture_id)

        if aperture_group is None:
            aperture_group = self.create_group_for_aperture(
                aperture.get_bounding_box(),
                aperture.hole_diameter,
            )
            aperture_group.append(
                drawsvg.Circle(
                    cx=0,
                    cy=0,
                    r=self.convert_size(aperture.diameter) / Decimal("2.0"),
                    fill=color,
                ),
            )
            self.set_aperture(aperture_id, aperture_group)

        self.add_element_to_frame(
            command.transform.polarity,
            drawsvg.Use(
                aperture_group,
                x=self.convert_x(command.flash_point.x),
                y=self.convert_y(command.flash_point.y),
            ),
        )

    def create_group_for_aperture(
        self,
        bbox: BoundingBox,
        hole_diameter: Optional[Offset],
    ) -> drawsvg.Group:
        """Create SVG group for aperture."""
        if hole_diameter is None:
            return drawsvg.Group()

        mask = self.create_mask(bbox)
        central_circle = drawsvg.Circle(
            cx=0,
            cy=0,
            r=self.convert_size(hole_diameter) / 2,
            fill="black",
        )
        mask.append(central_circle)

        return drawsvg.Group(mask=mask)

    def render_flash_no_circle(self, command: Flash2, aperture: NoCircle2) -> None:
        """Render flash no circle aperture to target image."""

    def render_flash_rectangle(self, command: Flash2, aperture: Rectangle2) -> None:
        """Render flash rectangle to target image."""
        color = self.get_color(command.transform.polarity)
        transform = command.transform
        aperture_id = self.get_aperture_id(aperture, transform)
        aperture_group = self.get_aperture(aperture_id)

        if aperture_group is None:
            aperture_group = self.create_group_for_aperture(
                aperture.get_bounding_box(),
                aperture.hole_diameter,
            )
            aperture_group.append(
                drawsvg.Rectangle(
                    -self.convert_size(aperture.x_size) / 2,
                    -self.convert_size(aperture.y_size) / 2,
                    self.convert_size(aperture.x_size),
                    self.convert_size(aperture.y_size),
                    fill=color,
                    transform=f"rotate(-{aperture.rotation})",
                ),
            )
            self.set_aperture(aperture_id, aperture_group)

        self.add_element_to_frame(
            command.transform.polarity,
            drawsvg.Use(
                aperture_group,
                self.convert_x(command.flash_point.x),
                self.convert_y(command.flash_point.y),
            ),
        )

    def render_flash_obround(self, command: Flash2, aperture: Obround2) -> None:
        """Render flash obround to target image."""
        color = self.get_color(command.transform.polarity)
        transform = command.transform
        aperture_id = self.get_aperture_id(aperture, transform)
        aperture_group = self.get_aperture(aperture_id)

        if aperture_group is None:
            aperture_group = self.create_group_for_aperture(
                aperture.get_bounding_box(),
                aperture.hole_diameter,
            )
            x_size = self.convert_size(aperture.x_size)
            y_size = self.convert_size(aperture.y_size)
            radius = x_size.min(y_size) / Decimal("2.0")

            aperture_group.append(
                drawsvg.Rectangle(
                    -self.convert_size(aperture.x_size) / 2,
                    -self.convert_size(aperture.y_size) / 2,
                    x_size,
                    y_size,
                    fill=color,
                    rx=radius,
                    ry=radius,
                    transform=f"rotate(-{aperture.rotation})",
                ),
            )
            self.set_aperture(aperture_id, aperture_group)

        self.add_element_to_frame(
            command.transform.polarity,
            drawsvg.Use(
                aperture_group,
                self.convert_x(command.flash_point.x),
                self.convert_y(command.flash_point.y),
            ),
        )

    def render_flash_polygon(self, command: Flash2, aperture: Polygon2) -> None:
        """Render flash polygon to target image."""
        color = self.get_color(command.transform.polarity)
        transform = command.transform
        aperture_id = self.get_aperture_id(aperture, transform)
        aperture_group = self.get_aperture(aperture_id)

        if aperture_group is None:
            aperture_group = self.create_group_for_aperture(
                aperture.get_bounding_box(),
                aperture.hole_diameter,
            )

            number_of_vertices = aperture.number_vertices
            initial_angle = aperture.rotation
            inner_angle = Decimal("360") / Decimal(number_of_vertices)

            radius_vector = Vector2D.UNIT_X * (aperture.outer_diameter / Decimal("2.0"))
            rotated_radius_vector = radius_vector.rotate_around_origin(initial_angle)

            p = drawsvg.Path(fill=color)
            p.M(
                f"{self.convert_size(rotated_radius_vector.x):.8f}",
                f"{self.convert_size(rotated_radius_vector.y):.8f}",
            )

            for i in range(1, number_of_vertices):
                rotation_angle = inner_angle * i + initial_angle
                rotated_radius_vector = radius_vector.rotate_around_origin(
                    rotation_angle,
                )
                p.L(
                    f"{self.convert_size(rotated_radius_vector.x):.8f}",
                    f"{self.convert_size(rotated_radius_vector.y):.8f}",
                )

            p.Z()

            aperture_group.append(p)
            self.set_aperture(aperture_id, aperture_group)

        self.add_element_to_frame(
            command.transform.polarity,
            drawsvg.Use(
                aperture_group,
                self.convert_x(command.flash_point.x),
                self.convert_y(command.flash_point.y),
            ),
        )

    def render_flash_macro(self, command: Flash2, aperture: Macro2) -> None:
        """Render flash macro aperture to target image."""
        transform = command.transform
        aperture_id = self.get_aperture_id(aperture, transform)
        aperture_group = self.get_aperture(aperture_id)

        if aperture_group is None:
            self.push_render_frame(
                command.get_bounding_box(),
                normalize_origin_to_0_0=False,
                flip_y=False,
            )
            for cmd in aperture.command_buffer:
                cmd.render(self.renderer)

            frame = self.pop_render_frame()
            aperture_group = frame.group
            self.set_aperture(aperture_id, aperture_group)

        self.add_element_to_frame(
            command.transform.polarity,
            drawsvg.Use(
                aperture_group,
                x=self.convert_x(command.flash_point.x),
                y=self.convert_y(command.flash_point.y),
            ),
        )

    def render_region(self, command: Region2) -> None:
        """Render region to target image."""
        if len(command.command_buffer) == 0:
            return

        self.current_frame.is_region = True

        color = self.get_color(command.transform.polarity)
        region = drawsvg.Path(fill=color)

        for cmd in command.command_buffer:
            if isinstance(cmd, (Line2, Arc2, CCArc2)):
                region.M(
                    f"{self.convert_x(cmd.start_point.x):.8f}",
                    f"{self.convert_y(cmd.start_point.y):.8f}",
                )
                break

        for cmd in command.command_buffer:
            if isinstance(cmd, Line2):
                self.render_line_to_path(cmd, region)
            elif isinstance(cmd, Arc2):
                self.render_arc_to_path(cmd, region)
            elif isinstance(cmd, CCArc2):
                self.render_cc_arc_to_path(cmd, region)
            else:
                raise NotImplementedError

        region.Z()
        self.add_element_to_frame(command.transform.polarity, region)

        self.current_frame.is_region = False

    def render_line_to_path(self, command: Line2, path: drawsvg.Path) -> None:
        """Render line region boundary."""
        path.L(
            f"{self.convert_x(command.end_point.x):.8f}",
            f"{self.convert_y(command.end_point.y):.8f}",
        )

    def render_arc_to_path(self, command: Arc2, path: drawsvg.Path) -> None:
        """Render line region boundary."""
        relative_start_vector = command.get_relative_start_point()
        relative_end_vector = command.get_relative_end_point()

        angle_clockwise = relative_start_vector.angle_between(relative_end_vector)
        angle_counter_clockwise = relative_start_vector.angle_between_cc(
            relative_end_vector,
        )
        # We want to render clockwise angle, so if cc angle is bigger, we need to
        # choose small angle.
        large_arc = angle_clockwise >= angle_counter_clockwise
        sweep = 1

        path.A(
            rx=f"{self.convert_size(command.get_radius()):.8f}",
            ry=f"{self.convert_size(command.get_radius()):.8f}",
            ex=f"{self.convert_x(command.end_point.x):.8f}",
            ey=f"{self.convert_y(command.end_point.y):.8f}",
            rot=0,
            large_arc=large_arc,
            sweep=sweep,
        )

    def render_cc_arc_to_path(self, command: CCArc2, path: drawsvg.Path) -> None:
        """Render line region boundary."""
        relative_start_vector = command.get_relative_start_point()
        relative_end_vector = command.get_relative_end_point()

        angle_clockwise = relative_start_vector.angle_between(relative_end_vector)
        angle_counter_clockwise = relative_start_vector.angle_between_cc(
            relative_end_vector,
        )
        # We want to render clockwise angle, so if cc angle is bigger, we need to
        # choose small angle.
        large_arc = not (angle_clockwise >= angle_counter_clockwise)
        sweep = 0

        path.A(
            rx=f"{self.convert_size(command.get_radius()):.8f}",
            ry=f"{self.convert_size(command.get_radius()):.8f}",
            ex=f"{self.convert_x(command.end_point.x):.8f}",
            ey=f"{self.convert_y(command.end_point.y):.8f}",
            rot=0,
            large_arc=large_arc,
            sweep=sweep,
        )

    def get_image_ref(self) -> ImageRef:
        """Get reference to render image."""
        return SvgImageRef(self.drawing)

    def finalize(self) -> None:
        """Finalize rendering."""
        if len(self.rendering_stack) > 1:
            self.rendering_stack = [self.rendering_stack[0]]
        elif len(self.rendering_stack) < 1:
            raise RuntimeError

        width = self.convert_size(self.current_frame.bounding_box.width)
        height = self.convert_size(self.current_frame.bounding_box.height)
        self.drawing = drawsvg.Drawing(
            width=width,
            height=height,
        )
        self.drawing.append(self.get_layer(Polarity.Dark))

base_frame property

base_frame: SvgRenderingFrame

Get base rendering stack frame.

current_frame property

current_frame: SvgRenderingFrame

Get current rendering stack frame.

init

init(
    renderer: Renderer2,
    command_buffer: ReadonlyCommandBuffer2,
) -> None

Initialize rendering hooks.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def init(
    self,
    renderer: Renderer2,
    command_buffer: ReadonlyCommandBuffer2,
) -> None:
    """Initialize rendering hooks."""
    if not isinstance(renderer, SvgRenderer2):
        raise NotImplementedError

    self.renderer = renderer
    self.command_buffer = command_buffer
    self.rendering_stack: list[SvgRenderingFrame] = [
        SvgRenderingFrame(
            bounding_box=self.command_buffer.get_bounding_box(),
            normalize_origin_to_0_0=True,
            flip_y=self.flip_y,
        ),
    ]
    self.apertures: dict[str, drawsvg.Group] = {}

push_render_frame

push_render_frame(
    bbox: BoundingBox,
    *,
    normalize_origin_to_0_0: bool,
    flip_y: bool
) -> None

Push new segment render frame.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def push_render_frame(
    self,
    bbox: BoundingBox,
    *,
    normalize_origin_to_0_0: bool,
    flip_y: bool,
) -> None:
    """Push new segment render frame."""
    self.rendering_stack.append(
        SvgRenderingFrame(
            bounding_box=bbox,
            normalize_origin_to_0_0=normalize_origin_to_0_0,
            flip_y=flip_y,
        ),
    )

pop_render_frame

pop_render_frame() -> SvgRenderingFrame

Pop segment render frame.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def pop_render_frame(self) -> SvgRenderingFrame:
    """Pop segment render frame."""
    if len(self.rendering_stack) <= 1:
        raise RuntimeError
    return self.rendering_stack.pop()

add_element_to_frame

add_element_to_frame(
    polarity: Polarity, element: drawsvg.DrawingBasicElement
) -> None

Add element to current frame.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def add_element_to_frame(
    self,
    polarity: Polarity,
    element: drawsvg.DrawingBasicElement,
) -> None:
    """Add element to current frame."""
    self.get_layer(polarity).append(element)

get_layer

get_layer(
    polarity: Polarity,
) -> drawsvg.Group | drawsvg.Mask

Get SVG layer object corresponding to polarity.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def get_layer(self, polarity: Polarity) -> drawsvg.Group | drawsvg.Mask:
    """Get SVG layer object corresponding to polarity."""
    # In general what we want to do is to have a layer made of group with mask.
    # First we fill the group with dark command, then after meeting first clear
    # command we start filling mask with consecutive clear command until
    # we meed dark command again. Then we create new group-mask layer to repeat the
    # cycle.

    # If frame is not initialized, initialize it.
    if self.current_frame.polarity is None:
        self.current_frame.polarity = polarity
        self.add_masked_group_to_frame()

        return self.current_frame.get_group_or_mask(polarity.is_solid())

    if polarity.is_solid() != self.current_frame.polarity.is_solid():
        # If polarity of frame is solid it means that mask for this group is still
        # empty and can be filled.
        if self.current_frame.polarity.is_solid():
            self.current_frame.polarity = polarity
            return self.current_frame.mask
        # If polarity of frame is clear, it means that we already filled
        # both group and mask and we need to create new group-mask layer.
        self.add_masked_group_to_frame()
        self.current_frame.polarity = polarity
        return self.current_frame.group

    # We have the same polarity as layer (and as previous commands) so we can
    # simply add it to current layer.
    return self.current_frame.get_group_or_mask(polarity.is_solid())

add_masked_group_to_frame

add_masked_group_to_frame() -> None

Create new layer including previous layer.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def add_masked_group_to_frame(self) -> None:
    """Create new layer including previous layer."""
    self.current_frame.mask = self.create_full_mask()
    new_layer = drawsvg.Group(mask=self.current_frame.mask)
    new_layer.append(self.current_frame.group)
    self.current_frame.group = new_layer

create_full_mask

create_full_mask() -> drawsvg.Mask

Create mask covering whole image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def create_full_mask(self) -> drawsvg.Mask:
    """Create mask covering whole image."""
    bbox = self.base_frame.bounding_box
    mask = drawsvg.Mask()
    mask.append(
        drawsvg.Rectangle(
            x=self.convert_size(-bbox.width / 2),
            y=self.convert_size(-bbox.height / 2),
            width=self.convert_size(bbox.width * 2),
            height=self.convert_size(bbox.height * 2),
            fill="white",
        ),
    )
    return mask

create_mask

create_mask(bbox: BoundingBox) -> drawsvg.Mask

Create mask covering specified bounding box.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def create_mask(self, bbox: BoundingBox) -> drawsvg.Mask:
    """Create mask covering specified bounding box."""
    mask = drawsvg.Mask()
    mask.append(
        drawsvg.Rectangle(
            x=self.convert_size(bbox.min_x),
            y=self.convert_size(bbox.min_y),
            width=self.convert_size(bbox.width),
            height=self.convert_size(bbox.height),
            fill="white",
        ),
    )
    return mask

convert_x

convert_x(x: Offset) -> Decimal

Convert y offset to y coordinate in image space.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def convert_x(self, x: Offset) -> Decimal:
    """Convert y offset to y coordinate in image space."""
    if self.current_frame.normalize_origin_to_0_0:
        origin_offset_x = self.current_frame.bounding_box.min_x.as_millimeters()
    else:
        origin_offset_x = Decimal(0)

    corrected_position_x = x.as_millimeters() - origin_offset_x

    return corrected_position_x * self.scale

convert_y

convert_y(y: Offset) -> Decimal

Convert y offset to y coordinate in image space.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def convert_y(self, y: Offset) -> Decimal:
    """Convert y offset to y coordinate in image space."""
    return self._convert_y(
        y,
        normalize_origin_to_0_0=self.current_frame.normalize_origin_to_0_0,
        flip_y=self.current_frame.flip_y,
    )

convert_size

convert_size(diameter: Offset) -> Decimal

Convert y offset to pixel y coordinate.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def convert_size(self, diameter: Offset) -> Decimal:
    """Convert y offset to pixel y coordinate."""
    return diameter.as_millimeters() * self.scale

get_color

get_color(polarity: Polarity) -> str

Get color for specified polarity.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def get_color(self, polarity: Polarity) -> str:
    """Get color for specified polarity."""
    if self.current_frame.is_region:
        if polarity.is_solid():
            return self.color_scheme.solid_region_color.to_hex()
        return "black"

    if polarity.is_solid():
        return self.color_scheme.solid_color.to_hex()
    return "black"

get_aperture_id

get_aperture_id(
    aperture: Aperture2, transform: ApertureTransform
) -> str

Get unique ID for aperture.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def get_aperture_id(self, aperture: Aperture2, transform: ApertureTransform) -> str:
    """Get unique ID for aperture."""
    return (
        f"{aperture.identifier}%"
        f"{transform.get_transform_key()}%{transform.polarity}"
    )

get_aperture

get_aperture(aperture_id: str) -> Optional[drawsvg.Group]

Get SVG group representing aperture.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def get_aperture(self, aperture_id: str) -> Optional[drawsvg.Group]:
    """Get SVG group representing aperture."""
    return self.apertures.get(aperture_id)

set_aperture

set_aperture(
    aperture_id: str, aperture: drawsvg.Group
) -> None

Set SVG group representing aperture.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def set_aperture(
    self,
    aperture_id: str,
    aperture: drawsvg.Group,
) -> None:
    """Set SVG group representing aperture."""
    self.apertures[aperture_id] = aperture

render_line

render_line(command: Line2) -> None

Render line to target image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_line(self, command: Line2) -> None:
    """Render line to target image."""
    color = self.get_color(command.transform.polarity)

    command.aperture.render_flash(
        self.renderer,
        Flash2(
            transform=command.transform,
            attributes=command.attributes,
            aperture=command.aperture,
            flash_point=command.start_point,
        ),
    )

    parallel_vector = command.start_point - command.end_point
    perpendicular_vector = parallel_vector.perpendicular()
    normalized_perpendicular_vector = perpendicular_vector.normalize()
    point_offset = normalized_perpendicular_vector * (
        command.aperture.get_stroke_width() / 2.0
    )

    p0 = command.start_point - point_offset
    p1 = command.start_point + point_offset
    p2 = command.end_point + point_offset
    p3 = command.end_point - point_offset

    rectangle = drawsvg.Lines(
        f"{self.convert_x(p0.x):.8f}",
        f"{self.convert_y(p0.y):.8f}",
        f"{self.convert_x(p1.x):.8f}",
        f"{self.convert_y(p1.y):.8f}",
        f"{self.convert_x(p2.x):.8f}",
        f"{self.convert_y(p2.y):.8f}",
        f"{self.convert_x(p3.x):.8f}",
        f"{self.convert_y(p3.y):.8f}",
        fill=color,
        close=True,
    )
    self.add_element_to_frame(command.transform.polarity, rectangle)

    command.aperture.render_flash(
        self.renderer,
        Flash2(
            transform=command.transform,
            attributes=command.attributes,
            aperture=command.aperture,
            flash_point=command.end_point,
        ),
    )

render_arc

render_arc(command: Arc2) -> None

Render arc to target image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_arc(self, command: Arc2) -> None:
    """Render arc to target image."""
    color = self.get_color(command.transform.polarity)
    # Arcs which start and end point overlaps are completely invisible in SVG.
    # Therefore we need to replace them with two half-full-arcs.
    # THB spec recommends doing it when exporting Gerber files, to avoid problems
    # with floating point numbers, but I guess nobody does that.
    if command.start_point == command.end_point:
        # This is a vector from center to start point, so we can invert it and
        # apply it twice to get the point on the opposite side of the center point.
        relative = command.get_relative_start_point()
        # Now we cen recursively invoke self with two modified copies of this
        # command.
        self.render_arc(
            command.model_copy(
                update={
                    "start_point": command.start_point,
                    "end_point": command.start_point - (relative * 2),
                },
            ),
        )
        self.render_arc(
            command.model_copy(
                update={
                    "start_point": command.start_point - (relative * 2),
                    "end_point": command.start_point,
                },
            ),
        )
        return

    command.aperture.render_flash(
        self.renderer,
        Flash2(
            transform=command.transform,
            attributes=command.attributes,
            aperture=command.aperture,
            flash_point=command.start_point,
        ),
    )
    # First we calculate perpendicular vector. This vector is always pointing
    # from the center, thus it is perpendicular to arc.
    # Then we can normalize it and multiply by half of aperture diameter,
    # effectively giving us vector pointing to inner/outer edge of line.
    # We can ignore the fact that we don't know which point (inner/outer) we
    # have, as long as we get the same every time, then we can pair it with
    # corresponding vector made from end point and create single arc,
    # Then invert both vectors and draw second arc.
    start_perpendicular_vector = command.get_relative_start_point()
    start_normalized_perpendicular_vector = start_perpendicular_vector.normalize()
    start_point_offset = start_normalized_perpendicular_vector * (
        command.aperture.get_stroke_width() / 2.0
    )

    end_perpendicular_vector = command.get_relative_end_point()
    end_normalized_perpendicular_vector = end_perpendicular_vector.normalize()
    end_point_offset = end_normalized_perpendicular_vector * (
        command.aperture.get_stroke_width() / 2.0
    )

    arc_path = drawsvg.Path(fill=color)

    # Determine start point of inner arc.
    start_inner = command.start_point + start_point_offset
    end_inner = command.end_point + end_point_offset
    # Move path ptr to inner arc start point.
    arc_path.M(
        f"{self.convert_x(start_inner.x):.8f}",
        f"{self.convert_y(start_inner.y):.8f}",
    )
    self.render_arc_to_path(
        command.model_copy(
            update={
                "start_point": start_inner,
                "end_point": end_inner,
            },
        ),
        arc_path,
    )
    # Determine start point of outer arc.
    # This arc have to be in reverse direction, so we swap start/end points.
    start_outer = command.end_point - end_point_offset
    end_outer = command.start_point - start_point_offset
    # Draw line between end of inner arc and start of outer arc.
    arc_path.L(
        f"{self.convert_x(start_outer.x):.8f}",
        f"{self.convert_y(start_outer.y):.8f}",
    )
    self.render_cc_arc_to_path(
        CCArc2(
            transform=command.transform,
            attributes=command.attributes,
            aperture=command.aperture,
            start_point=start_outer,
            center_point=command.center_point,
            end_point=end_outer,
        ),
        arc_path,
    )
    # Close arc box by drawing line between end of outer arc and start of inner
    arc_path.Z()
    self.add_element_to_frame(command.transform.polarity, arc_path)

    command.aperture.render_flash(
        self.renderer,
        Flash2(
            transform=command.transform,
            attributes=command.attributes,
            aperture=command.aperture,
            flash_point=command.end_point,
        ),
    )

render_cc_arc

render_cc_arc(command: CCArc2) -> None

Render arc to target image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_cc_arc(self, command: CCArc2) -> None:
    """Render arc to target image."""
    self.render_arc(
        command.model_copy(
            update={
                "start_point": command.end_point,
                "end_point": command.start_point,
            },
        ),
    )

render_flash_circle

render_flash_circle(
    command: Flash2, aperture: Circle2
) -> None

Render flash circle to target image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_flash_circle(self, command: Flash2, aperture: Circle2) -> None:
    """Render flash circle to target image."""
    color = self.get_color(command.transform.polarity)
    transform = command.transform
    aperture_id = self.get_aperture_id(aperture, transform)
    aperture_group = self.get_aperture(aperture_id)

    if aperture_group is None:
        aperture_group = self.create_group_for_aperture(
            aperture.get_bounding_box(),
            aperture.hole_diameter,
        )
        aperture_group.append(
            drawsvg.Circle(
                cx=0,
                cy=0,
                r=self.convert_size(aperture.diameter) / Decimal("2.0"),
                fill=color,
            ),
        )
        self.set_aperture(aperture_id, aperture_group)

    self.add_element_to_frame(
        command.transform.polarity,
        drawsvg.Use(
            aperture_group,
            x=self.convert_x(command.flash_point.x),
            y=self.convert_y(command.flash_point.y),
        ),
    )

create_group_for_aperture

create_group_for_aperture(
    bbox: BoundingBox, hole_diameter: Optional[Offset]
) -> drawsvg.Group

Create SVG group for aperture.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def create_group_for_aperture(
    self,
    bbox: BoundingBox,
    hole_diameter: Optional[Offset],
) -> drawsvg.Group:
    """Create SVG group for aperture."""
    if hole_diameter is None:
        return drawsvg.Group()

    mask = self.create_mask(bbox)
    central_circle = drawsvg.Circle(
        cx=0,
        cy=0,
        r=self.convert_size(hole_diameter) / 2,
        fill="black",
    )
    mask.append(central_circle)

    return drawsvg.Group(mask=mask)

render_flash_no_circle

render_flash_no_circle(
    command: Flash2, aperture: NoCircle2
) -> None

Render flash no circle aperture to target image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_flash_no_circle(self, command: Flash2, aperture: NoCircle2) -> None:
    """Render flash no circle aperture to target image."""

render_flash_rectangle

render_flash_rectangle(
    command: Flash2, aperture: Rectangle2
) -> None

Render flash rectangle to target image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_flash_rectangle(self, command: Flash2, aperture: Rectangle2) -> None:
    """Render flash rectangle to target image."""
    color = self.get_color(command.transform.polarity)
    transform = command.transform
    aperture_id = self.get_aperture_id(aperture, transform)
    aperture_group = self.get_aperture(aperture_id)

    if aperture_group is None:
        aperture_group = self.create_group_for_aperture(
            aperture.get_bounding_box(),
            aperture.hole_diameter,
        )
        aperture_group.append(
            drawsvg.Rectangle(
                -self.convert_size(aperture.x_size) / 2,
                -self.convert_size(aperture.y_size) / 2,
                self.convert_size(aperture.x_size),
                self.convert_size(aperture.y_size),
                fill=color,
                transform=f"rotate(-{aperture.rotation})",
            ),
        )
        self.set_aperture(aperture_id, aperture_group)

    self.add_element_to_frame(
        command.transform.polarity,
        drawsvg.Use(
            aperture_group,
            self.convert_x(command.flash_point.x),
            self.convert_y(command.flash_point.y),
        ),
    )

render_flash_obround

render_flash_obround(
    command: Flash2, aperture: Obround2
) -> None

Render flash obround to target image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_flash_obround(self, command: Flash2, aperture: Obround2) -> None:
    """Render flash obround to target image."""
    color = self.get_color(command.transform.polarity)
    transform = command.transform
    aperture_id = self.get_aperture_id(aperture, transform)
    aperture_group = self.get_aperture(aperture_id)

    if aperture_group is None:
        aperture_group = self.create_group_for_aperture(
            aperture.get_bounding_box(),
            aperture.hole_diameter,
        )
        x_size = self.convert_size(aperture.x_size)
        y_size = self.convert_size(aperture.y_size)
        radius = x_size.min(y_size) / Decimal("2.0")

        aperture_group.append(
            drawsvg.Rectangle(
                -self.convert_size(aperture.x_size) / 2,
                -self.convert_size(aperture.y_size) / 2,
                x_size,
                y_size,
                fill=color,
                rx=radius,
                ry=radius,
                transform=f"rotate(-{aperture.rotation})",
            ),
        )
        self.set_aperture(aperture_id, aperture_group)

    self.add_element_to_frame(
        command.transform.polarity,
        drawsvg.Use(
            aperture_group,
            self.convert_x(command.flash_point.x),
            self.convert_y(command.flash_point.y),
        ),
    )

render_flash_polygon

render_flash_polygon(
    command: Flash2, aperture: Polygon2
) -> None

Render flash polygon to target image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_flash_polygon(self, command: Flash2, aperture: Polygon2) -> None:
    """Render flash polygon to target image."""
    color = self.get_color(command.transform.polarity)
    transform = command.transform
    aperture_id = self.get_aperture_id(aperture, transform)
    aperture_group = self.get_aperture(aperture_id)

    if aperture_group is None:
        aperture_group = self.create_group_for_aperture(
            aperture.get_bounding_box(),
            aperture.hole_diameter,
        )

        number_of_vertices = aperture.number_vertices
        initial_angle = aperture.rotation
        inner_angle = Decimal("360") / Decimal(number_of_vertices)

        radius_vector = Vector2D.UNIT_X * (aperture.outer_diameter / Decimal("2.0"))
        rotated_radius_vector = radius_vector.rotate_around_origin(initial_angle)

        p = drawsvg.Path(fill=color)
        p.M(
            f"{self.convert_size(rotated_radius_vector.x):.8f}",
            f"{self.convert_size(rotated_radius_vector.y):.8f}",
        )

        for i in range(1, number_of_vertices):
            rotation_angle = inner_angle * i + initial_angle
            rotated_radius_vector = radius_vector.rotate_around_origin(
                rotation_angle,
            )
            p.L(
                f"{self.convert_size(rotated_radius_vector.x):.8f}",
                f"{self.convert_size(rotated_radius_vector.y):.8f}",
            )

        p.Z()

        aperture_group.append(p)
        self.set_aperture(aperture_id, aperture_group)

    self.add_element_to_frame(
        command.transform.polarity,
        drawsvg.Use(
            aperture_group,
            self.convert_x(command.flash_point.x),
            self.convert_y(command.flash_point.y),
        ),
    )

render_flash_macro

render_flash_macro(
    command: Flash2, aperture: Macro2
) -> None

Render flash macro aperture to target image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_flash_macro(self, command: Flash2, aperture: Macro2) -> None:
    """Render flash macro aperture to target image."""
    transform = command.transform
    aperture_id = self.get_aperture_id(aperture, transform)
    aperture_group = self.get_aperture(aperture_id)

    if aperture_group is None:
        self.push_render_frame(
            command.get_bounding_box(),
            normalize_origin_to_0_0=False,
            flip_y=False,
        )
        for cmd in aperture.command_buffer:
            cmd.render(self.renderer)

        frame = self.pop_render_frame()
        aperture_group = frame.group
        self.set_aperture(aperture_id, aperture_group)

    self.add_element_to_frame(
        command.transform.polarity,
        drawsvg.Use(
            aperture_group,
            x=self.convert_x(command.flash_point.x),
            y=self.convert_y(command.flash_point.y),
        ),
    )

render_region

render_region(command: Region2) -> None

Render region to target image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_region(self, command: Region2) -> None:
    """Render region to target image."""
    if len(command.command_buffer) == 0:
        return

    self.current_frame.is_region = True

    color = self.get_color(command.transform.polarity)
    region = drawsvg.Path(fill=color)

    for cmd in command.command_buffer:
        if isinstance(cmd, (Line2, Arc2, CCArc2)):
            region.M(
                f"{self.convert_x(cmd.start_point.x):.8f}",
                f"{self.convert_y(cmd.start_point.y):.8f}",
            )
            break

    for cmd in command.command_buffer:
        if isinstance(cmd, Line2):
            self.render_line_to_path(cmd, region)
        elif isinstance(cmd, Arc2):
            self.render_arc_to_path(cmd, region)
        elif isinstance(cmd, CCArc2):
            self.render_cc_arc_to_path(cmd, region)
        else:
            raise NotImplementedError

    region.Z()
    self.add_element_to_frame(command.transform.polarity, region)

    self.current_frame.is_region = False

render_line_to_path

render_line_to_path(
    command: Line2, path: drawsvg.Path
) -> None

Render line region boundary.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_line_to_path(self, command: Line2, path: drawsvg.Path) -> None:
    """Render line region boundary."""
    path.L(
        f"{self.convert_x(command.end_point.x):.8f}",
        f"{self.convert_y(command.end_point.y):.8f}",
    )

render_arc_to_path

render_arc_to_path(
    command: Arc2, path: drawsvg.Path
) -> None

Render line region boundary.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_arc_to_path(self, command: Arc2, path: drawsvg.Path) -> None:
    """Render line region boundary."""
    relative_start_vector = command.get_relative_start_point()
    relative_end_vector = command.get_relative_end_point()

    angle_clockwise = relative_start_vector.angle_between(relative_end_vector)
    angle_counter_clockwise = relative_start_vector.angle_between_cc(
        relative_end_vector,
    )
    # We want to render clockwise angle, so if cc angle is bigger, we need to
    # choose small angle.
    large_arc = angle_clockwise >= angle_counter_clockwise
    sweep = 1

    path.A(
        rx=f"{self.convert_size(command.get_radius()):.8f}",
        ry=f"{self.convert_size(command.get_radius()):.8f}",
        ex=f"{self.convert_x(command.end_point.x):.8f}",
        ey=f"{self.convert_y(command.end_point.y):.8f}",
        rot=0,
        large_arc=large_arc,
        sweep=sweep,
    )

render_cc_arc_to_path

render_cc_arc_to_path(
    command: CCArc2, path: drawsvg.Path
) -> None

Render line region boundary.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def render_cc_arc_to_path(self, command: CCArc2, path: drawsvg.Path) -> None:
    """Render line region boundary."""
    relative_start_vector = command.get_relative_start_point()
    relative_end_vector = command.get_relative_end_point()

    angle_clockwise = relative_start_vector.angle_between(relative_end_vector)
    angle_counter_clockwise = relative_start_vector.angle_between_cc(
        relative_end_vector,
    )
    # We want to render clockwise angle, so if cc angle is bigger, we need to
    # choose small angle.
    large_arc = not (angle_clockwise >= angle_counter_clockwise)
    sweep = 0

    path.A(
        rx=f"{self.convert_size(command.get_radius()):.8f}",
        ry=f"{self.convert_size(command.get_radius()):.8f}",
        ex=f"{self.convert_x(command.end_point.x):.8f}",
        ey=f"{self.convert_y(command.end_point.y):.8f}",
        rot=0,
        large_arc=large_arc,
        sweep=sweep,
    )

get_image_ref

get_image_ref() -> ImageRef

Get reference to render image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def get_image_ref(self) -> ImageRef:
    """Get reference to render image."""
    return SvgImageRef(self.drawing)

finalize

finalize() -> None

Finalize rendering.

Source code in src\pygerber\gerberx3\renderer2\svg.py
def finalize(self) -> None:
    """Finalize rendering."""
    if len(self.rendering_stack) > 1:
        self.rendering_stack = [self.rendering_stack[0]]
    elif len(self.rendering_stack) < 1:
        raise RuntimeError

    width = self.convert_size(self.current_frame.bounding_box.width)
    height = self.convert_size(self.current_frame.bounding_box.height)
    self.drawing = drawsvg.Drawing(
        width=width,
        height=height,
    )
    self.drawing.append(self.get_layer(Polarity.Dark))

SvgImageRef

Bases: ImageRef

Generic container for reference to rendered image.

Source code in src\pygerber\gerberx3\renderer2\svg.py
class SvgImageRef(ImageRef):
    """Generic container for reference to rendered image."""

    def __init__(self, image: drawsvg.Drawing) -> None:
        self.image = image

    def _save_to_io(
        self,
        output: BinaryIO,
        options: Optional[FormatOptions] = None,  # noqa: ARG002
    ) -> None:
        """Save rendered image to bytes stream buffer."""
        svg = self.image.as_svg()
        if svg is None:
            return
        output.write(svg.encode("utf-8"))

SvgFormatOptions

Format options for SVG format.

Source code in src\pygerber\gerberx3\renderer2\svg.py
class SvgFormatOptions:
    """Format options for SVG format."""