public static Matrix4x4 DrawColumns( Matrix4x4 matrix )
 {
     matrix.SetColumn( 0, EditorGUI.Vector4Field( GetRekt(), "", matrix.GetColumn( 0 ) ) );
     matrix.SetColumn( 1, EditorGUI.Vector4Field( GetRekt(), "", matrix.GetColumn( 1 ) ) );
     matrix.SetColumn( 2, EditorGUI.Vector4Field( GetRekt(), "", matrix.GetColumn( 2 ) ) );
     matrix.SetColumn( 3, EditorGUI.Vector4Field( GetRekt(), "", matrix.GetColumn( 3 ) ) );
     return matrix;
 }
Beispiel #2
0
        public static Vector3 Scale(this UnityEngine.Matrix4x4 trsMatrix)
        {
            var scale = new Vector3(
                trsMatrix.GetColumn(0).magnitude,
                trsMatrix.GetColumn(1).magnitude,
                trsMatrix.GetColumn(2).magnitude);

            return(scale);
        }
 public static void DrawAxis(Matrix4x4 frame)
 {
     Vector3 X = frame.GetColumn (0)*AxisSize;
     Vector3 Y = frame.GetColumn (1)*AxisSize;
     Vector3 Z = frame.GetColumn (2)*AxisSize;
     Vector3 pos = frame.GetColumn (3);
     Debug.DrawLine (pos,pos+X,Color.red);
     Debug.DrawLine (pos,pos+Y,Color.green);
     Debug.DrawLine (pos,pos+Z,Color.blue);
 }
Beispiel #4
0
        /// <summary>
        /// Add two matricies together.
        /// </summary>
        /// <param name="lhs">Left-hand side.</param>
        /// <param name="rhs">Right-hand side</param>
        /// <returns>Sum.</returns>
        public static Matrix AddMatrix(this Matrix lhs, Matrix rhs)
        {
            Matrix result = Matrix.identity;

            result.SetColumn(0, lhs.GetColumn(0) + rhs.GetColumn(0));
            result.SetColumn(1, lhs.GetColumn(1) + rhs.GetColumn(1));
            result.SetColumn(2, lhs.GetColumn(2) + rhs.GetColumn(2));
            result.SetColumn(3, lhs.GetColumn(3) + rhs.GetColumn(3));

            return(result);
        }
Beispiel #5
0
        /// <summary>
        /// Subtract one matrix from another.
        /// </summary>
        /// <param name="lhs">Left-hand side.</param>
        /// <param name="rhs">Right-hand side</param>
        /// <returns>Difference.</returns>
        public static Matrix SubtractMatrix(this Matrix lhs, Matrix rhs)
        {
            Matrix result = Matrix.identity;

            result.SetColumn(0, lhs.GetColumn(0) - rhs.GetColumn(0));
            result.SetColumn(1, lhs.GetColumn(1) - rhs.GetColumn(1));
            result.SetColumn(2, lhs.GetColumn(2) - rhs.GetColumn(2));
            result.SetColumn(3, lhs.GetColumn(3) - rhs.GetColumn(3));

            return(result);
        }
    public static Quaternion MatrixToQuaternion(ref Matrix4x4 source)
    {
        // adapted from http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm

        Matrix4x4 matrix = new Matrix4x4();
        matrix.SetColumn(0, source.GetColumn(0));
        matrix.SetColumn(1, source.GetColumn(1));
        matrix.SetColumn(2, source.GetColumn(2));
        matrix.SetColumn(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));

        float trace = Trace(ref matrix);
        if (trace > 0.0f)
        {
            float s = Mathf.Sqrt(trace + 1.0f) * 2.0f; // 4 * qw in Jon's equ
            return new Quaternion(
                (matrix[2,1] - matrix[1,2]) / s,
                (matrix[0,2] - matrix[2,0]) / s,
                (matrix[1,0] - matrix[0,1]) / s,
                0.25f * s);
        }
        else if (matrix[0,0] > matrix[1,1] && matrix[0,0] > matrix[2,2])
        {
            float s = Mathf.Sqrt(1.0f + matrix[0,0] - matrix[1,1] - matrix[2,2]) * 2.0f; // 4 * qx
            return new Quaternion(
                0.25f * s,
                (matrix[0,1] + matrix[1,0]) / s,
                (matrix[0,2] + matrix[2,0]) / s,
                (matrix[2,1] - matrix[1,2]) / s);
        }
        else if (matrix[1,1] > matrix[2,2])
        {
            float s = Mathf.Sqrt(1.0f + matrix[1,1] - matrix[0,0] - matrix[2,2]) * 2.0f; // 4 * qw
            return new Quaternion(
                (matrix[0,1] + matrix[1,0]) / s,
                0.25f * s,
                (matrix[1,2] + matrix[2,1]) / s,
                (matrix[0,2] - matrix[2,0]) / s);
        }
        else
        {
            float s = Mathf.Sqrt(1.0f + matrix[2,2] - matrix[0,0] - matrix[1,1]) * 2.0f; // 4 * qz
            return new Quaternion(
                (matrix[0,2] + matrix[2,0]) / s,
                (matrix[1,2] + matrix[2,1]) / s,
                0.25f * s,
                (matrix[1,0] - matrix[0,1]) / s);
        }
    }
Beispiel #7
0
    void LateUpdate()
    {
        for (int i = 0; i < _trackedTravellers.Count; i++)
        {
            PortalTraveller traveller  = _trackedTravellers[i];
            Transform       travellerT = traveller.transform;
            Matrix4x4       m          = otherPortal.transform.localToWorldMatrix * transform.worldToLocalMatrix * travellerT.localToWorldMatrix;

            Vector3 offsetFromPortal = travellerT.position - transform.position;
            int     portalSide       = Math.Sign(Vector3.Dot(offsetFromPortal, transform.forward));
            int     portalSideOld    = Math.Sign(Vector3.Dot(traveller.prevOffsetFromPortal, transform.forward));
            // Teleport the traveller if it has crossed from one side of the portal to the other
            if (portalSide != portalSideOld)
            {
                traveller.Teleport(transform, otherPortal.transform, m.GetColumn(3), m.rotation);
                // Can't rely on OnTriggerEnter/Exit to be called next frame since it depends on when FixedUpdate runs
                otherPortal.OnTravellerEnterPortal(traveller);
                _trackedTravellers.RemoveAt(i);
                i--;
            }
            else
            {
                traveller.prevOffsetFromPortal = offsetFromPortal;
            }
        }
    }
    private void ApplyTransformation(out UnityEngine.Matrix4x4 Transformation)
    {
        //Calculating Centroids from both coordinate system

        Accord.Math.Vector3 centroidA = CalculateCentroid(UnitytoAccord(ReadFrameLowerLeft), UnitytoAccord(ReadFrameLowerRight), UnitytoAccord(ReadFrameUpperLeft), UnitytoAccord(ReadFrameUpperRight));
        Accord.Math.Vector3 centroidB = CalculateCentroid(UnitytoAccord(FrameLowerLeft), UnitytoAccord(FrameLowerRight), UnitytoAccord(FrameUpperLeft), UnitytoAccord(FrameUpperRight));

        Matrix3x3 H = CovarianceMatrixStep(UnitytoAccord(ReadFrameLowerLeft) - centroidA, UnitytoAccord(FrameLowerLeft) - centroidB)
                      + CovarianceMatrixStep(UnitytoAccord(ReadFrameLowerRight) - centroidA, UnitytoAccord(FrameLowerRight) - centroidB)
                      + CovarianceMatrixStep(UnitytoAccord(ReadFrameUpperLeft) - centroidA, UnitytoAccord(FrameUpperLeft) - centroidB)
                      + CovarianceMatrixStep(UnitytoAccord(ReadFrameUpperRight) - centroidA, UnitytoAccord(FrameUpperRight) - centroidB);
        Matrix3x3 U;

        Accord.Math.Vector3 E;
        Matrix3x3           V;
        Matrix3x3           R;

        H.SVD(out U, out E, out V);

        R = V * U.Transpose();
        Debug.Log("Row  " + R.GetRow(0));
        Debug.Log("Row  " + R.GetRow(1));
        Debug.Log("Row  " + R.GetRow(2));


        if (R.Determinant < 0)
        {
            V.V02 = (-V.V02);
            V.V12 = (-V.V12);
            V.V22 = (-V.V22);
            R     = V * U.Transpose();
            Debug.LogWarning("Reflection case");
        }
        Accord.Math.Vector3 Translation;
        Translation = (NegativeMatrix(R) * centroidA + centroidB);
        Debug.Log("Translation is" + Translation);
        Transformation = UnityEngine.Matrix4x4.identity;
        Transformation = AccordToUnityMatrix(Transformation, R, Translation);

        Debug.Log("Trans" + Transformation.GetRow(0));
        Debug.Log("Trans" + Transformation.GetRow(1));
        Debug.Log("Trans" + Transformation.GetRow(2));
        Debug.Log("Trans" + Transformation.GetRow(3));

        Transformation.SetTRS(AccordtoUnity(Translation), Quaternion.LookRotation(Transformation.GetColumn(1),
                                                                                  Transformation.GetColumn(2)), UnityEngine.Vector3.one);
    }
Beispiel #9
0
 // Get a Transform ofject from a Matrix
 public static void TransformFromMatrix(Matrix4x4 matrix, Transform trans)
 {
     //trans.localRotation = QuaternionFromMatrix(matrix);
     trans.rotation = QuaternionFromMatrix(matrix);
     Vector3 tmp = matrix.GetColumn(3); // uses implicit conversion from Vector4 to Vector3
     // We need to invert the translation on the Y axis
     tmp.y = -tmp.y;
     //trans.localPosition = tmp;
     //tmp.z = 250;
     trans.position = tmp;
 }
 static public int GetColumn(IntPtr l)
 {
     try{
         UnityEngine.Matrix4x4 self = (UnityEngine.Matrix4x4)checkSelf(l);
         System.Int32          a1;
         checkType(l, 2, out a1);
         UnityEngine.Vector4 ret = self.GetColumn(a1);
         pushValue(l, ret);
         return(1);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Beispiel #11
0
    private void UpdateCameraParentPose()
    {
        Interlocked.Exchange(ref updateCameraToWorldMatrix, _cameraToWorldMatrix);

        UnityEngine.Matrix4x4 cameraToWorldMatrix = ConvertFloatArrayToMatrix4x4(updateCameraToWorldMatrix);

        Transform locatableCameraTransform = controller.LocatableCameraRoot.transform;

        // Note: we can't just directly convert the matrix into the rotation/position that Unity expects.
        // We need to convert it. See https://forum.unity.com/threads/locatable-camera-in-unity.398803/
        Vector3    position = cameraToWorldMatrix.MultiplyPoint(Vector3.zero);
        Quaternion rotation = Quaternion.LookRotation(-cameraToWorldMatrix.GetColumn(2), cameraToWorldMatrix.GetColumn(1));

        locatableCameraTransform.position = position;
        locatableCameraTransform.rotation = rotation;
    }
Beispiel #12
0
 static int GetColumn(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         UnityEngine.Matrix4x4 obj = (UnityEngine.Matrix4x4)ToLua.CheckObject(L, 1, typeof(UnityEngine.Matrix4x4));
         int arg0 = (int)LuaDLL.luaL_checknumber(L, 2);
         UnityEngine.Vector4 o = obj.GetColumn(arg0);
         ToLua.Push(L, o);
         ToLua.SetBack(L, 1, obj);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Beispiel #13
0
 /// <summary>
 /// Extract scale from transform matrix.
 /// </summary>
 /// <param name="matrix">Transform matrix. This parameter is passed by reference
 /// to improve performance; no changes will be made to it.</param>
 /// <returns>
 /// Scale vector.
 /// </returns>
 public static Vector3 ExtractScaleFromMatrix(ref Matrix4x4 matrix) {
     Vector3 scale = new Vector3(
         matrix.GetColumn(0).magnitude,
         matrix.GetColumn(1).magnitude,
         matrix.GetColumn(2).magnitude
         );
     if (Vector3.Cross(matrix.GetColumn(0), matrix.GetColumn(1)).normalized != (Vector3)matrix.GetColumn(2).normalized)
     {
         scale.x *= -1;
     }
     return scale;
 }
Beispiel #14
0
    // Function to apply transformation to 4th point/object
    void ApplyTransformation()
    {
        //Calculating Centroids from both coordinate system
        centroidA = (UnitytoAccord(CubeReg.transform.position) + UnitytoAccord(SphereReg.transform.position)
                     + UnitytoAccord(CylinderReg.transform.position)) / 3;
        centroidB = (UnitytoAccord(CubeTransformed.transform.position) + UnitytoAccord(SphereTransformed.transform.position)
                     + UnitytoAccord(CylinderTransformed.transform.position)) / 3;
        //Debug.Log("Centroid A is" + centroidA + " Centroid B is" + centroidB);

        // Calculating Covariance Matrix
        H = CovarianceMatrixStep(UnitytoAccord(CubeReg.transform.position) - centroidA, UnitytoAccord(CubeTransformed.transform.position) - centroidB)
            + CovarianceMatrixStep(UnitytoAccord(SphereReg.transform.position) - centroidA, UnitytoAccord(SphereTransformed.transform.position) - centroidB)
            + CovarianceMatrixStep(UnitytoAccord(CylinderReg.transform.position) - centroidA, UnitytoAccord(CylinderTransformed.transform.position) - centroidB);

        H.SVD(out U, out E, out V);
        R = V * U.Transpose();

        //special reflection case
        if (R.Determinant < 0)
        {
            V.V02 = (-V.V02);
            V.V12 = (-V.V12);
            V.V22 = (-V.V22);
            R     = V * U.Transpose();
            Debug.LogWarning("Reflection case");
        }

        Translation = NegativeMatrix(R) * centroidA + centroidB;
        //Debug.Log("Translation is" + Translation);
        TransformationMatrix = AccordToUnityMatrix(TransformationMatrix, R, Translation);
        //Debug.Log(TransformationMatrix);

        // Transformaiton Matrix for Unity
        TransformationMatrix.SetTRS(AccordtoUnity(Translation), Quaternion.LookRotation(TransformationMatrix.GetColumn(1),
                                                                                        TransformationMatrix.GetColumn(2)), UnityEngine.Vector3.one);

        // Applying Translation and rotation to 4th point/object
        TestObject.transform.position = TransformationMatrix.MultiplyPoint(InitPosition);
        TestObject.transform.rotation = Quaternion.LookRotation(TransformationMatrix.GetColumn(1), TransformationMatrix.GetColumn(2)) * InitQT;
    }
    private GameObject[] cubes; //A list of every cube in the scene

    #endregion Fields

    #region Methods

    /*
     * Used to apply transformations made to one Character to the other.
     *
     * @param transformation Matrix of the transformations applied to the Character calling the function
     * @param smallChar true if called by the small Character, false if called by the big one
     */
    public void Notify(Matrix4x4 transformation, bool smallChar)
    {
        GameObject charToAlter = (smallChar) ? smallCharacter : bigCharacter,
                   otherChar = (smallChar) ? bigCharacter : smallCharacter;
        CharController charController = charToAlter.GetComponent<CharController> (),
                       otherController = otherChar.GetComponent<CharController> ();

        //Extracting infos from the Matrix
        Vector3 translation = transformation.GetColumn (3),
                scale = new Vector3(transformation.GetColumn (0).magnitude,
                                    transformation.GetColumn (1).magnitude,
                                    transformation.GetColumn (2).magnitude);
        Quaternion rotation = Quaternion.LookRotation (transformation.GetColumn(2),
                                                       transformation.GetColumn(1));

        //Reproducing translation
        float dirCoef = (otherController.DistCamToCenter (translation) < otherController.DistCamToCenter (Vector3.zero))
                        ? -1f : 1f;
        translation = charController.charCamera.transform.forward * translation.magnitude * scale.magnitude * dirCoef;
        charController.TranslateBy (translation);

        /*
         * Version using the Matrix4x4 infos only.
         * Translation is okay, but could not get the rotation to work.
         * Solved problem of the angle direction conservation with a custom function,
         * but does not alter the rotation correctly
        Quaternion relativeRotation = Quaternion.Inverse (otherChar.transform.rotation) * charToAlter.transform.rotation;

        translation *= scale.magnitude;
        translation = relativeRotation * translation;
        charController.TranslateBy (translation);

        if (translation.Equals (Vector3.zero)) {
            rotation = relativeRotation * rotation;
            charController.RotateAroundCenter (QuaternionToEulerSigned(rotation));
        }
         */
    }
Beispiel #16
0
 Vector4 multiply(Vector4 point, Matrix4x4 mat)
 {
     Vector4 returnVal = new Vector4();
     Vector4 col0 = mat.GetColumn(0); Vector4 col1 = mat.GetColumn(1); Vector4 col2 = mat.GetColumn(2); Vector4 col3 = mat.GetColumn(3);
     returnVal.x = col0.x*point.x + col0.y*point.y + col0.z*point.z + col0.w*point.w;
     returnVal.y = col1.x*point.x + col1.y*point.y + col1.z*point.z + col1.w*point.w;
     returnVal.z = col2.x*point.x + col2.y*point.y + col2.z*point.z + col2.w*point.w;
     returnVal.w = col3.x*point.x + col3.y*point.y + col3.z*point.z + col3.w*point.w;
     return returnVal;
 }
Beispiel #17
0
    private static void DrawSingleMarker(ARMarker m, Matrix4x4 mat, bool selected) 
    {
        float pattWidth = m.PatternWidth;
		Vector3 origin = mat.GetColumn(3);
		Vector3 right = mat.GetColumn(0);
		Vector3 up = mat.GetColumn(1);

        //float d = selected ? 1.0f : 0.0f;
     
		DrawRectangle(origin, up, right, pattWidth * 0.5f, pattWidth * 0.5f, selected ? MarkerBorderSelected : MarkerBorderUnselected); // Inside border.
		DrawRectangle(origin, up, right, pattWidth, pattWidth, selected ? MarkerBorderSelected : MarkerBorderUnselected); // Edge.
		DrawRectangle(origin, up, right, pattWidth * 1.05f, pattWidth * 1.05f, selected ? MarkerEdgeSelected : MarkerEdgeUnselected); // Highlighting.

        //Gizmos.DrawGUITexture(new Rect(origin.x, origin.y, 20, 20), m.MarkerImage);
		
		float wordUnitSize = pattWidth * 0.02f;
		DrawWord(m.Tag, wordUnitSize, origin - up * (pattWidth * 0.6f + (wordUnitSize * 4)) - right * (pattWidth * 0.525f), up, right * 0.5f);
    }
Beispiel #18
0
 /// <summary>
 /// Vector3 translation from the 4x4 matrix
 /// </summary>
 /// <param name="m">
 /// A 4x4 transformation matrix <see cref="Matrix4x4"/>
 /// </param>
 /// <returns>
 /// A translation vector <see cref="Vector3"/>
 /// </returns>
 public static Vector3 TranslationFromMatrix(Matrix4x4 m)
 {
     Vector4 pos = m.GetColumn(3);
     Vector3 returnPos=new Vector3(pos.x,pos.y,pos.z);
     return returnPos;
 }
        public static Vector3 MatrixToScale(Matrix4x4 m)
        {
            //var xs = m.GetColumn(0);
            //var ys = m.GetColumn(1);
            //var zs = m.GetColumn(2);

            //var sc = new Vector3();
            //sc.x = Vector3.Magnitude(new Vector3(xs.x, xs.y, xs.z));
            //sc.y = Vector3.Magnitude(new Vector3(ys.x, ys.y, ys.z));
            //sc.z = Vector3.Magnitude(new Vector3(zs.x, zs.y, zs.z));

            //return sc;

            return new Vector3(m.GetColumn(0).magnitude, m.GetColumn(1).magnitude, m.GetColumn(2).magnitude);
        }
Beispiel #20
0
 public static void TransformFromMatrix(Matrix4x4 matrix, Transform trans)
 {
     trans.rotation = Util.QuaternionFromMatrix(matrix);
     trans.position = matrix.GetColumn(3); // uses implicit conversion from Vector4 to Vector3
 }
Beispiel #21
0
        /// <summary>
        /// Add a standalone model when not combining.
        /// </summary>
        private static GameObject AddStandaloneModel(
            DaggerfallUnity dfUnity,
            ref ModelData modelData,
            Matrix4x4 matrix,
            Transform parent,
            bool overrideStatic = false,
            bool ignoreCollider = false)
        {
            // Determine static flag
            bool isStatic = (dfUnity.Option_SetStaticFlags && !overrideStatic) ? true : false;

            // Add GameObject
            uint modelID = (uint)modelData.DFMesh.ObjectId;
            GameObject go = GameObjectHelper.CreateDaggerfallMeshGameObject(modelID, parent, isStatic, null, ignoreCollider);
            go.transform.position = matrix.GetColumn(3);
            go.transform.rotation = GameObjectHelper.QuaternionFromMatrix(matrix);

            return go;
        }
 static Quaternion QuaternionFromMatrixColumns(Matrix4x4 m)
 {
     return Quaternion.LookRotation (-m.GetColumn (2), m.GetColumn (1)); // forward, up
 }
Beispiel #23
0
 protected void Set(Matrix4x4 matrix) {
   Matrix = matrix;
   Position = matrix.GetColumn(3);
   Orientation = Quaternion.LookRotation(matrix.GetColumn(2), matrix.GetColumn(1));
 }
Beispiel #24
0
 public static void Matrix2Transform(Transform transform, Matrix4x4 mat)
 {
     transform.position = mat.GetColumn(3);
     transform.rotation = ConvertCoord.QuaternionFromMatrix(mat);
     transform.localScale = Vector3.one;
 }
Beispiel #25
0
    private static Quaternion QuaternionFromMatrix(Matrix4x4 m)
    {
        // Adapted from: http://forum.unity3d.com/threads/is-it-possible-to-get-a-quaternion-from-a-matrix4x4.142325/
        return Quaternion.LookRotation(m.GetColumn(2), m.GetColumn(1));

        // [DEPRECATED]
        /*
        // Adapted from: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm

        Quaternion q = new Quaternion();
        q.w = (float)Mathf.Sqrt(Mathf.Max(0.0f, 1.0f + m.m00 + m.m11 + m.m22)) * 0.5f;
        q.x = (float)Mathf.Sqrt(Mathf.Max(0.0f, 1.0f + m.m00 - m.m11 - m.m22)) * 0.5f;
        q.y = (float)Mathf.Sqrt(Mathf.Max(0.0f, 1.0f - m.m00 + m.m11 - m.m22)) * 0.5f;
        q.z = (float)Mathf.Sqrt(Mathf.Max(0.0f, 1.0f - m.m00 - m.m11 + m.m22)) * 0.5f;

        q.x *= Mathf.Sign(m.m21 - m.m12);
        q.y *= Mathf.Sign(m.m02 - m.m20);
        q.z *= Mathf.Sign(m.m10 - m.m01);

        return q;
        //*/
    }
Beispiel #26
0
 public static Vector3 Translation(this UnityEngine.Matrix4x4 trsMatrix)
 {
     return(trsMatrix.GetColumn(3));
 }
	private static Quaternion QuaternionFromMatrix (Matrix4x4 m)
	{		
		Quaternion q = Quaternion.LookRotation (m.GetColumn (2), m.GetColumn (1));
		return q;
	}
Beispiel #28
0
 //Gets a quaternion from a matrix
 public static Quaternion QuaternionFromMatrix(Matrix4x4 m)
 {
     return Quaternion.LookRotation(m.GetColumn(2), m.GetColumn(1));
 }
    static bool Matrix4x4_GetColumn__Int32(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 1)
        {
            System.Int32          arg0    = (System.Int32)JSApi.getInt32((int)JSApi.GetType.Arg);
            UnityEngine.Matrix4x4 argThis = (UnityEngine.Matrix4x4)vc.csObj;                JSMgr.datax.setObject((int)JSApi.SetType.Rval, argThis.GetColumn(arg0));
            JSMgr.changeJSObj(vc.jsObjID, argThis);
        }

        return(true);
    }
Beispiel #30
0
 /// <summary>
 /// Get quaternion from matrix.
 /// </summary>
 /// <param name="matrix">Input matrix.</param>
 /// <returns>Rotation in quaternion form.</returns>
 public static Quaternion GetRotation(this Matrix matrix)
 {
     return(Quaternion.LookRotation(matrix.GetColumn(2), matrix.GetColumn(1)));
 }
Beispiel #31
0
 public static Matrix4x4 MatrixSlerp(Matrix4x4 a, Matrix4x4 b, float t)
 {
     t = Mathf.Clamp01(t);
     Matrix4x4 m = MatrixFromQuaternion(Quaternion.Slerp(QuaternionFromMatrix(a),QuaternionFromMatrix(b),t));
     m.SetColumn(3,a.GetColumn(3)*(1-t)+b.GetColumn(3)*t);
     m[3,3] = 1;
     return m;
 }
Beispiel #32
0
	public static Quaternion QuaternionFromMatrix(Matrix4x4 m)
	{
		// Trap the case where the matrix passed in has an invalid rotation submatrix.
		if (m.GetColumn(2) == Vector4.zero) {
			ARController.Log("QuaternionFromMatrix got zero matrix.");
			return Quaternion.identity;
		}
		return Quaternion.LookRotation(m.GetColumn(2), m.GetColumn(1));
	}
Beispiel #33
0
 public static void TranslateMatrix(ref Matrix4x4 m, Vector3 position)
 {
     m.SetColumn(3,(Vector3)(m.GetColumn(3))+position);
     m[3,3] = 1;
 }
Beispiel #34
0
    public static void decomposeMatrix(Matrix4x4 matrix, out Vector3 position, out Quaternion rotation,
        out Vector3 scale)
    {
        // Extract new local position
        position = matrix.GetColumn(3);

        // Extract new local rotation
        rotation = Quaternion.LookRotation(
        matrix.GetColumn(2),
        matrix.GetColumn(1)
        );

        // Extract new local scale
        scale = new Vector3(
        matrix.GetColumn(0).magnitude,
        matrix.GetColumn(1).magnitude,
        matrix.GetColumn(2).magnitude
        );
    }
 public static Vector3 MatrixToTranslation(Matrix4x4 m)
 {
     var col = m.GetColumn(3);
     return new Vector3(col.x, col.y, col.z);
 }
Beispiel #36
0
	private static void DrawNFTMarker(ARMarker m, Matrix4x4 mat, bool selected) 
    {
        float pattWidth = m.NFTWidth;
		float pattHeight = m.NFTHeight;
		//Debug.Log("DrawNFTMarker got pattWidth=" + pattWidth + ", pattHeight=" + pattHeight + ".");
		if (pattWidth > 0.0f && pattHeight > 0.0f) {

			float biggestSide = Math.Max(pattWidth, pattHeight);
			Vector3 origin = mat.GetColumn(3);
			Vector3 right = mat.GetColumn(0);
			Vector3 up = mat.GetColumn(1);
			Vector3 centre = origin + right*0.5f*pattWidth + up*0.5f*pattHeight;

        	//float d = selected ? 1.0f : 0.0f;
     
			DrawRectangle(centre, up, right, pattWidth, pattHeight, selected ? MarkerBorderSelected : MarkerBorderUnselected);
			DrawRectangle(centre, up, right, pattWidth + biggestSide*0.05f, pattHeight + biggestSide*0.05f, selected ? MarkerEdgeSelected : MarkerEdgeUnselected);

        	//Gizmos.DrawGUITexture(new Rect(centre.x, centre.y, 20, 20), m.MarkerImage);
		
			float wordUnitSize = pattHeight * 0.02f;
			DrawWord(m.Tag, wordUnitSize, centre - up*(pattHeight*0.6f + (wordUnitSize*4)) - right*pattWidth*0.525f, up, right*0.5f);
		}
	}
	private static void MergeMeshInto(Mesh meshToMerge, Material[] ms, Matrix4x4 transformMatrix, List<Vector3> vertices, List<Vector3> normals, List<Vector2> uv1s, List<Vector2> uv2s, Dictionary<Material, List<int>> subMeshes) {
		if(meshToMerge == null) return;
		int vertexOffset = vertices.Count;
		Vector3[] vs = meshToMerge.vertices;
		
		for(int i=0;i<vs.Length;i++) {
			vs[i] = transformMatrix.MultiplyPoint3x4(vs[i]);
		}
		vertices.AddRange(vs);
		
		Quaternion rotation = Quaternion.LookRotation(transformMatrix.GetColumn(2), transformMatrix.GetColumn(1));
		Vector3[] ns = meshToMerge.normals;
		if(ns!=null && ns.Length>0) {
			for(int i=0;i<ns.Length;i++) ns[i] = rotation * ns[i];
			normals.AddRange(ns);
		}
		
		Vector2[] uvs = meshToMerge.uv;
		if(uvs!=null && uvs.Length>0) uv1s.AddRange(uvs);
		uvs = meshToMerge.uv2;
		if(uvs!=null && uvs.Length>0) uv2s.AddRange(uvs);
		
		for(int i=0;i<ms.Length;i++) {
			if(i<meshToMerge.subMeshCount) {
				int[] ts = meshToMerge.GetTriangles(i);
				if(ts.Length>0) {
					if(ms[i]!=null && !subMeshes.ContainsKey(ms[i])) {
						subMeshes.Add(ms[i], new List<int>());
					}
					List<int> subMesh = subMeshes[ms[i]];
					for(int t=0;t<ts.Length;t++) {
						ts[t] += vertexOffset;
					}
					subMesh.AddRange(ts);
				}
			}
		}
	}
Beispiel #38
0
 public static Quaternion Rotation(this UnityEngine.Matrix4x4 trsMatrix)
 {
     return(Quaternion.LookRotation(trsMatrix.GetColumn(2), trsMatrix.GetColumn(1)));
 }
Beispiel #39
0
		public static Matrix4x4 OrthogonalizeMatrix(Matrix4x4 m)
		{
			Matrix4x4 identity = Matrix4x4.identity;
			Vector3 vector = m.GetColumn(0);
			Vector3 vector2 = m.GetColumn(1);
			Vector3 normalized = m.GetColumn(2).normalized;
			vector = Vector3.Cross(vector2, normalized).normalized;
			vector2 = Vector3.Cross(normalized, vector).normalized;
			identity.SetColumn(0, vector);
			identity.SetColumn(1, vector2);
			identity.SetColumn(2, normalized);
			return identity;
		}
Beispiel #40
0
        private static GameObject AddStandaloneModel(
            DaggerfallUnity dfUnity,
            ref ModelData modelData,
            Matrix4x4 matrix,
            Transform parent)
        {
            uint modelID = (uint)modelData.DFMesh.ObjectId;

            // Add GameObject
            GameObject go = GameObjectHelper.CreateDaggerfallMeshGameObject(modelID, parent, dfUnity.Option_SetStaticFlags);
            go.transform.position = matrix.GetColumn(3);
            go.transform.rotation = GameObjectHelper.QuaternionFromMatrix(matrix);

            // Is this a city gate?
            if (IsCityGate(modelID))
            {
                DaggerfallCityGate gate = go.AddComponent<DaggerfallCityGate>();
                gate.SetOpen(!dfUnity.Option_CloseCityGates);
            }

            return go;
        }
Beispiel #41
0
 //Gets a position from a matrix
 public static Vector3 PositionFromMatrix(Matrix4x4 m)
 {
     Vector4 vector4Position = m.GetColumn(3);
     return new Vector3(vector4Position.x, vector4Position.y, vector4Position.z);
 }
Beispiel #42
0
        public static GameObject Load(string meshPath, float scaleX = 1, float scaleY = 1, float scaleZ = 1)
        {
            if (!File.Exists(meshPath))
            {
                return(null);
            }

            AssimpContext importer = new AssimpContext();
            Scene         scene    = importer.ImportFile(meshPath);

            if (scene == null)
            {
                return(null);
            }

            string parentDir = Directory.GetParent(meshPath).FullName;

            // Materials
            List <UnityEngine.Material> uMaterials = new List <Material>();

            if (scene.HasMaterials)
            {
                foreach (var m in scene.Materials)
                {
                    UnityEngine.Material uMaterial = new UnityEngine.Material(Shader.Find("Standard"));

                    // Albedo
                    if (m.HasColorDiffuse)
                    {
                        Color color = new Color(
                            m.ColorDiffuse.R,
                            m.ColorDiffuse.G,
                            m.ColorDiffuse.B,
                            m.ColorDiffuse.A
                            );
                        uMaterial.color = color;
                    }

                    // Emission
                    if (m.HasColorEmissive)
                    {
                        Color color = new Color(
                            m.ColorEmissive.R,
                            m.ColorEmissive.G,
                            m.ColorEmissive.B,
                            m.ColorEmissive.A
                            );
                        uMaterial.SetColor("_EmissionColor", color);
                        uMaterial.EnableKeyword("_EMISSION");
                    }

                    // Reflectivity
                    if (m.HasReflectivity)
                    {
                        uMaterial.SetFloat("_Glossiness", m.Reflectivity);
                    }

                    // Texture
                    if (m.HasTextureDiffuse)
                    {
                        Texture2D uTexture    = new Texture2D(2, 2);
                        string    texturePath = Path.Combine(parentDir, m.TextureDiffuse.FilePath);

                        byte[] byteArray = File.ReadAllBytes(texturePath);
                        bool   isLoaded  = uTexture.LoadImage(byteArray);
                        if (!isLoaded)
                        {
                            throw new Exception("Cannot find texture file: " + texturePath);
                        }

                        uMaterial.SetTexture("_MainTex", uTexture);
                    }

                    uMaterials.Add(uMaterial);
                }
            }

            // Mesh
            List <MeshMaterialBinding> uMeshAndMats = new List <MeshMaterialBinding>();

            if (scene.HasMeshes)
            {
                foreach (var m in scene.Meshes)
                {
                    List <Vector3> uVertices = new List <Vector3>();
                    List <Vector3> uNormals  = new List <Vector3>();
                    List <Vector2> uUv       = new List <Vector2>();
                    List <int>     uIndices  = new List <int>();

                    // Vertices
                    if (m.HasVertices)
                    {
                        foreach (var v in m.Vertices)
                        {
                            uVertices.Add(new Vector3(-v.X, v.Y, v.Z));
                        }
                    }

                    // Normals
                    if (m.HasNormals)
                    {
                        foreach (var n in m.Normals)
                        {
                            uNormals.Add(new Vector3(-n.X, n.Y, n.Z));
                        }
                    }

                    // Triangles
                    if (m.HasFaces)
                    {
                        foreach (var f in m.Faces)
                        {
                            // Ignore non-triangle faces
                            if (f.IndexCount != 3)
                            {
                                continue;
                            }

                            uIndices.Add(f.Indices[2]);
                            uIndices.Add(f.Indices[1]);
                            uIndices.Add(f.Indices[0]);
                        }
                    }

                    // Uv (texture coordinate)
                    if (m.HasTextureCoords(0))
                    {
                        foreach (var uv in m.TextureCoordinateChannels[0])
                        {
                            uUv.Add(new Vector2(uv.X, uv.Y));
                        }
                    }

                    UnityEngine.Mesh uMesh = new UnityEngine.Mesh();
                    uMesh.vertices  = uVertices.ToArray();
                    uMesh.normals   = uNormals.ToArray();
                    uMesh.triangles = uIndices.ToArray();
                    uMesh.uv        = uUv.ToArray();

                    uMeshAndMats.Add(new MeshMaterialBinding(m.Name, uMesh, uMaterials[m.MaterialIndex]));
                }
            }

            // Create GameObjects from nodes
            GameObject NodeToGameObject(Node node)
            {
                GameObject uOb = new GameObject(node.Name);

                // Set Mesh
                if (node.HasMeshes)
                {
                    foreach (var mIdx in node.MeshIndices)
                    {
                        var uMeshAndMat = uMeshAndMats[mIdx];

                        GameObject uSubOb = new GameObject(uMeshAndMat.MeshName);
                        uSubOb.AddComponent <MeshFilter>();
                        uSubOb.AddComponent <MeshRenderer>();
                        uSubOb.AddComponent <MeshCollider>();

                        uSubOb.GetComponent <MeshFilter>().mesh       = uMeshAndMat.Mesh;
                        uSubOb.GetComponent <MeshRenderer>().material = uMeshAndMat.Material;
                        uSubOb.transform.SetParent(uOb.transform, true);
                        uSubOb.transform.localScale = new Vector3(scaleX, scaleY, scaleZ);
                    }
                }

                // Transform
                UnityEngine.Matrix4x4 uTransform = new UnityEngine.Matrix4x4();
                uTransform.SetColumn(0, new Vector4(
                                         node.Transform.A1,
                                         node.Transform.B1,
                                         node.Transform.C1,
                                         node.Transform.D1
                                         ));
                uTransform.SetColumn(1, new Vector4(
                                         node.Transform.A2,
                                         node.Transform.B2,
                                         node.Transform.C2,
                                         node.Transform.D2
                                         ));
                uTransform.SetColumn(2, new Vector4(
                                         node.Transform.A3,
                                         node.Transform.B3,
                                         node.Transform.C3,
                                         node.Transform.D3
                                         ));
                uTransform.SetColumn(3, new Vector4(
                                         node.Transform.A4,
                                         node.Transform.B4,
                                         node.Transform.C4,
                                         node.Transform.D4
                                         ));

                var euler = uTransform.rotation.eulerAngles;

                uOb.transform.localPosition = uTransform.GetColumn(3);
                uOb.transform.localRotation = UnityEngine.Quaternion.Euler(euler.x, -euler.y, euler.z);
//                uOb.transform.localRotation = UnityEngine.Quaternion.LookRotation(uTransform.GetColumn(2), uTransform.GetColumn(1));

                if (node.HasChildren)
                {
                    foreach (var cn in node.Children)
                    {
                        var uObChild = NodeToGameObject(cn);
                        uObChild.transform.SetParent(uOb.transform, false);
                    }
                }

                return(uOb);
            }

            return(NodeToGameObject(scene.RootNode));;
        }
    // convert the matrix to quaternion, taking care of the mirroring
    private Quaternion ConvertMatrixToQuat(Matrix4x4 mOrient, int joint, bool flip)
    {
        Vector4 vZ = mOrient.GetColumn(2);
        Vector4 vY = mOrient.GetColumn(1);

        if(!flip)
        {
            vZ.y = -vZ.y;
            vY.x = -vY.x;
            vY.z = -vY.z;
        }
        else
        {
            vZ.x = -vZ.x;
            vZ.y = -vZ.y;
            vY.z = -vY.z;
        }

        if(vZ.x != 0.0f || vZ.y != 0.0f || vZ.z != 0.0f)
            return Quaternion.LookRotation(vZ, vY);
        else
            return Quaternion.identity;
    }
Beispiel #44
0
	public static Vector3 PositionFromMatrix(Matrix4x4 m)
	{
	    return m.GetColumn(3);
	}