Ejemplo n.º 1
0
        protected override async Task LoadContent()
        {
            material = new Material();

            string vsSource = @"
                attribute vec4 aPosition;
                attribute vec2 aTexture;
                attribute vec4 aColor;
                attribute float aSamplerIndex;

                uniform mat4 uProjectionMatrix;

                varying mediump vec4 vColor;
                varying highp vec2 vTextureCoord;
                varying mediump float vSamplerIndex;

                void main(void) {
                    gl_Position = uProjectionMatrix * aPosition;
                    vTextureCoord = aTexture;
                    vColor = aColor;
                    vSamplerIndex = aSamplerIndex;
                }";

            string fsSource = @"
                varying highp vec2 vTextureCoord;
                varying mediump vec4 vColor;
                varying mediump float vSamplerIndex;

                uniform sampler2D uSampler0;
                uniform sampler2D uSampler1;
                uniform sampler2D uSampler2;
                uniform sampler2D uSampler3;
                uniform sampler2D uSampler4;
                uniform sampler2D uSampler5;
                uniform sampler2D uSampler6;
                uniform sampler2D uSampler7;
                uniform sampler2D uSampler8;
                uniform sampler2D uSampler9;

                void main(void) {

                    mediump vec4 color;
                
                    if(vSamplerIndex > -0.5 && vSamplerIndex < 0.5)
                    {
                        color = texture2D(uSampler0, vTextureCoord);
                    }
                    if(vSamplerIndex > 0.5 && vSamplerIndex < 1.5)
                    {
                        color = texture2D(uSampler1, vTextureCoord);
                    }
                    if(vSamplerIndex > 1.5 && vSamplerIndex < 2.5)
                    {
                        color = texture2D(uSampler2, vTextureCoord);
                    }
                    if(vSamplerIndex > 2.5 && vSamplerIndex < 3.5)
                    {
                        color = texture2D(uSampler3, vTextureCoord);
                    }
                    if(vSamplerIndex > 3.5 && vSamplerIndex < 4.5)
                    {
                        color = texture2D(uSampler4, vTextureCoord);
                    }
                    if(vSamplerIndex > 4.5 && vSamplerIndex < 5.5)
                    {
                        color = texture2D(uSampler5, vTextureCoord);
                    }
                    if(vSamplerIndex > 5.5 && vSamplerIndex < 6.5)
                    {
                        color = texture2D(uSampler6, vTextureCoord);
                    }
                    if(vSamplerIndex > 6.5 && vSamplerIndex < 7.5)
                    {
                        color = texture2D(uSampler7, vTextureCoord);
                    }
                    if(vSamplerIndex > 7.5 && vSamplerIndex < 8.5)
                    {
                        color = texture2D(uSampler8, vTextureCoord);
                    }
                    if(vSamplerIndex > 8.5 && vSamplerIndex < 9.5)
                    {
                        color = texture2D(uSampler9, vTextureCoord);
                    }
                        
                    gl_FragColor = color * vColor;
                }";

            var vertexShader   = Context.CompileShader(ShaderType.VERTEX_SHADER, vsSource);
            var fragmentShader = Context.CompileShader(ShaderType.FRAGMENT_SHADER, fsSource);

            material.Program = Context.CreateShaderProgram();
            material.Program.Attach(vertexShader);
            material.Program.Attach(fragmentShader);

            material.Program.Link();

            Texture1 = await Context.LoadTextureAsync("res/birb.jpg");

            Texture2 = await Context.LoadTextureAsync("res/nyan.png");

            material.Textures = new[] { Texture1 };

            // material.Int32Uniforms = new Dictionary<string,int>()
            // {
            //     { "uSampler0", 0 },
            //     { "uSampler1", 1 },
            //     { "uSampler2", 2 },
            //     { "uSampler3", 3 },
            //     { "uSampler4", 4 },
            //     { "uSampler5", 5 },
            //     { "uSampler6", 6 },
            //     { "uSampler7", 7 },
            //     { "uSampler8", 8 },
            //     { "uSampler9", 9 }
            // };

            material.Matrix4Uniforms = new Dictionary <string, Matrix4>()
            {
                {
                    "uProjectionMatrix",
                    Matrix4.Orthogonal(-Context.Width * 0.5f, -Context.Height * 0.5f,
                                       Context.Width * 0.5f, Context.Height * 0.5f, -1, 1)
                }
            };

            drawables = new SpriteDrawable[benchmarkElementCount];
            Random random = new Random();

            for (int i = 0; i < benchmarkElementCount; i++)
            {
                drawables[i] = new SpriteDrawable()
                {
                    Color           = new Color(1, 1, 1, 1),
                    Size            = new Vector2(100, 100),
                    SourceRectangle = null,
                    Texture         = Texture1,
                    Transform       = TransformUtils.MakeTransform(
                        Vector3.Zero,
                        new Vector3(
                            (float)random.NextDouble() * Context.Width - Context.Width * 0.5f,
                            (float)random.NextDouble() * Context.Height - Context.Height * 0.5f,
                            0
                            ),
                        new Vector3(0, 0, (float)(random.NextDouble() * Math.PI)),
                        Vector3.One
                        )
                };
            }

            SpriteManager = new SpriteManager();
        }
Ejemplo n.º 2
0
        public virtual void UpdateTransform()
        {
            Matrix4F xform = TransformUtils.CalcTransform(this);

            SetAttribute(Schema.gameObjectType.transformAttribute, xform.ToArray());
        }
Ejemplo n.º 3
0
        private void RenderProperties(IEnumerable <object> objects, bool renderCaption, bool renderBound, bool renderPivot)
        {
            bool renderAny = renderCaption || renderBound || renderPivot;

            if (renderAny == false)
            {
                return;
            }

            Util3D.RenderFlag = BasicRendererFlags.WireFrame;
            Matrix4F vp = Camera.ViewMatrix * Camera.ProjectionMatrix;

            foreach (object obj in objects)
            {
                IBoundable bnode = obj.As <IBoundable>();
                if (bnode == null || bnode.BoundingBox.IsEmpty || obj.Is <IGameObjectFolder>())
                {
                    continue;
                }

                INameable      nnode = obj.As <INameable>();
                ITransformable trans = obj.As <ITransformable>();

                if (renderBound)
                {
                    Util3D.DrawAABB(bnode.BoundingBox);
                }
                if (renderCaption && nnode != null)
                {
                    Vec3F topCenter = bnode.BoundingBox.Center;
                    topCenter.Y = bnode.BoundingBox.Max.Y;
                    Point pt = Project(vp, topCenter);
                    GameEngine.DrawText2D(nnode.Name, Util3D.CaptionFont, pt.X, pt.Y, Color.White);
                }
            }

            if (renderPivot)
            {
                Util3D.RenderFlag = BasicRendererFlags.WireFrame
                                    | BasicRendererFlags.DisableDepthTest;

                // create few temp matrics to
                Matrix4F toWorld  = new Matrix4F();
                Matrix4F PV       = new Matrix4F();
                Matrix4F sc       = new Matrix4F();
                Matrix4F bl       = new Matrix4F();
                Matrix4F recXform = new Matrix4F();
                foreach (object obj in objects)
                {
                    ITransformable trans = obj.As <ITransformable>();
                    IBoundable     bnode = obj.As <IBoundable>();
                    if (trans == null || bnode == null || bnode.BoundingBox.IsEmpty || obj.Is <IGameObjectFolder>())
                    {
                        continue;
                    }

                    Path <DomNode> path = new Path <DomNode>(trans.Cast <DomNode>().GetPath());
                    toWorld.Set(Vec3F.ZeroVector);
                    TransformUtils.CalcPathTransform(toWorld, path, path.Count - 1);

                    // Offset by pivot
                    PV.Set(trans.Pivot);
                    toWorld.Mul(PV, toWorld);
                    Vec3F pos = toWorld.Translation;

                    float s;
                    Util.CalcAxisLengths(Camera, pos, out s);
                    s /= 12.0f;
                    sc.Scale(s);
                    Util.CreateBillboard(bl, pos, Camera.WorldEye, Camera.Up, Camera.LookAt);

                    Matrix4F.Multiply(sc, bl, recXform);

                    Util3D.DrawPivot(recXform, Color.Yellow);
                }
            }
        }
Ejemplo n.º 4
0
 private void RegenerateLocalToWorldMatrix()
 {
     _localToWorldMatrix = TransformUtils.GetLocalToWorldMatrix(_position, _rotation, _scale);
 }
Ejemplo n.º 5
0
 public static IEnumerator MoveTo(this Transform t, Vector3 to, float duration)
 {
     return(TransformUtils.MoveTo(t.position, to, duration, (newPosition) => t.position = newPosition));
 }
Ejemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="duct"></param>
        /// <param name="point"></param>
        /// <param name="damperType"></param>
        /// <param name="damperWidth"></param>
        /// <param name="damperHeight"></param>
        public static void InsertDamper(
            Element duct,
            Point point,
            FamilyType damperType,
            string damperWidth  = "Duct Width",
            string damperHeight = "Duct Height")
        {
            if (!(duct.InternalElement is Autodesk.Revit.DB.Mechanical.Duct duct1))
            {
                throw new ArgumentNullException(nameof(duct));
            }
            if (point == null)
            {
                throw new ArgumentNullException(nameof(point));
            }
            if (damperType == null)
            {
                throw new ArgumentNullException(nameof(damperType));
            }

            if (!(duct1.Location is Autodesk.Revit.DB.LocationCurve location))
            {
                throw new ArgumentException("Duct is not curve based.");
            }

            var doc    = duct1.Document;
            var xyz    = point.ToRevitType();
            var curve  = location.Curve;
            var result = curve.Project(xyz);
            var pt     = result.XYZPoint;
            var symbol = damperType.InternalElement as Autodesk.Revit.DB.FamilySymbol;

            TransactionManager.Instance.EnsureInTransaction(doc);

            // (Konrad) Create new Damper instance and split duct into two.
            var id = Autodesk.Revit.DB.Mechanical.MechanicalUtils.BreakCurve(doc, duct1.Id, pt);

            if (!(doc.GetElement(id) is Autodesk.Revit.DB.Mechanical.Duct duct2))
            {
                throw new ArgumentException("Failed to split Duct.");
            }

            var fi = doc.Create.NewFamilyInstance(pt, symbol, duct1, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

            doc.Regenerate();

            // (Konrad) Rotate Damper.
            var start         = curve.GetEndPoint(0).ToPoint();
            var end           = curve.GetEndPoint(1).ToPoint();
            var direction     = Vector.ByTwoPoints(start, end);
            var up            = Vector.ZAxis();
            var perpendicular = direction.Cross(up);
            var cs            = CoordinateSystem.ByOriginVectors(pt.ToPoint(), direction, perpendicular);
            var transform     = cs.ToTransform();

            TransformUtils.ExtractEularAnglesFromTransform(transform, out var newRotationAngles);
            var rotation     = ConvertEularToAngleDegrees(newRotationAngles.FirstOrDefault());
            var oldTransform = fi.GetTransform();

            TransformUtils.ExtractEularAnglesFromTransform(oldTransform, out var oldRotationAngles);
            var newRotationAngle = rotation * Math.PI / 180;
            var rotateAngle      = newRotationAngle - oldRotationAngles.FirstOrDefault();
            var axis             = Autodesk.Revit.DB.Line.CreateUnbound(oldTransform.Origin, oldTransform.BasisZ);

            Autodesk.Revit.DB.ElementTransformUtils.RotateElement(doc, fi.Id, axis, -rotateAngle);

            // (Konrad) Set Damper Width/Height to match Duct.
            var sourceWidth  = duct1.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.RBS_CURVE_WIDTH_PARAM).AsDouble();
            var sourceHeight = duct1.get_Parameter(Autodesk.Revit.DB.BuiltInParameter.RBS_CURVE_HEIGHT_PARAM).AsDouble();

            fi.GetParameters(damperWidth).FirstOrDefault()?.Set(sourceWidth);
            fi.GetParameters(damperHeight).FirstOrDefault()?.Set(sourceHeight);

            // (Konrad) Connect Damper to Ducts.
            var c1      = FindClosest(duct1.ConnectorManager.Connectors, xyz); // duct1 endpoint
            var c1Other = FindOther(duct1.ConnectorManager.Connectors, c1);
            var c1A     = FindClosest(fi.MEPModel.ConnectorManager.Connectors, c1Other);

            c1.ConnectTo(c1A);

            var c2      = FindClosest(duct2.ConnectorManager.Connectors, xyz); // duct2 endpoint
            var c2Other = FindOther(duct2.ConnectorManager.Connectors, c2);
            var c2A     = FindClosest(fi.MEPModel.ConnectorManager.Connectors, c2Other);

            c2.ConnectTo(c2A);

            TransactionManager.Instance.TransactionTaskDone();
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Appends a centered skew matrix from the give angles in radians.
 /// </summary>
 /// <param name="radiansX">The X angle, in radians.</param>
 /// <param name="radiansY">The Y angle, in radians.</param>
 /// <returns>The <see cref="AffineTransformBuilder"/>.</returns>
 public AffineTransformBuilder AppendSkewRadians(float radiansX, float radiansY)
 => this.Append(size => TransformUtils.CreateSkewMatrixRadians(radiansX, radiansY, size));
Ejemplo n.º 8
0
 private IEnumerable <ITargetGroup> GetAllTargetGroups()
 {
     return(TransformUtils.GetComponentsInDescendants <TargetGroupBase>(transform, true)
            .OfType <ITargetGroup>());
 }
Ejemplo n.º 9
0
    private Transform CreatePlatform(int platformNumber, int positionNumber, int moveTime, int col, int row, int startHeight)
    {
        // Create the platform if it doesn't exist yet.
        Transform platform;

        if (!Platforms.TryGetValue(platformNumber, out platform))
        {
            platform = _assetPool.SpawnTransform(Constants.TAG_PLATFORM);
            platform.GetComponent <Collider>().material = noFrictionMaterial;
            platform.name = CreateUniqueItemName(Constants.TAG_PLATFORM);

            var controller = platform.GetComponent <PlatformController>();
            controller.Positions            = new List <Vector3>();
            controller.SecondsToReachTarget = new List <int>();
            Platforms[platformNumber]       = platform;
        }

        // Determine where this point falls on the grid.
        var pointCoordinates   = new Vector3(col, startHeight, row);
        var platformDimensions = platform.localScale;
        var platformPosition   = TransformUtils.GetLocalPositionFromGridCoordinates(pointCoordinates, platformDimensions);

        // Add the position to PlatformPositions
        List <Vector3> positions;

        if (!PlatformPositions.TryGetValue(platformNumber, out positions))
        {
            positions = new List <Vector3>();
        }

        while (positionNumber >= positions.Count)
        {
            positions.Add(Vector3.zero);
        }
        positions[positionNumber]         = platformPosition;
        PlatformPositions[platformNumber] = positions;

        // Add the move time to PlatformMoveTimes
        List <int> moveTimes;

        if (!PlatformMoveTimes.TryGetValue(platformNumber, out moveTimes))
        {
            moveTimes = new List <int>();
        }

        while (positionNumber >= moveTimes.Count)
        {
            moveTimes.Add(0);
        }
        moveTimes[positionNumber]         = moveTime;
        PlatformMoveTimes[platformNumber] = moveTimes;

        // Set the platform start location
        if (positionNumber == 0)
        {
            platform.position         = platformPosition;
            Platforms[platformNumber] = platform;
        }

        return(platform);
    }
Ejemplo n.º 10
0
    public override VisualElement CreateInspectorGUI()
    {
        var visualTree = AssetDatabase.LoadAssetAtPath <VisualTreeAsset>("Assets/Editor/CustomTransformInspector.uxml");

        root = visualTree.CloneTree();

        var styleSheet = AssetDatabase.LoadAssetAtPath <StyleSheet>("Assets/Editor/CustomTransformInspector.uss");

        root.styleSheets.Add(styleSheet);

        Vector3Field localPosField   = root.Q <Vector3Field>("Vector3Position");
        Vector3Field localRotField   = root.Q <Vector3Field>("Vector3Rotation");
        Vector3Field localScaleField = root.Q <Vector3Field>("Vector3Scale");

        Vector3Field worldPosField   = root.Q <Vector3Field>("Vector3WorldPosition");
        Vector3Field worldRotField   = root.Q <Vector3Field>("Vector3WorldRotation");
        Vector3Field worldScaleField = root.Q <Vector3Field>("Vector3WorldScale");

        localPosField.value   = m_transform.localPosition;
        localRotField.value   = TransformUtils.GetInspectorRotation(m_transform);
        localScaleField.value = m_transform.localScale;

        worldPosField.value   = m_transform.position;
        worldScaleField.value = m_transform.lossyScale;
        worldRotField.value   = GetWorldRotation();

        worldPosField.SetEnabled(false);
        worldRotField.SetEnabled(false);
        worldScaleField.SetEnabled(false);


        localPosField.RegisterValueChangedCallback(evt =>
        {
            Undo.RecordObject(m_transform, m_transform.name);
            m_transform.localPosition = localPosField.value;
        });
        localRotField.RegisterValueChangedCallback(evt =>
        {
            Undo.RecordObject(m_transform, m_transform.name);
            TransformUtils.SetInspectorRotation(m_transform, localRotField.value);
        });
        localScaleField.RegisterValueChangedCallback(evt =>
        {
            Undo.RecordObject(m_transform, m_transform.name);
            m_transform.localScale = localScaleField.value;
        });

        //전체 리셋
        root.Q <Button>("LocalReset").RegisterCallback <MouseUpEvent>(evt =>
        {
            Undo.RecordObject(m_transform, m_transform.name);
            ResetPositionField(localPosField);
            ResetRotationField(localRotField);
            ResetScaleField(localScaleField);
        });

        //개별 리셋
        root.Q <Button>("RB").RegisterCallback <MouseUpEvent>(evt =>
        {
            Undo.RecordObject(m_transform, m_transform.name);
            ResetPositionField(localPosField);
        });
        root.Q <Button>("GB").RegisterCallback <MouseUpEvent>(evt =>
        {
            Undo.RecordObject(m_transform, m_transform.name);
            ResetRotationField(localRotField);
        });
        root.Q <Button>("BB").RegisterCallback <MouseUpEvent>(evt =>
        {
            Undo.RecordObject(m_transform, m_transform.name);
            ResetScaleField(localScaleField);
        });

        // 스케쥴러
        var scheduledAction = root.schedule.Execute(() =>
        {
            localPosField.value   = m_transform.localPosition;
            localRotField.value   = TransformUtils.GetInspectorRotation(m_transform);
            localScaleField.value = m_transform.localScale;

            worldPosField.value   = m_transform.position;
            worldScaleField.value = m_transform.lossyScale;
            worldRotField.value   = GetWorldRotation();
        });

        scheduledAction.Every(100);
        return(root);
    }
Ejemplo n.º 11
0
        /// <summary>
        /// Computes transformation matrix from transformation related atrributes.</summary>
        public void ComputeTransform()
        {
            Matrix4F xform = TransformUtils.CalcTransform(m_transformable);

            SetAttribute(Schema.gameObjectType.transformAttribute, xform.ToArray());
        }
Ejemplo n.º 12
0
        protected virtual void OnSceneGUI()
        {
            TransformController transformController   = (TransformController)target;
            Vector3             orientationCorrection = new Vector3(0, 0, 0);

            switch (transformController.FreeDOF)
            {
            case 4:
                angularLimitHandle.xMin           = transformController.LockMin;
                angularLimitHandle.xMax           = transformController.LockMax;
                angularLimitHandle.xRange         = new Vector2(-360, 360);
                angularLimitHandle.yMotion        = 0;
                angularLimitHandle.zMotion        = 0;
                transformController.initialOffset = TransformUtils.GetInspectorRotation(transformController.transform).x;
                break;

            case 5:
                angularLimitHandle.yMin           = transformController.LockMin;
                angularLimitHandle.yMax           = transformController.LockMax;
                angularLimitHandle.yRange         = new Vector2(-360, 360);
                angularLimitHandle.xMotion        = 0;
                angularLimitHandle.zMotion        = 0;
                orientationCorrection             = new Vector3(0, 90, 0);
                transformController.initialOffset = TransformUtils.GetInspectorRotation(transformController.transform).y;
                break;

            case 6:
                angularLimitHandle.zMin           = transformController.LockMin;
                angularLimitHandle.zMax           = transformController.LockMax;
                angularLimitHandle.zRange         = new Vector2(-360, 360);
                angularLimitHandle.xMotion        = 0;
                angularLimitHandle.yMotion        = 0;
                orientationCorrection             = new Vector3(0, 180, 90);
                transformController.initialOffset = TransformUtils.GetInspectorRotation(transformController.transform).z;
                break;

            default:
                // this is just for rotation (hinge) joints, if not one of these then return
                return;
            }

            // set the handle matrix to match the object's position/rotation with a uniform scale

            Matrix4x4 handleMatrix = Matrix4x4.TRS(
                transformController.transform.position,
                transformController.transform.parent.gameObject.transform.rotation * Quaternion.Euler(orientationCorrection),
                Vector3.one
                );

            EditorGUI.BeginChangeCheck();

            using (new Handles.DrawingScope(handleMatrix))
            {
                // maintain a constant screen-space size for the handle's radius based on the origin of the handle matrix
                // add 30% to avoid the handle getting lost behind the transform
                angularLimitHandle.radius = HandleUtility.GetHandleSize(Vector3.zero) * 1.3f;

                // draw the handle
                EditorGUI.BeginChangeCheck();
                angularLimitHandle.DrawHandle();
                if (EditorGUI.EndChangeCheck())
                {
                    // undone/redo
                    Undo.RecordObject(transformController, "Change transform lock angles");

                    // update JointController script
                    float[] validated = new float[2] {
                        0, 0
                    };
                    switch (transformController.FreeDOF)
                    {
                    case 4:
                        validated = LockCheckAngle(angularLimitHandle.xMin, angularLimitHandle.xMax);
                        break;

                    case 5:
                        validated = LockCheckAngle(angularLimitHandle.yMin, angularLimitHandle.yMax);
                        break;

                    case 6:
                        validated = LockCheckAngle(angularLimitHandle.zMin, angularLimitHandle.zMax);
                        break;

                    default:
                        // this is just for rotation (hinge) joints, if not one of these then do nothing
                        break;
                    }
                    transformController.LockMin = validated[0];
                    transformController.LockMax = validated[1];
                }
            }
        }
Ejemplo n.º 13
0
        private void DrawRotation()
        {
            GUILayout.BeginHorizontal();
            {
                bool reset = GUILayout.Button("R", GUILayout.Width(20f));

                // Vector3 visible = (serializedObject.targetObject as Transform).localEulerAngles;
                Vector3 visible = TransformUtils.GetInspectorRotation(serializedObject.targetObject as Transform);

                visible.x = WrapAngle(visible.x);
                visible.y = WrapAngle(visible.y);
                visible.z = WrapAngle(visible.z);

                Axes changed = CheckDifference(mRot);
                Axes altered = Axes.None;

                GUILayoutOption opt = GUILayout.MinWidth(30f);

                if (FloatField("X", ref visible.x, (changed & Axes.X) != 0, false, opt))
                {
                    altered |= Axes.X;
                }
                if (FloatField("Y", ref visible.y, (changed & Axes.Y) != 0, false, opt))
                {
                    altered |= Axes.Y;
                }
                if (FloatField("Z", ref visible.z, (changed & Axes.Z) != 0, false, opt))
                {
                    altered |= Axes.Z;
                }

                if (reset)
                {
                    mRot.quaternionValue = Quaternion.identity;
                }
                else if (altered != Axes.None)
                {
                    RegisterUndo("Change Rotation", serializedObject.targetObjects);

                    foreach (Object obj in serializedObject.targetObjects)
                    {
                        Transform t = obj as Transform;
                        //Vector3 v = t.localEulerAngles;
                        Vector3 v = TransformUtils.GetInspectorRotation(t);

                        if ((altered & Axes.X) != 0)
                        {
                            v.x = visible.x;
                        }
                        if ((altered & Axes.Y) != 0)
                        {
                            v.y = visible.y;
                        }
                        if ((altered & Axes.Z) != 0)
                        {
                            v.z = visible.z;
                        }

                        //t.localEulerAngles = v;
                        TransformUtils.SetInspectorRotation(t, v);
                    }
                }
            }
            GUILayout.EndHorizontal();
        }
        protected override void OnPreviewSettingGUI()
        {
            _showTargetSetting = EditorGUILayout.Foldout(_showTargetSetting, "Target");

            if (_showTargetSetting)
            {
                EditorGUI.indentLevel++;

                Transform targetTF    = TransformUtils.GetTransformByPath(_tht.targetPath);
                Transform newTargetTF = EditorGUILayout.ObjectField(new GUIContent("Target in Scene", "The target transform in current scene, this will be converted and saved as path string."), targetTF, typeof(Transform), true) as Transform;
                string    targetPath  = newTargetTF.ToPath();
                if (targetTF == null && !string.IsNullOrEmpty(_tht.targetPath))
                {
                    GUI.contentColor = Color.red;
                }
                string customTargetPath = EditorGUILayout.TextField(new GUIContent(string.IsNullOrEmpty(_tht.targetPath) ? "Enter Manually" : (targetTF == null ? "Not Found" : " "), "Manually set the target path, use this for dynamically-loaded prefab."), _tht.targetPath);
                if (customTargetPath != _tht.targetPath)
                {
                    EditorUtility.SetDirty(_tht);
                    Undo.RegisterCompleteObjectUndo(_tht, "Reassign Custom Target Path");
                    _tht.targetPath = customTargetPath;
                    targetPath      = customTargetPath;
                }
                if (targetTF == null && !string.IsNullOrEmpty(_tht.targetPath))
                {
                    GUI.contentColor = Color.white;
                }
                if ((string.IsNullOrEmpty(_tht.targetPath) || newTargetTF != null) && targetPath != _tht.targetPath)
                {
                    EditorUtility.SetDirty(_tht);
                    Undo.RegisterCompleteObjectUndo(_tht, "Reassign Target Path");
                    _tht.targetPath = targetPath;
                }

                if (!string.IsNullOrEmpty(_tht.targetPath))
                {
                    bool skipIfTargetInactive = EditorGUILayout.Toggle(new GUIContent("Skip If Target Inactive", "Mark this task complete if finding the target inactive."), _tht.skipIfTargetInactive);
                    if (skipIfTargetInactive != _tht.skipIfTargetInactive)
                    {
                        EditorUtility.SetDirty(_tht);
                        Undo.RegisterCompleteObjectUndo(_tht, "Reassign Skip If Target Inactive");
                        _tht.skipIfTargetInactive = skipIfTargetInactive;
                    }
                    bool cloneTarget = EditorGUILayout.Toggle(new GUIContent("Clone Target", "Clone a target and keep it in original place, use this on scroll slot etc."), _tht.cloneTarget);
                    if (cloneTarget != _tht.cloneTarget)
                    {
                        EditorUtility.SetDirty(_tht);
                        Undo.RegisterCompleteObjectUndo(_tht, "Reassign Clone Target");
                        _tht.cloneTarget = cloneTarget;
                    }

                    if (cloneTarget)
                    {
                        bool targetFollowCloneOnUpdate = EditorGUILayout.Toggle(new GUIContent("Target Follow Clone On Update", "Target follows the clone in update, use this on scroll slot etc."), _tht.targetFollowCloneOnUpdate);
                        if (targetFollowCloneOnUpdate != _tht.targetFollowCloneOnUpdate)
                        {
                            EditorUtility.SetDirty(_tht);
                            Undo.RegisterCompleteObjectUndo(_tht, "Reassign Target Follow Clone On Update");
                            _tht.targetFollowCloneOnUpdate = targetFollowCloneOnUpdate;
                        }
                        bool targetCanCatchRaycast = EditorGUILayout.Toggle(new GUIContent("Target Catch Raycast", "Toggle the target raycast, use this if you want tto turn on/off the target's interaction."), _tht.targetCanCatchRaycast);
                        if (targetCanCatchRaycast != _tht.targetCanCatchRaycast)
                        {
                            EditorUtility.SetDirty(_tht);
                            Undo.RegisterCompleteObjectUndo(_tht, "Reassign Target Can Catch Raycast");
                            _tht.targetCanCatchRaycast = targetCanCatchRaycast;
                        }
                        bool putCloneToTutorialPanelInstead = EditorGUILayout.Toggle(new GUIContent("Put Clone To Tutorial Panel Instead", "By default, put original target to tutorial panel, turn this on if you want the opposite."), _tht.putCloneToTutorialPanelInstead);
                        if (putCloneToTutorialPanelInstead != _tht.putCloneToTutorialPanelInstead)
                        {
                            EditorUtility.SetDirty(_tht);
                            Undo.RegisterCompleteObjectUndo(_tht, "Reassign Put Clone To Tutorial Panel Instead");
                            _tht.putCloneToTutorialPanelInstead = putCloneToTutorialPanelInstead;
                        }
                    }
                }

                EditorGUI.indentLevel--;
            }

            base.OnPreviewSettingGUI();
        }
Ejemplo n.º 15
0
        public void CappingModeNoneWithConcaveSection()
        {
            var sketch1 = Sketch.Create();

            sketch1.Points.Add(0, new Pnt2d(-13.889948477751762, 14.273648711943792));
            sketch1.Points.Add(1, new Pnt2d(-0.076740046838405171, 23.6359344262295));
            sketch1.Points.Add(2, new Pnt2d(15.424749414519905, 21.180252927400467));
            sketch1.Points.Add(3, new Pnt2d(21.870913348946136, 6.1392037470725977));
            sketch1.Points.Add(4, new Pnt2d(9.8227259953161585, -8.978585480093674));
            sketch1.Points.Add(5, new Pnt2d(-10.513386416861826, -4.8346229508196732));
            sketch1.Segments.Add(0, new SketchSegmentLine(0, 1));
            sketch1.Segments.Add(1, new SketchSegmentLine(1, 2));
            sketch1.Segments.Add(2, new SketchSegmentLine(2, 3));
            sketch1.Segments.Add(3, new SketchSegmentLine(3, 4));
            sketch1.Segments.Add(4, new SketchSegmentLine(4, 5));
            sketch1.Segments.Add(5, new SketchSegmentLine(5, 0));
            Assume.That(sketch1.Make(Shape.MakeFlags.None));
            var body1 = Body.Create(sketch1);

            var sketch2 = Sketch.Create();

            sketch2.Points.Add(0, new Pnt2d(-9.8227259953161639, 20.627724590163936));
            sketch2.Points.Add(1, new Pnt2d(5.4024992974238826, 18.785963466042151));
            sketch2.Points.Add(2, new Pnt2d(19.154315690866518, 24.679599063231855));
            sketch2.Points.Add(3, new Pnt2d(26.766928337236532, 2.5784655737704947));
            sketch2.Points.Add(4, new Pnt2d(9.2088056206089064, -2.4556814988290427));
            sketch2.Points.Add(5, new Pnt2d(-14.12016861826698, -10.43664637002342));
            sketch2.Segments.Add(0, new SketchSegmentLine(0, 1));
            sketch2.Segments.Add(1, new SketchSegmentLine(1, 2));
            sketch2.Segments.Add(2, new SketchSegmentLine(2, 3));
            sketch2.Segments.Add(3, new SketchSegmentLine(3, 4));
            sketch2.Segments.Add(4, new SketchSegmentLine(4, 5));
            sketch2.Segments.Add(5, new SketchSegmentLine(5, 0));
            Assume.That(sketch2.Make(Shape.MakeFlags.None));
            var body2 = Body.Create(sketch2);

            TransformUtils.Translate(body2, new Vec(0, 0, 20.0));

            var sketch3 = Sketch.Create();

            sketch3.Points.Add(0, new Pnt2d(-17.803690866510539, 3.560738173302112));
            sketch3.Points.Add(1, new Pnt2d(-19.522667915690871, 23.574542388758786));
            sketch3.Points.Add(2, new Pnt2d(6.7531241217798614, 28.854257611241216));
            sketch3.Points.Add(3, new Pnt2d(30.573234660421541, 23.697326463700239));
            sketch3.Points.Add(4, new Pnt2d(33.642836533957841, 0.24556814988290426));
            sketch3.Points.Add(5, new Pnt2d(6.9986922716627582, 19.522667915690867));
            sketch3.Segments.Add(0, new SketchSegmentLine(0, 1));
            sketch3.Segments.Add(1, new SketchSegmentLine(1, 2));
            sketch3.Segments.Add(2, new SketchSegmentLine(2, 3));
            sketch3.Segments.Add(3, new SketchSegmentLine(3, 4));
            sketch3.Segments.Add(4, new SketchSegmentLine(4, 5));
            sketch3.Segments.Add(5, new SketchSegmentLine(5, 0));
            Assume.That(sketch3.Make(Shape.MakeFlags.None));
            var body3 = Body.Create(sketch3);

            TransformUtils.Translate(body3, new Vec(0, 0, 40.0));

            var loft = Loft.Create(body1, new[] { new BodyShapeOperand(body2), new BodyShapeOperand(body3) });

            loft.StartCapping = Loft.CappingMode.None;
            loft.EndCapping   = Loft.CappingMode.None;

            loft.ThickenDirection = Loft.Direction.Inwards;
            Assert.IsTrue(loft.Make(Shape.MakeFlags.None));
            AssertHelper.IsSameModel(loft, Path.Combine(_BasePath, "CappingModeNoneWithConcaveSectionIn"));

            loft.ThickenDirection = Loft.Direction.Outwards;
            Assert.IsTrue(loft.Make(Shape.MakeFlags.None));
            AssertHelper.IsSameModel(loft, Path.Combine(_BasePath, "CappingModeNoneWithConcaveSectionOut"));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Defines the rotation elements in the inspector.
        /// </summary>
        private void RotationInspector()
        {
            // Rotation Label - Adjusts to whether or not the inspector is in wide mode
            if (EditorGUIUtility.wideMode)
            {
                EditorGUILayout.BeginHorizontal();
                GUILayout.Label("Rotation", GUILayout.MinWidth(90), GUILayout.ExpandHeight(false));
            }
            else
            {
                GUILayout.Label("Rotation", GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false));
            }

            // Making the  RotationVector3 Boxes in thier colours
            EditorGUIUtility.labelWidth = 15;
            EditorGUILayout.BeginHorizontal();
            EditorGUI.BeginChangeCheck();


            // Hotfix 2 - try to stop the 90/270 issue
            Vector3 _newRot = TransformUtils.GetInspectorRotation(_t);

            if (EditorPrefs.GetBool("CarterGames-TransformColours-Use2D"))
            {
                //// Rotation X - Red
                GUI.backgroundColor = _hidden;
                _newRot.x           = EditorGUILayout.FloatField(new GUIContent("X"), _newRot.x, GUILayout.Width(70), GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false));

                //// Rotation Y - Green
                _newRot.y           = EditorGUILayout.FloatField(new GUIContent("Y"), _newRot.y, GUILayout.Width(70), GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false));
                GUI.backgroundColor = Color.white;

                //// Rotation Z - Blue
                GUI.backgroundColor = Color.blue;
                _newRot.z           = EditorGUILayout.FloatField(new GUIContent("Z"), _newRot.z, GUILayout.Width(70), GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false));
                GUI.backgroundColor = Color.white;
            }
            else
            {
                //// Rotation X - Red
                GUI.backgroundColor = Color.red;
                _newRot.x           = EditorGUILayout.FloatField(new GUIContent("X"), _newRot.x, GUILayout.Width(70), GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false));
                GUI.backgroundColor = Color.white;

                //// Rotation Y - Green
                GUI.backgroundColor = Color.green;
                _newRot.y           = EditorGUILayout.FloatField(new GUIContent("Y"), _newRot.y, GUILayout.Width(70), GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false));
                GUI.backgroundColor = Color.white;

                //// Rotation Z - Blue
                GUI.backgroundColor = Color.blue;
                _newRot.z           = EditorGUILayout.FloatField(new GUIContent("Z"), _newRot.z, GUILayout.Width(70), GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(false));
                GUI.backgroundColor = Color.white;
            }


            EditorGUILayout.EndHorizontal();


            // Hotfix 2 - try to stop the 90/270 issue
            TransformUtils.SetInspectorRotation(_t, _newRot);


            // Runs if a edit was made to one of the fields above
            if (EditorGUI.EndChangeCheck())
            {
                _rotChange = true;
            }


            // Adjusts the editor Hoz grouping so the label shows above the boxes if the inspector is not in wide mode
            if (EditorGUIUtility.wideMode)
            {
                EditorGUILayout.EndHorizontal();
            }
        }
        public static async Task <HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, FunctionContext executionContext)
        {
            var log = executionContext.GetLogger("SubmitEncodingJob");

            log.LogInformation("C# HTTP trigger function processed a request.");

            // Get request body data.
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var    data        = (RequestBodyModel)JsonConvert.DeserializeObject(requestBody, typeof(RequestBodyModel));

            // Return bad request if input asset name is not passed in
            if (data.InputAssetName == null && data.InputUrl == null)
            {
                return(HttpRequest.ResponseBadRequest(req, "Please pass inputAssetName or inputUrl in the request body"));
            }

            // Return bad request if input asset name is not passed in
            if (data.TransformName == null)
            {
                return(HttpRequest.ResponseBadRequest(req, "Please pass transformName in the request body"));
            }

            ConfigWrapper config = ConfigUtils.GetConfig();

            IAzureMediaServicesClient client;

            try
            {
                client = await Authentication.CreateMediaServicesClientAsync(config, log);

                log.LogInformation("AMS Client created.");
            }
            catch (Exception e)
            {
                if (e.Source.Contains("ActiveDirectory"))
                {
                    log.LogError("TIP: Make sure that you have filled out the appsettings.json file before running this sample.");
                }
                log.LogError($"{e.Message}");

                return(HttpRequest.ResponseBadRequest(req, e.Message));
            }

            // Set the polling interval for long running operations to 2 seconds.
            // The default value is 30 seconds for the .NET client SDK
            client.LongRunningOperationRetryTimeout = 2;

            // Creating a unique suffix so that we don't have name collisions if you run the sample
            // multiple times without cleaning up.
            string uniqueness      = Guid.NewGuid().ToString().Substring(0, 13);
            string jobName         = $"job-{uniqueness}";
            string outputAssetName = $"output-{uniqueness}";

            Transform transform;

            try
            {
                // Ensure that you have the encoding Transform.  This is really a one time setup operation.
                transform = await TransformUtils.CreateEncodingTransform(client, log, config.ResourceGroup, config.AccountName, data.TransformName, data.BuiltInPreset);

                log.LogInformation("Transform retrieved.");
            }
            catch (Exception e)
            {
                log.LogError("Error when creating/getting the transform.");
                log.LogError($"{e.Message}");
                return(HttpRequest.ResponseBadRequest(req, e.Message));
            }

            Asset outputAsset;

            try
            {
                // Output from the job must be written to an Asset, so let's create one
                outputAsset = await AssetUtils.CreateAssetAsync(client, log, config.ResourceGroup, config.AccountName, outputAssetName, data.OutputAssetStorageAccount);

                log.LogInformation($"Output asset '{outputAssetName}' created.");
            }
            catch (Exception e)
            {
                log.LogError("Error when creating the output asset.");
                log.LogError($"{e.Message}");
                return(HttpRequest.ResponseBadRequest(req, e.Message));
            }

            // Job input prepration : asset or url
            JobInput jobInput;

            if (data.InputUrl != null)
            {
                jobInput = new JobInputHttp(files: new[] { data.InputUrl });
                log.LogInformation("Input is a Url.");
            }
            else
            {
                jobInput = new JobInputAsset(assetName: data.InputAssetName);
                log.LogInformation($"Input is asset '{data.InputAssetName}'.");
            }

            Job job;

            try
            {
                // Job submission to Azure Media Services
                job = await JobUtils.SubmitJobAsync(
                    client,
                    log,
                    config.ResourceGroup,
                    config.AccountName,
                    data.TransformName,
                    jobName,
                    jobInput,
                    outputAssetName
                    );

                log.LogInformation($"Job '{jobName}' submitted.");
            }
            catch (Exception e)
            {
                log.LogError("Error when submitting the job.");
                log.LogError($"{e.Message}");
                return(HttpRequest.ResponseBadRequest(req, e.Message));
            }

            AnswerBodyModel dataOk = new()
            {
                OutputAssetName = outputAsset.Name,
                JobName         = job.Name
            };

            return(HttpRequest.ResponseOk(req, dataOk));
        }
    }
        public static async Task <HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, FunctionContext executionContext)
        {
            var log = executionContext.GetLogger("SubmitSubclipJob");

            log.LogInformation("C# HTTP trigger function processed a request.");

            string triggerStart = DateTime.UtcNow.ToString("yyMMddHHmmss");

            // Get request body data.
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var    data        = (RequestBodyModel)JsonConvert.DeserializeObject(requestBody, typeof(RequestBodyModel));

            // Return bad request if input asset name is not passed in
            if (data.LiveEventName == null || data.LiveOutputName == null)
            {
                return(HttpRequest.ResponseBadRequest(req, "Please pass liveEventName and liveOutputName in the request body"));
            }

            data.IntervalSec ??= 60;

            ConfigWrapper config = ConfigUtils.GetConfig();

            IAzureMediaServicesClient client;

            try
            {
                client = await Authentication.CreateMediaServicesClientAsync(config);
            }
            catch (Exception e)
            {
                if (e.Source.Contains("ActiveDirectory"))
                {
                    log.LogError("TIP: Make sure that you have filled out the appsettings.json file before running this sample.");
                }
                log.LogError($"{e.Message}");

                return(HttpRequest.ResponseBadRequest(req, e.Message));
            }

            // Set the polling interval for long running operations to 2 seconds.
            // The default value is 30 seconds for the .NET client SDK
            client.LongRunningOperationRetryTimeout = 2;

            try
            {
                // Ensure that you have customized encoding Transform.  This is really a one time setup operation.
                Transform transform = await TransformUtils.GetOrCreateSubclipTransform(client, log, config.ResourceGroup, config.AccountName, SubclipTransformName);
            }
            catch (ErrorResponseException ex)
            {
                return(HttpRequest.ResponseBadRequest(req, LogUtils.LogError(log, ex, "Error when getting or creating the transform.")));
            }

            var liveOutput = await client.LiveOutputs.GetAsync(config.ResourceGroup, config.AccountName, data.LiveEventName, data.LiveOutputName);


            // let's analyze the client manifest and adjust times for the subclip job
            var doc = await LiveManifest.TryToGetClientManifestContentAsABlobAsync(client, config.ResourceGroup, config.AccountName, liveOutput.AssetName);

            var assetmanifestdata = LiveManifest.GetManifestTimingData(doc);

            if (assetmanifestdata.Error)
            {
                return(HttpRequest.ResponseBadRequest(req, "Data cannot be read from live output / asset manifest."));
            }

            log.LogInformation("Timestamps : " + string.Join(",", assetmanifestdata.TimestampList.Select(n => n.ToString()).ToArray()));

            var livetime = TimeSpan.FromSeconds(assetmanifestdata.TimestampEndLastChunk / (double)assetmanifestdata.TimeScale);

            log.LogInformation($"Livetime : {livetime}");

            var starttime = LiveManifest.ReturnTimeSpanOnGOP(assetmanifestdata, livetime.Subtract(TimeSpan.FromSeconds((int)data.IntervalSec)));

            log.LogInformation($"Value starttime : {starttime}");

            if (data.LastSubclipEndTime != null)
            {
                var lastEndTime = (TimeSpan)data.LastSubclipEndTime;
                log.LogInformation($"Value lastEndTime : {lastEndTime}");

                var delta = (livetime - lastEndTime - TimeSpan.FromSeconds((int)data.IntervalSec)).Duration();
                log.LogInformation($"Delta: {delta}");

                if (delta < (TimeSpan.FromSeconds(3 * (int)data.IntervalSec))) // less than 3 times the normal duration (3*60s)
                {
                    starttime = lastEndTime;
                    log.LogInformation($"Value new starttime : {starttime}");
                }
            }

            var duration = livetime - starttime;

            log.LogInformation($"Value duration: {duration}");
            if (duration == new TimeSpan(0)) // Duration is zero, this may happen sometimes !
            {
                return(HttpRequest.ResponseBadRequest(req, "Stopping. Duration of subclip is zero."));
            }

            Asset outputAsset;

            try
            {
                // Output from the Job must be written to an Asset, so let's create one
                outputAsset = await AssetUtils.CreateAssetAsync(client, log, config.ResourceGroup, config.AccountName, liveOutput.Name + "-subclip-" + triggerStart, data.OutputAssetStorageAccount);
            }
            catch (ErrorResponseException ex)
            {
                return(HttpRequest.ResponseBadRequest(req, LogUtils.LogError(log, ex, "Error when creating the output asset.")));
            }

            JobInput jobInput = new JobInputAsset(
                assetName: liveOutput.AssetName,
                start: new AbsoluteClipTime(starttime.Subtract(TimeSpan.FromMilliseconds(100))),
                end: new AbsoluteClipTime(livetime.Add(TimeSpan.FromMilliseconds(100)))
                );

            Job job;

            try
            {
                job = await JobUtils.SubmitJobAsync(
                    client,
                    log,
                    config.ResourceGroup,
                    config.AccountName,
                    SubclipTransformName,
                    $"Subclip-{liveOutput.Name}-{triggerStart}",
                    jobInput,
                    outputAsset.Name
                    );
            }
            catch (ErrorResponseException ex)
            {
                return(HttpRequest.ResponseBadRequest(req, LogUtils.LogError(log, ex, "Error when submitting the job.")));
            }


            AnswerBodyModel dataOk = new()
            {
                SubclipAssetName     = outputAsset.Name,
                SubclipJobName       = job.Name,
                SubclipTransformName = SubclipTransformName,
                SubclipEndTime       = starttime + duration
            };

            return(HttpRequest.ResponseOk(req, dataOk, HttpStatusCode.Accepted));
        }
    }
Ejemplo n.º 19
0
 /// <summary>
 /// Appends a centered skew matrix from the give angles in degrees.
 /// </summary>
 /// <param name="degreesX">The X angle, in degrees.</param>
 /// <param name="degreesY">The Y angle, in degrees.</param>
 /// <returns>The <see cref="AffineTransformBuilder"/>.</returns>
 public AffineTransformBuilder AppendSkewDegrees(float degreesX, float degreesY)
 => this.Append(size => TransformUtils.CreateSkewMatrixDegrees(degreesX, degreesY, size));
 /// <summary>
 /// Appends a centered skew matrix from the give angles in radians.
 /// </summary>
 /// <param name="radiansX">The X angle, in radians.</param>
 /// <param name="radiansY">The Y angle, in radians.</param>
 /// <returns>The <see cref="ProjectiveTransformBuilder"/>.</returns>
 public ProjectiveTransformBuilder AppendSkewRadians(float radiansX, float radiansY)
 => this.Append(size => new Matrix4x4(TransformUtils.CreateSkewMatrixRadians(radiansX, radiansY, size)));
Ejemplo n.º 21
0
 /// <summary>
 /// Appends a rotation matrix using the given rotation angle in radians
 /// and the image center point as rotation center.
 /// </summary>
 /// <param name="radians">The amount of rotation, in radians.</param>
 /// <returns>The <see cref="AffineTransformBuilder"/>.</returns>
 public AffineTransformBuilder AppendRotationRadians(float radians)
 => this.Append(size => TransformUtils.CreateRotationMatrixRadians(radians, size));
 /// <summary>
 /// Appends a matrix that performs a tapering projective transform.
 /// </summary>
 /// <param name="side">An enumeration that indicates the side of the rectangle that tapers.</param>
 /// <param name="corner">An enumeration that indicates on which corners to taper the rectangle.</param>
 /// <param name="fraction">The amount to taper.</param>
 /// <returns>The <see cref="ProjectiveTransformBuilder"/>.</returns>
 public ProjectiveTransformBuilder AppendTaper(TaperSide side, TaperCorner corner, float fraction)
 => this.Append(size => TransformUtils.CreateTaperMatrix(size, side, corner, fraction));
        public override bool Init()
        {
            if (string.IsNullOrEmpty(targetPath))
            {
                Debug.LogErrorFormat("{0}:{1}:Init - Target path not set", name, GetType());
                return(false);
            }

            Transform targetTF = TransformUtils.GetTransformByPath(targetPath);

            if (targetTF == null)
            {
                Debug.LogErrorFormat("{0}:{1}:Init - Target transform not found, targetPath={2}", name, GetType(), targetPath);
                return(false);
            }

            if (string.IsNullOrEmpty(targetComponentName))
            {
                Debug.LogErrorFormat("{0}:{1}:Init - Target component not set", name, GetType());
                return(false);
            }

            System.Type targetComponentType = System.Type.GetType(targetComponentName);

            if (targetComponentType == null)
            {
                Debug.LogErrorFormat("{0}:{1}:Init - Target component type not found, targetComponentName={2}", name, GetType(), targetComponentName);
                return(false);
            }

            Component targetC = targetTF.GetComponent(targetComponentName) as Component;

            if (targetC == null)
            {
                Debug.LogErrorFormat("{0}:{1}:Init - Target component not found, targetComponentType={2}", name, GetType(), targetComponentType);
                return(false);
            }

            UnityAction handler = DoComplete;

            if (string.IsNullOrEmpty(fieldName))
            {
                try {
                    EventInfo ei = targetComponentType.GetEvent(eventName, BindingFlags.Public | BindingFlags.Instance);
                    ei.AddEventHandler(targetC, handler);
                } catch {
                    Debug.LogWarningFormat("{0}:{1}:Init - Action not found, targetC={2}, actionName={3}", name, GetType(), targetC, eventName);
                    return(false);
                }
            }
            else
            {
                object obj;

                try {
                    obj = (object)targetComponentType.GetField(fieldName, BindingFlags.Public | BindingFlags.Instance).GetValue(targetC);
                } catch {
                    Debug.LogWarningFormat("{0}:{1}:Init - Target field not found, targetC={2}, fieldName={3}", name, GetType(), targetC, fieldName);
                    return(false);
                }

                try {
                    EventInfo ei = obj.GetType().GetEvent(eventName, BindingFlags.Public | BindingFlags.Instance);
                    ei.AddEventHandler(obj, handler);
                } catch {
                    Debug.LogWarningFormat("{0}:{1}:Init - Event not found, targetC={2}, obj={3}, eventName={4}", name, GetType(), targetC, obj, eventName);
                    return(false);
                }
            }

            return(true);
        }
 /// <summary>
 /// Appends a centered rotation matrix using the given rotation in radians.
 /// </summary>
 /// <param name="radians">The amount of rotation, in radians.</param>
 /// <returns>The <see cref="ProjectiveTransformBuilder"/>.</returns>
 public ProjectiveTransformBuilder AppendRotationRadians(float radians)
 => this.Append(size => new Matrix4x4(TransformUtils.CreateRotationMatrixRadians(radians, size)));
        public override void OnDragging(ViewControl vc, Point scrPt)
        {
            if (m_hitRegion == HitRegion.None || m_activeOp == null || m_activeOp.NodeList.Count == 0)
            {
                return;
            }

            // create ray in view space.
            Ray3F rayV = vc.GetWorldRay(scrPt);

            using (var intersectionScene = GameEngine.GetEditorSceneManager().GetIntersectionScene())
            {
                PickResult intersectionPt;
                if (!CalculateTerrainIntersection(vc, rayV, intersectionScene, out intersectionPt))
                {
                    return;
                }

                if (m_pendingStartPt)
                {
                    m_startPt        = intersectionPt._pt.Value;
                    m_pendingStartPt = false;
                }
                else
                {
                    ISnapSettings snapSettings = (ISnapSettings)DesignView;

                    bool  clampToSurface = Control.ModifierKeys == Keys.Shift;
                    var   pt             = intersectionPt._pt.Value;
                    Vec3F translate      = new Vec3F(pt.X - m_startPt.X, pt.Y - m_startPt.Y, 0.0f);
                    for (int i = 0; i < m_activeOp.NodeList.Count; i++)
                    {
                        ITransformable node = m_activeOp.NodeList[i];

                        Path <DomNode> path = new Path <DomNode>(Adapters.Cast <DomNode>(node).GetPath());
                        Matrix4F       parentLocalToWorld = TransformUtils.CalcPathTransform(path, path.Count - 2);
                        Matrix4F       parentWorldToLocal = new Matrix4F();
                        parentWorldToLocal.Invert(parentLocalToWorld);

                        Vec3F            newWorldPos   = m_originalTranslations[i] + translate;
                        float            terrainHeight = 0.0f;
                        GUILayer.Vector3 terrainNormal;
                        if (GUILayer.EditorInterfaceUtils.GetTerrainHeightAndNormal(
                                out terrainHeight, out terrainNormal,
                                intersectionScene, newWorldPos.X, newWorldPos.Y))
                        {
                            newWorldPos.Z = terrainHeight + (clampToSurface ? 0.0f : m_originalHeights[i]);
                            Vec3F localTranslation;
                            parentWorldToLocal.TransformVector(newWorldPos, out localTranslation);
                            node.Translation = localTranslation;

                            // There are two ways to orient the "up" vector of the object.
                            // One way is to decompose the 3x3 rotation matrix into a up vector + a rotation around
                            // that vector. Then we retain the rotation, and just move the up vector.
                            // Another way is to take the 3x3 matrix, and adjust it's up vector. Then just perform
                            // the Gram–Schmidt algorithm to re-orthogonalize it.
                            // We'll use the code from the SCEE level editor. This isn't the ideal math (there's a
                            // lot of room for floating point creep) but it should work.
                            var currentUp = node.Transform.ZAxis;
                            if (snapSettings.TerrainAlignment == TerrainAlignmentMode.TerrainUp)
                            {
                                node.Rotation = TransformUtils.RotateToVector(
                                    node.Rotation, new Vec3F(terrainNormal.X, terrainNormal.Y, terrainNormal.Z),
                                    AxisSystemType.ZIsUp);
                            }
                            else
                            if (snapSettings.TerrainAlignment == TerrainAlignmentMode.WorldUp)
                            {
                                // Prevent the change if the normal is already very close to straight up
                                if (Math.Abs(currentUp.X - 0.0f) > 1e-4f || Math.Abs(currentUp.Y - 0.0f) > 1e-4f || Math.Abs(currentUp.Z - 1.0f) > 1e-4f)
                                {
                                    node.Rotation = TransformUtils.RotateToVector(
                                        node.Rotation, new Vec3F(0.0f, 0.0f, 1.0f),
                                        AxisSystemType.ZIsUp);
                                }
                            }

                            node.UpdateTransform();
                        }
                    }
                }
            }
        }
Ejemplo n.º 26
0
        public override void OnBeginDrag()
        {
            if (m_hitRegion == HitRegion.None)
            {
                return;
            }

            var selection          = DesignView.Context.As <ISelectionContext>().Selection;
            var transactionContext = DesignView.Context.As <ITransactionContext>();

            NodeList.Clear();

            m_isUniformScaling = false;

            IEnumerable <DomNode> rootDomNodes = DomNode.GetRoots(selection.AsIEnumerable <DomNode>());

            foreach (DomNode node in rootDomNodes)
            {
                ITransformable transNode = node.As <ITransformable>();
                if (transNode == null || (transNode.TransformationType & TransformationTypes.Scale) == 0)
                {
                    continue;
                }

                IVisible vn = node.As <IVisible>();
                if (!vn.Visible)
                {
                    continue;
                }

                ILockable lockable = node.As <ILockable>();
                if (lockable.IsLocked)
                {
                    continue;
                }

                // force uniform scaling if any node requires it
                if ((transNode.TransformationType & TransformationTypes.UniformScale) == TransformationTypes.UniformScale)
                {
                    m_isUniformScaling = true;
                }

                NodeList.Add(transNode);

                IManipulatorNotify notifier = transNode.As <IManipulatorNotify>();
                if (notifier != null)
                {
                    notifier.OnBeginDrag();
                }
            }


            // to compute offset use bounding box in local space.
            Vec3F offset = Vec3F.ZeroVector;// 0.5f; // use bounding box in local space

            switch (m_hitRegion)
            {
            case HitRegion.XAxis:
            case HitRegion.YAxis:
            case HitRegion.ZAxis:
                offset = new Vec3F(-1, -1, -1);
                break;

            case HitRegion.NegXAxis:
            case HitRegion.NegYAxis:
            case HitRegion.NegZAxis:
                offset = new Vec3F(1, 1, 1);
                break;

            default:
                break;
            }

            m_originalScales       = new Vec3F[NodeList.Count];
            m_originalTranslations = new Vec3F[NodeList.Count];
            m_pivotOffset          = new Vec3F[NodeList.Count];
            int k = 0;

            foreach (ITransformable node in NodeList)
            {
                IBoundable boundable = node.As <IBoundable>();
                Vec3F      pivot     = Vec3F.Mul(boundable.LocalBoundingBox.Radius, offset);
                m_pivotOffset[k] = pivot;

                m_originalScales[k] = node.Scale;

                Matrix4F mtrx = TransformUtils.CalcTransform(
                    Vec3F.ZeroVector,
                    node.Rotation,
                    node.Scale,
                    pivot
                    );

                m_originalTranslations[k] = node.Translation - mtrx.Translation;
                k++;
            }

            if (NodeList.Count > 0)
            {
                transactionContext.Begin("Extend".Localize());
            }
        }
Ejemplo n.º 27
0
    public Vector3 GetGridNodeIndex(Vector3 worldPoint)
    {
        Vector3 localSpacePoint = VoxelContainer.InverseTransformPoint(worldPoint);

        return(TransformUtils.SnapToGrid(localSpacePoint, snapToForGridSize, inverseSnapToForGrid) * inverseSnapToForGrid);
    }
Ejemplo n.º 28
0
        public override void OnDragging(ViewControl vc, Point scrPt)
        {
            if (m_hitRegion == HitRegion.None || NodeList.Count == 0)
            {
                return;
            }

            Matrix4F view = vc.Camera.ViewMatrix;
            // compute world * view
            Matrix4F wv = new Matrix4F();

            wv.Mul(HitMatrix, view);

            // create ray in view space.
            Ray3F rayV = vc.GetRay(scrPt, vc.Camera.ProjectionMatrix);

            Vec3F xAxis  = wv.XAxis;
            Vec3F yAxis  = wv.YAxis;
            Vec3F zAxis  = wv.ZAxis;
            Vec3F origin = wv.Translation;

            m_scale = new Vec3F(1, 1, 1);
            float scale = 1;
            float a1, a2;

            switch (m_hitRegion)
            {
            case HitRegion.XAxis:
            case HitRegion.NegXAxis:
            {
                a1 = Math.Abs(Vec3F.Dot(HitRayV.Direction, yAxis));
                a2 = Math.Abs(Vec3F.Dot(HitRayV.Direction, zAxis));
                Vec3F axis       = (a1 > a2 ? yAxis : zAxis);
                Vec3F p0         = HitRayV.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                Vec3F p1         = rayV.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                float dragAmount = Vec3F.Dot((p1 - p0), xAxis);
                if (m_hitRegion == HitRegion.NegXAxis)
                {
                    dragAmount *= -1;
                }
                m_scale.X = 1.0f + dragAmount / m_hitScale;
                scale     = m_scale.X;
            }

            break;

            case HitRegion.YAxis:
            case HitRegion.NegYAxis:
            {
                a1 = Math.Abs(Vec3F.Dot(HitRayV.Direction, zAxis));
                a2 = Math.Abs(Vec3F.Dot(HitRayV.Direction, xAxis));
                Vec3F axis       = (a1 > a2 ? zAxis : xAxis);
                Vec3F p0         = HitRayV.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                Vec3F p1         = rayV.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                float dragAmount = Vec3F.Dot((p1 - p0), yAxis);
                if (m_hitRegion == HitRegion.NegYAxis)
                {
                    dragAmount *= -1;
                }
                m_scale.Y = 1.0f + dragAmount / m_hitScale;
                scale     = m_scale.Y;
            }
            break;

            case HitRegion.ZAxis:
            case HitRegion.NegZAxis:
            {
                a1 = Math.Abs(Vec3F.Dot(HitRayV.Direction, xAxis));
                a2 = Math.Abs(Vec3F.Dot(HitRayV.Direction, yAxis));
                Vec3F axis       = (a1 > a2 ? xAxis : yAxis);
                Vec3F p0         = HitRayV.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                Vec3F p1         = rayV.IntersectPlane(axis, -Vec3F.Dot(axis, origin));
                float dragAmount = Vec3F.Dot((p1 - p0), zAxis);
                if (m_hitRegion == HitRegion.NegZAxis)
                {
                    dragAmount *= -1;
                }
                m_scale.Z = 1.0f + dragAmount / m_hitScale;
                scale     = m_scale.Z;
            }
            break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            if (m_isUniformScaling)
            {
                m_scale = new Vec3F(scale, scale, scale);
            }


            // scale
            for (int i = 0; i < NodeList.Count; i++)
            {
                ITransformable node = NodeList[i];
                node.Scale = Vec3F.Mul(m_originalScales[i], m_scale);

                Matrix4F mtrx = TransformUtils.CalcTransform(
                    Vec3F.ZeroVector,
                    node.Rotation,
                    node.Scale,
                    m_pivotOffset[i]);
                node.Translation = m_originalTranslations[i] + mtrx.Translation;
            }
        }
Ejemplo n.º 29
0
        public override void OnDragging(ViewControl vc, Point scrPt)
        {
            if (m_cancelDrag || m_hitRegion == HitRegion.None || m_activeOp == null || m_activeOp.NodeList.Count == 0)
            {
                return;
            }

            var nativeVC = vc as NativeDesignControl;

            if (nativeVC == null)
            {
                return;
            }

            bool hitAxis = m_hitRegion == HitRegion.XAxis ||
                           m_hitRegion == HitRegion.YAxis ||
                           m_hitRegion == HitRegion.ZAxis;

            Matrix4F proj = vc.Camera.ProjectionMatrix;

            // create ray in view space.
            Ray3F rayV      = vc.GetRay(scrPt, proj);
            Vec3F translate = m_translatorControl.OnDragging(rayV);

            ISnapSettings snapSettings = (ISnapSettings)DesignView;
            bool          snapToGeom   = Control.ModifierKeys == m_snapGeometryKey;

            if (snapToGeom)
            {
                Matrix4F view = vc.Camera.ViewMatrix;
                Matrix4F vp   = view * proj;
                // create ray in world space.
                Ray3F rayW = vc.GetRay(scrPt, vp);

                Vec3F manipPos = HitMatrix.Translation;
                Vec3F manipMove;
                if (hitAxis)
                {
                    //Make rayw to point toward moving axis and starting
                    // from manipulator’s world position.
                    rayW.Direction = Vec3F.Normalize(translate);
                    rayW.Origin    = manipPos;
                    manipMove      = Vec3F.ZeroVector;
                    m_cancelDrag   = true; //stop further snap-to's
                }
                else
                {
                    manipMove = rayW.ProjectPoint(manipPos) - manipPos;
                }

                for (int i = 0; i < m_activeOp.NodeList.Count; i++)
                {
                    ITransformable node               = m_activeOp.NodeList[i];
                    Vec3F          snapOffset         = TransformUtils.CalcSnapFromOffset(node, snapSettings.SnapFrom);
                    Path <DomNode> path               = new Path <DomNode>(Adapters.Cast <DomNode>(node).GetPath());
                    Matrix4F       parentLocalToWorld = TransformUtils.CalcPathTransform(path, path.Count - 2);
                    Vec3F          orgPosW;
                    parentLocalToWorld.Transform(m_originalValues[i], out orgPosW);

                    Matrix4F parentWorldToLocal = new Matrix4F();
                    parentWorldToLocal.Invert(parentLocalToWorld);

                    rayW.MoveToIncludePoint(orgPosW + snapOffset + manipMove);

                    var hits = XLEBridgeUtils.Picking.RayPick(
                        nativeVC.Adapter, rayW,
                        XLEBridgeUtils.Picking.Flags.Terrain | XLEBridgeUtils.Picking.Flags.Objects | XLEBridgeUtils.Picking.Flags.IgnoreSelection);
                    bool cansnap = false;
                    var  target  = new XLEBridgeUtils.Picking.HitRecord();
                    if (hits != null && hits.Length > 0)
                    {
                        // find hit record.
                        foreach (var hit in hits)
                        {
                            if (m_snapFilter.CanSnapTo(node, m_nativeIdMapping.GetAdapter(hit.documentId, hit.instanceId)))
                            {
                                target  = hit;
                                cansnap = true;
                                break;
                            }
                        }
                    }

                    if (cansnap)
                    {
                        Vec3F pos;
                        if (target.hasNearestVert && snapSettings.SnapVertex)
                        {
                            pos = target.nearestVertex;
                        }
                        else
                        {
                            pos = target.hitPt;
                        }

                        pos -= snapOffset;
                        parentWorldToLocal.Transform(ref pos);
                        Vec3F diff = pos - node.Transform.Translation;
                        node.Translation += diff;
                        bool rotateOnSnap = snapSettings.RotateOnSnap &&
                                            target.hasNormal &&
                                            (node.TransformationType & TransformationTypes.Rotation) != 0;
                        if (rotateOnSnap)
                        {
                            Vec3F localSurfaceNormal;
                            parentWorldToLocal.TransformNormal(target.normal, out localSurfaceNormal);
                            node.Rotation = TransformUtils.RotateToVector(
                                m_originalRotations[i],
                                localSurfaceNormal,
                                AxisSystemType.YIsUp);
                        }
                    }
                }
            }
            else
            {
                IGrid grid       = DesignView.Context.Cast <IGame>().Grid;
                bool  snapToGrid = Control.ModifierKeys == m_snapGridKey &&
                                   grid.Visible &&
                                   vc.Camera.ViewType == ViewTypes.Perspective;
                float gridHeight = grid.Height;
                // translate.
                for (int i = 0; i < m_activeOp.NodeList.Count; i++)
                {
                    ITransformable node = m_activeOp.NodeList[i];
                    Path <DomNode> path = new Path <DomNode>(Adapters.Cast <DomNode>(node).GetPath());
                    Matrix4F       parentLocalToWorld = TransformUtils.CalcPathTransform(path, path.Count - 2);
                    Matrix4F       parentWorldToLocal = new Matrix4F();
                    parentWorldToLocal.Invert(parentLocalToWorld);
                    Vec3F localTranslation;
                    parentWorldToLocal.TransformVector(translate, out localTranslation);
                    Vec3F trans = m_originalValues[i] + localTranslation;

                    if (snapToGrid)
                    {
                        if (grid.Snap)
                        {
                            trans = grid.SnapPoint(trans);
                        }
                        else
                        {
                            trans.Y = gridHeight;
                        }
                    }

                    node.Translation = trans;
                }
            }
        }
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            bool isPlaying = Application.isPlaying;

#if UNITY_2018_2_OR_NEWER
            if (!serializedObject.isEditingMultipleObjects)
            {
                isPlaying = Application.IsPlaying(target);
            }
#endif
            GUI.enabled = !isPlaying;

            EditorGUILayout.PropertyField(rotationProp);
            EditorGUILayout.HelpBox("Initial Rotation should make sure palm faces forward, fingers points up in global axis.",
                                    MessageType.Info);
            EditorGUILayout.HelpBox("Global rotation of Transform component is locked to use value of Initial Rotation",
                                    MessageType.None);
            EditorGUILayout.PropertyField(isLeftProp);
            EditorGUILayout.PropertyField(collliderProp);
            EditorGUILayout.PropertyField(confidenceProp);
            EditorGUILayout.PropertyField(handProp);
            if (nodesProp.hasMultipleDifferentValues)
            {
                EditorGUILayout.LabelField("Nodes", "-");
            }
            else
            {
                showNodes.target = EditorGUILayout.Foldout(showNodes.target, "Nodes");
                if (EditorGUILayout.BeginFadeGroup(showNodes.faded))
                {
                    EditorGUI.indentLevel++;
                    for (int i = 0; i < 21; i++)
                    {
                        var element = nodesProp.GetArrayElementAtIndex(i);
                        element.objectReferenceValue =
                            EditorGUILayout.ObjectField(names[i], element.objectReferenceValue, typeof(Transform), true);
                    }
                    EditorGUI.indentLevel--;
                }
                EditorGUILayout.EndFadeGroup();
            }
            serializedObject.ApplyModifiedProperties();
            GUI.enabled = true;

            if (isPlaying)
            {
                return;
            }

            foreach (ModelRenderer target in targets)
            {
                TransformUtils.SetInspectorRotation(target.transform, target.initialRotation);
                target.initialRotation = TransformUtils.GetInspectorRotation(target.transform);
            }

            if (serializedObject.isEditingMultipleObjects)
            {
                return;
            }

            GUILayout.Space(5);
            if (GUILayout.Button("Auto detect properties"))
            {
                AutoDetect(target as ModelRenderer);
            }
            EditorGUILayout.HelpBox("Please manually check if auto detect set fields correctly. Please refer to help page for details.",
                                    MessageType.Info);
        }