Ejemplo n.º 1
0
	// Check on which Side this Face lie (given the Input Plane)
	public EPlaneSide Side( Plane inPlane )
	{
		// 
		int numBack = 0, numFront = 0, numPlanar = 0;
		
		for( int i = 0; i < vertices.Length; ++i )
		{
			float dist = inPlane.GetDistanceToPoint( vertices[i] );
			
			// FIXME: do this work right??
			if( dist > GlobalSettings.Epsilonf )
				numFront++;
			else if( dist < -GlobalSettings.Epsilonf )
				numBack++;
			else
			{
				numPlanar++;
				numFront++;
				numBack++;
			}
		}
		
		if( numPlanar == vertices.Length )
			return EPlaneSide.Side_Planar;
		
		if( numFront == vertices.Length )
			return EPlaneSide.Side_Front;
		
		if( numBack == vertices.Length )
			return EPlaneSide.Side_Back;
		
		return EPlaneSide.Side_Split;
	}
 void CalculateDownEdge()
 {
     RaycastHit hit;
     //for(float i=-colliderHeight/2; i<=colliderHeight/2; i+=colliderHeight/raysNumber)
     for(float i=-rayCastRangeX/2; i<=rayCastRangeX/2; i+=rayCastRangeX/raysNumber)
     {
         Ray down = new Ray(transform.position+Vector3.right*i, _traceDirectionDown);
         if(Physics.Raycast(down, out hit) && hit.transform.name!="Rocket")
         {
             Plane newPlane = new Plane(-_traceDirectionDown, hit.point-_traceDirectionDown*_currentHeight);
             if(newPlane.GetDistanceToPoint(transform.position+_traceDirectionDown*_currentHeight)<
                edges.downPlane.GetDistanceToPoint(transform.position+_traceDirectionDown*_currentHeight))
                 //&& Vector3.Dot(hit.normal, _traceDirectionDown) < _edgeAngleFactor)
             {
                 edges.downPlane = new Plane(hit.normal, hit.point+hit.normal*_currentHeight);
                 edges.downHit = hit;
             }
             if(Vector3.Distance(transform.position, hit.point)<_currentHeight+0.2f)
             {
                 obstacleInfo.obstacleOnBottom = true;
             }
             if(drawGizmos) Debug.DrawLine(transform.position+Vector3.right*i,hit.point,_downDebugColor);
         }
     }
 }
Ejemplo n.º 3
0
    int findLeaf(Vector3 position)
    {
        if (position == null)
        {
            throw new ArgumentException();
        }
        int index = 0;

        while (index >= 0)
        {
            //Debug.Log(index);
            BSPFileParser.BSPTreeNode node  = _nodes[index];
            UnityEngine.Plane         plane = planes[node.plane];
            float distance = plane.GetDistanceToPoint(position);
            if (distance >= 0)
            {
                index = node.children[0];
            }
            else
            {
                index = node.children[1];
            }
        }
        // When index < 0, meaning this is a BSP Leaf Index
        // convert into correct leaf index: -index-1
        return(-index - 1);
    }
Ejemplo n.º 4
0
        /// <summary>
        /// Projects a screen point to a plane from a camera's point of view.
        /// </summary>
        /// <param name="position">Screen point.</param>
        /// <param name="camera">The camera.</param>
        /// <param name="projectionPlane">Projection plane.</param>
        /// <returns>Projected point on the plane in World coordinates.</returns>
        public static Vector3 CameraToPlaneProjection(Vector2 position, Camera camera, Plane projectionPlane)
        {
            var distance = 0f;
            var ray = camera.ScreenPointToRay(position);
            var result = projectionPlane.Raycast(ray, out distance);
            if (!result && Mathf.Approximately(distance, 0f)) return -projectionPlane.normal * projectionPlane.GetDistanceToPoint(Vector3.zero); // perpendicular to the screen

            return ray.origin + ray.direction * distance;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Projects a screen point to a plane using parallel projection.
        /// </summary>
        /// <param name="position">Screen point.</param>
        /// <param name="projectionPlane">Projection plane.</param>
        /// <returns>Projected point on the plane in World coordinates.</returns>
        public static Vector3 ScreenToPlaneProjection(Vector2 position, Plane projectionPlane)
        {
            var distance = 0f;
            var ray = new Ray(position, Vector3.forward);
            var result = projectionPlane.Raycast(ray, out distance);
            if (!result && Mathf.Approximately(distance, 0f)) return -projectionPlane.normal * projectionPlane.GetDistanceToPoint(Vector3.zero); // perpendicular to the screen

            return ray.origin + new Vector3(0, 0, distance);
        }
Ejemplo n.º 6
0
 public float GetWorldPerScreenPixel(Vector3 worldPoint)
 {
     Camera cam = Camera.mainCamera;
     if (cam == null)
         return 0;
     Plane nearPlane = new Plane(cam.transform.forward, cam.transform.position);
     float dist = nearPlane.GetDistanceToPoint(worldPoint);
     float sample = 100;
     return Vector3.Distance(cam.ScreenToWorldPoint(new Vector3(Screen.width/2, Screen.height/2-sample/2, dist)), cam.ScreenToWorldPoint(new Vector3(Screen.width/2, Screen.height/2+sample/2, dist))) / sample;
 }
 void LateUpdate()
 {
     float v = scale * Settings.marker_scale;
     if (Settings.marker_autoscale) {
         var cam = EditorCamera.Instance;
         var plane = new Plane (cam.transform.forward, cam.transform.position);
         float dist = plane.GetDistanceToPoint (transform.position);
         v *= Mathf.Clamp (dist_c * dist, 0f, 1f);
     }
     transform.localScale = Vector3.one * v;
 }
Ejemplo n.º 8
0
 void Update() {
   Plane plane = new Plane(transform.up, transform.position);
   for (int i = 0; i < LockedObjects.Length; i++) {
     float currentDistance = plane.GetDistanceToPoint(LockedObjects[i].position);
     Vector3 currentoffset = transform.up * currentDistance;
     Vector3 offset = transform.up * MaxDistance;
     Debug.DrawLine(LockedObjects[i].position, LockedObjects[i].position - offset);
     LockedObjects[i].position = LockedObjects[i].position - currentoffset + offset;
     Vector3 centerOffset = LockedObjects[i].position - transform.position;
     centerOffset = Vector3.ClampMagnitude(centerOffset, MaxRadialDistance);
     LockedObjects[i].position = transform.position + centerOffset;
   }
 }
Ejemplo n.º 9
0
	static public int GetDistanceToPoint(IntPtr l) {
		try{
			UnityEngine.Plane self=(UnityEngine.Plane)checkSelf(l);
			UnityEngine.Vector3 a1;
			checkType(l,2,out a1);
			System.Single ret=self.GetDistanceToPoint(a1);
			pushValue(l,ret);
			return 1;
		}
		catch(Exception e) {
			LuaDLL.luaL_error(l, e.ToString());
			return 0;
		}
	}
Ejemplo n.º 10
0
    protected Plane GetSelectedPlane()
    {
        const float distEpsilon = 0.2f;
        bool        isFound;
        bool        loopOnceIfPlaneNotFound = true;

        do
        {
            for (int idPlane = 0; idPlane < m_listPlane.Count; idPlane++)
            {
                isFound = true;

                Plane globalPlane = new Plane(transform.TransformPoint(m_listPlane[idPlane].normal),
                                              m_listPlane[idPlane].distance);

                foreach (var faceGO in m_selectedSlice)
                {
                    if (Mathf.Abs(globalPlane.GetDistanceToPoint(faceGO.transform.position)) > distEpsilon)
                    {
                        isFound = false;
                        break;
                    }
                }

                if (isFound)
                {
#if UNITY_EDITOR
                    if (m_drawSelectedPlane)
                    {
                        drawDebugPlane(globalPlane);
                    }
#endif
                    currentPlaneSelectedID = idPlane;
                    return(globalPlane);
                }
            }

            loopOnceIfPlaneNotFound = false;
            RefreachPrescisionCube();
            RefreachPrecisionPlane();
            Debug.LogWarning("Cube or plane corruption");
        } while (loopOnceIfPlaneNotFound);

        Debug.LogError("Cube still corrupted after plane and cube refreach");
        Restart();

        return(new Plane());
    }
Ejemplo n.º 11
0
    protected List <GameObject> GetSelectedCubeWithPlane(Plane plane)
    {
        List <GameObject> rst         = new List <GameObject>();
        const float       distEpsilon = 0.01f;

        foreach (GameObject cube in m_cubes)
        {
            Plane globalPlane = new Plane(transform.TransformPoint(plane.normal), plane.distance);

            if (Mathf.Abs(globalPlane.GetDistanceToPoint(cube.transform.position)) < distEpsilon)
            {
                rst.Add(cube);
            }
        }
        return(rst);
    }
    public static Classification ClassifyPoint(Vector3 point, Plane plane, float e)
    {
        float distance = plane.GetDistanceToPoint(point);

        if (distance < -e)
        {
            return Classification.BACK;
        }
        else if (distance > e)
        {
            return Classification.FRONT;
        }
        else
        {
            return Classification.COINCIDING;
        }
    }
    public static Classification ClassifyPoints(Vector3[] points, Plane plane, out Classification[] classes, float e)
    {
        uint numpos = 0;
        uint numneg = 0;
        classes = new Classification[3];
        for(int i = 0; i < points.Length; i++)
        {
            float distance = plane.GetDistanceToPoint(points[i]);

            if (distance < -e)
            {
                classes[i] = Classification.BACK;
                numneg++;
            }
            else if (distance > e)
            {
                classes[i] = Classification.FRONT;
                numpos++;
            }
            else
            {
                classes[i] = Classification.COINCIDING;
            }
        }

        if (numpos > 0 && numneg == 0)
        {
            return Classification.FRONT;
        }
        else if (numpos == 0 && numneg > 0)
        {
            return Classification.BACK;
        }
        else if (numpos > 0 && numneg > 0)
        {
            return Classification.STRADDLE;
        }
        else
        {
            return Classification.COINCIDING;
        }
    }
Ejemplo n.º 14
0
        public static PolygonPlaneRelation TestPolygonAgainstPlane(Polygon polygon, UnityEngine.Plane testPlane)
        {
            if (polygon.Plane.normal == testPlane.normal && polygon.Plane.distance == testPlane.distance)
            {
                return(PolygonPlaneRelation.Coplanar);
            }

            // Count the number of vertices in front and behind the clip plane
            int verticesInFront = 0;
            int verticesBehind  = 0;

            for (int i = 0; i < polygon.Vertices.Length; i++)
            {
                float distance = testPlane.GetDistanceToPoint(polygon.Vertices[i].Position);
                if (distance < -EPSILON_LOWER) // Is the point in front of the plane (with thickness)
                {
                    verticesInFront++;
                }
                else if (distance > EPSILON_LOWER) // Is the point behind the plane (with thickness)
                {
                    verticesBehind++;
                }
            }

            if (verticesInFront > 0 && verticesBehind > 0) // If some are in front and some are behind, then the poly spans
            {
                return(PolygonPlaneRelation.Spanning);
            }
            else if (verticesInFront > 0) // Only in front, so entire polygon is in front
            {
                return(PolygonPlaneRelation.InFront);
            }
            else if (verticesBehind > 0)  // Only behind, so entire polygon is behind
            {
                return(PolygonPlaneRelation.Behind);
            }
            else // No points in front or behind the plane, so assume coplanar
            {
                return(PolygonPlaneRelation.Coplanar);
            }
        }
 void Update() {
   Plane plane = new Plane(transform.up, transform.position);
   for (int i = 0; i < LockedObjects.Count; i++) {
     float currentDistance = plane.GetDistanceToPoint(LockedObjects[i].position);
     if (currentDistance < 0) {
       Vector3 planarOffset = Vector3.ProjectOnPlane(LockedObjects[i].position, transform.up) -
                              Vector3.ProjectOnPlane(transform.position, transform.up);
       if (!RestrictWhileOutsideCircle && planarOffset.magnitude > MaxRadialDistance) {
         Debug.DrawRay(transform.position, planarOffset);
         continue;
       }
       Vector3 currentoffset = transform.up * currentDistance;
       Vector3 offset = transform.up * MaxDistance;
       Debug.DrawLine(LockedObjects[i].position, LockedObjects[i].position - offset);
       LockedObjects[i].position = LockedObjects[i].position - currentoffset + offset;
       Vector3 centerOffset = LockedObjects[i].position - transform.position;
       centerOffset = Vector3.ClampMagnitude(centerOffset, MaxRadialDistance);
       LockedObjects[i].position = transform.position + centerOffset;
     }
   }
 }
Ejemplo n.º 16
0
		public override void OnBrushApply(z_BrushTarget target, z_BrushSettings settings)
		{
			Vector3[] vertices = target.editableObject.vertices;
			Vector3 v, t, avg, dirVec = direction.ToVector3();
			Plane plane = new Plane(Vector3.up, Vector3.zero);

			foreach(KeyValuePair<int, float> weight in target.weights)
			{
				if(weight.Value < .0001f || (ignoreNonManifoldIndices && nonManifoldIndices.Contains(weight.Key)))
					continue;

				v = vertices[weight.Key];

				if(direction == z_Direction.Normal && relax)
					avg = z_Math.Average(cached_vertices, neighborLookup[weight.Key]);
				else
					avg = z_Math.WeightedAverage(cached_vertices, neighborLookup[weight.Key], target.weights);

				if(direction != z_Direction.Normal || !relax)
				{
					if(direction == z_Direction.Normal)
						dirVec = z_Math.WeightedAverage(cached_normals, neighborLookup[weight.Key], target.weights).normalized;

					plane.SetNormalAndPosition(dirVec, avg);
					avg = v - dirVec * plane.GetDistanceToPoint(v);
				}

				t = Vector3.Lerp(v, avg, weight.Value);

				vertices[weight.Key] = v + (t-v) * settings.strength * SMOOTH_STRENGTH_MODIFIER;
			}

			target.editableObject.mesh.vertices = vertices;

			if(tempComponent != null)
				tempComponent.OnVerticesMoved();

			base.OnBrushApply(target, settings);
		}
Ejemplo n.º 17
0
	/// <summary>
	/// Sets the camera to use when calculating
	/// a pixel-perfect character size.
	/// </summary>
	/// <param name="c"></param>
	public void SetCamera(Camera c)
	{
		if (c == null || !m_started)
			return;

		float dist;
		Plane nearPlane = new Plane(c.transform.forward, c.transform.position);

		if (!Application.isPlaying)
		{
			// If the screenSize has never been initialized,
			// or if this is a different camera, get what 
			// values we can get, otherwise just keep the 
			// values we got during our last run:
#if !(UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_3_6 || UNITY_3_7 || UNITY_3_8 || UNITY_3_9)
			if ((screenSize.x == 0 || c != renderCamera) && c.pixelHeight > 100)
#endif
			{
				screenSize.x = c.pixelWidth;
				screenSize.y = c.pixelHeight;
			}

			if (screenSize.x == 0)
				return;

			renderCamera = c;

			if (screenPlacer != null)
				screenPlacer.SetCamera(renderCamera);

			// Determine the world distance between two vertical
			// screen pixels for this camera:
			dist = nearPlane.GetDistanceToPoint(transform.position);
			worldUnitsPerScreenPixel = Vector3.Distance(c.ScreenToWorldPoint(new Vector3(0, 1, dist)), c.ScreenToWorldPoint(new Vector3(0, 0, dist)));

			if(!hideAtStart)
				CalcSize();
			return;
		}

		screenSize.x = c.pixelWidth;
		screenSize.y = c.pixelHeight;
		renderCamera = c;

		if (screenPlacer != null)
			screenPlacer.SetCamera(renderCamera);

		// Determine the world distance between two vertical
		// screen pixels for this camera:
		dist = nearPlane.GetDistanceToPoint(transform.position);
		worldUnitsPerScreenPixel = Vector3.Distance(c.ScreenToWorldPoint(new Vector3(0, 1, dist)), c.ScreenToWorldPoint(new Vector3(0, 0, dist)));

		CalcSize();
	}
Ejemplo n.º 18
0
	/// <summary>
	/// Gets the 3d overlay position of the given joint over the color-image.
	/// </summary>
	/// <returns>The joint position for color overlay.</returns>
	/// <param name="userId">User ID</param>
	/// <param name="joint">Joint index</param>
	/// <param name="camera">Camera used to visualize the 3d overlay position</param>
	/// <param name="imageRect">Color image rectangle on the screen</param>
	public Vector3 GetJointPosColorOverlay(Int64 userId, int joint, Camera camera, Rect imageRect)
	{
		if(dictUserIdToIndex.ContainsKey(userId) && camera != null)
		{
			int index = dictUserIdToIndex[userId];
			
			if(index >= 0 && index < sensorData.bodyCount && 
			   bodyFrame.bodyData[index].bIsTracked != 0)
			{
				if(joint >= 0 && joint < sensorData.jointCount)
				{
					KinectInterop.JointData jointData = bodyFrame.bodyData[index].joint[joint];
					Vector3 posJointRaw = jointData.kinectPos;
					
					if(posJointRaw != Vector3.zero)
					{
						// 3d position to depth
						Vector2 posDepth = MapSpacePointToDepthCoords(posJointRaw);
						ushort depthValue = GetDepthForPixel((int)posDepth.x, (int)posDepth.y);
						
						if(posDepth != Vector2.zero && depthValue > 0 && sensorData != null)
						{
							// depth pos to color pos
							Vector2 posColor = MapDepthPointToColorCoords(posDepth, depthValue);

							if(!float.IsInfinity(posColor.x) && !float.IsInfinity(posColor.y))
							{
								float xScaled = (float)posColor.x * imageRect.width / sensorData.colorImageWidth;
								float yScaled = (float)posColor.y * imageRect.height / sensorData.colorImageHeight;
								
								float xScreen = imageRect.x + xScaled;
								//float yScreen = camera.pixelHeight - (imageRect.y + yScaled);
								float yScreen = imageRect.y + imageRect.height - yScaled;

								Plane cameraPlane = new Plane(camera.transform.forward, camera.transform.position);
								float zDistance = cameraPlane.GetDistanceToPoint(posJointRaw);
								//float zDistance = (jointData.kinectPos - camera.transform.position).magnitude;

								//Vector3 vPosJoint = camera.ViewportToWorldPoint(new Vector3(xNorm, yNorm, zDistance));
								Vector3 vPosJoint = camera.ScreenToWorldPoint(new Vector3(xScreen, yScreen, zDistance));

								return vPosJoint;
							}
						}
					}
				}
			}
		}

		return Vector3.zero;
	}
Ejemplo n.º 19
0
	// Let's do this thing!:
	void OnWizardCreate()
	{
		float worldUnitsPerScreenPixel;
		int skipped = 0; // How many sprites had to be skipped because they were prefabs?

		if (disablePixelPerfect)
			disablePixelPerfect = EditorUtility.DisplayDialog("Are you sure?", "Are you sure you wish to disable pixel-perfect on all selected sprites?", "Yes", "No");

		// Get our desired sprites:
		FindSprites();


		if (renderCamera.isOrthoGraphic)
		{
			// Use orthographic logic:
			worldUnitsPerScreenPixel = (renderCamera.orthographicSize * 2f) / targetScreenHeight;

			// Now set their sizes:
			for (int i = 0; i < sprites.Count; ++i)
			{
				SpriteRoot sprite = sprites[i];
				Vector2 pxSize = sprite.GetDefaultPixelSize(AssetDatabase.GUIDToAssetPath, AssetDatabase.LoadAssetAtPath);

				if (disablePixelPerfect)
					sprite.pixelPerfect = false;

				if (sprite.spriteMesh == null)
				{
					sprite.width = pxSize.x * worldUnitsPerScreenPixel;
					sprite.height = pxSize.y * worldUnitsPerScreenPixel;
				}
				else
					sprite.SetSize(pxSize.x * worldUnitsPerScreenPixel, pxSize.y * worldUnitsPerScreenPixel);

				EditorUtility.SetDirty(sprites[i].gameObject);
			}
		}
		else
		{
			// Use perspective logic:
			float dist;
			Plane nearPlane;

			// Now set their sizes:
			for (int i = 0; i < sprites.Count; ++i)
			{
#if (UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_3_6 || UNITY_3_7 || UNITY_3_8 || UNITY_3_9 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9)
	#if (UNITY_3_5 || UNITY_3_6 || UNITY_3_7 || UNITY_3_8 || UNITY_3_9 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9)
				PrefabType ptype = PrefabUtility.GetPrefabType(sprites[i].gameObject);
	#else
				PrefabType ptype = EditorUtility.GetPrefabType(sprites[i].gameObject);
	#endif
				// We can't do prefabs with perspective cameras:
				if (ptype == PrefabType.Prefab || ptype == PrefabType.ModelPrefab)
				{
					++skipped;
					Debug.LogWarning("Sprite \"" + sprites[i].name + "\" skipped because it is a prefab and the selected camera is perspective. Size cannot be calculated for perspective cameras without the object actually being positioned in front of the camera.\n Either use an orthographic camera, or use an instance of the prefab in the scene instead.");
					continue;
				}
#endif
				SpriteRoot sprite = sprites[i];
				nearPlane = new Plane(renderCamera.transform.forward, renderCamera.transform.position);
				Vector2 pxSize = sprite.GetDefaultPixelSize(AssetDatabase.GUIDToAssetPath, AssetDatabase.LoadAssetAtPath);

				// Determine the world distance between two vertical
				// screen pixels for this camera:
				dist = nearPlane.GetDistanceToPoint(sprite.transform.position);
				worldUnitsPerScreenPixel = Vector3.Distance(renderCamera.ScreenToWorldPoint(new Vector3(0, 1, dist)), renderCamera.ScreenToWorldPoint(new Vector3(0, 0, dist)));

				if (disablePixelPerfect)
					sprite.pixelPerfect = false;

				if (sprite.spriteMesh == null)
				{
					sprite.width = pxSize.x * worldUnitsPerScreenPixel;
					sprite.height = pxSize.y * worldUnitsPerScreenPixel;
				}
				else
					sprite.SetSize(pxSize.x * worldUnitsPerScreenPixel, pxSize.y * worldUnitsPerScreenPixel);

				EditorUtility.SetDirty(sprites[i].gameObject);
			}
		}



		// See if we need to advise the user to reload the scene:
		if (applyToAllPrefabs)
			EditorUtility.DisplayDialog("NOTE", "You may need to reload the current scene for prefab instances to reflect your changes.", "OK");

		Debug.Log( (sprites.Count - skipped) + " sprites sized.");

		// Save our settings for next time:
		SaveSettings();
	}
Ejemplo n.º 20
0
        private static bool ComputeIslandsMeshDataConnectivity(FracturedObject fracturedComponent, bool bVerticesAreLocal, MeshData meshData1, MeshData meshData2)
        {
            float fMargin = fracturedComponent.ChunkIslandConnectionMaxDistance;

            // Vertices and min/max may be in local space. We want distance checks to be in world space

            Vector3 v3Min1 = meshData1.v3Min; if(bVerticesAreLocal) v3Min1 = Vector3.Scale(v3Min1, meshData1.v3Scale);
            Vector3 v3Max1 = meshData1.v3Max; if(bVerticesAreLocal) v3Max1 = Vector3.Scale(v3Max1, meshData1.v3Scale);
            Vector3 v3Min2 = meshData2.v3Min; if(bVerticesAreLocal) v3Min2 = Vector3.Scale(v3Min2, meshData2.v3Scale);
            Vector3 v3Max2 = meshData2.v3Max; if(bVerticesAreLocal) v3Max2 = Vector3.Scale(v3Max2, meshData2.v3Scale);

            if((v3Min1.x > (v3Max2.x + fMargin)) || (v3Min1.y > (v3Max2.y + fMargin)) || (v3Min1.z > (v3Max2.z + fMargin)))
            {
                return false;
            }

            if((v3Min2.x > (v3Max1.x + fMargin)) || (v3Min2.y > (v3Max1.y + fMargin)) || (v3Min2.z > (v3Max1.z + fMargin)))
            {
                return false;
            }

            bool  bConnected    = false;
            float fDistPlaneMax = fracturedComponent.ChunkIslandConnectionMaxDistance;

            for(int nSubMesh1 = 0; nSubMesh1 < meshData1.aaIndices.Length; nSubMesh1++)
            {
                for(int nFace1 = 0; nFace1 < meshData1.aaIndices[nSubMesh1].Length / 3; nFace1++)
                {
                    Vector3 v1 = meshData1.aVertexData[meshData1.aaIndices[nSubMesh1][nFace1 * 3 + 0]].v3Vertex;
                    Vector3 v2 = meshData1.aVertexData[meshData1.aaIndices[nSubMesh1][nFace1 * 3 + 1]].v3Vertex;
                    Vector3 v3 = meshData1.aVertexData[meshData1.aaIndices[nSubMesh1][nFace1 * 3 + 2]].v3Vertex;

                    if(bVerticesAreLocal)
                    {
                        v1 = Vector3.Scale(v1, meshData1.v3Scale);
                        v2 = Vector3.Scale(v2, meshData1.v3Scale);
                        v3 = Vector3.Scale(v3, meshData1.v3Scale);
                    }

                    Vector3 v3Forward = -Vector3.Cross(v2 - v1, v3 - v1);
                    float   fArea1    = v3Forward.magnitude;

                    if(fArea1 < Parameters.EPSILONCROSSPRODUCT)
                    {
                        continue;
                    }

                    Quaternion qFace     = Quaternion.LookRotation(v3Forward.normalized, (v2 - v1).normalized);
                    Matrix4x4  mtxToFace = Matrix4x4.TRS(v1, qFace, Vector3.one).inverse;

                    Plane planeFace1 = new Plane(v1, v2, v3);

                    for(int nSubMesh2 = 0; nSubMesh2 < meshData2.aaIndices.Length; nSubMesh2++)
                    {
                        for(int nFace2 = 0; nFace2 < meshData2.aaIndices[nSubMesh2].Length / 3; nFace2++)
                        {
                            Vector3 v3Other1 = meshData2.aVertexData[meshData2.aaIndices[nSubMesh2][nFace2 * 3 + 0]].v3Vertex;
                            Vector3 v3Other2 = meshData2.aVertexData[meshData2.aaIndices[nSubMesh2][nFace2 * 3 + 1]].v3Vertex;
                            Vector3 v3Other3 = meshData2.aVertexData[meshData2.aaIndices[nSubMesh2][nFace2 * 3 + 2]].v3Vertex;

                            if(bVerticesAreLocal)
                            {
                                v3Other1 = Vector3.Scale(v3Other1, meshData2.v3Scale);
                                v3Other2 = Vector3.Scale(v3Other2, meshData2.v3Scale);
                                v3Other3 = Vector3.Scale(v3Other3, meshData2.v3Scale);
                            }

                            // Compute distance from face1 to face2

                            float fDist1 = Mathf.Abs(planeFace1.GetDistanceToPoint(v3Other1)); if(fDist1 > fDistPlaneMax) continue;
                            float fDist2 = Mathf.Abs(planeFace1.GetDistanceToPoint(v3Other2)); if(fDist2 > fDistPlaneMax) continue;
                            float fDist3 = Mathf.Abs(planeFace1.GetDistanceToPoint(v3Other3)); if(fDist3 > fDistPlaneMax) continue;

                            // See if they intersect in 2D (face 1 local coordinates)

                            Vector3 v3OtherCenterLocal = (v3Other1 + v3Other2 + v3Other3) / 3.0f;
                            v3OtherCenterLocal = mtxToFace.MultiplyPoint3x4(v3OtherCenterLocal);

                            Vector3 v3Local1 = mtxToFace.MultiplyPoint3x4(v1);
                            Vector3 v3Local2 = mtxToFace.MultiplyPoint3x4(v2);
                            Vector3 v3Local3 = mtxToFace.MultiplyPoint3x4(v3);
                            Vector3 v3Edge2  = v3Local3 - v3Local2;
                            Vector3 v3Edge3  = v3Local1 - v3Local3;

                            bool bFaceConnected = false;

                            // Test the center

                            if(v3OtherCenterLocal.x >= 0.0f)
                            {
                                if(Vector3.Cross(v3Edge2, v3OtherCenterLocal - v3Local2).z <= 0.0f)
                                {
                                    if(Vector3.Cross(v3Edge3, v3OtherCenterLocal - v3Local3).z <= 0.0f)
                                    {
                                        bFaceConnected = true;
                                    }
                                }
                            }

                            if(bFaceConnected == false)
                            {
                                // Try intersecting lines

                                Vector3 v3OtherLocal1 = mtxToFace.MultiplyPoint3x4(v3Other1);
                                Vector3 v3OtherLocal2 = mtxToFace.MultiplyPoint3x4(v3Other2);
                                Vector3 v3OtherLocal3 = mtxToFace.MultiplyPoint3x4(v3Other3);

                                if(bFaceConnected == false) if(IntersectEdges2D(v3OtherLocal1.x, v3OtherLocal1.y, v3OtherLocal2.x, v3OtherLocal2.y, v3Local1.x, v3Local1.y, v3Local2.x, v3Local2.y)) bFaceConnected = true;
                                if(bFaceConnected == false) if(IntersectEdges2D(v3OtherLocal1.x, v3OtherLocal1.y, v3OtherLocal2.x, v3OtherLocal2.y, v3Local2.x, v3Local2.y, v3Local3.x, v3Local3.y)) bFaceConnected = true;
                                if(bFaceConnected == false) if(IntersectEdges2D(v3OtherLocal1.x, v3OtherLocal1.y, v3OtherLocal2.x, v3OtherLocal2.y, v3Local3.x, v3Local3.y, v3Local1.x, v3Local1.y)) bFaceConnected = true;

                                if(bFaceConnected == false) if(IntersectEdges2D(v3OtherLocal2.x, v3OtherLocal2.y, v3OtherLocal3.x, v3OtherLocal3.y, v3Local1.x, v3Local1.y, v3Local2.x, v3Local2.y)) bFaceConnected = true;
                                if(bFaceConnected == false) if(IntersectEdges2D(v3OtherLocal2.x, v3OtherLocal2.y, v3OtherLocal3.x, v3OtherLocal3.y, v3Local2.x, v3Local2.y, v3Local3.x, v3Local3.y)) bFaceConnected = true;
                                if(bFaceConnected == false) if(IntersectEdges2D(v3OtherLocal2.x, v3OtherLocal2.y, v3OtherLocal3.x, v3OtherLocal3.y, v3Local3.x, v3Local3.y, v3Local1.x, v3Local1.y)) bFaceConnected = true;

                                if(bFaceConnected == false) if(IntersectEdges2D(v3OtherLocal3.x, v3OtherLocal3.y, v3OtherLocal1.x, v3OtherLocal1.y, v3Local1.x, v3Local1.y, v3Local2.x, v3Local2.y)) bFaceConnected = true;
                                if(bFaceConnected == false) if(IntersectEdges2D(v3OtherLocal3.x, v3OtherLocal3.y, v3OtherLocal1.x, v3OtherLocal1.y, v3Local2.x, v3Local2.y, v3Local3.x, v3Local3.y)) bFaceConnected = true;
                                if(bFaceConnected == false) if(IntersectEdges2D(v3OtherLocal3.x, v3OtherLocal3.y, v3OtherLocal1.x, v3OtherLocal1.y, v3Local3.x, v3Local3.y, v3Local1.x, v3Local1.y)) bFaceConnected = true;
                            }

                            if(bFaceConnected)
                            {
                                int nHash = MeshDataConnectivity.GetNewHash(); // New hash value to identify the 2 shared faces
                                meshData1.meshDataConnectivity.NotifyNewCapFace(nHash, nSubMesh1, nFace1);
                                meshData2.meshDataConnectivity.NotifyNewCapFace(nHash, nSubMesh2, nFace2);
                                bConnected = true;
                            }
                        }
                    }
                }
            }

            return bConnected;
        }
Ejemplo n.º 21
0
    public Vector3 ClosestPointOn(Vector3 to, float bodyRadius, bool displayDebugInfo, bool displayExtendedDebugInfo)
    {
        RPGTriangleTree tt;

        if (triangleTrees.TryGetValue(meshId, out tt))
        {
            Vector3
                p = Vector3.zero,
                p0 = Vector3.zero,
                p1 = Vector3.zero,
                p2 = Vector3.zero,
                tp0 = Vector3.zero,
                tp1 = Vector3.zero,
                tp2 = Vector3.zero,
                closestPoint = Vector3.zero;

            float magnitude = float.MaxValue;
            Vector3 localOrigin = transform.InverseTransformPoint(to);

            triangles.Clear();
            tt.FindClosestTriangles(localOrigin, bodyRadius, triangles);

            foreach (int index in triangles)
            {
                tt.GetTrianglePoints(index, out p0, out p1, out p2);

                if (displayDebugInfo)
                {
                    Debug.DrawLine(transform.TransformPoint(p0), transform.TransformPoint(p1), color);
                    Debug.DrawLine(transform.TransformPoint(p1), transform.TransformPoint(p2), color);
                    Debug.DrawLine(transform.TransformPoint(p2), transform.TransformPoint(p0), color);
                }

                ClosestPointOnTriangleToPoint(ref p0, ref p1, ref p2, ref localOrigin, out closestPoint);
                closestPoint = transform.TransformPoint(closestPoint);

                if ((closestPoint - to).magnitude < magnitude)
                {
                    p = closestPoint;
                    tp0 = transform.TransformPoint(p0);
                    tp1 = transform.TransformPoint(p1);
                    tp2 = transform.TransformPoint(p2);
                    magnitude = (closestPoint - to).magnitude;
                }
            }

            if (triangles.Count > 0)
            {
                Plane trianglePlane = new Plane(tp0, tp1, tp2);
                Vector3 projectedPoint = to - trianglePlane.GetDistanceToPoint(to) * trianglePlane.normal;

                if (PointLiesInTriangle(projectedPoint, p0, p1, p2))
                {
                    p = projectedPoint;
                }

                if (displayDebugInfo)
                {
                    Debug.DrawLine(tp0, tp1);
                    Debug.DrawLine(tp1, tp2);
                    Debug.DrawLine(tp2, tp0);
                }

                return p;
            }
        }

        return Vector3.zero;
    }
	/// <summary>
	/// This function calculates the closest point on the spline to a given plane.
	/// </summary>
	/// <returns>
	/// The closest spline parameter of the point to the plane on the spline.
	/// </returns>
	/// <param name='plane'>
	/// A given plane.
	/// </param>
	/// <param name='iterations'>
	/// Defines how accurate the calculation will be. A value of 5 should be high enough for most purposes. 
	/// </param>
	/// <param name='start'>
	/// A spline parameter from 0 to 1 that specifies the lower bound for the numeric search. (default is 0.0)
	/// </param>
	/// <param name='end'>
	/// A spline parameter from 0 to 1 that specifies the upper bound for the numeric search. (default is 1.0)
	/// </param>
	/// <param name='step'>
	/// Specifies the step between two sample points on the spline for the 1st iteration. (default is 0.01) 
	/// </param>
	public float GetClosestPointParamToPlane( Plane plane, int iterations, float start = 0, float end = 1, float step = .01f )
	{
		return GetClosestPointParamIntern( (splinePos) => Mathf.Abs( plane.GetDistanceToPoint( splinePos ) ), iterations, start, end, step );
	}
Ejemplo n.º 23
0
    public void Update()
    {
        if(boundsOctree==null)
        {
            boundsOctree = BoidsArea.getBoundsOctree(transform.position);
        }

        if (boundsOctree != null)
        {
            if(!boundsOctree.isPointInside(transform.position))
            {
                boundsOctree = BoidsArea.getBoundsOctree(transform.position);
            }

            if(boundsOctree !=null && boundsOctree.Border)
            {
                if (boundsOctree.neighbors != null)
                {
                    RepelVelocity = Vector3.zero;
                    gotObstacles = false;
                    foreach (var neighBor in boundsOctree.neighbors)
                    {
                        if (!neighBor.Empty || neighBor.Obstacle)
                        {
                            Vector3 v1 = (boundsOctree.position - neighBor.position);
                            Vector3 v2 = getFaceDirection((v1 * neighBor.size * 2)+boundsOctree.position, neighBor);

                            Vector3 facePoint = boundsOctree.position + (-v2 * boundsOctree.size);
                            //getting corner
                            Vector3 v2isOne;
                            v2isOne.x = v2.x * v2.x;
                            v2isOne.y = v2.y * v2.y;
                            v2isOne.z = v2.z * v2.z;

                            if (v2isOne == Vector3.one) // special case if its a corner.
                            {
                                Vector3 repelDir = facePoint - transform.position;
                                if (repelDir.sqrMagnitude <= maximumObstacleDistance * maximumObstacleDistance)
                                {
                                    RepelVelocity += repelDir.normalized * (1.0f - (repelDir.magnitude / maximumObstacleDistance));
                                    gotObstacles = true;

                                }
                            }
                            else
                            {
                                Plane p1 = new Plane((facePoint - boundsOctree.position).normalized, facePoint);
                                float distance = p1.GetDistanceToPoint(transform.position);

                                Debug.DrawLine(facePoint, transform.position, Color.yellow);

                                if (distance < maximumObstacleDistance)
                                {
                                    Debug.DrawLine(transform.position, transform.position - (p1.normal * distance), Color.red);

                                    gotObstacles = true;

                                    RepelVelocity += v2.normalized * (1.0f - (distance / maximumObstacleDistance));
                                }

                            }
                        }
                    }
                    if (gotObstacles)
                    {
                        schooling.RepelVelocity = RepelVelocity;
                        schooling.GroupUpVelocity = Vector3.zero;
                        schooling.MatchVelocity = Vector3.zero;

                    }

                }
            }
        }
    }
Ejemplo n.º 24
0
    void UpdateParticles2()
    {
        Plane movePlane = new Plane();

        for (int i = 1; i < m_Particles.Count; ++i)
        {
            Particle p = m_Particles[i];
            Particle p0 = m_Particles[p.m_ParentIndex];

            float restLen;
            if (p.m_Transform != null)
            {
                restLen = (p0.m_Transform.position - p.m_Transform.position).magnitude;
            }
            else
            {
                restLen = p0.m_Transform.localToWorldMatrix.MultiplyVector(p.m_EndOffset).magnitude;
            }

            // keep shape
            float stiffness = Mathf.Lerp(1.0f, p.m_Stiffness, m_Weight);
            if (stiffness > 0 || p.m_Elasticity > 0)
            {
                Matrix4x4 m0 = p0.m_Transform.localToWorldMatrix;
                m0.SetColumn(3, p0.m_Position);
                Vector3 restPos;
                if (p.m_Transform != null)
                {
                    restPos = m0.MultiplyPoint3x4(p.m_Transform.localPosition);
                }
                else
                {
                    restPos = m0.MultiplyPoint3x4(p.m_EndOffset);
                }

                Vector3 d = restPos - p.m_Position;
                p.m_Position += d * p.m_Elasticity;

                if (stiffness > 0)
                {
                    d = restPos - p.m_Position;
                    float len = d.magnitude;
                    float maxlen = restLen * (1 - stiffness) * 2;
                    if (len > maxlen)
                    {
                        p.m_Position += d * ((len - maxlen) / len);
                    }
                }
            }

            // collide
            if (m_Colliders != null)
            {
                float particleRadius = p.m_Radius * m_ObjectScale;
                foreach (DynamicBoneCollider c in m_Colliders)
                {
                    if (c != null && c.enabled)
                        c.Collide(ref p.m_Position, particleRadius);
                }
            }

            // freeze axis, project to plane
            if (m_FreezeAxis != FreezeAxis.None)
            {
                switch (m_FreezeAxis)
                {
                    case FreezeAxis.X:
                        movePlane.SetNormalAndPosition(p0.m_Transform.right, p0.m_Position);
                        break;
                    case FreezeAxis.Y:
                        movePlane.SetNormalAndPosition(p0.m_Transform.up, p0.m_Position);
                        break;
                    case FreezeAxis.Z:
                        movePlane.SetNormalAndPosition(p0.m_Transform.forward, p0.m_Position);
                        break;
                }
                p.m_Position -= movePlane.normal * movePlane.GetDistanceToPoint(p.m_Position);
            }

            // keep length
            Vector3 dd = p0.m_Position - p.m_Position;
            float leng = dd.magnitude;
            if (leng > 0)
            {
                p.m_Position += dd * ((leng - restLen) / leng);
            }
        }
    }
Ejemplo n.º 25
0
        protected override bool CalculateTagalongTargetPosition(Vector3 fromPosition, out Vector3 toPosition)
        {
            bool needsToMoveX = false;
            bool needsToMoveY = false;
            toPosition = fromPosition;

            // Cache some things that we will need later.
            Transform cameraTransform = Camera.main.transform;
            Vector3 cameraPosition = cameraTransform.position;

            // Get the bounds of the Tagalong's collider.
            Bounds colliderBounds = tagalongCollider.bounds;

            // Default the new position to be the current position.
            Vector3 newToPosition = tagalongCollider.bounds.center;

            // Adjust the center of the bounds to be TagalongDistance away from
            // the camera. We will use this point instead of tranform.position for
            // the rest of our calculations.
            Ray rayTemp = new Ray(cameraPosition, colliderBounds.center - cameraPosition);
            colliderBounds.center = rayTemp.GetPoint(TagalongDistance);

#if UNITY_EDITOR
            DebugDrawColliderBox(DebugDrawLines, colliderBounds);
#endif // UNITY_EDITOR

            // Get the actual width and height of the Tagalong's BoxCollider.
            float width = tagalongCollider.size.x * transform.lossyScale.x;
            float height = tagalongCollider.size.y * transform.lossyScale.y;

            // Determine if the Tagalong is to the left or right of the Camera's
            // forward vector.
            Plane verticalCenterPlane = new Plane(cameraTransform.right, cameraPosition + cameraTransform.forward);
            bool tagalongIsRightOfCenter = verticalCenterPlane.GetDistanceToPoint(colliderBounds.center) > 0;

            // Based on left/right of center choose the appropriate directional
            // vector and frustum plane for the rest of our horizontal calculations.
            Vector3 horizontalTowardCenter = tagalongIsRightOfCenter ? -transform.right : transform.right;
            Plane verticalFrustumPlane = tagalongIsRightOfCenter ? frustumPlanes[frustumRight] : frustumPlanes[frustumLeft];

            // Find the edge of the collider that is closest to the center plane.
            Vector3 centermostHorizontalEdge = colliderBounds.center + (horizontalTowardCenter * (width / 2f));

            // Find the point on the collider that is the MinimumHorizontalOverlap
            // as percentage away from the centermostHorizontalEdge.
            Vector3 targetPoint = centermostHorizontalEdge + (-horizontalTowardCenter * (width * MinimumHorizontalOverlap));

            // If the calculated targetPoint is outside the verticalFrustumPlane
            // of interest, we need to move the tagalong so it is at least
            // TargetHorizontalOverlap inside the view frustum.
            needsToMoveX = verticalFrustumPlane.GetDistanceToPoint(targetPoint) < 0;
            if (needsToMoveX || DebugDrawLines)
            {
                // Calculate the new target position, ignoring the vertical.
                Vector3 newCalculatedTargetPosition =
                    CalculateTargetPosition(true, centermostHorizontalEdge, horizontalTowardCenter, width,
                    colliderBounds.center, verticalFrustumPlane, tagalongIsRightOfCenter);

                if (needsToMoveX)
                {
                    newToPosition.x = newCalculatedTargetPosition.x;
                    newToPosition.z = newCalculatedTargetPosition.z;
                }
            }

            // Repeat everything we did above, but for the vertical dimension.
            // Comments will be abbreviated.

            colliderBounds = tagalongCollider.bounds;
            rayTemp = new Ray(cameraPosition, colliderBounds.center - cameraPosition);
            colliderBounds.center = rayTemp.GetPoint(TagalongDistance);
            Plane horizontalCenterPlane = new Plane(cameraTransform.up, cameraPosition + cameraTransform.forward);
            bool tagalongIsAboveCenter = horizontalCenterPlane.GetDistanceToPoint(colliderBounds.center) > 0;
            Vector3 verticalTowardCenter = tagalongIsAboveCenter ? -transform.up : transform.up;
            Plane horizontalFrustumPlane = tagalongIsAboveCenter ? frustumPlanes[frustumTop] : frustumPlanes[frustumBottom];
            Vector3 centermostVerticalEdge = colliderBounds.center + (verticalTowardCenter * (height / 2f));
            targetPoint = centermostVerticalEdge + (-verticalTowardCenter * (height * MinimumVerticalOverlap));
            // We've determined the Tagalong needs to move in the YZ plane.
            needsToMoveY = horizontalFrustumPlane.GetDistanceToPoint(targetPoint) < 0;
            if (needsToMoveY || DebugDrawLines)
            {
                // Calculate the new target position, ignoring the vertical.
                Vector3 newCalculatedTargetPosition =
                    CalculateTargetPosition(false, centermostVerticalEdge, verticalTowardCenter, height,
                    colliderBounds.center, horizontalFrustumPlane, !tagalongIsAboveCenter);
                if (needsToMoveY)
                {
                    newToPosition.y = newCalculatedTargetPosition.y;
                    newToPosition.z = newCalculatedTargetPosition.z;
                }
            }

            if (needsToMoveX || needsToMoveY)
            {
                Ray ray = new Ray(cameraPosition, newToPosition - cameraPosition);
                toPosition = ray.GetPoint(TagalongDistance);
            }

            return needsToMoveX || needsToMoveY;
        }
Ejemplo n.º 26
0
    private void Split(Plane worldPlane, Vector3 lineStart, Vector3 lineEnd, int casts)
    {
        if (!splitting)
            return;

        // Sometimes there is null here
        // Too lazy to find real reason right now
        if (transform == null)
            return;

        float distance = worldPlane.GetDistanceToPoint(transform.position);

        Plane plane = new Plane();
        Vector3 newNormal = transform.InverseTransformDirection(worldPlane.normal);
        //Vector3 newNormal = Quaternion.Inverse(transform.rotation) * worldPlane.normal;
        plane.SetNormalAndPosition(newNormal, newNormal * -distance);

        posNormals.Add(-newNormal);
        negNormals.Add(newNormal);
        posNormals.AddRange(mesh.normals);
        negNormals.AddRange(mesh.normals);

        for (int i = 0; i < triangles.Length; i += 3)
        {
            int i1 = triangles[i];//index 1, 2 and 3 of vertices
            int i2 = triangles[i + 1];
            int i3 = triangles[i + 2];
            bool side1 = plane.GetSide(vertices[i1]);
            bool side2 = plane.GetSide(vertices[i2]);
            bool side3 = plane.GetSide(vertices[i3]);

            if (side1 == true && side2 == true && side3 == true)
            {
                posTriangles.Add(i1 + 1); //first index is reserved for interior face middle vertex so every index is incremented by 1
                posTriangles.Add(i2 + 1);
                posTriangles.Add(i3 + 1);
            }
            else if (side1 == false && side2 == false && side3 == false)
            {
                negTriangles.Add(i1 + 1);
                negTriangles.Add(i2 + 1);
                negTriangles.Add(i3 + 1);
            }
            else
            {
                //find odd boolean value(expression found using karnaugh map)
                bool odd = (!side1 && !side2) || (!side1 && !side3) || (!side2 && !side3);

                //find vertex with odd boolean value
                int vertex1, vertex2;
                if (side1 == odd)
                {
                    vertex1 = findNewVertex(i1, i2, plane);
                    vertex2 = findNewVertex(i1, i3, plane);
                    if (side1 == true)
                    {                                          //               i1 /\                  Positive Side
                        posTriangles.Add(i1 + 1);              //                 /  \
                        posTriangles.Add(vertex1 + 1);         //         vertex1/____\vertex2
                        posTriangles.Add(vertex2 + 1);         //               /   _-'\
                                                               //            i2/_.-'____\i3            Negative Side
                        negTriangles.Add(i2 + 1);
                        negTriangles.Add(i3 + 1);
                        negTriangles.Add(vertex2 + 1);

                        negTriangles.Add(i2 + 1);
                        negTriangles.Add(vertex2 + 1);
                        negTriangles.Add(vertex1 + 1);
                    }
                    else
                    {                                           //               i1 /\                  Negative Side
                        negTriangles.Add(i1 + 1);               //                 /  \
                        negTriangles.Add(vertex1 + 1);          //         vertex1/____\vertex2
                        negTriangles.Add(vertex2 + 1);          //               /   _-'\
                                                                //            i2/_.-'____\i3            Positive Side
                        posTriangles.Add(i2 + 1);
                        posTriangles.Add(i3 + 1);
                        posTriangles.Add(vertex2 + 1);

                        posTriangles.Add(i2 + 1);
                        posTriangles.Add(vertex2 + 1);
                        posTriangles.Add(vertex1 + 1);
                    }
                }
                else if (side2 == odd)
                {
                    vertex1 = findNewVertex(i2, i3, plane);
                    vertex2 = findNewVertex(i2, i1, plane);
                    if (side2 == true)
                    {                                           //               i2 /\                  Positive Side
                        posTriangles.Add(i2 + 1);               //                 /  \
                        posTriangles.Add(vertex1 + 1);          //         vertex1/____\vertex2
                        posTriangles.Add(vertex2 + 1);          //               /   _-'\
                                                                //            i3/_.-'____\i1            Negative Side
                        negTriangles.Add(i3 + 1);
                        negTriangles.Add(i1 + 1);
                        negTriangles.Add(vertex2 + 1);

                        negTriangles.Add(i3 + 1);
                        negTriangles.Add(vertex2 + 1);
                        negTriangles.Add(vertex1 + 1);
                    }
                    else
                    {                                           //               i2 /\                  Negative Side
                        negTriangles.Add(i2 + 1);               //                 /  \
                        negTriangles.Add(vertex1 + 1);          //         vertex1/____\vertex2
                        negTriangles.Add(vertex2 + 1);          //               /   _-'\
                                                                //            i3/_.-'____\i1            Positive Side
                        posTriangles.Add(i3 + 1);
                        posTriangles.Add(i1 + 1);
                        posTriangles.Add(vertex2 + 1);

                        posTriangles.Add(i3 + 1);
                        posTriangles.Add(vertex2 + 1);
                        posTriangles.Add(vertex1 + 1);
                    }
                }
                else
                {
                    vertex1 = findNewVertex(i3, i1, plane);
                    vertex2 = findNewVertex(i3, i2, plane);
                    if (side3 == true)
                    {                                           //               i3 /\                  Positive Side
                        posTriangles.Add(i3 + 1);               //                 /  \
                        posTriangles.Add(vertex1 + 1);          //         vertex1/____\vertex2
                        posTriangles.Add(vertex2 + 1);          //               /   _-'\
                                                                //            i1/_.-'____\i2            Negative Side
                        negTriangles.Add(i1 + 1);
                        negTriangles.Add(i2 + 1);
                        negTriangles.Add(vertex2 + 1);

                        negTriangles.Add(i1 + 1);
                        negTriangles.Add(vertex2 + 1);
                        negTriangles.Add(vertex1 + 1);
                    }
                    else
                    {                                           //               i3 /\                  Negative Side
                        negTriangles.Add(i3 + 1);               //                 /  \
                        negTriangles.Add(vertex1 + 1);          //         vertex1/____\vertex2
                        negTriangles.Add(vertex2 + 1);          //               /   _-'\
                                                                //            i1/_.-'____\i2            Positive Side
                        posTriangles.Add(i1 + 1);
                        posTriangles.Add(i2 + 1);
                        posTriangles.Add(vertex2 + 1);

                        posTriangles.Add(i1 + 1);
                        posTriangles.Add(vertex2 + 1);
                        posTriangles.Add(vertex1 + 1);
                    }
                }

                if (odd == true)
                {
                    //add inner triangles
                    posInnerTriangles.Add(vertex1 + 2);
                    posInnerTriangles.Add(0);
                    posInnerTriangles.Add(vertex2 + 2);

                    negInnerTriangles.Add(vertex1 + 2);
                    negInnerTriangles.Add(vertex2 + 2);
                    negInnerTriangles.Add(0);
                }
                else
                {
                    negInnerTriangles.Add(vertex1 + 2);
                    negInnerTriangles.Add(0);
                    negInnerTriangles.Add(vertex2 + 2);

                    posInnerTriangles.Add(vertex1 + 2);
                    posInnerTriangles.Add(vertex2 + 2);
                    posInnerTriangles.Add(0);
                }

                /*if (odd == true)
                {
                    //add inner triangles
                    posTriangles.Add(vertex1 + 1);
                    posTriangles.Add(0);
                    posTriangles.Add(vertex2 + 1);

                    negTriangles.Add(vertex1 + 1);
                    negTriangles.Add(vertex2 + 1);
                    negTriangles.Add(0);
                }
                else
                {
                    negTriangles.Add(vertex1 + 1);
                    negTriangles.Add(0);
                    negTriangles.Add(vertex2 + 1);

                    posTriangles.Add(vertex1 + 1);
                    posTriangles.Add(vertex2 + 1);
                    posTriangles.Add(0);
                }*/
            }
        }
        //now average all seam vertices to find center of inner face
        float x = 0;
        float y = 0;
        float z = 0;
        int n = seamVertices.Count;
        for (int j = 0; j < n; j++)
        {
            Vector3 current = seamVertices[j];
            x += current.x;
            y += current.y;
            z += current.z;
        }
        Vector3 center = new Vector3(x / n, y / n, z / n);

        var newVertices = new List<Vector3>();
        newVertices.Add(center); // at index 0
        newVertices.AddRange(vertices); // index 1 to vertices.length
        newVertices.AddRange(seamVertices); // then add the new seam vertices
        Vector3[] doneVertices = newVertices.ToArray();
        Vector2[] uvs = uv.ToArray();

        if (posTriangles.Count != 0 && negTriangles.Count != 0)//dont bother creating a gameobject if there are no triangles
        {
            Vector3 force = plane.normal * 50f;
            CreateNewSplit(doneVertices, posTriangles.ToArray(), posInnerTriangles.ToArray(), uvs, posNormals.ToArray(), force);
            CreateNewSplit(doneVertices, negTriangles.ToArray(), negInnerTriangles.ToArray(), uvs, negNormals.ToArray(), -force);
            if (OnSplit != null)
                OnSplit();
        }
        else
        {
            return;
        }

        splitting = false;
        PlaneGenerator.OnGeneration -= Split;
        Destroy(gameObject);
    }
Ejemplo n.º 27
0
	/// <summary>
	/// Returns the width, in screen pixels, of the specified string
	/// were it to be rendered using the current font and settings.
	/// NOTE: Assumes the string is a single line.
	/// </summary>
	/// <param name="s">The string to measure.</param>
	/// <returns>The width, in world units.</returns>
	public float GetScreenWidth(string s)
	{
		if (spriteFont == null)
			return 0;

		if (renderCamera == null)
			return 0;

		float dist;
		Plane nearPlane = new Plane(renderCamera.transform.forward, renderCamera.transform.position);

		screenSize.x = renderCamera.pixelWidth;
		screenSize.y = renderCamera.pixelHeight;

		// Determine the world distance between two vertical
		// screen pixels for this camera:
		dist = nearPlane.GetDistanceToPoint(transform.position);
		worldUnitsPerScreenPixel = Vector3.Distance(renderCamera.ScreenToWorldPoint(new Vector3(0, 1, dist)), renderCamera.ScreenToWorldPoint(new Vector3(0, 0, dist)));

		return GetWidth(s) / worldUnitsPerScreenPixel;
	}
Ejemplo n.º 28
0
	/// <summary>
	/// Gets the 3d overlay position of the given joint over the depth-image.
	/// </summary>
	/// <returns>The joint position for depth overlay.</returns>
	/// <param name="userId">User ID</param>
	/// <param name="joint">Joint index</param>
	/// <param name="camera">Camera used to visualize the 3d overlay position</param>
	/// <param name="imageRect">Depth image rectangle on the screen</param>
	public Vector3 GetJointPosDepthOverlay(Int64 userId, int joint, Camera camera, Rect imageRect)
	{
		if(dictUserIdToIndex.ContainsKey(userId))
		{
			int index = dictUserIdToIndex[userId];
			
			if(index >= 0 && index < sensorData.bodyCount && 
			   bodyFrame.bodyData[index].bIsTracked != 0)
			{
				if(joint >= 0 && joint < sensorData.jointCount)
				{
					KinectInterop.JointData jointData = bodyFrame.bodyData[index].joint[joint];
					Vector3 posJointRaw = jointData.kinectPos;
					
					if(posJointRaw != Vector3.zero)
					{
						// 3d position to depth
						Vector2 posDepth = MapSpacePointToDepthCoords(posJointRaw);

						if(posDepth != Vector2.zero && sensorData != null)
						{
							if(!float.IsInfinity(posDepth.x) && !float.IsInfinity(posDepth.y))
							{
								float xScaled = (float)posDepth.x * imageRect.width / sensorData.depthImageWidth;
								float yScaled = (float)posDepth.y * imageRect.height / sensorData.depthImageHeight;

								float xScreen = imageRect.x + xScaled;
								float yScreen = camera.pixelHeight - (imageRect.y + yScaled);
								
								Plane cameraPlane = new Plane(camera.transform.forward, camera.transform.position);
								float zDistance = cameraPlane.GetDistanceToPoint(jointData.kinectPos);

								Vector3 vPosJoint = camera.ScreenToWorldPoint(new Vector3(xScreen, yScreen, zDistance));
								
								return vPosJoint;
							}
						}
					}
				}
			}
		}
		
		return Vector3.zero;
	}
Ejemplo n.º 29
0
    void FirstSliceMethod()
    {
        newPlane = new UnityEngine.Plane(transform.rotation * Vector3.up, -Vector3.Dot(transform.up, transform.position));
        foreach (var meshTransform in meshes)
        {
            z = z2 = 0;

            vertices = meshTransform.GetComponent <MeshFilter>().mesh.vertices;

            int[] triangles = meshTransform.GetComponent <MeshFilter>().mesh.triangles;
            trisList  = new List <int>();
            trisList2 = new List <int>();



            Vector3 pointB  = new Vector3(); //point bellow
            Vector3 pointA1 = new Vector3(); //point above 1
            Vector3 pointA2 = new Vector3(); //point above 2


            Vector3 pointB1 = new Vector3(); //point bellow 1
            Vector3 pointB2 = new Vector3(); //point bellow 2
            Vector3 pointA  = new Vector3(); //point above

            Vector3 transformPosition = transform.position;
            initialUVs = meshTransform.GetComponent <MeshFilter>().mesh.uv;
            uvs        = new List <Vector2>();
            uvs2       = new List <Vector2>();
            for (int i = 0; i < triangles.Length; i += 3)
            {
                var i0 = meshTransform.TransformPoint(vertices[triangles[i]]);
                var i1 = meshTransform.TransformPoint(vertices[triangles[i + 1]]);
                var i2 = meshTransform.TransformPoint(vertices[triangles[i + 2]]);

                var uv0 = meshTransform.TransformPoint(initialUVs[triangles[i]]);
                var uv1 = meshTransform.TransformPoint(initialUVs[triangles[i + 1]]);
                var uv2 = meshTransform.TransformPoint(initialUVs[triangles[i + 2]]);

                float dist0 = newPlane.GetDistanceToPoint(i0);
                float dist1 = newPlane.GetDistanceToPoint(i1);
                float dist2 = newPlane.GetDistanceToPoint(i2);

                if (dist0 <= 0 &&
                    dist1 <= 0 &&
                    dist2 <= 0)
                {
                    uvPoint = uv0;
                    point   = i0;
                    CheckContains(true);
                    uvPoint = uv1;
                    point   = i1;
                    CheckContains(true);
                    uvPoint = uv2;
                    point   = i2;
                    CheckContains(true);
                }

                if (dist0 > 0 &&
                    dist1 > 0 &&
                    dist2 > 0)
                {
                    //continue;
                    uvPoint = uv0;
                    point   = i0;
                    CheckContains(false);
                    uvPoint = uv1;
                    point   = i1;
                    CheckContains(false);
                    uvPoint = uv2;
                    point   = i2;
                    CheckContains(false);
                }

                if (dist0 > 0 &&
                    dist1 <= 0 &&
                    dist2 <= 0)
                {
                    var     LineForward = (i0 - i2) / (i0 - i2).sqrMagnitude;
                    float   t           = Vector3.Dot(transform.position - i0, -transform.up) / Vector3.Dot(LineForward, -transform.up);
                    Vector3 p           = i0 + LineForward * t;


                    uvPoint = p;
                    point   = p;
                    CheckContains(true);
                    //uvPoint= uv1;
                    point = i1;
                    CheckContains(true);
                    //uvPoint= uv2;
                    point = i2;
                    CheckContains(true);


                    var     LineForward2 = (i0 - i1) / (i0 - i1).magnitude;
                    float   t2           = Vector3.Dot(transform.position - i0, -transform.up) / Vector3.Dot(LineForward2, -transform.up);
                    Vector3 p2           = i0 + LineForward2 * t2;

                    //uvPoint= p;
                    point = p;
                    CheckContains(true);
                    //uvPoint= p2;
                    point = p2;
                    CheckContains(true);
                    //uvPoint= uv1;
                    point = i1;
                    CheckContains(true);


                    point = p;
                    FillFacePointsCheckContains(true);
                    point = p2;
                    FillFacePointsCheckContains(true);
                }
                if (dist0 <= 0 &&
                    dist1 > 0 &&
                    dist2 > 0)
                {
                    // continue;
                    var   LineForward = (i0 - i2) / (i0 - i2).sqrMagnitude;
                    float t           = Vector3.Dot(transform.position - i0, -transform.up) / Vector3.Dot(LineForward, -transform.up);
                    var   p           = i0 + LineForward * t;

                    //uvPoint= p;
                    point = p;
                    CheckContains(false);
                    //uvPoint= uv1;
                    point = i1;
                    CheckContains(false);
                    //uvPoint= uv2;
                    point = i2;
                    CheckContains(false);


                    var   LineForward2 = (i0 - i1) / (i0 - i1).sqrMagnitude;
                    float t2           = Vector3.Dot(transform.position - i0, -transform.up) / Vector3.Dot(LineForward2, -transform.up);
                    var   p2           = i0 + LineForward2 * t2;

                    //uvPoint= p;
                    point = p;
                    CheckContains(false);
                    //uvPoint= p2;
                    point = p2;
                    CheckContains(false);
                    //uvPoint= uv1;
                    point = i1;
                    CheckContains(false);

                    point = p;
                    FillFacePointsCheckContains(false);
                    point = p2;
                    FillFacePointsCheckContains(false);
                }
                #region one point bellow
                if ((dist0 > 0 &&
                     dist1 <= 0 &&
                     dist2 > 0) ||

                    (dist0 <= 0 &&
                     dist1 > 0 &&
                     dist2 > 0) ||

                    (dist0 > 0 &&
                     dist1 > 0 &&
                     dist2 <= 0))
                {
                    if (dist1 <= 0)
                    {
                        pointB  = i1;
                        pointA1 = i0;
                        pointA2 = i2;
                    }
                    if (dist0 <= 0)
                    {
                        pointB  = i0;
                        pointA1 = i1;
                        pointA2 = i2;
                    }
                    if (dist2 <= 0)
                    {
                        pointB  = i2;
                        pointA1 = i0;
                        pointA2 = i1;
                    }
                    var   LineForward = (pointB - pointA1) / (pointB - pointA1).sqrMagnitude;
                    float t           = Vector3.Dot(transform.position - pointB, -transform.up) / Vector3.Dot(LineForward, -transform.up);
                    var   p           = pointB + (LineForward * t);

                    var   LineForward2 = (pointB - pointA2) / (pointB - pointA2).sqrMagnitude;
                    float t2           = Vector3.Dot(transform.position - pointB, -transform.up) / Vector3.Dot(LineForward2, -transform.up);
                    var   p2           = pointB + LineForward2 * t2;
                    if (dist0 <= 0)
                    {
                        //uvPoint= pointB;
                        point = pointB;
                        CheckContains(true);
                        //uvPoint= p;
                        point = p;
                        CheckContains(true);
                        //uvPoint= p2;
                        point = p2;
                        CheckContains(true);
                    }
                    if (dist1 <= 0)
                    {
                        //uvPoint= p;
                        point = p;
                        CheckContains(true);
                        //uvPoint= pointB;
                        point = pointB;
                        CheckContains(true);
                        //uvPoint= p2;
                        point = p2;
                        CheckContains(true);
                    }
                    if (dist2 <= 0)
                    {
                        //uvPoint= pointB;
                        point = pointB;
                        CheckContains(true);
                        //uvPoint= p;
                        point = p;
                        CheckContains(true);
                        //uvPoint= p2;
                        point = p2;
                        CheckContains(true);
                    }

                    point = p;
                    FillFacePointsCheckContains(true);
                    point = p2;
                    FillFacePointsCheckContains(true);
                }
                #endregion
                #region one point above


                if ((dist0 <= 0 &&
                     dist1 > 0 &&
                     dist2 <= 0) ||

                    (dist0 > 0 &&
                     dist1 <= 0 &&
                     dist2 <= 0) ||

                    (dist0 <= 0 &&
                     dist1 <= 0 &&
                     dist2 > 0))
                {
                    if (dist1 > 0)
                    {
                        pointB  = i1;
                        pointA1 = i0;
                        pointA2 = i2;
                    }
                    if (dist0 > 0)
                    {
                        pointB  = i0;
                        pointA1 = i1;
                        pointA2 = i2;
                    }
                    if (dist2 > 0)
                    {
                        pointB  = i2;
                        pointA1 = i0;
                        pointA2 = i1;
                    }
                    var   LineForward = (pointB - pointA1) / (pointB - pointA1).sqrMagnitude;
                    float t           = Vector3.Dot(transform.position - pointB, -transform.up) / Vector3.Dot(LineForward, -transform.up);
                    var   p           = pointB + LineForward * t;

                    var   LineForward2 = (pointB - pointA2) / (pointB - pointA2).sqrMagnitude;
                    float t2           = Vector3.Dot(transform.position - pointB, -transform.up) / Vector3.Dot(LineForward2, -transform.up);
                    var   p2           = pointB + LineForward2 * t2;



                    if (dist0 > 0)
                    {
                        //uvPoint= pointB;
                        point = pointB;
                        CheckContains(false);
                        //uvPoint= p;
                        point = p;
                        CheckContains(false);
                        //uvPoint= p2;
                        point = p2;
                        CheckContains(false);
                    }
                    if (dist1 > 0)
                    {
                        //uvPoint= p;
                        point = p;
                        CheckContains(false);
                        //uvPoint= pointB;
                        point = pointB;
                        CheckContains(false);
                        //uvPoint= p2;
                        point = p2;
                        CheckContains(false);
                    }
                    if (dist2 > 0)
                    {
                        uvPoint = pointB;
                        point   = pointB;
                        CheckContains(false);
                        uvPoint = p;
                        point   = p;
                        CheckContains(false);
                        uvPoint = p2;
                        point   = p2;
                        CheckContains(false);
                    }
                    point = p;
                    FillFacePointsCheckContains(false);
                    point = p2;
                    FillFacePointsCheckContains(false);
                }
                #endregion

                #region two points bellow
                if (
                    (dist0 > 0 &&
                     dist1 <= 0 &&
                     dist2 <= 0) ||

                    (dist0 <= 0 &&
                     dist1 > 0 &&
                     dist2 <= 0) ||

                    (dist0 <= 0 &&
                     dist1 <= 0 &&
                     dist2 > 0)
                    )
                {
                    if (dist0 > 0)
                    {
                        pointB1 = i1;
                        pointB2 = i2;
                        pointA  = i0;
                    }
                    if (dist1 > 0)
                    {
                        pointB1 = i0;
                        pointB2 = i2;
                        pointA  = i1;
                    }
                    if (dist2 > 0)
                    {
                        pointB1 = i0;
                        pointB2 = i1;
                        pointA  = i2;
                    }

                    var   LineForward = (pointB1 - pointA) / (pointB1 - pointA).sqrMagnitude;
                    float t           = Vector3.Dot(transform.position - pointB1, -transform.up) / Vector3.Dot(LineForward, -transform.up);
                    var   p           = pointB1 + LineForward * t;

                    var   LineForward2 = (pointB2 - pointA) / (pointB2 - pointA).sqrMagnitude;
                    float t2           = Vector3.Dot(transform.position - pointB2, -transform.up) / Vector3.Dot(LineForward2, -transform.up);
                    var   p2           = pointB2 + LineForward2 * t2;



                    if (dist0 > 0)
                    {
                        //verticesList.Add(p);
                        //verticesList.Add(pointB1);
                        //verticesList.Add(p2);

                        //verticesList.Add(pointB1);
                        //verticesList.Add(pointB1);
                        //verticesList.Add(p2);
                    }
                    if (dist1 > 0)
                    {
                        uvPoint = p;
                        point   = p;
                        CheckContains(true);
                        uvPoint = p2;
                        point   = p2;
                        CheckContains(true);
                        uvPoint = pointB1;
                        point   = pointB1;
                        CheckContains(true);

                        uvPoint = pointB1;
                        point   = pointB1;
                        CheckContains(true);
                        uvPoint = p2;
                        point   = p2;
                        CheckContains(true);
                        uvPoint = pointB2;
                        point   = pointB2;
                        CheckContains(true);
                    }
                    if (dist2 > 0)
                    {
                        uvPoint = p;
                        point   = p;
                        CheckContains(true);
                        uvPoint = pointB1;
                        point   = pointB1;
                        CheckContains(true);
                        uvPoint = p2;
                        point   = p2;
                        CheckContains(true);

                        uvPoint = pointB1;
                        point   = pointB1;
                        CheckContains(true);
                        uvPoint = pointB2;
                        point   = pointB2;
                        CheckContains(true);
                        uvPoint = p2;
                        point   = p2;
                        CheckContains(true);
                    }

                    point = p;
                    FillFacePointsCheckContains(true);
                    point = p2;
                    FillFacePointsCheckContains(true);
                }
                #endregion

                #region two above bellow
                if (
                    (dist0 <= 0 &&
                     dist1 > 0 &&
                     dist2 > 0) ||

                    (dist0 > 0 &&
                     dist1 <= 0 &&
                     dist2 > 0) ||

                    (dist0 > 0 &&
                     dist1 > 0 &&
                     dist2 <= 0)
                    )
                {
                    //  continue;


                    if (dist0 <= 0)
                    {
                        pointB1 = i1;
                        pointB2 = i2;
                        pointA  = i0;
                    }
                    if (dist1 <= 0)
                    {
                        pointB1 = i0;
                        pointB2 = i2;
                        pointA  = i1;
                    }
                    if (dist2 <= 0)
                    {
                        pointB1 = i0;
                        pointB2 = i1;
                        pointA  = i2;
                    }

                    var   LineForward = (pointB1 - pointA) / (pointB1 - pointA).sqrMagnitude;
                    float t           = Vector3.Dot(transform.position - pointB1, -transform.up) / Vector3.Dot(LineForward, -transform.up);
                    var   p           = pointB1 + LineForward * t;

                    var   LineForward2 = (pointB2 - pointA) / (pointB2 - pointA).sqrMagnitude;
                    float t2           = Vector3.Dot(transform.position - pointB2, -transform.up) / Vector3.Dot(LineForward2, -transform.up);
                    var   p2           = pointB2 + LineForward2 * t2;



                    if (dist0 <= 0)
                    {
                        //verticesList2.Add(p);
                        //verticesList2.Add(pointB2);
                        //verticesList2.Add(p2);

                        //verticesList2.Add(p2);
                        //verticesList2.Add(pointB1);
                        //verticesList2.Add(pointB2);

                        //  z2 = AddTris2(z2, 1);
                    }
                    if (dist1 <= 0)
                    {
                        uvPoint = p;
                        point   = p;
                        CheckContains(false);
                        uvPoint = p2;
                        point   = p2;
                        CheckContains(false);
                        uvPoint = pointB1;
                        point   = pointB1;
                        CheckContains(false);

                        uvPoint = pointB1;
                        point   = pointB1;
                        CheckContains(false);
                        uvPoint = p2;
                        point   = p2;
                        CheckContains(false);
                        uvPoint = pointB2;
                        point   = pointB2;
                        CheckContains(false);
                    }
                    if (dist2 <= 0)
                    {
                        uvPoint = p;
                        point   = p;
                        CheckContains(false);
                        uvPoint = pointB1;
                        point   = pointB1;
                        CheckContains(false);
                        uvPoint = p2;
                        point   = p2;
                        CheckContains(false);

                        uvPoint = pointB1;
                        point   = pointB1;
                        CheckContains(false);
                        uvPoint = pointB2;
                        point   = pointB2;
                        CheckContains(false);
                        uvPoint = p2;
                        point   = p2;
                        CheckContains(false);
                    }
                    point = p;
                    FillFacePointsCheckContains(false);
                    point = p2;
                    FillFacePointsCheckContains(false);
                }
                #endregion
            }
            if (fillCutout)
            {
                FillVoid(fillFacePoints, true);
                FillVoid(fillFacePoints2, false);
            }

            //UnityEngine.Debug.Log(vertices.Length + " " + triangles.Length);
            //UnityEngine.Debug.Log(points.Count + " " + trisList.Count);

            CreateObjects(meshTransform);
        }
    }
Ejemplo n.º 30
0
	/// <summary>
	/// Sizes the viewable area of the scroll list using
	/// pixel dimensions as the unit of measurement.
	/// </summary>
	/// <param name="cam">The camera through which the list will be viewed.</param>
	/// <param name="width">The width, in pixels, of the list's viewable area.</param>
	/// <param name="height">The height, in pixels, of the list's viewable area.</param>
	public void SetViewableAreaPixelDimensions(Camera cam, int width, int height)
	{
		Plane nearPlane = new Plane(cam.transform.forward, cam.transform.position);

		// Determine the world distance between two vertical
		// screen pixels for this camera:
		float dist = nearPlane.GetDistanceToPoint(transform.position);
		float worldUnitsPerScreenPixel = Vector3.Distance(cam.ScreenToWorldPoint(new Vector3(0, 1, dist)), cam.ScreenToWorldPoint(new Vector3(0, 0, dist)));
		viewableAreaActual = new Vector2(width * worldUnitsPerScreenPixel, height * worldUnitsPerScreenPixel);

		CalcClippingRect();

		RepositionItems();
	}
Ejemplo n.º 31
0
    /// <summary> Loads binding sites and constraints from the specified file. </summary>
    // TODO: Don't make this static.  Add a manager to a GameObject and expose editor fields for resolver, search patterns, etc.
    public static GameObject[] BuildTriggerVolumes(GameObject bindingMesh, GameObject hostMesh)
    {
        List <GameObject> triggerVolumes = new List <GameObject> ();

        foreach (MeshFilter meshFilter in bindingMesh.GetComponentsInChildren <MeshFilter>(true))
        {
            Type         snapType     = default(Type);
            MeshRenderer meshRenderer = meshFilter.gameObject.GetComponent <MeshRenderer> ();

            string parentName   = meshRenderer.sharedMaterial.name;
            string BindCoplanar = "_bindCoplanar";
            string BindCoradial = "_bindCoradial";
            string BindFixed    = "_bindFixed";

            if (meshRenderer.sharedMaterial.name.EndsWith(BindCoplanar))
            {
                snapType   = typeof(CoplanarSnap);
                parentName = parentName.Substring(0, parentName.Length - BindCoplanar.Length);
            }
            else if (meshRenderer.sharedMaterial.name.EndsWith(BindCoradial))
            {
                snapType   = typeof(CoradialSnap);
                parentName = parentName.Substring(0, parentName.Length - BindCoradial.Length);
            }
            else if (meshRenderer.sharedMaterial.name.EndsWith(BindFixed))
            {
                snapType   = typeof(FixedSnap);
                parentName = parentName.Substring(0, parentName.Length - BindFixed.Length);
            }
            else
            {
                Debug.Log("WARNING: Invalid snap material: " + meshRenderer.sharedMaterial.name);
                continue;
            }

            bool wasActive = hostMesh.activeSelf;
            hostMesh.SetActive(true);
            GameObject parent = GameObject.Find(parentName);
            if (parent == null)
            {
                Debug.Log("WARNING: Failed to find parent object: " + parentName);
                continue;
            }
            hostMesh.SetActive(wasActive);

            Vector3[] vertices = meshFilter.sharedMesh.vertices;

            int[] triangles = meshFilter.sharedMesh.triangles;

            var polygons = new List <Vector3[]> ();

            // See if we can coalesce 2 triangles into a quad.
            for (int triangleBase = 0; triangleBase + 6 <= triangles.Length; triangleBase += 6)
            {
                bool      combinedTriangles = false;
                Vector3[] polygon           = new Vector3[4];

                int matchCount = 0;
                for (int i = 0; i < 3; i++)
                {
                    polygon [i] = vertices [triangles [triangleBase + i]];
                }

                for (int j = 3; j < 6; j++)
                {
                    bool foundMatch = false;
                    for (int i = 0; i < 3; i++)
                    {
                        if (Mathf.Approximately(polygon [i].x, vertices [triangles [triangleBase + j]].x) &&
                            Mathf.Approximately(polygon [i].y, vertices [triangles [triangleBase + j]].y) &&
                            Mathf.Approximately(polygon [i].z, vertices [triangles [triangleBase + j]].z))
                        {
                            foundMatch = true;
                            matchCount++;
                            break;
                        }
                    }
                    if (!foundMatch)
                    {
                        polygon [3] = vertices [triangles [triangleBase + j]];
                    }
                }
                if (matchCount == 2)
                {
                    UnityEngine.Plane plane = new UnityEngine.Plane(polygon [0], polygon [1], polygon [2]);
                    float             dist  = plane.GetDistanceToPoint(polygon [3]);
                    if (Mathf.Approximately(dist, 0.0f))
                    {
                        polygons.Add(polygon);
                        combinedTriangles = true;
                    }
                }

                if (!combinedTriangles)
                {
                    for (int i = 0; i < 6; i += 3)
                    {
                        Vector3[] triangle = new Vector3[3];
                        triangle [0] = vertices [triangles [triangleBase + i]];
                        triangle [1] = vertices [triangles [triangleBase + i + 1]];
                        triangle [2] = vertices [triangles [triangleBase + i + 2]];
                        polygons.Add(triangle);
                    }
                }
            }

            foreach (Vector3[] polygon in polygons)
            {
                float snapMargin = 0.005f;
                ++s_bindSiteIdSuffix;

                GameObject go = new GameObject(snapType.Name + s_bindSiteIdSuffix);

                go.transform.parent = parent.transform;

                go.transform.localScale    = Vector3.one;
                go.transform.localPosition = Vector3.zero;
                go.transform.localRotation = Quaternion.identity;

                triggerVolumes.Add(go);

                Snap Snap = go.AddComponent(snapType) as Snap;
                Snap.snapMargin = snapMargin;
                Snap.Polygon    = polygon;
            }

            UnityEngine.Object.Destroy(meshFilter.gameObject.GetComponent <MeshRenderer> ());
            UnityEngine.Object.Destroy(meshFilter);
        }

        return(triggerVolumes.ToArray());
    }
Ejemplo n.º 32
0
        public static Vector3 ProjectOnPlane(Vector3 point, Vector3 planePoint, Vector3 planeNormal)
        {
            planeNormal = planeNormal.normalized;

            Plane plane = new Plane(planeNormal, planePoint);
            float distance = plane.GetDistanceToPoint(point);

            return point - (distance*planeNormal);
        }
        // Assuming the target object is outside the view which of the four "wall" planes should
        // the pointer snap to.
        private FrustumPlanes GetExitPlane(Vector3 targetPosition, Camera camera)
        {
            // To do this we first create two planes that diagonally bisect the frustum
            // These panes create four quadrants. We then infer the exit plane based on
            // which quadrant the target position is in.

            // Calculate a set of vectors that can be used to build the frustum corners in world
            // space.
            float aspect = camera.aspect;
            float fovy = 0.5f * camera.fieldOfView;
            float near = camera.nearClipPlane;
            float far = camera.farClipPlane;

            float tanFovy = Mathf.Tan(Mathf.Deg2Rad * fovy);
            float tanFovx = aspect * tanFovy;

            // Calculate the edges of the frustum as world space offsets from the middle of the
            // frustum in world space.
            Vector3 nearTop = near * tanFovy * cameraUp;
            Vector3 nearRight = near * tanFovx * cameraRight;
            Vector3 nearBottom = -nearTop;
            Vector3 nearLeft = -nearRight;
            Vector3 farTop = far * tanFovy * cameraUp;
            Vector3 farRight = far * tanFovx * cameraRight;
            Vector3 farLeft = -farRight;

            // Caclulate the center point of the near plane and the far plane as offsets from the
            // camera in world space.
            Vector3 nearBase = near * cameraForward;
            Vector3 farBase = far * cameraForward;

            // Calculate the frustum corners needed to create 'd'
            Vector3 nearUpperLeft = nearBase + nearTop + nearLeft;
            Vector3 nearLowerRight = nearBase + nearBottom + nearRight;
            Vector3 farUpperLeft = farBase + farTop + farLeft;

            Plane d = new Plane(nearUpperLeft, nearLowerRight, farUpperLeft);

            // Calculate the frustum corners needed to create 'e'
            Vector3 nearUpperRight = nearBase + nearTop + nearRight;
            Vector3 nearLowerLeft = nearBase + nearBottom + nearLeft;
            Vector3 farUpperRight = farBase + farTop + farRight;

            Plane e = new Plane(nearUpperRight, nearLowerLeft, farUpperRight);

            #if UNITY_EDITOR
            if (DebugDrawPointerOrientationPlanes)
            {
                // Debug draw a tringale coplanar with 'd'
                Debug.DrawLine(nearUpperLeft, nearLowerRight);
                Debug.DrawLine(nearLowerRight, farUpperLeft);
                Debug.DrawLine(farUpperLeft, nearUpperLeft);

                // Debug draw a triangle coplanar with 'e'
                Debug.DrawLine(nearUpperRight, nearLowerLeft);
                Debug.DrawLine(nearLowerLeft, farUpperRight);
                Debug.DrawLine(farUpperRight, nearUpperRight);
            }
            #endif

            // We're not actually interested in the "distance" to the planes. But the sign
            // of the distance tells us which quadrant the target position is in.
            float dDistance = d.GetDistanceToPoint(targetPosition);
            float eDistance = e.GetDistanceToPoint(targetPosition);

            //     d              e
            //     +\-          +/-
            //       \  -d +e   /
            //        \        /
            //         \      /
            //          \    /
            //           \  /
            //  +d +e     \/
            //            /\    -d -e
            //           /  \
            //          /    \
            //         /      \
            //        /        \
            //       /  +d -e   \
            //     +/-          +\-

            if (dDistance > 0.0f)
            {
                if (eDistance > 0.0f)
                {
                    return FrustumPlanes.Left;
                }
                else
                {
                    return FrustumPlanes.Bottom;
                }
            }
            else
            {
                if (eDistance > 0.0f)
                {
                    return FrustumPlanes.Top;
                }
                else
                {
                    return FrustumPlanes.Right;
                }
            }
        }
Ejemplo n.º 34
0
// methods

    static bool Plane_GetDistanceToPoint__Vector3(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 1)
        {
            UnityEngine.Vector3 arg0    = (UnityEngine.Vector3)JSApi.getVector3S((int)JSApi.GetType.Arg);
            UnityEngine.Plane   argThis = (UnityEngine.Plane)vc.csObj;                JSApi.setSingle((int)JSApi.SetType.Rval, (System.Single)(argThis.GetDistanceToPoint(arg0)));
            JSMgr.changeJSObj(vc.jsObjID, argThis);
        }

        return(true);
    }
Ejemplo n.º 35
0
	protected void CalcScreenToWorldUnits()
	{
		Plane nearPlane = new Plane(renderCamera.transform.forward, renderCamera.transform.position);

		// Determine the world distance between two vertical
		// screen pixels for this camera:
		float dist = nearPlane.GetDistanceToPoint(transform.position);
		localUnitsPerPixel = Vector3.Distance(renderCamera.ScreenToWorldPoint(new Vector3(0, 1, dist)), renderCamera.ScreenToWorldPoint(new Vector3(0, 0, dist)));
	}
Ejemplo n.º 36
0
	public static Vector3 GetScreenToWorld(Vector3 targetWorld, Vector2 screenPos)
	{
		Camera cam = Camera.main;
		if (cam == null)
			return Vector3.zero;
		Plane nearPlane = new Plane(cam.transform.forward, cam.transform.position);
		float dist = nearPlane.GetDistanceToPoint(targetWorld);
		return cam.ScreenToWorldPoint(new Vector3(screenPos.x, screenPos.y, dist));
	}
Ejemplo n.º 37
0
 public Ray GetRay()
 {
     var p = cursor[0].position;
     var pl = new Plane(rot * Vector3.forward, pos);
     p -= rot * Vector3.forward * pl.GetDistanceToPoint(p);
     var r = new Ray(p, rot * new Vector3(0, 0, 1));
     return r;
 }
Ejemplo n.º 38
0
	/// <summary>
	/// Sets the camera to use when calculating
	/// a pixel-perfect character size.
	/// </summary>
	/// <param name="c"></param>
	public void SetCamera(Camera c)
	{
		if (c == null || !m_started)
			return;

		float dist;
		Plane nearPlane = new Plane(c.transform.forward, c.transform.position);

		if (!Application.isPlaying)
		{
			// If the screenSize has never been initialized,
			// or if this is a different camera, get what 
			// values we can get, otherwise just keep the 
			// values we got during our last run:
			if ((screenSize.x == 0 || c != renderCamera) && c.pixelHeight > 100)
			{
				screenSize.x = c.pixelWidth;
				screenSize.y = c.pixelHeight;
			}

			if (screenSize.x == 0)
				return;

			renderCamera = c;

#if SCREEN_SPACE_POSITIONING
			if (positionInScreenSpace)
				PositionOnScreen(screenPos);
#endif

			// Determine the world distance between two vertical
			// screen pixels for this camera:
			dist = nearPlane.GetDistanceToPoint(transform.position);
			worldUnitsPerScreenPixel = Vector3.Distance(c.ScreenToWorldPoint(new Vector3(0, 1, dist)), c.ScreenToWorldPoint(new Vector3(0, 0, dist)));

			if(!hideAtStart)
				CalcSize();
			return;
		}

		screenSize.x = c.pixelWidth;
		screenSize.y = c.pixelHeight;
		renderCamera = c;

#if SCREEN_SPACE_POSITIONING
		if (positionInScreenSpace)
			PositionOnScreen(screenPos);
#endif

		// Determine the world distance between two vertical
		// screen pixels for this camera:
		dist = nearPlane.GetDistanceToPoint(transform.position);
		worldUnitsPerScreenPixel = Vector3.Distance(c.ScreenToWorldPoint(new Vector3(0, 1, dist)), c.ScreenToWorldPoint(new Vector3(0, 0, dist)));

		CalcSize();
	}