コード例 #1
0
 private void SyllabifyAnnotation(Word word, Annotation <ShapeNode> ann, Shape newShape)
 {
     if (word.Shape.GetNodes(ann.Span).Any(n => n.Type() == CogFeatureSystem.ToneLetterType || n.StrRep() == "."))
     {
         ShapeNode[] annNodes = word.Shape.GetNodes(ann.Span).ToArray();
         int         i;
         for (i = 0; i < annNodes.Length && annNodes[i].Type().IsOneOf(CogFeatureSystem.ToneLetterType, CogFeatureSystem.BoundaryType); i++)
         {
             newShape.Add(annNodes[i].DeepClone());
         }
         ShapeNode syllableStart = annNodes[i];
         ShapeNode node          = syllableStart.GetNext(n => n.Type().IsOneOf(CogFeatureSystem.ToneLetterType, CogFeatureSystem.BoundaryType));
         while (ann.Span.Contains(node))
         {
             if (syllableStart != node)
             {
                 ProcessSyllable(syllableStart, node.Prev, newShape);
             }
             newShape.Add(node.DeepClone());
             syllableStart = node.Next;
             node          = node.GetNext(n => n.Type().IsOneOf(CogFeatureSystem.ToneLetterType, CogFeatureSystem.BoundaryType));
         }
         if (ann.Span.Contains(syllableStart))
         {
             ProcessSyllable(syllableStart, ann.Span.End, newShape);
         }
     }
     else
     {
         SyllabifyUnmarkedAnnotation(word, ann, newShape);
     }
 }
コード例 #2
0
ファイル: PagerShapes.cs プロジェクト: duytuit/OrchardCore
        public async Task <IHtmlContent> PagerSlim(Shape Shape, dynamic DisplayAsync, dynamic New, IHtmlHelper Html, DisplayContext DisplayContext,
                                                   object PreviousText,
                                                   object NextText,
                                                   string PreviousClass,
                                                   string NextClass,
                                                   string ItemTagName,
                                                   IDictionary <string, string> Attributes,
                                                   IDictionary <string, string> ItemAttributes,
                                                   Dictionary <string, string> UrlParams)
        {
            Shape.Properties["ItemTagName"] = ItemTagName;

            var attributes = Shape.Attributes;

            foreach (var item in Attributes)
            {
                attributes.Add(item.Key, item.Value);
            }

            Shape.Properties["ItemAttributes"] = ItemAttributes;

            var previousText = PreviousText ?? S["<"];
            var nextText     = NextText ?? S[">"];

            Shape.Classes.Add("pager");
            Shape.Metadata.Alternates.Clear();
            Shape.Metadata.Type = "List";

            var routeData = new RouteValueDictionary(Html.ViewContext.RouteData.Values);

            // Allows to pass custom url params to PagerSlim
            if (UrlParams != null)
            {
                foreach (var item in UrlParams)
                {
                    routeData.Add(item.Key, item.Value);
                }
            }

            if (Shape.Properties.TryGetValue("Before", out var beforeValue) && beforeValue is string before)
            {
                var beforeRouteData = new RouteValueDictionary(routeData);
                beforeRouteData["before"] = before;
                Shape.Add(await New.Pager_Previous(Value: previousText, RouteValues: beforeRouteData, Pager: Shape));
                Shape.Properties["FirstClass"] = PreviousClass;
            }

            if (Shape.Properties.TryGetValue("After", out var afterValue) && afterValue is string after)
            {
                var afterRouteData = new RouteValueDictionary(routeData);
                afterRouteData["after"] = after;
                Shape.Add(await New.Pager_Next(Value: nextText, RouteValues: afterRouteData, Pager: Shape));
                Shape.Properties["LastClass"] = NextClass;
            }

            return(await DisplayAsync(Shape));
        }
コード例 #3
0
        public AbstractDrawable buildDrawable()
        {
            Shape s = new Shape();

            s.Add(getFacets());
            return(s);
        }
コード例 #4
0
        protected override Element CreateChildForParameter(Parameter parameter)
        {
            switch (parameter.Id)
            {
            case 1:
                OnlyBorder = parameter.Value > 0;
                return(new ValueElement(parameter, this));

            case 2:
                Color = Color.FromArgb(0xff, Color.FromArgb((int)parameter.Value));
                return(new ValueElement(parameter, this));

            case 3:
                Center = new CoordinatesElement(parameter, this);
                return(Center);

            case 4:
                var point = new CoordinatesElement(parameter, this);
                Shape.Add(point);
                return(point);

            case 5:
                CenterImage = new ImageElement(parameter, this);
                return(CenterImage);

            default:
                return(base.CreateChildForParameter(parameter));
            }
        }
コード例 #5
0
ファイル: ImportFont.cs プロジェクト: DWVoid/Msdfgen.Net
 internal int FtMoveTo(ref FTVector to, IntPtr context)
 {
     _contour = new Contour();
     _shape.Add(_contour);
     _position = FtPoint2(ref to);
     return(0);
 }
コード例 #6
0
 private void Untruncate(PatternNode <Word, ShapeNode> patternNode, Shape output, bool optional, VariableBindings varBindings)
 {
     foreach (PatternNode <Word, ShapeNode> node in patternNode.Children)
     {
         var constraint = node as Constraint <Word, ShapeNode>;
         if (constraint != null && constraint.Type() == HCFeatureSystem.Segment)
         {
             FeatureStruct fs = constraint.FeatureStruct.DeepClone();
             fs.ReplaceVariables(varBindings);
             output.Add(fs, optional);
         }
         else
         {
             var quantifier = node as Quantifier <Word, ShapeNode>;
             if (quantifier != null)
             {
                 for (int i = 0; i < quantifier.MaxOccur; i++)
                 {
                     Untruncate(quantifier, output, i >= quantifier.MinOccur, varBindings);
                 }
             }
             else
             {
                 Untruncate(node, output, optional, varBindings);
             }
         }
     }
 }
コード例 #7
0
ファイル: RingTessellator.cs プロジェクト: kgfathur/nzy3d-api
        public override Primitives.AbstractComposite build(float[] x, float[] y, float[] z)
        {
            setData(x, y, z);
            Shape s = new Shape();

            s.Add(getInterpolatedRingPolygons());
            return(s);
        }
コード例 #8
0
        public override Primitives.AbstractComposite build(float[] x, float[] y, float[] z)
        {
            setData(x, y, z);
            Shape s = new Shape();

            s.Add(getSquarePolygonsOnCoordinates());
            return(s);
        }
コード例 #9
0
        protected override Element CreateChildForParameter(Parameter parameter)
        {
            if (Header.HeaderSize == 60)
            {
                switch (parameter.Id)
                {
                case 1:
                    unknown1 = parameter.Value;
                    return(new ValueElement(parameter, this));

                case 2:
                    unknown2 = parameter.Value;
                    return(new ValueElement(parameter, this));

                case 3:
                    Center = unknown3 = new CoordinatesElement(parameter, this);
                    return(unknown3);

                case 4:
                    unknown4 = new CoordinatesElement(parameter, this);
                    return(unknown4);

                case 5:
                    CenterImage = new ImageElement(parameter, this);
                    return(CenterImage);
                }
            }
            else
            {
                switch (parameter.Id)
                {
                case 1:
                    OnlyBorder = parameter.Value > 0;
                    return(new ValueElement(parameter, this));

                case 2:
                    Color = Color.FromArgb(0xff, Color.FromArgb((int)parameter.Value));
                    return(new ValueElement(parameter, this));

                case 3:
                    Center = new CoordinatesElement(parameter, this);
                    return(Center);

                case 4:
                    var point = new CoordinatesElement(parameter, this);
                    Shape.Add(point);
                    return(point);

                case 5:
                    CenterImage = new ImageElement(parameter, this);
                    return(CenterImage);
                }
            }

            return(base.CreateChildForParameter(parameter));
        }
コード例 #10
0
        private Affix CreateAffix(Ngram <Segment> ngram, string category, double score)
        {
            var shape = new Shape(begin => new ShapeNode(FeatureStruct.New().Symbol(CogFeatureSystem.AnchorType).Feature(CogFeatureSystem.StrRep).EqualTo("#").Value));

            foreach (Segment seg in ngram)
            {
                if (seg.Type != CogFeatureSystem.AnchorType)
                {
                    shape.Add(seg.FeatureStruct);
                }
            }
            shape.Freeze();
            return(new Affix(string.Concat(shape.Select(n => n.StrRep())), ngram.First.Equals(Segment.Anchor) ? AffixType.Prefix : AffixType.Suffix,
                             category)
            {
                Shape = shape, Score = score
            });
        }
コード例 #11
0
        private void OnImportString(object obj)
        {
            if (string.IsNullOrWhiteSpace(_polygonString))
            {
                PolygonString = "Invalid String";
                return;
            }

            var split = _polygonString.Split(' ');

            if (split.Length % 2 != 0)
            {
                PolygonString = "Invalid String";
                return;
            }

            if (Shape == null)
            {
                Shape = new List <Vector2D>();
            }
            else
            {
                Shape.Clear();
            }

            double x = 0;
            double y = 0;

            for (int i = 0; i < split.Length; i += 2)
            {
                x = double.Parse(split[i]);
                y = double.Parse(split[i + 1]);

                var pt = new Vector2D(x, y);
                Shape.Add(pt);
            }


            PolygonString = "String Imported";
        }
コード例 #12
0
        protected void ProcessSyllable(ShapeNode startNode, ShapeNode endNode, Shape newShape)
        {
            ShapeNode newStartNode = null;
            ShapeNode node         = startNode;

            while (node.Type() == CogFeatureSystem.BoundaryType && node != endNode.Next)
            {
                ShapeNode newNode = node.DeepClone();
                newShape.Add(newNode);
                if (newStartNode == null)
                {
                    newStartNode = newNode;
                }
                node = node.Next;
            }

            ShapeNode onsetStart = node;

            while (node.Type() == CogFeatureSystem.ConsonantType && node != endNode.Next)
            {
                node = node.Next;
            }
            ShapeNode onsetEnd = node.Prev;

            if (onsetStart != node)
            {
                ShapeNode start = Combine(CogFeatureSystem.Onset, newShape, onsetStart, onsetEnd);
                if (newStartNode == null)
                {
                    newStartNode = start;
                }
            }

            if (node != endNode.Next)
            {
                ShapeNode nucleusStart = node;
                while (node.Type() == CogFeatureSystem.VowelType && node != endNode.Next)
                {
                    node = node.Next;
                }
                ShapeNode nucleusEnd = node.Prev;

                ShapeNode start = Combine(CogFeatureSystem.Nucleus, newShape, nucleusStart, nucleusEnd);
                if (newStartNode == null)
                {
                    newStartNode = start;
                }
            }

            if (node != endNode.Next)
            {
                ShapeNode codaStart = node;
                while (node.Type() == CogFeatureSystem.ConsonantType && node != endNode.Next)
                {
                    node = node.Next;
                }
                if (codaStart != node)
                {
                    ShapeNode codaEnd = node.Prev;
                    Combine(CogFeatureSystem.Coda, newShape, codaStart, codaEnd);
                }
            }

            while (node != endNode.Next)
            {
                newShape.Add(node.DeepClone());
                node = node.Next;
            }
            newShape.Annotations.Add(newStartNode, newShape.Last, FeatureStruct.New().Symbol(CogFeatureSystem.SyllableType).Value);
        }
コード例 #13
0
ファイル: Segmenter.cs プロジェクト: JRetza/cog
        private bool SegmentString(Shape shape, string str)
        {
            if (_regex == null)
            {
                _regex = new Regex(CreateRegexString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
            }

            int index = 0;

            foreach (Match match in _regex.Matches(str))
            {
                if (match.Index != index)
                {
                    break;
                }

                if (match.Groups["vowelSeg"].Success)
                {
                    string        strRep;
                    FeatureStruct phonemeFS;
                    if (!TryMultipleBaseCharacterSymbol(match, _vowels, out strRep, out phonemeFS))
                    {
                        var    sb        = new StringBuilder();
                        Group  vowelComp = match.Groups["vowelComp"];
                        string partStrRep;
                        phonemeFS = BuildFeatStruct(match, vowelComp.Captures[0], "vowelBase", _vowels, out partStrRep);
                        sb.Append(partStrRep);
                        Group joinerGroup = match.Groups["joiner"];
                        if (joinerGroup.Success || vowelComp.Captures.Count > 1)
                        {
                            phonemeFS.AddValue(CogFeatureSystem.First, phonemeFS.Clone());
                            phonemeFS.AddValue(CogFeatureSystem.SegmentType, CogFeatureSystem.Complex);
                        }
                        else
                        {
                            phonemeFS.AddValue(CogFeatureSystem.SegmentType, CogFeatureSystem.Simple);
                        }
                        if (joinerGroup.Success)
                        {
                            for (int i = 0; i < joinerGroup.Captures.Count; i++)
                            {
                                string joinerStr = joinerGroup.Captures[i].Value;
                                phonemeFS.Add(BuildFeatStruct(match, vowelComp.Captures[i + 1], "vowelBase", _vowels, out partStrRep));
                                sb.Append(partStrRep);
                                FeatureStruct joinerFs = _joiners[joinerStr].FeatureStruct;
                                if (joinerFs != null)
                                {
                                    phonemeFS.PriorityUnion(joinerFs);
                                }
                            }
                        }
                        else if (vowelComp.Captures.Count > 1)
                        {
                            for (int i = 1; i < vowelComp.Captures.Count; i++)
                            {
                                phonemeFS.Add(BuildFeatStruct(match, vowelComp.Captures[i], "vowelBase", _vowels, out partStrRep));
                                sb.Append(partStrRep);
                            }
                        }
                        strRep = sb.ToString();
                    }

                    phonemeFS.AddValue(CogFeatureSystem.StrRep, strRep);
                    phonemeFS.AddValue(CogFeatureSystem.OriginalStrRep, match.Value);
                    phonemeFS.AddValue(CogFeatureSystem.Type, CogFeatureSystem.VowelType);
                    shape.Add(phonemeFS);
                }
                else if (match.Groups["consSeg"].Success)
                {
                    string        strRep;
                    FeatureStruct phonemeFS;
                    if (!TryMultipleBaseCharacterSymbol(match, _consonants, out strRep, out phonemeFS))
                    {
                        var    sb       = new StringBuilder();
                        Group  consComp = match.Groups["consComp"];
                        string compStrRep;
                        phonemeFS = BuildFeatStruct(match, consComp.Captures[0], "consBase", _consonants, out compStrRep);
                        sb.Append(compStrRep);
                        Group joinerGroup = match.Groups["joiner"];
                        if (joinerGroup.Success || consComp.Captures.Count > 1)
                        {
                            phonemeFS.AddValue(CogFeatureSystem.First, phonemeFS.Clone());
                            phonemeFS.AddValue(CogFeatureSystem.SegmentType, CogFeatureSystem.Complex);
                        }
                        else
                        {
                            phonemeFS.AddValue(CogFeatureSystem.SegmentType, CogFeatureSystem.Simple);
                        }
                        if (joinerGroup.Success)
                        {
                            for (int i = 0; i < joinerGroup.Captures.Count; i++)
                            {
                                string joinerStr = joinerGroup.Captures[i].Value;
                                phonemeFS.Add(BuildFeatStruct(match, consComp.Captures[i + 1], "consBase", _consonants, out compStrRep));
                                sb.Append(compStrRep);
                                FeatureStruct joinerFs = _joiners[joinerStr].FeatureStruct;
                                if (joinerFs != null)
                                {
                                    phonemeFS.PriorityUnion(joinerFs);
                                }
                            }
                        }
                        else if (consComp.Captures.Count > 1)
                        {
                            for (int i = 1; i < consComp.Captures.Count; i++)
                            {
                                phonemeFS.Add(BuildFeatStruct(match, consComp.Captures[i], "consBase", _consonants, out compStrRep));
                                sb.Append(compStrRep);
                            }
                        }
                        strRep = sb.ToString();
                    }

                    phonemeFS.AddValue(CogFeatureSystem.StrRep, strRep);
                    phonemeFS.AddValue(CogFeatureSystem.OriginalStrRep, match.Value);
                    phonemeFS.AddValue(CogFeatureSystem.Type, CogFeatureSystem.ConsonantType);
                    shape.Add(phonemeFS);
                }
                else if (match.Groups["tone"].Success)
                {
                    shape.Add(FeatureStruct.New()
                              .Symbol(CogFeatureSystem.ToneLetterType)
                              .Feature(CogFeatureSystem.StrRep).EqualTo(match.Value)
                              .Feature(CogFeatureSystem.OriginalStrRep).EqualTo(match.Value).Value);
                }
                else if (match.Groups["bdry"].Success)
                {
                    shape.Add(FeatureStruct.New()
                              .Symbol(CogFeatureSystem.BoundaryType)
                              .Feature(CogFeatureSystem.StrRep).EqualTo(match.Value)
                              .Feature(CogFeatureSystem.OriginalStrRep).EqualTo(match.Value).Value);
                }

                index = match.Index + match.Length;

                if (index == str.Length)
                {
                    if (shape.Count == 0)
                    {
                        break;
                    }

                    return(true);
                }
            }

            return(false);
        }
コード例 #14
0
        private bool GenerateShape(SpanFactory <ShapeNode> spanFactory, FeatureSystem featSys)
        {
            m_shape.Add(FeatureStruct.New(featSys).Symbol("bdry").Symbol("wordBdry").Value);
            var typeFeat = featSys.GetFeature <SymbolicFeature>("type");
            var catFeat  = featSys.GetFeature <SymbolicFeature>("cat");
            var inflFeat = featSys.GetFeature <ComplexFeature>("infl");
            var segments = new Dictionary <ISegment, List <Annotation <ShapeNode> > >();

            foreach (ISegment segment in m_para.SegmentsOS)
            {
                var annotations = new List <Annotation <ShapeNode> >();
                foreach (Tuple <IAnalysis, int, int> analysis in segment.GetAnalysesAndOffsets())
                {
                    // check if analyses are out-of-sync with the baseline
                    ITsString baselineStr = m_para.Contents.GetSubstring(analysis.Item2, analysis.Item3);
                    ITsString formStr     = analysis.Item1.GetForm(baselineStr.get_WritingSystemAt(0));
                    if (!baselineStr.Text.Equals(formStr.Text, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(false);
                    }

                    var wordform = analysis.Item1 as IWfiWordform;
                    if (wordform != null)
                    {
                        var wordFS = new FeatureStruct();
                        wordFS.AddValue(typeFeat, typeFeat.PossibleSymbols["word"]);
                        foreach (int ws in wordform.Form.AvailableWritingSystemIds)
                        {
                            StringFeature strFeat;
                            if (featSys.TryGetFeature(string.Format("form-{0}", ws), out strFeat))
                            {
                                wordFS.AddValue(strFeat, wordform.Form.get_String(ws).Text);
                            }
                        }
                        ShapeNode node = m_shape.Add(wordFS);
                        node.Annotation.Data = analysis;
                        annotations.Add(node.Annotation);
                    }
                    else
                    {
                        if (analysis.Item1 is IPunctuationForm)
                        {
                            annotations.Add(null);
                            continue;
                        }

                        FeatureStruct wordInflFS    = null;
                        IWfiAnalysis  wanalysis     = analysis.Item1.Analysis;
                        ShapeNode     analysisStart = null;
                        foreach (IWfiMorphBundle mb in wanalysis.MorphBundlesOS)
                        {
                            var morphFS = new FeatureStruct();
                            morphFS.AddValue(typeFeat, typeFeat.PossibleSymbols["morph"]);
                            foreach (int ws in mb.Form.AvailableWritingSystemIds.Union(mb.MorphRA == null ? Enumerable.Empty <int>() : mb.MorphRA.Form.AvailableWritingSystemIds))
                            {
                                StringFeature strFeat;
                                if (!featSys.TryGetFeature(string.Format("form-{0}", ws), out strFeat))
                                {
                                    continue;
                                }

                                IEnumerable <string> forms  = Enumerable.Empty <string>();
                                ITsString            mbForm = mb.Form.StringOrNull(ws);
                                if (mbForm != null)
                                {
                                    forms = forms.Concat(mbForm.Text);
                                }
                                if (mb.MorphRA != null)
                                {
                                    ITsString morphForm = mb.MorphRA.Form.StringOrNull(ws);
                                    if (morphForm != null)
                                    {
                                        forms = forms.Concat(morphForm.Text);
                                    }
                                }

                                morphFS.AddValue(strFeat, forms.Distinct());
                            }
                            if (mb.SenseRA != null)
                            {
                                foreach (int ws in mb.SenseRA.Gloss.AvailableWritingSystemIds)
                                {
                                    StringFeature strFeat;
                                    if (featSys.TryGetFeature(string.Format("gloss-{0}", ws), out strFeat))
                                    {
                                        morphFS.AddValue(strFeat, mb.SenseRA.Gloss.get_String(ws).Text);
                                    }
                                }
                            }

                            if (mb.MorphRA != null)
                            {
                                var entry = (ILexEntry)mb.MorphRA.Owner;
                                foreach (int ws in entry.LexemeFormOA.Form.AvailableWritingSystemIds)
                                {
                                    StringFeature strFeat;
                                    if (featSys.TryGetFeature(string.Format("entry-{0}", ws), out strFeat))
                                    {
                                        morphFS.AddValue(strFeat, entry.LexemeFormOA.Form.get_String(ws).Text);
                                    }
                                }
                            }

                            if (mb.MsaRA != null && mb.MsaRA.ComponentsRS != null)
                            {
                                FeatureSymbol[] catSymbols = GetHvoOfMsaPartOfSpeech(mb.MsaRA).Select(hvo => catFeat.PossibleSymbols[hvo.ToString(CultureInfo.InvariantCulture)]).ToArray();
                                if (catSymbols.Length > 0)
                                {
                                    morphFS.AddValue(catFeat, catSymbols);
                                }
                                var inflFS = GetFeatureStruct(featSys, mb.MsaRA);
                                if (inflFS != null)
                                {
                                    morphFS.AddValue(inflFeat, inflFS);
                                    if (wordInflFS == null)
                                    {
                                        wordInflFS = inflFS.DeepClone();
                                    }
                                    else
                                    {
                                        wordInflFS.Union(inflFS);
                                    }
                                }
                            }

                            ShapeNode node = m_shape.Add(morphFS);
                            if (analysisStart == null)
                            {
                                analysisStart = node;
                            }
                        }

                        var wordFS = new FeatureStruct();
                        wordFS.AddValue(typeFeat, typeFeat.PossibleSymbols["word"]);
                        if (wanalysis.CategoryRA != null)
                        {
                            wordFS.AddValue(catFeat, catFeat.PossibleSymbols[wanalysis.CategoryRA.Hvo.ToString(CultureInfo.InvariantCulture)]);
                        }
                        if (wordInflFS != null && !wordInflFS.IsEmpty)
                        {
                            wordFS.AddValue(inflFeat, wordInflFS);
                        }
                        wordform = wanalysis.Wordform;
                        foreach (int ws in wordform.Form.AvailableWritingSystemIds)
                        {
                            StringFeature strFeat;
                            if (featSys.TryGetFeature(string.Format("form-{0}", ws), out strFeat))
                            {
                                wordFS.AddValue(strFeat, wordform.Form.get_String(ws).Text);
                            }
                        }
                        var gloss = analysis.Item1 as IWfiGloss;
                        if (gloss != null)
                        {
                            foreach (int ws in gloss.Form.AvailableWritingSystemIds)
                            {
                                StringFeature strFeat;
                                if (featSys.TryGetFeature(string.Format("gloss-{0}", ws), out strFeat))
                                {
                                    wordFS.AddValue(strFeat, gloss.Form.get_String(ws).Text);
                                }
                            }
                        }
                        Annotation <ShapeNode> ann;
                        if (analysisStart != null)
                        {
                            ann = m_shape.Annotations.Add(analysisStart, m_shape.Last, wordFS);
                            m_shape.Add(FeatureStruct.New(featSys).Symbol("bdry").Symbol("wordBdry").Value);
                        }
                        else
                        {
                            ShapeNode node = m_shape.Add(wordFS);
                            ann = node.Annotation;
                        }
                        ann.Data = analysis;
                        annotations.Add(ann);
                    }
                }

                segments[segment] = annotations;
                m_shape.Add(FeatureStruct.New(featSys).Symbol("bdry").Symbol("segBdry").Value);
            }

            foreach (ITextTag tag in m_para.OwnerOfClass <IStText>().TagsOC)
            {
                // skip invalid tags
                // TODO: should these tags be cleaned up somewhere?
                if (tag.BeginAnalysisIndex >= tag.BeginSegmentRA.AnalysesRS.Count || tag.EndAnalysisIndex >= tag.EndSegmentRA.AnalysesRS.Count ||
                    tag.BeginAnalysisIndex > tag.EndAnalysisIndex)
                {
                    continue;
                }
                List <Annotation <ShapeNode> > beginSegment, endSegment;
                if (!segments.TryGetValue(tag.BeginSegmentRA, out beginSegment) || !segments.TryGetValue(tag.EndSegmentRA, out endSegment))
                {
                    continue;
                }
                Annotation <ShapeNode> beginAnnotation = beginSegment[tag.BeginAnalysisIndex];
                Annotation <ShapeNode> endAnnotation   = endSegment[tag.EndAnalysisIndex];
                ICmPossibility         tagType         = tag.TagRA;
                if (tagType == null || beginAnnotation == null || endAnnotation == null)
                {
                    continue;                     // guard against LT-14549 crash
                }
                Annotation <ShapeNode> tagAnn = new Annotation <ShapeNode>(spanFactory.Create(beginAnnotation.Span.Start, endAnnotation.Span.End),
                                                                           FeatureStruct.New(featSys).Symbol("ttag").Symbol(tagType.Hvo.ToString(CultureInfo.InvariantCulture)).Value)
                {
                    Data = tag
                };
                m_shape.Annotations.Add(tagAnn, false);
            }

            return(true);
        }
コード例 #15
0
        /*
         * Detectar os ciclos dentro do grafo para transforma-los em objetos coloridos
         */
        internal String CreateShapes()
        {
            Shapes    shapes          = new Shapes();
            Shape     shape           = new Shape();
            ArrayList processedCurves = new ArrayList();

            Pixel lastPixel  = null;
            Pixel firstPixel = null;
            Color color;
            bool  hasCurve = true;

            foreach (Curve curve in curvesC)
            {
                Curve processingCurve = curve;
                color = processingCurve.color;
                if (!processedCurves.Contains(processingCurve))
                {
                    processedCurves.Add(processingCurve);
                    ArrayList curveArray = (ArrayList)processingCurve.curve;

                    firstPixel = getFirstPixel(curveArray);
                    lastPixel  = getLastPixel(curveArray);
                    shape.Add(curve);
                    if (!firstPixel.Equals(lastPixel)) // se primeiro e ultimo são iguais, então o circuito já esta fechado
                    {
                        hasCurve = true;
                        while (hasCurve)
                        {
                            foreach (Curve newCurve in curvesC)                                                            // verifico todas as curvas procurando uma que comece ou termine com o ultimo pixel da pesquisada
                            {
                                if ((newCurve.color == color && newCurve != curve && !processedCurves.Contains(newCurve))) // Precisa ser uma curva não processessada e com cor igual
                                {
                                    hasCurve = false;
                                    ArrayList newCurveArray = (ArrayList)newCurve.curve;
                                    TaggedUndirectedEdge <Pixel, EdgeTag> firstNewEdge = (TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0];
                                    TaggedUndirectedEdge <Pixel, EdgeTag> lastNewEdge  = (TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[newCurveArray.Count - 1];

                                    if (firstNewEdge.Source.Equals(lastPixel) || firstNewEdge.Target.Equals(lastPixel) || lastNewEdge.Target.Equals(lastPixel) || lastNewEdge.Source.Equals(lastPixel)) // se a curva analizada possui o primeiro ou ultimo pixel igual a um pixel do lastEdge // simplificado apenas para conter um dos pixeis da ultima aresta da curva
                                    {
                                        if (firstNewEdge.Source.Equals(lastPixel) || firstNewEdge.Target.Equals(lastPixel))
                                        {
                                            if (newCurveArray.Count == 1)
                                            {
                                                if (((TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0]).Source.Equals(lastPixel))
                                                {
                                                    lastPixel = ((TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0]).Target;
                                                }
                                                else
                                                {
                                                    lastPixel = ((TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0]).Source;
                                                }
                                            }
                                            else
                                            {
                                                lastPixel = getLastPixel(newCurveArray);
                                            }
                                        }
                                        else
                                        {
                                            if (newCurveArray.Count == 1)
                                            {
                                                if (((TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0]).Source.Equals(lastPixel))
                                                {
                                                    lastPixel = ((TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0]).Target;
                                                }
                                                else
                                                {
                                                    lastPixel = ((TaggedUndirectedEdge <Pixel, EdgeTag>)newCurveArray[0]).Source;
                                                }
                                            }
                                            else
                                            {
                                                lastPixel = getFirstPixel(newCurveArray);
                                                newCurveArray.Reverse();
                                            }
                                        }


                                        processedCurves.Add(newCurve);
                                        if (!lastPixel.Equals(firstPixel))
                                        {
                                            shape.Add(newCurve);
                                            hasCurve = true;
                                            break;
                                        }
                                        else // terminou o grupo de curvas
                                        {
                                            shape.Add(newCurve);
                                            shapes.Add(shape);
                                            hasCurve = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        shapes.Add(shape);
                    }
                    shape = new Shape();
                }
            }

            //remove shapes iguais de cores diferentes
            ArrayList remove = new ArrayList();

            foreach (Shape shapeItem in shapes)
            {
                foreach (Shape shapeItem2 in shapes)
                {
                    if (!remove.Contains(shapeItem) && !remove.Contains(shapeItem2) && shapeItem.getColor() != Color.Beige && shapeItem2.getColor() != Color.Beige)
                    {
                        if (shapeItem.getColor() != shapeItem2.getColor() && shapeItem.isSameShape(shapeItem2))
                        {
                            Color c = new Color();
                            //localiza o pixel de cor dentro do poligono
                            foreach (Pixel v in g.Vertices)
                            {
                                if (v.pixelInsidePolygon(shapeItem.ToPoints()))
                                {
                                    c = v.color;
                                    break;
                                }
                            }

                            if (shapeItem.getColor() == c)
                            {
                                remove.Add(shapeItem2);
                                break;
                            }
                            else
                            if (shapeItem2.getColor() == c)
                            {
                                remove.Add(shapeItem);
                                break;
                            }
                        }
                    }
                }
            }


            foreach (Shape item in remove)
            {
                shapes.Remove(item);
            }

            //Ordena do objeto com maior area para os de menor area
            shapes.Sort();

            SvgVector svg = new SvgVector();

            svg.Height = Height * scale;
            svg.Width  = Width * scale;
            svg.scale  = 1;

            return(svg.NewImage(g, shapes, "NewImage.svg"));
        }
コード例 #16
0
        public async Task <IHtmlContent> Pager_Links(Shape Shape, dynamic DisplayAsync, dynamic New,
                                                     IHtmlHelper Html,
                                                     DisplayContext DisplayContext,
                                                     int Page,
                                                     int PageSize,
                                                     double TotalItemCount,
                                                     int?Quantity,
                                                     object FirstText,
                                                     object PreviousText,
                                                     object NextText,
                                                     object LastText,
                                                     object GapText,
                                                     string PagerId,
                                                     bool ShowNext
                                                     // parameter omitted to workaround an issue where a NullRef is thrown
                                                     // when an anonymous object is bound to an object shape parameter
                                                     /*object RouteValues*/)
        {
            var currentPage = Page;

            if (currentPage < 1)
            {
                currentPage = 1;
            }

            var pageSize = PageSize;

            var numberOfPagesToShow = Quantity ?? 0;

            if (Quantity == null || Quantity < 0)
            {
                numberOfPagesToShow = 7;
            }

            var totalPageCount = pageSize > 0 ? (int)Math.Ceiling(TotalItemCount / pageSize) : 1;

            // return shape early if pager is not needed.
            if (totalPageCount < 2)
            {
                Shape.Metadata.Type = "List";
                return(await DisplayAsync(Shape));
            }


            var firstText    = FirstText ?? T["<<"];
            var previousText = PreviousText ?? T["<"];
            var nextText     = NextText ?? T[">"];
            var lastText     = LastText ?? T[">>"];
            var gapText      = GapText ?? T["..."];

            var httpContextAccessor = DisplayContext.ServiceProvider.GetService <IHttpContextAccessor>();
            var httpContext         = httpContextAccessor.HttpContext;

            var routeData = new RouteValueDictionary(Html.ViewContext.RouteData.Values);

            if (httpContext != null)
            {
                var queryString = httpContext.Request.Query;
                if (queryString != null)
                {
                    foreach (var key in from string key in queryString.Keys where key != null && !routeData.ContainsKey(key) let value = queryString[key] select key)
                    {
                        routeData[key] = queryString[key];
                    }
                }
            }

            // specific cross-requests route data can be passed to the shape directly (e.g., OrchardCore.Users)
            var shapeRoute = (object)((dynamic)Shape).RouteData;

            if (shapeRoute != null)
            {
                var shapeRouteData = shapeRoute as RouteValueDictionary;
                if (shapeRouteData == null)
                {
                    var route = shapeRoute as RouteData;
                    if (route != null)
                    {
                        shapeRouteData = new RouteValueDictionary(route.Values);
                    }
                }

                if (shapeRouteData != null)
                {
                    foreach (var rd in shapeRouteData)
                    {
                        routeData[rd.Key] = rd.Value;
                    }
                }
            }

            int firstPage = Math.Max(1, Page - (numberOfPagesToShow / 2));
            int lastPage  = Math.Min(totalPageCount, Page + (int)(numberOfPagesToShow / 2));

            var pageKey = String.IsNullOrEmpty(PagerId) ? "page" : PagerId;

            Shape.Classes.Add("pager");
            Shape.Metadata.Alternates.Clear();
            Shape.Metadata.Type = "List";

            // first and previous pages
            if ((Page > 1) && (routeData.ContainsKey(pageKey)))
            {
                routeData.Remove(pageKey); // to keep from having "page=1" in the query string
            }
            // first
            Shape.Add(await New.Pager_First(Value: firstText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape, Disabled: Page < 2));

            // previous
            if ((Page > 1) && (currentPage > 2))
            { // also to keep from having "page=1" in the query string
                routeData[pageKey] = currentPage - 1;
            }
            Shape.Add(await New.Pager_Previous(Value: previousText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape, Disabled: Page < 2));


            // gap at the beginning of the pager
            if (firstPage > 1 && numberOfPagesToShow > 0)
            {
                Shape.Add(await New.Pager_Gap(Value: gapText, Pager: Shape));
            }

            // page numbers
            if (numberOfPagesToShow > 0 && lastPage > 1)
            {
                for (var p = firstPage; p <= lastPage; p++)
                {
                    if (p == currentPage)
                    {
                        routeData[pageKey] = currentPage;
                        Shape.Add(await New.Pager_CurrentPage(Value: p, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));
                    }
                    else
                    {
                        if (p == 1)
                        {
                            routeData.Remove(pageKey);
                        }
                        else
                        {
                            routeData[pageKey] = p;
                        }
                        Shape.Add(await New.Pager_Link(Value: p, RouteValues: new RouteValueDictionary(routeData), Pager: Shape));
                    }
                }
            }

            // gap at the end of the pager
            if (lastPage < totalPageCount && numberOfPagesToShow > 0)
            {
                Shape.Add(await New.Pager_Gap(Value: gapText, Pager: Shape));
            }

            // Next
            routeData[pageKey] = Page + 1;
            Shape.Add(await New.Pager_Next(Value: nextText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape, Disabled: Page >= totalPageCount && !ShowNext));

            // Last
            routeData[pageKey] = totalPageCount;
            Shape.Add(await New.Pager_Last(Value: lastText, RouteValues: new RouteValueDictionary(routeData), Pager: Shape, Disabled: Page >= totalPageCount));

            return(await DisplayAsync(Shape));
        }
コード例 #17
0
        public async Task <IHtmlContent> PagerSlim(Shape shape, dynamic DisplayAsync, dynamic New, IHtmlHelper Html, DisplayContext DisplayContext,
                                                   string PagerId,
                                                   object PreviousText,
                                                   object NextText,
                                                   string PreviousClass,
                                                   string NextClass,
                                                   string ItemTagName,
                                                   IDictionary <string, string> ItemAttributes,
                                                   Dictionary <string, string> UrlParams)
        {
            var noFollow     = shape.Attributes.ContainsKey("rel") && shape.Attributes["rel"] == "no-follow";
            var previousText = PreviousText ?? S["<"];
            var nextText     = NextText ?? S[">"];

            shape.Classes.Add("pager");
            shape.Metadata.Alternates.Clear();
            shape.Metadata.Type = "List";

            var routeData = new RouteValueDictionary(Html.ViewContext.RouteData.Values);

            // Allows to pass custom url params to PagerSlim
            if (UrlParams != null)
            {
                foreach (var item in UrlParams)
                {
                    routeData.Add(item.Key, item.Value);
                }
            }

            if (shape.Properties.TryGetValue("Before", out var beforeValue) && beforeValue is string before)
            {
                var beforeRouteData = new RouteValueDictionary(routeData)
                {
                    ["before"] = before
                };

                var previousItem = await New.Pager_Previous(Value : previousText, RouteValues : beforeRouteData, Pager : shape);

                if (noFollow)
                {
                    previousItem.Attributes["rel"] = "no-follow";
                }

                shape.Add(previousItem);
                shape.Properties["FirstClass"] = PreviousClass;
            }

            if (shape.Properties.TryGetValue("After", out var afterValue) && afterValue is string after)
            {
                var afterRouteData = new RouteValueDictionary(routeData)
                {
                    ["after"] = after
                };

                var nextItem = await New.Pager_Next(Value : nextText, RouteValues : afterRouteData, Pager : shape);

                if (noFollow)
                {
                    nextItem.Attributes["rel"] = "no-follow";
                }

                shape.Add(nextItem);
                shape.Properties["LastClass"] = NextClass;
            }

            return(await DisplayAsync(shape));
        }
コード例 #18
0
        /// <summary>
        ///
        /// </summary>
        /// <remarks>
        /// For all of the shapes that has directions (e.g., Cylinder, Hemisphere), Y direction is
        /// used, so if you would like it to face other directions, use MataliObject.ShapeOriginalMatrix
        /// to orient them.
        ///
        /// For a cylinder with different bottom and top radius, IPhysicsObject.ShapeData are used.
        /// ShapeData[0] - bottom radius, ShapeData[1] - height, ShapeData[2] = top radius
        ///
        /// For Compound shape, an additional information can be set by using
        /// MataliObject.CompoundShape.
        ///
        /// For additional shape types such as Heightmap, Point, and so on, set Shape to ShapeType.Extra
        /// and define MataliObject.ExtraShape.
        /// </remarks>
        /// <param name="mataliPhysicsObj"></param>
        /// <param name="physObj"></param>
        private void SetShape(MataliPhysicsObject mataliPhysicsObj, IPhysicsObject physObj)
        {
            Vector3 boundingBox = Vector3.Zero;

            if (physObj.Model != null)
            {
                boundingBox = Vector3Helper.GetDimensions(physObj.Model.MinimumBoundingBox);
            }
            Vector3 size = Vector3.Zero;

            MataliObject mataliObj = null;

            if (physObj is MataliObject)
            {
                mataliObj = (MataliObject)physObj;
            }

            switch (physObj.Shape)
            {
            case ShapeType.Box:
                if (physObj.ShapeData.Count == 3)
                {
                    size = new Vector3(physObj.ShapeData[0], physObj.ShapeData[1], physObj.ShapeData[2]);
                }
                else
                {
                    size = boundingBox;
                }

                size /= 2;
                break;

            case ShapeType.Sphere:
                if (physObj.ShapeData.Count == 1)
                {
                    size = new Vector3(physObj.ShapeData[0], 0, 0);
                }
                else
                {
                    size = boundingBox / 2;
                }
                break;

            case ShapeType.Cone:
            case ShapeType.Cylinder:
            case ShapeType.Capsule:
                if (physObj.ShapeData.Count == 2)
                {
                    size = new Vector3(physObj.ShapeData[0], physObj.ShapeData[1], physObj.ShapeData[0]);
                }
                else if (physObj.ShapeData.Count == 3)
                {
                    size = new Vector3(physObj.ShapeData[0], physObj.ShapeData[1], physObj.ShapeData[2]);
                }
                else
                {
                    size = new Vector3(boundingBox.X / 2, boundingBox.Y, boundingBox.X / 2);
                }
                break;

            case ShapeType.Compound:
                // size is used solely for naming, not used for the collision shape
                size = new Vector3(physObj.ShapeData.Count, physObj.ShapeData[0],
                                   physObj.ShapeData[physObj.ShapeData.Count - 1]);
                break;

            case ShapeType.ConvexHull:
                // size is used solely for naming, not used for the collision shape
                size = new Vector3(physObj.MeshProvider.Vertices.Count,
                                   physObj.MeshProvider.Indices.Count, physObj.MeshProvider.Vertices[0].X);
                break;

            case ShapeType.Extra:
                if (mataliObj == null)
                {
                    throw new GoblinException("For extra shape type, you need to define the 'physObj' " +
                                              "as MataliObject instance");
                }

                if (mataliObj.ExtraShape == ExtraShapeType.Undefined)
                {
                    throw new GoblinException("Undefined type is not allowed if Extra shape type is specified");
                }

                // size is used solely for naming, not used for the collision shape
                switch (mataliObj.ExtraShape)
                {
                case ExtraShapeType.Point:
                    if (physObj.ShapeData.Count != 3)
                    {
                        throw new GoblinException("For Point shape type, you need to specify the position (x,y,z) in ShapeData");
                    }

                    size = new Vector3(physObj.ShapeData[0], physObj.ShapeData[1], physObj.ShapeData[2]);
                    break;

                case ExtraShapeType.Heightmap:
                    if (physObj.ShapeData.Count < 2)
                    {
                        throw new GoblinException("There needs to be at least two floats specifying the " +
                                                  "width and height");
                    }

                    size = new Vector3(physObj.ShapeData[0], physObj.ShapeData[1], physObj.ShapeData.Count);
                    break;

                case ExtraShapeType.Edge:
                    if (physObj.ShapeData.Count != 6)
                    {
                        throw new GoblinException("For Edge shape type, you need to specify the start and " +
                                                  "end positions (x,y,z) in ShapeData");
                    }

                    size = new Vector3(physObj.ShapeData[0] + physObj.ShapeData[3],
                                       physObj.ShapeData[1] + physObj.ShapeData[4],
                                       physObj.ShapeData[2] + physObj.ShapeData[5]);
                    break;

                default:
                    throw new GoblinException(mataliObj.ExtraShape.ToString() + " not implemented yet");
                }
                break;
            }

            String shapeName     = physObj.Shape.ToString() + size.ToString();
            String primitiveName = physObj.Shape.ToString() + size.ToString();

            if (mataliObj != null)
            {
                String suffix = "";
                if (physObj.Shape == ShapeType.Extra)
                {
                    suffix += mataliObj.ExtraShape.ToString();
                }
                else if (physObj.Shape == ShapeType.Compound)
                {
                    suffix += mataliObj.CompoundShape.ToString();
                }
                suffix += mataliObj.ShapeOriginalMatrix.ToString();
                suffix += mataliObj.ShapeCollisionMargin;

                shapeName     += suffix;
                primitiveName += suffix;
            }
            Shape          shape     = null;
            ShapePrimitive primitive = null;

            if (scene.Factory.ShapeManager.Contains(shapeName))
            {
                shape = scene.Factory.ShapeManager.Find(shapeName);
            }
            else
            {
                if (physObj.Shape != ShapeType.Compound)
                {
                    primitive = scene.Factory.ShapePrimitiveManager.Create(primitiveName);
                }
                shape = scene.Factory.ShapeManager.Create(shapeName);
                bool shapeSet = false;
                switch (physObj.Shape)
                {
                case ShapeType.Box:
                    primitive.CreateBox(size.X, size.Y, size.Z);
                    break;

                case ShapeType.Sphere:
                    primitive.CreateSphere(size.X);
                    break;

                case ShapeType.Cone:
                    primitive.CreateConeY(size.Y, size.X);
                    break;

                case ShapeType.Cylinder:
                    if (size.X != size.Z)
                    {
                        primitive.CreateCylinder2RY(size.Y, size.X, size.Z);
                    }
                    else
                    {
                        primitive.CreateCylinderY(size.Y, size.X);
                    }
                    break;

                case ShapeType.Capsule:
                    primitive.CreateCapsuleY(size.Y - size.X * 2, size.X);
                    break;

                case ShapeType.Compound:
                    ShapeCompoundType type = ShapeCompoundType.ConvexHull;
                    if (mataliObj != null)
                    {
                        if (mataliObj.CompoundShape == CompoundShapeType.MinkowskiSum)
                        {
                            type = ShapeCompoundType.MinkowskiSum;
                        }
                    }

                    int            dataIndex         = 0;
                    Shape          compoundShapePart = null;
                    ShapePrimitive compoundPrimitive = null;
                    float[]        matrixVals        = new float[16];
                    while (dataIndex < physObj.ShapeData.Count)
                    {
                        ShapeType shapeType = (ShapeType)Enum.ToObject(typeof(ShapeType), (int)physObj.ShapeData[dataIndex++]);
                        switch (shapeType)
                        {
                        case ShapeType.Cylinder:
                            size = new Vector3(physObj.ShapeData[dataIndex], physObj.ShapeData[dataIndex + 1],
                                               physObj.ShapeData[dataIndex]);
                            dataIndex += 2;
                            break;

                        case ShapeType.Sphere:
                            size = new Vector3(physObj.ShapeData[dataIndex], 0, 0);
                            dataIndex++;
                            break;
                        }

                        shapeName     = shapeType.ToString() + size.ToString();
                        primitiveName = shapeType.ToString() + size.ToString();

                        if (scene.Factory.ShapeManager.Contains(shapeName))
                        {
                            compoundShapePart = scene.Factory.ShapeManager.Find(shapeName);
                        }
                        else
                        {
                            compoundPrimitive = scene.Factory.ShapePrimitiveManager.Create(primitiveName);
                            compoundShapePart = scene.Factory.ShapeManager.Create(shapeName);
                            switch (shapeType)
                            {
                            case ShapeType.Cylinder:
                                compoundPrimitive.CreateCylinderY(size.Y, size.X);
                                break;

                            case ShapeType.Sphere:
                                compoundPrimitive.CreateSphere(size.X);
                                break;

                            default:
                                throw new GoblinException(shape.ToString() + " is not supported yet as a compound part");
                            }

                            compoundShapePart.Set(compoundPrimitive, Matrix.Identity, 0.0f);
                        }

                        for (int i = 0; i < 16; ++i)
                        {
                            matrixVals[i] = physObj.ShapeData[dataIndex + i];
                        }
                        dataIndex += 16;
                        shape.Add(compoundShapePart, MatrixHelper.FloatsToMatrix(matrixVals), 0.0f, type);
                    }

                    float margin = 0.0f;
                    if (mataliObj != null)
                    {
                        margin = mataliObj.ShapeCollisionMargin;
                    }
                    shape.CreateMesh(margin);

                    shapeSet = true;
                    break;

                case ShapeType.ConvexHull:
                case ShapeType.TriangleMesh:
                    float[] frictions    = null;
                    float[] restitutions = null;

                    if (physObj.Shape == ShapeType.ConvexHull)
                    {
                        primitive.CreateConvex(physObj.MeshProvider.Vertices);
                    }
                    else
                    {
                        int triangleCount = physObj.MeshProvider.Indices.Count / 3;
                        frictions    = new float[triangleCount];
                        restitutions = new float[triangleCount];

                        for (int i = 0; i < frictions.Length; i++)
                        {
                            frictions[i]    = 1.0f;
                            restitutions[i] = 0.0f;
                        }

                        Vector3[] triVerts = new Vector3[physObj.MeshProvider.Indices.Count];
                        for (int i = 0; i < triVerts.Length; ++i)
                        {
                            triVerts[i] = physObj.MeshProvider.Vertices[physObj.MeshProvider.Indices[i]];
                        }

                        bool flipTriangle = (physObj is MataliObject) ? ((MataliObject)physObj).FlipTriangleOrder : true;
                        primitive.CreateTriangleMesh(triVerts, flipTriangle, 2, frictions, restitutions, 1.0f, 0.0f);
                    }

                    break;

                case ShapeType.Extra:
                    switch (mataliObj.ExtraShape)
                    {
                    case ExtraShapeType.Heightmap:
                        int     width             = (int)physObj.ShapeData[0];
                        int     height            = (int)physObj.ShapeData[1];
                        float[] heightData        = new float[height * width];
                        float[] heightFrictions   = new float[height * width];
                        float[] heightRestituions = new float[height * width];

                        if (physObj.ShapeData.Count < (2 + heightData.Length))
                        {
                            throw new GoblinException("You also need to specify the hegith map data");
                        }
                        Buffer.BlockCopy(physObj.ShapeData.ToArray(), 2 * sizeof(float), heightData, 0,
                                         heightData.Length * sizeof(float));

                        if (physObj.ShapeData.Count > (2 + heightData.Length * 2))
                        {
                            Buffer.BlockCopy(physObj.ShapeData.ToArray(), (2 + heightData.Length) * sizeof(float),
                                             heightFrictions, 0, heightFrictions.Length * sizeof(float));
                        }
                        else
                        {
                            for (int i = 0; i < heightFrictions.Length; ++i)
                            {
                                heightFrictions[i] = mataliObj.TriangleMeshFriction;
                            }
                        }

                        if (physObj.ShapeData.Count > (2 + heightData.Length * 3))
                        {
                            Buffer.BlockCopy(physObj.ShapeData.ToArray(), (2 + heightData.Length * 2) * sizeof(float),
                                             heightRestituions, 0, heightRestituions.Length * sizeof(float));
                        }
                        else
                        {
                            for (int i = 0; i < heightRestituions.Length; ++i)
                            {
                                heightRestituions[i] = mataliObj.TriangleMeshRestitution;
                            }
                        }

                        primitive.CreateHeightmap(0, 0, width, height, width, height, heightData, heightFrictions, heightRestituions,
                                                  mataliObj.TriangleMeshFriction, mataliObj.TriangleMeshRestitution, mataliObj.IsDynamic);
                        shape.Set(primitive, mataliObj.ShapeOriginalMatrix, mataliObj.ShapeCollisionMargin);
                        shape.CreateMesh(0.0f);
                        shapeSet = true;

                        mataliPhysicsObj.InternalControllers.CreateHeightmapController(true);
                        break;

                    case ExtraShapeType.Point:
                        primitive.CreatePoint(physObj.ShapeData[0], physObj.ShapeData[1], physObj.ShapeData[2]);
                        break;

                    case ExtraShapeType.Edge:
                        primitive.CreateEdge(new Vector3(physObj.ShapeData[0], physObj.ShapeData[1], physObj.ShapeData[2]),
                                             new Vector3(physObj.ShapeData[3], physObj.ShapeData[4], physObj.ShapeData[5]));
                        break;

                    case ExtraShapeType.Plane:
                        primitive.CreatePlaneY(physObj.ShapeData[0], (physObj.ShapeData[1] > 0));
                        break;

                    case ExtraShapeType.Triangle:
                        primitive.CreateTriangle(
                            new Vector3(physObj.ShapeData[0], physObj.ShapeData[1], physObj.ShapeData[2]),
                            new Vector3(physObj.ShapeData[3], physObj.ShapeData[4], physObj.ShapeData[5]),
                            new Vector3(physObj.ShapeData[6], physObj.ShapeData[7], physObj.ShapeData[8]));
                        break;

                    case ExtraShapeType.Tetrahedron:
                        primitive.CreateTetrahedron(
                            new Vector3(physObj.ShapeData[0], physObj.ShapeData[1], physObj.ShapeData[2]),
                            new Vector3(physObj.ShapeData[3], physObj.ShapeData[4], physObj.ShapeData[5]),
                            new Vector3(physObj.ShapeData[6], physObj.ShapeData[7], physObj.ShapeData[8]),
                            new Vector3(physObj.ShapeData[9], physObj.ShapeData[10], physObj.ShapeData[11]));
                        break;

                    case ExtraShapeType.Fluid:
                        break;

                    case ExtraShapeType.Hemisphere:
                        primitive.CreateHemisphereY(physObj.ShapeData[0]);
                        break;
                    }
                    break;
                }

                if (!shapeSet)
                {
                    if (mataliObj != null)
                    {
                        shape.Set(primitive, mataliObj.ShapeOriginalMatrix, mataliObj.ShapeCollisionMargin);
                    }
                    else
                    {
                        shape.Set(primitive, Matrix.Identity, 0.0f);
                    }

                    if (buildCollisionMesh)
                    {
                        float margin = 0.0f;
                        if (mataliObj != null)
                        {
                            margin = mataliObj.ShapeCollisionMargin;
                        }
                        shape.CreateMesh(margin);
                    }
                }
            }

            mataliPhysicsObj.Shape = shape;
        }
コード例 #19
0
ファイル: UserShapes.cs プロジェクト: 0000duck/KAOS-Engine
        public static void CreateShapes(Demo demo, PhysicsScene scene)
        {
            ShapePrimitive shapePrimitive = null;
            Shape          shape          = null;
            Shape          userShape      = null;

            Shape sphere    = scene.Factory.ShapeManager.Find("Sphere");
            Shape box       = scene.Factory.ShapeManager.Find("Box");
            Shape coneY     = scene.Factory.ShapeManager.Find("ConeY");
            Shape cylinderY = scene.Factory.ShapeManager.Find("CylinderY");

            shape = scene.Factory.ShapeManager.Create("UserShape 1");
            shape.Add(box, Matrix4.Identity, 0.0f, ShapeCompoundType.MinkowskiSum);
            shape.Add(sphere, Matrix4.Identity, 0.0f, ShapeCompoundType.MinkowskiSum);
            shape.CreateMesh(0.0f);

            if (!demo.Meshes.ContainsKey("UserShape1"))
            {
                demo.Meshes.Add("UserShape1", new DemoMesh(demo, shape, demo.Textures["Default"], Vector2.One, false, false, false, false, true, CullFaceMode.Back, false, false));
            }

            shape = scene.Factory.ShapeManager.Create("UserShape 2");
            shape.Add(coneY, Matrix4.Identity, 0.0f, ShapeCompoundType.MinkowskiSum);
            shape.Add(sphere, Matrix4.Identity, 0.0f, ShapeCompoundType.MinkowskiSum);
            shape.CreateMesh(0.0f);

            if (!demo.Meshes.ContainsKey("UserShape2"))
            {
                demo.Meshes.Add("UserShape2", new DemoMesh(demo, shape, demo.Textures["Default"], Vector2.One, false, false, false, false, true, CullFaceMode.Back, false, false));
            }

            shape = scene.Factory.ShapeManager.Create("UserShape 3");
            shape.Add(cylinderY, Matrix4.Identity, 0.0f, ShapeCompoundType.MinkowskiSum);
            shape.Add(sphere, Matrix4.Identity, 0.0f, ShapeCompoundType.MinkowskiSum);
            shape.CreateMesh(0.0f);

            if (!demo.Meshes.ContainsKey("UserShape3"))
            {
                demo.Meshes.Add("UserShape3", new DemoMesh(demo, shape, demo.Textures["Default"], Vector2.One, false, false, false, false, true, CullFaceMode.Back, false, false));
            }

            shape = scene.Factory.ShapeManager.Create("UserShape 4");
            shape.Add(coneY, Matrix4.Identity, 0.0f, ShapeCompoundType.MinkowskiSum);
            shape.Add(sphere, Matrix4.Identity, 0.0f, ShapeCompoundType.MinkowskiSum);
            shape.Add(cylinderY, Matrix4.CreateScale(4.0f, 0.5f, 4.0f), 0.0f, ShapeCompoundType.ConvexHull);
            shape.CreateMesh(0.0f);

            if (!demo.Meshes.ContainsKey("UserShape4"))
            {
                demo.Meshes.Add("UserShape4", new DemoMesh(demo, shape, demo.Textures["Default"], Vector2.One, false, false, false, false, true, CullFaceMode.Back, false, false));
            }

            Vector3[] convexTab1 = new Vector3[6];
            convexTab1[0] = new Vector3(0.0f, -2.0f, 0.0f);
            convexTab1[1] = new Vector3(0.0f, 4.0f, 0.0f);
            convexTab1[2] = new Vector3(2.0f, 0.0f, 0.0f);
            convexTab1[3] = new Vector3(-4.0f, 0.0f, 0.0f);
            convexTab1[4] = new Vector3(0.0f, 0.0f, 4.0f);
            convexTab1[5] = new Vector3(0.0f, 0.0f, -2.0f);

            shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("Convex 1");
            shapePrimitive.CreateConvex(convexTab1);

            userShape = scene.Factory.ShapeManager.Create("UserShape 5");
            userShape.Set(shapePrimitive, Matrix4.Identity, 0.0f);
            userShape.CreateMesh(0.0f);

            if (!demo.Meshes.ContainsKey("UserShape5"))
            {
                demo.Meshes.Add("UserShape5", new DemoMesh(demo, userShape, demo.Textures["Default"], Vector2.One, false, false, false, false, true, CullFaceMode.Back, false, false));
            }

            shape = scene.Factory.ShapeManager.Create("UserShape 6");
            shape.Add(userShape, Matrix4.Identity, 0.0f, ShapeCompoundType.MinkowskiSum);
            shape.Add(sphere, Matrix4.CreateScale(0.5f), 0.0f, ShapeCompoundType.MinkowskiSum);
            shape.CreateMesh(0.0f);

            if (!demo.Meshes.ContainsKey("UserShape6"))
            {
                demo.Meshes.Add("UserShape6", new DemoMesh(demo, shape, demo.Textures["Default"], Vector2.One, false, false, false, false, true, CullFaceMode.Back, false, false));
            }

            Vector3[] convexTab2 = new Vector3[10];
            convexTab2[0] = new Vector3(-2.0f, -0.5f, -1.0f);
            convexTab2[1] = new Vector3(-1.5f, -0.5f, 0.5f);
            convexTab2[2] = new Vector3(0.0f, -0.5f, 2.0f);
            convexTab2[3] = new Vector3(1.5f, -0.5f, 0.5f);
            convexTab2[4] = new Vector3(2.0f, -0.5f, -1.0f);
            convexTab2[5] = new Vector3(-2.0f, 0.5f, -1.0f);
            convexTab2[6] = new Vector3(-1.5f, 0.5f, 0.5f);
            convexTab2[7] = new Vector3(0.0f, 0.5f, 2.0f);
            convexTab2[8] = new Vector3(1.5f, 0.5f, 0.5f);
            convexTab2[9] = new Vector3(2.0f, 0.5f, -1.0f);

            shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("Convex 2");
            shapePrimitive.CreateConvex(convexTab2);
            userShape = scene.Factory.ShapeManager.Create("UserShape 7");
            userShape.Set(shapePrimitive, Matrix4.Identity, 0.0f);
            userShape.CreateMesh(0.0f);

            if (!demo.Meshes.ContainsKey("UserShape7"))
            {
                demo.Meshes.Add("UserShape7", new DemoMesh(demo, userShape, demo.Textures["Default"], Vector2.One, false, false, false, false, true, CullFaceMode.Back, false, false));
            }

            shape = scene.Factory.ShapeManager.Create("UserShape 8");
            shape.Add(userShape, Matrix4.Identity, 0.0f, ShapeCompoundType.MinkowskiSum);
            shape.Add(sphere, Matrix4.CreateScale(0.5f), 0.0f, ShapeCompoundType.MinkowskiSum);
            shape.CreateMesh(0.0f);

            if (!demo.Meshes.ContainsKey("UserShape8"))
            {
                demo.Meshes.Add("UserShape8", new DemoMesh(demo, shape, demo.Textures["Default"], Vector2.One, false, false, false, false, true, CullFaceMode.Back, false, false));
            }
        }
コード例 #20
0
        protected ShapeNode Combine(FeatureSymbol syllablePosition, Shape newShape, ShapeNode start, ShapeNode end)
        {
            ShapeNode newStart = null;

            if (start == end)
            {
                newStart = start.DeepClone();
                newStart.Annotation.FeatureStruct.AddValue(CogFeatureSystem.SyllablePosition, syllablePosition);
                newShape.Add(newStart);
            }
            else if ((_combineVowels && syllablePosition == CogFeatureSystem.Nucleus) || (_combineConsonants && syllablePosition != CogFeatureSystem.Nucleus))
            {
                var fs         = start.Annotation.FeatureStruct.DeepClone();
                var strRep     = new StringBuilder();
                var origStrRep = new StringBuilder();
                strRep.Append(start.StrRep());
                origStrRep.Append(start.OriginalStrRep());
                ShapeNode node      = start.Next;
                bool      isComplex = false;
                while (node != end.Next)
                {
                    strRep.Append(node.StrRep());
                    origStrRep.Append(node.OriginalStrRep());
                    fs.Add(node.Annotation.FeatureStruct);
                    node      = node.Next;
                    isComplex = true;
                }
                fs.AddValue(CogFeatureSystem.StrRep, strRep.ToString());
                fs.AddValue(CogFeatureSystem.OriginalStrRep, origStrRep.ToString());
                fs.AddValue(CogFeatureSystem.SegmentType, isComplex ? CogFeatureSystem.Complex : CogFeatureSystem.Simple);
                fs.AddValue(CogFeatureSystem.SyllablePosition, syllablePosition);
                if (isComplex)
                {
                    FeatureStruct firstFS;
                    if (start.IsComplex())
                    {
                        firstFS = start.Annotation.FeatureStruct.GetValue(CogFeatureSystem.First);
                    }
                    else
                    {
                        firstFS = new FeatureStruct();
                        foreach (Feature feature in start.Annotation.FeatureStruct.Features.Where(f => !CogFeatureSystem.Instance.ContainsFeature(f)))
                        {
                            firstFS.AddValue(feature, start.Annotation.FeatureStruct.GetValue(feature));
                        }
                    }
                    fs.AddValue(CogFeatureSystem.First, firstFS);
                }
                newStart = newShape.Add(fs);
            }
            else
            {
                ShapeNode node = start;
                while (node != end.Next)
                {
                    var newNode = node.DeepClone();
                    newNode.Annotation.FeatureStruct.AddValue(CogFeatureSystem.SyllablePosition, syllablePosition);
                    newShape.Add(newNode);
                    if (newStart == null)
                    {
                        newStart = newNode;
                    }
                    node = node.Next;
                }
            }

            Debug.Assert(newStart != null);
            return(newStart);
        }
コード例 #21
0
        public async Task <IHtmlContent> ColumnGrouping(dynamic DisplayAsync, dynamic Shape, IShapeFactory ShapeFactory)
        {
            var htmlContentBuilder = new HtmlContentBuilder();
            IGrouping <string, dynamic> grouping = Shape.Grouping;

            var groupings = grouping.GroupBy(x => {
                // By convention all placement delimiters default to the name 'Content' when not specified during placement.
                var key = (string)x.Metadata.Column;
                if (String.IsNullOrEmpty(key))
                {
                    key = "Content";
                }

                // Remove column modifier.
                var modifierIndex = key.IndexOf('_');
                if (modifierIndex != -1)
                {
                    key = key.Substring(0, modifierIndex);
                }

                // Remove positional modifier.
                modifierIndex = key.IndexOf(';');
                if (modifierIndex != -1)
                {
                    key = key.Substring(0, modifierIndex);
                }

                return(key);
            }).ToList();

            if (groupings.Count > 1)
            {
                var positionModifiers = GetColumnPositions(groupings);

                var orderedGroupings = groupings.OrderBy(grouping => {
                    if (positionModifiers.TryGetValue(grouping.Key, out var position))
                    {
                        return(new PositionalGrouping {
                            Position = position
                        });
                    }
                    else
                    {
                        return(new PositionalGrouping());
                    }
                }, FlatPositionComparer.Instance).ToList();

                var columnModifiers = GetColumnModifiers(orderedGroupings);

                Shape container = (Shape)await ShapeFactory.CreateAsync("ColumnContainer", Arguments.From(
                                                                            new
                {
                    ContentItem = Shape.ContentItem
                }));

                foreach (var orderedGrouping in orderedGroupings)
                {
                    Shape groupingShape = (Shape)await ShapeFactory.CreateAsync("Column", Arguments.From(
                                                                                    new
                    {
                        Grouping    = orderedGrouping,
                        ContentItem = Shape.ContentItem
                    }));

                    groupingShape.Classes.Add("ta-col-grouping");
                    groupingShape.Classes.Add("column-" + orderedGrouping.Key.HtmlClassify());

                    // To adjust this breakpoint apply a modifier of lg-3 to every column.
                    var columnClasses = "col-12 col-md";
                    if (columnModifiers.TryGetValue(orderedGrouping.Key, out var columnModifier))
                    {
                        // When the modifier also has a - assume it is providing a breakpointed class.
                        if (columnModifier.IndexOf('-') != -1)
                        {
                            columnClasses = "col-12 col-" + columnModifier;
                        }
                        else // Otherwise assume a default md breakpoint.
                        {
                            columnClasses = "col-12 col-md-" + columnModifier;
                        }
                    }

                    groupingShape.Classes.Add(columnClasses);

                    foreach (var item in orderedGrouping)
                    {
                        groupingShape.Add(item);
                    }
                    container.Add(groupingShape);
                }

                htmlContentBuilder.AppendHtml(await DisplayAsync(container));
            }
            else
            {
                foreach (var item in grouping)
                {
                    htmlContentBuilder.AppendHtml(await DisplayAsync(item));
                }
            }

            return(htmlContentBuilder);
        }
コード例 #22
0
 private void Untruncate(PatternNode<Word, ShapeNode> patternNode, Shape output, bool optional, VariableBindings varBindings)
 {
     foreach (PatternNode<Word, ShapeNode> node in patternNode.Children)
     {
         var constraint = node as Constraint<Word, ShapeNode>;
         if (constraint != null && constraint.Type() == HCFeatureSystem.Segment)
         {
             FeatureStruct fs = constraint.FeatureStruct.DeepClone();
             fs.ReplaceVariables(varBindings);
             output.Add(fs, optional);
         }
         else
         {
             var quantifier = node as Quantifier<Word, ShapeNode>;
             if (quantifier != null)
             {
                 for (int i = 0; i < quantifier.MaxOccur; i++)
                     Untruncate(quantifier, output, i >= quantifier.MinOccur, varBindings);
             }
             else
             {
                 Untruncate(node, output, optional, varBindings);
             }
         }
     }
 }
コード例 #23
0
        public async Task <IHtmlContent> ContentZone(dynamic DisplayAsync, dynamic Shape, IShapeFactory ShapeFactory)
        {
            var htmlContentBuilder = new HtmlContentBuilder();

            var shapes = ((IEnumerable <dynamic>)Shape);

            var groupings = shapes.GroupBy(x =>
            {
                // By convention all placement delimiters default to the name 'Content' when not specified during placement.
                var key = (string)x.Metadata.Tab;
                if (String.IsNullOrEmpty(key))
                {
                    key = "Content";
                }

                // Remove any positioning modifier.
                var modifierIndex = key.IndexOf(';');
                if (modifierIndex != -1)
                {
                    key = key.Substring(0, modifierIndex);
                }

                return(key);
            }).ToList();

            // Process Tabs first, then Cards, then Columns.
            if (groupings.Count > 1)
            {
                var orderedGroupings = groupings.OrderBy(grouping => {
                    var firstGroupWithModifier = grouping.FirstOrDefault(group => {
                        var key = (string)group.Metadata.Tab;
                        if (!String.IsNullOrEmpty(key))
                        {
                            var modifierIndex = key.IndexOf(';');
                            if (modifierIndex != -1)
                            {
                                return(true);
                            }
                        }
                        return(false);
                    });

                    if (firstGroupWithModifier != null)
                    {
                        var key           = (string)firstGroupWithModifier.Metadata.Tab;
                        var modifierIndex = key.IndexOf(';');
                        return(new PositionalGrouping(key.Substring(modifierIndex)));
                    }

                    return(new PositionalGrouping(null));
                }, FlatPositionComparer.Instance).ToList();

                Shape container = (Shape)await ShapeFactory.CreateAsync("TabContainer", Arguments.From(
                                                                            new
                {
                    ContentItem = Shape.ContentItem,
                    Grouping    = orderedGroupings
                }));

                foreach (var orderedGrouping in orderedGroupings)
                {
                    Shape groupingShape = (Shape)await ShapeFactory.CreateAsync("Tab", Arguments.From(
                                                                                    new
                    {
                        Grouping    = orderedGrouping,
                        ContentItem = Shape.ContentItem
                    }));

                    foreach (var item in orderedGrouping)
                    {
                        groupingShape.Add(item);
                    }
                    container.Add(groupingShape);
                }

                htmlContentBuilder.AppendHtml(await DisplayAsync(container));
            }
            else if (groupings.Count == 1)
            {
                // Evaluate for cards.
                var cardGrouping = await ShapeFactory.CreateAsync("CardGrouping", Arguments.From(
                                                                      new
                {
                    Grouping    = groupings[0],
                    ContentItem = Shape.ContentItem
                }));

                htmlContentBuilder.AppendHtml(await DisplayAsync(cardGrouping));
            }

            return(htmlContentBuilder);
        }
コード例 #24
0
ファイル: Segmenter.cs プロジェクト: rmunn/cog
        private bool SegmentString(Shape shape, string str)
        {
            if (_regex == null)
                _regex = new Regex(CreateRegexString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

            int index = 0;
            foreach (Match match in _regex.Matches(str))
            {
                if (match.Index != index)
                    break;

                if (match.Groups["vowelSeg"].Success)
                {
                    string strRep;
                    FeatureStruct phonemeFS;
                    if (!TryMultipleBaseCharacterSymbol(match, _vowels, out strRep, out phonemeFS))
                    {
                        var sb = new StringBuilder();
                        Group vowelComp = match.Groups["vowelComp"];
                        string partStrRep;
                        phonemeFS = BuildFeatStruct(match, vowelComp.Captures[0], "vowelBase", _vowels, out partStrRep);
                        sb.Append(partStrRep);
                        Group joinerGroup = match.Groups["joiner"];
                        if (joinerGroup.Success || vowelComp.Captures.Count > 1)
                        {
                            phonemeFS.AddValue(CogFeatureSystem.First, phonemeFS.DeepClone());
                            phonemeFS.AddValue(CogFeatureSystem.SegmentType, CogFeatureSystem.Complex);
                        }
                        else
                        {
                            phonemeFS.AddValue(CogFeatureSystem.SegmentType, CogFeatureSystem.Simple);
                        }
                        if (joinerGroup.Success)
                        {
                            for (int i = 0; i < joinerGroup.Captures.Count; i++)
                            {
                                string joinerStr = joinerGroup.Captures[i].Value;
                                phonemeFS.Add(BuildFeatStruct(match, vowelComp.Captures[i + 1], "vowelBase", _vowels, out partStrRep));
                                sb.Append(partStrRep);
                                FeatureStruct joinerFs = _joiners[joinerStr].FeatureStruct;
                                if (joinerFs != null)
                                    phonemeFS.PriorityUnion(joinerFs);
                            }
                        }
                        else if (vowelComp.Captures.Count > 1)
                        {
                            for (int i = 1; i < vowelComp.Captures.Count; i++)
                            {
                                phonemeFS.Add(BuildFeatStruct(match, vowelComp.Captures[i], "vowelBase", _vowels, out partStrRep));
                                sb.Append(partStrRep);
                            }
                        }
                        strRep = sb.ToString();
                    }

                    phonemeFS.AddValue(CogFeatureSystem.StrRep, strRep);
                    phonemeFS.AddValue(CogFeatureSystem.OriginalStrRep, match.Value);
                    phonemeFS.AddValue(CogFeatureSystem.Type, CogFeatureSystem.VowelType);
                    shape.Add(phonemeFS);
                }
                else if (match.Groups["consSeg"].Success)
                {
                    string strRep;
                    FeatureStruct phonemeFS;
                    if (!TryMultipleBaseCharacterSymbol(match, _consonants, out strRep, out phonemeFS))
                    {
                        var sb = new StringBuilder();
                        Group consComp = match.Groups["consComp"];
                        string compStrRep;
                        phonemeFS = BuildFeatStruct(match, consComp.Captures[0], "consBase", _consonants, out compStrRep);
                        sb.Append(compStrRep);
                        Group joinerGroup = match.Groups["joiner"];
                        if (joinerGroup.Success || consComp.Captures.Count > 1)
                        {
                            phonemeFS.AddValue(CogFeatureSystem.First, phonemeFS.DeepClone());
                            phonemeFS.AddValue(CogFeatureSystem.SegmentType, CogFeatureSystem.Complex);
                        }
                        else
                        {
                            phonemeFS.AddValue(CogFeatureSystem.SegmentType, CogFeatureSystem.Simple);
                        }
                        if (joinerGroup.Success)
                        {
                            for (int i = 0; i < joinerGroup.Captures.Count; i++)
                            {
                                string joinerStr = joinerGroup.Captures[i].Value;
                                phonemeFS.Add(BuildFeatStruct(match, consComp.Captures[i + 1], "consBase", _consonants, out compStrRep));
                                sb.Append(compStrRep);
                                FeatureStruct joinerFs = _joiners[joinerStr].FeatureStruct;
                                if (joinerFs != null)
                                    phonemeFS.PriorityUnion(joinerFs);
                            }
                        }
                        else if (consComp.Captures.Count > 1)
                        {
                            for (int i = 1; i < consComp.Captures.Count; i++)
                            {
                                phonemeFS.Add(BuildFeatStruct(match, consComp.Captures[i], "consBase", _consonants, out compStrRep));
                                sb.Append(compStrRep);
                            }
                        }
                        strRep = sb.ToString();
                    }

                    phonemeFS.AddValue(CogFeatureSystem.StrRep, strRep);
                    phonemeFS.AddValue(CogFeatureSystem.OriginalStrRep, match.Value);
                    phonemeFS.AddValue(CogFeatureSystem.Type, CogFeatureSystem.ConsonantType);
                    shape.Add(phonemeFS);
                }
                else if (match.Groups["tone"].Success)
                {
                    shape.Add(FeatureStruct.New()
                        .Symbol(CogFeatureSystem.ToneLetterType)
                        .Feature(CogFeatureSystem.StrRep).EqualTo(match.Value)
                        .Feature(CogFeatureSystem.OriginalStrRep).EqualTo(match.Value).Value);
                }
                else if (match.Groups["bdry"].Success)
                {
                    shape.Add(FeatureStruct.New()
                        .Symbol(CogFeatureSystem.BoundaryType)
                        .Feature(CogFeatureSystem.StrRep).EqualTo(match.Value)
                        .Feature(CogFeatureSystem.OriginalStrRep).EqualTo(match.Value).Value);
                }

                index = match.Index + match.Length;

                if (index == str.Length)
                {
                    if (shape.Count == 0)
                        break;

                    return true;
                }
            }

            return false;
        }
コード例 #25
0
        /*
         * Detectar os ciclos dentro do grafo para transforma-los em objetos coloridos
         */
        internal String CreateShapes()
        {
            Shapes shapes = new Shapes();
            Shape shape = new Shape();
            ArrayList processedCurves = new ArrayList();

            Pixel lastPixel = null;
            Pixel firstPixel = null;
            Color color;
            bool hasCurve = true;
            foreach (Curve curve in curvesC)
            {

                Curve processingCurve = curve;
                color = processingCurve.color;
                if (!processedCurves.Contains(processingCurve))
                {
                    processedCurves.Add(processingCurve);
                    ArrayList curveArray = (ArrayList)processingCurve.curve;

                    firstPixel = getFirstPixel(curveArray);
                    lastPixel = getLastPixel(curveArray);
                    shape.Add(curve);
                    if (!firstPixel.Equals(lastPixel)) // se primeiro e ultimo são iguais, então o circuito já esta fechado
                    {
                        hasCurve = true;
                        while (hasCurve)
                        {

                            foreach (Curve newCurve in curvesC) // verifico todas as curvas procurando uma que comece ou termine com o ultimo pixel da pesquisada
                            {

                                if ((newCurve.color == color && newCurve != curve && !processedCurves.Contains(newCurve) )) // Precisa ser uma curva não processessada e com cor igual
                                {

                                    hasCurve = false;
                                    ArrayList newCurveArray = (ArrayList)newCurve.curve;
                                    TaggedUndirectedEdge<Pixel, EdgeTag> firstNewEdge = (TaggedUndirectedEdge<Pixel, EdgeTag>)newCurveArray[0];
                                    TaggedUndirectedEdge<Pixel, EdgeTag> lastNewEdge = (TaggedUndirectedEdge<Pixel, EdgeTag>)newCurveArray[newCurveArray.Count - 1];

                                    if (firstNewEdge.Source.Equals(lastPixel) || firstNewEdge.Target.Equals(lastPixel) || lastNewEdge.Target.Equals(lastPixel) || lastNewEdge.Source.Equals(lastPixel)) // se a curva analizada possui o primeiro ou ultimo pixel igual a um pixel do lastEdge // simplificado apenas para conter um dos pixeis da ultima aresta da curva
                                    {
                                        if (firstNewEdge.Source.Equals(lastPixel) || firstNewEdge.Target.Equals(lastPixel))
                                        {
                                            if (newCurveArray.Count == 1)
                                            {
                                                if (((TaggedUndirectedEdge<Pixel, EdgeTag>)newCurveArray[0]).Source.Equals(lastPixel))
                                                    lastPixel = ((TaggedUndirectedEdge<Pixel, EdgeTag>)newCurveArray[0]).Target;
                                                else
                                                    lastPixel = ((TaggedUndirectedEdge<Pixel, EdgeTag>)newCurveArray[0]).Source;
                                            }
                                            else lastPixel = getLastPixel(newCurveArray);
                                        }
                                        else
                                        {
                                            if (newCurveArray.Count == 1)
                                            {
                                                if (((TaggedUndirectedEdge<Pixel, EdgeTag>)newCurveArray[0]).Source.Equals(lastPixel))
                                                    lastPixel = ((TaggedUndirectedEdge<Pixel, EdgeTag>)newCurveArray[0]).Target;
                                                else
                                                    lastPixel = ((TaggedUndirectedEdge<Pixel, EdgeTag>)newCurveArray[0]).Source;
                                            }
                                            else
                                            {
                                                lastPixel = getFirstPixel(newCurveArray);
                                                newCurveArray.Reverse();
                                            }
                                        }

                                        processedCurves.Add(newCurve);
                                        if (!lastPixel.Equals(firstPixel))
                                        {
                                            shape.Add(newCurve);
                                            hasCurve = true;
                                            break;
                                        }
                                        else // terminou o grupo de curvas
                                        {
                                            shape.Add(newCurve);
                                            shapes.Add(shape);
                                            hasCurve = false;
                                        }

                                    }
                                }

                            }

                        }
                    }
                    else
                    {
                        shapes.Add(shape);

                    }
                    shape = new Shape();
                }

            }

            //remove shapes iguais de cores diferentes
            ArrayList remove = new ArrayList();

            foreach (Shape shapeItem in shapes)
            {
                foreach (Shape shapeItem2 in shapes)
                {
                    if (!remove.Contains(shapeItem) && !remove.Contains(shapeItem2) && shapeItem.getColor() != Color.Beige && shapeItem2.getColor() != Color.Beige)
                        if ( shapeItem.getColor() != shapeItem2.getColor() && shapeItem.isSameShape(shapeItem2) )
                        {
                            Color c = new Color();
                            //localiza o pixel de cor dentro do poligono
                            foreach (Pixel v in g.Vertices)
                            {
                                if (v.pixelInsidePolygon(shapeItem.ToPoints()))
                                {
                                    c = v.color;
                                    break;
                                }
                            }

                            if (shapeItem.getColor() == c)
                            {
                                remove.Add(shapeItem2);
                                break;
                            }else
                            if (shapeItem2.getColor() == c)
                            {
                                remove.Add(shapeItem);
                                break;
                            }

                        }
                }

            }

            foreach (Shape item in remove)
            {
                shapes.Remove(item);

            }

            //Ordena do objeto com maior area para os de menor area
            shapes.Sort();

            SvgVector svg = new SvgVector();
            svg.Height = Height * scale;
            svg.Width = Width * scale;
            svg.scale = 1;

            return svg.NewImage(g, shapes, "NewImage.svg");
        }