Example #1
0
        public void MinimalBST_Null_Null()
        {
            var actual = ArrayExtensions.CreateMinimalBST(null);

            Assert.AreEqual(null, actual);
        }
Example #2
0
 public void RemoveStyle()
 {
     ArrayExtensions.Shrink(ref Functions);
 }
        public void NawArrayUnordered_InsertionSort_EightAndFourSwapped_ShouldHaveRightBounds()
        {
            // Arrange
            NAW[] testSet;
            var   expectedLength = 10;
            var   array          = ArrayExtensions.InitializeTestSubject(new NawArrayUnordered(expectedLength), expectedLength, out testSet);
            var   newNaw         = RandomNawGenerator.New();

            testSet[0].Woonplaats = "0";
            testSet[1].Woonplaats = "1";
            testSet[2].Woonplaats = "2";
            testSet[3].Woonplaats = "3";
            testSet[4].Woonplaats = "8";
            testSet[5].Woonplaats = "5";
            testSet[6].Woonplaats = "6";
            testSet[7].Woonplaats = "7";
            testSet[8].Woonplaats = "4";
            testSet[9].Woonplaats = "9";

            // Act
            Alg1_Practicum_Utils.Globals.Alg1NawArrayMethodCalled = false;

            array.InsertionSort();

            // Assert
            Assert.IsFalse(Alg1_Practicum_Utils.Globals.Alg1NawArrayMethodCalled, "\n\nEr wordt een methode van Alg1NawArray gebruikt!\n\n");

            // Logger.Instance.Print();

            Assert.IsTrue(array.CheckIsGesorteerd(), "De array is niet gesorteerd na de InsertionSort.");

            int lowerBound = 4, upperBound = 8;

            NAW toMoveUp        = testSet[lowerBound];
            var toMoveUpSetters = (from li in Logger.Instance.LogItems
                                   where li.NewNaw1 == toMoveUp && li.ArrayAction == ArrayAction.SET &&
                                   li.NewNaw1 != li.OldNaw1     // This will be checked in another test
                                   orderby li.Index1
                                   select li).ToArray();

            // This one bubbles up slowly.
            for (int i = lowerBound + 1; i <= upperBound; i++)
            {
                Assert.IsTrue(toMoveUpSetters[i - lowerBound - 1].Index1 == i, "Er zouden 4 items verplaatst moeten zijn om ruimte te maken in het geordende deel.");
            }

            NAW toBeInsertedDown        = testSet[upperBound];
            var toBeInsertedDownSetters = (from li in Logger.Instance.LogItems
                                           where li.NewNaw1 == toBeInsertedDown && li.ArrayAction == ArrayAction.SET &&
                                           li.NewNaw1 != li.OldNaw1     // This will be checked in another test
                                           orderby li.Index1
                                           select li).ToArray();

            // This one moves down in an insertion way.
            Assert.AreEqual(1, toBeInsertedDownSetters.Count(), "Meerdere items zijn geïnsert in de sortering, dit had er 1 moeten zijn.");
            Assert.AreEqual(lowerBound, toBeInsertedDownSetters.First().Index1, "Item met woonplaats 4 zou op de 4e index geïnsert moeten zijn.");


            // All setters must be in between the bounds.
            Assert.IsTrue(Logger.Instance.LogItems
                          .Where(li => li.ArrayAction == ArrayAction.SET && li.NewNaw1 != li.OldNaw1)
                          .All(li => li.Index1 >= lowerBound && li.Index1 <= upperBound), "Je hebt items verplaatst die niet verplaatst hadden hoeven worden omdat ze al goed stonden.");
        }
Example #4
0
    public MotionData Create(string path, string currentDirectory)
    {
        Name = path.Substring(path.LastIndexOf("/") + 1);
        if (AssetDatabase.LoadAssetAtPath(currentDirectory + Name + ".asset", typeof(MotionData)) == null)
        {
            AssetDatabase.CreateAsset(this, currentDirectory + Name + ".asset");
        }
        else
        {
            int i = 1;
            while (AssetDatabase.LoadAssetAtPath(currentDirectory + Name + Name + " (" + i + ").asset", typeof(MotionData)) != null)
            {
                i += 1;
            }
            AssetDatabase.CreateAsset(this, currentDirectory + Name + Name + " (" + i + ").asset");
        }

        string[] lines      = File.ReadAllLines(path);
        char[]   whitespace = new char[] { ' ' };
        int      index      = 0;

        //Read BVH
        Source = new BVHData();
        string  name   = string.Empty;
        string  parent = string.Empty;
        Vector3 offset = Vector3.zero;

        int[] channels = null;
        for (index = 0; index < lines.Length; index++)
        {
            if (lines[index] == "MOTION")
            {
                break;
            }
            string[] entries = lines[index].Split(whitespace);
            for (int entry = 0; entry < entries.Length; entry++)
            {
                if (entries[entry].Contains("ROOT"))
                {
                    parent = "None";
                    name   = entries[entry + 1];
                    break;
                }
                else if (entries[entry].Contains("JOINT"))
                {
                    parent = name;
                    name   = entries[entry + 1];
                    break;
                }
                else if (entries[entry].Contains("End"))
                {
                    parent = name;
                    name   = name + entries[entry + 1];
                    string[] subEntries = lines[index + 2].Split(whitespace);
                    for (int subEntry = 0; subEntry < subEntries.Length; subEntry++)
                    {
                        if (subEntries[subEntry].Contains("OFFSET"))
                        {
                            offset.x = Utility.ReadFloat(subEntries[subEntry + 1]);
                            offset.y = Utility.ReadFloat(subEntries[subEntry + 2]);
                            offset.z = Utility.ReadFloat(subEntries[subEntry + 3]);
                            break;
                        }
                    }
                    Source.AddBone(name, parent, offset, new int[0]);
                    index += 2;
                    break;
                }
                else if (entries[entry].Contains("OFFSET"))
                {
                    offset.x = Utility.ReadFloat(entries[entry + 1]);
                    offset.y = Utility.ReadFloat(entries[entry + 2]);
                    offset.z = Utility.ReadFloat(entries[entry + 3]);
                    break;
                }
                else if (entries[entry].Contains("CHANNELS"))
                {
                    channels = new int[Utility.ReadInt(entries[entry + 1])];
                    for (int i = 0; i < channels.Length; i++)
                    {
                        if (entries[entry + 2 + i] == "Xposition")
                        {
                            channels[i] = 1;
                        }
                        else if (entries[entry + 2 + i] == "Yposition")
                        {
                            channels[i] = 2;
                        }
                        else if (entries[entry + 2 + i] == "Zposition")
                        {
                            channels[i] = 3;
                        }
                        else if (entries[entry + 2 + i] == "Xrotation")
                        {
                            channels[i] = 4;
                        }
                        else if (entries[entry + 2 + i] == "Yrotation")
                        {
                            channels[i] = 5;
                        }
                        else if (entries[entry + 2 + i] == "Zrotation")
                        {
                            channels[i] = 6;
                        }
                    }
                    Source.AddBone(name, parent, offset, channels);
                    break;
                }
                else if (entries[entry].Contains("}"))
                {
                    name   = parent;
                    parent = name == "None" ? "None" : Source.FindBone(name).Parent;
                    break;
                }
            }
        }

        //Read frame count
        index += 1;
        while (lines[index].Length == 0)
        {
            index += 1;
        }
        ArrayExtensions.Resize(ref Frames, Utility.ReadInt(lines[index].Substring(8)));

        //Read frame time
        index    += 1;
        Framerate = Mathf.RoundToInt(1f / Utility.ReadFloat(lines[index].Substring(12)));

        //Read motions
        index += 1;
        for (int i = index; i < lines.Length; i++)
        {
            Source.AddMotion(Utility.ReadArray(lines[i]));
        }

        //Detect settings
        DetectHeightMapSensor();
        DetectDepthMapSensor();
        DetectSymmetry();
        DetectCorrections();

        //Create frames
        for (int i = 0; i < GetTotalFrames(); i++)
        {
            Frames[i] = new Frame(this, i + 1, (float)i / Framerate);
        }

        //Generate
        ComputePostures();
        ComputeStyles();
        AddSequence();

        //Finish
        return(this);
    }
Example #5
0
 public void AddMotion(float[] values)
 {
     ArrayExtensions.Add(ref Motions, new Motion(values));
 }
Example #6
0
 public void AddSequence()
 {
     ArrayExtensions.Add(ref Sequences, new Sequence(this));
 }
Example #7
0
 public void RemoveSequence()
 {
     ArrayExtensions.Shrink(ref Sequences);
 }
Example #8
0
 public void SetChord()
 {
     this.Items            = ArrayExtensions.ArrayAppend(this.Items, new empty());
     this.ItemsElementName = ArrayExtensions.ArrayAppend(this.ItemsElementName, ItemsChoiceType1.chord);
 }
Example #9
0
 public void AddPitch(pitch pitch)
 {
     this.Items            = ArrayExtensions.ArrayAppend(this.Items, pitch);
     this.ItemsElementName = ArrayExtensions.ArrayAppend(this.ItemsElementName, ItemsChoiceType1.pitch);
 }
Example #10
0
    private IEnumerator Process()
    {
        if (Editor != null)
        {
            Processing = true;
            foreach (Asset a in Assets)
            {
                a.Processed = false;
            }
            int count = 0;

            if (Pipeline == PIPELINE.Basketball)
            {
                string     referenceBone = string.Empty;
                MotionData referenceData = null;
                foreach (Asset a in Assets)
                {
                    if (a.Selected)
                    {
                        count += 1;
                        MotionData data = OfflineProcessing ? Editor.GetAsset(a.GUID) : Editor.LoadData(a.GUID);
                        while (!OfflineProcessing && !data.GetScene().isLoaded)
                        {
                            Debug.Log("Waiting for scene being loaded...");
                            yield return(new WaitForSeconds(0f));
                        }
                        //START OF PROCESSING

                        // Reset motion data
                        foreach (Frame frame in data.Frames)
                        {
                            frame.ResetTransformations();
                        }

                        // Global
                        data.RemoveAllModules();
                        data.MirrorAxis = Axis.ZPositive;

                        // 1on1 Ball Copying
                        {
                            string GetID(MotionData asset)
                            {
                                return(asset.GetName().Substring(0, asset.GetName().LastIndexOf("_P0")));
                            }

                            referenceBone = "Player 01:Ball";
                            if (data.GetName().Contains("_P0"))
                            {
                                if (data.GetName().Contains("_P01"))
                                {
                                    referenceData = data;
                                }
                                else if (GetID(data) == GetID(referenceData))
                                {
                                    data.SampleTransformations(referenceData, referenceBone);
                                }
                                else
                                {
                                    Debug.LogError("Skipping asset " + data.GetName() + " as information of P01 is not of same capture.");
                                }
                            }
                            else
                            {
                                Debug.LogError("Skipping asset " + data.GetName() + " as it does not contain player information.");
                            }
                        }

                        {
                            RootModule root = data.AddModule <RootModule>();
                            root.Root          = data.Source.FindBone("Player 01:Hips").Index;
                            root.RightShoulder = data.Source.FindBone("Player 01:LeftShoulder").Index;
                            root.LeftShoulder  = data.Source.FindBone("Player 01:RightShoulder").Index;
                            root.RightHip      = data.Source.FindBone("Player 01:LeftUpLeg").Index;
                            root.LeftHip       = data.Source.FindBone("Player 01:RightUpLeg").Index;
                            root.Neck          = data.Source.FindBone("Player 01:Neck").Index;
                            root.Hips          = data.Source.FindBone("Player 01:Hips").Index;
                            root.Smooth        = true;
                            root.Topology      = RootModule.TOPOLOGY.Biped;
                            root.ForwardAxis   = Axis.XPositive;
                        }

                        {
                            ContactModule contact = data.AddModule <ContactModule>();
                            contact.Clear();
                            contact.AddSensor("Player 01:LeftFootEnd", "Player 01:LeftFootEnd", Vector3.zero, 0.075f, 1f, -1);
                            contact.AddSensor("Player 01:RightFootEnd", "Player 01:RightFootEnd", Vector3.zero, 0.075f, 1f, -1);
                            contact.AddSensor("Player 01:LeftHand", "Player 01:LeftHand", new Vector3(-0.1f, 0f, 0f), 0.075f, 0f, -1);
                            contact.AddSensor("Player 01:RightHand", "Player 01:RightHand", new Vector3(-0.1f, 0f, 0f), 0.075f, 0f, -1);
                            contact.AddSensor("Player 01:Ball", "Player 01:Ball", Vector3.zero, 0.2f, 0f, LayerMask.GetMask("Ground"));
                            contact.CaptureContacts(Editor);
                        }

                        {
                            DribbleModule dribble = data.AddModule <DribbleModule>();
                            dribble.Area   = 2.5f;
                            dribble.Radius = 0.125f;
                            dribble.Axis   = Axis.YPositive;
                            Matrix4x4[] motion = dribble.CleanupBallTransformations(false);
                            for (int i = 0; i < data.Frames.Length; i++)
                            {
                                data.Frames[i].Transformations[dribble.Ball] = motion[i];
                            }
                            data.GetModule <ContactModule>().CaptureContacts(Editor);
                        }

                        {
                            StyleModule   style   = data.AddModule <StyleModule>();
                            RootModule    root    = data.GetModule <RootModule>();
                            DribbleModule dribble = data.GetModule <DribbleModule>();
                            style.Clear();
                            StyleModule.StyleFunction standing  = style.AddStyle("Stand");
                            StyleModule.StyleFunction moving    = style.AddStyle("Move");
                            StyleModule.StyleFunction dribbling = style.AddStyle("Dribble");
                            StyleModule.StyleFunction holding   = style.AddStyle("Hold");
                            StyleModule.StyleFunction shooting  = style.AddStyle("Shoot");
                            float threshold = 1f;
                            for (int f = 0; f < data.Frames.Length; f++)
                            {
                                float[] timestamps = data.SimulateTimestamps(data.Frames[f], 30);
                                float[] weights    = new float[timestamps.Length];
                                for (int j = 0; j < timestamps.Length; j++)
                                {
                                    weights[j] = Mathf.Clamp(root.GetRootVelocity(timestamps[j], false).magnitude, 0f, threshold);
                                    weights[j] = weights[j].Normalize(0f, threshold, 0, 1f);
                                    weights[j] = weights[j].SmoothStep(2f, 0.5f);
                                }
                                float weight = weights.Gaussian().SmoothStep(2f, 0.5f);
                                standing.Values[f]  = 1f - weight;
                                moving.Values[f]    = weight;
                                dribbling.Values[f] = dribble.IsDribbling(data.Frames[f].Timestamp, false) ? 1f : 0f;
                                holding.Values[f]   = dribble.IsHolding(data.Frames[f].Timestamp, false) ? 1f : 0f;
                                shooting.Values[f]  = dribble.IsShooting(data.Frames[f].Timestamp, false) ? 1f : 0f;
                            }
                            style.Mode = StyleModule.DRAWING.Frames;
                            style.GenerateKeys();
                        }

                        {
                            PhaseModule   phase   = data.AddModule <PhaseModule>();
                            ContactModule contact = data.GetModule <ContactModule>();
                            phase.Inspect = true;
                            phase.SetFunctions(contact.GetNames());
                            phase.ShowNormalized   = true;
                            phase.ShowHighlighted  = true;
                            phase.ShowValues       = true;
                            phase.ShowFitting      = true;
                            phase.ShowZero         = true;
                            phase.ShowPhase        = true;
                            phase.ShowWindow       = false;
                            phase.DisplayValues    = false;
                            phase.MaxIterations    = 50;
                            phase.Individuals      = 50;
                            phase.Elites           = 5;
                            phase.Exploration      = 0.2f;
                            phase.Memetism         = 0.1f;
                            phase.MaxFrequency     = 4f;
                            phase.RescalingMethod  = PhaseModule.Rescaling.Window;
                            phase.ApplyButterworth = true;
                            phase.StartFitting();
                            while (phase.IsFitting())
                            {
                                yield return(new WaitForSeconds(0f));
                            }
                        }

                        //END OF PROCESSING
                        data.MarkDirty();
                        a.Processed = true;
                    }
                }
                foreach (Asset a in Assets)
                {
                    if (a.Selected)
                    {
                        MotionData data = Editor.LoadData(a.GUID);
                        while (!data.GetScene().isLoaded)
                        {
                            Debug.Log("Waiting for scene being loaded...");
                            yield return(new WaitForSeconds(0f));
                        }
                        //START OF PROCESSING

                        data.GetModule <DribbleModule>().ComputeInteraction();

                        //END OF PROCESSING
                        if (SaveAfterProcessing)
                        {
                            data.MarkDirty(true, !OfflineProcessing);
                        }
                        a.Processed = true;
                        yield return(new WaitForSeconds(0f));
                    }
                }
                if (SaveAfterProcessing)
                {
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();
                }
            }

            if (Pipeline == PIPELINE.Quadruped)
            {
                foreach (Asset a in Assets)
                {
                    if (a.Selected)
                    {
                        count += 1;
                        MotionData data = OfflineProcessing ? Editor.GetAsset(a.GUID) : Editor.LoadData(a.GUID);
                        while (!OfflineProcessing && !data.GetScene().isLoaded)
                        {
                            Debug.Log("Waiting for scene being loaded...");
                            yield return(new WaitForSeconds(0f));
                        }
                        // START OF PROCESSING

                        // Reset motion data
                        foreach (Frame frame in data.Frames)
                        {
                            frame.ResetTransformations();
                        }

                        // Global
                        data.RemoveAllModules();
                        data.Scale      = 0.01f;
                        data.MirrorAxis = Axis.ZPositive;
                        data.Source.FindBone("Head").Alignment      = new Vector3(90f, 0f, 0f);
                        data.Source.FindBone("Tail").Alignment      = new Vector3(-45f, 0f, 0f);
                        data.Source.FindBone("Tail1").Alignment     = new Vector3(-45f, 0f, 0f);
                        data.Source.FindBone("Tail1Site").Alignment = new Vector3(-45f, 0f, 0f);

                        {
                            ContactModule contact = data.AddModule <ContactModule>();
                            contact.Clear();
                            contact.AddSensor("Hips", "Hips", Vector3.zero, 0.2f, 1f, LayerMask.GetMask("Ground"));
                            contact.AddSensor("Neck", "Neck", Vector3.zero, 0.25f, 1f, LayerMask.GetMask("Ground"));
                            contact.AddSensor("LeftHandSite", new string[] { "LeftForeArm", "LeftHandSite" }, Vector3.zero, 1f / 30f, 1f, LayerMask.GetMask("Ground"));
                            contact.AddSensor("RightHandSite", new string[] { "RightForeArm", "RightHandSite" }, Vector3.zero, 1f / 30f, 1f, LayerMask.GetMask("Ground"));
                            contact.AddSensor("LeftFootSite", "LeftFootSite", Vector3.zero, 1f / 30f, 1f, LayerMask.GetMask("Ground"));
                            contact.AddSensor("RightFootSite", "RightFootSite", Vector3.zero, 1f / 30f, 1f, LayerMask.GetMask("Ground"));
                            contact.CaptureContacts(Editor);
                        }

                        {
                            StyleModule style = data.AddModule <StyleModule>();
                            RootModule  root  = data.AddModule <RootModule>();
                            root.Topology = RootModule.TOPOLOGY.Quadruped;
                            ContactModule contact = data.GetModule <ContactModule>();
                            style.Clear();
                            StyleModule.StyleFunction idling   = style.AddStyle("Idle");
                            StyleModule.StyleFunction moving   = style.AddStyle("Move");
                            StyleModule.StyleFunction sitting  = style.AddStyle("Sit");
                            StyleModule.StyleFunction resting  = style.AddStyle("Rest");
                            StyleModule.StyleFunction standing = style.AddStyle("Stand");
                            StyleModule.StyleFunction jumping  = style.AddStyle("Jump");
                            StyleModule.StyleFunction speed    = style.AddStyle("Speed");
                            float[]        timeWindow          = data.GetTimeWindow(MotionEditor.GetInstance().PastWindow + MotionEditor.GetInstance().FutureWindow, 1f);
                            float[]        contactHeights      = new float[data.Frames.Length];
                            List <float[]> sitPatterns         = new List <float[]>()
                            {
                                new float[] { 1f, 0f, 1f, 1f, 1f, 1f },
                                new float[] { 1f, 0f, 0f, 1f, 1f, 1f },
                                new float[] { 1f, 0f, 1f, 0f, 1f, 1f }
                            };
                            List <float[]> restPatterns = new List <float[]>()
                            {
                                new float[] { 1f, 1f, 1f, 1f, 1f, 1f }
                            };
                            List <float[]> standPatterns = new List <float[]>()
                            {
                                new float[] { 1f, 0f, 0f, 0f, 1f, 1f }
                            };
                            List <float[]> jumpPatterns = new List <float[]>()
                            {
                                new float[] { 0f, 0f, 0f, 0f, 0f, 0f }
                            };
                            for (int i = 0; i < data.Frames.Length; i++)
                            {
                                for (int j = 0; j < contact.Sensors.Length; j++)
                                {
                                    contactHeights[i] += data.Frames[i].GetBoneTransformation(contact.Sensors[j].Bones.Last(), false).GetPosition().y;
                                }
                                contactHeights[i] /= contact.Sensors.Length;
                            }
                            for (int f = 0; f < data.Frames.Length; f++)
                            {
                                float weight = GetMovementWeight(data.Frames[f].Timestamp, 0.5f, 0.5f);
                                idling.Values[f] = 1f - weight;
                                moving.Values[f] = weight;
                                float   sit     = GetContactsWeight(data.Frames[f].Timestamp, 0.5f, contact, sitPatterns, 0f, 1f);
                                float   rest    = GetContactsWeight(data.Frames[f].Timestamp, 0.5f, contact, restPatterns, 0f, 1f);
                                float   stand   = GetContactsWeight(data.Frames[f].Timestamp, 0.5f, contact, standPatterns, 0f, 1f);
                                float   jump    = GetContactsWeight(data.Frames[f].Timestamp, 0.5f, contact, jumpPatterns, 0.3f, 0.1f);
                                float[] actions = new float[] { sit, rest, stand, jump };
                                Utility.SoftMax(ref actions);
                                sitting.Values[f]  = sit;
                                resting.Values[f]  = rest;
                                standing.Values[f] = stand;
                                jumping.Values[f]  = jump;
                                speed.Values[f]    = GetRootSpeed(data.Frames[f].Timestamp);
                            }

                            float GetRootSpeed(float timestamp)
                            {
                                return(Compute());

                                float Compute()
                                {
                                    Vector3[] positions = new Vector3[timeWindow.Length];
                                    for (int i = 0; i < timeWindow.Length; i++)
                                    {
                                        positions[i] = root.GetRootPosition(timestamp + timeWindow[i], false);
                                    }
                                    float length = 0f;

                                    for (int i = 1; i < positions.Length; i++)
                                    {
                                        length += Vector3.Distance(positions[i - 1], positions[i]);
                                    }
                                    return(length / (timeWindow.Last() - timeWindow.First()));
                                }
                            }

                            float GetMovementWeight(float timestamp, float window, float threshold)
                            {
                                float[] weights = new float[timeWindow.Length];
                                for (int j = 0; j < timeWindow.Length; j++)
                                {
                                    weights[j] = Mathf.Clamp(root.GetRootVelocity(timestamp + timeWindow[j], false).magnitude, 0f, threshold) / threshold;
                                }

                                float[] gradients = new float[weights.Length - 1];
                                for (int i = 0; i < gradients.Length; i++)
                                {
                                    gradients[i] = (weights[i + 1] - weights[i]) / (timeWindow[i + 1] - timeWindow[i]);
                                }
                                float gradient = Mathf.Abs(gradients.Gaussian());

                                return(weights.Gaussian(gradient).SmoothStep(2f, 0.5f));
                            }

                            float GetContactsWeight(float timestamp, float window, ContactModule module, List <float[]> patterns, float heightThreshold, float power)
                            {
                                float ContactGaussian(float t)
                                {
                                    float[] weights = new float[timeWindow.Length];
                                    for (int j = 0; j < timeWindow.Length; j++)
                                    {
                                        bool match = false;
                                        for (int i = 0; i < patterns.Count; i++)
                                        {
                                            float[] contacts = module.GetContacts(t + timeWindow[j], false);
                                            match = ArrayExtensions.Equal(contacts, patterns[i]).All(true);
                                            if (match)
                                            {
                                                break;
                                            }
                                        }
                                        if (match && heightThreshold != 0f && contactHeights[data.GetFrame(t).Index - 1] < heightThreshold)
                                        {
                                            match = false;
                                        }
                                        weights[j] = match ? 1f : 0f;
                                    }
                                    return(weights.Gaussian());
                                }

                                float weight = ContactGaussian(timestamp);

                                weight = Mathf.Pow(weight, 1f - weight);
                                return(Mathf.Pow(weight, power));
                            }

                            style.Mode = StyleModule.DRAWING.Frames;
                        }

                        {
                            PhaseModule phase = data.AddModule <PhaseModule>();
                            phase.Inspect = true;
                            RootModule    root    = data.GetModule <RootModule>();
                            ContactModule contact = data.GetModule <ContactModule>();
                            phase.SetFunctions(contact.GetNames());
                            phase.ShowNormalized   = true;
                            phase.ShowHighlighted  = true;
                            phase.ShowValues       = true;
                            phase.ShowFitting      = true;
                            phase.ShowZero         = true;
                            phase.ShowPhase        = true;
                            phase.ShowWindow       = false;
                            phase.DisplayValues    = false;
                            phase.MaxIterations    = 50;
                            phase.Individuals      = 100;
                            phase.Elites           = 10;
                            phase.Exploration      = 0.2f;
                            phase.Memetism         = 0.1f;
                            phase.MaxFrequency     = 4f;
                            phase.RescalingMethod  = PhaseModule.Rescaling.Window;
                            phase.ApplyButterworth = true;

                            phase.StartFitting();
                            while (phase.IsFitting())
                            {
                                yield return(new WaitForSeconds(0f));
                            }
                        }

                        //END OF PROCESSING
                        if (SaveAfterProcessing)
                        {
                            data.MarkDirty(true, !OfflineProcessing);
                        }
                        a.Processed = true;
                        yield return(new WaitForSeconds(0f));
                    }
                }

                for (int i = 0; i < Editor.Assets.Length; i++)
                {
                    Editor.GetAsset(i).ResetSequences();
                    Editor.GetAsset(i).Export = false;
                }
                Editor.GetAsset(0).Export = true;
                Editor.GetAsset(0).SetSequence(0, 180, 1531);
                Editor.GetAsset(2).Export = true;
                Editor.GetAsset(2).SetSequence(0, 680, 820);
                Editor.GetAsset(6).Export = true;
                Editor.GetAsset(6).SetSequence(0, 90, 593);
                Editor.GetAsset(7).Export = true;
                Editor.GetAsset(7).SetSequence(0, 290, 1072);
                Editor.GetAsset(8).Export = true;
                Editor.GetAsset(8).SetSequence(0, 1, 50);
                Editor.GetAsset(8).SetSequence(1, 400, 911);
                Editor.GetAsset(9).Export  = true;
                Editor.GetAsset(10).Export = true;
                Editor.GetAsset(10).SetSequence(0, 230, 548);
                Editor.GetAsset(11).Export = true;
                Editor.GetAsset(11).SetSequence(0, 400, 567);
                Editor.GetAsset(12).Export = true;
                Editor.GetAsset(13).Export = true;
                Editor.GetAsset(14).Export = true;
                Editor.GetAsset(16).Export = true;
                Editor.GetAsset(16).SetSequence(0, 200, 550);
                Editor.GetAsset(17).Export = true;
                Editor.GetAsset(17).SetSequence(0, 470, 720);
                Editor.GetAsset(18).Export = true;
                Editor.GetAsset(18).SetSequence(0, 175, 395);
                Editor.GetAsset(19).Export = true;
                Editor.GetAsset(19).SetSequence(0, 300, 750);
                Editor.GetAsset(19).SetSequence(1, 1040, 1079);
                Editor.GetAsset(20).Export = true;
                Editor.GetAsset(21).Export = true;
                Editor.GetAsset(21).SetSequence(0, 1, 1300);
                Editor.GetAsset(21).SetSequence(1, 2950, 3530);
                Editor.GetAsset(21).SetSequence(2, 3730, 4200);
                Editor.GetAsset(22).Export = true;
                Editor.GetAsset(23).Export = true;
                Editor.GetAsset(23).Export = true;
                Editor.GetAsset(24).Export = true;
                Editor.GetAsset(24).SetSequence(0, 200, 630);
                Editor.GetAsset(25).Export = true;
                Editor.GetAsset(25).SetSequence(0, 1, 2690);
                Editor.GetAsset(25).SetSequence(1, 2760, 4336);
                Editor.GetAsset(26).Export = true;
                Editor.GetAsset(27).Export = true;
                Editor.GetAsset(27).SetSequence(0, 1, 1100);
                Editor.GetAsset(27).SetSequence(1, 2820, 3940);
                Editor.GetAsset(27).SetSequence(2, 4100, 4500);
                Editor.GetAsset(27).SetSequence(3, 5660, 6010);
                Editor.GetAsset(27).SetSequence(4, 6600, 7200);
                Editor.GetAsset(27).SetSequence(5, 12300, 12850);
                Editor.GetAsset(27).SetSequence(6, 13200, 13399);
                Editor.GetAsset(28).Export = true;
                Editor.GetAsset(28).SetSequence(0, 920, 985);
                Editor.GetAsset(28).SetSequence(1, 1700, 1907);
                Editor.GetAsset(29).Export = true;
                Editor.GetAsset(29).SetSequence(0, 250, 790);
                Editor.GetAsset(29).SetSequence(1, 970, 1575);
                Editor.GetAsset(29).SetSequence(2, 1630, 1750);
                Editor.GetAsset(30).Export = true;
                Editor.GetAsset(30).SetSequence(0, 1790, 1920);
                Editor.GetAsset(30).SetSequence(1, 2070, 2470);
                Editor.GetAsset(30).SetSequence(2, 2770, 3025);
                Editor.GetAsset(31).Export = true;
                Editor.GetAsset(31).SetSequence(0, 170, 500);
                Editor.GetAsset(31).SetSequence(1, 1250, 2460);
                Editor.GetAsset(31).SetSequence(2, 3040, 3200);
                Editor.GetAsset(31).SetSequence(3, 4680, 6550);
                Editor.GetAsset(31).SetSequence(4, 7600, 9450);
                Editor.GetAsset(31).SetSequence(5, 11540, 11691);
                Editor.GetAsset(32).Export = true;
                Editor.GetAsset(32).SetSequence(0, 1, 300);
                Editor.GetAsset(32).SetSequence(1, 1360, 1540);
                Editor.GetAsset(32).SetSequence(2, 2380, 3086);
                Editor.GetAsset(33).Export = true;
                Editor.GetAsset(33).SetSequence(0, 1, 1170);
                Editor.GetAsset(33).SetSequence(1, 1980, 2160);
                Editor.GetAsset(33).SetSequence(2, 7830, 8090);
                Editor.GetAsset(34).Export = true;
                Editor.GetAsset(34).SetSequence(0, 1, 270);
                Editor.GetAsset(34).SetSequence(1, 2490, 2856);
                Editor.GetAsset(35).Export = true;
                Editor.GetAsset(37).Export = true;
                Editor.GetAsset(38).Export = true;
                Editor.GetAsset(38).SetSequence(0, 3330, 3900);
                Editor.GetAsset(39).Export = true;
                Editor.GetAsset(39).SetSequence(0, 880, 920);
                Editor.GetAsset(39).SetSequence(1, 1280, 5052);
                Editor.GetAsset(41).Export = true;
                Editor.GetAsset(41).SetSequence(0, 4690, 6190);
                Editor.GetAsset(42).Export = true;
                Editor.GetAsset(42).SetSequence(0, 900, 3594);
                Editor.GetAsset(43).Export = true;
                Editor.GetAsset(43).SetSequence(0, 1, 500);
                Editor.GetAsset(43).SetSequence(1, 4340, 4577);
                Editor.GetAsset(44).Export = true;
                Editor.GetAsset(44).SetSequence(0, 1, 700);
                Editor.GetAsset(44).SetSequence(1, 950, 2000);
                Editor.GetAsset(45).Export = true;
                Editor.GetAsset(45).SetSequence(0, 1, 410);
                Editor.GetAsset(45).SetSequence(1, 680, 778);
                Editor.GetAsset(46).Export = true;
                Editor.GetAsset(46).SetSequence(0, 175, 235);
                Editor.GetAsset(47).Export = true;
                Editor.GetAsset(47).SetSequence(0, 275, 498);
                Editor.GetAsset(48).Export = true;
                Editor.GetAsset(48).SetSequence(0, 1, 220);
                Editor.GetAsset(48).SetSequence(1, 675, 748);
                Editor.GetAsset(49).Export = true;
                Editor.GetAsset(49).SetSequence(0, 1, 700);
                Editor.GetAsset(49).SetSequence(1, 1510, 8300);
                Editor.GetAsset(50).Export = true;
                Editor.GetAsset(50).SetSequence(0, 200, 1000);
                Editor.GetAsset(50).SetSequence(1, 1850, 2100);
                Editor.GetAsset(50).SetSequence(2, 4150, 4700);
                Editor.GetAsset(50).SetSequence(3, 5030, 5356);

                //Mark for saving
                for (int i = 0; i < Editor.Assets.Length; i++)
                {
                    Editor.GetAsset(i).MarkDirty(true, false);
                }

                if (SaveAfterProcessing)
                {
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();
                }
            }

            Processing = false;
            foreach (Asset a in Assets)
            {
                a.Processed = false;
            }
            yield return(new WaitForSeconds(0f));

            Debug.Log("Finished processing " + count + " assets.");
        }
    }
Example #11
0
 public void AddDuration(decimal duration)
 {
     this.Items            = ArrayExtensions.ArrayAppend(this.Items, duration);
     this.ItemsElementName = ArrayExtensions.ArrayAppend(this.ItemsElementName, ItemsChoiceType1.duration);
 }
 private void _NullArrayInsideTestBody()
 {
     int[][] input = { null, new int[] { -91, 29, 37, 4, 0 }, new int[] { -31, 256, 3, 8, 45 } };
     ArrayExtensions.DoBubbleSort(input);
 }
 private void _NullArrayTestBody()
 {
     int[][] input = null;
     ArrayExtensions.DoBubbleSort(input);
 }
Example #14
0
        public static void CreateBundle(string bundleUrl, IOdbBackend backend, ObjectId[] objectIds, ISet <ObjectId> disableCompressionIds, Dictionary <string, ObjectId> indexMap, IList <string> dependencies, bool useIncrementalBundle)
        {
            if (objectIds.Length == 0)
            {
                throw new InvalidOperationException("Nothing to pack.");
            }

            var objectsToIndex = new Dictionary <ObjectId, int>(objectIds.Length);

            var objects = new List <KeyValuePair <ObjectId, ObjectInfo> >();

            for (int i = 0; i < objectIds.Length; ++i)
            {
                objectsToIndex.Add(objectIds[i], objects.Count);
                objects.Add(new KeyValuePair <ObjectId, ObjectInfo>(objectIds[i], new ObjectInfo()));
            }

            var incrementalBundles = new List <ObjectId>();

            // If there is a .bundle, add incremental id before it
            var bundleExtensionLength = (bundleUrl.EndsWith(BundleExtension) ? BundleExtension.Length : 0);

            // Early exit if package didn't change (header-check only)
            if (VirtualFileSystem.FileExists(bundleUrl))
            {
                try
                {
                    using (var packStream = VirtualFileSystem.OpenStream(bundleUrl, VirtualFileMode.Open, VirtualFileAccess.Read))
                    {
                        var bundle = ReadBundleDescription(packStream);

                        // If package didn't change since last time, early exit!
                        if (ArrayExtensions.ArraysEqual(bundle.Dependencies, dependencies) &&
                            ArrayExtensions.ArraysEqual(bundle.Assets.OrderBy(x => x.Key).ToList(), indexMap.OrderBy(x => x.Key).ToList()) &&
                            ArrayExtensions.ArraysEqual(bundle.Objects.Select(x => x.Key).OrderBy(x => x).ToList(), objectIds.OrderBy(x => x).ToList()))
                        {
                            // Make sure all incremental bundles exist
                            // Also, if we don't want incremental bundles but we have some (or vice-versa), let's force a regeneration
                            if ((useIncrementalBundle == (bundle.IncrementalBundles.Count > 0)) &&
                                bundle.IncrementalBundles.Select(x => bundleUrl.Insert(bundleUrl.Length - bundleExtensionLength, "." + x)).All(x =>
                            {
                                if (!VirtualFileSystem.FileExists(x))
                                {
                                    return(false);
                                }
                                using (var incrementalStream = VirtualFileSystem.OpenStream(x, VirtualFileMode.Open, VirtualFileAccess.Read))
                                    return(ValidateHeader(incrementalStream));
                            }))
                            {
                                return;
                            }
                        }
                    }

                    // Process existing incremental bundles one by one
                    // Try to find if there is enough to reuse in each of them
                    var filename  = VirtualFileSystem.GetFileName(bundleUrl);
                    var directory = VirtualFileSystem.GetParentFolder(bundleUrl);

                    foreach (var incrementalBundleUrl in VirtualFileSystem.ListFiles(directory, filename.Insert(filename.Length - bundleExtensionLength, ".*"), VirtualSearchOption.TopDirectoryOnly).Result)
                    {
                        var      incrementalIdString = incrementalBundleUrl.Substring(incrementalBundleUrl.Length - bundleExtensionLength - ObjectId.HashStringLength, ObjectId.HashStringLength);
                        ObjectId incrementalId;
                        if (!ObjectId.TryParse(incrementalIdString, out incrementalId))
                        {
                            continue;
                        }

                        // If we don't want incremental bundles, delete old ones from previous build
                        if (!useIncrementalBundle)
                        {
                            VirtualFileSystem.FileDelete(incrementalBundleUrl);
                            continue;
                        }

                        long sizeNeededItems = 0;
                        long sizeTotal       = 0;

                        BundleDescription incrementalBundle;
                        try
                        {
                            using (var packStream = VirtualFileSystem.OpenStream(incrementalBundleUrl, VirtualFileMode.Open, VirtualFileAccess.Read))
                            {
                                incrementalBundle = ReadBundleDescription(packStream);
                            }

                            // Compute size of objects (needed ones and everything)
                            foreach (var @object in incrementalBundle.Objects)
                            {
                                var objectCompressedSize = @object.Value.EndOffset - @object.Value.StartOffset;

                                // TODO: Detect object that are stored without ObjectId being content hash: we need to check actual content hash is same in this case
                                if (objectsToIndex.ContainsKey(@object.Key))
                                {
                                    sizeNeededItems += objectCompressedSize;
                                }
                                sizeTotal += objectCompressedSize;
                            }

                            // Check if we would reuse at least 50% of the incremental bundle, otherwise let's just get rid of it
                            var reuseRatio = (float)((double)sizeNeededItems / (double)sizeTotal);
                            if (reuseRatio < 0.5f)
                            {
                                VirtualFileSystem.FileDelete(incrementalBundleUrl);
                            }
                            else
                            {
                                // We will reuse this incremental bundle
                                // Let's add ObjectId entries
                                foreach (var @object in incrementalBundle.Objects)
                                {
                                    int objectIndex;
                                    if (objectsToIndex.TryGetValue(@object.Key, out objectIndex))
                                    {
                                        var objectInfo = @object.Value;
                                        objectInfo.IncrementalBundleIndex = incrementalBundles.Count + 1;
                                        objects[objectIndex] = new KeyValuePair <ObjectId, ObjectInfo>(@object.Key, objectInfo);
                                    }
                                }

                                // Add this incremental bundle in the list
                                incrementalBundles.Add(incrementalId);
                            }
                        }
                        catch (Exception)
                        {
                            // Could not read incremental bundle (format changed?)
                            // Let's delete it
                            VirtualFileSystem.FileDelete(incrementalBundleUrl);
                        }
                    }
                }
                catch (Exception)
                {
                    // Could not read previous bundle (format changed?)
                    // Let's just mute this error as new bundle will overwrite it anyway
                }
            }

            // Count objects which needs to be saved
            var incrementalObjects = new List <KeyValuePair <ObjectId, ObjectInfo> >();

            if (useIncrementalBundle)
            {
                for (int i = 0; i < objectIds.Length; ++i)
                {
                    // Skip if already part of an existing incremental package
                    if (objects[i].Value.IncrementalBundleIndex > 0)
                    {
                        continue;
                    }

                    incrementalObjects.Add(new KeyValuePair <ObjectId, ObjectInfo>(objects[i].Key, new ObjectInfo()));
                }
            }

            // Create an incremental package
            var newIncrementalId       = ObjectId.New();
            var incrementalBundleIndex = incrementalBundles.Count;

            if (useIncrementalBundle && incrementalObjects.Count > 0)
            {
                incrementalBundles.Add(newIncrementalId);
            }

            using (var packStream = VirtualFileSystem.OpenStream(bundleUrl, VirtualFileMode.Create, VirtualFileAccess.Write))
            {
                var header = new Header();
                header.MagicHeader = Header.MagicHeaderValid;

                var packBinaryWriter = new BinarySerializationWriter(packStream);
                packBinaryWriter.Write(header);
                // Write dependencies
                packBinaryWriter.Write(dependencies.ToList());
                // Write inecremental bundles
                packBinaryWriter.Write(incrementalBundles.ToList());

                // Save location of object ids
                var packObjectIdPosition = packStream.Position;

                // Write empty object ids (reserve space, will be rewritten later)
                packBinaryWriter.Write(objects);

                // Write index
                packBinaryWriter.Write(indexMap.ToList());

                using (var incrementalStream = incrementalObjects.Count > 0 ? VirtualFileSystem.OpenStream(bundleUrl.Insert(bundleUrl.Length - bundleExtensionLength, "." + newIncrementalId), VirtualFileMode.Create, VirtualFileAccess.Write) : null)
                {
                    var  incrementalBinaryWriter     = incrementalStream != null ? new BinarySerializationWriter(incrementalStream) : null;
                    long incrementalObjectIdPosition = 0;
                    if (incrementalStream != null)
                    {
                        incrementalBinaryWriter.Write(header);
                        // Write dependencies
                        incrementalBinaryWriter.Write(new List <string>());
                        // Write inecremental bundles
                        incrementalBinaryWriter.Write(new List <ObjectId>());

                        // Save location of object ids
                        incrementalObjectIdPosition = incrementalStream.Position;

                        // Write empty object ids (reserve space, will be rewritten later)
                        incrementalBinaryWriter.Write(incrementalObjects);

                        // Write index
                        incrementalBinaryWriter.Write(new List <KeyValuePair <string, ObjectId> >());
                    }

                    var objectOutputStream     = incrementalStream ?? packStream;
                    int incrementalObjectIndex = 0;
                    for (int i = 0; i < objectIds.Length; ++i)
                    {
                        // Skip if already part of an existing incremental package
                        if (objects[i].Value.IncrementalBundleIndex > 0)
                        {
                            continue;
                        }

                        using (var objectStream = backend.OpenStream(objectIds[i]))
                        {
                            // Prepare object info
                            var objectInfo = new ObjectInfo {
                                StartOffset = objectOutputStream.Position, SizeNotCompressed = objectStream.Length
                            };

                            // re-order the file content so that it is not necessary to seek while reading the input stream (header/object/refs -> header/refs/object)
                            var inputStream          = objectStream;
                            var originalStreamLength = objectStream.Length;
                            var streamReader         = new BinarySerializationReader(inputStream);
                            var chunkHeader          = ChunkHeader.Read(streamReader);
                            if (chunkHeader != null)
                            {
                                // create the reordered stream
                                var reorderedStream = new MemoryStream((int)originalStreamLength);

                                // copy the header
                                var streamWriter = new BinarySerializationWriter(reorderedStream);
                                chunkHeader.Write(streamWriter);

                                // copy the references
                                var newOffsetReferences = reorderedStream.Position;
                                inputStream.Position = chunkHeader.OffsetToReferences;
                                inputStream.CopyTo(reorderedStream);

                                // copy the object
                                var newOffsetObject = reorderedStream.Position;
                                inputStream.Position = chunkHeader.OffsetToObject;
                                inputStream.CopyTo(reorderedStream, chunkHeader.OffsetToReferences - chunkHeader.OffsetToObject);

                                // rewrite the chunk header with correct offsets
                                chunkHeader.OffsetToObject     = (int)newOffsetObject;
                                chunkHeader.OffsetToReferences = (int)newOffsetReferences;
                                reorderedStream.Position       = 0;
                                chunkHeader.Write(streamWriter);

                                // change the input stream to use reordered stream
                                inputStream          = reorderedStream;
                                inputStream.Position = 0;
                            }

                            // compress the stream
                            if (!disableCompressionIds.Contains(objectIds[i]))
                            {
                                objectInfo.IsCompressed = true;

                                var lz4OutputStream = new LZ4Stream(objectOutputStream, CompressionMode.Compress);
                                inputStream.CopyTo(lz4OutputStream);
                                lz4OutputStream.Flush();
                            }
                            else // copy the stream "as is"
                            {
                                // Write stream
                                inputStream.CopyTo(objectOutputStream);
                            }

                            // release the reordered created stream
                            if (chunkHeader != null)
                            {
                                inputStream.Dispose();
                            }

                            // Add updated object info
                            objectInfo.EndOffset = objectOutputStream.Position;
                            // Note: we add 1 because 0 is reserved for self; first incremental bundle starts at 1
                            objectInfo.IncrementalBundleIndex = objectOutputStream == incrementalStream ? incrementalBundleIndex + 1 : 0;
                            objects[i] = new KeyValuePair <ObjectId, ObjectInfo>(objectIds[i], objectInfo);

                            if (useIncrementalBundle)
                            {
                                // Also update incremental bundle object info
                                objectInfo.IncrementalBundleIndex            = 0; // stored in same bundle
                                incrementalObjects[incrementalObjectIndex++] = new KeyValuePair <ObjectId, ObjectInfo>(objectIds[i], objectInfo);
                            }
                        }
                    }

                    // First finish to write incremental package so that main one can't be valid on the HDD without the incremental one being too
                    if (incrementalStream != null)
                    {
                        // Rewrite headers
                        header.Size = incrementalStream.Length;
                        incrementalStream.Position = 0;
                        incrementalBinaryWriter.Write(header);

                        // Rewrite object with updated offsets/size
                        incrementalStream.Position = incrementalObjectIdPosition;
                        incrementalBinaryWriter.Write(incrementalObjects);
                    }
                }

                // Rewrite headers
                header.Size         = packStream.Length;
                packStream.Position = 0;
                packBinaryWriter.Write(header);

                // Rewrite object with updated offsets/size
                packStream.Position = packObjectIdPosition;
                packBinaryWriter.Write(objects);
            }
        }
Example #15
0
    public void Repair(MotionEditor editor)
    {
        //Repair
        for (int i = 0; i < Modules.Length; i++)
        {
            if (Modules[i] == null)
            {
                ArrayExtensions.RemoveAt(ref Modules, i);
                i--;
            }
        }
        Object[] objects = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(this));
        foreach (Object o in objects)
        {
            if (o is Module)
            {
                if (ArrayExtensions.Contains(ref Modules, (Module)o))
                {
                    //	Debug.Log(((Module)o).Type().ToString() + " contained.");
                }
                else
                {
                    ArrayExtensions.Add(ref Modules, (Module)o);
                    //	Debug.Log(((Module)o).Type().ToString() + " missing.");
                }
            }
        }

        //Repair
        StyleModule styleModule = (StyleModule)GetModule(Module.TYPE.Style);

        if (styleModule != null)
        {
            if (styleModule.Keys.Length != styleModule.Data.GetTotalFrames())
            {
                styleModule.Keys    = new bool[styleModule.Data.GetTotalFrames()];
                styleModule.Keys[0] = true;
                styleModule.Keys[styleModule.Keys.Length - 1] = true;
                for (int i = 1; i < styleModule.Keys.Length - 1; i++)
                {
                    for (int j = 0; j < styleModule.Functions.Length; j++)
                    {
                        if (styleModule.Functions[j].Values[i] == 0f && styleModule.Functions[j].Values[i + 1] != 0f)
                        {
                            styleModule.Keys[i] = true;
                        }
                        if (styleModule.Functions[j].Values[i] == 1f && styleModule.Functions[j].Values[i + 1] != 1f)
                        {
                            styleModule.Keys[i] = true;
                        }
                        if (styleModule.Functions[j].Values[i] != 0f && styleModule.Functions[j].Values[i + 1] == 0f)
                        {
                            styleModule.Keys[i + 1] = true;
                        }
                        if (styleModule.Functions[j].Values[i] != 1f && styleModule.Functions[j].Values[i + 1] == 1f)
                        {
                            styleModule.Keys[i + 1] = true;
                        }
                    }
                }
            }
        }
        //
        //
    }
Example #16
0
        //Should return an Enumerable<RtpPacket> and should ask for bytesPerPayload.
        /// <summary>
        /// Given many packets a single packet is made in accordance with RFC2198
        /// </summary>
        /// <param name="packets"></param>
        /// <returns></returns>
        public static RtpPacket Packetize(RtpPacket[] packets) //todo needs a timestamp of the packet created...
        {
            //Make one packet with the data of all packets
            //Must also include headers which is 4 * packets.Length + 1

            int packetsLength;

            if (ArrayExtensions.IsNullOrEmpty(packets, out packetsLength))
            {
                return(null);
            }

            //4 byte headers are only needed if there are more than 1 packet.
            int headersNeeded = packetsLength - 1;

            //Calulcate the size of the single packet we will need.
            int size = RtpHeader.Length + ((4 * headersNeeded) + 1);

            //Create the packet with the known length
            RtpPacket result = new RtpPacket(new byte[size], 0); //RtpHeader.Length + 4 * packetsLength - (packetsLength * RtpHeader.Length) + 1

            int bitOffset = 0;

            int packetIndex = 0;

            bool marker = false;

            RtpPacket packet;

            int payloadDataOffset = (4 * headersNeeded) + 1;

            int blockLen;

            //For all but the last packet write a full header
            for (int e = headersNeeded; packetIndex < e; ++packetIndex)
            {
                packet = packets[packetIndex];

                //csrc Extensions and padding included...
                blockLen = packet.Payload.Count;

                //Write the payloadType
                Common.Binary.WriteBitsMSB(result.Payload.Array, ref bitOffset, (ulong)packet.PayloadType, 7);

                //Should be offset from timestamp
                Common.Binary.WriteBitsMSB(result.Payload.Array, ref bitOffset, (ulong)packet.Timestamp, 14);

                //Write the BlockLength
                Common.Binary.WriteBitsMSB(result.Payload.Array, ref bitOffset, (ulong)blockLen, 10);

                //Copy the data
                System.Array.Copy(packet.Payload.Array, packet.Payload.Offset, result.Payload.Array, payloadDataOffset, blockLen);

                //Move the payloadDataOffset for the block of data just copied.
                payloadDataOffset += blockLen;

                //If the marker was not already found check for it
                if (false == marker && packet.Marker)
                {
                    marker = true;
                }
            }

            //Write the last header (1 byte with (F)irst bit set and PayloadType

            //Get the packet
            packet = packets[packetIndex];

            //Could just write 0x80 | PayloadType at payloadStart - 1
            //result.Payload.Array[payloadStart - 1] = (byte)(0x80 | packet.PayloadType);

            //Set the (F)irst bit
            Common.Binary.WriteBitsMSB(result.Payload.Array, ref bitOffset, (ulong)1, 1);

            //Write the payloadType
            Common.Binary.WriteBitsMSB(result.Payload.Array, ref bitOffset, (ulong)packets[packetIndex].PayloadType, 7);

            //Copy the data
            System.Array.Copy(packet.Payload.Array, packet.Payload.Offset, result.Payload.Array, payloadDataOffset, packet.Payload.Count);

            //Set the Timestamp
            result.Timestamp = packet.Timestamp;

            //Set the SequenceNumber
            result.Timestamp = packet.SequenceNumber;

            //Set the marker bit if it needs to be set.
            result.Marker = marker || packet.Marker;

            //Return the single packet created.
            return(result);
        }
Example #17
0
    void OnGUI()
    {
        Scroll = EditorGUILayout.BeginScrollView(Scroll);

        Utility.SetGUIColor(UltiDraw.Black);
        using (new EditorGUILayout.VerticalScope("Box")) {
            Utility.ResetGUIColor();

            Utility.SetGUIColor(UltiDraw.Grey);
            using (new EditorGUILayout.VerticalScope("Box")) {
                Utility.ResetGUIColor();

                Utility.SetGUIColor(UltiDraw.Orange);
                using (new EditorGUILayout.VerticalScope("Box")) {
                    Utility.ResetGUIColor();
                    EditorGUILayout.LabelField("Exporter");
                }

                if (!Exporting)
                {
                    if (Utility.GUIButton("Load", UltiDraw.DarkGrey, UltiDraw.White))
                    {
                        Load();
                    }
                    EditorGUILayout.BeginHorizontal();
                    if (Utility.GUIButton("Export Input Labels", UltiDraw.DarkGrey, UltiDraw.White))
                    {
                        this.StartCoroutine(ExportInputLabels());
                    }
                    if (Utility.GUIButton("Export Output Labels", UltiDraw.DarkGrey, UltiDraw.White))
                    {
                        this.StartCoroutine(ExportOutputLabels());
                    }
                    EditorGUILayout.EndHorizontal();

                    if (Utility.GUIButton("Export Data", UltiDraw.DarkGrey, UltiDraw.White))
                    {
                        this.StartCoroutine(ExportData());
                    }

                    if (Utility.GUIButton("Export JSON", UltiDraw.DarkGrey, UltiDraw.White))
                    {
                        this.StartCoroutine(ExportJSON());
                    }

                    EditorGUILayout.BeginHorizontal();
                    if (Utility.GUIButton("Enable All", UltiDraw.DarkGrey, UltiDraw.White))
                    {
                        for (int i = 0; i < Export.Length; i++)
                        {
                            Export[i] = true;
                        }
                    }
                    if (Utility.GUIButton("Disable All", UltiDraw.DarkGrey, UltiDraw.White))
                    {
                        for (int i = 0; i < Export.Length; i++)
                        {
                            Export[i] = false;
                        }
                    }
                    EditorGUILayout.EndHorizontal();
                }
                else
                {
                    EditorGUILayout.LabelField("Generating");
                    EditorGUI.DrawRect(new Rect(EditorGUILayout.GetControlRect().x, EditorGUILayout.GetControlRect().y, Generating * EditorGUILayout.GetControlRect().width, 25f), UltiDraw.Green.Transparent(0.75f));

                    EditorGUILayout.LabelField("Writing");
                    EditorGUI.DrawRect(new Rect(EditorGUILayout.GetControlRect().x, EditorGUILayout.GetControlRect().y, Writing * EditorGUILayout.GetControlRect().width, 25f), UltiDraw.IndianRed.Transparent(0.75f));

                    if (Utility.GUIButton("Stop", UltiDraw.DarkRed, UltiDraw.White))
                    {
                        this.StopAllCoroutines();
                        Exporting = false;
                    }
                }

                Framerate = EditorGUILayout.IntField("Framerate", Framerate);
                BatchSize = Mathf.Max(1, EditorGUILayout.IntField("Batch Size", BatchSize));
                Mirror    = EditorGUILayout.Toggle("Mirror", Mirror);

                using (new EditorGUILayout.VerticalScope("Box")) {
                    for (int i = 0; i < StyleFilters.Length; i++)
                    {
                        Utility.SetGUIColor(UltiDraw.Cyan);
                        using (new EditorGUILayout.VerticalScope("Box")) {
                            Utility.ResetGUIColor();
                            StyleFilters[i].Name = EditorGUILayout.TextField("Name", StyleFilters[i].Name);
                            for (int j = 0; j < StyleFilters[i].Indices.Length; j++)
                            {
                                StyleFilters[i].Indices[j] = EditorGUILayout.IntField("ID", StyleFilters[i].Indices[j]);
                            }
                            EditorGUILayout.BeginHorizontal();
                            if (Utility.GUIButton("+", UltiDraw.DarkGrey, UltiDraw.White))
                            {
                                ArrayExtensions.Expand(ref StyleFilters[i].Indices);
                            }
                            if (Utility.GUIButton("-", UltiDraw.DarkGrey, UltiDraw.White))
                            {
                                ArrayExtensions.Shrink(ref StyleFilters[i].Indices);
                            }
                            EditorGUILayout.EndHorizontal();
                            if (Utility.GUIButton("X", UltiDraw.DarkRed, UltiDraw.White))
                            {
                                ArrayExtensions.RemoveAt(ref StyleFilters, i);
                            }
                        }
                    }

                    for (int i = 0; i < Editors.Length; i++)
                    {
                        if (Exporting)
                        {
                            Utility.SetGUIColor(UltiDraw.Mustard);
                        }
                        else
                        {
                            if (Export[i])
                            {
                                Utility.SetGUIColor(UltiDraw.DarkGreen);
                            }
                            else
                            {
                                Utility.SetGUIColor(UltiDraw.DarkRed);
                            }
                        }

                        using (new EditorGUILayout.VerticalScope("Box")) {
                            Utility.ResetGUIColor();
                            EditorGUILayout.BeginHorizontal();
                            EditorGUILayout.LabelField((i + 1).ToString(), GUILayout.Width(20f));
                            Export[i] = EditorGUILayout.Toggle(Export[i], GUILayout.Width(20f));
                            EditorGUILayout.ObjectField(Editors[i], typeof(MotionEditor), true);
                            EditorGUILayout.EndHorizontal();
                        }
                    }
                }
            }
        }

        EditorGUILayout.EndScrollView();
    }
Example #18
0
    private IEnumerator ExportData()
    {
        Exporting = true;

        StreamWriter input  = CreateFile("Input");
        StreamWriter output = CreateFile("Output");

        for (int e = 0; e < Editors.Length; e++)
        {
            if (Export[e])
            {
                MotionEditor editor = Editors[e];
                int          items  = 0;
                for (int i = 0; i < editor.GetFiles().Length; i++)
                {
                    if (editor.Files[i].Data.Export)
                    {
                        editor.LoadFile(editor.Files[i]);

                        //StyleModule styleModule = editor.GetFile().Data.GetModule(Module.TYPE.Style) == null ? null : (StyleModule)editor.GetFile().Data.GetModule(Module.TYPE.Style);
                        PhaseModule phaseModule = editor.GetFile().Data.GetModule(Module.TYPE.Phase) == null ? null : (PhaseModule)editor.GetFile().Data.GetModule(Module.TYPE.Phase);
                        //ContactModule contactModule = editor.GetFile().Data.GetModule(Module.TYPE.Contact) == null ? null : (ContactModule)editor.GetFile().Data.GetModule(Module.TYPE.Contact);

                        for (int m = 1; m <= (Mirror ? 2 : 1); m++)
                        {
                            if (m == 1)
                            {
                                editor.SetMirror(false);
                            }
                            if (m == 2)
                            {
                                editor.SetMirror(true);
                            }
                            for (int s = 0; s < editor.GetFile().Data.Sequences.Length; s++)
                            {
                                MotionData.Sequence.Interval[] intervals = editor.GetFile().Data.Sequences[s].GetIntervals();
                                for (int interval = 0; interval < intervals.Length; interval++)
                                {
                                    Generating = 0f;
                                    Writing    = 0f;

                                    List <State> states = new List <State>();
                                    float        start  = editor.GetFile().Data.GetFrame(intervals[interval].Start).Timestamp;
                                    float        end    = editor.GetFile().Data.GetFrame(intervals[interval].End).Timestamp;

                                    for (float t = start; t <= end; t += 1f / Framerate)
                                    {
                                        Generating = (t - start) / (end - start - 1f / Framerate);
                                        editor.LoadFrame(t);
                                        states.Add(editor.GetState());
                                        //Spin
                                        items += 1;
                                        if (items == BatchSize)
                                        {
                                            items = 0;
                                            yield return(new WaitForSeconds(0f));
                                        }
                                    }

                                    for (int state = 1; state < states.Count - 1; state++)
                                    {
                                        Writing = (float)(state) / (float)(states.Count - 2);
                                        State previous = states[state - 1];
                                        State next     = states[state + 1];
                                        State current  = states[state];
                                        editor.LoadFrame(current);

                                        //Input
                                        string inputLine = string.Empty;
                                        for (int k = 0; k < 12; k++)
                                        {
                                            Vector3 position  = current.Trajectory.Points[k].GetPosition().GetRelativePositionTo(current.Root);
                                            Vector3 direction = current.Trajectory.Points[k].GetDirection().GetRelativeDirectionTo(current.Root);
                                            Vector3 velocity  = current.Trajectory.Points[k].GetVelocity().GetRelativeDirectionTo(current.Root);
                                            //float speed = current.Trajectory.Points[k].GetSpeed();
                                            //float[] style = FilterStyle(current.Trajectory.Points[k].Styles);
                                            //float[] style = current.Trajectory.Points[k].Styles;
                                            //ArrayExtensions.Shrink(ref style);
                                            inputLine += FormatValue(position.x);
                                            inputLine += FormatValue(position.z);
                                            inputLine += FormatValue(direction.x);
                                            inputLine += FormatValue(direction.z);
                                            inputLine += FormatValue(velocity.x);
                                            inputLine += FormatValue(velocity.z);
                                            //inputLine += FormatValue(speed);
                                            //inputLine += FormatArray(style);
                                        }
                                        for (int k = 0; k < previous.BoneTransformations.Length; k++)
                                        {
                                            Vector3 position = previous.BoneTransformations[k].GetPosition().GetRelativePositionTo(previous.Root);
                                            Vector3 forward  = previous.BoneTransformations[k].GetForward().GetRelativeDirectionTo(previous.Root);
                                            Vector3 up       = previous.BoneTransformations[k].GetUp().GetRelativeDirectionTo(previous.Root);
                                            Vector3 velocity = previous.BoneVelocities[k].GetRelativeDirectionTo(previous.Root);
                                            inputLine += FormatVector3(position);
                                            inputLine += FormatVector3(forward);
                                            inputLine += FormatVector3(up);
                                            inputLine += FormatVector3(velocity);
                                        }
                                        if (phaseModule != null)
                                        {
                                            //float previousPhase = phaseModule.GetPhase(editor.GetFile().Data.GetFrame(previous.Index), editor.ShowMirror);
                                            float currentPhase = phaseModule.GetPhase(editor.GetFile().Data.GetFrame(current.Index), editor.ShowMirror);
                                            //inputLine += FormatVector2(Utility.GetCirclePhase(currentPhase));
                                            //inputLine += FormatVector2(Utility.GetCirclePhaseUpdate(previousPhase, currentPhase));
                                            float[] style = current.Trajectory.Points[6].Styles;
                                            ArrayExtensions.Shrink(ref style);
                                            style      = Utility.StylePhase(style, currentPhase);
                                            inputLine += FormatArray(style);
                                            //inputLine += FormatValue(currentPhase);
                                        }

                                        /*
                                         * if(contactModule != null) {
                                         *      for(int c=0; c<contactModule.Functions.Length; c++) {
                                         *              bool contact = contactModule.Functions[c].HasContact(editor.GetFile().Data.GetFrame(current.Index), editor.ShowMirror);
                                         *              float value = contact ? 1f : 0f;
                                         *              inputLine += FormatValue(value);
                                         *      }
                                         * }
                                         */
                                        inputLine = inputLine.Remove(inputLine.Length - 1);
                                        inputLine = inputLine.Replace(",", ".");
                                        input.WriteLine(inputLine);

                                        //Output
                                        string outputLine = string.Empty;
                                        for (int k = 6; k < 12; k++)
                                        {
                                            Vector3 position  = next.Trajectory.Points[k].GetPosition().GetRelativePositionTo(next.Root);
                                            Vector3 direction = next.Trajectory.Points[k].GetDirection().GetRelativeDirectionTo(next.Root);
                                            Vector3 velocity  = next.Trajectory.Points[k].GetVelocity().GetRelativeDirectionTo(next.Root);
                                            outputLine += FormatValue(position.x);
                                            outputLine += FormatValue(position.z);
                                            outputLine += FormatValue(direction.x);
                                            outputLine += FormatValue(direction.z);
                                            outputLine += FormatValue(velocity.x);
                                            outputLine += FormatValue(velocity.z);
                                        }
                                        for (int k = 0; k < current.BoneTransformations.Length; k++)
                                        {
                                            Vector3 position = current.BoneTransformations[k].GetPosition().GetRelativePositionTo(current.Root);
                                            Vector3 forward  = current.BoneTransformations[k].GetForward().GetRelativeDirectionTo(current.Root);
                                            Vector3 up       = current.BoneTransformations[k].GetUp().GetRelativeDirectionTo(current.Root);
                                            Vector3 velocity = current.BoneVelocities[k].GetRelativeDirectionTo(current.Root);
                                            outputLine += FormatVector3(position);
                                            outputLine += FormatVector3(forward);
                                            outputLine += FormatVector3(up);
                                            outputLine += FormatVector3(velocity);
                                        }
                                        outputLine += FormatVector3(next.RootMotion);
                                        if (phaseModule != null)
                                        {
                                            //float currentPhase = phaseModule.GetPhase(editor.GetFile().Data.GetFrame(current.Index), editor.ShowMirror);
                                            float nextPhase = phaseModule.GetPhase(editor.GetFile().Data.GetFrame(next.Index), editor.ShowMirror);
                                            outputLine += FormatVector2(Utility.GetCirclePhase(nextPhase));
                                        }

                                        /*
                                         * if(contactModule != null) {
                                         *      for(int c=0; c<contactModule.Functions.Length; c++) {
                                         *              bool contact = contactModule.Functions[c].HasContact(editor.GetFile().Data.GetFrame(next.Index), editor.ShowMirror);
                                         *              float value = contact ? 1f : 0f;
                                         *              outputLine += FormatValue(value);
                                         *      }
                                         * }
                                         */
                                        outputLine = outputLine.Remove(outputLine.Length - 1);
                                        outputLine = outputLine.Replace(",", ".");
                                        output.WriteLine(outputLine);

                                        //Spin
                                        items += 1;
                                        if (items == BatchSize)
                                        {
                                            items = 0;
                                            yield return(new WaitForSeconds(0f));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            yield return(new WaitForSeconds(0f));
        }
        input.Close();
        output.Close();
        Exporting = false;
    }
Example #19
0
 public void AddSequence(int start, int end)
 {
     ArrayExtensions.Add(ref Sequences, new Sequence(this, start, end));
 }
Example #20
0
        public override void OnInspectorGUI()
        {
            Target.Actor = (Actor)EditorGUILayout.ObjectField("Actor", Target.Actor, typeof(Actor), true);

            EditorGUILayout.BeginHorizontal();
            Target.Folder = EditorGUILayout.TextField("Folder", "Assets/" + Target.Folder.Substring(Mathf.Min(7, Target.Folder.Length)));
            if (GUILayout.Button("Load"))
            {
                Target.Load();
                if (Target.Files.Length == 0)
                {
                    Debug.Log("Motion data could not be found!");
                    return;
                }
                if (Target.Data == null)
                {
                    Target.LoadData(Target.Files[0]);
                }
                InitNames();
            }
            EditorGUILayout.EndHorizontal();

            if (Target.Data != null)
            {
                {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField("Data", GUILayout.Width(50.0f));
                    int selectIndex = EditorGUILayout.Popup(System.Array.FindIndex(Names, x => x == Target.Data.GetName()), EnumNames);
                    if (selectIndex != -1)
                    {
                        Target.LoadData(Names[selectIndex]);
                    }
                    if (GUILayout.Button("<"))
                    {
                        Target.LoadPreviousData();
                    }
                    if (GUILayout.Button(">"))
                    {
                        Target.LoadNextData();
                    }
                    int sliderIndex = EditorGUILayout.IntSlider(System.Array.FindIndex(Target.Files, x => x == Target.Data) + 1, 1, Target.Files.Length);
                    if (Event.current.type == EventType.Used)
                    {
                        Target.LoadData(Target.Files[sliderIndex - 1]);
                    }
                    EditorGUILayout.LabelField("/ " + Target.Files.Length, GUILayout.Width(60.0f));
                    GUI.color = Target.Data.Mirrored ? Color.red : Color.white;
                    if (GUILayout.Button("Mirror"))
                    {
                        Target.Data.Mirrored      = !Target.Data.Mirrored;
                        Target.Data.MirrorChanged = true;
                    }
                    GUI.color = Color.white;
                    EditorGUILayout.EndHorizontal();
                }

                {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField("Data", GUILayout.Width(50.0f));
                    EditorGUILayout.ObjectField(Target.Data, typeof(MotionData), true);
                    EditorGUILayout.EndHorizontal();
                }

                using (new EditorGUILayout.VerticalScope("Box"))
                {
                    {
                        EditorGUILayout.BeginHorizontal();
                        Visiable = EditorGUILayout.Toggle(Visiable, GUILayout.Width(20.0f));
                        EditorGUILayout.LabelField("Show Bone Map", GUILayout.Width(300.0f));
                        if (GUILayout.Button("Auto"))
                        {
                            Target.AutoMap();
                        }
                        EditorGUILayout.EndHorizontal();
                    }

                    if (Visiable)
                    {
                        EditorGUILayout.BeginHorizontal();
                        EditorGUILayout.LabelField("BVH Bone Name", GUILayout.Width(200.0f));
                        EditorGUILayout.LabelField("Actor Bone Name");
                        EditorGUILayout.EndHorizontal();

                        for (int i = 0; i < Target.Data.Root.Bones.Length; i++)
                        {
                            EditorGUILayout.BeginHorizontal();
                            EditorGUILayout.LabelField(Target.Map[i].BvhBoneName, GUILayout.Width(200.0f));
                            EditorGUILayout.ObjectField(Target.Map[i].ActorBoneTransform, typeof(Transform), true);
                            EditorGUILayout.EndHorizontal();
                        }
                    }
                }

                {
                    Frame frame = Target.GetCurrentFrame();
                    EditorGUILayout.BeginHorizontal();
                    if (GUILayout.Button("<<"))
                    {
                        Target.LoadFrame(Mathf.Max(frame.Timestamp - 1.0f, 0.0f));
                    }
                    if (GUILayout.Button("<"))
                    {
                        Target.LoadFrame(Mathf.Max(frame.Timestamp - 1.0f / Target.Data.Framerate, 0.0f));
                    }
                    if (GUILayout.Button(">"))
                    {
                        Target.LoadFrame(Mathf.Min(frame.Timestamp + 1.0f / Target.Data.Framerate, Target.Data.GetTotalTime()));
                    }
                    if (GUILayout.Button(">>"))
                    {
                        Target.LoadFrame(Mathf.Min(frame.Timestamp + 1.0f, Target.Data.GetTotalTime()));
                    }
                    int index = EditorGUILayout.IntSlider(frame.Index, 1, Target.Data.GetTotalFrames());
                    if (index != frame.Index)
                    {
                        Target.LoadFrame(index);
                    }
                    EditorGUILayout.LabelField(frame.Timestamp.ToString("F3") + "s", GUILayout.Width(50f));
                    EditorGUILayout.EndHorizontal();
                }

                if (GUILayout.Button("Create Actor"))
                {
                    Target.Data.CreateActor();
                }

                {
                    EditorGUILayout.BeginHorizontal();
                    if (GUILayout.Button("Play"))
                    {
                        Target.PlayAnimation();
                    }
                    if (GUILayout.Button("Stop"))
                    {
                        Target.StopAnimation();
                    }
                    EditorGUILayout.EndHorizontal();
                }

                int module = EditorGUILayout.Popup(0, ArrayExtensions.Concat(new string[1] {
                    "Add Module"
                }, Module.GetNames()));
                if (module > 0)
                {
                    Target.Data.AddModule(((Module.ID)(module - 1)));
                }

                for (int i = 0; i < Target.Data.Modules.Length; i++)
                {
                    Target.Data.Modules[i].Inspector(Target);
                }
            }
        }
Example #21
0
 public void RemoveSequence(int index)
 {
     ArrayExtensions.RemoveAt(ref Sequences, index);
 }
Example #22
0
 public static T[] Concat <T>(T[] lhs, T rhs)
 {
     T[] clone = (T[])lhs.Clone();
     ArrayExtensions.Add(ref clone, rhs);
     return(clone);
 }
Example #23
0
 public void AddBone(string name, string parent, Vector3 offset, int[] channels)
 {
     ArrayExtensions.Add(ref Bones, new Bone(Bones.Length, name, parent, offset, channels));
 }
Example #24
0
 public VertexAttribsKey(VertexAttrib[] attribs)
 {
     Attribs = attribs;
     Hash    = ArrayExtensions.ComputeHash(attribs);
 }
Example #25
0
        public void CreateCopies()
        {
            Copies = new Interval[0];

            //Transition Copies
            for (int c = 0; c < TransitionCopies.Length; c++)
            {
                for (int i = Start; i <= End; i++)
                {
                    if (Data.GetFrame(i).IsTransition(c))
                    {
                        Interval copy = new Interval();
                        copy.Start = i;
                        while (true)
                        {
                            i += 1;
                            if (i == End)
                            {
                                copy.End = i;
                                break;
                            }
                            if (!Data.GetFrame(i).IsTransition(c))
                            {
                                copy.End = i - 1;
                                break;
                            }
                        }
                        for (int k = 0; k < TransitionCopies[c]; k++)
                        {
                            ArrayExtensions.Add(ref Copies, copy);
                        }
                    }
                }
            }

            //Style Copies
            for (int c = 0; c < StyleCopies.Length; c++)
            {
                if (StyleCopies[c] > 0)
                {
                    for (int i = Start; i <= End; i++)
                    {
                        if (Data.GetFrame(i).StyleValues[c] == 1f)
                        {
                            Interval copy = new Interval();
                            copy.Start = i;
                            while (true)
                            {
                                i += 1;
                                if (i == End)
                                {
                                    copy.End = i;
                                    break;
                                }
                                if (Data.GetFrame(i).StyleValues[c] != 1f)
                                {
                                    copy.End = i - 1;
                                    break;
                                }
                            }
                            for (int k = 0; k < StyleCopies[c]; k++)
                            {
                                ArrayExtensions.Add(ref Copies, copy);
                            }
                        }
                    }
                }
            }
        }
Example #26
0
 public bool Equals(VertexAttribsKey other)
 {
     return(Hash == other.Hash && ArrayExtensions.ArraysEqual(Attribs, other.Attribs));
 }
Example #27
0
        private object ExportModel(ICommandContext commandContext, ContentManager contentManager)
        {
            // Read from model file
            var modelSkeleton = LoadSkeleton(commandContext, contentManager); // we get model skeleton to compare it to real skeleton we need to map to

            AdjustSkeleton(modelSkeleton);
            var model = LoadModel(commandContext, contentManager);

            if (!CheckInputSlots(commandContext, model))
            {
                return(null);
            }

            // Apply materials
            foreach (var modelMaterial in Materials)
            {
                if (modelMaterial.MaterialInstance?.Material == null)
                {
                    commandContext.Logger.Verbose($"The material [{modelMaterial.Name}] is null in the list of materials.");
                }
                model.Materials.Add(modelMaterial.MaterialInstance);
            }

            model.BoundingBox = BoundingBox.Empty;

            foreach (var mesh in model.Meshes)
            {
                if (TessellationAEN)
                {
                    // TODO: Generate AEN model view
                    commandContext.Logger.Error($"TessellationAEN is not supported in {ContextAsString}");
                }
            }

            SkeletonMapping skeletonMapping;

            Skeleton skeleton;

            if (SkeletonUrl != null)
            {
                // Load skeleton and process it
                skeleton = contentManager.Load <Skeleton>(SkeletonUrl);

                // Assign skeleton to model
                model.Skeleton = AttachedReferenceManager.CreateProxyObject <Skeleton>(AssetId.Empty, SkeletonUrl);
            }
            else
            {
                skeleton = null;
            }

            skeletonMapping = new SkeletonMapping(skeleton, modelSkeleton);

            // Refresh skeleton updater with model skeleton
            var hierarchyUpdater = new SkeletonUpdater(modelSkeleton);

            hierarchyUpdater.UpdateMatrices();

            // Move meshes in the new nodes
            foreach (var mesh in model.Meshes)
            {
                // Apply scale import on meshes
                if (!MathUtil.NearEqual(ScaleImport, 1.0f))
                {
                    var transformationMatrix = Matrix.Scaling(ScaleImport);
                    for (int vbIdx = 0; vbIdx < mesh.Draw.VertexBuffers.Length; vbIdx++)
                    {
                        mesh.Draw.VertexBuffers[vbIdx].TransformBuffer(ref transformationMatrix);
                    }
                }

                var skinning = mesh.Skinning;
                if (skinning != null)
                {
                    // Update node mapping
                    // Note: we only remap skinning matrices, but we could directly remap skinning bones instead
                    for (int i = 0; i < skinning.Bones.Length; ++i)
                    {
                        var linkNodeIndex    = skinning.Bones[i].NodeIndex;
                        var newLinkNodeIndex = skeletonMapping.SourceToSource[linkNodeIndex];

                        var nodeIndex    = mesh.NodeIndex;
                        var newNodeIndex = skeletonMapping.SourceToSource[mesh.NodeIndex];

                        skinning.Bones[i].NodeIndex = skeletonMapping.SourceToTarget[linkNodeIndex];

                        // Adjust scale import
                        if (!MathUtil.NearEqual(ScaleImport, 1.0f))
                        {
                            skinning.Bones[i].LinkToMeshMatrix.TranslationVector = skinning.Bones[i].LinkToMeshMatrix.TranslationVector * ScaleImport;
                        }

                        // If it was remapped, we also need to update matrix
                        if (nodeIndex != newNodeIndex)
                        {
                            // Update mesh part
                            var transformMatrix = CombineMatricesFromNodeIndices(hierarchyUpdater.NodeTransformations, newNodeIndex, nodeIndex);
                            transformMatrix.Invert();
                            skinning.Bones[i].LinkToMeshMatrix = Matrix.Multiply(transformMatrix, skinning.Bones[i].LinkToMeshMatrix);
                        }

                        if (newLinkNodeIndex != linkNodeIndex)
                        {
                            // Update link part
                            var transformLinkMatrix = CombineMatricesFromNodeIndices(hierarchyUpdater.NodeTransformations, newLinkNodeIndex, linkNodeIndex);
                            skinning.Bones[i].LinkToMeshMatrix = Matrix.Multiply(skinning.Bones[i].LinkToMeshMatrix, transformLinkMatrix);
                        }
                    }
                }

                // Check if there was a remap using model skeleton
                if (skeletonMapping.SourceToSource[mesh.NodeIndex] != mesh.NodeIndex)
                {
                    // Transform vertices
                    var transformationMatrix = CombineMatricesFromNodeIndices(hierarchyUpdater.NodeTransformations, skeletonMapping.SourceToSource[mesh.NodeIndex], mesh.NodeIndex);
                    for (int vbIdx = 0; vbIdx < mesh.Draw.VertexBuffers.Length; vbIdx++)
                    {
                        mesh.Draw.VertexBuffers[vbIdx].TransformBuffer(ref transformationMatrix);
                    }

                    // Check if geometry is inverted, to know if we need to reverse winding order
                    // TODO: What to do if there is no index buffer? We should create one... (not happening yet)
                    if (mesh.Draw.IndexBuffer == null)
                    {
                        throw new InvalidOperationException();
                    }

                    Matrix  rotation;
                    Vector3 scale, translation;
                    if (transformationMatrix.Decompose(out scale, out rotation, out translation) &&
                        scale.X * scale.Y * scale.Z < 0)
                    {
                        mesh.Draw.ReverseWindingOrder();
                    }
                }

                // Update new node index using real asset skeleton
                mesh.NodeIndex = skeletonMapping.SourceToTarget[mesh.NodeIndex];
            }

            // Merge meshes with same parent nodes, material and skinning
            var meshesByNodes = model.Meshes.GroupBy(x => x.NodeIndex).ToList();

            foreach (var meshesByNode in meshesByNodes)
            {
                // This logic to detect similar material is kept from old code; this should be reviewed/improved at some point
                foreach (var meshesPerDrawCall in meshesByNode.GroupBy(x => x,
                                                                       new AnonymousEqualityComparer <Mesh>((x, y) =>
                                                                                                            x.MaterialIndex == y.MaterialIndex && // Same material
                                                                                                            ArrayExtensions.ArraysEqual(x.Skinning?.Bones, y.Skinning?.Bones) && // Same bones
                                                                                                            CompareParameters(model, x, y) && // Same parameters
                                                                                                            CompareShadowOptions(model, x, y), // Same shadow parameters
                                                                                                            x => 0)).ToList())
                {
                    if (meshesPerDrawCall.Count() == 1)
                    {
                        // Nothing to group, skip to next entry
                        continue;
                    }

                    // Remove old meshes
                    foreach (var mesh in meshesPerDrawCall)
                    {
                        model.Meshes.Remove(mesh);
                    }

                    // Add new combined mesh(es)
                    var baseMesh    = meshesPerDrawCall.First();
                    var newMeshList = meshesPerDrawCall.Select(x => x.Draw).ToList().GroupDrawData(Allow32BitIndex);

                    foreach (var generatedMesh in newMeshList)
                    {
                        model.Meshes.Add(new Mesh(generatedMesh, baseMesh.Parameters)
                        {
                            MaterialIndex = baseMesh.MaterialIndex,
                            Name          = baseMesh.Name,
                            Draw          = generatedMesh,
                            NodeIndex     = baseMesh.NodeIndex,
                            Skinning      = baseMesh.Skinning,
                        });
                    }
                }
            }

            // split the meshes if necessary
            model.Meshes = SplitExtensions.SplitMeshes(model.Meshes, Allow32BitIndex);

            // Refresh skeleton updater with asset skeleton
            hierarchyUpdater = new SkeletonUpdater(skeleton);
            hierarchyUpdater.UpdateMatrices();

            // bounding boxes
            var modelBoundingBox    = model.BoundingBox;
            var modelBoundingSphere = model.BoundingSphere;

            foreach (var mesh in model.Meshes)
            {
                var vertexBuffers = mesh.Draw.VertexBuffers;
                for (int vbIdx = 0; vbIdx < vertexBuffers.Length; vbIdx++)
                {
                    // Compute local mesh bounding box (no node transformation)
                    Matrix matrix = Matrix.Identity;
                    mesh.BoundingBox = vertexBuffers[vbIdx].ComputeBounds(ref matrix, out mesh.BoundingSphere);

                    // Compute model bounding box (includes node transformation)
                    hierarchyUpdater.GetWorldMatrix(mesh.NodeIndex, out matrix);
                    BoundingSphere meshBoundingSphere;
                    var            meshBoundingBox = vertexBuffers[vbIdx].ComputeBounds(ref matrix, out meshBoundingSphere);
                    BoundingBox.Merge(ref modelBoundingBox, ref meshBoundingBox, out modelBoundingBox);
                    BoundingSphere.Merge(ref modelBoundingSphere, ref meshBoundingSphere, out modelBoundingSphere);
                }

                // TODO: temporary Always try to compact
                mesh.Draw.CompactIndexBuffer();
            }
            model.BoundingBox    = modelBoundingBox;
            model.BoundingSphere = modelBoundingSphere;

            // Count unique meshes (they can be shared)
            var uniqueDrawMeshes = model.Meshes.Select(x => x.Draw).Distinct();

            // Count unique vertex buffers and squish them together in a single buffer
            var uniqueVB = uniqueDrawMeshes.SelectMany(x => x.VertexBuffers).Distinct().ToList();

            var vbMap                    = new Dictionary <VertexBufferBinding, VertexBufferBinding>();
            var sizeVertexBuffer         = uniqueVB.Select(x => x.Buffer.GetSerializationData().Content.Length).Sum();
            var vertexBuffer             = new BufferData(BufferFlags.VertexBuffer, new byte[sizeVertexBuffer]);
            var vertexBufferSerializable = vertexBuffer.ToSerializableVersion();

            var vertexBufferNextIndex = 0;

            foreach (var vbBinding in uniqueVB)
            {
                var oldVertexBuffer = vbBinding.Buffer.GetSerializationData().Content;
                Array.Copy(oldVertexBuffer, 0, vertexBuffer.Content, vertexBufferNextIndex, oldVertexBuffer.Length);

                vbMap.Add(vbBinding, new VertexBufferBinding(vertexBufferSerializable, vbBinding.Declaration, vbBinding.Count, vbBinding.Stride, vertexBufferNextIndex));

                vertexBufferNextIndex += oldVertexBuffer.Length;
            }

            // Count unique index buffers and squish them together in a single buffer
            var uniqueIB        = uniqueDrawMeshes.Select(x => x.IndexBuffer).Distinct().ToList();
            var sizeIndexBuffer = 0;

            foreach (var ibBinding in uniqueIB)
            {
                // Make sure 32bit indices are properly aligned to 4 bytes in case the last alignment was 2 bytes
                if (ibBinding.Is32Bit && sizeIndexBuffer % 4 != 0)
                {
                    sizeIndexBuffer += 2;
                }

                sizeIndexBuffer += ibBinding.Buffer.GetSerializationData().Content.Length;
            }

            var ibMap                   = new Dictionary <IndexBufferBinding, IndexBufferBinding>();
            var indexBuffer             = new BufferData(BufferFlags.IndexBuffer, new byte[sizeIndexBuffer]);
            var indexBufferSerializable = indexBuffer.ToSerializableVersion();
            var indexBufferNextIndex    = 0;

            foreach (var ibBinding in uniqueIB)
            {
                var oldIndexBuffer = ibBinding.Buffer.GetSerializationData().Content;

                // Make sure 32bit indices are properly aligned to 4 bytes in case the last alignment was 2 bytes
                if (ibBinding.Is32Bit && indexBufferNextIndex % 4 != 0)
                {
                    indexBufferNextIndex += 2;
                }

                Array.Copy(oldIndexBuffer, 0, indexBuffer.Content, indexBufferNextIndex, oldIndexBuffer.Length);

                ibMap.Add(ibBinding, new IndexBufferBinding(indexBufferSerializable, ibBinding.Is32Bit, ibBinding.Count, indexBufferNextIndex));

                indexBufferNextIndex += oldIndexBuffer.Length;
            }

            // Assign new vertex and index buffer bindings
            foreach (var drawMesh in uniqueDrawMeshes)
            {
                for (int i = 0; i < drawMesh.VertexBuffers.Length; i++)
                {
                    drawMesh.VertexBuffers[i] = vbMap[drawMesh.VertexBuffers[i]];
                }

                drawMesh.IndexBuffer = ibMap[drawMesh.IndexBuffer];
            }

            vbMap.Clear();
            ibMap.Clear();

            // Convert to Entity
            return(model);
        }
Example #28
0
 public void AddBone(string name, string parent)
 {
     ArrayExtensions.Add(ref Bones, new Bone(Bones.Length, name, parent));
 }
Example #29
0
    private IEnumerator ImportMotionData()
    {
        string destination = "Assets/" + Destination;

        if (!AssetDatabase.IsValidFolder(destination))
        {
            Debug.Log("Folder " + "'" + destination + "'" + " is not valid.");
        }
        else
        {
            Importing = true;
            for (int f = 0; f < Assets.Length; f++)
            {
                if (Assets[f].Import)
                {
                    string assetName = Assets[f].Object.Name.Replace(".bvh", "");
                    if (!Directory.Exists(destination + "/" + assetName))
                    {
                        AssetDatabase.CreateFolder(destination, assetName);
                        MotionData data = ScriptableObject.CreateInstance <MotionData>();
                        data.name = assetName;
                        AssetDatabase.CreateAsset(data, destination + "/" + assetName + "/" + data.name + ".asset");

                        string[] lines      = System.IO.File.ReadAllLines(Assets[f].Object.FullName);
                        char[]   whitespace = new char[] { ' ' };
                        int      index      = 0;

                        //Create Source Data
                        List <Vector3> offsets  = new List <Vector3>();
                        List <int[]>   channels = new List <int[]>();
                        List <float[]> motions  = new List <float[]>();
                        data.Source = new MotionData.Hierarchy();
                        string  name    = string.Empty;
                        string  parent  = string.Empty;
                        Vector3 offset  = Vector3.zero;
                        int[]   channel = null;
                        for (index = 0; index < lines.Length; index++)
                        {
                            if (lines[index] == "MOTION")
                            {
                                break;
                            }
                            string[] entries = lines[index].Split(whitespace);
                            for (int entry = 0; entry < entries.Length; entry++)
                            {
                                if (entries[entry].Contains("ROOT"))
                                {
                                    parent = "None";
                                    name   = entries[entry + 1];
                                    break;
                                }
                                else if (entries[entry].Contains("JOINT"))
                                {
                                    parent = name;
                                    name   = entries[entry + 1];
                                    break;
                                }
                                else if (entries[entry].Contains("End"))
                                {
                                    parent = name;
                                    name   = name + entries[entry + 1];
                                    string[] subEntries = lines[index + 2].Split(whitespace);
                                    for (int subEntry = 0; subEntry < subEntries.Length; subEntry++)
                                    {
                                        if (subEntries[subEntry].Contains("OFFSET"))
                                        {
                                            offset.x = FileUtility.ReadFloat(subEntries[subEntry + 1]);
                                            offset.y = FileUtility.ReadFloat(subEntries[subEntry + 2]);
                                            offset.z = FileUtility.ReadFloat(subEntries[subEntry + 3]);
                                            break;
                                        }
                                    }
                                    data.Source.AddBone(name, parent);
                                    offsets.Add(offset);
                                    channels.Add(new int[0]);
                                    index += 2;
                                    break;
                                }
                                else if (entries[entry].Contains("OFFSET"))
                                {
                                    offset.x = FileUtility.ReadFloat(entries[entry + 1]);
                                    offset.y = FileUtility.ReadFloat(entries[entry + 2]);
                                    offset.z = FileUtility.ReadFloat(entries[entry + 3]);
                                    break;
                                }
                                else if (entries[entry].Contains("CHANNELS"))
                                {
                                    channel = new int[FileUtility.ReadInt(entries[entry + 1])];
                                    for (int i = 0; i < channel.Length; i++)
                                    {
                                        if (entries[entry + 2 + i] == "Xposition")
                                        {
                                            channel[i] = 1;
                                        }
                                        else if (entries[entry + 2 + i] == "Yposition")
                                        {
                                            channel[i] = 2;
                                        }
                                        else if (entries[entry + 2 + i] == "Zposition")
                                        {
                                            channel[i] = 3;
                                        }
                                        else if (entries[entry + 2 + i] == "Xrotation")
                                        {
                                            channel[i] = 4;
                                        }
                                        else if (entries[entry + 2 + i] == "Yrotation")
                                        {
                                            channel[i] = 5;
                                        }
                                        else if (entries[entry + 2 + i] == "Zrotation")
                                        {
                                            channel[i] = 6;
                                        }
                                    }
                                    data.Source.AddBone(name, parent);
                                    offsets.Add(offset);
                                    channels.Add(channel);
                                    break;
                                }
                                else if (entries[entry].Contains("}"))
                                {
                                    name   = parent;
                                    parent = name == "None" ? "None" : data.Source.FindBone(name).Parent;
                                    break;
                                }
                            }
                        }

                        //Set Frames
                        index += 1;
                        while (lines[index].Length == 0)
                        {
                            index += 1;
                        }
                        ArrayExtensions.Resize(ref data.Frames, FileUtility.ReadInt(lines[index].Substring(8)));

                        //Set Framerate
                        index         += 1;
                        data.Framerate = Mathf.RoundToInt(1f / FileUtility.ReadFloat(lines[index].Substring(12)));

                        //Compute Frames
                        index += 1;
                        for (int i = index; i < lines.Length; i++)
                        {
                            motions.Add(FileUtility.ReadArray(lines[i]));
                        }
                        for (int k = 0; k < data.GetTotalFrames(); k++)
                        {
                            Matrix4x4[] matrices = new Matrix4x4[data.Source.Bones.Length];
                            int         idx      = 0;
                            for (int i = 0; i < data.Source.Bones.Length; i++)
                            {
                                MotionData.Hierarchy.Bone info = data.Source.Bones[i];
                                Vector3    position            = Vector3.zero;
                                Quaternion rotation            = Quaternion.identity;
                                for (int j = 0; j < channels[i].Length; j++)
                                {
                                    if (channels[i][j] == 1)
                                    {
                                        position.x = motions[k][idx]; idx += 1;
                                    }
                                    if (channels[i][j] == 2)
                                    {
                                        position.y = motions[k][idx]; idx += 1;
                                    }
                                    if (channels[i][j] == 3)
                                    {
                                        position.z = motions[k][idx]; idx += 1;
                                    }
                                    if (channels[i][j] == 4)
                                    {
                                        rotation *= Quaternion.AngleAxis(motions[k][idx], Vector3.right); idx += 1;
                                    }
                                    if (channels[i][j] == 5)
                                    {
                                        rotation *= Quaternion.AngleAxis(motions[k][idx], Vector3.up); idx += 1;
                                    }
                                    if (channels[i][j] == 6)
                                    {
                                        rotation *= Quaternion.AngleAxis(motions[k][idx], Vector3.forward); idx += 1;
                                    }
                                }

                                position = (position == Vector3.zero ? offsets[i] : position) * Scale;
                                Matrix4x4 local = Matrix4x4.TRS(position, rotation, Vector3.one);
                                if (Flip)
                                {
                                    local = local.GetMirror(Axis);
                                }
                                matrices[i] = info.Parent == "None" ? local : matrices[data.Source.FindBone(info.Parent).Index] * local;
                            }
                            data.Frames[k] = new Frame(data, k + 1, (float)k / data.Framerate, matrices);

                            /*
                             * for(int i=0; i<data.Source.Bones.Length; i++) {
                             *      data.Frames[k].Local[i] *= Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(data.Corrections[i]), Vector3.one);
                             *      data.Frames[k].World[i] *= Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(data.Corrections[i]), Vector3.one);
                             * }
                             */
                        }

                        if (data.GetTotalFrames() == 1)
                        {
                            Frame reference = data.Frames.First();
                            ArrayExtensions.Resize(ref data.Frames, Mathf.RoundToInt(data.Framerate));
                            for (int k = 0; k < data.GetTotalFrames(); k++)
                            {
                                data.Frames[k] = new Frame(data, k + 1, (float)k / data.Framerate, reference.GetSourceTransformations(false));
                            }
                        }

                        //Detect Symmetry
                        data.DetectSymmetry();

                        //Add Scene
                        data.CreateScene();
                        data.AddSequence();

                        //Save
                        EditorUtility.SetDirty(data);
                    }
                    else
                    {
                        Debug.Log("Asset with name " + assetName + " already exists.");
                    }

                    yield return(new WaitForSeconds(0f));
                }
            }
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            Importing = false;
        }
        yield return(new WaitForSeconds(0f));
    }
Example #30
0
        public void MinimalBST_InvalidIndices_Null(int start, int end)
        {
            var actual = ArrayExtensions.CreateMinimalBST(OneNode, start, end);

            Assert.AreEqual(null, actual);
        }