# PShape Intersections

**URL:** <https://discourse.processing.org/t/pshape-intersections/32616>\
**Category:** Libraries\
**Created:** [October 4, 2021, 9:01pm UTC](https://discourse.processing.org/t/pshape-intersections/32616 "2021-10-04T21:01:58Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![TomD](https://avatars.discourse-cdn.com/v4/letter/t/b4bc9f/32.png) [@TomD](https://discourse.processing.org/u/TomD)\
**Post date:** [October 4, 2021, 9:01pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/1 "2021-10-04T21:01:59Z")

</div>

Hi there 👋

I’m using processing to generate SVG files for pen plotting.

I have a PShape object which is a custom geometry, I would like to use that geometry as a mask/intersection or a boolean check to then draw a some additional geometry within it as a fill.

I’m not able to use textures or PImage objects for the fill as I need to be able to export an SVG at the end of the script.

I’m aware of RShape from geometrive, which does offer a handy .intersection() function, although I’m not sure how to get that to play nicely with my PShape objects.

Are there any other methods I could investigate to solve my problem?  
(I’m trying to avoid writing lengthy region checks)

For reference; the geometries that I would like to fill are these sections of a circle:

 ![image](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/6/6d1f81a578cbd8a9fd13f985274d30c7562bcd8e.png)

Thanks for any help you can offer.

---

<div class="post-metadata">

**Author:** ![tabreturn](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/tabreturn/32/3697_2.png) [@tabreturn](https://discourse.processing.org/u/tabreturn)\
**Post date:** [October 5, 2021, 6:58am UTC](https://discourse.processing.org/t/pshape-intersections/32616/2 "2021-10-05T06:58:50Z")

</div>

This is a bit of a hack, maybe not an answer you’re looking for …

Sometimes I render ‘whole’ shapes in the Processing sketch, then apply the ‘boolean’ operation I desire in Inkscape (you might even automate this using [Inkscape’s command line mode](https://wiki.inkscape.org/wiki/Using_the_Command_Line)). So, the fill is one set of shapes, and the mask another. Additionally, you [can separate shapes into layers](https://discourse.processing.org/t/how-to-control-layers-when-exporting-an-svg/21758/6) to make the Inkscape work easier.

I’d rather expedite the process of getting results onto paper when I’m plotting, even if the sketch isn’t ‘fully-automated.’

---

<div class="post-metadata">

**Author:** ![micycle](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/micycle/32/201_2.png) [@micycle](https://discourse.processing.org/u/micycle)\
**Post date:** [October 5, 2021, 7:46am UTC](https://discourse.processing.org/t/pshape-intersections/32616/3 "2021-10-05T07:46:41Z")

</div>

[Processing Geometry Suite](https://discourse.processing.org/t/processing-geometry-suite/29924) provides 2D shape boolean operations like _Geomerative_ but takes in (and outputs) PShapes.

---

<div class="post-metadata">

**Author:** ![TomD](https://avatars.discourse-cdn.com/v4/letter/t/b4bc9f/32.png) [@TomD](https://discourse.processing.org/u/TomD)\
**Post date:** [October 5, 2021, 1:36pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/4 "2021-10-05T13:36:39Z")

</div>

Wow! That’s a seriously well featured suite!

There’s a lot of methods in there that I’d been putting off trying for fear of over-complication.

I’m going to enjoy playing with this package, thank you very much!

---

<div class="post-metadata">

**Author:** ![TomD](https://avatars.discourse-cdn.com/v4/letter/t/b4bc9f/32.png) [@TomD](https://discourse.processing.org/u/TomD)\
**Post date:** [October 5, 2021, 1:41pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/5 "2021-10-05T13:41:36Z")

</div>

Yeah that is a bit of a hack… 😬  
I once lined some disparate parts of a plot up in Inkscape and still feel a little guilty about it.

I guess I take the opinion that the final drawing is only an abstraction of the input code if it remains as unadulterated as possible throughout the entire digital workflow.  
I’m either a purist or a pedant and I’m not sure which is worse! 😅

---

<div class="post-metadata">

**Author:** ![TomD](https://avatars.discourse-cdn.com/v4/letter/t/b4bc9f/32.png) [@TomD](https://discourse.processing.org/u/TomD)\
**Post date:** [October 5, 2021, 7:00pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/6 "2021-10-05T19:00:57Z")

</div>

I’m having some issues getting .intersection to work as I’d expect.

As above I’m taking my sectioned circle and trying to fill each section with some diagonal lines.

I’m applying your .intersection() method as below:

```auto
      shape(section);
      if (i%2==0) {
        fill = PGS_ShapeBoolean.intersect(section, leftFill);
      } else {
        fill = PGS_ShapeBoolean.intersect(section, rightFill);
      }
      PGS_Conversion.setAllStrokeColor(fill, 0, 1);
      shape(fill);

```

I’m seeing vertical lines being output, not the diagonal lines that are contained in rightFill & leftFill.

 ![image](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/9/9cf9a484b8d3664935a54bd05e07388cdea63019.png)

Any thoughts?

---

<div class="post-metadata">

**Author:** ![micycle](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/micycle/32/201_2.png) [@micycle](https://discourse.processing.org/u/micycle)\
**Post date:** [October 6, 2021, 10:05am UTC](https://discourse.processing.org/t/pshape-intersections/32616/7 "2021-10-06T10:05:45Z")

</div>

Can you post your full code? I’m not fully clear about what you’re trying to do… slice the vertical strips? What are leftFill and rightFill exactly?

---

<div class="post-metadata">

**Author:** ![TomD](https://avatars.discourse-cdn.com/v4/letter/t/b4bc9f/32.png) [@TomD](https://discourse.processing.org/u/TomD)\
**Post date:** [October 7, 2021, 7:40pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/8 "2021-10-07T19:40:30Z")

</div>

Excuse my messy code!  
The idea is that I generate the sectioned circle as above and then fill each section with an alternating fill, leftFill & rightFill. Which are PShape objects made up of many diagonal lines with varying spacing.

I had hoped that .intersect() would allow me to make a masked PShape object to apply rightFill & leftFill to the main sectioned circle shape. Although I’m guessing that I’m getting my use cases mixed up…

```auto
import processing.svg.*;
import micycle.pgs.*;

void setup() {
  size(420, 594);
  background(255);
  noLoop();
  noFill();
  beginRecord(SVG, "sectionedCircle.svg");
}

PShape createLineFills(float a, float maxspacing) {
  float spacing = maxspacing;
  PShape line = createShape();
  
  line.beginShape(LINES);
  for (float x=-height; x<=height; x+=spacing) {
    line.vertex(x, -height);
    line.vertex(x, height);
    spacing = map(noise(x*0.01), 0, 1, 0, maxspacing);
  }
  line.endShape();
  line.rotate(a);
  return line;
}

float sagitta(float r, float s) {
  return sqrt(2*s*r-s*s);
}

void drawSectionedLinedCircle(float x, float y, float r, int n) {
  translate(x, y);
  float rInc = (2*r)/n;
  float s = rInc;
  float a1 = 0;
  float a2 = asin(sagitta(r, s)/r);
  float maxShift = 100;
  float scale = 0.15;

  PShape leftFill = createLineFills(QUARTER_PI, 50);
  PShape rightFill = createLineFills(-QUARTER_PI, 50);
  PShape fill;

  while (a2<=PI) {
    for (float i=0; i<n; i++) {
      
      pushMatrix();
      translate(0, map(noise(i*scale), 0, 1, -maxShift, maxShift));
      
      PShape section = createShape();
      section.beginShape();

      for (float a=a1; a<=a2; a+=radians(0.5)) {
        section.vertex(r*cos(a), r*sin(a));
      }
      
      for (float a=a2; a>=a1; a-=radians(0.5)) {
        section.vertex(r*cos(-a), r*sin(-a));
      }
      section.endShape(CLOSE);
      
      a1 = a2;
      s += rInc;
      a2 = asin(sagitta(r, s)/r);
      if (s>=r)
        a2 += 2*(HALF_PI-a2);
      //println(degrees(a2));

      shape(section);
      if (i%2==0) {
        fill = PGS_ShapeBoolean.intersect(section, leftFill);
      } else {
        fill = PGS_ShapeBoolean.intersect(section, rightFill);
      }
      PGS_Conversion.setAllStrokeColor(fill, 150, 2);
      shape(fill);
      popMatrix();
    }
  }
}

void draw() {
  drawSectionedLinedCircle(width/2, height/2, width/2, 9);
  endRecord();
}

```

---

<div class="post-metadata">

**Author:** ![micycle](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/micycle/32/201_2.png) [@micycle](https://discourse.processing.org/u/micycle)\
**Post date:** [October 8, 2021, 5:27pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/9 "2021-10-08T17:27:48Z")

</div>

Your approach was correct, but you were thrown off by the way geometry operations work. Lines are 1D objects (they have no “height”) so intersecting a line with a polygon returns nothing. The solution is to buffer the lines into actual 2D polygons so `intersection()` becomes a meaningful operation.

I’ve also had to replace `line.rotate(a)` with a _PGS_ rotation method. The problem with `.rotate()` is that it affects the shape’s _rotation matrix_ only and not the actual coordinates of its vertices. A PShape’s rotation matrix is not accessible and so the buffer() method would otherwise buffer the unrotated (vertical) lines.

So in the end only your `createLineFills()` method needed changing in the last few lines.

```auto
PShape createLineFills(float a, float maxspacing) {
  float spacing = maxspacing;
  PShape line = createShape();

  line.beginShape(LINES);
  for (float x=-height; x<=height; x+=spacing) {
    line.vertex(x, -height);
    line.vertex(x, height);
    spacing = map(noise(x*0.01), 0, 1, 0, maxspacing);
  }
  line.endShape();
  line = PGS_Transformation.rotateAroundCenter(line, a);
  line = PGS_Morphology.buffer(line, 1);
  return line;
}

```

![image](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/f/f3087f536363d920e55a489afd3c4a876f36dc88.png)

---

<div class="post-metadata">

**Author:** ![TomD](https://avatars.discourse-cdn.com/v4/letter/t/b4bc9f/32.png) [@TomD](https://discourse.processing.org/u/TomD)\
**Post date:** [October 8, 2021, 11:16pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/10 "2021-10-08T23:16:48Z")

</div>

Ah Thanks so much!  
I think I’m going to spend some time exploring the quirks of PGS further.

Glad to be able to put a lid on this little project. The final output is interesting to look at, but I’m very excited to be able to quickly and easily create fills for custom geometry.

Thanks Again!

 ![PXL_20211008_230502960](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/6/6a3fe7abd0101912c838fa2b2a2cfeecb32b834b.jpeg)

---

<div class="post-metadata">

**Author:** ![computershawn](https://avatars.discourse-cdn.com/v4/letter/c/439d5e/32.png) [@computershawn](https://discourse.processing.org/u/computershawn)\
**Post date:** [October 11, 2022, 8:24pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/11 "2022-10-11T20:24:51Z")

</div>

@micycle PGS is exactly the tool that will make one of my projects easier to do. There’s something in your above ‘createLineFills’ method here that’s baffling me though. It seems like all lines are somehow getting doubled? Even if I strip out the ‘for’ loops and use line.vertex to draw a single diagonal from the upper-left to the lower-right of the container, it renders (and saves as an SVG) with two diagonal lines separated by a few pixels. Is this a known quirk, and/or is there a way to have it draw just a single line?

Edit: I just read your response above about needing the lines to form a closed loop in order for the intersection operation to work.

---

<div class="post-metadata">

**Author:** ![micycle](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/micycle/32/201_2.png) [@micycle](https://discourse.processing.org/u/micycle)\
**Post date:** [October 12, 2022, 9:39pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/12 "2022-10-12T21:39:17Z")

</div>

What I said before was actually incorrect. PGS can (at least now) intersect a LINES shape with a polygon, returning the linework as expected. For instance, a hilbert curve intersected with a heart-shaped polygon:

 ![image](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/3X/1/8/18fe0316a067c1fa38bea37e419c1fd72df06d39.png)

---

<div class="post-metadata">

**Author:** ![computershawn](https://avatars.discourse-cdn.com/v4/letter/c/439d5e/32.png) [@computershawn](https://discourse.processing.org/u/computershawn)\
**Post date:** [October 12, 2022, 10:06pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/13 "2022-10-12T22:06:08Z")

</div>

@micycle sweet, is that a more recent development? I need to check which version of PGS I’m using and update if it’s not the current.

---

<div class="post-metadata">

**Author:** ![micycle](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/micycle/32/201_2.png) [@micycle](https://discourse.processing.org/u/micycle)\
**Post date:** [October 12, 2022, 10:23pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/14 "2022-10-12T22:23:02Z")

</div>

Well I’m not sure why I didn’t think it worked like that before. Either way, latest dev build is [here](https://github.com/micycle1/PGS/suites/8702075034/artifacts/392846112).

---

<div class="post-metadata">

**Author:** ![computershawn](https://avatars.discourse-cdn.com/v4/letter/c/439d5e/32.png) [@computershawn](https://discourse.processing.org/u/computershawn)\
**Post date:** [October 12, 2022, 10:37pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/15 "2022-10-12T22:37:23Z")

</div>

Thanks for sharing this project! 🙌🏽

---

<div class="post-metadata">

**Author:** ![computershawn](https://avatars.discourse-cdn.com/v4/letter/c/439d5e/32.png) [@computershawn](https://discourse.processing.org/u/computershawn)\
**Post date:** [July 15, 2023, 8:37pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/16 "2023-07-15T20:37:41Z")

</div>

Hey @micycle quick question on using `intersect`… I have a shape called fillyFill which contains several closed shapes created with beginShape…endShape(CLOSE). Now when I try to ‘shape mask’ them using a circle…

`PGS_ShapeBoolean.intersect(circ, fillyFill)`

I get an error that reads TopologyException: side location conflict: arg 1 [(311.98916659225284, 486.17156982421875, NaN)]. If I remove CLOSE from endShape, the intersection works. Are there some conditions where multiple shapes can’t be intersected by a shape? Or maybe my multiple shapes within fillyFill need to be added to a group? I’m baffled 🙂

---

<div class="post-metadata">

**Author:** ![micycle](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/micycle/32/201_2.png) [@micycle](https://discourse.processing.org/u/micycle)\
**Post date:** [July 15, 2023, 9:01pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/17 "2023-07-15T21:01:58Z")

</div>

Intersecting multiple shapes with another one should be no big deal. The error message you’re encountering originates from the base geometry library, suggesting that there may be an issue with your shape’s structure or configuration.

First, try making `fillyFill` a ‘GROUP’ shape and add all the closed shapes to it. This might solve the issue.

If that doesn’t do the trick, let me know. We can dive deeper into the problem to figure out what’s going on.

---

<div class="post-metadata">

**Author:** ![computershawn](https://avatars.discourse-cdn.com/v4/letter/c/439d5e/32.png) [@computershawn](https://discourse.processing.org/u/computershawn)\
**Post date:** [July 17, 2023, 4:26am UTC](https://discourse.processing.org/t/pshape-intersections/32616/18 "2023-07-17T04:26:23Z")

</div>

Thanks for getting back to me @micycle! I tried using GROUP. Maybe my syntax is wonky, because when I do that, my intersected geometry seems to disappear 🤷🏽‍♂️

If you have a few minutes, I’ve attached a sample sketch for reference. There’s a `render` method and a `renderGroup` method. In both cases, providing `CLOSE` as an arg in `endShape` will break things. Somehow Processing doesn’t seem to play nice with `PGS_ShapeBoolean.intersect`. Totally possible that I’m doing something wrong…

```auto
int radius = 70;
float[][] pts = {
  {130, 330, 130, 143, 270, 172, 270, 330},
  {130, 331, 130, 148, 270, 180, 270, 331},
  {130, 332, 130, 154, 270, 188, 270, 332},
  {130, 333, 130, 160, 270, 197, 270, 333},
  {130, 334, 130, 169, 270, 206, 270, 334},
  {130, 335, 130, 178, 270, 214, 270, 335},
  {130, 336, 130, 187, 270, 223, 270, 336},
  {130, 337, 130, 197, 270, 230, 270, 337}
};

void setup() {
  size(400, 400);
  noLoop();
}

void draw() {
  background(0);

  // Intersects multiple shapes only if endShape
  // is not provided with the CLOSE arg
  render(-80, 0);

  // When running renderGroup, intersected
  // geometry does not seem to be there
  renderGroup(80, 0);
}

void render(int x, int y) {
  PVector loc = new PVector(width / 2 + x, height / 2 + y);
  PShape s = createShape(ELLIPSE, loc.x, loc.y, 2 * radius, 2 * radius);
  s.setFill(0);
  s.setStroke(255);
  PShape fillyFill = createShape();

  for (int j = 0; j < pts.length; j++) {
    fillyFill.setFill(0);
    fillyFill.setStroke(255);

    float[] points = pts[j];
    float p0x = points[0];
    float p0y = points[1];
    float pNx = points[points.length - 2];
    float pNy = points[points.length - 1];

    fillyFill.beginShape();
    fillyFill.vertex(p0x + x, p0y + y);
    for (int i = 0; i < points.length / 2 - 2; i++) {
      float px = points[2 * i + 2];
      float py = points[2 * i + 3];
      fillyFill.vertex(px + x, py + y);
    }
    fillyFill.vertex(pNx + x, pNy + y);
    //fillyFill.endShape(CLOSE); // <- THIS DOES NOT WORK :(
    fillyFill.endShape();
  }

  PShape f1 = PGS_ShapeBoolean.intersect(s, fillyFill);
  PGS_Conversion.setAllFillColor(f1, color(0));
  PGS_Conversion.setAllStrokeColor(f1, color(255, 127, 0), 1);

  shape(s);
  shape(f1);
}

void renderGroup(int x, int y) {
  PVector loc = new PVector(width / 2 + x, height / 2 + y);
  PShape s = createShape(ELLIPSE, loc.x, loc.y, 2 * radius, 2 * radius);
  s.setFill(0);
  s.setStroke(255);
  PShape fillyFill = createShape(GROUP);

  for (int j = 0; j < pts.length; j++) {
    PShape temp = createShape();
    temp.setFill(0);
    temp.setStroke(255);

    float[] points = pts[j];
    float p0x = points[0];
    float p0y = points[1];
    float pNx = points[points.length - 2];
    float pNy = points[points.length - 1];

    temp.beginShape();
    temp.vertex(p0x + x, p0y + y);
    for (int i = 0; i < points.length / 2 - 2; i++) {
      float px = points[2 * i + 2];
      float py = points[2 * i + 3];
      temp.vertex(px + x, py + y);
    }
    temp.vertex(pNx + x, pNy + y);
    //temp.endShape(CLOSE); // <- THIS DOES NOT WORK
    temp.endShape();
    fillyFill.addChild(temp);
  }

  // Intersect the shape layer and the hatching layer
  PShape f1 = PGS_ShapeBoolean.intersect(s, fillyFill);

  // Set the color of the new hatching layer
  PGS_Conversion.setAllFillColor(f1, color(0));
  PGS_Conversion.setAllStrokeColor(f1, color(255, 127, 0), 1);

  shape(s);
  shape(f1);
}

```

---

<div class="post-metadata">

**Author:** ![micycle](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/micycle/32/201_2.png) [@micycle](https://discourse.processing.org/u/micycle)\
**Post date:** [July 17, 2023, 6:20pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/19 "2023-07-17T18:20:29Z")

</div>

It seems the way you’re making this shape is creating a lot of overlapping/nearly overlapping lines and it seems closing it is creating an invalid (self-intersecting) shape.

![image](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/3X/4/f/4f0789c7189b5b0b752d0f745a223544d6c9a367.png)

In fact we can check this with a JTS internal operation:

```auto
import org.locationtech.jts.operation.valid.IsValidOp;

IsValidOp o = new IsValidOp(PGS_Conversion.fromPShape(fillyFill));
println(o.getValidationError());

```

Result: `Self-intersection at or near point (50.0, 148.0, NaN)`.

---

<div class="post-metadata">

**Author:** ![computershawn](https://avatars.discourse-cdn.com/v4/letter/c/439d5e/32.png) [@computershawn](https://discourse.processing.org/u/computershawn)\
**Post date:** [July 17, 2023, 7:34pm UTC](https://discourse.processing.org/t/pshape-intersections/32616/20 "2023-07-17T19:34:18Z")

</div>

Aw man 🙁 I’m not well versed in matters of topology, so not sure if there’s a quick solution. One idea is to make it so that those overlapping lines (the area you circled in red) no longer overlap. Those lines are not part of the final composition after all; Maybe Processing will be happier if I programmatically prevent those overlaps (Update: This didn’t work lol). The other idea is to work around the self-intersecting issue by separating the overlapping closed shapes into individual shapes, and intersecting each of them with the ‘mask’ shape.

Ultimately I’m plotting this work on an AxiDraw pen plotter. I know that the Axi library has some methods for removing overlapping geometry and such, so things might work out afterall. Thanks for your time and insights Michael 🙌🏽

[Next page](https://discourse.processing.org/t/pshape-intersections/32616.md?page=2)
