Java Code Examples for processing.core.PVector#dist()

The following examples show how to use processing.core.PVector#dist() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TouchDetectionColor.java    From PapARt with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public boolean checkPoint(int offset, int currentPoint) {

    // TODO: not sure if the distance is relevant in this context.
    int x1 = offset % imgSize.getWidth();
    int y1 = (int) (offset / imgSize.getWidth());

    int x2 = currentPoint % imgSize.getWidth();
    int y2 = (int) (currentPoint / imgSize.getWidth());

    float dist = PVector.dist(new PVector(x1, y1), new PVector(x2, y2));

    return !assignedPoints[offset] // not assigned  
            && segmentedImage[offset] == segmentedImage[currentPoint] // is the same color/compo.
            && dist < calib.getMaximumDistance();
}
 
Example 2
Source File: KinectSilhouetteVectorField.java    From haxademic with MIT License 6 votes vote down vote up
protected void updateWithVectorField() {
	// adjust to surrounding vectors
	int closeVectors = 0;
	float averageDirection = 0;
	for (int i = 0; i < _vectorFieldBase.size(); i++) {
		PVector vector = _vectorFieldBase.get(i);
		PVector vectorOffset = _vectorFieldOffset.get(i);
		if( vector.dist( _position ) < _canvasW/10f ) {
			averageDirection += vector.z + vectorOffset.z;
			closeVectors++;
		}
	}
	if( closeVectors > 0 ) {
		_radians.setTarget( (-averageDirection / closeVectors) ); // _radians.target() + 4f * 
	}

}
 
Example 3
Source File: LineTrail.java    From haxademic with MIT License 6 votes vote down vote up
public void update(PGraphics pg, PVector newPos, int colorStart, int colorEnd) {
	// init points to start point
	if(trail == null) {
		trail = new PVector[size];
		for (int i = 0; i < size; i++) trail[i] = newPos.copy();
	}
	
	// copy all positions towards tail end each step
	for (int i = size - 1; i > 0; i--) {
		trail[i].set(trail[i-1]);
	}
	trail[0].set(newPos);
	
	// render
	for (int i = 0; i < size - 1; i++) {
		PVector curSegment = trail[i]; 
		PVector nexSegment = trail[i+1]; 
		if(curSegment.dist(nexSegment) != 0) {
			if(colorStart != NO_FILL) {
				float progress = (float) i / (float) size;
				pg.stroke(P.p.lerpColor(colorStart, colorEnd, progress));
			}
			pg.line(curSegment.x, curSegment.y,  curSegment.z, nexSegment.x, nexSegment.y, nexSegment.z);
		}
	}
}
 
Example 4
Source File: QuadSurface.java    From sketch-mapper with MIT License 5 votes vote down vote up
/**
 * Get the longest side as double
 *
 * @return
 */
public double getLongestSide() {
    double[] longest = new double[4];
    longest[0] = PVector.dist(new PVector(cornerPoints[0].x, cornerPoints[0].y), new PVector(cornerPoints[1].x, cornerPoints[1].y));
    longest[1] = PVector.dist(new PVector(cornerPoints[2].x, cornerPoints[2].y), new PVector(cornerPoints[3].x, cornerPoints[3].y));
    longest[2] = PVector.dist(new PVector(cornerPoints[0].x, cornerPoints[0].y), new PVector(cornerPoints[3].x, cornerPoints[3].y));
    longest[3] = PVector.dist(new PVector(cornerPoints[1].x, cornerPoints[1].y), new PVector(cornerPoints[2].x, cornerPoints[2].y));

    double longer = 0;
    for (int i = 0; i < longest.length; i++) {
        if (longest[i] > longer) longer = longest[i];
    }
    return longer;
}
 
Example 5
Source File: BezierSurface.java    From sketch-mapper with MIT License 5 votes vote down vote up
/**
 * Get the longest side as double
 *
 * @return
 */
public double getLongestSide() {
    double[] longest = new double[4];
    longest[0] = PVector.dist(new PVector(cornerPoints[0].x, cornerPoints[0].y), new PVector(cornerPoints[1].x, cornerPoints[1].y));
    longest[1] = PVector.dist(new PVector(cornerPoints[2].x, cornerPoints[2].y), new PVector(cornerPoints[3].x, cornerPoints[3].y));
    longest[2] = PVector.dist(new PVector(cornerPoints[0].x, cornerPoints[0].y), new PVector(cornerPoints[3].x, cornerPoints[3].y));
    longest[3] = PVector.dist(new PVector(cornerPoints[1].x, cornerPoints[1].y), new PVector(cornerPoints[2].x, cornerPoints[2].y));

    double longer = 0;
    for (int i = 0; i < longest.length; i++) {
        if (longest[i] > longer) longer = longest[i];
    }
    return longer;
}
 
Example 6
Source File: Demo_VectorField.java    From haxademic with MIT License 5 votes vote down vote up
public void update( ArrayList<PVector> vectorField, int index ) {
	// adjust to surrounding vectors
	int closeVectors = 0;
	float averageDirection = 0;
	for (PVector vector : _vectorField) {
		if( vector.dist( position ) < ATTENTION_RADIUS ) {
			averageDirection += vector.z;
			closeVectors++;
		}
	}
	if( closeVectors > 0 ) {
		if( p.frameCount == 1 ) {
			radians.setCurrent( -averageDirection / closeVectors );
		} else {
			radians.setTarget( -averageDirection / closeVectors );
		}
	}

	radians.update();
	
	// update position
	lastPosition.set(position);
	float curSpeed = speed * AudioIn.audioFreq(index);
	position.set( position.x + P.sin(radians.value()) * curSpeed * P.map(p.mouseX, 0, p.width, 0, 2f), position.y + P.cos(radians.value()) * curSpeed * P.map(p.mouseX, 0, p.width, 0, 2f) );
	if( position.x < 0 ) position.set( p.width, position.y );
	if( position.x > p.width ) position.set( 0, position.y );
	if( position.y < 0 ) position.set( position.x, p.height );
	if( position.y > p.height ) position.set( position.x, 0 );
	
	// draw
	if(position.dist(lastPosition) < curSpeed * 2f) {
		p.line(position.x, position.y, lastPosition.x, lastPosition.y);
	}
}
 
Example 7
Source File: Demo_MultichannelAudio_BeadsJack.java    From haxademic with MIT License 5 votes vote down vote up
public void update(PGraphics pg) {
	// draw
	pg.push();
	pg.noFill();
	pg.stroke(0, 255, 0);
	PG.setDrawCenter(pg);
	PG.setCenterScreen(pg);
	pg.ellipse(position.x, position.y, 20, 20);
	pg.pop();
	
	// set gains
	for (int i = 0; i < outputs; i++) {
		// get dist to speaker
		PVector speakerPos = stage.getSpeaker(i).position();
		float dist = speakerPos.dist(position);
		float distToGain = P.map(dist, 0, stage.radius() * 2, 1, 0);
		distToGain = P.constrain(distToGain, 0, 1);
		gains[i].setGain(distToGain);
		
		// draw debug to speakers
		pg.push();
		pg.noFill();
		pg.stroke(0, 255 * distToGain, 0);
		PG.setDrawCenter(pg);
		PG.setCenterScreen(pg);
		pg.line(position.x, position.y, speakerPos.x, speakerPos.y);
		float midX = (position.x + speakerPos.x) / 2f;
		float midY = (position.y + speakerPos.y) / 2f;
		pg.text(distToGain, midX, midY);
		pg.pop();
	}
}
 
Example 8
Source File: OrientationUtil.java    From haxademic with MIT License 5 votes vote down vote up
public static void setRotationTowards2(PGraphics pg, PVector point1, PVector point2) {
	// spin on y axis
	float yRads = MathUtil.getRadiansToTarget(point1.x, point1.z, point2.x, point2.z);
	// calculate z-tilt
	float c = point1.dist(point2);	 			// we have the diagonal distance
	float b = point1.y - point2.y;	 			// and y-difference
	float a = P.sqrt(P.sq(c) - P.sq(b));		// so we solve for a (c^2 - b^2 = a^2)
	float zRads = MathUtil.getRadiansToTarget(0, 0, a, b);	// get radians based on a/b (x/y) offset
	pg.rotateY(-yRads);
	pg.rotateZ(-zRads);
	pg.rotateZ(P.HALF_PI);
}
 
Example 9
Source File: TextureVectorFieldEQ.java    From haxademic with MIT License 5 votes vote down vote up
public void update( ArrayList<PVector> vectorField, int index ) {
	// adjust to surrounding vectors
	int closeVectors = 0;
	float averageDirection = 0;
	for (PVector vector : _vectorField) {
		if( vector.dist( position ) < ATTENTION_RADIUS ) {
			averageDirection += vector.z;
			closeVectors++;
		}
	}
	if( closeVectors > 0 ) {
		if( P.p.frameCount == 1 ) {
			radians.setCurrent( -averageDirection / closeVectors );
		} else {
			radians.setTarget( -averageDirection / closeVectors );
		}
	}

	radians.update();
	
	// update position
	lastPosition.set(position);
	float curSpeed = speed * (0.15f + AudioIn.audioFreq(index) * 4f);
	curSpeed = P.min(curSpeed, 6f);
	position.set( position.x + P.sin(radians.value()) * curSpeed, position.y + P.cos(radians.value()) * curSpeed );
	if( position.x < 0 ) position.set( width, position.y );
	if( position.x > width ) position.set( 0, position.y );
	if( position.y < 0 ) position.set( position.x, height );
	if( position.y > height ) position.set( position.x, 0 );
	
	// draw
	if(position.dist(lastPosition) < curSpeed * 2f) {
		_texture.line(position.x, position.y, lastPosition.x, lastPosition.y);
	}
}
 
Example 10
Source File: Camera.java    From Project-16x16 with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the world position the mouse is over, accounting for camera rotation
 * (uses polar coordinates). Overrides the {@link ZoomPan#getMouseCoord() parent
 * method}, since this does not account for camera rotation.
 * 
 * @return World position the mouse is over.
 */
@Override
public PVector getMouseCoord() {
	final float theta = Utility.angleBetween(super.getMouseCoord(), logicalPosition) - rotation;
	final float eDist = PVector.dist(super.getMouseCoord(), logicalPosition);
	final float xReal = logicalPosition.x + eDist * (cos(theta));
	final float yReal = logicalPosition.y + eDist * (sin(theta));

	return new PVector(xReal, yReal);
}
 
Example 11
Source File: MarkerBoardJavaCV.java    From PapARt with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
    protected void updatePositionImpl(int id, int currentTime, int endTime, int mode,
            Camera camera, opencv_core.IplImage img, Object globalTracking) {

//        Do not find when not needed. 
        if (this.subscribersAmount == 0
                || (mode == BLOCK_UPDATE && currentTime < endTime)) {
            return;
        }

        try {
            System.out.println("Subscribers: " + this.subscribersAmount);
            ObjectFinder finder = (ObjectFinder) trackers.get(id);

            // TODO: the  finder.find should be done ONCE per image. Not once per board.
            // Find the markers
            double[] corners = finder.find(img);

            // one use... HACK  -- Why 
            // why so evil ?
//        finder = new ObjectFinder(finder.getSettings());
//        trackers.set(id, finder);
            if (corners == null) {
                return;
            }

            PMatrix3D newPos = compute3DPos(corners, camera);

            if (newPos == null) {
                return;
            }

            PVector currentPos = new PVector(newPos.m03, newPos.m13, newPos.m23);
            if (currentPos.z < 10f || currentPos.z > 10000) {
                return;
            }

            float distance = currentPos.dist(lastPos.get(id));

//        System.out.println("Distance " + distance);
//        if (distance > 5000) // 1 meter~?
//        {
//            return;
//        }
            lastDistance.set(id, distance);
            // if the update is forced 
            if (mode == FORCE_UPDATE && currentTime < endTime) {
                update(newPos, id);
                return;
            }

            // the force and block updates are finished, revert back to normal
            if (mode == FORCE_UPDATE || mode == BLOCK_UPDATE && currentTime > endTime) {
                updateStatus.set(id, NORMAL);
            }

            // if it is a drawing mode
            if (drawingMode.get(id)) {

                if (distance > this.minDistanceDrawingMode.get(id)) {
                    update(newPos, id);

                    lastPos.set(id, currentPos);
                    updateStatus.set(id, FORCE_UPDATE);
                    nextTimeEvent.set(id, applet.millis() + MarkerBoard.updateTime);
//                    System.out.println("Next Update for x seconds");
                }

            } else {
                update(newPos, id);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Example 12
Source File: MarkerBoardSvg.java    From PapARt with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void updatePositionImpl(int id,
        int currentTime,
        int endTime,
        int mode,
        Camera camera,
        opencv_core.IplImage img,
        Object globalTracking) {

    DetectedMarker[] markers = (DetectedMarker[]) globalTracking;
    PMatrix3D newPos = DetectedMarker.compute3DPos(markers, markersFromSVG, camera);

    if (newPos == INVALID_LOCATION) {
        return;
    }
    PVector currentPos = new PVector(newPos.m03, newPos.m13, newPos.m23);

    // Cannot detect elements as close as closer than 10cm
    if (currentPos.z < 10) {
        return;
    }

    // if the update is forced 
    if (mode == FORCE_UPDATE && currentTime < endTime) {
        update(newPos, id);
        return;
    }

    // the force and block updates are finished, revert back to normal
    if (mode == FORCE_UPDATE || mode == BLOCK_UPDATE && currentTime > endTime) {
        updateStatus.set(id, NORMAL);
    }

    float distance = currentPos.dist(lastPos.get(id));
    lastDistance.set(id, distance);

    // if it is a drawing mode
    if (drawingMode.get(id)) {

        if (distance > this.minDistanceDrawingMode.get(id)) {
            update(newPos, id);
            lastPos.set(id, currentPos);
            updateStatus.set(id, FORCE_UPDATE);
            nextTimeEvent.set(id, applet.millis() + MarkerBoard.updateTime);
        }

    } else {
        update(newPos, id);
        lastPos.set(id, currentPos);

    }

}
 
Example 13
Source File: Demo_VectorFlyer.java    From haxademic with MIT License 4 votes vote down vote up
protected boolean attractorExists(PVector p) {
	for (int i = 0; i < attractors.size(); i++) {
		if(p.dist(attractors.get(i)) == 0) return true;
	}
	return false;
}
 
Example 14
Source File: Demo_Polygon.java    From haxademic with MIT License 4 votes vote down vote up
public Polygon createNeighborTriangle(Polygon parentPoly) {
		// get available edge
		// and find a reasonable new vertex for a neighbor 
		Edge edge = parentPoly.availableNeighborEdge();
		PVector newNeighborVertex = parentPoly.newNeighbor3rdVertex(edge, MathUtil.randRangeDecimal(0.5f, 1.8f), 0.25f, 0.75f);
		
		// new triangle off the Edge, but lerp the shared edge away a tiny bit to prevent overlap check
		tempTriangle.setVertex(0, edge.v1());
		tempTriangle.setVertex(1, edge.v2());
		tempTriangle.setVertex(2, newNeighborVertex);
		tempTriangle.shrink(0.001f);
		
		// if offscreen, bail
		if(polygonOffscreen(tempTriangle)) return null;
		
		// check to see if we're overlapping with another polygon
		Polygon overlappedPoly = null;
		for (int i = 0; i < polygons.size(); i++) {
			if(overlappedPoly == null) {
				if(CollisionUtil.polygonsIntersect(polygons.get(i), tempTriangle)) {
					overlappedPoly = polygons.get(i);
//					log.update("overlappedPoly");
				}
			}
		}
		
		// if we're overlapping another poly, try to move the new vertex to the closest vertex of the overlapped triangle, then see if the two triangles share an edge
		if(overlappedPoly != null) {
			PVector closestOverlappedVert = overlappedPoly.closestVertexToVertex(newNeighborVertex);
			newNeighborVertex.set(closestOverlappedVert);
//			log.update("OVERLAP SNAP!");
		} else {
			// if we're not overlapped, but close to another vertex, let's try to snap
			boolean snapped = false;
			for (int i = 0; i < polygons.size(); i++) {
				for (int j = 0; j < polygons.get(i).vertices().size(); j++) {
					if(snapped == false && polygons.get(i) != parentPoly) {		// don't snap to parent, or we get overlaps that don't get cleaned up below
						PVector vertex = polygons.get(i).vertices().get(j);
						if(newNeighborVertex.dist(vertex) < SNAP_RADIUS) {
							newNeighborVertex.set(vertex);
							overlappedPoly = polygons.get(i);	// ensures that the neighbors are connected below
							snapped = true;
							log.update("SNAP!");
						}
					}
				}
			}
		}
		
//		// TODO: Do we need to check for overlap again, based on "SNAP" above??
//		if(overlappedPoly != null) {
//			
//		}
		
		// new triangle to attach
		Polygon newNeighbor = new Polygon(new float[] {
				edge.v1().x, edge.v1().y, edge.v1().z,
				edge.v2().x, edge.v2().y, edge.v2().z,
				newNeighborVertex.x, newNeighborVertex.y, newNeighborVertex.z
		});
		
		// if not overlapping another, add to collection
		if(overlappedPoly == null && newNeighbor.area() < MAX_POLY_AREA) { // && newNeighborArea > 800) {
			// tell polys about their shared edges
			parentPoly.findNeighbor(newNeighbor);
			newNeighbor.findNeighbor(parentPoly);
			return newNeighbor;
		} else {
			// TODO: put this in an object pool for recycling
			return null;
		}
	}
 
Example 15
Source File: Demo_Polygon.java    From haxademic with MIT License 4 votes vote down vote up
protected boolean attemptCloseTriangle(PVector v1, PVector v2, PVector v3) {
		// are vertices too far from each other to close a triangle?
		if(v1.dist(v2) > tooFarThresh || v1.dist(v3) > tooFarThresh || v2.dist(v3) > tooFarThresh) {
			return false;
		}
		
		// build triangle to check for collisions
		tempTriangle.setVertex(0, v1);
		tempTriangle.setVertex(1, v2);
		tempTriangle.setVertex(2, v3);
		tempTriangle.shrink(0.001f);
		
		// bail if the triangle is too big
//		float newTriArea = CollisionUtil.polygonArea(tempTriangle);
		if(tempTriangle.area() > MAX_POLY_AREA) {
			log.update("TRIANGLE TOO BIG");
			return false;
		}

		// debug draw attempted/potential connections
		p.strokeWeight(2);
		p.stroke(255,0,0);
		p.line(v1.x + 2, v1.y + 2, v2.x + 2, v2.y + 2);
		p.line(v1.x + 2, v1.y + 2, v3.x + 2, v3.y + 2);
		p.line(v3.x + 2, v3.y + 2, v2.x + 2, v2.y + 2);
		p.strokeWeight(1);

		// check to see if we're overlapping with another polygon
		Polygon overlappedPoly = null;
		for (int i = 0; i < polygons.size(); i++) {
			if(overlappedPoly == null) {
				if(CollisionUtil.polygonsIntersect(polygons.get(i), tempTriangle)) {
					overlappedPoly = polygons.get(i);
				}
			}
		}
		
		// if we've passed all of the tests, add a new triangle and return the success result
		if(overlappedPoly == null) {
			Polygon newNeighbor = new Polygon(new float[] {
					v1.x, v1.y, v1.z,
					v2.x, v2.y, v2.z,
					v3.x, v3.y, v3.z
			});
			addNewPolygon(newNeighbor);
			log.update("CLOSED TRIANGLE!!!!!");
			
			// find any matching edges and add neighbor Polygons.
			// This is super important to stop edges without neighbors from being in `availableVertices`
			ensureNeighborsConnect();
			return true;
		} else {
			return false;
		}

	}
 
Example 16
Source File: PerlinNoise3dParticles.java    From haxademic with MIT License 4 votes vote down vote up
protected void update() {
			// set trail
			for (int i = trail.length - 2; i >= 0; i--) {
				trail[i+1].set(trail[i]);
			}
			
			// add direction
			for (int i = 0; i < fieldVecs.size(); i++) {
				if(PVector.dist(pos, fieldVecs.get(i)) < influenceDist) {
					dir.lerp(fieldVecRots.get(i), influenceAmp);
				}
			}
			
			dir.normalize();
			dir.mult(speed * amp);
			pos.add(dir);
			trail[0].set(pos);
			
			// draw
			p.pushMatrix();
			p.translate(pos.x, pos.y, pos.z);
//			p.point(0, 0, 0);
			p.popMatrix();
			
			// draw trail
			float newAmp = 0.3f + AudioIn.audioFreq(index);
			if(newAmp > amp) amp = newAmp;
			else amp *= 0.8f;
			
			float startSize = amp * 10f;
			float shrinkInc = startSize / (float)trail.length;
			
			for (int i = 0; i < trail.length - 1; i++) {
				p.strokeWeight(startSize - shrinkInc * (float)i);
//				BoxBetween.draw(p, trail[i], trail[i+1], 4f);
//				P.println(i, trail[i].x, trail[i+1].x);
				p.line(trail[i].x, trail[i].y, trail[i].z, trail[i+1].x, trail[i+1].y, trail[i+1].z);
			}
			
			// reset is needed
			if(pos.dist(center) > halfSize * 4f) reset();
		}
 
Example 17
Source File: MarkerBoardARToolKitPlus.java    From PapARt with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
    protected void updatePositionImpl(int id, int currentTime, int endTime, int mode,
            Camera camera, opencv_core.IplImage img, Object globalTracking) {

        ARToolKitPlus.TrackerMultiMarker tracker = (ARToolKitPlus.TrackerMultiMarker) trackers.get(id);

//        tracker.getCamera().changeFrameSize(camera.width(), camera.height());
        // Find the markers
        tracker.calc(img.imageData());

//        System.out.println("Calc... " + tracker.getNumDetectedMarkers());
        if (tracker.getNumDetectedMarkers() < MIN_ARTOOLKIT_MARKER_DETECTED) {
            return;
        }

        ARToolKitPlus.ARMultiMarkerInfoT multiMarkerConfig = tracker.getMultiMarkerConfig();

        PVector currentPos = new PVector((float) multiMarkerConfig.trans().get(3),
                (float) multiMarkerConfig.trans().get(7),
                (float) multiMarkerConfig.trans().get(11));

        // Cannot detect elements as close as closer than 10cm
        if (currentPos.z < 10) {
            return;
        }

        // if the update is forced 
        if (mode == FORCE_UPDATE && currentTime < endTime) {
            update(multiMarkerConfig, id);
            return;
        }

        // the force and block updates are finished, revert back to normal
        if (mode == FORCE_UPDATE || mode == BLOCK_UPDATE && currentTime > endTime) {
            updateStatus.set(id, NORMAL);
        }

        float distance = currentPos.dist(lastPos.get(id));
        lastDistance.set(id, distance);

        // if it is a drawing mode
        if (drawingMode.get(id)) {

            if (distance > this.minDistanceDrawingMode.get(id)) {
                update(multiMarkerConfig, id);
                lastPos.set(id, currentPos);
                updateStatus.set(id, FORCE_UPDATE);
                nextTimeEvent.set(id, applet.millis() + MarkerBoard.updateTime);
//            } else {
//                System.out.println("Not updating, because of drawing mode...");
            }

        } else {
            update(multiMarkerConfig, id);

        }

    }
 
Example 18
Source File: PShapeUtil.java    From haxademic with MIT License 4 votes vote down vote up
protected static boolean hasVertex(ArrayList<PVector> array, PVector p) {
	for (int i = 0; i < array.size(); i++) {
		if(p.dist(array.get(i)) == 0) return true;
	}
	return false;
}