Snippets

renderTom AE Script: Shape to Circle

You are viewing an old version of this snippet. View the current version.
Revised by renderTom - bcd6a8e
/**********************************************************************************************
    Shape to Circle.jsx
    Copyright (c) 2017 Tomas Šinkūnas. All rights reserved.
    www.rendertom.com

    Description:
    	Morpth any shape into a circle.

        This script is provided "as is," without warranty of any kind, expressed
        or implied. In no event shall the author be held liable for any damages
        arising in any way from the use of this script.
**********************************************************************************************/

(function(thisObj) {

	scriptBuildUI(thisObj)

	function scriptBuildUI(thisObj) {
		var win = (thisObj instanceof Panel) ? thisObj : new Window("palette", "Shape to Circle", undefined, {
			resizeable: true
		});
		win.alignChildren = ["fill", "top"];
		win.spacing = 5;
		var grpCustomRadius = win.add("group");
		var checkCustomRadius = grpCustomRadius.add("checkbox", undefined, "Custom Radius");
		checkCustomRadius.value = true;
		checkCustomRadius.onClick = function() {
			etCustomRadius.enabled = this.value;
			ddRadius.enabled = !this.value;
		}
		var etCustomRadius = grpCustomRadius.add("edittext", undefined, "200");
		etCustomRadius.alignment = ["fill", "top"];

		var ddRadius = win.add("dropdownlist", undefined, ["Average from center", "Maximum from center", "Minimum from center"])
		ddRadius.selection = 0;

		var button = win.add("button", undefined, "Do It!");
		button.onClick = function() {
			if (etCustomRadius.enabled) {
				if (isNaN(etCustomRadius.text) || parseInt(etCustomRadius.text) < 0) {
					etCustomRadius.active = true;
					return alert("Please enter vadid radius value.");
				} else {
					main(parseInt(etCustomRadius.text));
				}
			} else {
				main(ddRadius.selection.text);
			}
		}
		win.onShow = function() {
			checkCustomRadius.onClick();
		}
		win.onResizing = win.onResize = function() {
			this.layout.resize();
		};

		win instanceof Window
			? (win.center(), win.show())
			: (win.layout.layout(true), win.layout.resize());
	}

	function main(radiusFromUI) {
		try {
			var radius = radiusFromUI;
			var distanceArray = [];

			var composition = getActiveComposition();
			var selectedLayers = getSelectedLayers(composition);
			var allShapeProperties = getAllShapeProperties(selectedLayers);
			if (allShapeProperties.length === 0)
				throw new Error ("Please select Path property")

			app.beginUndoGroup("Shape to Circle");

			for (var j = 0, jl = allShapeProperties.length; j < jl; j ++) {
				var pathValue = allShapeProperties[j].value;
				var vertices = pathValue.vertices;
				var centerCoordinates = getAverageInArray(vertices);

				if (isNaN(radiusFromUI)) {
					distanceArray = calculateDistancesFromCenter(centerCoordinates, vertices);
					if (radiusFromUI.match("Average")) 	  	radius = getAverageInArray(distanceArray);
					else if (radiusFromUI.match("Maximum")) radius = Math.max.apply(null, distanceArray);
					else if (radiusFromUI.match("Minimum")) radius = Math.min.apply(null, distanceArray);
				}

				var circlePoints = pointsToCircle(centerCoordinates, radius, vertices);

				var circleShape = new Shape();
					circleShape.vertices = circlePoints.vertices;
					circleShape.inTangents = circlePoints.inTangents;
					circleShape.outTangents = circlePoints.outTangents;
					circleShape.closed = pathValue.closed;

				allShapeProperties[j].numKeys === 0
					? allShapeProperties[j].setValue(circleShape)
					: allShapeProperties[j].setValueAtTime(composition.time, circleShape);

			}

			app.endUndoGroup();

		} catch (e) {
			alert(e.message);
		}

	}

	function getActiveComposition() {
		var composition = app.project.activeItem;
		if (!composition || !(composition instanceof CompItem))
			throw new Error("Please select composition first.");
		return composition;
	}

	function getSelectedLayers(composition) {
		var selectedLayers = composition.selectedLayers;
		if (selectedLayers.length === 0)
			throw new Error("Please select layer first.");
		return selectedLayers;
	}

	function getLayerShapeProperties(layer) {
		var shapeProperties = [];
		var prop;
		var selectedProperties = layer.selectedProperties;
		for (var i = 0, il = selectedProperties.length; i < il; i ++) {
			prop = selectedProperties[i];
			
			if (prop.matchName === "ADBE Vector Shape - Group") {
				if (prop.property("ADBE Vector Shape").selected === true) {
					continue
				} else {
					shapeProperties.push(prop.property("ADBE Vector Shape"))
				}
			} else if (prop.matchName === "ADBE Mask Atom") {
				if (prop.property("ADBE Mask Shape").selected === true) {
					continue
				} else {
					shapeProperties.push(prop.property("ADBE Mask Shape"))
				}
			} else if (prop.matchName.match("ADBE Vector Shape|ADBE Mask Shape")) {
				shapeProperties.push(prop)
			}
		}
		return shapeProperties;
	}

	function getAllShapeProperties(selectedLayers) {
		var allShapeProperties = [];
		var layerShapeProperties = [];
		for (var i = 0, il = selectedLayers.length; i < il; i ++) {
			layerShapeProperties = getLayerShapeProperties(selectedLayers[i]);
			if (layerShapeProperties.length > 0) {
				allShapeProperties = allShapeProperties.concat(layerShapeProperties);
			}
		}
		return allShapeProperties;
	}

	function pointsToCircle(center, radius, pointsArray) {
		var angle, anchor, handle;

		var numPoints = pointsArray.length;
		var slice = 2 * Math.PI / numPoints;
		var handleLength = getHandleLength(numPoints, radius);
		var angleOffset = getAngle(center, pointsArray[0]);

		var newCoordinates = {
			vertices: [],
			inTangents: [],
			outTangents: []
		};

		if (clockwiseDirection(pointsArray)) {
			for (var i = 0; i < numPoints; i++) {
				angle = slice * i + angleOffset;

				anchor = getPointCoordinates(center, radius, angle);
				handle = getPointCoordinates(anchor, handleLength, angle + Math.PI / 2);

				newCoordinates.vertices.push(anchor);
				newCoordinates.inTangents.push(anchor - handle);
				newCoordinates.outTangents.push(handle - anchor);
			}
		} else {
			for (var i = numPoints; i > 0; i--) {
				angle = slice * i + angleOffset;

				anchor = getPointCoordinates(center, radius, angle);
				handle = getPointCoordinates(anchor, handleLength, angle + Math.PI / 2);

				newCoordinates.vertices.push(anchor);
				newCoordinates.inTangents.push(handle - anchor);
				newCoordinates.outTangents.push(anchor - handle);
			}
		}

		return newCoordinates;
	}

	function getPointCoordinates(center, radius, angle) {
		return [
			center[0] + radius * Math.cos(angle),
			center[1] + radius * Math.sin(angle)
		]
	}

	function getHandleLength(numPoints, radius) {
		return radius * getMagicNumber() * 4 / numPoints;
	}

	function getMagicNumber() {
		// http://stackoverflow.com/questions/1734745/how-to-create-circle-with-bézier-curves
		// https://people-mozilla.org/~jmuizelaar/Riskus354.pdf
		return (4 / 3) * Math.tan(Math.PI / (2 * 4));
	}

	function getAverageInArray(verticesArray) {
		return sumArray(verticesArray) / verticesArray.length;
	}

	function sumArray(array) {
		var totalSum = array[0];
		for (var i = 1, il = array.length; i < il; i++)
			totalSum += array[i];
		return totalSum;
	}

	function clockwiseDirection(vertices) {
		// http://stackoverflow.com/questions/14505565/detect-if-a-set-of-points-in-an-array-that-are-the-vertices-of-a-complex-polygon
		var polygonArea = getPoligonArea(vertices);
		return polygonArea > 0;
	}

	function getPoligonArea(vertices) {
		var area = 0;
		for (var i = 0; i < vertices.length; i++) {
			j = (i + 1) % vertices.length;
			area += vertices[i][0] * vertices[j][1];
			area -= vertices[j][0] * vertices[i][1];
		}
		return area / 2;
	}

	function getAngle(point1, point2) {
		var distanceX = point2[0] - point1[0];
		var distanceY = point2[1] - point1[1];
		var theta = Math.atan2(distanceY, distanceX);
		return theta;
	}

	function calculateDistancesFromCenter(center, vertices) {
		var distanceFromCenter;
		var distanceArray = [];
		for (var i = 0, il = vertices.length; i < il; i++) {
			distanceFromCenter = distanceBetweenPoints(center, vertices[i]);
			distanceArray.push(distanceFromCenter);
		}
		return distanceArray;
	}

	function distanceBetweenPoints(point1, point2) {
		var deltaX = point1[0] - point2[0];
		var deltaY = point1[1] - point2[1];
		var distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
		return distance;
	}
})(this);
HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.