Exemplo n.º 1
0
    public static void DrawWave(Graphics g,
                                RectangleF r,
                                float phase,
                                IStream Source)
    {
        g.SmoothingMode   = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        DrawPaper(g, r);
        phase = Source?.ElapsedTime ?? 0;
        float hz = Source?.Hz ?? 0;

        float[] X =
            Source?.Read();
        if (X == null)
        {
            return;
        }
        DrawFunction(g, r, (i, cc) => Envelopes.Hann(i, cc) * X[i * X.Length / cc], Brushes.DarkOrange);
        var fft = Complex.FFT(X);

        X = Complex.InverseFFT(fft);
        DrawFunction(g, r, (i, cc) => Envelopes.Hann(i, cc) * X[i * X.Length / cc], Brushes.DarkViolet);

        DrawLabels(g, r, Source.ElapsedTime, hz, X);
    }
Exemplo n.º 2
0
        protected override void Init()
        {
            // Event occurs once at the start of the strategy
            #region GetIndicatorsAndFrames             // Get Indicators' references...

            Print("Starting TS on account: {0} ", this.Account.Number);

            InitLogFile();

            _period    = Timeframe;
            _barSeries = GetCustomSeries(Instrument.Id,
                                         _period);
            FTOind = GetIndicator <FisherTransformOscillator>(
                Instrument.Id,
                _period,
                FisherPeriod,
                FisherMa1Period,
                FisherMa1Method,
                FisherMa2Period,
                FisherMa2Method);
            EnvindTP = GetIndicator <Envelopes>(
                Instrument.Id,
                _period,
                envelopesTPperiod,
                envelopesTPdev,
                envelopesTPshift,
                envelopesTPmethod,
                envelopesTPprice);


            #endregion             //GetIndicatorsAndFrames
            // Print("Starting TS on account: {0}, comment: {1}", this.Account.Number, CommentText);
        }
Exemplo n.º 3
0
Arquivo: Mel.cs Projeto: azret/mozart
        public static Matrix Noise()
        {
            int Fs = 1024 * 2;

            Debug.Assert(Fs == 1024 * 2);
            var Model = new Matrix(113);

            for (int i = 0; i < Model.Capacity; i++)
            {
                double[] re = new double[CBOW.DIMS],
                im = new double[CBOW.DIMS];
                for (int j = 0; j < CBOW.DIMS; j++)
                {
                    re[j] = ((global::Random.Next() & 0xFFFF) / (65536f))
                            * ((global::Random.Next() & 0xFFFF) / (65536f));
                    im[j] = Envelopes.MIDI2FREQ(j);
                    if (((global::Random.Next() & 0xFFFF) / (65536f)) > 0.3)
                    {
                        re[j] = 0;
                    }
                }
                Vector it       = new Vector("𝆕", re, im);
                var    duration = Math.Round((double)Fs / Wav._hz, 5);
                Debug.Assert((int)(duration * Wav._hz) == Fs);
                double scale = 1.6;
                it.Score.Re = scale * duration;
                for (int j = 0; j < CBOW.DIMS; j++)
                {
                    RunSpeachFrequencyFilters(it, j);
                }
                Model[i] = it;
            }
            return(Model);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Creates Levels within the subgrade and ongrade Envelopes.
        /// </summary>
        /// <param name="stdHeight">Desired height for repeating Levels.</param>
        /// <param name="grdHeight">Desired height for first Level above grade.</param>
        private void GradeLevels(double stdHeight, double grdHeight)
        {
            var envelopes = Envelopes.Where(e => e.Elevation >= 0.0).ToList();

            if (envelopes.Count() == 0)
            {
                return;
            }
            var envelope = envelopes.First();
            var subs     = Envelopes.Where(e => e.Elevation < 0.0).ToList();

            if (subs.Count() == 0) // if no subgrade levels created, add the first Level.
            {
                MakeLevel(envelope, envelope.Elevation);
            }
            if (envelope.Height >= grdHeight + (stdHeight * 2))
            {
                // Temporary Envelope to populate levels above the lobby.
                envelope = new Envelope(envelope.Profile, grdHeight, envelope.Height - grdHeight,
                                        Vector3.ZAxis, 0.0, new Transform(0.0, 0.0, grdHeight), null, null,
                                        false, Guid.NewGuid(), "");
                MakeLevels(envelope, stdHeight, true, true);
            }
            else
            {
                MakeLevel(envelope, envelope.Height);
            }
            Levels          = Levels.OrderBy(l => l.Elevation).ToList();
            LevelPerimeters = LevelPerimeters.OrderBy(l => l.Elevation).ToList();
        }
Exemplo n.º 5
0
        private PictureBox createPbEnvType(int posX, byte noise, byte envType, EventHandler clickHandler, Panel panel)
        {
            PictureBox result = new PictureBox();

            result.BackColor             = Color.LightGray;
            result.BorderStyle           = BorderStyle.FixedSingle;
            result.Click                += clickHandler;
            result.BackgroundImageLayout = ImageLayout.Center;
            result.Width                 = 24;
            result.Height                = 24;
            result.Left = posX + (3 * sliderWidth) - 12;
            result.Top  = 0;
            if ((noise & 0x80) == 0x80)
            {
                Envelopes         envValue = (Envelopes)envType;
                ToolStripMenuItem item     = getItemByTagValue((int)envValue);
                tipCtl.SetToolTip(result, item == null ? "N/A" : item.Text);
                result.BackgroundImage =
                    WYZTracker.Properties.Resources.ResourceManager.GetObject(envValue.ToString()) as Image;
            }
            else
            {
                result.BackgroundImage = WYZTracker.Properties.Resources.env_none;
                tipCtl.SetToolTip(result, "No Envelope");
            }
            panel.Controls.Add(result);
            return(result);
        }
Exemplo n.º 6
0
        private static Envelopes LoadEVP1FromStream(EndianBinaryReader reader, long chunkStart)
        {
            Envelopes envelopes = new Envelopes();
            ushort numEnvelopes = reader.ReadUInt16();
            reader.ReadUInt16(); // Padding

            // numEnvelope many uint8 - each one describes how many bones belong to this index.
            uint boneCountOffset = reader.ReadUInt32();
            // "sum over all bytes in boneCountOffset many shorts (index into some joint stuff? into matrix table?)"
            uint indexDataOffset = reader.ReadUInt32();
            // Bone Weights (as many floats here as there are ushorts at indexDataOffset)
            uint weightOffset = reader.ReadUInt32();
            // Matrix Table (3x4 float array) - Inverse Bind Pose
            uint boneMatrixOffset = reader.ReadUInt32();

            // - Is this the number of bones which influence the vert?
            reader.BaseStream.Position = chunkStart + boneCountOffset;
            for (int b = 0; b < numEnvelopes; b++)
                envelopes.numBonesAffecting.Add(reader.ReadByte());

            // ???
            reader.BaseStream.Position = chunkStart + indexDataOffset;
            for (int m = 0; m < envelopes.numBonesAffecting.Count; m++)
            {
                for (int j = 0; j < envelopes.numBonesAffecting[m]; j++)
                {
                    envelopes.indexRemap.Add(reader.ReadUInt16());
                }
            }

            // Bone Weights
            reader.BaseStream.Position = chunkStart + weightOffset;
            for (int w = 0; w < envelopes.numBonesAffecting.Count; w++)
            {
                for (int j = 0; j < envelopes.numBonesAffecting[w]; j++)
                {
                    envelopes.weights.Add(reader.ReadSingle());
                }
            }

            // Inverse Bind Pose Matrices
            reader.BaseStream.Position = chunkStart + boneMatrixOffset;
            for (int w = 0; w < numEnvelopes; w++)
            {
                Matrix3x4 matrix = new Matrix3x4();
                for (int j = 0; j < 3; j++)
                {
                    for (int k = 0; k < 4; k++)
                        matrix[j, k] = reader.ReadSingle();
                }

                envelopes.inverseBindPose.Add(matrix);
            }

            return envelopes;
        }
Exemplo n.º 7
0
        public static void Envelope(float[] X)
        {
            var samples = X.Length;

            for (int s = 0; s < samples; s++)
            {
                X[s] = X[s]
                       * (float)Envelopes.Hann(s, samples);
            }
        }
Exemplo n.º 8
0
    void ExportEnvelopes(XmlElement parent, Envelopes envelopes)
    {
        XmlElement elt = AddChild(parent, "Envelopes");

        elt.SetAttribute("Count", envelopes.Count.ToString(myNumberFormat));
        foreach (Envelope envelope in envelopes)
        {
            ExportEnvelope(elt, envelope);
        }
    }
Exemplo n.º 9
0
        private async Task LoadAsync()
        {
            Envelopes.Clear();
            var service   = new EnvelopeManager();
            var envelopes = await service.GetEnvelopeByAccountAsync(accID);

            foreach (var item in envelopes)
            {
                Envelopes.Add(item);
            }
        }
Exemplo n.º 10
0
        public IRootSerializable Deserialize(ActorSystem system)
        {
            var ser = system.Serialization();
            //deserialize messages in the envelope
            var messages = Envelopes
                           .Select(e => ser
                                   .Deserialize(TypeNames[e.TypeId], e.MessageData, e.SerializerId))
                           .ToList();

            return(new TopicBatchMessage(messages));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Creates Levels within the subgrade Envelopes.
        /// </summary>
        /// <param name="stdHeight">Desired height for repeating Levels.</param>
        /// <param name="grdHeight">Desired height for first Level above grade.</param>
        private void SubGradeLevels(double stdHeight)
        {
            // Add subgrade Levels.
            var subs = Envelopes.Where(e => e.Elevation < 0.0).ToList();

            foreach (var env in subs)
            {
                MakeLevels(env, stdHeight, true, true);
            }
            Levels          = Levels.OrderBy(l => l.Elevation).ToList();
            LevelPerimeters = LevelPerimeters.OrderBy(l => l.Elevation).ToList();
        }
Exemplo n.º 12
0
    void ImportEnvelopes(XmlElement parent, Envelopes envelopes)
    {
        XmlElement elt = parent["Envelopes"];

        if (null == elt)
        {
            return;
        }
        foreach (XmlElement child in elt)
        {
            ImportEnvelope(child, envelopes);
        }
    }
Exemplo n.º 13
0
        /// <summary>
        /// Returns a string representation of the object.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder s = Envelopes.Aggregate(new StringBuilder("Message["), (sb, a) => sb.Append(a).Append("["));

            s.AppendFormat("{0} bytes in {1} parts]", Body.Aggregate(0, (acc, d) => acc += d.Length), Body.Count);

            for (int i = 0; i < Envelopes.Count; i++)
            {
                s.Append("]");
            }

            return(s.ToString());
        }
Exemplo n.º 14
0
 static float RenderEnv(string envType, float atk, float hld, float dcy,
                        float sus, int time)
 {
     if (envType.Equals("AHD"))
     {
         return(Envelopes.AHD(atk, hld, dcy, time));
     }
     else if (envType.Equals("AHDS"))
     {
         return(Envelopes.AHDS(atk, hld, dcy, sus, time));
     }
     else
     {
         return(1f);
     }
 }
Exemplo n.º 15
0
Arquivo: Mel.cs Projeto: azret/mozart
        static void RunSpeachFrequencyFilters(Vector it, int j, double vol = 0.01, int dbMin = -20, int dbMax = +20)
        {
            bool IsAudible(double f)
            {
                if ((f >= 8.1 && f <= 16743.9))
                {
                    return(true);
                }
                return(false);
            }

            bool pass = true;

            if (!IsAudible(it.Axis[j].Im))
            {
                pass = false;
            }
            if (it.Axis[j].Re <= 0.01)
            {
                pass = false;
            }
            if (pass)
            {
                var n = Envelopes.MIDI2NOTE(Envelopes.FREQ2MIDI(it.Axis[j].Im));
                if (string.IsNullOrWhiteSpace(n))
                {
                    pass = false;
                }
                if (n == null || (!n.Contains("3") && !n.Contains("4") && !n.Contains("5") &&
                                  !n.Contains("6")))
                {
                    pass = false;
                }
                if (pass && it.Axis[j].Re > 0)
                {
                    var dB = Envelopes.dB(it.Axis[j].Re);
                    if (dB <= dbMin || dB >= dbMax)
                    {
                        pass = false;
                    }
                }
            }
            if (!pass)
            {
                it.Axis[j].Re = 0;
            }
        }
Exemplo n.º 16
0
        private async Task ReceiveEnvelopeAsync(Envelope envelope, Dispatcher dispatcher)
        {
            var envelopeViewModel = new EnvelopeViewModel
            {
                Envelope  = envelope,
                Direction = DataOperation.Receive
            };

            await await dispatcher.InvokeAsync(async() =>
            {
                Envelopes.Add(envelopeViewModel);

                foreach (var macro in Macros.Where(m => m.IsActive))
                {
                    await macro.Macro.ProcessAsync(envelopeViewModel, this);
                }
            });
        }
Exemplo n.º 17
0
        /// <summary>
        /// Creates levels in the highest Envelope, including a higher mechanical Level below the top of the Envelope.
        /// </summary>
        /// <param name="stdHeight">Desired height for repeating Levels.</param>
        /// <param name="pntHeight">Desired height for mechanical Levels</param>
        private void HighLevels(double stdHeight, double pntHeight)
        {
            if (Envelopes.Where(e => e.Elevation >= 0.0).ToList().Count() < 2)
            {
                return;
            }
            // Add penthouse level and roof level to highest Envelope.
            var envelope   = Envelopes.Last();
            var bldgHeight = envelope.Elevation + envelope.Height;

            MakeLevel(envelope, bldgHeight);

            // Create temporary envelope to populate the region beneath the penthouse level.
            envelope = new Envelope(envelope.Profile.Perimeter, envelope.Elevation, envelope.Height - pntHeight,
                                    Vector3.ZAxis, 0.0, envelope.Transform, null, envelope.Representation,
                                    false, Guid.NewGuid(), "");
            MakeLevels(envelope, stdHeight, false, true);
            Levels          = Levels.OrderBy(l => l.Elevation).ToList();
            LevelPerimeters = LevelPerimeters.OrderBy(l => l.Elevation).ToList();
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates Levels within the subgrade and ongrade Envelopes.
        /// </summary>
        /// <param name="stdHeights">The list of desired height for repeating Levels.</param>
        private void GradeLevels(IList <double> stdHeights)
        {
            var envelopes = Envelopes.Where(e => e.Elevation >= 0.0).ToList();

            if (envelopes.Count() == 0)
            {
                return;
            }
            var envelope = envelopes.First();
            var subs     = Envelopes.Where(e => e.Elevation < 0.0).ToList();

            if (subs.Count() == 0) // if no subgrade levels created, add the first Level.
            {
                MakeLevel(envelope, envelope.Elevation);
            }
            double elevation = 0;

            // Populate explicity defined levels
            foreach (double height in stdHeights)
            {
                elevation = elevation + height;
                MakeLevel(envelope, elevation);
            }

            // Populate the rest of the levels

            if (envelope.Height >= elevation)
            {
                // Temporary Envelope to populate levels above the explicity defined levels.
                envelope = new Envelope(envelope.Profile, elevation, envelope.Height - elevation,
                                        Vector3.ZAxis, 0.0, new Transform(0.0, 0.0, elevation), null, null,
                                        false, Guid.NewGuid(), "");
                MakeLevels(envelope, stdHeights.Last(), false, true);
            }
            else
            {
                MakeLevel(envelope, envelope.Height);
            }
            Levels          = Levels.OrderBy(l => l.Elevation).ToList();
            LevelPerimeters = LevelPerimeters.OrderBy(l => l.Elevation).ToList();
        }
Exemplo n.º 19
0
        static Vector CreateMidiVector(Complex[] fft)
        {
            int N = fft.Length * 2;

            Debug.Assert(N == 1024);
            double[] im       = new double[128];
            Vector   vec      = new Vector("𝅘𝅥𝅮", null, im);
            var      duration = Math.Round(
                (double)N / Wav._hz, 5);

            Debug.Assert((int)(duration * Wav._hz) == N);
            vec.Score.Re = duration;
            vec.Score.Im = N;
            for (int i = 0; i < fft.Length; i++)
            {
                double h   = Wav._hz / (double)N,
                       f   = i * h;
                double vol = fft[i].Abs();
                var    m   = Envelopes.FREQ2MIDI(f);
                if (m >= 0 && m < vec.Axis.Length && vol > 1E-3)
                {
                    vec.Axis[m].Re += vol;
                    vec.Axis[m].Im += 1;
                }
            }
            for (int m = 0; m < vec.Axis.Length; m++)
            {
                if (vec.Axis[m].Im == 0)
                {
                    vec.Axis[m].Re = 0;
                }
                else
                {
                    vec.Axis[m].Re /= vec.Axis[m].Im;
                }
                vec.Axis[m].Im = Envelopes.MIDI2FREQ(m);
                Debug.Assert(Envelopes.FREQ2MIDI(vec.Axis[m].Im) == m);
            }
            Debug.Assert(vec.Axis[69].Im == 440);
            return(vec);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Creates Levels in middle-height Envelopes.
        /// </summary>
        /// <param name="stdHeight">Desired height for repeating Levels.</param>
        private void MidLevels(double stdHeight)
        {
            if (Envelopes.Where(e => e.Elevation >= 0.0).ToList().Count() < 3)
            {
                return;
            }
            // Remove completed Levels from Envelope list.
            var envelopes = new List <Envelope>();

            envelopes.AddRange(Envelopes.Where(e => e.Elevation >= 0.0).Skip(1).ToList());
            envelopes = envelopes.SkipLast(1).ToList();

            // Add standard height Levels.
            foreach (var envelope in envelopes)
            {
                //Skip the last level so we don't get redundant levels at the top of one envelope and the bottom of the next.
                MakeLevels(envelope, stdHeight, false, true);
            }
            Levels          = Levels.OrderBy(l => l.Elevation).ToList();
            LevelPerimeters = LevelPerimeters.OrderBy(l => l.Elevation).ToList();
        }
Exemplo n.º 21
0
        static void RunSpeachFrequencyFilters(Vector vec, int j)
        {
            bool IsAudible(double f)
            {
                if ((f >= 8.1 && f <= 16743.9))
                {
                    return(true);
                }
                return(false);
            }

            if (!IsAudible(vec.Axis[j].Im))
            {
                vec.Axis[j].Re = 0;
            }
            var n = Envelopes.MIDI2NOTE(Envelopes.FREQ2MIDI(vec.Axis[j].Im));

            if (string.IsNullOrWhiteSpace(n)
                // || n.Contains("#")
                // || n.Contains("0")
                // || n.Contains("1")
                // || n.Contains("2")
                // || n.Contains("3")
                // || n.Contains("4")
                // || n.Contains("5")
                // || n == "C6"
                // || n == "E6"
                // || n == "D6"
                // || n == "A6"
                // || n == "F6"
                // || n == "G6"
                // || n == "B6"
                // || n.Contains("7")
                // || n.Contains("8")
                // || n.Contains("9")
                )
            {
                vec.Axis[j].Re = 0;
            }
        }
Exemplo n.º 22
0
/// <summary>
///  Main Initialization...
/// </summary>
        protected override void Init()
        {
            InitLogFile();
            if (LogMode)
            {
                Print("Log mode is on. Path to log file: {0}", trueLogPath);
            }

            #region GetIndicatorsAndFrames

            XXPrint("Starting TS on account: {0}, comment: {1}, buystop : {2} sellstop : {3}", this.Account.Number, "CommentText", listOfBuyStop.Count, listOfSellStop.Count);

            _period    = Timeframe;
            _barSeries = GetCustomSeries(Instrument.Id,
                                         _period);

            EnvindTP = GetIndicator <Envelopes>(Instrument.Id,
                                                _period,
                                                envelopesTPperiod,
                                                envelopesTPdev,
                                                envelopesTPshift,
                                                envelopesTPmethod,
                                                envelopesTPprice);
            EnvindSL = GetIndicator <Envelopes>(Instrument.Id,
                                                _period,
                                                envelopesSLperiod,
                                                envelopesSLdev,
                                                envelopesSLshift,
                                                envelopesSLmethod,
                                                envelopesSLprice);
            EnvindSIGN = GetIndicator <Envelopes>(Instrument.Id,
                                                  _period,
                                                  envelopesSIGNperiod,
                                                  envelopesSIGNdev,
                                                  envelopesSIGNshift,
                                                  envelopesSIGNmethod,
                                                  envelopesSIGNprice);

            #endregion      GetIndicatorsAndFrames
        }
Exemplo n.º 23
0
Arquivo: Mel.cs Projeto: azret/mozart
        static Vector MelFromFourier(Complex[] STFT)
        {
            int Fs = STFT.Length * 2;

            Debug.Assert(Fs == 1024 * 2);
            double[] re = new double[CBOW.DIMS],
            im = new double[CBOW.DIMS],
            cc = new double[CBOW.DIMS];
            for (int i = 0; i < STFT.Length; i++)
            {
                double h = Wav._hz / (double)Fs,
                       f = i * h;
                var m    = Envelopes.FREQ2MIDI(f);
                Debug.Assert(m == Envelopes.FREQ2MIDI(Envelopes.MIDI2FREQ(m)));
                if (m >= 0 && m < CBOW.DIMS)
                {
                    re[m] += STFT[i].Abs();
                    cc[m] += +1;
                }
            }
            for (int m = 0; m < CBOW.DIMS; m++)
            {
                // Normalize
                if (cc[m] > 0)
                {
                    re[m] /= cc[m];
                }
                im[m] = Envelopes.MIDI2FREQ(m);
            }
            Vector it       = new Vector("𝆕", re, im);
            var    duration = Math.Round((double)Fs / Wav._hz, 5);

            Debug.Assert((int)(duration * Wav._hz) == Fs);
            double scale = 1.6;

            it.Score.Re = scale * duration;
            return(it);
        }
Exemplo n.º 24
0
    void ImportEnvelope(XmlElement elt, Envelopes envelopes)
    {
        EnvelopeType type           = ChildEnvelopeType(elt, "Type");
        Boolean      isSurroundMode = (myVegas.Project.Audio.MasterBusMode == AudioBusMode.Surround);
        Envelope     envelope       = null;

        switch (type)
        {
        case EnvelopeType.PanY:
        case EnvelopeType.PanSmoothness:
        case EnvelopeType.PanCenter:
            // skip surround-related envelopes if not in surround mode
            if (!isSurroundMode)
            {
                return;
            }
            // make sure the surround pan position x envelope exists
            Envelope panEnvelope = envelopes.FindByType(EnvelopeType.Pan);
            if (null == panEnvelope)
            {
                panEnvelope = new Envelope(EnvelopeType.Pan);
                envelopes.Add(panEnvelope);
            }
            envelope = envelopes.FindByType(type);
            if (null == envelope)
            {
                throw new ApplicationException("Failed to create envelope of type: " + type.ToString());
            }
            break;

        default:
            envelope = new Envelope(type);
            envelopes.Add(envelope);
            break;
        }
        ImportPoints(elt, envelope.Points);
    }
Exemplo n.º 25
0
/// <summary>
///  Main Initialization...
/// </summary>
        protected override void Init()
        {
            InitLogFile();
            #region GetIndicatorsAndFrames// Get Indicators' references...

            XXPrint("Starting TS on account: {0}", this.Account.Number);

            _period    = Timeframe;
            _barSeries = GetCustomSeries(Instrument.Id,
                                         _period);

            EnvindTP = GetIndicator <Envelopes>(Instrument.Id,
                                                _period,
                                                envelopesTPperiod,
                                                envelopesTPdev,
                                                envelopesTPshift,
                                                envelopesTPmethod,
                                                envelopesTPprice);
            EnvindSL = GetIndicator <Envelopes>(Instrument.Id,
                                                _period,
                                                envelopesSLperiod,
                                                envelopesSLdev,
                                                envelopesSLshift,
                                                envelopesSLmethod,
                                                envelopesSLprice);
            EnvindSIGN = GetIndicator <Envelopes>(Instrument.Id,
                                                  _period,
                                                  envelopesSIGNperiod,
                                                  envelopesSIGNdev,
                                                  envelopesSIGNshift,
                                                  envelopesSIGNmethod,
                                                  envelopesSIGNprice);

            // Event occurs once at the start of the strategy
            #endregion //GetIndicatorsAndFrames
        }
Exemplo n.º 26
0
        public Mesh LoadFromStream(EndianBinaryReader reader)
        {
            MeshVertexAttributeHolder vertexData = null;
            SceneNode        rootNode            = new SceneNode();
            List <Texture2D> textureList         = new List <Texture2D>();
            List <WEditor.Common.Nintendo.J3D.Material> materialList = null;
            List <SkeletonBone> joints    = new List <SkeletonBone>();
            DrawInfo            drawInfo  = null;
            Envelopes           envelopes = null;

            Mesh j3dMesh = new Mesh();

            // Read the Header
            int magic = reader.ReadInt32(); // J3D1, J3D2, etc

            if (magic != 1244873778)
            {
                WLog.Warning(LogCategory.ModelLoading, null, "Attempted to load model with invalid magic, ignoring!");
                return(null);
            }

            int j3dType       = reader.ReadInt32(); // BMD3 (models) BDL4 (models), jpa1 (particles), bck1 (animations), etc.
            int totalFileSize = reader.ReadInt32();
            int chunkCount    = reader.ReadInt32();

            // Skip over an unused tag (consistent in all files) and some padding.
            reader.ReadBytes(16);

            for (int i = 0; i < chunkCount; i++)
            {
                long chunkStart = reader.BaseStream.Position;

                string tagName   = reader.ReadString(4);
                int    chunkSize = reader.ReadInt32();

                switch (tagName)
                {
                // INFO - Vertex Count, Scene Hierarchy
                case "INF1":
                    rootNode = LoadINF1FromFile(rootNode, reader, chunkStart);
                    break;

                // VERTEX - Stores vertex arrays for pos/normal/color0/tex0 etc. Contains VertexAttributes which describe
                // how this data is stored/laid out.
                case "VTX1":
                    vertexData = LoadVTX1FromFile(reader, chunkStart, chunkSize);
                    break;

                // ENVELOPES - Defines vertex weights for skinning.
                case "EVP1":
                    envelopes = LoadEVP1FromStream(reader, chunkStart);
                    break;

                // DRAW (Skeletal Animation Data) - Stores which matrices are weighted, and which are used directly.
                case "DRW1":
                    drawInfo = LoadDRW1FromStream(reader, chunkStart);
                    break;

                // JOINTS - Stores the skeletal joints (position, rotation, scale, etc.)
                case "JNT1":
                    joints = LoadJNT1SectionFromStream(reader, chunkStart);
                    break;

                // SHAPE - Face/Triangle information for model.
                case "SHP1":
                    LoadSHP1SectionFromFile(vertexData, j3dMesh, reader, chunkStart);
                    break;

                // MATERIAL - Stores materials (which describes how textures, etc. are drawn)
                case "MAT3":
                    materialList = LoadMAT3SectionFromStream(reader, chunkStart, chunkSize);
                    break;

                // TEXTURES - Stores binary texture images.
                case "TEX1":
                    textureList = LoadTEX1FromFile(reader, chunkStart);
                    break;

                // MODEL - Seems to be bypass commands for Materials and invokes GX registers directly.
                case "MDL3":
                    break;
                }

                reader.BaseStream.Position = chunkStart + chunkSize;
            }

            // Resolve the texture indexes into actual textures now that we've loaded the TEX1 section.
            foreach (Material mat in materialList)
            {
                for (int i = 0; i < mat.TextureIndexes.Length; i++)
                {
                    short index = mat.TextureIndexes[i];
                    if (index < 0)
                    {
                        continue;
                    }

                    mat.Textures[i] = textureList[index];
                }
            }

            // loltests
            for (int i = 0; i < materialList.Count; i++)
            {
                materialList[i].VtxDesc = j3dMesh.SubMeshes[0].GetVertexDescription();
                Shader shader = TEVShaderGenerator.GenerateShader(materialList[i]);
                materialList[i].Shader = shader;
            }

            // We're going to do something a little crazy - we're going to read the scene view and apply textures to meshes (for now)
            Material curMat = null;

            AssignMaterialsToMeshRecursive(rootNode, j3dMesh, ref curMat, materialList);


            List <SkeletonBone> skeleton = new List <SkeletonBone>();

            BuildSkeletonRecursive(rootNode, skeleton, joints, 0);

            j3dMesh.Skeleton  = skeleton;
            j3dMesh.BindPoses = envelopes.inverseBindPose;

            // Let's do some ugly post-processing here to see if we can't resolve all of the cross-references and turn it into
            // a normal computer-readable format that we can digest in our RenderSytem.
            {
                for (int i = 0; i < j3dMesh.SubMeshes.Count; i++)
                {
                    MeshBatch batch = j3dMesh.SubMeshes[i];
                    batch.BoneWeights = new BoneWeight[batch.Vertices.Length];

                    for (int j = 0; j < batch.PositionMatrixIndexs.Count; j++)
                    {
                        // Okay so this is where it gets more complicated. The PMI gives us an index into the MatrixTable for the packet, which we
                        // resolve and call "drawIndexes" - however we have to divide the number they give us by three for some reason, so that is
                        // already done and now our drawIndexes array should be one-index-for-every-vertex-in-batch and it should be the index into
                        // the draw section we need.
                        ushort drw1Index = batch.drawIndexes[j];

                        // The drw1Index can be set as 0xFFFF - if so, this means that you need to use the dr1Index of the previous one.
                        // until it is no longer 0xFFFF.
                        int counter = 0;
                        while (drw1Index == 0xFFFF)
                        {
                            drw1Index = batch.drawIndexes[j - counter];
                            counter++;
                        }


                        bool       isWeighted = drawInfo.IsWeighted[drw1Index];
                        BoneWeight weight     = new BoneWeight();

                        if (isWeighted)
                        {
                            // Something on this doesn't work for models that actually specify a PositionMatrixIndex.
                            // So... some math is off somewhere and I don't know where for the moment.
                            ushort numBonesAffecting = envelopes.numBonesAffecting[drw1Index];
                            weight.BoneIndexes = new ushort[numBonesAffecting];
                            weight.BoneWeights = new float[numBonesAffecting];

                            // "Much WTFs"
                            ushort offset = 0;
                            for (ushort e = 0; e < envelopes.indexRemap[drw1Index]; e++)
                            {
                                offset += envelopes.numBonesAffecting[e];
                            }

                            offset *= 2;
                            Matrix4 finalTransform = Matrix4.Identity;
                            for (ushort k = 0; k < numBonesAffecting; k++)
                            {
                                ushort boneIndex  = envelopes.indexRemap[offset + (k * 0x2)];
                                float  boneWeight = envelopes.weights[(offset / 2) + k];

                                weight.BoneIndexes[k] = boneIndex;
                                weight.BoneWeights[k] = boneWeight;

                                // This was apaprently a partial thought I never finished or got working in the old one? :S
                            }
                        }
                        else
                        {
                            // If the vertex isn't weighted, we just use the position from the bone matrix.
                            SkeletonBone joint       = skeleton[drawInfo.Indexes[drw1Index]];
                            Matrix4      translation = Matrix4.CreateTranslation(joint.Translation);
                            Matrix4      rotation    = Matrix4.CreateFromQuaternion(joint.Rotation);
                            Matrix4      finalMatrix = rotation * translation;

                            // Move the mesh by transforming the position by this much.

                            // I think we can just assign full weight to the first bone index and call it good.
                            weight.BoneIndexes = new[] { drawInfo.Indexes[drw1Index] };
                            weight.BoneWeights = new[] { 1f };
                        }

                        batch.BoneWeights[j] = weight;
                    }
                }
            }

            return(j3dMesh);
        }
Exemplo n.º 27
0
 public Task OnEnvelopeAsync(T envelope, CancellationToken cancellationToken)
 {
     Envelopes.Add(envelope);
     return(Task.CompletedTask);
 }
Exemplo n.º 28
0
    static void ParseNotes(Matrix Model, string sl, int dims)
    {
        int i = 0, wordStart = i;

        while (i < sl.Length && (sl[i] == '\t' || sl[i] == ' ' ||
                                 sl[i] == '•' || sl[i] == '|' || sl[i] == '⁞'))
        {
            i++;
        }
        Vector vec;
        int    t = Model.Count;

        if (t >= Model.Capacity)
        {
            throw new OutOfMemoryException();
        }
        vec = new Vector("𝆕");
        if (vec.Axis == null)
        {
            vec.Axis = new Complex[dims];
        }
        Model[t] = vec;
        for (; ;)
        {
            wordStart = i;
            while (i < sl.Length && (sl[i] == '±' || sl[i] == '-' || sl[i] == '+' || sl[i] == 'E' ||
                                     sl[i] == 'A' || sl[i] == 'B' || sl[i] == 'C' ||
                                     sl[i] == 'D' || sl[i] == 'F' || sl[i] == 'G' ||
                                     sl[i] == '#' ||
                                     sl[i] == '.' || char.IsDigit(sl[i])))
            {
                i++;
            }
            var ImSign = +1;
            int len    = (i - wordStart) - 1;
            while (wordStart + len > 0 && wordStart + len < sl.Length &&
                   (sl[wordStart + len] == '-' || sl[wordStart + len] == '+' || sl[wordStart + len] == '±'))
            {
                if (sl[wordStart + len] == '-')
                {
                    ImSign = -1;
                }
                len--;
            }
            string Re = sl.Substring(wordStart, len + 1);
            string Im = null;
            if (i < sl.Length && (sl[i] == 'i'))
            {
                i++;
                wordStart = i;
                while (i < sl.Length && (sl[i] == '-' || sl[i] == '+' || sl[i] == 'E' ||
                                         sl[i] == 'A' || sl[i] == 'B' || sl[i] == 'C' ||
                                         sl[i] == 'D' || sl[i] == 'F' || sl[i] == 'G' ||
                                         sl[i] == '#' ||
                                         sl[i] == '.' || char.IsDigit(sl[i])))
                {
                    i++;
                }
                Im = sl.Substring(wordStart, i - wordStart);
            }
            if (!string.IsNullOrWhiteSpace(Re))
            {
                var f = Envelopes.NOTE2FREQ(Re);
                int m = Envelopes.FREQ2MIDI(f);
                if (m >= 0 && m < vec.Axis.Length)
                {
                    vec.Axis[m].Im = f;
                    vec.Axis[m].Re = 1;
                    if (!string.IsNullOrWhiteSpace(Im))
                    {
                        vec.Axis[m].Re = Envelopes.Amplitude((int)(ImSign * double.Parse(Im)));
                    }
                }
                while (i < sl.Length && (sl[i] == '\t' || sl[i] == ' ' || sl[i] == '•' || sl[i] == '|' || sl[i] == '⁞'))
                {
                    i++;
                }
            }
            else   /* End of Line */
            {
                break;
            }
        }
    }
        private void InitOverlays()
        {
            defaultSeries = new FinancialSeries()
            {
                Name = "Box"
            };
            bollingerBands = new BollingerBands()
            {
                Name = "Bollinger Bands"
            };
            envelopes = new Envelopes()
            {
                Name = "Envoloper"
            };
            ichimokuCloud = new IchimokuCloud()
            {
                Name = "Ichimoku Cloud",
                ConversionLineStyle = new C1.Win.Chart.ChartStyle()
                {
                    StrokeColor = Color.Orange
                },
                BaseLineStyle = new C1.Win.Chart.ChartStyle()
                {
                    StrokeColor = Color.Blue
                },
                LaggingLineStyle = new C1.Win.Chart.ChartStyle()
                {
                    StrokeColor = Color.Black
                },
                LeadingSpanALineStyle = new C1.Win.Chart.ChartStyle()
                {
                    StrokeColor = Color.LightGreen
                },
                LeadingSpanBLineStyle = new C1.Win.Chart.ChartStyle()
                {
                    StrokeColor = Color.IndianRed
                },
                BullishCloudColor = new SolidBrush(Color.LightGreen),
                BearishCloudColor = new SolidBrush(Color.IndianRed)
            };

            zigZag = new ZigZag()
            {
                Name = "ZigZag"
            };
            zigZag.Style.StrokeColor = Color.Green;
            zigZag.Style.StrokeWidth = 0.8f;

            alligator = new Alligator()
            {
                Name         = "Alligator",
                JawLineStyle = new C1.Win.Chart.ChartStyle()
                {
                    StrokeColor = Color.LightGreen
                },
                TeethLineStyle = new C1.Win.Chart.ChartStyle()
                {
                    StrokeColor = Color.IndianRed
                },
                LipsLineStyle = new C1.Win.Chart.ChartStyle()
                {
                    StrokeColor = Color.Black
                },
            };
        }
Exemplo n.º 30
0
    public void FromVegas(Vegas vegas)
    {
        Project proj = vegas.Project;

        /*foreach (Track track in proj.Tracks)
         * {
         *                      //Audio detection for later on...
         *                      if(track.Name == "Sync"){
         *                              //MessageBox.Show("Audio a Sync detectado");
         *                              foreach (TrackEvent trackEvent in track.Events)
         *                              {
         *                                      if(trackEvent.MediaType == MediaType.Audio){
         *
         *                                      }
         *                              }
         *                      }
         *
         *      }*/

        foreach (Track track in proj.Tracks)
        {
            foreach (TrackEvent trackEvent in track.Events)
            {
                if (trackEvent.MediaType == MediaType.Video && trackEvent.Selected)
                {
                    VideoEvent vevnt    = (VideoEvent)trackEvent;
                    Envelopes  vevntEnv = vevnt.Envelopes;

                    if (!vevntEnv.HasEnvelope(EnvelopeType.Velocity))                    // Comprobamos si el video tiene envolvente
                    {
                        Envelope envelope = new Envelope(EnvelopeType.Velocity);
                        vevntEnv.Add(envelope);
                    }

                    Envelope sensitivity = vevntEnv.FindByType(EnvelopeType.Velocity);
                    sensitivity.Points.Clear();

                    Timecode timeFirst = trackEvent.Start;                     //Inicio del clip en milisegundos.
                    Timecode timeLast  = trackEvent.End;                       //Fin del clip en milisegundos.


                    sensitivity.Points.GetPointAtX(Timecode.FromMilliseconds(0)).Y = 3;                      //Modificamos el valor del punto inicial

                    foreach (Marker marker in proj.Markers)                                                  //Recorremos todos los marcadores
                    {
                        if (marker.Position > timeFirst && marker.Position < timeLast && marker.Label == "") // Miramos si el marcador esta dentro del video
                        {
                            if (sensitivity.Points.GetPointAtX(marker.Position - timeFirst) == null)         // Comprobamos que no exista ya un punto en dicha posicion.

                            {
                                EnvelopePoint point = new EnvelopePoint(marker.Position - timeFirst, 0.15);                               //Creamos un nuevo punto en el marcador
                                sensitivity.Points.Add(point);
                            }
                        }
                    }

                    EnvelopePoint pointEnd = new EnvelopePoint(timeLast, 3);                    //Añadimos el punto final
                    sensitivity.Points.Add(pointEnd);
                }
            }
        }
    }
Exemplo n.º 31
0
        private async Task SendAsync(object parameter)
        {
            var times = 0;

            var repeatCountVariable = Variables.FirstOrDefault(v => v.Name == "repeatCount");

            if (repeatCountVariable == null)
            {
                repeatCountVariable = new VariableViewModel()
                {
                    Name = "repeatCount"
                };
                Variables.Add(repeatCountVariable);
            }

            do
            {
                repeatCountVariable.Value = (times + 1).ToString();

                await ExecuteAsync(async() =>
                {
                    AddStatusMessage("Sending...");

                    var inputJson = parameter.ToString();

                    if (ParseBeforeSend)
                    {
                        inputJson = ParseInput(inputJson, Variables);
                    }

                    var timeoutCancellationToken = _operationTimeout.ToCancellationToken();

                    var envelopeViewModel       = new EnvelopeViewModel(false);
                    envelopeViewModel.Json      = inputJson;
                    var envelope                = envelopeViewModel.Envelope;
                    envelopeViewModel.Direction = DataOperation.Send;

                    if (SendAsRaw)
                    {
                        envelopeViewModel.IsRaw = true;
                        var stream        = TcpClient.GetStream();
                        var envelopeBytes = Encoding.UTF8.GetBytes(envelopeViewModel.Json);
                        await stream.WriteAsync(envelopeBytes, 0, envelopeBytes.Length, timeoutCancellationToken);
                    }
                    else
                    {
                        await Transport.SendAsync(envelope, timeoutCancellationToken);
                        envelopeViewModel.IndentJson();
                    }

                    Envelopes.Add(envelopeViewModel);

                    if (ClearAfterSent)
                    {
                        InputJson = string.Empty;
                    }

                    AddStatusMessage(string.Format("{0} envelope sent", envelope.GetType().Name));
                });
            } while (Repeat && RepeatTimes > ++times);
        }