I have written generic Point classes, line/line intersection algorithms and Layer administration code more times than I can remember. I don't like menial programming, so this is effectively my code library. But you can use it too!
The language used is Processing, which is a mostly-Java-syntax language. I hardly ever use Java-specific ninja code, so rewriting any of these snippets to your favourite language is less than a minute's worth of work, typically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | /** * Perform a coordinate tranlation/rotation so that * line (x3/y3, x4/y4) becomes (0/0, .../0), with * the other coordinates transformed accordingly. * * INPUT x1,y1,x2,y2 constitute a line segment S1. * x3,y3,x4,y4 constitute a line segment S2. * angle is the angle of S2 in the world. * cosine represents cos(-angle). * sine represents sin(-angle). * * Angle, cosine, and sine are required as arguments * because while we can compute them every time this * function is called, that's just throwing away cycles. * * RETURNS float[9], with [0]/[1], [2]/[3], [4]/[5] * and [6]/[7] being the rotated points * for lines S1 and S2. Element [8] * is the rotation angle, because you * may want to send this data on, and * then you don't want to waste time * repacking a float[8] to a float[9]. */ float[] translateRotate(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float angle, float cosine, float sine) { // First, translate all coordinates so that x3/y3 lies on 0/0 x1 -= x3; y1 -= y3; x2 -= x3; y2 -= y3; x4 -= x3; y4 -= y3; // Rotate (x1'/y1') about (0,0) float x1n = x1 * cosine - y1 * sine, y1n = x1 * sine + y1 * cosine; // Rotate (x2'/y2') about (0,0) float x2n = x2 * cosine - y2 * sine, y2n = x2 * sine + y2 * cosine; // Rotate (x4'/y4') about (0,0) float x4n = x4 * cosine - y4 * sine; // And then return the transformed coordinates, plus angle used return new float[] {x1n, y1n, x2n, y2n, 0, 0, x4n, 0, angle}; } |
Written and maintained by Mike "Pomax" Kamermans. All code snippets on this site are "do whatever you want with it" licensed.