Build plane geometry
483652
function() {
        var heightSegments = this.heightSegments;
        var widthSegments = this.widthSegments;
        var attributes = this.attributes;
        var positions = [];
        var texcoords = [];
        var normals = [];
        var faces = [];

        for (var y = 0; y <= heightSegments; y++) {
            var t = y / heightSegments;
            for (var x = 0; x <= widthSegments; x++) {
                var s = x / widthSegments;

                positions.push([2 * s - 1, 2 * t - 1, 0]);
                if (texcoords) {
                    texcoords.push([s, t]);
                }
                if (normals) {
                    normals.push([0, 0, 1]);
                }
                if (x < widthSegments && y < heightSegments) {
                    var i = x + y * (widthSegments + 1);
                    faces.push([i, i + 1, i + widthSegments + 1]);
                    faces.push([i + widthSegments + 1, i + 1, i + widthSegments + 2]);
                }
            }
        }

        attributes.position.fromArray(positions);
        attributes.texcoord0.fromArray(texcoords);
        attributes.normal.fromArray(normals);

        this.initIndicesFromArray(faces);

        this.boundingBox = new BoundingBox();
        this.boundingBox.min.set(-1, -1, 0);
        this.boundingBox.max.set(1, 1, 0);
    }
710041
def fitPlane(points, c="g", bc="darkgreen"):
    
    data = np.array(points)
    datamean = data.mean(axis=0)
    res = np.linalg.svd(data - datamean)
    dd, vv = res[1], res[2]
    xyz_min = points.min(axis=0)
    xyz_max = points.max(axis=0)
    s = np.linalg.norm(xyz_max - xyz_min)
    n = np.cross(vv[0], vv[1])
    pla = vs.Plane(datamean, n, s, s, c, bc)
    pla.info["normal"] = n
    pla.info["center"] = datamean
    pla.info["variance"] = dd[2]
    return pla
751686
function(circ, poly)
{
    var planes = poly.tPlanes;
    
    var mini = 0;
    var min = vdot(planes[0].n, circ.tc) - planes[0].d - circ.r;
    for(var i=0; i<planes.length; i++){
        var dist = vdot(planes[i].n, circ.tc) - planes[i].d - circ.r;
        if(dist > 0){
            return NONE;
        } else if(dist > min) {
            min = dist;
            mini = i;
        }
    }
    
    var n = planes[mini].n;

    var verts = poly.tVerts;
    var len = verts.length;
    var mini2 = mini<<1;

    //var a = poly.tVerts[mini];
    //var b = poly.tVerts[(mini + 1)%poly.tVerts.length];
    var ax = verts[mini2];
    var ay = verts[mini2+1];
    var bx = verts[(mini2+2)%len];
    var by = verts[(mini2+3)%len];

    var dta = vcross2(n.x, n.y, ax, ay);
    var dtb = vcross2(n.x, n.y, bx, by);
    var dt = vcross(n, circ.tc);
        
    if(dt < dtb){
        var con = circle2circleQuery(circ.tc, new Vect(bx, by), circ.r, 0, con);
        return con ? [con] : NONE;
    } else if(dt < dta) {
        return [new Contact(
            vsub(circ.tc, vmult(n, circ.r + min/2)),
            vneg(n),
            min,
            0
        )];
    } else {
        var con = circle2circleQuery(circ.tc, new Vect(ax, ay), circ.r, 0, con);
        return con ? [con] : NONE;
    }
}
303177
function(orthobasis) {
            var EPS = 1e-5;
            var cags = [];
            this.polygons.filter(function(p) {
                    // only return polys in plane, others may disturb result
                    return p.plane.normal.minus(orthobasis.plane.normal).lengthSquared() < EPS*EPS;
                })
                .map(function(polygon) {
                    var cag = polygon.projectToOrthoNormalBasis(orthobasis);
                    if (cag.sides.length > 0) {
                        cags.push(cag);
                    }
            });
            var result = new CAG().union(cags);
            return result;
        }
488809
function buildSideFaces() {

			var start = verticesArray.length / 3;
			var layeroffset = 0;
			sidewalls( contour, layeroffset );
			layeroffset += contour.length;

			for ( h = 0, hl = holes.length; h < hl; h ++ ) {

				ahole = holes[ h ];
				sidewalls( ahole, layeroffset );

				//, true
				layeroffset += ahole.length;

			}


			scope.addGroup( start, verticesArray.length / 3 - start, 1 );


		}
791886
function() {
        var angle, point;
        var ring = this.feature.geometry.components[0];
        // if the number of sides ever changes, create a new geometry
        if(ring.components.length != (this.sides + 1)) {
            this.createGeometry();
            ring = this.feature.geometry.components[0];
        }
        for(var i=0; i<this.sides; ++i) {
            point = ring.components[i];
            angle = this.angle + (i * 2 * Math.PI / this.sides);
            point.x = this.origin.x + (this.radius * Math.cos(angle));
            point.y = this.origin.y + (this.radius * Math.sin(angle));
            point.clearBounds();
        }
    }
701746
function createGeometry (data) {
  var geometryType = data.primitive;
  var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  var geometryInstance = new GeometryClass();

  if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }

  geometryInstance.init(data);
  return toBufferGeometry(geometryInstance.geometry, data.buffer);
}
359229
def setup_local_geometry(self, isite, coords, optimization=None):
        
        self.local_geometry = AbstractGeometry(
            central_site=self.structure.cart_coords[isite],
            bare_coords=coords,
            centering_type=self.centering_type,
            include_central_site_in_centroid=
            self.include_central_site_in_centroid,
            optimization=optimization)
93940
def build_stereographic_projection(center):
    """"""

    # TODO: Computing the center should really be done using
    # optimization, as in:
    # https://math.stackexchange.com/questions/409217/
    p = center.position.au
    u = p / length_of(p)
    c = u.mean(axis=1)
    c = c / length_of(c)
    x_c, y_c, z_c = c

    def project(position):
        p = position.position.au
        u = p / length_of(p)
        x, y, z = u
#        x_out = (x*y_c/sqrt(x_c**2 + y_c**2) - x_c*y/sqrt(x_c**2 + y_c**2))/(x*x_c*sqrt(-z_c**2 + 1)/sqrt(x_c**2 + y_c**2) + y*y_c*sqrt(-z_c**2 + 1)/sqrt(x_c**2 + y_c**2) + z*z_c + 1)
#        y_out = (-x*x_c*z_c/sqrt(x_c**2 + y_c**2) - y*y_c*z_c/sqrt(x_c**2 + y_c**2) + z*sqrt(-z_c**2 + 1))/(x*x_c*sqrt(-z_c**2 + 1)/sqrt(x_c**2 + y_c**2) + y*y_c*sqrt(-z_c**2 + 1)/sqrt(x_c**2 + y_c**2) + z*z_c + 1)
#        return x_out, y_out

        t0 = 1/sqrt(x_c**2 + y_c**2)
        t1 = x*x_c
        t2 = sqrt(-z_c**2 + 1)
        t3 = t0*t2
        t4 = y*y_c
        t5 = 1/(t1*t3 + t3*t4 + z*z_c + 1)
        t6 = t0*z_c

        return t0*t5*(x*y_c - x_c*y), -t5*(t1*t6 - t2*z + t4*t6)

    return project
28112
function ( vertices, indices, radius, detail ) {

	BufferGeometry.call( this );

	this.type = '';

	this.parameters = {
		vertices: vertices,
		indices: indices,
		radius: radius,
		detail: detail
	};

	radius = radius || 1;
	detail = detail || 0;

	// default buffer data

	var vertexBuffer = [];
	var uvBuffer = [];

	// the subdivision creates the vertex buffer data

	subdivide( detail );

	// all vertices should lie on a conceptual sphere with a given radius

	appplyRadius( radius );

	// finally, create the uv data

	generateUVs();

	// build non-indexed geometry

	this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
	this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
	this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );

	if ( detail === 0 ) {

		this.computeVertexNormals(); // flat normals

	} else {

		this.normalizeNormals(); // smooth normals

	}

	// helper functions

	function subdivide( detail ) {

		var a = new Vector3();
		var b = new Vector3();
		var c = new Vector3();

		// iterate over all faces and apply a subdivison with the given detail value

		for ( var i = 0; i < indices.length; i += 3 ) {

			// get the vertices of the face

			getVertexByIndex( indices[ i + 0 ], a );
			getVertexByIndex( indices[ i + 1 ], b );
			getVertexByIndex( indices[ i + 2 ], c );

			// perform subdivision

			subdivideFace( a, b, c, detail );

		}

	}

	function subdivideFace( a, b, c, detail ) {

		var cols = Math.pow( 2, detail );

		// we use this multidimensional array as a data structure for creating the subdivision

		var v = [];

		var i, j;

		// construct all of the vertices for this subdivision

		for ( i = 0; i <= cols; i ++ ) {

			v[ i ] = [];

			var aj = a.clone().lerp( c, i / cols );
			var bj = b.clone().lerp( c, i / cols );

			var rows = cols - i;

			for ( j = 0; j <= rows; j ++ ) {

				if ( j === 0 && i === cols ) {

					v[ i ][ j ] = aj;

				} else {

					v[ i ][ j ] = aj.clone().lerp( bj, j / rows );

				}

			}

		}

		// construct all of the faces

		for ( i = 0; i < cols; i ++ ) {

			for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {

				var k = Math.floor( j / 2 );

				if ( j % 2 === 0 ) {

					pushVertex( v[ i ][ k + 1 ] );
					pushVertex( v[ i + 1 ][ k ] );
					pushVertex( v[ i ][ k ] );

				} else {

					pushVertex( v[ i ][ k + 1 ] );
					pushVertex( v[ i + 1 ][ k + 1 ] );
					pushVertex( v[ i + 1 ][ k ] );

				}

			}

		}

	}

	function appplyRadius( radius ) {

		var vertex = new Vector3();

		// iterate over the entire buffer and apply the radius to each vertex

		for ( var i = 0; i < vertexBuffer.length; i += 3 ) {

			vertex.x = vertexBuffer[ i + 0 ];
			vertex.y = vertexBuffer[ i + 1 ];
			vertex.z = vertexBuffer[ i + 2 ];

			vertex.normalize().multiplyScalar( radius );

			vertexBuffer[ i + 0 ] = vertex.x;
			vertexBuffer[ i + 1 ] = vertex.y;
			vertexBuffer[ i + 2 ] = vertex.z;

		}

	}

	function generateUVs() {

		var vertex = new Vector3();

		for ( var i = 0; i < vertexBuffer.length; i += 3 ) {

			vertex.x = vertexBuffer[ i + 0 ];
			vertex.y = vertexBuffer[ i + 1 ];
			vertex.z = vertexBuffer[ i + 2 ];

			var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
			var v = inclination( vertex ) / Math.PI + 0.5;
			uvBuffer.push( u, 1 - v );

		}

		correctUVs();

		correctSeam();

	}

	function correctSeam() {

		// handle case when face straddles the seam, see #3269

		for ( var i = 0; i < uvBuffer.length; i += 6 ) {

			// uv data of a single face

			var x0 = uvBuffer[ i + 0 ];
			var x1 = uvBuffer[ i + 2 ];
			var x2 = uvBuffer[ i + 4 ];

			var max = Math.max( x0, x1, x2 );
			var min = Math.min( x0, x1, x2 );

			// 0.9 is somewhat arbitrary

			if ( max > 0.9 && min < 0.1 ) {

				if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
				if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
				if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;

			}

		}

	}

	function pushVertex( vertex ) {

		vertexBuffer.push( vertex.x, vertex.y, vertex.z );

	}

	function getVertexByIndex( index, vertex ) {

		var stride = index * 3;

		vertex.x = vertices[ stride + 0 ];
		vertex.y = vertices[ stride + 1 ];
		vertex.z = vertices[ stride + 2 ];

	}

	function correctUVs() {

		var a = new Vector3();
		var b = new Vector3();
		var c = new Vector3();

		var centroid = new Vector3();

		var uvA = new Vector2();
		var uvB = new Vector2();
		var uvC = new Vector2();

		for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {

			a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
			b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
			c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );

			uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
			uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
			uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );

			centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );

			var azi = azimuth( centroid );

			correctUV( uvA, j + 0, a, azi );
			correctUV( uvB, j + 2, b, azi );
			correctUV( uvC, j + 4, c, azi );

		}

	}

	function correctUV( uv, stride, vector, azimuth ) {

		if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {

			uvBuffer[ stride ] = uv.x - 1;

		}

		if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {

			uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;

		}

	}

	// Angle around the Y axis, counter-clockwise when looking from above.

	function azimuth( vector ) {

		return Math.atan2( vector.z, - vector.x );

	}


	// Angle above the XZ plane.

	function inclination( vector ) {

		return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );

	}

}
1197803
private static GeometricParity geometric3D(int i, int[] adjacent, IAtomContainer container) {

        IAtom atom = container.getAtom(i);
        Point3d[] coordinates = new Point3d[4];

        // set the forth ligand to centre as default (overwritten if
        // we have 4 neighbors)
        if (atom.getPoint3d() != null)
            coordinates[3] = atom.getPoint3d();
        else
            return null;

        // for each neighboring atom check if we have 3D coordinates
        for (int j = 0; j < adjacent.length; j++) {
            IAtom neighbor = container.getAtom(adjacent[j]);

            if (neighbor.getPoint3d() != null)
                coordinates[j] = neighbor.getPoint3d();
            else
                return null; // skip to next atom
        }

        // add new 3D stereo encoder
        return new Tetrahedral3DParity(coordinates);

    }
337122
function Plane3D( a , b , c , d ) {
	var self = Object.create( Plane3D.prototype ) ;

	self.normal = new Vector3D( a , b , c ) ;
	self.d = + d ;
	self.normalizeCheck() ;

	return self ;
}
643967
def make_simple(self):
        
        (inner_radius, outer_radius) = self.get_radii()
        radius = (inner_radius + outer_radius) / 2
        return cadquery.Workplane('XY') \
            .circle(radius).extrude(self.length)
85421
def slice_triangle_plane(verts, tri, plane_orig, plane_norm):
    
    dists = [point_to_plane_dist(p, plane_orig, plane_norm)
             for p in verts[tri]]

    if np.sign(dists[0]) == np.sign(dists[1]) \
            and np.sign(dists[1]) == np.sign(dists[2]):
        # Triangle is on one side of the plane
        return []

    # Iterate through the edges, cutting the ones that intersect
    intersect_points = []
    for fi in range(3):
        v1 = verts[tri[fi]]
        d1 = dists[fi]
        v2 = verts[tri[(fi + 1) % 3]]
        d2 = dists[(fi + 1) % 3]

        if d1 * d2 < 0:
            # intersection factor (between 0 and 1)
            # here is a nice drawing :
            # https://ravehgonen.files.wordpress.com/2013/02/slide8.png
            s = d1 / (d1 - d2)
            vdir = v2 - v1
            intersect_points.append(v1 + vdir * s)
        elif np.fabs(d1) < 1e-5:
            # point on plane
            intersect_points.append(v1)

    return intersect_points
917770
function buildLidFaces() {

			var start = verticesArray.length / 3;

			if ( bevelEnabled ) {

				var layer = 0; // steps + 1
				var offset = vlen * layer;

				// Bottom faces

				for ( i = 0; i < flen; i ++ ) {

					face = faces[ i ];
					f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );

				}

				layer = steps + bevelSegments * 2;
				offset = vlen * layer;

				// Top faces

				for ( i = 0; i < flen; i ++ ) {

					face = faces[ i ];
					f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );

				}

			} else {

				// Bottom faces

				for ( i = 0; i < flen; i ++ ) {

					face = faces[ i ];
					f3( face[ 2 ], face[ 1 ], face[ 0 ] );

				}

				// Top faces

				for ( i = 0; i < flen; i ++ ) {

					face = faces[ i ];
					f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );

				}

			}

			scope.addGroup( start, verticesArray.length / 3 - start, 0 );

		}
566370
def create_triangular_prism(p1, p2, p3, height):
    '''
    

    '''
    from blmath.geometry import Plane

    base_plane = Plane.from_points(p1, p2, p3)
    lower_base_to_upper_base = height * -base_plane.normal # pylint: disable=invalid-unary-operand-type
    vertices = np.vstack(([p1, p2, p3], [p1, p2, p3] + lower_base_to_upper_base))

    faces = np.array([
        [0, 1, 2],  # base
        [0, 3, 4], [0, 4, 1],  # side 0, 3, 4, 1
        [1, 4, 5], [1, 5, 2],  # side 1, 4, 5, 2
        [2, 5, 3], [2, 3, 0],  # side 2, 5, 3, 0
        [5, 4, 3],  # base
    ])

    return Mesh(v=vertices, f=faces)
556018
function(plane) {
            if (this.polygons.length === 0) {
                return new CSG();
            }
            // Ideally we would like to do an intersection with a polygon of inifinite size
            // but this is not supported by our implementation. As a workaround, we will create
            // a cube, with one face on the plane, and a size larger enough so that the entire
            // solid fits in the cube.
            // find the max distance of any vertex to the center of the plane:
            var planecenter = plane.normal.times(plane.w);
            var maxdistance = 0;
            this.polygons.map(function(polygon) {
                polygon.vertices.map(function(vertex) {
                    var distance = vertex.pos.distanceToSquared(planecenter);
                    if (distance > maxdistance) maxdistance = distance;
                });
            });
            maxdistance = Math.sqrt(maxdistance);
            maxdistance *= 1.01; // make sure it's really larger
            // Now build a polygon on the plane, at any point farther than maxdistance from the plane center:
            var vertices = [];
            var orthobasis = new CSG.OrthoNormalBasis(plane);
            vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(maxdistance, -maxdistance))));
            vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(-maxdistance, -maxdistance))));
            vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(-maxdistance, maxdistance))));
            vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(maxdistance, maxdistance))));
            var polygon = new CSG.Polygon(vertices, null, plane.flipped());

            // and extrude the polygon into a cube, backwards of the plane:
            var cube = polygon.extrude(plane.normal.times(-maxdistance));

            // Now we can do the intersection:
            var result = this.intersect(cube);
            result.properties = this.properties; // keep original properties
            return result;
        }