コード例 #1
0
 public EffectBarRenderer(Bar bar, IEffectBarRendererInfo info)
     : base(bar)
 {
     _info = info;
     _uniqueEffectGlyphs = new FastList<FastList<EffectGlyph>>();
     _effectGlyphs = new FastList<FastDictionary<int, EffectGlyph>>();
 }
コード例 #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DynamicEffectCompiler" /> class.
        /// </summary>
        /// <param name="services">The services.</param>
        /// <param name="effectName">Name of the effect.</param>
        /// <param name="asyncDynamicEffectCompiler">if set to <c>true</c> it can compile effect asynchronously.</param>
        /// <exception cref="System.ArgumentNullException">services
        /// or
        /// effectName</exception>
        public DynamicEffectCompiler(IServiceRegistry services, string effectName, int taskPriority = 0)
        {
            if (services == null) throw new ArgumentNullException("services");
            if (effectName == null) throw new ArgumentNullException("effectName");

            Services = services;
            this.effectName = effectName;
            this.taskPriority = taskPriority;
            EffectSystem = Services.GetSafeServiceAs<EffectSystem>();
            GraphicsDevice = Services.GetSafeServiceAs<IGraphicsDeviceService>().GraphicsDevice;
            parameterCollections = new FastList<ParameterCollection>();

            // Default behavior for fallback effect: load effect with same name but empty compiler parameters
            ComputeFallbackEffect = (dynamicEffectCompiler, type, name, parameters) =>
            {
                ParameterCollection usedParameters;
                var compilerParameters = new CompilerParameters();

                // We want high priority
                compilerParameters.TaskPriority = -1;

                var effect = dynamicEffectCompiler.EffectSystem.LoadEffect(effectName, compilerParameters, out usedParameters).WaitForResult();
                return new ComputeFallbackEffectResult(effect, usedParameters);
            };
        }
コード例 #3
0
ファイル: DebugInfo.cs プロジェクト: rizwan3d/elalang
 internal DebugInfo()
 {
     Scopes = new FastList<ScopeSym>();
     Lines = new FastList<LineSym>();
     Vars = new FastList<VarSym>();
     Functions = new FastList<FunSym>();
 }
コード例 #4
0
ファイル: Note.cs プロジェクト: CoderLine/alphaTab
        public Note()
        {
            BendPoints = new FastList<BendPoint>();
            Dynamic = DynamicValue.F;

            Accentuated = AccentuationType.None;
            Fret = int.MinValue;
            HarmonicType = HarmonicType.None;
            SlideType = SlideType.None;
            Vibrato = VibratoType.None;

            LeftHandFinger = Fingers.Unknown;
            RightHandFinger = Fingers.Unknown;

            TrillValue = -1;
            TrillSpeed = Duration.ThirtySecond;
            DurationPercent = 1;

            Octave = -1;
            Tone = -1;

            Fret = -1;
            String = -1;

            Element = -1;
            Variation = -1;
        }
コード例 #5
0
        public void ScanAll(int deltaCount, FastList<LSAgent> outputAgents,
		                      bool CheckAllegiance = false,
		                      AllegianceType allegianceType = AllegianceType.Neutral)
        {
            for (i = 0; i < deltaCount; i++) {
                tempNode = GridManager.GetNode (
                    LocatedNode.gridX + DeltaCache.CacheX[i],
                    LocatedNode.gridY + DeltaCache.CacheY[i]);

                if (tempNode != null && tempNode.LocatedAgents != null) {
                    tempBucket = tempNode.LocatedAgents;
                    for (j = 0; j < tempBucket.PeakCount; j++) {
                        if (LSUtility.GetBitTrue (tempBucket.arrayAllocation, j)) {
                            tempAgent = tempBucket.innerArray [j].Agent;
                            if (System.Object.ReferenceEquals (tempAgent, Agent) == false) {
                                if (CheckAllegiance)
                                {
                                    if (Agent.MyAgentController.DiplomacyFlags
                                        [tempAgent.MyAgentController.ControllerID] != allegianceType) continue;
                                }
                                outputAgents.Add (tempAgent);
                            }
                        }
                    }
                }
            }
        }
コード例 #6
0
        // TODO: Find a way to replug this

        /// <summary>
        /// Adds a default frustum culling for rendering only meshes that are only inside the frustum/
        /// </summary>
        /// <param name="modelRenderer">The model renderer.</param>
        /// <returns>ModelRenderer.</returns>
        //public static ModelComponentRenderer AddDefaultFrustumCulling(this ModelComponentRenderer modelRenderer)
        //{
        //    modelRenderer.UpdateMeshes = FrustumCulling;
        //    return modelRenderer;
        //}

        private static void FrustumCulling(RenderContext context, FastList<RenderMesh> meshes)
        {
            Matrix viewProjection, mat1, mat2;

            // Compute view * projection
            context.Parameters.Get(TransformationKeys.View, out mat1);
            context.Parameters.Get(TransformationKeys.Projection, out mat2);
            Matrix.Multiply(ref mat1, ref mat2, out viewProjection);

            var frustum = new BoundingFrustum(ref viewProjection);

            for (var i = 0; i < meshes.Count; ++i)
            {
                var renderMesh = meshes[i];

                // Fast AABB transform: http://zeuxcg.org/2010/10/17/aabb-from-obb-with-component-wise-abs/
                // Get world matrix
                renderMesh.Mesh.Parameters.Get(TransformationKeys.World, out mat1);

                // Compute transformed AABB (by world)
                var boundingBoxExt = new BoundingBoxExt(renderMesh.Mesh.BoundingBox);
                boundingBoxExt.Transform(mat1);

                // Perform frustum culling
                if (!frustum.Contains(ref boundingBoxExt))
                {
                    meshes.SwapRemoveAt(i--);
                }
            }
        }
コード例 #7
0
ファイル: RModel.cs プロジェクト: scotttorgeson/HeroesOfRock
        public RModel(ParameterSet parm)
        {
            ModelInfo m;
            m.modelName = parm.GetString("ModelName");
            Name = m.modelName;

            ShadowDrawLists = new FastList<RModelInstance>[Sun.NUM_CASCADES];
            for (int i = 0; i < ShadowDrawLists.Length; i++)
                ShadowDrawLists[i] = new FastList<RModelInstance>();

            if (parm.HasParm("BumpMap"))
                IsBumpMapped = true;
            if (parm.HasParm("Shininess"))
                Shininess = parm.GetFloat("Shininess");
            if (parm.HasParm("SpecularPower"))
                SpecularPower = parm.GetFloat("SpecularPower");
            if (parm.HasParm("SpecularMap"))
                IsSpecularMapped = true;
            if (parm.HasParm("CastsShadows"))
                CastsShadows = parm.GetBool("CastsShadows");
            if (parm.HasParm("ReceivesShadows"))
                ReceivesShadows = parm.GetBool("ReceivesShadows");
            if (parm.HasParm("AlphaBlend"))
                AlphaBlend = parm.GetBool("AlphaBlend");

            m.textureName = "";
            if (parm.HasParm("Texture"))
                m.textureName = parm.GetString("Texture");

            modelDictionary.Add(m, this);
            Renderer.Instance.AddRModel(this);
        }
コード例 #8
0
ファイル: CallPoint.cs プロジェクト: rizwan3d/elalang
 internal CallPoint(int modHandle, EvalStack stack, ElaValue[] locals, FastList<ElaValue[]> captures)
 {
     ModuleHandle = modHandle;
     Locals = locals;
     Captures = captures;
     Stack = stack;
 }
コード例 #9
0
ファイル: Blueprint.cs プロジェクト: wow4all/evemu_server
        /// <summary>
        /// Deserialization constructor.
        /// </summary>
        /// <param name="group">Market Group the Blueprint will be a member of.</param>
        /// <param name="src">Source serializable blueprint.</param>
        internal Blueprint(BlueprintMarketGroup group, SerializableBlueprint src)
            : base(group, src)
        {

            m_maxProductionLimit = src.MaxProductionLimit;
            m_produceItemID = src.ProduceItemID;
            m_productionTime= src.ProductionTime;
            m_productivityModifier = src.ProductivityModifier;
            m_researchCopyTime = src.ResearchCopyTime;
            m_researchMaterialTime = src.ResearchMaterialTime;
            m_researchProductivityTime = src.ResearchProductivityTime;
            m_researchTechTime = src.ResearchTechTime;
            m_techLevel = src.TechLevel;
            m_wasteFactor = src.WasteFactor;

            // Invented blueprint
            m_inventBlueprint = new FastList<int>(src.InventionTypeID != null ? src.InventionTypeID.Length : 0);
            if (src.InventionTypeID != null)
            {
                foreach (var blueprintID in src.InventionTypeID)
                {
                    m_inventBlueprint.Add(blueprintID);
                }
            }

            // Materials prerequisites
            m_materialRequirements = new FastList<StaticRequiredMaterial>(src.ReqMaterial != null ? src.ReqMaterial.Length : 0);
            if (src.ReqMaterial == null)
                return;
            
            foreach (var prereq in src.ReqMaterial)
            {
                m_materialRequirements.Add(new StaticRequiredMaterial(prereq));
            }
        }
コード例 #10
0
        /// <summary>
        /// Deserialization constructor.
        /// </summary>
        /// <param name="group">Market Group the Blueprint will be a member of.</param>
        /// <param name="src">Source serializable blueprint.</param>
        internal Blueprint(MarketGroup group, SerializableBlueprint src)
            : base(group, src)
        {
            RunsPerCopy = src.MaxProductionLimit;
            ProducesItem = StaticItems.GetItemByID(src.ProduceItemID);
            ProductionTime = src.ProductionTime;
            ResearchCopyTime = src.ResearchCopyTime;
            ResearchMaterialTime = src.ResearchMaterialTime;
            ResearchProductivityTime = src.ResearchProductivityTime;
            ResearchInventionTime = src.InventionTime;
            ReverseEngineeringTime = src.ReverseEngineeringTime;

            // Invented blueprints
            m_inventBlueprints = new Dictionary<int, double>(src.InventionTypeIDs?.Count ?? 0);
            if (src.InventionTypeIDs != null && src.InventionTypeIDs.Any())
            {
                m_inventBlueprints.AddRange(src.InventionTypeIDs);
            }

            // Materials prerequisites
            m_materialRequirements =
                new FastList<StaticRequiredMaterial>(src.ReqMaterial?.Count ?? 0);
            if (src.ReqMaterial == null)
                return;

            foreach (SerializableRequiredMaterial prereq in src.ReqMaterial)
            {
                m_materialRequirements.Add(new StaticRequiredMaterial(prereq));
            }
        }
コード例 #11
0
 public ScoreNoteChordGlyph()
     : base(0, 0)
 {
     _infos = new FastList<ScoreNoteGlyphInfo>();
     BeatEffects = new FastDictionary<string, Glyph>();
     _noteLookup = new FastDictionary<int, Glyph>();
 }
コード例 #12
0
        public int Reconstruct(AgentController agentController, byte[] source, int startIndex)
        {
            curIndex = startIndex;
            Header = BitConverter.ToUInt64 (source, curIndex);
            curIndex += 8;

            if (selectedAgentLocalIDs == null)
                selectedAgentLocalIDs = new FastList<int> (64);
            else
                selectedAgentLocalIDs.FastClear ();

            for (i = 0; i < 64; i++) {
                castedBigIndex = (ulong)1 << i;
                if ((Header & castedBigIndex) == castedBigIndex) {
                    CullGroup = source [curIndex++];
                    for (j = 0; j < 8; j++) {
                        castedSmallIndex = (byte)(1 << j);
                        if ((CullGroup & (castedSmallIndex)) == castedSmallIndex)
                        {
                            selectedAgentLocalIDs.Add (i * 8 + j);
                        }
                    }
                }
            }
            return curIndex - startIndex;
        }
コード例 #13
0
        public override void SetViews(FastList<RenderView> views)
        {
            base.SetViews(views);

            // Make sure array is big enough for all render views
            Array.Resize(ref lightShaderGroup.AmbientColor, views.Count);
        }
コード例 #14
0
ファイル: RepeatGroup.cs プロジェクト: eriser/alphaTab
 public RepeatGroup()
 {
     MasterBars = new FastList<MasterBar>();
     Openings = new FastList<MasterBar>();
     Closings = new FastList<MasterBar>();
     IsClosed = false;
 }
コード例 #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EffectReflection"/> class.
 /// </summary>
 public EffectReflection()
 {
     SamplerStates = new List<EffectSamplerStateBinding>();
     ResourceBindings = new FastList<EffectResourceBindingDescription>();
     ConstantBuffers = new List<EffectConstantBufferDescription>();
     ShaderStreamOutputDeclarations = new List<ShaderStreamOutputDeclarationEntry>();
 }
コード例 #16
0
        public OptionPopUp(string message)
            : this(message, true)
        {
            //load saved values here
            options = new FastList<OptionFunc>();
            options.Add(ChangeMusicVol);
            options.Add(ChangeFxVol);
            options.Add(ChangeGore);
            options.Add(ChangeMoreGore);
            options.Add(ChangeStrum);

            if (!Stage.Editor)
            {
                strumMode = Stage.SaveGame.getStrumMode();
                Stage.SaveGame.getGores(out gore, out moreGore);
                Stage.SaveGame.getVolumes(out musicVol, out fxVol);
            }

            origFXVol = fxVol;
            origGore = gore;
            origMoreGore = moreGore;
            origMusicVol = musicVol;
            PlayerAgent.isStrumMode = strumMode;
            origStrumMode = strumMode;
            Stage.ActiveStage.PauseGame();
        }
コード例 #17
0
ファイル: GroupedBarRenderer.cs プロジェクト: eriser/alphaTab
 public GroupedBarRenderer(Bar bar)
     : base(bar)
 {
     _preBeatGlyphs = new FastList<Glyph>();
     _voiceContainers = new FastDictionary<int, VoiceContainerGlyph>();
     _postBeatGlyphs = new FastList<Glyph>();
 }
コード例 #18
0
        public static void ProcessPacket(FastList<byte> packet)
        {
            if (packet == null || packet.Count < 4) {
                throw new System.Exception("Packet is null or not valid length");
            }
            int frameCount = BitConverter.ToInt32 (packet.innerArray, 0);
            int index = 4;

            if (FrameManager.HasFrame (frameCount) == false) {
                Frame frame = new Frame ();

                if (packet.Count > 4) {
                    RecordedBytes.AddRange (BitConverter.GetBytes ((ushort)packet.Count));
                    RecordedBytes.AddRange (packet);
                    while (index < packet.Count) {
                        Command com = new Command ();
                        index += com.Reconstruct (packet.innerArray, index);
                        frame.AddCommand (com);
                    }
                    if (frameCount > LastCommandedFrameCount) {
                        LastCommandedFrameCount = frameCount;
                    }
                }
                FrameManager.AddFrame (frameCount, frame);

            } else {

            }
        }
コード例 #19
0
 public void AddCommand(Command com)
 {
     if (Commands == null)
     {
         Commands = new FastList<Command>(2);
     }
     Commands.Add(com);
 }
コード例 #20
0
 public BeatContainerGlyph(Beat beat, VoiceContainerGlyph voiceContainer, bool useLayoutingInfo = false)
     : base(0, 0)
 {
     Beat = beat;
     Ties = new FastList<Glyph>();
     VoiceContainer = voiceContainer;
     UseLayoutingInfo = useLayoutingInfo;
 }
コード例 #21
0
ファイル: MoveProcessor.cs プロジェクト: ricksladkey/Spider
 public MoveProcessor(Game game)
     : base(game)
 {
     HoldingMoveStack = new FastList<Move>();
     MoveStack = new FastList<Move>();
     SpacesMoveStack = new FastList<Move>();
     Spaces = new FastList<int>();
 }
コード例 #22
0
        public virtual void SetViews(FastList<RenderView> views)
        {
            Array.Resize(ref LightRanges, views.Count);

            // Reset ranges
            for (var i = 0; i < views.Count; ++i)
                LightRanges[i] = new LightRange(0, 0);
        }
コード例 #23
0
ファイル: BeamingHelper.cs プロジェクト: CoderLine/alphaTab
        public BeamingHelper(Track track)
        {
            _track = track;

            Beats = new FastList<Beat>();
            _beatLineXPositions = new FastDictionary<int, BeatLinePositions>();
            ShortestDuration = Duration.QuadrupleWhole;
        }
コード例 #24
0
ファイル: CodeWriter.cs プロジェクト: rizwan3d/elalang
 internal CodeWriter(FastList<Op> ops, FastList<Int32> opData)
 {
     this.ops = ops;
     this.opData = opData;
     labels = new FastList<Int32>();
     fixups = new FastList<Int32>();
     locals = new FastStack<StackSize>();
 }
コード例 #25
0
 public void AddCommands(Command[] coms, int startIndex, int count)
 {
     if (Commands == null)
     {
         Commands = new FastList<Command> ();
     }
     Commands.AddRange (coms,startIndex,count);
 }
コード例 #26
0
        /// <summary>
        /// Base constructor for default items.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        internal Item(int id, string name)
        {
            ID = id;
            Name = name;
            Description = "No description.";

            m_prerequisites = new FastList<StaticSkillLevel>(0);
        }
コード例 #27
0
 public TabNoteChordGlyph(float x, float y, bool isGrace)
     : base(x, y)
 {
     _isGrace = isGrace;
     _notes = new FastList<NoteNumberGlyph>();
     BeatEffects = new FastDictionary<string, Glyph>();
     _noteLookup = new FastDictionary<int, NoteNumberGlyph>();
 }
コード例 #28
0
ファイル: Item.cs プロジェクト: wow4all/evemu_server
        /// <summary>
        /// Base constructor for default items.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        internal Item(int id, string name)
        {
            m_id = id;
            m_name = name;
            m_description = "No description.";

            m_reprocessing = new FastList<Material>(0);
            m_prerequisites = new FastList<StaticSkillLevel>(0);
        }
コード例 #29
0
ファイル: BoundsLookup.cs プロジェクト: CoderLine/alphaTab
        public object ToJson()
        {
            var json = Std.NewObject();

            var staveGroups = new FastList<StaveGroupBounds>();
            json.StaveGroups = staveGroups;

            foreach (var group in StaveGroups)
            {
                StaveGroupBounds g = Std.NewObject();
                g.VisualBounds = BoundsToJson(group.VisualBounds);
                g.RealBounds = BoundsToJson(group.RealBounds);
                g.Bars = new FastList<MasterBarBounds>();

                foreach (var masterBar in group.Bars)
                {
                    MasterBarBounds mb = Std.NewObject();
                    mb.VisualBounds = BoundsToJson(masterBar.VisualBounds);
                    mb.RealBounds = BoundsToJson(masterBar.RealBounds);

                    mb.Bars = new FastList<BarBounds>();

                    foreach (var bar in masterBar.Bars)
                    {
                        BarBounds b = Std.NewObject();
                        b.VisualBounds = BoundsToJson(bar.VisualBounds);
                        b.RealBounds = BoundsToJson(bar.RealBounds);

                        b.Beats = new FastList<BeatBounds>();

                        foreach (var beat in bar.Beats)
                        {
                            var bb = Std.NewObject();

                            bb.VisualBounds = BoundsToJson(beat.VisualBounds);
                            bb.RealBounds = BoundsToJson(beat.RealBounds);
                            bb.BeatIndex = beat.Beat.Index;
                            bb.VoiceIndex = beat.Beat.Voice.Index;
                            bb.BarIndex = beat.Beat.Voice.Bar.Index;
                            bb.StaffIndex = beat.Beat.Voice.Bar.Staff.Index;
                            bb.TrackIndex = beat.Beat.Voice.Bar.Staff.Track.Index;

                            b.Beats.Add(bb);
                        }

                        mb.Bars.Add(b);
                    }

                    g.Bars.Add(mb);
                }

                staveGroups.Add(g);
            }

            return json;
        }
コード例 #30
0
ファイル: Track.cs プロジェクト: eriser/alphaTab
 public Track()
 {
     Name = "";
     ShortName = "";
     Tuning = new int[0];
     Bars = new FastList<Bar>();
     Chords = new FastDictionary<string, Chord>();
     PlaybackInfo = new PlaybackInformation();
     Color = new Color(200, 0, 0);
 }
コード例 #31
0
ファイル: Dispatcher.cs プロジェクト: vvvv/stride
 public static void ForEach <T>([NotNull] FastList <T> collection, [Pooled] ValueAction <T> action)
 {
     For(0, collection.Count, i => action(ref collection.Items[i]));
 }
コード例 #32
0
        /**
         * Workaround a scenario where there is another building closer to the offer's position
         * that doesn't belong to the same district, causing the offer never to be handled.
         */
        internal static bool delegateToAnotherBuilding(ushort buildingID, ref Building data,
                                                       TransferManager.TransferReason material, TransferManager.TransferOffer offer)
        {
            Utils.LogBuilding(" - Searching another building to delegate");

            Type            aiType          = data.Info.m_buildingAI.GetType().BaseType;
            BuildingManager buildingManager = Singleton <BuildingManager> .instance;

            ItemClass.Service service   = data.Info.GetService();
            FastList <ushort> buildings = buildingManager.GetServiceBuildings(service);

            bool delegateMode = (material == TransferManager.TransferReason.Fire ||
                                 material == TransferManager.TransferReason.Crime ||
                                 material == TransferManager.TransferReason.Dead ||
                                 material == TransferManager.TransferReason.Fire2 ||
                                 material == TransferManager.TransferReason.Garbage ||
                                 material == TransferManager.TransferReason.RoadMaintenance ||
                                 material == TransferManager.TransferReason.Snow ||
                                 material == TransferManager.TransferReason.Sick ||
                                 material == TransferManager.TransferReason.Sick2 ||
                                 material == TransferManager.TransferReason.Taxi);

            if (buildings == null)
            {
                return(false);
            }

            for (int index = 0; index < buildings.m_size; index++)
            {
                ushort otherBuildingID = buildings.m_buffer[index];
                if (buildingID == otherBuildingID)
                {
                    continue;
                }

                Building otherBuilding = buildingManager.m_buildings.m_buffer[otherBuildingID];
                if ((otherBuilding.m_flags & Building.Flags.Active) == Building.Flags.None)
                {
                    continue;
                }
                if ((otherBuilding.m_problems & Notification.Problem.Emptying) != Notification.Problem.None)
                {
                    continue;
                }
                if ((otherBuilding.m_problems & Notification.Problem.EmptyingFinished) != Notification.Problem.None)
                {
                    continue;
                }

                BuildingAI otherBuildingAI = (BuildingAI)otherBuilding.Info.m_buildingAI;
                if (!aiType.IsAssignableFrom(otherBuildingAI.GetType()))
                {
                    continue;
                }
                if (otherBuildingAI.IsFull(otherBuildingID, ref otherBuilding))
                {
                    continue;
                }
                if (delegateMode && !hasSpareVehicles(otherBuildingID, ref otherBuilding, otherBuildingAI))
                {
                    continue;                                                                                           //target delegation does not need vehicle from target!
                }
                if (delegateMode)
                {
                    if (DistrictChecker.IsBuildingTransferAllowed(otherBuildingID, ref otherBuilding, material, offer, true))
                    {
                        // let other building handle the offer
                        Utils.LogBuilding(" - delegation success, starting transfer (origin delegated)");
                        otherBuildingAI.StartTransfer(otherBuildingID, ref otherBuilding, material, offer);
                        return(true);
                    }
                }
                else
                {
                    offer.Building = otherBuildingID;
                    offer.Position = otherBuilding.m_position;

                    if (DistrictChecker.IsBuildingTransferAllowed(buildingID, ref data, material, offer, true))
                    {
                        // change the target to other building
                        Utils.LogBuilding(" - delegation success, starting transfer (target changed)");
                        data.Info.m_buildingAI.StartTransfer(buildingID, ref data, material, offer);
                        return(true);
                    }
                }
            }

            Utils.LogBuilding(" - delegation finally failed, request NOT handled!");

            return(false);
        }
コード例 #33
0
        private FastList <object> Filter(List <BuildingItem> list)
        {
            List <BuildingItem> filtered = new List <BuildingItem>();

            for (int i = 0; i < list.Count; i++)
            {
                BuildingItem item = (BuildingItem)list[i];

                // Origin
                if (m_filter.buildingOrigin == Origin.Default && item.isCustomAsset)
                {
                    continue;
                }
                if (m_filter.buildingOrigin == Origin.Custom && !item.isCustomAsset)
                {
                    continue;
                }
                if (m_filter.buildingOrigin == Origin.Cloned && !item.isCloned)
                {
                    continue;
                }

                // Status
                if (m_filter.buildingStatus == Status.Included && !item.included)
                {
                    continue;
                }
                if (m_filter.buildingStatus == Status.Excluded && item.included)
                {
                    continue;
                }

                // Level
                int level = (int)(m_filter.buildingLevel + 1);
                if (m_filter.buildingLevel != ItemClass.Level.None && item.level != level)
                {
                    continue;
                }

                // size
                Vector2 buildingSize = m_filter.buildingSize;
                if (buildingSize != Vector2.zero && item.size != buildingSize)
                {
                    continue;
                }

                // zone
                if (!m_filter.IsAllZoneSelected())
                {
                    Category category = item.category;
                    if (category == Category.None || !m_filter.IsZoneSelected(category))
                    {
                        continue;
                    }
                }
                // Name
                if (!m_filter.buildingName.IsNullOrWhiteSpace() && !item.name.ToLower().Contains(m_filter.buildingName.ToLower()))
                {
                    continue;
                }

                filtered.Add(item);
            }

            list = filtered;

            FastList <object> fastList = new FastList <object>();

            fastList.m_buffer = list.ToArray();
            fastList.m_size   = list.Count;

            return(fastList);
        }
コード例 #34
0
 public Staff()
 {
     Bars = new FastList <Bar>();
 }
コード例 #35
0
 /// <summary>
 /// Fast add all from another <see cref="FastList{T}"/>.
 /// </summary>
 /// <param name="list">The list.</param>
 public void AddAll(FastList <T> list)
 {
     EnsureCapacity(_size + list.Count);
     Array.Copy(list.Items, 0, Items, Count, list.Count);
     _size += list.Count;
 }
コード例 #36
0
            /// <summary>
            ///     To the hx mesh nodes.
            /// </summary>
            /// <param name="mesh">The mesh.</param>
            /// <param name="scene">The scene.</param>
            /// <param name="transform"></param>
            /// <returns></returns>
            /// <exception cref="System.NotSupportedException">Mesh Type {mesh.Type}</exception>
            protected virtual HxScene.SceneNode OnCreateHxMeshNode(MeshInfo mesh, HelixInternalScene scene, Matrix transform)
            {
                switch (mesh.Type)
                {
                case PrimitiveType.Triangle:
                    var material = scene.Materials[mesh.MaterialIndex];
                    var cullMode = material.Key.HasTwoSided && material.Key.IsTwoSided
                            ? CullMode.Back
                            : CullMode.None;
                    if (Configuration.ForceCullMode)
                    {
                        cullMode = Configuration.CullMode;
                    }
                    var fillMode = material.Key.HasWireFrame && material.Key.IsWireFrameEnabled
                            ? FillMode.Wireframe
                            : FillMode.Solid;

                    //Determine if has bones
                    HxScene.MeshNode mnode;
                    if (mesh.AssimpMesh.HasBones || mesh.AssimpMesh.HasMeshAnimationAttachments)
                    {
                        var mn = new HxScene.BoneSkinMeshNode();

                        //Bones
                        if (mesh.AssimpMesh.HasBones)
                        {
                            mn.Bones = mesh.AssimpMesh.Bones.Select(x => new HxAnimations.Bone()
                            {
                                Name               = x.Name,
                                BindPose           = x.OffsetMatrix.ToSharpDXMatrix(configuration.IsSourceMatrixColumnMajor).Inverted(),
                                BoneLocalTransform = Matrix.Identity,
                                InvBindPose        = x.OffsetMatrix.ToSharpDXMatrix(configuration.IsSourceMatrixColumnMajor),//Documented at https://github.com/assimp/assimp/pull/1803
                            }).ToArray();
                        }
                        else
                        {
                            mn.Geometry = mesh.Mesh;
                            mn.SetupIdentitySkeleton();
                        }

                        //Morph targets
                        if (mesh.AssimpMesh.HasMeshAnimationAttachments)
                        {
                            int attCount = mesh.AssimpMesh.MeshAnimationAttachmentCount;
                            var mtv      = new FastList <MorphTargetVertex>(attCount * mesh.AssimpMesh.VertexCount);
                            foreach (var att in mesh.AssimpMesh.MeshAnimationAttachments)
                            {
                                //NOTE: It seems some files may have invalid normal/tangent data for morph targets.
                                //May need to provide option in future to use 0 normal/tangent deltas or recalculate
                                mtv.AddRange(new MorphTargetVertex[mesh.AssimpMesh.VertexCount].Select((x, i) =>
                                                                                                       new MorphTargetVertex()
                                {
                                    deltaPosition = (att.Vertices[i] - mesh.AssimpMesh.Vertices[i]).ToSharpDXVector3(),
                                    deltaNormal   = att.HasNormals ? (att.Normals[i] - mesh.AssimpMesh.Normals[i]).ToSharpDXVector3() : Vector3.Zero,
                                    deltaTangent  = att.HasTangentBasis ? (att.Tangents[i] - mesh.AssimpMesh.Tangents[i]).ToSharpDXVector3() : Vector3.Zero
                                }));
                            }

                            mn.MorphTargetWeights = new float[attCount];
                            mn.InitializeMorphTargets(mtv.ToArray(), mesh.AssimpMesh.VertexCount);
                        }

                        mnode = mn;
                    }
                    else
                    {
                        mnode = new HxScene.MeshNode();
                    }

                    mnode.Name        = string.IsNullOrEmpty(mesh.AssimpMesh.Name) ? $"{nameof(HxScene.MeshNode)}_{Interlocked.Increment(ref MeshIndexForNoName)}" : mesh.AssimpMesh.Name;
                    mnode.Geometry    = mesh.Mesh;
                    mnode.Material    = material.Value;
                    mnode.ModelMatrix = transform;
                    mnode.CullMode    = cullMode;
                    mnode.FillMode    = fillMode;
                    return(mnode);

                case PrimitiveType.Line:
                    var lnode = new HxScene.LineNode
                    {
                        Name = string.IsNullOrEmpty(mesh.AssimpMesh.Name)
                                ? $"{nameof(HxScene.LineNode)}_{Interlocked.Increment(ref MeshIndexForNoName)}"
                                : mesh.AssimpMesh.Name,
                        Geometry    = mesh.Mesh,
                        ModelMatrix = transform
                    };
                    var lmaterial = new LineMaterialCore();     //Must create separate line material
                    lnode.Material = lmaterial;
                    var ml = scene.Materials[mesh.MaterialIndex].Value;
                    if (ml is DiffuseMaterialCore diffuse)
                    {
                        lmaterial.LineColor = diffuse.DiffuseColor;
                    }
                    return(lnode);

                case PrimitiveType.Point:
                    var pnode = new HxScene.PointNode
                    {
                        Name = string.IsNullOrEmpty(mesh.AssimpMesh.Name)
                                ? $"{nameof(HxScene.PointNode)}_{Interlocked.Increment(ref MeshIndexForNoName)}"
                                : mesh.AssimpMesh.Name,
                        Geometry    = mesh.Mesh,
                        ModelMatrix = transform
                    };
                    var pmaterial = new PointMaterialCore();     //Must create separate point material
                    pnode.Material = pmaterial;
                    var pm = scene.Materials[mesh.MaterialIndex].Value;
                    if (pm is DiffuseMaterialCore diffuse1)
                    {
                        pmaterial.PointColor = diffuse1.DiffuseColor;
                    }
                    return(pnode);

                default:
                    throw new NotSupportedException($"Mesh Type {mesh.Type} does not supported");
                }
            }
コード例 #37
0
 public StaveTrackGroup(StaveGroup staveGroup, Track track)
 {
     StaveGroup = staveGroup;
     Track      = track;
     Staves     = new FastList <Staff>();
 }
コード例 #38
0
        public RenderWindow(CurrentRendererPointer renderer, MidiFile midi, RenderSettings settings) : base(16, 9, new GraphicsMode(new ColorFormat(8, 8, 8, 8)), "Render", GameWindowFlags.Default, DisplayDevice.Default)
        {
            Width    = (int)(DisplayDevice.Default.Width / 1.5);
            Height   = (int)((double)Width / settings.width * settings.height);
            Location = new Point((DisplayDevice.Default.Width - Width) / 2, (DisplayDevice.Default.Height - Height) / 2);
            //textEngine = new GLTextEngine();
            render        = renderer;
            this.settings = settings;
            lastTempo     = midi.zerothTempo;
            lock (render)
            {
                render.renderer.Tempo = 60000000.0 / midi.zerothTempo;
                midiTime = -render.renderer.NoteScreenTime;
                if (settings.timeBasedNotes)
                {
                    tempoFrameStep = 1000.0 / settings.fps;
                }
                else
                {
                    tempoFrameStep = ((double)midi.division / lastTempo) * (1000000 / settings.fps);
                }
                midiTime -= tempoFrameStep * settings.renderSecondsDelay * settings.fps;
            }

            globalDisplayNotes   = midi.globalDisplayNotes;
            globalTempoEvents    = midi.globalTempoEvents;
            globalColorEvents    = midi.globalColorEvents;
            globalPlaybackEvents = midi.globalPlaybackEvents;
            this.midi            = midi;
            if (settings.ffRender)
            {
                pixels      = new byte[settings.width * settings.height * 4 / settings.downscale / settings.downscale];
                ffmpegvideo = startNewFF(settings.ffPath);
                if (settings.ffRenderMask)
                {
                    pixelsmask = new byte[settings.width * settings.height * 4 / settings.downscale / settings.downscale];
                    ffmpegmask = startNewFF(settings.ffMaskPath);
                }
            }

            finalCompositeBuff = new GLPostbuffer(settings.width, settings.height);
            ffmpegOutputBuff   = new GLPostbuffer(settings.width / settings.downscale, settings.height / settings.downscale);
            downscaleBuff      = new GLPostbuffer(settings.width / settings.downscale, settings.height / settings.downscale);

            GL.GenBuffers(1, out screenQuadBuffer);
            GL.GenBuffers(1, out screenQuadIndexBuffer);

            GL.BindBuffer(BufferTarget.ArrayBuffer, screenQuadBuffer);
            GL.BufferData(
                BufferTarget.ArrayBuffer,
                (IntPtr)(screenQuadArray.Length * 8),
                screenQuadArray,
                BufferUsageHint.StaticDraw);

            GL.BindBuffer(BufferTarget.ElementArrayBuffer, screenQuadIndexBuffer);
            GL.BufferData(
                BufferTarget.ElementArrayBuffer,
                (IntPtr)(screenQuadArrayIndex.Length * 4),
                screenQuadArrayIndex,
                BufferUsageHint.StaticDraw);

            postShader          = MakeShader(postShaderVert, postShaderFrag);
            postShaderFlip      = MakeShader(postShaderFlipVert, postShaderFrag);
            postShaderMask      = MakeShader(postShaderVert, postShaderFragAlphaMask);
            postShaderMaskColor = MakeShader(postShaderVert, postShaderFragAlphaMaskColor);
            postShaderDownscale = MakeShader(postShaderVert, postShaderFragDownscale);
            postShaderBlackFill = MakeShader(postShaderVert, postShaderFragBlackFill);

            uDownscaleRes = GL.GetUniformLocation(postShaderDownscale, "res");
            uDownscaleFac = GL.GetUniformLocation(postShaderDownscale, "factor");
        }
コード例 #39
0
        protected override void OnRenderFrame(FrameEventArgs e)
        {
            Task.Factory.StartNew(() => PlaybackLoop(), TaskCreationOptions.LongRunning);
            SpinWait.SpinUntil(() => playbackLoopStarted);
            Stopwatch watch = new Stopwatch();

            watch.Start();
            if (!settings.timeBasedNotes)
            {
                tempoFrameStep = ((double)midi.division / lastTempo) * (1000000.0 / settings.fps);
            }
            lock (render)
            {
                lastDeltaTimeOnScreen       = render.renderer.NoteScreenTime;
                render.renderer.CurrentMidi = midi.info;
            }
            int  noNoteFrames  = 0;
            long lastNC        = 0;
            bool firstRenderer = true;

            frameStartTime = DateTime.Now.Ticks;
            if (settings.timeBasedNotes)
            {
                microsecondsPerTick = 10000;
            }
            else
            {
                microsecondsPerTick = (long)((double)lastTempo / midi.division * 10);
            }
            while (settings.running && (noNoteFrames < settings.fps * 5 || midi.unendedTracks != 0))
            {
                if (!settings.Paused || settings.forceReRender)
                {
                    if (settings.lastyBGChangeTime != lastBGChangeTime)
                    {
                        if (settings.BGImage == null)
                        {
                            if (bgTexID != -1)
                            {
                                GL.DeleteTexture(bgTexID);
                            }
                            bgTexID = -1;
                        }
                        else
                        {
                            if (bgTexID == -1)
                            {
                                bgTexID = GL.GenTexture();
                            }
                            loadImage(settings.BGImage, bgTexID, false, true);
                        }
                    }

                    lock (render)
                    {
                        try
                        {
                            if (render.disposeQueue.Count != 0)
                            {
                                try
                                {
                                    while (true)
                                    {
                                        var r = render.disposeQueue.Dequeue();
                                        if (r.Initialized)
                                        {
                                            try
                                            {
                                                r.Dispose();
                                            }
                                            catch { }
                                            GC.Collect();
                                        }
                                    }
                                }
                                catch (InvalidOperationException) { }
                            }
                            if (!render.renderer.Initialized)
                            {
                                render.renderer.Init();
                                render.renderer.NoteColors = midi.tracks.Select(t => t.trkColors).ToArray();
                                render.renderer.ReloadTrackColors();
                                if (firstRenderer)
                                {
                                    firstRenderer = false;
                                    midi.SetZeroColors();
                                }
                                render.renderer.CurrentMidi = midi.info;
                                lock (globalDisplayNotes)
                                {
                                    foreach (Note n in globalDisplayNotes)
                                    {
                                        n.meta = null;
                                    }
                                }
                            }
                            render.renderer.Tempo = 60000000.0 / lastTempo;
                            lastDeltaTimeOnScreen = render.renderer.NoteScreenTime;
                            if (settings.timeBasedNotes)
                            {
                                SpinWait.SpinUntil(() => (midi.currentFlexSyncTime > midiTime + lastDeltaTimeOnScreen + tempoFrameStep * settings.tempoMultiplier || midi.unendedTracks == 0) || !settings.running);
                            }
                            else
                            {
                                SpinWait.SpinUntil(() => (midi.currentSyncTime > midiTime + lastDeltaTimeOnScreen + tempoFrameStep * settings.tempoMultiplier || midi.unendedTracks == 0) || !settings.running);
                            }
                            if (!settings.running)
                            {
                                break;
                            }

                            render.renderer.RenderFrame(globalDisplayNotes, midiTime, finalCompositeBuff.BufferID);
                            lastNC = render.renderer.LastNoteCount;
                            if (lastNC == 0 && midi.unendedTracks == 0)
                            {
                                noNoteFrames++;
                            }
                            else
                            {
                                noNoteFrames = 0;
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("The renderer has crashed\n" + ex.Message + "\n" + ex.StackTrace);
                            break;
                        }
                    }
                }
                double mv = 1;
                if (settings.realtimePlayback)
                {
                    mv = (DateTime.Now.Ticks - frameStartTime) / microsecondsPerTick / tempoFrameStep;
                    if (mv > settings.fps / 4)
                    {
                        mv = settings.fps / 4;
                    }
                }
                lastMV = mv;
                if (!settings.Paused)
                {
                    lock (globalTempoEvents)
                    {
                        while (globalTempoEvents.First != null && midiTime + (tempoFrameStep * mv * settings.tempoMultiplier) > globalTempoEvents.First.pos)
                        {
                            var t = globalTempoEvents.Pop();
                            if (t.tempo == 0)
                            {
                                Console.WriteLine("Zero tempo event encountered, ignoring");
                                continue;
                            }
                            var _t = ((t.pos) - midiTime) / (tempoFrameStep * mv * settings.tempoMultiplier);
                            mv *= 1 - _t;
                            if (!settings.timeBasedNotes)
                            {
                                tempoFrameStep = ((double)midi.division / t.tempo) * (1000000.0 / settings.fps);
                            }
                            lastTempo = t.tempo;
                            midiTime  = t.pos;
                        }
                    }
                    midiTime += mv * tempoFrameStep * settings.tempoMultiplier;
                }
                frameStartTime = DateTime.Now.Ticks;
                if (settings.timeBasedNotes)
                {
                    microsecondsPerTick = 10000;
                }
                else
                {
                    microsecondsPerTick = (long)(lastTempo / midi.division * 10);
                }

                while (globalColorEvents.First != null && globalColorEvents.First.pos < midiTime)
                {
                    var c     = globalColorEvents.Pop();
                    var track = c.track;
                    if (!settings.ignoreColorEvents)
                    {
                        if (c.channel == 0x7F)
                        {
                            for (int i = 0; i < 16; i++)
                            {
                                c.track.trkColors[i].left      = c.col1;
                                c.track.trkColors[i].right     = c.col2;
                                c.track.trkColors[i].isDefault = false;
                            }
                        }
                        else
                        {
                            c.track.trkColors[c.channel].left      = c.col1;
                            c.track.trkColors[c.channel].right     = c.col2;
                            c.track.trkColors[c.channel].isDefault = false;
                        }
                    }
                }

                downscaleBuff.BindBuffer();
                GL.Clear(ClearBufferMask.ColorBufferBit);
                GL.Viewport(0, 0, settings.width / settings.downscale, settings.height / settings.downscale);
                if (bgTexID != -1)
                {
                    GL.UseProgram(postShaderFlip);
                    GL.BindTexture(TextureTarget.Texture2D, bgTexID);
                    DrawScreenQuad();
                }

                if (settings.downscale > 1)
                {
                    GL.UseProgram(postShaderDownscale);
                    GL.Uniform1(uDownscaleFac, (int)settings.downscale);
                    GL.Uniform2(uDownscaleRes, new Vector2(settings.width / settings.downscale, settings.height / settings.downscale));
                }
                else
                {
                    GL.UseProgram(postShader);
                }

                finalCompositeBuff.BindTexture();
                DrawScreenQuad();

                if (settings.ffRender)
                {
                    if (!settings.ffRenderMask)
                    {
                        GL.UseProgram(postShader);
                    }
                    else
                    {
                        GL.UseProgram(postShaderMaskColor);
                    }
                    finalCompositeBuff.BindTexture();
                    ffmpegOutputBuff.BindBuffer();
                    GL.Clear(ClearBufferMask.ColorBufferBit);
                    GL.Viewport(0, 0, settings.width / settings.downscale, settings.height / settings.downscale);
                    downscaleBuff.BindTexture();
                    DrawScreenQuad();
                    IntPtr unmanagedPointer = Marshal.AllocHGlobal(pixels.Length);
                    GL.ReadPixels(0, 0, settings.width / settings.downscale, settings.height / settings.downscale, PixelFormat.Bgra, PixelType.UnsignedByte, unmanagedPointer);
                    Marshal.Copy(unmanagedPointer, pixels, 0, pixels.Length);

                    if (lastRenderPush != null)
                    {
                        lastRenderPush.GetAwaiter().GetResult();
                    }
                    lastRenderPush = Task.Run(() =>
                    {
                        ffmpegvideo.StandardInput.BaseStream.Write(pixels, 0, pixels.Length);
                    });
                    Marshal.FreeHGlobal(unmanagedPointer);

                    if (settings.ffRenderMask)
                    {
                        if (lastRenderPushMask != null)
                        {
                            lastRenderPushMask.GetAwaiter().GetResult();
                        }
                        GL.UseProgram(postShaderMask);
                        ffmpegOutputBuff.BindBuffer();
                        GL.Clear(ClearBufferMask.ColorBufferBit);
                        GL.Viewport(0, 0, settings.width / settings.downscale, settings.height / settings.downscale);
                        downscaleBuff.BindTexture();
                        DrawScreenQuad();
                        unmanagedPointer = Marshal.AllocHGlobal(pixelsmask.Length);
                        GL.ReadPixels(0, 0, settings.width / settings.downscale, settings.height / settings.downscale, PixelFormat.Bgra, PixelType.UnsignedByte, unmanagedPointer);
                        Marshal.Copy(unmanagedPointer, pixelsmask, 0, pixelsmask.Length);

                        if (lastRenderPush != null)
                        {
                            lastRenderPush.GetAwaiter().GetResult();
                        }
                        lastRenderPush = Task.Run(() =>
                        {
                            ffmpegmask.StandardInput.BaseStream.Write(pixelsmask, 0, pixelsmask.Length);
                        });
                        Marshal.FreeHGlobal(unmanagedPointer);
                    }
                }

                GLPostbuffer.UnbindBuffers();
                GL.Clear(ClearBufferMask.ColorBufferBit);
                GL.UseProgram(postShaderBlackFill);
                DrawScreenQuad();
                GL.UseProgram(postShader);
                GL.Viewport(0, 0, Width, Height);
                downscaleBuff.BindTexture();
                DrawScreenQuad();
                GLPostbuffer.UnbindTextures();
                if (settings.ffRender)
                {
                    VSync = VSyncMode.Off;
                }
                else if (settings.vsync)
                {
                    VSync = VSyncMode.On;
                }
                else
                {
                    VSync = VSyncMode.Off;
                }
                try
                {
                    SwapBuffers();
                }
                catch
                {
                    break;
                }
                ProcessEvents();
                double fr = 10000000.0 / watch.ElapsedTicks;
                settings.liveFps = (settings.liveFps * 2 + fr) / 3;
                watch.Reset();
                watch.Start();
            }
            Console.WriteLine("Left render loop");
            settings.running = false;
            if (settings.ffRender)
            {
                if (lastRenderPush != null)
                {
                    lastRenderPush.GetAwaiter().GetResult();
                }
                ffmpegvideo.StandardInput.Close();
                ffmpegvideo.Close();
                if (settings.ffRenderMask)
                {
                    if (lastRenderPushMask != null)
                    {
                        lastRenderPushMask.GetAwaiter().GetResult();
                    }
                    ffmpegmask.StandardInput.Close();
                    ffmpegmask.Close();
                }
            }
            Console.WriteLine("Disposing current renderer");
            try
            {
                render.renderer.Dispose();
            }
            catch { }
            try
            {
                Console.WriteLine("Disposing of other renderers");
                while (render.disposeQueue.Count != 0)
                {
                    var r = render.disposeQueue.Dequeue();
                    try
                    {
                        if (r.Initialized)
                        {
                            r.Dispose();
                        }
                    }
                    catch { }
                }
            }
            catch (InvalidOperationException) { }
            Console.WriteLine("Disposed of renderers");

            globalDisplayNotes = null;
            globalTempoEvents  = null;
            globalColorEvents  = null;
            pixels             = null;
            pixelsmask         = null;
            if (settings.ffRender)
            {
                ffmpegvideo.Dispose();
                if (settings.ffRenderMask)
                {
                    ffmpegmask.Dispose();
                }
            }
            ffmpegvideo = null;
            ffmpegmask  = null;


            finalCompositeBuff.Dispose();
            ffmpegOutputBuff.Dispose();
            downscaleBuff.Dispose();
            finalCompositeBuff = null;
            ffmpegOutputBuff   = null;
            downscaleBuff      = null;

            GL.DeleteBuffers(2, new int[] { screenQuadBuffer, screenQuadIndexBuffer });

            GL.DeleteProgram(postShader);
            GL.DeleteProgram(postShaderMask);
            GL.DeleteProgram(postShaderMaskColor);
            GL.DeleteProgram(postShaderDownscale);

            midi   = null;
            render = null;
            Console.WriteLine("Closing window");

            this.Close();
        }
コード例 #40
0
 public Score()
 {
     MasterBars          = new FastList <MasterBar>();
     Tracks              = new FastList <Track>();
     _currentRepeatGroup = new RepeatGroup();
 }
コード例 #41
0
 public MidiTickLookup()
 {
     MasterBars      = new FastList <MasterBarTickLookup>();
     MasterBarLookup = new FastDictionary <int, MasterBarTickLookup>();
 }
コード例 #42
0
ファイル: LightProbeRenderer.cs プロジェクト: vvvv/stride
        public override void SetViews(FastList <RenderView> views)
        {
            base.SetViews(views);

            lightprobeGroup.SetViews(views);
        }
コード例 #43
0
        public void TestWildcards()
        {
            var wc = new WildcardMatcher("ab*");

            Assert.IsTrue(wc.Matches("ab"));
            Assert.IsTrue(wc.Matches("abc"));
            Assert.IsTrue(wc.Matches("abcdefgh"));
            Assert.IsFalse(wc.Matches("ac"));
            Assert.IsFalse(wc.Matches("acb"));
            Assert.IsFalse(wc.Matches("xab"));
            Assert.IsFalse(wc.Matches("xabx"));
            Assert.IsFalse(wc.Matches(""));

            wc = new WildcardMatcher("*ab");
            Assert.IsTrue(wc.Matches("ab"));
            Assert.IsTrue(wc.Matches("xab"));
            Assert.IsTrue(wc.Matches("xyzab"));
            Assert.IsFalse(wc.Matches("abx"));
            Assert.IsFalse(wc.Matches("xxabxx"));
            Assert.IsFalse(wc.Matches(""));

            wc = new WildcardMatcher("a*b");
            Assert.IsTrue(wc.Matches("ab"));
            Assert.IsTrue(wc.Matches("axb"));
            Assert.IsTrue(wc.Matches("aaabb"));

            Assert.IsFalse(wc.Matches(""));
            Assert.IsFalse(wc.Matches("a"));
            Assert.IsFalse(wc.Matches("b"));
            Assert.IsFalse(wc.Matches("yab"));
            Assert.IsFalse(wc.Matches("yaxb"));
            Assert.IsFalse(wc.Matches("yaaabb"));
            Assert.IsFalse(wc.Matches("aby"));
            Assert.IsFalse(wc.Matches("axby"));
            Assert.IsFalse(wc.Matches("aaabby"));

            wc = new WildcardMatcher("years?ago");
            Assert.IsTrue(wc.Matches("years1ago"));
            Assert.IsTrue(wc.Matches("yearsXago"));
            Assert.IsTrue(wc.Matches("years?ago"));
            Assert.IsTrue(wc.Matches("yearsaago"));
            Assert.IsTrue(wc.Matches("yearssago"));
            Assert.IsFalse(wc.Matches(""));
            Assert.IsFalse(wc.Matches("yearsago"));
            Assert.IsFalse(wc.Matches("yearsXXXago"));
            Assert.IsFalse(wc.Matches("yearsago"));
            Assert.IsFalse(wc.Matches(null));
            Assert.IsFalse(wc.Matches("yyyyyXago"));

            wc = new WildcardMatcher("*hello*");
            Assert.IsTrue(wc.Matches("1hello2"));
            Assert.IsTrue(wc.Matches("asdfhelloasdf"));
            Assert.IsTrue(wc.Matches("helloXxx"));
            Assert.IsTrue(wc.Matches("Xxxhello"));
            Assert.IsTrue(wc.Matches("hello"));
            Assert.IsFalse(wc.Matches("hell"));
            Assert.IsFalse(wc.Matches("hellXo"));
            Assert.IsFalse(wc.Matches("111hellXo111"));
            Assert.IsFalse(wc.Matches("111hell111o"));

            // The tests below are borrowed from
            // from https://bitbucket.org/hasullivan/fast-wildcard-matching-testing/src/master/WildCardTesting/Program.cs
            // by H.A. Sullivan

            var texts    = new FastList <string>(64);
            var filters  = new FastList <string>(64);
            var expected = new FastList <bool>(64);

            texts.Add("abcccd");
            filters.Add("*ccd");
            expected.Add(true);

            texts.Add("adacccdcccd");
            filters.Add("*ccd");
            expected.Add(true);

            texts.Add("mississipissippi");
            filters.Add("*issip*ss*");
            expected.Add(true);

            texts.Add("mississipissippi");
            filters.Add("*mi*issip*ss*");
            expected.Add(true);

            texts.Add("xxxxzzzzzzzzyf");
            filters.Add("xxxx*zzy*fffff");
            expected.Add(false);

            texts.Add("xxxxzzzzzzzzyf");
            filters.Add("xxxx*zzy*f");
            expected.Add(true);

            texts.Add("xyxyxyzyxyz");
            filters.Add("xy*z*xyz");
            expected.Add(true);

            texts.Add("mississippi");
            filters.Add("*sip*");
            expected.Add(true);

            texts.Add("xyxyxyxyz");
            filters.Add("xy*xyz");
            expected.Add(true);

            texts.Add("mississippi");
            filters.Add("mi*sip*");
            expected.Add(true);

            texts.Add("ababac");
            filters.Add("*abac*");
            expected.Add(true);

            texts.Add("ababac");
            filters.Add("*abac");
            expected.Add(true);

            texts.Add("aaazz");
            filters.Add("a*zz*");
            expected.Add(true);

            texts.Add("a12b12");
            filters.Add("*12*23");
            expected.Add(false);

            texts.Add("a12b12");
            filters.Add("a12b");
            expected.Add(false);

            texts.Add("a12b12");
            filters.Add("*12*12*");
            expected.Add(true);

            texts.Add("XYXYXYZYXYz");
            filters.Add("XY*Z*XYz");
            expected.Add(true);

            texts.Add("missisSIPpi");
            filters.Add("*SIP*");
            expected.Add(true);

            texts.Add("mississipPI");
            filters.Add("*issip*PI");
            expected.Add(true);

            texts.Add("xyxyxyxyz");
            filters.Add("xy*xyz");
            expected.Add(true);

            texts.Add("miSsissippi");
            filters.Add("mi*sip*");
            expected.Add(true);

            texts.Add("miSsissippi");
            filters.Add("mi*Sip*");
            expected.Add(false);

            texts.Add("abAbac");
            filters.Add("Abac*");
            expected.Add(false);

            texts.Add("abAbac");
            filters.Add("*Abac*");
            expected.Add(true);

            texts.Add("aAazz");
            filters.Add("a*zz*");
            expected.Add(true);

            texts.Add("A12b12");
            filters.Add("*12*23");
            expected.Add(false);

            texts.Add("a12B12");
            filters.Add("*12*12*");
            expected.Add(true);

            texts.Add("oWn");
            filters.Add("*oWn*");
            expected.Add(true);

            texts.Add("bLah");
            filters.Add("bLah");
            expected.Add(true);

            texts.Add("bLah");
            filters.Add("bLaH");
            expected.Add(false);

            texts.Add("a");
            filters.Add("*?");
            expected.Add(true);

            texts.Add("ab");
            filters.Add("*?");
            expected.Add(true);

            texts.Add("abc");
            filters.Add("*?");
            expected.Add(true);

            texts.Add("a");
            filters.Add("??");
            expected.Add(false);

            texts.Add("ab");
            filters.Add("?*?");
            expected.Add(true);

            texts.Add("ab");
            filters.Add("*?*?*");
            expected.Add(true);

            texts.Add("abc");
            filters.Add("?**?*?");
            expected.Add(true);

            texts.Add("abc");
            filters.Add("?**?*&?");
            expected.Add(false);

            texts.Add("abc");
            filters.Add("***&*");
            expected.Add(false);

            texts.Add("abcd");
            filters.Add("?b*??");
            expected.Add(true);

            texts.Add("abcd");
            filters.Add("?a*??");
            expected.Add(false);

            texts.Add("abcd");
            filters.Add("?**?c?");
            expected.Add(true);

            texts.Add("abcd");
            filters.Add("?**?d?");
            expected.Add(false);

            texts.Add("abcde");
            filters.Add("?*b*?*d*?");
            expected.Add(true);

            texts.Add("bLah");
            filters.Add("bL?h");
            expected.Add(true);

            texts.Add("bLaaa");
            filters.Add("bLa?");
            expected.Add(false);

            texts.Add("bLah");
            filters.Add("bLa?");
            expected.Add(true);

            texts.Add("bLaH");
            filters.Add("?Lah");
            expected.Add(false);

            texts.Add("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab");
            filters.Add("a*a*a*a*a*a*aa*aaa*a*a*b");
            expected.Add(true);

            texts.Add("abababababababababababababababababababaacacacacacacacadaeafagahaiajakalaaaaaaaaaaaaaaaaaffafagaagggagaaaaaaaab");
            filters.Add("*a*b*ba*ca*a*x*aaa*fa*ga*b*");
            expected.Add(false);

            texts.Add("aaabbaabbaab");
            filters.Add("*aabbaa*a*");
            expected.Add(true);

            texts.Add("aaaaaaaaaaaaaaaaa");
            filters.Add("*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*");
            expected.Add(true);

            texts.Add("aaaaaaaaaaaaaaaa");
            filters.Add("*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*");
            expected.Add(false);

            texts.Add("abc");
            filters.Add("********a********b********c********");
            expected.Add(true);

            texts.Add("abc");
            filters.Add("********a********b********b********");
            expected.Add(false);

            texts.Add("abulomania");
            filters.Add("abulomania");
            expected.Add(true);

            texts.Add("accidentiality");
            filters.Add("accidentiality");
            expected.Add(true);

            texts.Add("aimworthiness");
            filters.Add("aimworthiness");
            expected.Add(true);

            texts.Add("bardocucullus");
            filters.Add("bardocucullus");
            expected.Add(true);

            texts.Add("beaned");
            filters.Add("beaned");
            expected.Add(true);

            texts.Add("bedrowse");
            filters.Add("bedrowse");
            expected.Add(true);

            texts.Add("benumbedness");
            filters.Add("benumbedness");
            expected.Add(true);

            texts.Add("booklists");
            filters.Add("booklists");
            expected.Add(true);

            texts.Add("bratchet");
            filters.Add("bratchet");
            expected.Add(true);

            texts.Add("accidentiality");
            filters.Add("accidentialities");
            expected.Add(false);

            texts.Add("aimworthiness");
            filters.Add("aimworthaness");
            expected.Add(false);

            texts.Add("dardocucullus");
            filters.Add("bardocucullus");
            expected.Add(false);

            texts.Add("beaned");
            filters.Add("beened");
            expected.Add(false);

            texts.Add("bedrowser");
            filters.Add("bedrowsen");
            expected.Add(false);

            texts.Add("benumbedness");
            filters.Add("benumbedniss");
            expected.Add(false);

            texts.Add("booklists");
            filters.Add("booklests");
            expected.Add(false);

            texts.Add("brawtcet");
            filters.Add("bratchet");
            expected.Add(false);

            texts.Add("");
            filters.Add("*");
            expected.Add(true);

            texts.Add("");
            filters.Add("?");
            expected.Add(false);

            texts.Add("Bananas");
            filters.Add("Ba*na*s");
            expected.Add(true);

            texts.Add("Something");
            filters.Add("S*eth??g");
            expected.Add(true);

            texts.Add("Something");
            filters.Add("*");
            expected.Add(true);

            texts.Add("A very long long long stringggggggg");
            filters.Add("A *?string*");
            expected.Add(true);

            texts.Add("Reg: Performance issue when using WebSphere MQ 7.1, Window server 2008 R2 and java 1.6.0_21");
            filters.Add("Reg: Performance issue when using *, Window server ???? R? and java *.*.*_*");
            expected.Add(true);

            texts.Add("Reg: Performance issue when using WebSphere MQ 7.1, Window server 2008 R2 and java 1.6.0_21");
            filters.Add("Reg: Performance* and java 1.6.0_21");
            expected.Add(true);

            texts.Add("Reg: Performance issue when using WebSphere MQ 7.1, Window server 2008 R2 and java 1.6.0_21");
            filters.Add("Reg: Performance issue when using *, Window server ???? R? and java *.*.*_");
            expected.Add(false);

            texts.Add("http://hasullivan.com/");
            filters.Add("*//hasullivan*");
            expected.Add(true);

            texts.Add("http://hasullivan.com/");
            filters.Add("*s*//hasullivan*");
            expected.Add(false);

            texts.Add("http://hasullivan.com/wp-content/uploads/2015/12/SylizedBarbariansMaleStrong.png");
            filters.Add("*//hasullivan*20??*.png");
            expected.Add(true);

            texts.Add("http://hasullivan.com/wp-content/uploads/2015/12/SylizedBarbariansFemale_Small.png");
            filters.Add("https*");
            expected.Add(false);

            texts.Add("http://hasullivan.com/wp-content/uploads/2015/12/SylizedBarbariansFemale_Small.png");
            filters.Add("http*wp-content*.???");
            expected.Add(true);

            texts.Add("https://mva.microsoft.com/training-topics/c-app-development#!jobf=Developer&lang=1033");
            filters.Add("http*microsoft.???*development*");
            expected.Add(true);

            texts.Add("https://mva.microsoft.com/en-US/training-courses/introduction-to-json-with-c-12742");
            filters.Add("*training-courses*introduction-to-*");
            expected.Add(true);

            texts.Add("https://mva.microsoft.com/en-US/training-courses/programming-in-c-jump-start-14254");
            filters.Add("https*programming*C#*");
            expected.Add(false);

            texts.Add("https://github.com/ValveSoftware/openvr");
            filters.Add("*s:*.???*vr");
            expected.Add(true);

            texts.Add("https://github.com/mono/MonoGame");
            filters.Add("*github.???????MonoGame");
            expected.Add(false);

            texts.Add("https://github.com/dotnet/roslyn");
            filters.Add("*dotnet*");
            expected.Add(true);

            texts.Add("https://github.com/dotnet/corefx");
            filters.Add("https*corefx");
            expected.Add(true);

            texts.Add("https://github.com/dotnet/cli");
            filters.Add("*clr*");
            expected.Add(false);

            texts.Add("uQ10mG10OeNbPW2X8Yet");
            filters.Add("uQ10mG10OeNdPW2X8Yet");
            expected.Add(false);

            texts.Add("CNInQBMi01ZmG3Ymb0pr");
            filters.Add("CN***??*G3*r");
            expected.Add(true);

            texts.Add("kVRglhOfmMqutfF020LW");
            filters.Add("**Ofm*M*tf?020L?");
            expected.Add(true);

            texts.Add("FIG3j1g8GSuhfyrfEgIK");
            filters.Add("*FIG??????????");
            expected.Add(false);

            texts.Add("*****@*****.**");
            filters.Add("*?@*.???");
            expected.Add(true);

            texts.Add("<h1>HTML Heading</h1>");
            filters.Add("*<h1>*</h1>*");
            expected.Add(true);

            texts.Add("Nabd");
            filters.Add("*.xxxN*");
            expected.Add(false);

            for (int i = 0; i < texts.Count; i++)
            {
                var txt    = texts[i];
                var filter = filters[i];
                var facit  = expected[i];
                var awc    = new WildcardMatcher(filter);
                Assert.AreEqual(facit, awc.Matches(txt));

                // convert to regex and test that too
                var rx = "^" + filter.Replace("?", ".{1}");
                rx  = rx.Replace("*", ".*");
                rx += "$";
                Assert.AreEqual(facit, System.Text.RegularExpressions.Regex.IsMatch(txt, rx));
            }
        }
コード例 #44
0
            private AnimationClip SubtractAnimations(AnimationClip baseAnimation, AnimationClip sourceAnimation)
            {
                if (baseAnimation == null)
                {
                    throw new ArgumentNullException("baseAnimation");
                }
                if (sourceAnimation == null)
                {
                    throw new ArgumentNullException("sourceAnimation");
                }

                var animationBlender = new AnimationBlender();

                var baseEvaluator   = animationBlender.CreateEvaluator(baseAnimation);
                var sourceEvaluator = animationBlender.CreateEvaluator(sourceAnimation);

                // Create a result animation with same channels
                var resultAnimation = new AnimationClip();

                foreach (var channel in sourceAnimation.Channels)
                {
                    // Create new instance of curve
                    var newCurve = (AnimationCurve)Activator.CreateInstance(typeof(AnimationCurve <>).MakeGenericType(channel.Value.ElementType));

                    // Quaternion curve are linear, others are cubic
                    if (newCurve.ElementType != typeof(Quaternion))
                    {
                        newCurve.InterpolationType = AnimationCurveInterpolationType.Cubic;
                    }

                    resultAnimation.AddCurve(channel.Key, newCurve);
                }

                var resultEvaluator = animationBlender.CreateEvaluator(resultAnimation);

                var animationOperations = new FastList <AnimationOperation>();

                // Perform animation blending for each frame and upload results in a new animation
                // Note that it does a simple per-frame sampling, so animation discontinuities will be lost.
                // TODO: Framerate is hardcoded at 30 FPS.
                var frameTime = TimeSpan.FromSeconds(1.0f / 30.0f);

                for (var time = TimeSpan.Zero; time < sourceAnimation.Duration + frameTime; time += frameTime)
                {
                    // Last frame, round it to end of animation
                    if (time > sourceAnimation.Duration)
                    {
                        time = sourceAnimation.Duration;
                    }

                    TimeSpan baseTime;
                    switch (AssetParameters.Mode)
                    {
                    case AdditiveAnimationBaseMode.FirstFrame:
                        baseTime = TimeSpan.Zero;
                        break;

                    case AdditiveAnimationBaseMode.Animation:
                        baseTime = TimeSpan.FromTicks(time.Ticks % baseAnimation.Duration.Ticks);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    // Generates result = source - base
                    animationOperations.Clear();
                    animationOperations.Add(AnimationOperation.NewPush(sourceEvaluator, time));
                    animationOperations.Add(AnimationOperation.NewPush(baseEvaluator, baseTime));
                    animationOperations.Add(AnimationOperation.NewBlend(AnimationBlendOperation.Subtract, 1.0f));
                    animationOperations.Add(AnimationOperation.NewPop(resultEvaluator, time));

                    // Compute
                    AnimationClipResult animationClipResult = null;
                    animationBlender.Compute(animationOperations, ref animationClipResult);
                }

                resultAnimation.Duration   = sourceAnimation.Duration;
                resultAnimation.RepeatMode = sourceAnimation.RepeatMode;

                return(resultAnimation);
            }
コード例 #45
0
ファイル: Dispatcher.cs プロジェクト: vvvv/stride
 public static void Sort <T>([NotNull] FastList <T> collection, IComparer <T> comparer)
 {
     Sort(collection.Items, 0, collection.Count, comparer);
 }
コード例 #46
0
        private void InitializeData()
        {
            Type databaseType   = Database.GetType();
            Type foundationType = typeof(LSDatabase);

            if (!databaseType.IsSubclassOf(foundationType))
            {
                throw new System.Exception("Database does not inherit from LSDatabase and cannot be edited.");
            }
            HashSet <string>    nameCollisionChecker = new HashSet <string>();
            FastList <SortInfo> sortInfos            = new FastList <SortInfo>();

            while (databaseType != foundationType)
            {
                FieldInfo[] fields = databaseType.GetFields((BindingFlags) ~0);
                for (int i = 0; i < fields.Length; i++)
                {
                    FieldInfo field      = fields [i];
                    object[]  attributes = field.GetCustomAttributes(typeof(RegisterDataAttribute), false);
                    for (int j = 0; j < attributes.Length; j++)
                    {
                        RegisterDataAttribute registerDataAttribute = attributes [j] as RegisterDataAttribute;
                        if (registerDataAttribute != null)
                        {
                            if (!field.FieldType.IsArray)
                            {
                                Debug.LogError("Serialized data field must be array");
                                continue;
                            }
                            if (!field.FieldType.GetElementType().IsSubclassOf(typeof(DataItem)))
                            {
                                Debug.LogError("Serialized data type must be derived from DataItem");
                                continue;
                            }


                            object[] sortAttributes = field.GetCustomAttributes(typeof(RegisterSortAttribute), false);
                            sortInfos.FastClear();
                            foreach (object obj in sortAttributes)
                            {
                                RegisterSortAttribute sortAtt = obj as RegisterSortAttribute;
                                if (sortAtt != null)
                                {
                                    sortInfos.Add(new SortInfo(sortAtt.Name, sortAtt.DegreeGetter));
                                }
                            }

                            DataItemInfo dataInfo = new DataItemInfo(
                                field.FieldType.GetElementType(),
                                registerDataAttribute.DataName,
                                field.Name,
                                sortInfos.ToArray()
                                );

                            if (nameCollisionChecker.Add(dataInfo.DataName) == false)
                            {
                                throw new System.Exception("Data Name collision detected for '" + dataInfo.DataName + "'.");
                            }
                            RegisterData(dataInfo);
                            break;
                        }
                    }
                }
                databaseType = databaseType.BaseType;
            }
        }
コード例 #47
0
 public virtual void SetViews(FastList <RenderView> views)
 {
 }
コード例 #48
0
ファイル: SceneInstance.cs プロジェクト: Aggror/Stride
        private void Add(Scene scene)
        {
            if (scene.Entities.Count > 0)
            {
                var entitiesToAdd = new FastList <Entity>();
                // Reverse order, we're adding and removing from the tail to
                // avoid forcing the list to move all items when removing at [0]
                for (int i = scene.Entities.Count - 1; i >= 0; i--)
                {
                    entitiesToAdd.Add(scene.Entities[i]);
                }

                scene.Entities.CollectionChanged += DealWithTempChanges;
                while (entitiesToAdd.Count > 0)
                {
                    int i      = entitiesToAdd.Count - 1;
                    var entity = entitiesToAdd[i];
                    entitiesToAdd.RemoveAt(i);
                    Add(entity);
                }
                scene.Entities.CollectionChanged -= DealWithTempChanges;

                void DealWithTempChanges(object sender, TrackingCollectionChangedEventArgs e)
                {
                    Entity entity = (Entity)e.Item;

                    if (e.Action == NotifyCollectionChangedAction.Remove)
                    {
                        if (entitiesToAdd.Remove(entity) == false)
                        {
                            Remove(entity);
                        }
                    }
                    else if (e.Action == NotifyCollectionChangedAction.Add)
                    {
                        entitiesToAdd.Add(entity);
                    }
                }
            }

            if (scene.Children.Count > 0)
            {
                var scenesToAdd = new FastList <Scene>();
                // Reverse order, we're adding and removing from the tail to
                // avoid forcing the list to move all items when removing at [0]
                for (int i = scene.Children.Count - 1; i >= 0; i--)
                {
                    scenesToAdd.Add(scene.Children[i]);
                }

                scene.Children.CollectionChanged += DealWithTempChanges;
                while (scenesToAdd.Count > 0)
                {
                    int i      = scenesToAdd.Count - 1;
                    var entity = scenesToAdd[i];
                    scenesToAdd.RemoveAt(i);
                    Add(entity);
                }
                scene.Children.CollectionChanged -= DealWithTempChanges;

                void DealWithTempChanges(object sender, TrackingCollectionChangedEventArgs e)
                {
                    Scene subScene = (Scene)e.Item;

                    if (e.Action == NotifyCollectionChangedAction.Remove)
                    {
                        if (scenesToAdd.Remove(subScene) == false)
                        {
                            Remove(subScene);
                        }
                    }
                    else if (e.Action == NotifyCollectionChangedAction.Add)
                    {
                        scenesToAdd.Add(subScene);
                    }
                }
            }

            // Listen to future changes in entities and child scenes
            scene.Children.CollectionChanged += Children_CollectionChanged;
            scene.Entities.CollectionChanged += Entities_CollectionChanged;
        }
コード例 #49
0
 public Voice()
 {
     Beats = new FastList <Beat>();
 }
コード例 #50
0
 /// <summary>
 /// Fills the parameter collections used by this instance.
 /// </summary>
 /// <param name="parameterCollections">The parameter collections.</param>
 public abstract void FillParameterCollections(FastList <ParameterCollection> parameterCollections);
コード例 #51
0
        private void BuildBoundingsLookup(float cx, float cy)
        {
            if (Layout.Renderer.BoundsLookup.IsFinished)
            {
                return;
            }
            if (_firstStaffInAccolade == null || _lastStaffInAccolade == null)
            {
                return;
            }

            var visualTop    = cy + Y + _firstStaffInAccolade.Y;
            var visualBottom = cy + Y + _lastStaffInAccolade.Y + _lastStaffInAccolade.Height;
            var realTop      = cy + Y + _allStaves[0].Y;
            var realBottom   = cy + Y + _allStaves[_allStaves.Count - 1].Y + _allStaves[_allStaves.Count - 1].Height;

            var visualHeight = visualBottom - visualTop;
            var realHeight   = realBottom - realTop;

            var x = X + _firstStaffInAccolade.X;

            var staveGroupBounds = new StaveGroupBounds();

            staveGroupBounds.VisualBounds = new Bounds
            {
                X = cx,
                Y = cy + Y,
                W = Width,
                H = Height
            };
            staveGroupBounds.RealBounds = new Bounds
            {
                X = cx,
                Y = cy + Y,
                W = Width,
                H = Height
            };
            Layout.Renderer.BoundsLookup.AddStaveGroup(staveGroupBounds);

            var masterBarBoundsLookup = new FastList <MasterBarBounds>();

            for (int i = 0; i < Staves.Count; i++)
            {
                for (int j = 0, k = Staves[i].FirstStaffInAccolade.BarRenderers.Count; j < k; j++)
                {
                    var renderer = Staves[i].FirstStaffInAccolade.BarRenderers[j];

                    if (i == 0)
                    {
                        var masterBarBounds = new MasterBarBounds();
                        masterBarBounds.IsFirstOfLine = renderer.IsFirstOfLine;
                        masterBarBounds.RealBounds    = new Bounds
                        {
                            X = x + renderer.X,
                            Y = realTop,
                            W = renderer.Width,
                            H = realHeight
                        };
                        masterBarBounds.VisualBounds = new Bounds
                        {
                            X = x + renderer.X,
                            Y = visualTop,
                            W = renderer.Width,
                            H = visualHeight
                        };
                        Layout.Renderer.BoundsLookup.AddMasterBar(masterBarBounds);
                        masterBarBoundsLookup.Add(masterBarBounds);
                    }

                    renderer.BuildBoundingsLookup(masterBarBoundsLookup[j], x, cy + Y + _firstStaffInAccolade.Y);
                }
            }
        }
コード例 #52
0
        /* Sometimes the intersection end snaps to an existing road. But it can happen that the intersection road and the road it snaps to are (more or
         * less) parallel. Then we are left with a piece of old road overlapping the new road because the old segment for some reason doesn't show up as
         * colliding. We have to find it and release it. I think that it shouldn't happen more than once per intersection tho. */
        private static void ReleaseQuestionableSegments(FastList <ushort> newNodes, FastList <ushort> newSegments)
        {
            foreach (ushort node in newNodes)
            {
                NetNode netNode      = NetUtil.Node(node);
                ushort  foundSegment = 0;
                for (int i = 0; i < 8; i++)
                {
                    ushort segment = netNode.GetSegment(i);
                    if (segment != 0 && newSegments.Contains(segment))
                    {
                        if (foundSegment != 0)
                        {
                            goto continueOuterLoop;
                        }
                        else
                        {
                            foundSegment = segment;
                        }
                    }
                }

                Vector3 direction = NetUtil.Segment(foundSegment).GetDirection(node);
                for (int i = 0; i < 8; i++)
                {
                    ushort segment = netNode.GetSegment(i);
                    if (segment != 0 && segment != foundSegment)
                    {
                        float angle = Vector3.Angle(direction, NetUtil.Segment(segment).GetDirection(node));
                        if (angle < 10)
                        {
                            //Debug.Log("Releasing questionable segment " + segment);
                            //NetUtil.ReleaseSegment(segment);
                            WrappedSegment segmentW = _networkDictionary.RegisterSegment(segment);
                            _actionGroup.Actions.Add(segmentW);
                            segmentW.IsBuildAction = false;
                            segmentW.Release();

                            if (segmentW.StartNode.TryRelease())
                            {
                                _actionGroup.Actions.Add(segmentW.StartNode);
                                segmentW.StartNode.IsBuildAction = false;
                            }

                            if (segmentW.EndNode.TryRelease())
                            {
                                _actionGroup.Actions.Add(segmentW.EndNode);
                                segmentW.EndNode.IsBuildAction = false;
                            }

                            /*WrappedSegment segmentW = _networkDictionary.RegisterSegment(segment);
                             * segmentW.Release();*/

                            goto breakOuterLoop;
                        }
                    }
                }

                continueOuterLoop :;
            }
            breakOuterLoop :;
        }
コード例 #53
0
 /// <summary>
 /// Creates a new GpxFileSystem instance
 /// </summary>
 public ZipFile()
 {
     Entries    = new FastList <ZipEntry>();
     FileFilter = s => true;
 }
コード例 #54
0
        // Called after intersection is built
        private static void AfterIntersectionBuilt(BuildingInfo info, FastList <ushort> m_tempNodeBuffer, FastList <ushort> m_tempSegmentBuffer)
        {
            if (info.m_paths.Length > 0)
            {
                foreach (ushort node in m_tempNodeBuffer)
                {
                    var nodeW = _networkDictionary.RegisterNode(node);
                    _actionGroup.Actions.Add(nodeW);
                }
                foreach (ushort segment in m_tempSegmentBuffer)
                {
                    var segmentW = _networkDictionary.RegisterSegment(segment);
                    _actionGroup.Actions.Add(segmentW);
                }
                ReleaseQuestionableSegments(m_tempNodeBuffer, m_tempSegmentBuffer);
                new MakeConnections(borderNodes, m_tempNodeBuffer, _networkDictionary, _actionGroup);
                _actionGroup.IsDone = true;

                SmartIntersections.instance.PushGameAction(_actionGroup);
            }
        }
コード例 #55
0
 public static void CleanPropertyArrayOffset()
 {
     _propertyArrayOffset = null;
     _intBuffer?.Clear();
     _intBuffer = null;
 }
コード例 #56
0
        private static void SetupTurningLaneProps(NetInfo.Lane lane)
        {
            var isLeftDriving = Singleton <SimulationManager> .instance.m_metaData.m_invertTraffic == SimulationMetaData.MetaBool.True;

            if (lane.m_laneProps == null)
            {
                return;
            }

            if (lane.m_laneProps.m_props == null)
            {
                return;
            }

            var fwd   = lane.m_laneProps.m_props.FirstOrDefault(p => p.m_flagsRequired == NetLane.Flags.Forward);
            var left  = lane.m_laneProps.m_props.FirstOrDefault(p => p.m_flagsRequired == NetLane.Flags.Left);
            var right = lane.m_laneProps.m_props.FirstOrDefault(p => p.m_flagsRequired == NetLane.Flags.Right);

            if (fwd == null)
            {
                return;
            }

            if (left == null)
            {
                return;
            }

            if (right == null)
            {
                return;
            }


            // Existing props
            //var r0 = NetLane.Flags.Forward;
            //var r1 = NetLane.Flags.ForwardRight;
            //var r2 = NetLane.Flags.Left;
            //var r3 = NetLane.Flags.LeftForward;
            //var r4 = NetLane.Flags.LeftForwardRight;
            //var r5 = NetLane.Flags.LeftRight;
            //var r6 = NetLane.Flags.Right;

            //var f0 = NetLane.Flags.LeftRight;
            //var f1 = NetLane.Flags.Left;
            //var f2 = NetLane.Flags.ForwardRight;
            //var f3 = NetLane.Flags.Right;
            //var f4 = NetLane.Flags.None;
            //var f5 = NetLane.Flags.Forward;
            //var f6 = NetLane.Flags.LeftForward;


            var newProps = new FastList <NetLaneProps.Prop>();

            //newProps.Add(fwd); // Do we want "Forward" on a turning lane?
            newProps.Add(left);
            newProps.Add(right);

            var fl = left.ShallowClone();

            fl.m_flagsRequired  = NetLane.Flags.LeftForward;
            fl.m_flagsForbidden = NetLane.Flags.Right;
            newProps.Add(fl);

            var fr = right.ShallowClone();

            fr.m_flagsRequired  = NetLane.Flags.ForwardRight;
            fr.m_flagsForbidden = NetLane.Flags.Left;
            newProps.Add(fr);

            var flr = isLeftDriving ? right.ShallowClone() : left.ShallowClone();

            flr.m_flagsRequired  = NetLane.Flags.LeftForwardRight;
            flr.m_flagsForbidden = NetLane.Flags.None;
            newProps.Add(flr);

            var lr = isLeftDriving ? right.ShallowClone() : left.ShallowClone();

            lr.m_flagsRequired  = NetLane.Flags.LeftRight;
            lr.m_flagsForbidden = NetLane.Flags.Forward;
            newProps.Add(lr);

            lane.m_laneProps         = ScriptableObject.CreateInstance <NetLaneProps>();
            lane.m_laneProps.name    = "TurningLane";
            lane.m_laneProps.m_props = newProps.ToArray();
        }
コード例 #57
0
        protected JsApi(HtmlElement element, dynamic options)
        {
            Element = element;

            Element.classList.add("alphaTab");

            // load settings
            var dataAttributes = GetDataAttributes();
            var settings       = Settings = AlphaTab.Settings.FromJson(options, dataAttributes);
            var autoSize       = settings.Width < 0;

            #region build tracks array

            // get track data to parse
            dynamic tracksData;
            if (options != null && options.tracks)
            {
                tracksData = options.tracks;
            }
            else
            {
                if (dataAttributes.ContainsKey("tracks"))
                {
                    tracksData = dataAttributes["tracks"];
                }
                else
                {
                    tracksData = 0;
                }
            }

            SetTracks(tracksData, false);

            #endregion

            string contents = "";
            if (element != null)
            {
                // get load contents

                if (dataAttributes.ContainsKey("tex") && element.innerText.As <JsBoolean>())
                {
                    contents          = (element.innerHTML.As <string>()).Trim();
                    element.innerHTML = "";
                }

                #region Create context elements (wrapper, canvas etc)

                CanvasElement = (HtmlElement)document.createElement("div");

                CanvasElement.className        = "alphaTabSurface";
                CanvasElement.style.fontSize   = "0";
                CanvasElement.style.overflow   = "hidden";
                CanvasElement.style.lineHeight = "0";
                element.appendChild(CanvasElement);

                #endregion

                #region Setup scroll and resize handlers for lazy-loading

                if (settings.Engine == "default" || settings.Engine == "svg")
                {
                    window.addEventListener("scroll", e =>
                    {
                        ShowSvgsInViewPort();
                    }, true);
                    window.addEventListener("resize", e =>
                    {
                        ShowSvgsInViewPort();
                    }, true);
                }

                #endregion

                #region Auto Sizing

                if (autoSize)
                {
                    settings.Width = element.offsetWidth;
                    int timeoutId = 0;
                    window.addEventListener("resize", e =>
                    {
                        clearTimeout(timeoutId);
                        timeoutId = setTimeout(() =>
                        {
                            if (element.offsetWidth != settings.Width)
                            {
                                TriggerResize();
                            }
                        }, 1);
                    });
                }

                #endregion
            }

            #region Renderer Setup

            CreateStyleElement(settings);

            if (element != null && autoSize)
            {
                var initialResizeEventInfo = new ResizeEventArgs();
                initialResizeEventInfo.OldWidth = 0;
                initialResizeEventInfo.NewWidth = element.offsetWidth;
                initialResizeEventInfo.Settings = settings;
                TriggerEvent("resize", initialResizeEventInfo);
                settings.Width = initialResizeEventInfo.NewWidth;
            }

            var workersUnsupported = !window.Worker.As <bool>();
            if (settings.UseWebWorker && !workersUnsupported && settings.Engine != "html5")
            {
                Renderer = new WorkerScoreRenderer(this, settings);
            }
            else
            {
                Renderer = new ScoreRenderer(settings);
            }
            Renderer.RenderFinished     += o => TriggerEvent("rendered");
            Renderer.PostRenderFinished += () =>
            {
                Element.classList.remove("loading");
                Element.classList.remove("rendering");
                TriggerEvent("postRendered");
            };
            Renderer.PreRender += result =>
            {
                _renderResults    = new FastList <RenderFinishedEventArgs>();
                _totalResultCount = 0;
                AppendRenderResult(result);
            };
            Renderer.PartialRenderFinished += AppendRenderResult;
            Renderer.RenderFinished        += r =>
            {
                AppendRenderResult(r);
                AppendRenderResult(null); // marks last element
            };
            Renderer.Error += Error;

            #endregion

            #region Load Default Data

            Action initialRender = () =>
            {
                // rendering was possibly delayed due to invisible element
                // in this case we need the correct width for autosize
                if (autoSize)
                {
                    Settings.Width = Element.offsetWidth;
                    Renderer.UpdateSettings(settings);
                }

                if (!string.IsNullOrEmpty(contents))
                {
                    Tex(contents);
                }
                else if (options && options.file)
                {
                    Load(options.file);
                }
                else if (dataAttributes.ContainsKey("file"))
                {
                    Load(dataAttributes["file"]);
                }
            };

            _visibilityCheckerInterval = options && options.visibilityCheckInterval || 500;
            if (IsElementVisible)
            {
                // element is visible, so we start rendering
                initialRender();
            }
            else
            {
                // if the alphaTab element is not visible, we postpone the rendering
                // we check in a regular interval whether it became available.
                Logger.Warning("Rendering", "AlphaTab container is invisible, checking for element visibility in " + _visibilityCheckerInterval + "ms intervals");
                _visibilityCheckerIntervalId = setInterval(() =>
                {
                    if (IsElementVisible)
                    {
                        Logger.Info("Rendering", "AlphaTab container became visible, triggering initial rendering");
                        initialRender();
                        clearInterval(_visibilityCheckerIntervalId);
                        _visibilityCheckerIntervalId = 0;
                    }
                }, _visibilityCheckerInterval);
            }

            #endregion
        }
コード例 #58
0
 /// <summary>
 /// Inserts the data in the list if this is a copy of a previously set one.
 /// </summary>
 /// <param name="data">The  data.</param>
 /// <param name="index">The index in the list.</param>
 /// <param name="bindings">The list of bindings.</param>
 /// <returns>The new index of the data.</returns>
 private static int GetReflexionIndex(EffectResourceBindingDescription data, int index, FastList <EffectResourceBindingDescription> bindings)
 {
     if (data.SlotCount != 0)
     {
         // slot count has been specified, this means that this resource was already configured
         // We have to create a new entry for the data
         var newIndex = bindings.Count;
         bindings.Add(data);
         return(newIndex);
     }
     return(index);
 }
コード例 #59
0
        public static bool ScreenPositionToWorldPositionRaycast(Vector2 screenPos, CameraComponent camera, Simulation simulation, out ClickResult clickResult)
        {
            Matrix invViewProj = Matrix.Invert(camera.ViewProjectionMatrix);

            Vector3 sPos;

            sPos.X = screenPos.X * 2f - 1f;
            sPos.Y = 1f - screenPos.Y * 2f;

            sPos.Z = 0f;
            var vectorNear = Vector3.Transform(sPos, invViewProj);

            vectorNear /= vectorNear.W;

            sPos.Z = 1f;
            var vectorFar = Vector3.Transform(sPos, invViewProj);

            vectorFar /= vectorFar.W;

            clickResult.ClickedEntity = null;
            clickResult.WorldPosition = Vector3.Zero;
            clickResult.Type          = ClickType.Empty;
            clickResult.HitResult     = new HitResult();

            var minDistance = float.PositiveInfinity;

            var result = new FastList <HitResult>();

            simulation.RaycastPenetrating(vectorNear.XYZ(), vectorFar.XYZ(), result);
            foreach (var hitResult in result)
            {
                ClickType type = ClickType.Empty;

                var staticBody = hitResult.Collider as StaticColliderComponent;
                if (staticBody != null)
                {
                    if (staticBody.CollisionGroup == CollisionFilterGroups.CustomFilter1)
                    {
                        type = ClickType.Ground;
                    }

                    if (staticBody.CollisionGroup == CollisionFilterGroups.CustomFilter2)
                    {
                        type = ClickType.LootCrate;
                    }

                    if (type != ClickType.Empty)
                    {
                        var distance = (vectorNear.XYZ() - hitResult.Point).LengthSquared();
                        if (distance < minDistance)
                        {
                            minDistance               = distance;
                            clickResult.Type          = type;
                            clickResult.HitResult     = hitResult;
                            clickResult.WorldPosition = hitResult.Point;
                            clickResult.ClickedEntity = hitResult.Collider.Entity;
                        }
                    }
                }
            }

            return(clickResult.Type != ClickType.Empty);
        }
コード例 #60
0
ファイル: PickingPlugin.cs プロジェクト: rohitshe/Code
        public override void Load()
        {
            base.Load();

            if (OfflineCompilation)
            {
                return;
            }

            var renderTargets = new RenderTarget[2];
            DepthStencilBuffer depthStencilBuffer  = null;
            Texture2D          depthStencilTexture = null;

            Parameters.AddSources(MainPlugin.ViewParameters);

            Parameters.RegisterParameter(EffectPlugin.BlendStateKey);

            var filteredPasses = new FastList <RenderPass>();

            RenderPass.UpdatePasses += updatePassesAction = (RenderPass currentRenderPass, ref FastList <RenderPass> currentPasses) =>
            {
                var originalPasses = currentPasses;
                filteredPasses.Clear();
                currentPasses = filteredPasses;

                Parameters.Set(PickingFrameIndex, ++currentPickingFrameIndex);
                Request[] requests;

                lock (pendingRequests)
                {
                    // No picking request or no mesh to pick?
                    if (pendingRequests.Count == 0)
                    {
                        return;
                    }

                    requests = pendingRequests.ToArray();
                    pendingRequests.Clear();
                }

                foreach (var request in requests)
                {
                    requestResults.Add(request);
                }

                if (originalPasses == null)
                {
                    return;
                }

                // Count mesh passes
                int meshIndex = 0;
                foreach (var pass in originalPasses)
                {
                    meshIndex += pass.Passes.Count;
                }

                // No mesh to pick?
                if (meshIndex == 0)
                {
                    return;
                }

                // Copy mesh passes and assign indices
                var meshPasses = new EffectMesh[meshIndex];
                meshIndex = 0;
                foreach (var pass in RenderPass.Passes)
                {
                    throw new NotImplementedException();
                    //foreach (var effectMeshPass in pass.Meshes)
                    //{
                    //    meshPasses[meshIndex] = (EffectMesh)effectMeshPass;
                    //    // Prefix increment so that 0 means no rendering.
                    //    effectMeshPass.Parameters.Set(PickingMeshIndex, ++meshIndex);
                    //}
                }

                // For now, it generates one rendering per picking.
                // It would be quite easy to optimize it by make Picking shader works on multiple picking points at a time.
                foreach (var request in requests)
                {
                    var pickingRenderPass = new RenderPass("Picking");

                    pickingRenderPass.StartPass.AddFirst = (threadContext) =>
                    {
                        threadContext.GraphicsDevice.Clear(renderTargets[0], Color.Black);
                        threadContext.GraphicsDevice.Clear(renderTargets[1], Color.Black);
                        threadContext.Parameters.Set(PickingScreenPosition, request.Location);
                        threadContext.GraphicsDevice.SetViewport(new Viewport(0, 0, renderTargets[0].Description.Width, renderTargets[0].Description.Height));

                        threadContext.GraphicsDevice.Clear(depthStencilBuffer, DepthStencilClearOptions.DepthBuffer);
                        threadContext.GraphicsDevice.SetRenderTargets(depthStencilBuffer, renderTargets);
                    };
                    pickingRenderPass.EndPass.AddLast = (threadContext) =>
                    {
                        threadContext.Parameters.Reset(PickingScreenPosition);
                        threadContext.GraphicsDevice.Copy(renderTargets[0].Texture, request.ResultTextures[0]);
                        threadContext.GraphicsDevice.Copy(renderTargets[1].Texture, request.ResultTextures[1]);
                    };
                    //pickingRenderPass.PassesInternal = originalPasses;
                    throw new NotImplementedException();

                    request.MeshPasses = meshPasses;

                    currentPasses.Add(pickingRenderPass);

                    request.HasResults = true;

                    // Wait 2 frames before pulling the results.
                    request.FrameCounter = 2;
                }
            };

            RenderSystem.GlobalPass.EndPass.AddLast = CheckPickingResults;

            var backBuffer = GraphicsDevice.BackBuffer;

            int pickingArea = 1 + PickingDistance * 2;

            renderTargets[0] = Texture.New2D(GraphicsDevice, pickingArea, pickingArea, PixelFormat.R32_UInt, TextureFlags.ShaderResource | TextureFlags.RenderTarget).ToRenderTarget().KeepAliveBy(ActiveObjects);
            renderTargets[1] = Texture.New2D(GraphicsDevice, pickingArea, pickingArea, PixelFormat.R32G32B32A32_Float, TextureFlags.ShaderResource | TextureFlags.RenderTarget).ToRenderTarget().KeepAliveBy(ActiveObjects);

            depthStencilTexture = Texture.New2D(GraphicsDevice, pickingArea, pickingArea, PixelFormat.D32_Float, TextureFlags.ShaderResource | TextureFlags.DepthStencil).KeepAliveBy(ActiveObjects);
            depthStencilBuffer  = depthStencilTexture.ToDepthStencilBuffer(false);

            Parameters.AddDynamic(PickingMatrix, ParameterDynamicValue.New(PickingScreenPosition, (ref Vector2 pickingPosition, ref Matrix picking) =>
            {
                // Move center to picked position, and zoom (it is supposed to stay per-pixel according to render target size)
                picking = Matrix.Translation(1.0f - (pickingPosition.X) / backBuffer.Width * 2.0f, -1.0f + (pickingPosition.Y) / backBuffer.Height * 2.0f, 0.0f)
                          * Matrix.Scaling((float)backBuffer.Width / (float)pickingArea, (float)backBuffer.Height / (float)pickingArea, 1.0f);
            }));
        }