public static void Init()
        {
            _info             = new CurveInfo();
            _info.LearnMore   = "https://ru.wikipedia.org/wiki/%D0%90%D1%80%D1%85%D0%B8%D0%BC%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0_%D1%81%D0%BF%D0%B8%D1%80%D0%B0%D0%BB%D1%8C";
            _info.Name        = "Спираль Архимеда";
            _info.Discription =
                @"   Архимедова спираль — спираль, плоская кривая, траектория точки M, которая
равномерно движется вдоль луча OV сначалом в O, в то время как сам луч
OV равномерно вращается вокруг O. Другими словами, расстояние ρ = OM
пропорционально углу поворота φ луча OV. Повороту луча OV на один и тот же
угол соответствует одно и то же приращение ρ.";
            _info.Creator =
                @"   Архимедова спираль была открыта Архимедом. Это произошло в III веке до н.э.,
когда он экспериментировал с компасом.Он тянул стрелку компаса с постоянной 
скоростью, вращая сам компас по часовой стрелке. Получившаяся кривая была c
пиралью, которая сдвигались на ту же величину, на которую поворачивался компас, 
и между витками спирали сохранялось одно и то же расстояние.";
            _info.Usage =
                @"   В III веке да нашей эры Архимед на основе своей спирали изобрёл винт, который
успешно применяли для передачи воды в оросительные каналы из водоёмов, 
расположенных ниже. Позже на основе винта Архимеда создали шнек («улитку»). Его
очень известная разновидность – винтовой ротор в мясорубке. Шнек используют
в механизмах для перемешивания материалов различной консистенции. В технике 
нашли применение антенны в виде спирали Архимеда.Самоцентрирующийся патрон 
выполнен по спирали Архимеда. Звуковые дорожки на CD и DVD дисках также имеют 
форму спирали Архимеда. Спираль Архимеда нашла практическое применение в математике,
технике, архитектуре, машиностроении.";
            _info.MathematicalBasis = "p = k * phi";
        }
        public override void Initialize(PropertiesModel.Property property)
        {
            base.Initialize(property);

            m_info = property.EditorAdditionalData<CurveInfo>();
            if (m_info != null && m_info.Curves != null && m_info.Curves.Length > 0)
            {
                PlayCanvas.CurveSet curveSet = PropertyModel.Data<PlayCanvas.CurveSet>();
                if (curveSet == null)
                    curveSet = new PlayCanvas.CurveSet();
                if (curveSet.CurvesList.Count < m_info.Curves.Length)
                    for (int i = curveSet.CurvesList.Count; i < m_info.Curves.Length; ++i)
                        curveSet.CurvesList.Add(new PlayCanvas.Curve(new float[] { 0.0f, 0.0f }));
                PropertyModel.Data<PlayCanvas.CurveSet>(curveSet);
            }

            m_curvePictureBox = new PictureBox();
            m_curvePictureBox.Cursor = Cursors.Hand;
            m_curvePictureBox.Width = 0;
            m_curvePictureBox.Height = 48;
            m_curvePictureBox.BackColor = Color.FromArgb(255, 64, 64, 64);
            m_curvePictureBox.Dock = DockStyle.Top;
            m_curvePictureBox.Click += m_curvePictureBox_Click;
            m_curvePictureBox.Resize += m_curvePictureBox_Resize;
            m_curvePictureBox.Paint += m_curvePictureBox_Paint;
            Content.Controls.Add(m_curvePictureBox);

            UpdateEditor();
        }
        public static void Init()
        {
            _info             = new CurveInfo();
            _info.Name        = "Логарифмическая спираль";
            _info.LearnMore   = "https://ru.wikipedia.org/wiki/%D0%9B%D0%BE%D0%B3%D0%B0%D1%80%D0%B8%D1%84%D0%BC%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B0%D1%8F_%D1%81%D0%BF%D0%B8%D1%80%D0%B0%D0%BB%D1%8C";
            _info.Discription =
                @"   Логарифми́ческая спира́ль или изогональная спираль — особый вид спирали, 
часто встречающийся в природе.";
            _info.Creator =
                @"   Логарифмическая спираль была впервые описана Декартом и позже 
интенсивно исследована Бернулли, который называл её Spira mirabilis —
«удивительная спираль». Декарт искал кривую, обладающую свойством,
подобным свойству окружности, так чтобы касательная в каждой точке 
образовывала с радиус-вектором в каждой точке один и тот же угол. Он
показал, что это условие равносильно тому, что полярные углы для точек 
кривой пропорциональны логарифмам радиус-векторов.";
            _info.Usage =
                @"   Логарифмическая спираль, несомненно, является спиралью, которая 
наиболее часто встречается в природе. Царство животных предоставляет нам 
примеры спиралей раковин улиток и моллюсков. Все эти формы указывают на 
природное явление: процесс накручивания связан с процессом роста. В самом
деле, раковина улитки – это не больше, не меньше, чем конус, накрученный
на себя. Рога жвачных животных тоже, но они к тому же витые. И хотя физические
законы роста у разных видов различны, математические законы, которые управляют 
ими, одинаковы: все они имеют в основе геометрическую спираль, самоподобную
кривую. Если мы внимательно посмотрим на рост раковин и рогов, то заметим
еще одно любопытное свойство: рост происходит только на одном конце. И это
свойство сохраняет форму полностью уникальную среди кривых в математике, форму 
логарифмической, или равноугольной спирали.";
        }
            public int CompareTo(CurveInfo otherCurve)
            {
                int result = jointIndex.CompareTo(otherCurve.jointIndex);

                if (result == 0)
                {
                    result = curveIndex.CompareTo(otherCurve.curveIndex);
                }

                return(result);
            }
        public static void UpdateData(string curveData)
        {
            try
            {
                string[] curves = curveData.Split(',');
                long     index;
                if (curves != null && curves.Length > 0)
                {
                    index = Convert.ToInt64(curves[0]);
                    if (!LSTCurvesData.Contains(curveData))
                    {
                        LSTCurvesData.Add(curveData);
                    }

                    foreach (string header in LSTCurveHeaders)
                    {
                        CurveInfo[] infos = LSTIndexInfo.Where(x => (x.Name.TrimEnd().TrimStart() == header.TrimEnd().TrimStart())).ToArray();
                        if (infos.Length > 0)
                        {
                            if (infos[0].MaxIndex < index)
                            {
                                infos[0].MaxIndex = index;
                            }

                            if (infos[0].MinIndex > index)
                            {
                                infos[0].MinIndex = index;
                            }
                        }
                        else
                        {
                            CurveInfo info = new CurveInfo()
                            {
                                Name = header, MaxIndex = index, MinIndex = index
                            };
                            if (!LSTIndexInfo.Contains(info))
                            {
                                LSTIndexInfo.Add(info);
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("Empty or Invalid data received");
                }
            }
            catch (Exception ex)
            {
                Logger.WrieException(string.Format("Data Subscription failed - {0}", ex.Message));
                throw new Exception(string.Format("Data Subscription failed - {0}", ex.Message));
            }
        }
Beispiel #6
0
        public static void Init()
        {
            _info             = new CurveInfo();
            _info.Name        = "Спираль Ферма";
            _info.LearnMore   = "https://ru.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%80%D0%B0%D0%BB%D1%8C_%D0%A4%D0%B5%D1%80%D0%BC%D0%B0";
            _info.Discription =
                @"   Спираль Ферма (иногда параболическая спираль) — спираль, задаваемая на
плоскости в полярных координатах уравнением r^2 = a^2 * phi. Является видом
Архимедовой спирали.";
            _info.Creator = "";
            _info.Usage   = "";
        }
        private void ProcessBinSRM(
            List <ChromatogramLoadingStatus.TransitionData.Peak> bin,
            ref bool peaksAdded,
            ref float maxTime,
            ref float maxIntensity)
        {
            float retentionTime = bin[0].BinIndex * ChromatogramLoadingStatus.TIME_RESOLUTION;

            maxTime    = Math.Max(maxTime, retentionTime);
            peaksAdded = true;

            foreach (var peak in bin)
            {
                // New peptide curve.
                if (_lastCurve == null || !ReferenceEquals(peak.ModifiedSequence, _lastCurve.ModifiedSequence))
                {
                    _lastCurve = new CurveInfo(peak.ModifiedSequence, peak.Color, retentionTime, peak.Intensity);
                    _graphPane.CurveList.Add(_lastCurve.Curve);
                    maxIntensity = Math.Max(maxIntensity, peak.Intensity);
                    continue;
                }

                // Add intensity to existing peptide curve.
                for (int i = _lastCurve.Curve.NPts - 1; i >= 0; i--)
                {
                    int binIndex = ChromatogramLoadingStatus.GetBinIndex((float)_lastCurve.Curve.Points[i].X);
                    if (binIndex > peak.BinIndex)
                    {
                        if (i == 0)
                        {
                            _lastCurve.InsertAt(0, retentionTime, peak.Intensity);
                            _lastCurve.CheckZeroes(0);
                            maxIntensity = Math.Max(maxIntensity, peak.Intensity);
                        }
                    }
                    else if (binIndex == peak.BinIndex)
                    {
                        _lastCurve.Curve.Points[i].Y += peak.Intensity;
                        _lastCurve.CheckZeroes(i);
                        maxIntensity = Math.Max(maxIntensity, (float)_lastCurve.Curve.Points[i].Y);
                        break;
                    }
                    else
                    {
                        _lastCurve.InsertAt(i + 1, retentionTime, peak.Intensity);
                        _lastCurve.CheckZeroes(i + 1);
                        maxIntensity = Math.Max(maxIntensity, peak.Intensity);
                        break;
                    }
                }
            }
        }
Beispiel #8
0
    void OnGUI()
    {
        if (Event.current.type == EventType.repaint && (lastWidth != Screen.width || lastHeight != Screen.height || curveInfs.Count == 0))
        {
            lastWidth  = Screen.width;
            lastHeight = Screen.height;
            float width      = Screen.width - border * 2;
            float height     = Screen.height - border * 2 - 20;
            int   row        = Mathf.CeilToInt(Mathf.Sqrt((int)MathUtil.EaseType.max * height / width));
            int   col        = Mathf.FloorToInt((int)MathUtil.EaseType.max / row) + 1;
            float itemWidth  = width / col;
            float itemHeight = height / row;
            gridW = itemWidth / 2;
            gridH = itemHeight / 2;
            curveInfs.Clear();
            for (int i = 1; i < (int)MathUtil.EaseType.max; ++i)
            {
                int       itemRow = (i - 1) / col;
                int       itemCol = (i - 1) % col;
                CurveInfo info    = new CurveInfo();
                curveInfs.Add(info);
                info.rc   = new Rect(border + itemCol * itemWidth, border + itemRow * itemHeight, itemWidth, itemHeight);
                info.name = ((MathUtil.EaseType)i).ToString();

                for (int j = 0; j < CurveInfo.COUNT; ++j)
                {
                    float h = 1 - MathUtil.Curve((MathUtil.EaseType)i, 0, 1, j * CurveInfo.UNIT);

                    info.pts[j] = new Vector3(info.rc.x + j * CurveInfo.UNIT * itemWidth, info.rc.y + h * itemHeight);
                }
            }
        }



        Color c = Handles.color;

        Handles.color = Color.green;
        foreach (var curveInfo in curveInfs)
        {
            //GUI.Box(curveInfo.rc, GUIContent.none, EditorUtil.BoxStyle(new Color(0.2f, 0.2f, 0.2f)));


            EditorGUI.LabelField(curveInfo.rc, curveInfo.name);

            Handles.DrawPolyLine(curveInfo.pts);
        }

        Handles.color = c;
    }
        public static void Init()
        {
            _info             = new CurveInfo();
            _info.LearnMore   = "https://ru.wikipedia.org/wiki/%D0%96%D0%B5%D0%B7%D0%BB_(%D0%BF%D0%BB%D0%BE%D1%81%D0%BA%D0%B0%D1%8F_%D0%BA%D1%80%D0%B8%D0%B2%D0%B0%D1%8F)";
            _info.Name        = " рива¤: ∆езл";
            _info.Discription =
                @"   ∆езл Ч плоска¤ трансцендентна¤ крива¤, определ¤ема¤ уравнением (в 
пол¤рной системе) p = a / sqrt(phi). рива¤ стремитс¤ из бесконечности
(где она асимптотически приближаетс¤ к горизонтальной оси) к точке (0;0),
закручива¤сь вокруг неЄ по спирали против часовой стрелки. –азмер спирали 
определ¤етс¤ коэффициентом a. »меет одну точку перегиба Ч (1/2; a*sqrt(2))";
            _info.Creator           = "";
            _info.Usage             = "";
            _info.MathematicalBasis = "p = k * phi";
        }
Beispiel #10
0
        public static void Init()
        {
            _info             = new CurveInfo();
            _info.Name        = "Синусоидальная спираль";
            _info.LearnMore   = "https://ru.wikipedia.org/wiki/%D0%A1%D0%B8%D0%BD%D1%83%D1%81%D0%BE%D0%B8%D0%B4%D0%B0%D0%BB%D1%8C%D0%BD%D0%B0%D1%8F_%D1%81%D0%BF%D0%B8%D1%80%D0%B0%D0%BB%D1%8C";
            _info.Discription =
                @"   Синусоида́льная спира́ль — семейство плоских кривых, определяемых классом
уравнений в полярных координатах r^n = a^n * sin(phi * n),где a — ненулевая
константа и n — рациональное число, не равное нулю. С учётом возможности
поворота кривой относительно начала координат уравнение также может быть
записано в виде r^n = a^n * cos(phi * n). Использование термина «спираль» в
данном случае не является точным, так как получаемые кривые по форме скорее
напоминают цветок.";
            _info.Creator = "";
            _info.Usage   = "";
        }
        public static void Init()
        {
            _info             = new CurveInfo();
            _info.LearnMore   = "https://ru.wikipedia.org/wiki/%D0%9A%D0%BE%D1%85%D0%BB%D0%B5%D0%BE%D0%B8%D0%B4%D0%B0";
            _info.Name        = "Кохлеоида";
            _info.Discription =
                @"   Кохлео́ида — плоская трансцендентная кривая. Возможны несколько способов
определить кохлеоиду геометрически. Рассмотрим всевозможные дуги данной
окружности, имеющие начало в одной и той же точке A. Тогда центры тяжести
таких дуг образуют кохлеоиду. Рассмотрим всевозможные окружности, касающиеся
данной прямой в одной и той же точке M. Отложим на каждой окружности от
точки M дугу заданной длины a. Тогда концы дуг образуют кохлеоиду.";
            _info.Creator           = "";
            _info.Usage             = "";
            _info.MathematicalBasis = "p = k * phi";
        }
Beispiel #12
0
        void MainForm_Load(object sender, EventArgs e)
        {
            var plusButton = new Button
            {
                Text   = "+",
                Width  = 80,
                Height = 24
            };
            var minusButton = new Button
            {
                Left   = 80,
                Width  = 80,
                Height = 24,
                Text   = "-"
            };
            var comboBox = new ComboBox
            {
                Left          = 160,
                Width         = 80,
                DisplayMember = "Name",
                Items         =
                {
                    new CentralCircleInfo(2),
                    new EllipticCurveInfo()
                },
                DropDownStyle = ComboBoxStyle.DropDownList
            };

            plusButton.Click  += (o, args) => PlusButton_Click(plusButton, minusButton, (CurveInfo)comboBox.SelectedItem);
            minusButton.Click += (o, args) => MinusButton_Click(plusButton, minusButton, (CurveInfo)comboBox.SelectedItem);

            comboBox.SelectedIndexChanged += (o, args) =>
            {
                selectedCurve = comboBox.SelectedItem as CurveInfo;
                painter.Paint(selectedCurve, pixelsInUnit);
            };

            SizeChanged += (a, b) => painter.Paint(selectedCurve, pixelsInUnit);

            Controls.Add(plusButton);
            Controls.Add(minusButton);
            Controls.Add(comboBox);

            MinimumSize = new Size(WindowWidth, WindowHeight);
            MaximumSize = new Size(WindowWidth, WindowHeight);
        }
Beispiel #13
0
        void MinusButton_Click(Button plus, Button minus, CurveInfo curve)
        {
            if (pixelsInUnit > 32)
            {
                pixelsInUnit /= 2;
                plus.Enabled  = true;
                minus.Enabled = true;
            }
            else
            {
                pixelsInUnit  = 16;
                plus.Enabled  = true;
                minus.Enabled = false;
            }

            painter.Paint(curve, pixelsInUnit);
        }
Beispiel #14
0
        void PlusButton_Click(Button plus, Button minus, CurveInfo curve)
        {
            if (pixelsInUnit < 256)
            {
                pixelsInUnit *= 2;
                plus.Enabled  = true;
                minus.Enabled = true;
            }
            else
            {
                pixelsInUnit  = 512;
                plus.Enabled  = false;
                minus.Enabled = true;
            }

            painter.Paint(curve, pixelsInUnit);
        }
        public static void Init()
        {
            _info             = new CurveInfo();
            _info.Name        = "Эпициклоида";
            _info.LearnMore   = "https://ru.wikipedia.org/wiki/%D0%AD%D0%BF%D0%B8%D1%86%D0%B8%D0%BA%D0%BB%D0%BE%D0%B8%D0%B4%D0%B0";
            _info.Discription =
                @"   Эпицикло́ида (от греч. ὲπί — на, над, при и κυκλος — круг, окружность) —
плоская кривая, образуемая фиксированной точкой окружности, катящейся по
внешней стороне другой окружности без скольжения.
    Величина k определяет форму эпициклоиды. При k=1 эпициклоида образует
кардиоиду, а при k=2 — нефроиду. Если k — несократимая дробь вида m/n,
то m — это количество каспов данной эпициклоиды, а n — количество полных
вращений катящейся окружности. Если k иррациональное число, то кривая
является незамкнутой и имеет бесконечное множество несовпадающих каспов.";
            _info.Creator = "";
            _info.Usage   = "";
        }
Beispiel #16
0
        public static void Init()
        {
            _info             = new CurveInfo();
            _info.Name        = "Спирали Пуансо";
            _info.LearnMore   = "https://ru.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%80%D0%B0%D0%BB%D0%B8_%D0%9F%D1%83%D0%B0%D0%BD%D1%81%D0%BE";
            _info.Discription =
                @"   Спирали Пуансо (англ. Poinsot's spirals) — два типа спиралей, задаваемых
уравнениями:

   r = a * csch(n * phi)

   r = a * sech(n * phi)

где csch обозначает гиперболический косеканс, sech обозначает гиперболический
секанс. Спирали названы в честь французского математика Луи Пуансо.";
            _info.Creator = "";
            _info.Usage   = "";
        }
Beispiel #17
0
        public static void Init()
        {
            _info             = new CurveInfo();
            _info.LearnMore   = "https://ru.wikipedia.org/wiki/%D0%93%D0%B8%D0%BF%D0%B5%D1%80%D0%B1%D0%BE%D0%BB%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B0%D1%8F_%D1%81%D0%BF%D0%B8%D1%80%D0%B0%D0%BB%D1%8C";
            _info.Name        = "√иперболическа¤ —пираль";
            _info.Discription =
                @"   √иперболическа¤ спираль Ч плоска¤ трансцендентна¤ крива¤. ”равнение
гиперболической спирали в пол¤рной систем координат ¤вл¤етс¤ обратным 
дл¤ уравнени¤ јрхимедовой спирали.  рива¤ состоит из двух ветвей, симметричных
относительно пр¤мой d. Ќачало координат ¤вл¤етс¤ асимптотической 
точкой. јсимптота - пр¤ма¤, параллельна¤ пол¤рной оси и отсто¤ща¤ от нее на 
рассто¤нии a. √иперболическа¤ спираль получаетс¤ при движении точки по
вращающейс¤ пр¤мой таким образом, что ее рассто¤ние от центра вращени¤ 
всегда будет обратно пропорционально углу поворота пр¤мой, измеренному от
начального положени¤.";
            _info.Creator           = "";
            _info.Usage             = "";
            _info.MathematicalBasis = "p = k * phi";
        }
        public override void Initialize(PropertiesModel.Property property)
        {
            ColorCurveInfo colorCurveInfo = property.EditorAdditionalData<ColorCurveInfo>();
            CurveInfo curveInfo = new CurveInfo();
            if (colorCurveInfo.Type == ColorCurveType.R)
                curveInfo.Curves = new string[] { "Red" };
            else if (colorCurveInfo.Type == ColorCurveType.G)
                curveInfo.Curves = new string[] { "Green" };
            if (colorCurveInfo.Type == ColorCurveType.B)
                curveInfo.Curves = new string[] { "Blue" };
            else if (colorCurveInfo.Type == ColorCurveType.RGB)
                curveInfo.Curves = new string[] { "Red", "Green", "Blue" };
            else if (colorCurveInfo.Type == ColorCurveType.RGBA)
                curveInfo.Curves = new string[] { "Red", "Green", "Blue", "Alpha" };
            PropertiesModel.Property p = new PropertiesModel.Property(property.Name, property.Editor, property.Value.DeepClone());
            p.EditorAdditionalData<CurveInfo>(curveInfo);

            base.Initialize(p);
        }
        public static void Init()
        {
            _info             = new CurveInfo();
            _info.LearnMore   = "https://ru.wikipedia.org/wiki/%D0%93%D0%B8%D0%BF%D0%B5%D1%80%D0%B1%D0%BE%D0%BB%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B0%D1%8F_%D1%81%D0%BF%D0%B8%D1%80%D0%B0%D0%BB%D1%8C";
            _info.Name        = "Гиперболическая Спираль";
            _info.Discription =
                @"   Гиперболическая спираль — плоская трансцендентная кривая. Уравнение
гиперболической спирали в полярной систем координат является обратным 
для уравнения Архимедовой спирали. Кривая состоит из двух ветвей, симметричных
относительно прямой d. Начало координат является асимптотической 
точкой. Асимптота - прямая, параллельная полярной оси и отстоящая от нее на 
расстоянии a. Гиперболическая спираль получается при движении точки по
вращающейся прямой таким образом, что ее расстояние от центра вращения 
всегда будет обратно пропорционально углу поворота прямой, измеренному от
начального положения.";
            _info.Creator           = "";
            _info.Usage             = "";
            _info.MathematicalBasis = "p = k * phi";
        }
Beispiel #20
0
        private void CreateCurves(CurveInfo curveInfo, XmlTextWriter writer)
        {
            try
            {
                writer.WriteStartElement("logCurveInfo");
                writer.WriteAttributeString("id", curveInfo.Name);

                writer.WriteElementString("minIndex", curveInfo.MinIndex.ToString());
                writer.WriteElementString("maxIndex", curveInfo.MaxIndex.ToString());

                writer.WriteElementString("typeLogData", "double");

                writer.WriteEndElement();
            }
            catch (Exception ex)
            {
                Logger.WrieException(string.Format("Error in writing curves to xml - {0}", ex.Message));
                throw new Exception(string.Format("Error in writing curves to xml - {0}", ex.Message));
            }
        }
        private void ResetGraph()
        {
            string sampleName = _status.FilePath.GetSampleName();
            string filePath   = _status.FilePath.GetFileName();
            var    fileName   = !string.IsNullOrEmpty(sampleName)
                ? string.Format(Resources.AsyncChromatogramsGraph_Render__0___sample__1_, filePath, sampleName)
                : filePath;

            _graphPane.Title.Text = fileName;
            _graphPane.CurveList.Clear();
            _graphPane.XAxis.Scale.Max = _xMax = Math.Max(X_AXIS_START, _status.Transitions.MaxRetentionTime);
            _graphPane.YAxis.Scale.Max = _yMax = Y_AXIS_START;
            _graphPane.AxisChange();
            _xAxisAnimation = null;
            _yAxisAnimation = null;
            _activeCurves.Clear();
            _lastCurve = null;
            _fullFrame = true;
            UpdateProgressLine(0);
            _graphPane.Chart.Fill = new Fill(Color.White);
        }
Beispiel #22
0
        public void SendAnimationCurve(CurveInfo data)
        {
            NetCommand command = MixerUtils.BuildSendAnimationCurve(data);

            AddCommand(command);
        }
Beispiel #23
0
        /// <summary>
        /// 绘图
        /// </summary>
        /// <param name="g"></param>
        /// <param name="e"></param>
        /// <param name="p"></param>
        /// <param name="pe"></param>
        public void GetBitmap(List <CurveInfo>[] listCurveMid, double hou)
        { // bi.RotateFlip(RotateFlipType.RotateNoneFlipY);
            try
            {
                double interx = -1;
                double intery = -1;

                int list0 = -1;
                int list1 = -1;

                if (listCurveMid.Length == 2)
                {
                    List <CurveInfo> listCurve0 = listCurveMid[0];
                    List <CurveInfo> listCurve1 = listCurveMid[1];

                    for (int i = 0; i < listCurve0.Count; i++)
                    {
                        if (listCurve0[i].r == 0)
                        {
                            for (int j = 0; j < listCurve1.Count; j++)
                            {
                                if (listCurve1[j].r == 0)
                                {
                                    double dx12 = -listCurve1[j].endMathPoint[0] + listCurve1[j].startMathPoint[0];
                                    double dy12 = -listCurve1[j].endMathPoint[1] + listCurve1[j].startMathPoint[1];

                                    double dx23 = -listCurve0[i].endMathPoint[0] + listCurve0[i].startMathPoint[0];
                                    double dy23 = -listCurve0[i].endMathPoint[1] + listCurve0[i].startMathPoint[1];

                                    double lengh12 = Math.Sqrt(dx12 * dx12 + dy12 * dy12);
                                    double lengh23 = Math.Sqrt(dx23 * dx23 + dy23 * dy23);

                                    double dx1 = -listCurve1[j].endMathPoint[0] + listCurve0[i].startMathPoint[0];
                                    double dy1 = -listCurve1[j].endMathPoint[1] + listCurve0[i].startMathPoint[1];

                                    double dx2 = -listCurve1[j].endMathPoint[0] + listCurve0[i].endMathPoint[0];
                                    double dy2 = -listCurve1[j].endMathPoint[1] + listCurve0[i].endMathPoint[1];

                                    double lengh1 = (Math.Sqrt((dx1 * dy2 - dy1 * dx2) * (dx1 * dy2 - dy1 * dx2))) / lengh23;

                                    double dx11 = -listCurve1[j].startMathPoint[0] + listCurve0[i].startMathPoint[0];
                                    double dy11 = -listCurve1[j].startMathPoint[1] + listCurve0[i].startMathPoint[1];

                                    double dx22 = -listCurve1[j].startMathPoint[0] + listCurve0[i].endMathPoint[0];
                                    double dy22 = -listCurve1[j].startMathPoint[1] + listCurve0[i].endMathPoint[1];

                                    double lengh2 = (Math.Sqrt((dx11 * dy22 - dy11 * dx22) * (dx11 * dy22 - dy11 * dx22))) / lengh23;

                                    double dx111 = -listCurve0[i].endMathPoint[0] + listCurve1[j].startMathPoint[0];
                                    double dy111 = -listCurve0[i].endMathPoint[1] + listCurve1[j].startMathPoint[1];

                                    double dx222 = -listCurve0[i].endMathPoint[0] + listCurve1[j].endMathPoint[0];
                                    double dy222 = -listCurve0[i].endMathPoint[1] + listCurve1[j].endMathPoint[1];

                                    double lengh11 = (Math.Sqrt((dx111 * dy222 - dy111 * dx222) * (dx111 * dy222 - dy111 * dx222))) / lengh12;

                                    double dx1111 = -listCurve0[i].startMathPoint[0] + listCurve1[j].startMathPoint[0];
                                    double dy1111 = -listCurve0[i].startMathPoint[1] + listCurve1[j].startMathPoint[1];

                                    double dx2222 = -listCurve0[i].startMathPoint[0] + listCurve1[j].endMathPoint[0];
                                    double dy2222 = -listCurve0[i].startMathPoint[1] + listCurve1[j].endMathPoint[1];

                                    double lengh22 = (Math.Sqrt((dx1111 * dy2222 - dy1111 * dx2222) * (dx1111 * dy2222 - dy1111 * dx2222))) / lengh12;
                                    if (Math.Round(lengh1 + lengh2, 3) == Math.Round(lengh12, 3) &&
                                        Math.Round(lengh11 + lengh22, 3) == Math.Round(lengh23, 3))
                                    {
                                        double dx = -listCurve1[j].endMathPoint[0] + listCurve1[j].startMathPoint[0];
                                        double dy = -listCurve1[j].endMathPoint[1] + listCurve1[j].startMathPoint[1];

                                        double idx = dx * lengh1 / lengh12;
                                        double idy = dy * lengh1 / lengh12;

                                        interx = listCurve1[j].endMathPoint[0] + idx;
                                        intery = listCurve1[j].endMathPoint[1] + idy;
                                        list0  = i;
                                        list1  = j;
                                    }
                                }
                            }
                        }
                    }
                }

                pee = Convert.ToSingle(5);

                Pen pe = new Pen(Color.Black, pee);

                for (int j = 0; j < listCurveMid.Length; j++)
                {
                    for (int i = 0; i < listCurveMid[j].Count; i++)
                    {
                        CurveInfo e = listCurveMid[j][i];
                        if (e.r == 0)
                        {
                            Point p1 = new Point((int)Math.Round(e.startMathPoint[0], 0), (int)Math.Round(e.startMathPoint[1], 0));
                            Point p2 = new Point((int)Math.Round(e.endMathPoint[0], 0), (int)Math.Round(e.endMathPoint[1], 0));

                            g.DrawLine(pe, p1, p2);

                            String drawString = Math.Round(e.length, 1).ToString();

                            // Create font and brush.
                            Font       drawFont  = new Font("仿宋", Convert.ToSingle(coox));
                            SolidBrush drawBrush = new SolidBrush(Color.Black);

                            StringFormat stringFormat = new StringFormat();
                            stringFormat.Alignment     = StringAlignment.Center;
                            stringFormat.LineAlignment = StringAlignment.Center;
                            // Create point for upper-left corner of drawing.

                            double stax = e.endMathPoint[0] - e.startMathPoint[0];
                            double stay = e.endMathPoint[1] - e.startMathPoint[1];

                            float x = (float)((e.startMathPoint[0] + e.endMathPoint[0]) / 2);
                            float y = (float)((e.startMathPoint[1] + e.endMathPoint[1]) / 2);

                            if (i == 0)
                            {
                                if ((Math.Round(listCurveMid[j][i].startMathPoint[0], 3) == Math.Round(listCurveMid[j][i + 2].startMathPoint[0], 3) &&
                                     Math.Round(listCurveMid[j][i].startMathPoint[1], 3) == Math.Round(listCurveMid[j][i + 2].startMathPoint[1], 3)) ||
                                    (Math.Round(listCurveMid[j][i].startMathPoint[0], 3) == Math.Round(listCurveMid[j][i + 2].endMathPoint[0], 3) &&
                                     Math.Round(listCurveMid[j][i].startMathPoint[1], 3) == Math.Round(listCurveMid[j][i + 2].endMathPoint[1], 3)))
                                {
                                    x = (float)(e.endMathPoint[0]);
                                    y = (float)(e.endMathPoint[1]);
                                }
                                else if ((Math.Round(listCurveMid[j][i].endMathPoint[0], 3) == Math.Round(listCurveMid[j][i + 2].startMathPoint[0], 3) &&
                                          Math.Round(listCurveMid[j][i].endMathPoint[1], 3) == Math.Round(listCurveMid[j][i + 2].startMathPoint[1], 3)) ||
                                         (Math.Round(listCurveMid[j][i].endMathPoint[0], 3) == Math.Round(listCurveMid[j][i + 2].endMathPoint[0], 3) &&
                                          Math.Round(listCurveMid[j][i].endMathPoint[1], 3) == Math.Round(listCurveMid[j][i + 2].endMathPoint[1], 3)))
                                {
                                    x = (float)(e.startMathPoint[0]);
                                    y = (float)(e.startMathPoint[1]);
                                }
                            }
                            else if (i == listCurveMid[j].Count - 1)
                            {
                                if ((Math.Round(listCurveMid[j][i].startMathPoint[0], 3) == Math.Round(listCurveMid[j][i - 2].startMathPoint[0], 3) &&
                                     Math.Round(listCurveMid[j][i].startMathPoint[1], 3) == Math.Round(listCurveMid[j][i - 2].startMathPoint[1], 3)) ||
                                    (Math.Round(listCurveMid[j][i].startMathPoint[0], 3) == Math.Round(listCurveMid[j][i - 2].endMathPoint[0], 3) &&
                                     Math.Round(listCurveMid[j][i].startMathPoint[1], 3) == Math.Round(listCurveMid[j][i - 2].endMathPoint[1], 3)))
                                {
                                    x = (float)(e.endMathPoint[0]);
                                    y = (float)(e.endMathPoint[1]);
                                }
                                else if ((Math.Round(listCurveMid[j][i].endMathPoint[0], 3) == Math.Round(listCurveMid[j][i - 2].startMathPoint[0], 3) &&
                                          Math.Round(listCurveMid[j][i].endMathPoint[1], 3) == Math.Round(listCurveMid[j][i - 2].startMathPoint[1], 3)) ||
                                         (Math.Round(listCurveMid[j][i].endMathPoint[0], 3) == Math.Round(listCurveMid[j][i - 2].endMathPoint[0], 3) &&
                                          Math.Round(listCurveMid[j][i].endMathPoint[1], 3) == Math.Round(listCurveMid[j][i - 2].endMathPoint[1], 3)))
                                {
                                    x = (float)(e.startMathPoint[0]);
                                    y = (float)(e.startMathPoint[1]);
                                }
                            }
                            else if ((list0 != -1) && ((j == 0 && list0 == i) || (j == 1 && list1 == i)))
                            {
                                double dx1 = interx - e.startMathPoint[0];
                                double dy1 = intery - e.startMathPoint[1];

                                double dx2 = interx - e.endMathPoint[0];
                                double dy2 = intery - e.endMathPoint[1];

                                double length1 = Math.Sqrt(dx1 * dx1 + dy1 * dy1);
                                double length2 = Math.Sqrt(dx2 * dx2 + dy2 * dy2);

                                if (length1 >= length2)
                                {
                                    x = (float)(interx - dx1 / 2);
                                    y = (float)(intery - dy1 / 2);
                                }
                                else
                                {
                                    x = (float)(interx - dx2 / 2);
                                    y = (float)(intery - dy2 / 2);
                                }
                            }
                            if (j == 0)
                            {
                                if (Math.Round(stay) == 0)
                                {
                                    stringFormat.LineAlignment = StringAlignment.Near;
                                }
                                else if (Math.Round(stax) == 0)
                                {
                                    stringFormat.Alignment = StringAlignment.Far;
                                }
                                else if (stay > 0)
                                {
                                    stringFormat.Alignment     = StringAlignment.Far;
                                    stringFormat.LineAlignment = StringAlignment.Near;
                                }
                                else
                                {
                                    stringFormat.Alignment     = StringAlignment.Far;
                                    stringFormat.LineAlignment = StringAlignment.Far;
                                }
                            }
                            else
                            {
                                if (Math.Round(stay) == 0)
                                {
                                    stringFormat.LineAlignment = StringAlignment.Far;
                                }
                                else if (Math.Round(stax) == 0)
                                {
                                    stringFormat.Alignment = StringAlignment.Near;
                                }
                                else if (stay > 0)
                                {
                                    stringFormat.Alignment     = StringAlignment.Near;
                                    stringFormat.LineAlignment = StringAlignment.Far;
                                }
                                else
                                {
                                    stringFormat.Alignment     = StringAlignment.Near;
                                    stringFormat.LineAlignment = StringAlignment.Near;
                                }
                            }

                            // Draw string to screen.
                            g.DrawString(drawString, drawFont, drawBrush, x, y, stringFormat);
                        }
                        else if (e.r != 0)
                        {
                            double total = Math.Round((e.length / e.r) * (180 / Math.PI), 1);

                            double stax = e.centerpoint[0] - e.startMathPoint[0];
                            double stay = e.centerpoint[1] - e.startMathPoint[1];

                            double endx = e.centerpoint[0] - e.endMathPoint[0];
                            double endy = e.centerpoint[1] - e.endMathPoint[1];

                            double vertx = endx + stax;
                            double verty = endy + stay;

                            double positionx = 0;
                            double positiony = 0;

                            String drawString = Math.Round(180 - total).ToString() + "°";

                            // Create font and brush.
                            Font       drawFont  = new Font("仿宋", Convert.ToSingle(coox));
                            SolidBrush drawBrush = new SolidBrush(Color.Black);

                            // Create point for upper-left corner of drawing.
                            float x = (float)(positionx);
                            float y = (float)(positiony);

                            if ((Math.Round(listCurveMid[j][i - 1].startMathPoint[0], 3) == Math.Round(listCurveMid[j][i + 1].startMathPoint[0], 3) &&
                                 Math.Round(listCurveMid[j][i - 1].startMathPoint[1], 3) == Math.Round(listCurveMid[j][i + 1].startMathPoint[1], 3)) ||
                                (Math.Round(listCurveMid[j][i - 1].startMathPoint[0], 3) == Math.Round(listCurveMid[j][i + 1].endMathPoint[0], 3) &&
                                 Math.Round(listCurveMid[j][i - 1].startMathPoint[1], 3) == Math.Round(listCurveMid[j][i + 1].endMathPoint[1], 3)))
                            {
                                x = (float)(listCurveMid[j][i - 1].startMathPoint[0]);
                                y = (float)(listCurveMid[j][i - 1].startMathPoint[1]);
                            }
                            else if ((Math.Round(listCurveMid[j][i - 1].endMathPoint[0], 3) == Math.Round(listCurveMid[j][i + 1].startMathPoint[0], 3) &&
                                      Math.Round(listCurveMid[j][i - 1].endMathPoint[1], 3) == Math.Round(listCurveMid[j][i + 1].startMathPoint[1], 3)) ||
                                     (Math.Round(listCurveMid[j][i - 1].endMathPoint[0], 3) == Math.Round(listCurveMid[j][i + 1].endMathPoint[0], 3) &&
                                      Math.Round(listCurveMid[j][i - 1].endMathPoint[1], 3) == Math.Round(listCurveMid[j][i + 1].endMathPoint[1], 3)))
                            {
                                x = (float)(listCurveMid[j][i - 1].endMathPoint[0]);
                                y = (float)(listCurveMid[j][i - 1].endMathPoint[1]);
                            }

                            StringFormat stringFormat = new StringFormat();
                            stringFormat.Alignment     = StringAlignment.Center;
                            stringFormat.LineAlignment = StringAlignment.Center;

                            if (vertx > 0 && verty > 0)
                            {
                                stringFormat.Alignment     = StringAlignment.Far;
                                stringFormat.LineAlignment = StringAlignment.Far;
                            }
                            else if (vertx > 0 && verty < 0)
                            {
                                stringFormat.Alignment     = StringAlignment.Far;
                                stringFormat.LineAlignment = StringAlignment.Near;
                            }
                            else if (vertx < 0 && verty < 0)
                            {
                                stringFormat.Alignment     = StringAlignment.Near;
                                stringFormat.LineAlignment = StringAlignment.Near;
                            }
                            else if (vertx < 0 && verty > 0)
                            {
                                stringFormat.Alignment     = StringAlignment.Near;
                                stringFormat.LineAlignment = StringAlignment.Far;
                            }
                            else if (vertx == 0 && verty > 0)
                            {
                                stringFormat.LineAlignment = StringAlignment.Far;
                            }
                            else if (vertx == 0 && verty < 0)
                            {
                                stringFormat.LineAlignment = StringAlignment.Near;
                            }
                            else if (vertx > 0 && verty == 0)
                            {
                                stringFormat.Alignment = StringAlignment.Far;
                            }
                            else if (vertx < 0 && verty == 0)
                            {
                                stringFormat.Alignment = StringAlignment.Near;
                            }

                            // Draw string to screen.
                            g.DrawString(drawString, drawFont, drawBrush, x, y, stringFormat);
                        }
                    }
                }
            }
            catch (System.Exception e1)
            {
                Relation.Exp(e1);
            }
        }
Beispiel #24
0
    private void Gasp()
    {
        bool flag;
        bool flag2;
        bool flag3;

        this.infoX = new CurveInfo(this.forceX);
        this.infoY = new CurveInfo(this.forceY);
        this.infoZ = new CurveInfo(this.forceZ);
        this.calc  = (this.infoX.calc || this.infoY.calc) || this.infoZ.calc;
        int length = this.sourceMask.length;

        if (length == 1)
        {
            Keyframe keyframe = this.sourceMask[0];
            if (keyframe.value == 1f)
            {
                flag = false;
            }
            else
            {
                Keyframe keyframe2 = this.sourceMask[0];
                if (keyframe2.value == 0f)
                {
                    this.calc = false;
                    flag      = false;
                }
                else
                {
                    flag = true;
                }
            }
        }
        else if (length == 0)
        {
            flag = false;
        }
        else
        {
            flag = true;
        }
        length = this.sourceScale.length;
        if (length == 1)
        {
            Keyframe keyframe3 = this.sourceScale[0];
            if (keyframe3.value == 1f)
            {
                flag2 = false;
            }
            else
            {
                flag2 = true;
            }
            Keyframe keyframe4 = this.sourceScale[0];
            if (keyframe4.value == 0f)
            {
                flag3 = true;
            }
            else
            {
                flag3 = false;
            }
        }
        else if (length == 0)
        {
            flag2 = false;
            flag3 = false;
        }
        else
        {
            flag2 = true;
            flag3 = false;
        }
        this.mask       = flag;
        this.scale      = flag2;
        this.scaleFixed = flag3;
        this.once       = true;
    }
Beispiel #25
0
 public void DestroyKeyframe(CurveInfo info)
 {
     mCurveList?.Remove(info);
 }
        internal void CreateAnimation(
            string animationName,
            IEnumerable <MWAnimationKeyframe> keyframes,
            IEnumerable <MWAnimationEvent> events,
            MWAnimationWrapMode wrapMode,
            MWSetAnimationStateOptions initialState,
            bool isInternal,
            bool managed,
            Action onCreatedCallback)
        {
            var continuation = new MWContinuation(AttachedActor, null, (result) =>
            {
                var clip = new AnimationClip
                {
                    legacy   = true,
                    wrapMode = wrapMode.ToUnityWrapMode(),
                };

                var curves = new Dictionary <string, CurveInfo>();

                CurveInfo GetOrCreateCurve(Type type, string propertyName)
                {
                    if (!curves.TryGetValue(propertyName, out CurveInfo info))
                    {
                        info = new CurveInfo()
                        {
                            Curve = new AnimationCurve(),
                            Type  = type
                        };

                        curves.Add(propertyName, info);
                    }

                    return(info);
                }

                void AddFloatPatch(Type type, string propertyName, float time, float?value)
                {
                    if (value.HasValue)
                    {
                        var curveInfo = GetOrCreateCurve(type, propertyName);
                        var keyframe  = new UnityEngine.Keyframe(time, value.Value, 0, 0, 0, 0);
                        curveInfo.Curve.AddKey(keyframe);
                    }
                }

                void AddVector3Patch(Type type, string propertyName, float time, Vector3Patch value)
                {
                    AddFloatPatch(type, String.Format("{0}.x", propertyName), time, value?.X);
                    AddFloatPatch(type, String.Format("{0}.y", propertyName), time, value?.Y);
                    AddFloatPatch(type, String.Format("{0}.z", propertyName), time, value?.Z);
                }

                void AddQuaternionPatch(Type type, string propertyName, float time, QuaternionPatch value)
                {
                    AddFloatPatch(type, String.Format("{0}.x", propertyName), time, value?.X);
                    AddFloatPatch(type, String.Format("{0}.y", propertyName), time, value?.Y);
                    AddFloatPatch(type, String.Format("{0}.z", propertyName), time, value?.Z);
                    AddFloatPatch(type, String.Format("{0}.w", propertyName), time, value?.W);
                }

                void AddTransformPatch(float time, ScaledTransformPatch value)
                {
                    // Work around a Unity bug/feature where all position components must be specified
                    // in the keyframe or the missing fields get set to zero.
                    Vector3Patch position = value?.Position;
                    if (position != null && position.IsPatched())
                    {
                        if (!position.X.HasValue)
                        {
                            position.X = transform.localPosition.x;
                        }
                        if (!position.Y.HasValue)
                        {
                            position.Y = transform.localPosition.y;
                        }
                        if (!position.Z.HasValue)
                        {
                            position.Z = transform.localPosition.z;
                        }
                    }
                    // Work around a Unity bug/feature where all scale components must be specified
                    // in the keyframe or the missing fields get set to one.
                    Vector3Patch scale = value?.Scale;
                    if (scale != null && scale.IsPatched())
                    {
                        if (!scale.X.HasValue)
                        {
                            scale.X = transform.localScale.x;
                        }
                        if (!scale.Y.HasValue)
                        {
                            scale.Y = transform.localScale.y;
                        }
                        if (!scale.Z.HasValue)
                        {
                            scale.Z = transform.localScale.z;
                        }
                    }
                    AddVector3Patch(typeof(Transform), "m_LocalPosition", time, value?.Position);
                    AddQuaternionPatch(typeof(Transform), "m_LocalRotation", time, value?.Rotation);
                    AddVector3Patch(typeof(Transform), "m_LocalScale", time, value?.Scale);
                }

                void AddActorPatch(float time, ActorPatch value)
                {
                    AddTransformPatch(time, value?.Transform.Local);
                }

                void AddKeyframe(MWAnimationKeyframe keyframe)
                {
                    AddActorPatch(keyframe.Time, keyframe.Value);
                }

                foreach (var keyframe in keyframes)
                {
                    AddKeyframe(keyframe);
                }

                foreach (var kv in curves)
                {
                    clip.SetCurve("", kv.Value.Type, kv.Key, kv.Value.Curve);
                }

                _animationData[animationName] = new AnimationData()
                {
                    IsInternal = isInternal,
                    Managed    = managed
                };

                float initialTime   = 0f;
                float initialSpeed  = 1f;
                bool initialEnabled = false;

                if (initialState != null)
                {
                    initialTime    = initialState.Time ?? initialTime;
                    initialSpeed   = initialState.Speed ?? initialSpeed;
                    initialEnabled = initialState.Enabled ?? initialEnabled;
                }

                var animation = GetOrCreateUnityAnimationComponent();
                animation.AddClip(clip, animationName);

                SetAnimationState(animationName, initialTime, initialSpeed, initialEnabled);

                onCreatedCallback?.Invoke();
            });

            continuation.Start();
        }
Beispiel #27
0
    IEnumerator GenerateNewPiece()
    {
        print("StartAngle " + startAngle);

        if (segmentsRemaining == 0)
        {
            targetAngle = Random.Range(minSteepness, maxSteepness);

            segmentsRemaining = Random.Range(1, maxRepeatingSegments + 1);

            if (pieceType != 1)
            {
                pieceType = Random.Range(0, 2);
            }
            else
            {
                pieceType = 0;

                segmentsRemaining = 1;
            }

//			if (pieceType != 0)
//			{
//				segmentsRemaining *= Random.Range (1, maxRepeatingSegments + 1);
//			}
        }

        segmentsRemaining--;

        float pieceMinSteepness = 0;

        float pieceMaxSteepness = 0;

        float curveAngle = 0;

        if (pieceType == 1)
        {
            lastPiecePos = new Vector3(lastPiecePos.x + Random.Range(minGapWidth, maxGapWidth), lastPiecePos.y + Random.Range(minGapHeight, maxGapHeight), 0);

            if (prevGeneratedPiece != null)
            {
                prevGeneratedPiece.GetComponent <DestroyTrack> ().lastGeneratedPiece = false;
            }

            prevGeneratedPiece = null;

            readyForNewPiece = true;

            yield break;
        }

        if (pieceType == 0)
        {
            if (startAngle != targetAngle)
            {
                if (startAngle > targetAngle)
                {
                    curveAngle = Random.Range(-maxRandomCurveAngle, 0);



                    pieceMinSteepness = targetAngle;
                    pieceMaxSteepness = startAngle;
                }
                else
                {
                    curveAngle = Random.Range(0, maxRandomCurveAngle);

                    pieceMinSteepness = startAngle;
                    pieceMaxSteepness = targetAngle;
                }
            }
            else
            {
                curveAngle = 0;

                pieceMinSteepness = targetAngle;
                pieceMaxSteepness = targetAngle;
            }
        }
//		else
//		{
//			curveAngle = Random.Range (-maxRandomCurveAngle, maxRandomCurveAngle);
//
//			pieceMinSteepness = minSteepness;
//			pieceMaxSteepness = maxSteepness;
//		}

        //			int maxVertCount;
        //
        //			if (curveAngle >= 0)
        //			{
        //				maxVertCount = Mathf.RoundToInt (((80f - startAngle) / curveAngle));
        //			}
        //			else
        //			{
        //				maxVertCount = Mathf.RoundToInt (((80f + startAngle) / curveAngle));
        //			}

        //int verticeCount = Random.Range(5, Mathf.Clamp(maxVertCount, 0, 12));

        //verticeCount = (verticeCount * 2) + 2;

        generateCurve = new GenerateCurveMesh();

        Mesh newCurvePieceMesh;

        Vector2 newJoinPoint;

        float prevPieceFinalAngle;

        generateCurve.GenerateNewCurve(trackHeight, curveVerticeDistance, verticesPerPiece, curveAngle, startAngle, pieceMinSteepness, pieceMaxSteepness, out newCurvePieceMesh, out newJoinPoint, out prevPieceFinalAngle);

        print(newJoinPoint);

        GameObject newCurvePiece = new GameObject();

        newCurvePiece.layer = 8;         //Track layer

        CurveInfo newCurveInfo = newCurvePiece.AddComponent <CurveInfo> ();

        DestroyTrack newDestroyTrack = newCurvePiece.AddComponent <DestroyTrack> ();

        newDestroyTrack.destroyDist = destroyDist;

        newDestroyTrack.player = player;

        newDestroyTrack.generator = gameObject;

        newDestroyTrack.trackManager = trackManager;

        if (prevGeneratedPiece != null)
        {
            prevGeneratedPiece.GetComponent <DestroyTrack> ().lastGeneratedPiece = false;

            prevGeneratedPiece.GetComponent <CurveInfo> ().nextTrackPiece = newCurvePiece;
        }

        newDestroyTrack.lastGeneratedPiece = true;

        prevGeneratedPiece = newCurvePiece;

        newCurvePiece.AddComponent(typeof(MeshRenderer));
        MeshFilter filter = newCurvePiece.AddComponent(typeof(MeshFilter)) as MeshFilter;

        filter.mesh = newCurvePieceMesh;

        //newCurvePiece.AddComponent<MeshCollider> ();



        EdgeCollider2D edgeCollider = newCurvePiece.AddComponent <EdgeCollider2D> ();

        edgeCollider.isTrigger = true;

        Vector2[] edgePoints = new Vector2[newCurvePieceMesh.vertices.Length / 2];

        for (int i = 0; i < newCurvePieceMesh.vertices.Length / 2; i++)
        {
            edgePoints [i] = new Vector2(newCurvePieceMesh.vertices [i].x, newCurvePieceMesh.vertices [i].y);
        }

        edgeCollider.points = edgePoints;


        Renderer rend = newCurvePiece.GetComponent <Renderer> ();

        Vector3 newPos = new Vector3(lastPiecePos.x + prevJoinPoint.x, lastPiecePos.y + prevJoinPoint.y, 0);

        newCurvePiece.transform.position = newPos;

        lastPiecePos = newPos;

        prevJoinPoint = newJoinPoint;

        //lastPieceSize = rend.bounds.size;

        startAngle = prevPieceFinalAngle;

        //(((verticesPerPiece - 2) / 2) * curveAngle) + startAngle;

        rend.material = material;

        rend.material.mainTextureOffset = new Vector2(newCurvePiece.transform.position.x * rend.material.mainTextureScale.x, newCurvePiece.transform.position.y * rend.material.mainTextureScale.y);

        //newCurvePiece.transform.parent = gameObject.transform;

        readyForNewPiece = true;

        yield break;
    }
 public override void Clear()
 {
     base.Clear();
     m_curvePictureBox = null;
     m_info = null;
 }
Beispiel #29
0
 protected override void InitializeNonSerializedData()
 {
     this.x             = new CurveInfo(this._x);
     this.y             = new CurveInfo(this._y);
     this.z             = new CurveInfo(this._z);
     this.yaw           = new CurveInfo(this._yaw);
     this.pitch         = new CurveInfo(this._pitch);
     this.roll          = new CurveInfo(this._roll);
     this.glob.valid    = (((this.x.valid || this.y.valid) || (this.z.valid || this.yaw.valid)) || this.pitch.valid) || this.roll.valid;
     this.glob.constant = this.glob.valid && (((((!this.x.valid || this.x.constant) && (!this.y.valid || this.y.constant)) && ((!this.z.valid || this.z.constant) && (!this.yaw.valid || this.yaw.constant))) && (!this.pitch.valid || this.pitch.constant)) && (!this.roll.valid || this.roll.constant));
     if (this.glob.constant)
     {
         this.glob.valid     = false;
         this.glob.startTime = 0f;
         this.glob.endTime   = 0f;
         this.glob.duration  = 0f;
     }
     else
     {
         this.glob.startTime = float.PositiveInfinity;
         this.glob.endTime   = float.NegativeInfinity;
         if (this.x.valid && !this.x.constant)
         {
             if (this.x.startTime < this.glob.startTime)
             {
                 this.glob.startTime = this.x.startTime;
             }
             if (this.x.endTime > this.glob.endTime)
             {
                 this.glob.endTime = this.x.endTime;
             }
         }
         if (this.z.valid && !this.z.constant)
         {
             if (this.z.startTime < this.glob.startTime)
             {
                 this.glob.startTime = this.z.startTime;
             }
             if (this.z.endTime > this.glob.endTime)
             {
                 this.glob.endTime = this.z.endTime;
             }
         }
         if (this.yaw.valid && !this.yaw.constant)
         {
             if (this.yaw.startTime < this.glob.startTime)
             {
                 this.glob.startTime = this.yaw.startTime;
             }
             if (this.yaw.endTime > this.glob.endTime)
             {
                 this.glob.endTime = this.yaw.endTime;
             }
         }
         if (this.pitch.valid && !this.pitch.constant)
         {
             if (this.pitch.startTime < this.glob.startTime)
             {
                 this.glob.startTime = this.pitch.startTime;
             }
             if (this.pitch.endTime > this.glob.endTime)
             {
                 this.glob.endTime = this.pitch.endTime;
             }
         }
         if (this.roll.valid && !this.roll.constant)
         {
             if (this.roll.startTime < this.glob.startTime)
             {
                 this.glob.startTime = this.roll.startTime;
             }
             if (this.roll.endTime > this.glob.endTime)
             {
                 this.glob.endTime = this.roll.endTime;
             }
         }
         if (this.roll.valid && !this.roll.constant)
         {
             if (this.roll.startTime < this.glob.startTime)
             {
                 this.glob.startTime = this.roll.startTime;
             }
             if (this.roll.endTime > this.glob.endTime)
             {
                 this.glob.endTime = this.roll.endTime;
             }
         }
         if (this.glob.startTime == float.PositiveInfinity)
         {
             this.glob.startTime = 0f;
             this.glob.endTime   = 0f;
             this.glob.duration  = 0f;
             this.glob.valid     = false;
         }
         else
         {
             this.glob.duration = this.glob.endTime - this.glob.startTime;
         }
     }
 }
        private void ProcessBinProgressive(
            List <ChromatogramLoadingStatus.TransitionData.Peak> bin,
            GraphInfo info)
        {
            float retentionTime = bin[0].BinIndex * ChromatogramLoadingStatus.TIME_RESOLUTION;

            info.MaxX  = Math.Max(info.MaxX, retentionTime + ChromatogramLoadingStatus.TIME_RESOLUTION);
            _renderMin = Math.Min(_renderMin, retentionTime - ChromatogramLoadingStatus.TIME_RESOLUTION);
            _renderMax = Math.Max(_renderMax, retentionTime + ChromatogramLoadingStatus.TIME_RESOLUTION);

            // Order the top peaks to be shown for each bin.
            bin.Sort((a, b) => a.Intensity.CompareTo(b.Intensity));

            for (int i = 0; i < info.ActiveCurves.Count; i++)
            {
                info.ActiveCurves[i].IsActive = false;
            }

            // Add the top peaks to the list of active curves. This allows peaks to be displayed smoothly
            // and with anti-aliasing instead of as unconnected spikes.
            for (int i = bin.Count - 1; i >= 0; i--)
            {
                // Filter out small intensities.
                var   peak      = bin[i];
                float intensity = peak.Intensity;
                if (intensity < ChromatogramLoadingStatus.DISPLAY_FILTER_PERCENT * info.MaxY)
                {
                    break;
                }
                info.MaxY = Math.Max(info.MaxY, intensity);

                CurveInfo curve = null;
                foreach (var activeCurve in info.ActiveCurves)
                {
                    if (ReferenceEquals(peak.ModifiedSequence, activeCurve.ModifiedSequence))
                    {
                        curve = activeCurve;
                        break;
                    }
                }

                // Add a new curve.
                if (curve == null)
                {
                    curve = new CurveInfo(bin[i].ModifiedSequence, bin[i].Color, retentionTime, intensity);
                    info.GraphPane.CurveList.Insert(0, curve.Curve);
                    info.ActiveCurves.Add(curve);
                }
                // Add preceding zero if necessary.
                else if (curve.Curve.Points[curve.Curve.NPts - 1].X < retentionTime - ChromatogramLoadingStatus.TIME_RESOLUTION * 1.01)
                {
                    curve.Curve.AddPoint(retentionTime - ChromatogramLoadingStatus.TIME_RESOLUTION, 0);
                    curve.Curve.AddPoint(retentionTime, intensity);
                    curve.Curve.AddPoint(retentionTime + ChromatogramLoadingStatus.TIME_RESOLUTION, 0);
                }
                // Add next point by modifying preceding intensity.
                else
                {
                    curve.Curve.Points[curve.Curve.NPts - 1].Y += intensity;
                    curve.Curve.AddPoint(retentionTime + ChromatogramLoadingStatus.TIME_RESOLUTION, 0);
                }

                curve.IsActive = true;
            }

            // Remove curves that weren't among the top curves in this bin.
            for (int i = info.ActiveCurves.Count - 1; i >= 0; i--)
            {
                if (!info.ActiveCurves[i].IsActive)
                {
                    info.ActiveCurves.RemoveAt(i);
                }
            }
        }
 private void ResetGraph()
 {
     string sampleName = _status.FilePath.GetSampleName();
     string filePath = _status.FilePath.GetFileName();
     var fileName = !string.IsNullOrEmpty(sampleName)
         ? string.Format(Resources.AsyncChromatogramsGraph_Render__0___sample__1_, filePath, sampleName)
         : filePath;
     _graphPane.Title.Text = fileName;
     _graphPane.CurveList.Clear();
     _graphPane.XAxis.Scale.Max = _xMax = Math.Max(X_AXIS_START, _status.Transitions.MaxRetentionTime);
     _graphPane.YAxis.Scale.Max = _yMax = Y_AXIS_START;
     _graphPane.AxisChange();
     _xAxisAnimation = null;
     _yAxisAnimation = null;
     _activeCurves.Clear();
     _lastCurve = null;
     _fullFrame = true;
     UpdateProgressLine(0);
     _graphPane.Chart.Fill = new Fill(Color.White);
 }
        private void ProcessBinSRM(
            List<ChromatogramLoadingStatus.TransitionData.Peak> bin,
            ref bool peaksAdded,
            ref float maxTime,
            ref float maxIntensity)
        {
            float retentionTime = bin[0].BinIndex * ChromatogramLoadingStatus.TIME_RESOLUTION;
            maxTime = Math.Max(maxTime, retentionTime);
            peaksAdded = true;

            foreach (var peak in bin)
            {
                // New peptide curve.
                if (_lastCurve == null || !ReferenceEquals(peak.ModifiedSequence, _lastCurve.ModifiedSequence))
                {
                    _lastCurve = new CurveInfo(peak.ModifiedSequence, peak.Color, retentionTime, peak.Intensity);
                    _graphPane.CurveList.Add(_lastCurve.Curve);
                    maxIntensity = Math.Max(maxIntensity, peak.Intensity);
                    continue;
                }

                // Add intensity to existing peptide curve.
                for (int i = _lastCurve.Curve.NPts - 1; i >= 0; i--)
                {
                    int binIndex = ChromatogramLoadingStatus.GetBinIndex((float) _lastCurve.Curve.Points[i].X);
                    if (binIndex > peak.BinIndex)
                    {
                        if (i == 0)
                        {
                            _lastCurve.InsertAt(0, retentionTime, peak.Intensity);
                            _lastCurve.CheckZeroes(0);
                            maxIntensity = Math.Max(maxIntensity, peak.Intensity);
                        }
                    }
                    else if (binIndex == peak.BinIndex)
                    {
                        _lastCurve.Curve.Points[i].Y += peak.Intensity;
                        _lastCurve.CheckZeroes(i);
                        maxIntensity = Math.Max(maxIntensity, (float) _lastCurve.Curve.Points[i].Y);
                        break;
                    }
                    else
                    {
                        _lastCurve.InsertAt(i + 1, retentionTime, peak.Intensity);
                        _lastCurve.CheckZeroes(i + 1);
                        maxIntensity = Math.Max(maxIntensity, peak.Intensity);
                        break;
                    }
                }
            }
        }
        private void ProcessBinProgressive(
            List<ChromatogramLoadingStatus.TransitionData.Peak> bin,
            ref bool peaksAdded,
            ref float maxTime,
            ref float maxIntensity)
        {
            float retentionTime = bin[0].BinIndex*ChromatogramLoadingStatus.TIME_RESOLUTION;
            maxTime = _status.Transitions.MaxRetentionTime;

            // Order the top peaks to be shown for each bin.
            bin.Sort((a, b) => a.Intensity.CompareTo(b.Intensity));

            for (int i = 0; i < _activeCurves.Count; i++)
                _activeCurves[i].IsActive = false;

            // Add the top peaks to the list of active curves. This allows peaks to be displayed smoothly
            // and with anti-aliasing instead of as unconnected spikes.
            for (int i = bin.Count - 1; i >= 0; i--)
            {
                // Filter out small intensities.
                var peak = bin[i];
                float intensity = peak.Intensity;
                if (intensity < ChromatogramLoadingStatus.DISPLAY_FILTER_PERCENT*maxIntensity)
                    break;

                CurveInfo curve = null;
                foreach (var activeCurve in _activeCurves)
                {
                    if (ReferenceEquals(peak.ModifiedSequence, activeCurve.ModifiedSequence))
                    {
                        curve = activeCurve;
                        break;
                    }
                }

                // Add a new curve.
                if (curve == null)
                {
                    curve = new CurveInfo(bin[i].ModifiedSequence, bin[i].Color, retentionTime, intensity);
                    _graphPane.CurveList.Insert(0, curve.Curve);
                    _activeCurves.Add(curve);
                }
                // Add preceding zero if necessary.
                else if (curve.Curve.Points[curve.Curve.NPts - 1].X < retentionTime - ChromatogramLoadingStatus.TIME_RESOLUTION*1.01)
                {
                    curve.Curve.AddPoint(retentionTime - ChromatogramLoadingStatus.TIME_RESOLUTION, 0);
                    curve.Curve.AddPoint(retentionTime, intensity);
                    curve.Curve.AddPoint(retentionTime + ChromatogramLoadingStatus.TIME_RESOLUTION, 0);
                }
                // Add next point by modifying preceding intensity.
                else
                {
                    curve.Curve.Points[curve.Curve.NPts - 1].Y += intensity;
                    curve.Curve.AddPoint(retentionTime + ChromatogramLoadingStatus.TIME_RESOLUTION, 0);
                }

                // Add intensity value to the curve.
                maxIntensity = Math.Max(maxIntensity, intensity);
                curve.IsActive = true;
                peaksAdded = true;
            }

            // Remove curves that weren't among the top curves in this bin.
            for (int i = _activeCurves.Count - 1; i >= 0; i--)
            {
                if (!_activeCurves[i].IsActive)
                    _activeCurves.RemoveAt(i);
            }
        }