UNPKG

greiner-hormann

Version:

Greiner-Hormann clipping algorithm

60 lines (46 loc) 1.07 kB
export default class Intersection { /** * @param {Vertex} s1 * @param {Vertex} s2 * @param {Vertex} c1 * @param {Vertex} c2 */ constructor(s1, s2, c1, c2) { /** * @type {Number} */ this.x = 0.0; /** * @type {Number} */ this.y = 0.0; /** * @type {Number} */ this.toSource = 0.0; /** * @type {Number} */ this.toClip = 0.0; const d = (c2.y - c1.y) * (s2.x - s1.x) - (c2.x - c1.x) * (s2.y - s1.y); if (d === 0) return; /** * @type {Number} */ this.toSource = ((c2.x - c1.x) * (s1.y - c1.y) - (c2.y - c1.y) * (s1.x - c1.x)) / d; /** * @type {Number} */ this.toClip = ((s2.x - s1.x) * (s1.y - c1.y) - (s2.y - s1.y) * (s1.x - c1.x)) / d; if (this.valid()) { this.x = s1.x + this.toSource * (s2.x - s1.x); this.y = s1.y + this.toSource * (s2.y - s1.y); } } /** * @return {Boolean} */ valid () { return (0 < this.toSource && this.toSource < 1) && (0 < this.toClip && this.toClip < 1); } }