vydd / sketch

A Common Lisp framework for the creation of electronic art, visual design, game prototyping, game making, computer graphics, exploration of human-computer interaction, and more.
MIT License
1.39k stars 66 forks source link

Extend triangulate optimisation to quadrilaterals. #129

Closed Kevinpgalligan closed 6 months ago

Kevinpgalligan commented 6 months ago

Avoids calling the 2d-geometry package if the polygon in question has 4 sides, since we can easily triangulate it by hand.

Also added a comment to the polygon code example in the docs that describes the limitations of this drawing function.

Testing:

(defsketch triangle-test ()
   (polygon 90 90 100 100 110 90) ; triangle
   (polygon 0 0 0 40 20 35 40 20) ; quadrilateral
   (polygon 150 150 170 150 180 180 170 180 150 180) ; 5-sided polygon
   (stop-loop))

(Can call (trace 2d-geometry:make-polygon-from-coords) to show that the heavyweight triangulation code is only getting called for the 5-sided polygon).

Gleefre commented 6 months ago

This doesn't work for non-convex polygons:

(defpackage #:sketch-user
  (:use #:cl #:sketch))

(in-package #:sketch-user)

(defparameter *points* (list 3 3
                             5 5
                             7 3
                             5 9))

(defsketch foo ((resizable t))
  (with-fit (10 10 width height)
    (with-pen (make-pen :fill +white+ :stroke +red+ :weight 0.1)
      (apply #'polygon *points*))
    (with-pen (make-pen :stroke +black+)
      (mapcar (lambda (xy) (apply #'point xy)) (sketch::group *points* 2)))))

(make-instance 'foo)

Before this change: image

After this change: image

Kevinpgalligan commented 6 months ago

Ooh, nice catch. I think I accidentally made all of my test cases convex. I guess this would require testing for convexity and ordering the points accordingly.

Gleefre commented 6 months ago

It also has a problem with self-intersecting quads: image vs image

Kevinpgalligan commented 6 months ago

Oh ya, I added a mention of that in the docs. But maybe not worth changing the behaviour for a short-term fix.

vydd commented 6 months ago

I don't think it's worth merging if it's going to break the current functionality, especially for concave polygons.

Kevinpgalligan commented 6 months ago

Agreed, I'll close for now, may or may not come back to this and add the necessary fix.

Kevinpgalligan commented 6 months ago

In the meantime, we should prob update the docs to say that polygon expects rational coordinates.