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(); }
public static bool FindPath(Vector2d End, GridNode startNode, GridNode endNode, FastList<Vector2d> outputVectorPath) { if (startNode.Unwalkable || endNode.Unwalkable) return false; if (FindPath (startNode, endNode, OutputPath)) { outputVectorPath.FastClear (); length = OutputPath.Count - 1; for (i = 0; i < length; i++) { outputVectorPath.Add (OutputPath [i].WorldPos); } outputVectorPath.Add (End); return true; } return false; }
public static bool FindPath(Vector2d Start, Vector2d End, FastList<Vector2d> outputVectorPath) { if (!GetPathNodes(Start.x,Start.y,End.x,End.y,out node1, out node2)) return false; if (FindPath (node1, node2, OutputPath)) { outputVectorPath.FastClear (); length = OutputPath.Count - 1; for (i = 0; i < length; i++) { outputVectorPath.Add (OutputPath [i].WorldPos); } outputVectorPath.Add (End); return true; } return false; }
/// <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)); } }
/// <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)); } }
public static void RemoveProps() { var prefabs = Resources.FindObjectsOfTypeAll<BuildingInfo>(); foreach (var buildingInfo in prefabs) { var fastList = new FastList<BuildingInfo.Prop>(); if (buildingInfo == null) { continue; } if (buildingInfo.m_props != null) { var props = buildingInfo.m_props; foreach (var prop in props.Where(prop => prop != null)) { if (prop.m_finalProp != null) { if ( (!OptionsHolder.Options.removeSmoke || !prop.m_finalProp.name.Contains("Smoke") && !prop.m_finalProp.name.Contains("smoke")) && (!OptionsHolder.Options.removeSteam || !prop.m_finalProp.name.Contains("Steam") && !prop.m_finalProp.name.Contains("steam")) && (!OptionsHolder.Options.removeClownHeads || !prop.m_finalProp.name.Contains("Clown") && !prop.m_finalProp.name.Contains("clown")) && (!OptionsHolder.Options.removeIceCones || !prop.m_finalProp.name.Contains("Cream") && !prop.m_finalProp.name.Contains("cream")) && (!OptionsHolder.Options.removeDoughnutSquirrels || !prop.m_finalProp.name.Contains("Squirrel") && !prop.m_finalProp.name.Contains("squirrel")) && (!OptionsHolder.Options.removeRandom3dBillboards || prop.m_finalProp.name != "Billboard_3D_variation") && (!OptionsHolder.Options.removeFlatBillboards || prop.m_finalProp.name != "Hologram Ad Game Arcade") && (!OptionsHolder.Options.removeNeonChirpy || !BillboardCategories.Contains(prop.m_finalProp.editorCategory)) && (!OptionsHolder.Options.removeOctopodes || !prop.m_finalProp.name.Contains("Octopus") && !prop.m_finalProp.name.Contains("octopus")) && (!OptionsHolder.Options.removeWallFlags || prop.m_finalProp.name != "flag_pole_wall") && (!OptionsHolder.Options.removeSolarPanels || !prop.m_finalProp.name.Contains("Solar panel")) ) { fastList.Add(prop); } } else { fastList.Add(prop); } } } buildingInfo.m_props = fastList.ToArray(); } }
public override void FillParameterCollections(FastList<ParameterCollection> parameterCollections) { // Test common types to avoid struct enumerator boxing var localParameterCollectionsList = localParameterCollections as List<ParameterCollection>; if (localParameterCollectionsList != null) { foreach (var parameter in localParameterCollectionsList) { if (parameter != null) { parameterCollections.Add(parameter); } } } else { var localParameterCollectionsArray = localParameterCollections as ParameterCollection[]; if (localParameterCollectionsArray != null) { foreach (var parameter in localParameterCollectionsArray) { if (parameter != null) { parameterCollections.Add(parameter); } } } else { // Slow: enumerator will be boxed foreach (var parameter in localParameterCollections) { if (parameter != null) { parameterCollections.Add(parameter); } } } } }
public AlternateEndingsBarRenderer(Bar bar) : base(bar) { var alternateEndings = Bar.MasterBar.AlternateEndings; _endings = new FastList<int>(); for (var i = 0; i < MasterBar.MaxAlternateEndings; i++) { if ((alternateEndings & (0x01 << i)) != 0) { _endings.Add(i); } } }
public virtual bool ShouldCreateGlyph(EffectBarRenderer renderer, Beat beat) { LastCreateInfo = new FastList<Note>(); for (int i = 0, j = beat.Notes.Count; i < j; i++) { var n = beat.Notes[i]; if (ShouldCreateGlyphForNote(renderer, n)) { LastCreateInfo.Add(n); } } return LastCreateInfo.Count > 0; }
/// <summary> /// Base constructor for blueprints. /// </summary> /// <param name="id"></param> /// <param name="name"></param> internal Item(BlueprintMarketGroup group, SerializableBlueprint src) : this(src.ID, src.Name) { m_icon = src.Icon; m_metaGroup = src.MetaGroup; m_marketGroup = group; m_family = ItemFamily.Bpo; m_prerequisites = new FastList<StaticSkillLevel>(src.PrereqSkill != null ? src.PrereqSkill.Length : 0); if (src.PrereqSkill == null) return; foreach (var prereq in src.PrereqSkill) { m_prerequisites.Add(new StaticSkillLevel(prereq.ID, prereq.Level, prereq.Activity)); } }
/// <summary> /// Base constructor for blueprints. /// </summary> /// <param name="group">The group.</param> /// <param name="src">The source.</param> internal Item(MarketGroup group, SerializableBlueprint src) : this(src.ID, src.Name) { Icon = src.Icon; MetaGroup = src.MetaGroup; MarketGroup = group; Family = ItemFamily.Blueprint; // Skills prerequisites m_prerequisites = new FastList<StaticSkillLevel>(src.PrereqSkill?.Count ?? 0); if (src.PrereqSkill == null) return; foreach (SerializablePrereqSkill prereq in src.PrereqSkill) { m_prerequisites.Add(new StaticSkillLevel(prereq.ID, prereq.Level, prereq.Activity)); } }
private unsafe LazyStringValue CreateLazyStringValueFromParserState(JsonParserState state) { int escapePositionsCount = state.EscapePositions.Count; var maxSizeOfEscapePos = escapePositionsCount * 5 // max size of var int + JsonParserState.VariableSizeIntSize(escapePositionsCount); var mem = _ctx.GetMemory(maxSizeOfEscapePos + state.StringSize); _allocations.Add(mem); Memory.Copy(mem.Address, state.StringBuffer, state.StringSize); var lazyStringValueFromParserState = _ctx.AllocateStringValue(null, mem.Address, state.StringSize); if (escapePositionsCount > 0) { lazyStringValueFromParserState.EscapePositions = state.EscapePositions.ToArray(); } return(lazyStringValueFromParserState); }
/// <summary> /// Pefrorms a sweep test using a collider shape and never stops until "to" /// </summary> /// <param name="shape">The shape.</param> /// <param name="from">From.</param> /// <param name="to">To.</param> /// <param name="groupFilters">The PhysicsCompoenet CollisionGroup(s) that we intend to filter in.</param> /// <returns></returns> /// <exception cref="System.Exception">This kind of shape cannot be used for a ShapeSweep.</exception> public FastList <HitResult> ShapeSweepPenetrating(ColliderShape shape, Matrix from, Matrix to, IReadOnlyCollection <CollisionFilterGroups> groupFilters) { var sh = shape.InternalShape as BulletSharp.ConvexShape; if (sh == null) { throw new Exception("This kind of shape cannot be used for a ShapeSweep."); } var fullDistance = (to.TranslationVector - from.TranslationVector).LengthSquared(); using (var rcb = new BulletSharp.AllHitsConvexResultCallback()) { collisionWorld.ConvexSweepTest(sh, from, to, rcb); var count = rcb.CollisionObjects.Count; var result = new FastList <HitResult>(count); for (var i = 0; i < count; i++) { var component = (PhysicsComponent)rcb.CollisionObjects[i].UserObject; if (!groupFilters.Contains(component.CollisionGroup)) { continue; } var singleResult = new HitResult { Succeeded = true, Collider = (PhysicsComponent)rcb.CollisionObjects[i].UserObject, Normal = rcb.HitNormalWorld[i], Point = rcb.HitPointWorld[i], FullLength = fullDistance, StartPoint = from.TranslationVector, NormalizedDistance = -1.0f //lazily computed }; result.Add(singleResult); } return(result); } }
private void UpdateCoordinates() { const long gridSpacing = FixedMath.One; bufferCoordinates.FastClear(); CachedBody.GetCoveredSnappedPositions(gridSpacing, bufferCoordinates); foreach (Vector2d vec in bufferCoordinates) { GridNode node = GridManager.GetNode(vec.x, vec.y); if (node == null) { continue; } node.AddObstacle(); LastCoordinates.Add(node); } }
public unsafe LazyStringValue AllocateStringValue(string str, byte *ptr, int size) { if (_numberOfAllocatedStringsValues < _allocateStringValues.Count) { var lazyStringValue = _allocateStringValues[_numberOfAllocatedStringsValues++]; Debug.Assert(lazyStringValue != null); lazyStringValue.Renew(str, ptr, size); return(lazyStringValue); } var allocateStringValue = new LazyStringValue(str, ptr, size, this); if (_numberOfAllocatedStringsValues < 25 * 1000) { _allocateStringValues.Add(allocateStringValue); _numberOfAllocatedStringsValues++; } return(allocateStringValue); }
private float LayoutAndRenderScore(float x, float y) { var score = Renderer.Score; var canvas = Renderer.Canvas; var startIndex = Renderer.Settings.Layout.Get("start", 1); startIndex--; // map to array index startIndex = Math.Min(score.MasterBars.Count - 1, Math.Max(0, startIndex)); var currentBarIndex = startIndex; var endBarIndex = Renderer.Settings.Layout.Get("count", score.MasterBars.Count); if (endBarIndex < 0) { endBarIndex = score.MasterBars.Count; } endBarIndex = startIndex + endBarIndex - 1; // map count to array index endBarIndex = Math.Min(score.MasterBars.Count - 1, Math.Max(0, endBarIndex)); _groups = new FastList <StaveGroup>(); if (Renderer.Settings.Staves.Count > 0) { while (currentBarIndex <= endBarIndex) { // create group and align set proper coordinates var group = CreateStaveGroup(currentBarIndex, endBarIndex); _groups.Add(group); group.X = x; group.Y = y; currentBarIndex = group.LastBarIndex + 1; // finalize group (sizing etc). FitGroup(group); group.FinalizeGroup(this); y += PaintGroup(group, y, canvas); } } return(y); }
/// <summary> /// Base constructor for blueprints. /// </summary> /// <param name="id"></param> /// <param name="name"></param> internal Item(BlueprintMarketGroup group, SerializableBlueprint src) : this(src.ID, src.Name) { m_icon = src.Icon; m_metaGroup = src.MetaGroup; m_marketGroup = group; m_family = ItemFamily.Bpo; m_prerequisites = new FastList <StaticSkillLevel>(src.PrereqSkill != null ? src.PrereqSkill.Length : 0); if (src.PrereqSkill == null) { return; } foreach (var prereq in src.PrereqSkill) { m_prerequisites.Add(new StaticSkillLevel(prereq.ID, prereq.Level, prereq.Activity)); } }
private static void UpdateGarbageBuildingsInformations() { _buildingManager = ColossalFramework.Singleton <BuildingManager> .instance; var buffer = _buildingManager.m_buildings.m_buffer; // ゴミ関連施設のリスト garbageBuildings = _buildingManager.GetServiceBuildings(ItemClass.Service.Garbage); foreach (ushort serviceGarbage in garbageBuildings) { var _buildingAi = buffer[serviceGarbage].Info.m_buildingAI; // ゴミ集積場の場合のみ if (_buildingAi is LandfillSiteAI) { listLandFill.Add(serviceGarbage); } } }
public void GetSpacedNeighborCoordinates(Coordinate position, int size, FastList <Coordinate> output) { int half = size / 2; int lowX = half, highX = half, lowY = half, highY = half; if (size % 2 == 0) { highX -= 1; highY -= 1; } lowX = position.x - lowX; highX = position.x + highX; lowY = position.y - lowY; highY = position.y + highY; int neighborLowX = lowX - BuildSpacing; int neighborHighX = highX + BuildSpacing; int neighborLowY = lowY - BuildSpacing; int neighborHighY = highY + BuildSpacing; output.FastClear(); for (int x = neighborLowX; x <= neighborHighX; x++) { if (IsOnGrid(x) == false) { continue; } for (int y = neighborLowY; y <= neighborHighY; y++) { if (IsOnGrid(y) == false) { continue; } if (x >= lowX && x <= highX && y >= lowY && y <= highY) { continue; } output.Add(new Coordinate(x, y)); } } }
private void LoadMidiFile(MidiFile midiFile) { _tempoChanges = new FastList <MidiFileSequencerTempoChange>(); //Converts midi to sample based format for easy sequencing float bpm = 120.0f; //Combine all tracks into 1 track that is organized from lowest to highest absolute time if (midiFile.Tracks.Length > 1 || midiFile.Tracks[0].EndTime == 0) { midiFile.CombineTracks(); } //Convert delta time to sample time _synthData = new SynthEvent[midiFile.Tracks[0].MidiEvents.Length]; _division = midiFile.Division; _eventIndex = 0; CurrentTime = 0; CurrentTempo = (int)bpm; //Calculate sample based time using double counter and round down to nearest integer sample. var absDelta = 0.0; var absTick = 0; var absTime = 0.0; for (int x = 0; x < midiFile.Tracks[0].MidiEvents.Length; x++) { var mEvent = midiFile.Tracks[0].MidiEvents[x]; _synthData[x] = new SynthEvent(mEvent); absTick += mEvent.DeltaTime; absTime += mEvent.DeltaTime * (60000.0 / (bpm * midiFile.Division)); absDelta += Synth.SampleRate * mEvent.DeltaTime * (60.0 / (bpm * midiFile.Division)); _synthData[x].Delta = (int)(absDelta); //Update tempo if (IsTempoMessage(mEvent.Command, mEvent.Data1)) { var meta = (MetaNumberEvent)mEvent; bpm = MidiHelper.MicroSecondsPerMinute / meta.Value; _tempoChanges.Add(new MidiFileSequencerTempoChange(bpm, absTick, (int)(absTime))); } } EndTime = _synthData[_synthData.Length - 1].Delta; }
private static MidiEvent ReadSystemCommonMessage(IReadable input, int delta, byte status) { switch ((SystemCommonTypeEnum)status) { case SystemCommonTypeEnum.SystemExclusive2: case SystemCommonTypeEnum.SystemExclusive: { var maker = input.ReadInt16BE(); if (maker == 0x0) { maker = input.ReadInt16BE(); } else if (maker == 0xF7) { return(null); } var data = new FastList <byte>(); var b = input.ReadByte(); while (b != 0xF7) { data.Add((byte)b); b = input.ReadByte(); } return(new SystemExclusiveEvent(delta, status, maker, data.ToArray())); } case SystemCommonTypeEnum.MtcQuarterFrame: return(new SystemCommonEvent(delta, status, (byte)input.ReadByte(), 0)); case SystemCommonTypeEnum.SongPosition: return(new SystemCommonEvent(delta, status, (byte)input.ReadByte(), (byte)input.ReadByte())); case SystemCommonTypeEnum.SongSelect: return(new SystemCommonEvent(delta, status, (byte)input.ReadByte(), 0)); case SystemCommonTypeEnum.TuneRequest: return(new SystemCommonEvent(delta, status, 0, 0)); default: throw new Exception("The system common message was invalid or unsupported : " + status); } }
/// <summary> /// Ends the primitive. /// </summary> public void EndPrimitive() { #if !WINDOWS_PHONE if (currentPrimitive.PrimitiveType == PrimitiveType.LineList || currentPrimitive.PrimitiveType == PrimitiveType.LineStrip) { ExpandLineVertices(currentPrimitive.PrimitiveType == PrimitiveType.LineList); for (var index = 0; index < (currentVertex - currentPrimitive.StartVertex) / 2; ++index) { if (index % 2 == 0) { AddIndexInternal(index * 2); AddIndexInternal(index * 2 + 1); AddIndexInternal(index * 2 + 2); AddIndexInternal(index * 2 + 2); AddIndexInternal(index * 2 + 1); AddIndexInternal(index * 2 + 3); } } currentPrimitive.PrimitiveType = PrimitiveType.TriangleList; } #endif hasPrimitiveBegin = false; currentPrimitive.Segment = currentSegment; currentPrimitive.VertexCount = currentVertex - currentPrimitive.StartVertex; currentPrimitive.IndexCount = currentIndex - currentPrimitive.StartIndex; vertexSegments[vertexSegments.Count - 1] = baseSegmentVertex + currentVertex; indexSegments[indexSegments.Count - 1] = baseSegmentIndex + currentIndex; var i = batches.Count - 1; if (batches.Count > 0 && (AlwaysMergePrimitives || CanMerge(ref batches.Elements[i], ref currentPrimitive)) && batches.Elements[i].Segment == currentPrimitive.Segment) { batches.Elements[i].IndexCount += currentPrimitive.IndexCount; batches.Elements[i].VertexCount += currentPrimitive.VertexCount; return; } batches.Add(currentPrimitive); }
private bool TryGetBuildCoordinates(Coordinate position, int size, FastList <Coordinate> output) { int half = size / 2; int lowX = half, highX = half, lowY = half, highY = half; if (size % 2 == 0) { highX -= 1; highY -= 1; } lowX = position.x - lowX; if (!IsOnGrid(lowX)) { return(false); } highX = position.x + highX; if (!IsOnGrid(highX)) { return(false); } lowY = position.y - lowY; if (!IsOnGrid(lowY)) { return(false); } highY = position.y + highY; if (!IsOnGrid(highY)) { return(false); } output.FastClear(); for (int x = lowX; x <= highX; x++) { for (int y = lowY; y <= highY; y++) { output.Add(new Coordinate(x, y)); } } return(true); }
public void AddStave(Track track, Stave stave) { var group = GetStaveTrackGroup(track); if (group == null) { group = new StaveTrackGroup(this, track); Staves.Add(group); } stave.StaveTrackGroup = group; stave.StaveGroup = this; stave.Index = _allStaves.Count; _allStaves.Add(stave); group.Staves.Add(stave); if (stave.IsInAccolade) { if (_firstStaveInAccolade == null) { _firstStaveInAccolade = stave; stave.IsFirstInAccolade = true; } if (group.FirstStaveInAccolade == null) { group.FirstStaveInAccolade = stave; } if (_lastStaveInAccolade == null) { _lastStaveInAccolade = stave; stave.IsLastInAccolade = true; } if (_lastStaveInAccolade != null) { _lastStaveInAccolade.IsLastInAccolade = false; } _lastStaveInAccolade = stave; _lastStaveInAccolade.IsLastInAccolade = true; group.LastStaveInAccolade = stave; } }
public void TestLoadSf2PatchBank() { var data = TestPlatform.LoadFile("TestFiles/Audio/default.sf2"); var patchBank = new PatchBank(); var input = ByteBuffer.FromBuffer(data); patchBank.LoadSf2(input); Assert.AreEqual("GS sound set (16 bit)", patchBank.Name); Assert.AreEqual("960920 ver. 1.00.16", patchBank.Comments); Assert.AreEqual("0,1,2,3,4,5,6,7,8,9,16,24,32,128", string.Join(",", patchBank.LoadedBanks)); var gmBank = patchBank.GetBank(0); var expectedPatches = new string[] { "Piano 1", "Piano 2", "Piano 3", "Honky-tonk", "E.Piano 1", "E.Piano 2", "Harpsichord", "Clav.", "Celesta", "Glockenspiel", "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular-bell", "Santur", "Organ 1", "Organ 2", "Organ 3", "Church Org.1", "Reed Organ", "Accordion Fr", "Harmonica", "Bandoneon", "Nylon-str.Gt", "Steel-str.Gt", "Jazz Gt.", "Clean Gt.", "Muted Gt.", "Overdrive Gt", "DistortionGt", "Gt.Harmonics", "Acoustic Bs.", "Fingered Bs.", "Picked Bs.", "Fretless Bs.", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin", "Viola", "Cello", "Contrabass", "Tremolo Str", "PizzicatoStr", "Harp", "Timpani", "Strings", "Slow Strings", "Syn.Strings1", "Syn.Strings2", "Choir Aahs", "Voice Oohs", "SynVox", "OrchestraHit", "Trumpet", "Trombone", "Tuba", "MutedTrumpet", "French Horns", "Brass 1", "Synth Brass1", "Synth Brass2", "Soprano Sax", "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet", "Piccolo", "Flute", "Recorder", "Pan Flute", "Bottle Blow", "Shakuhachi", "Whistle", "Ocarina", "Square Wave", "Saw Wave", "Syn.Calliope", "Chiffer Lead", "Charang", "Solo Vox", "5th Saw Wave", "Bass & Lead", "Fantasia", "Warm Pad", "Polysynth", "Space Voice", "Bowed Glass", "Metal Pad", "Halo Pad", "Sweep Pad", "Ice Rain", "Soundtrack", "Crystal", "Atmosphere", "Brightness", "Goblin", "Echo Drops", "Star Theme", "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bagpipe", "Fiddle", "Shanai", "Tinkle Bell", "Agogo", "Steel Drums", "Woodblock", "Taiko", "Melo. Tom 1", "Synth Drum", "Reverse Cym.", "Gt.FretNoise", "Breath Noise", "Seashore", "Bird", "Telephone 1", "Helicopter", "Applause", "Gun Shot" }; var actualPatches = new FastList <string>(); foreach (var patch in gmBank) { if (patch != null) { actualPatches.Add(patch.Name); } } Assert.AreEqual(string.Join(",", expectedPatches), string.Join(",", actualPatches)); }
public override void Record(int frame) { List <EntityBase> list = GetEntityList(); for (int i = 0; i < list.Count; i++) { T data = list[i].GetComp <T>(hashCode); //if(data.IsChange) { data.IsChange = false; T record = (T)data.DeepCopy(); record.Frame = frame; record.ID = list[i].ID; m_record.Add(record); } } }
/// <summary> /// BuildBlendTree is called every frame from the animation system when the <see cref="AnimationComponent"/> needs to be evaluated /// It overrides the default behavior of the <see cref="AnimationComponent"/> by setting a custom blend tree /// </summary> /// <param name="blendStack">The stack of animation operations to be blended</param> public void BuildBlendTree(FastList <AnimationOperation> blendStack) { switch (state) { case AnimationState.Walking: { // Note! The tree is laid out as a stack and has to be flattened before returning it to the animation system! blendStack.Add(AnimationOperation.NewPush(animEvaluatorWalkLerp1, TimeSpan.FromTicks((long)(currentTime * animationClipWalkLerp1.Duration.Ticks)))); blendStack.Add(AnimationOperation.NewPush(animEvaluatorWalkLerp2, TimeSpan.FromTicks((long)(currentTime * animationClipWalkLerp2.Duration.Ticks)))); blendStack.Add(AnimationOperation.NewBlend(CoreAnimationOperation.Blend, walkLerpFactor)); } break; case AnimationState.Jumping: { blendStack.Add(AnimationOperation.NewPush(animEvaluatorJumpStart, TimeSpan.FromTicks((long)(currentTime * AnimationJumpStart.Duration.Ticks)))); } break; case AnimationState.Airborne: { blendStack.Add(AnimationOperation.NewPush(animEvaluatorJumpMid, TimeSpan.FromTicks((long)(currentTime * AnimationJumpMid.Duration.Ticks)))); } break; case AnimationState.Landing: { blendStack.Add(AnimationOperation.NewPush(animEvaluatorJumpEnd, TimeSpan.FromTicks((long)(currentTime * AnimationJumpEnd.Duration.Ticks)))); } break; case AnimationState.Punching: { blendStack.Add(AnimationOperation.NewPush(animEvaluatorPunch, TimeSpan.FromTicks((long)(currentTime * AnimationPunch.Duration.Ticks)))); } break; } }
public FastList <EventData> GameEventsThatStartWithin(double hours, bool countStarted = false) { FastList <EventData> _eventsWithin = new FastList <EventData>(); EventManager _eventManager = Singleton <EventManager> .instance; for (int index = 0; index < _eventManager.m_events.m_size; ++index) { EventData thisEvent = _eventManager.m_events.m_buffer[index]; if ((thisEvent.m_flags & EventData.Flags.Created) != EventData.Flags.None) { if (GameEventHelpers.EventStartsWithin(thisEvent, hours) || (countStarted && (thisEvent.m_flags & EventData.Flags.Active) != EventData.Flags.None)) { _eventsWithin.Add(thisEvent); } } } return(_eventsWithin); }
public void RaycastMove(Vector3d delta) { #if true Vector3d nextPosition = this.Position; nextPosition.Add(ref delta); HitBodies.FastClear(); foreach (LSBody body in Raycaster.RaycastAll(this.Position, nextPosition)) { if (this.BodyConditional(body)) { HitBodies.Add(body); } } if (HitBodies.Count > 0) { Hit(); } this.Position = nextPosition; #endif }
/// <summary> /// Base constructor for blueprints. /// </summary> /// <param name="group">The group.</param> /// <param name="src">The source.</param> internal Item(MarketGroup group, SerializableBlueprint src) : this(src.ID, src.Name) { Icon = src.Icon; MetaGroup = src.MetaGroup; MarketGroup = group; Family = ItemFamily.Blueprint; // Skills prerequisites m_prerequisites = new FastList <StaticSkillLevel>(src.PrereqSkill?.Count ?? 0); if (src.PrereqSkill == null) { return; } foreach (SerializablePrereqSkill prereq in src.PrereqSkill) { m_prerequisites.Add(new StaticSkillLevel(prereq.ID, prereq.Level, prereq.Activity)); } }
//based on CitizenManager#RefreshGroupCitizens() private static FastList <ushort> RefreshAnimals() { var animals = new FastList <ushort>(); var num1 = PrefabCollection <CitizenInfo> .PrefabCount(); for (var index = 0; index < num1; ++index) { var prefab = PrefabCollection <CitizenInfo> .GetPrefab((uint)index); if (prefab == null) { continue; } if (prefab.m_citizenAI.IsAnimal()) { animals.Add((ushort)index); } } return(animals); }
private bool TryGetBuildCoordinates(Coordinate position, int sizeLow, int sizeHigh, FastList <Coordinate> output) { int halfLow = sizeLow / 2; int halfHigh = sizeHigh / 2; int lowX = halfLow, lowY = halfHigh; int highX = halfLow, highY = halfHigh; lowX = position.x - lowX; if (!IsOnGrid(lowX)) { return(false); } lowY = position.y - lowY; if (!IsOnGrid(lowY)) { return(false); } highX = position.x + highX; if (!IsOnGrid(highX)) { return(false); } highY = position.y + highY; if (!IsOnGrid(highY)) { return(false); } output.FastClear(); for (int x = lowX; x <= highX; x++) { for (int y = lowY; y <= highY; y++) { output.Add(new Coordinate(x, y)); } } return(true); }
/// <summary> /// Creates a render target from the pool without locking it. /// </summary> public static RenderTarget2D GetRenderTarget(GraphicsDevice graphics, int width, int height, SurfaceFormat surfaceFormat, DepthFormat depthFormat) { var key = sharedKey; key.Graphics = graphics; key.Width = width; key.Height = height; key.SurfaceFormat = surfaceFormat; key.DepthFormat = depthFormat; PooledRenderTarget2D tag; FastList <PooledRenderTarget2D> tags; if (!renderTargetPools.TryGetValue(key, out tags)) { key = new RenderTargetPoolKey(); key.Graphics = graphics; key.Width = width; key.Height = height; key.SurfaceFormat = surfaceFormat; key.DepthFormat = depthFormat; tag = new PooledRenderTarget2D(graphics, width, height, false, surfaceFormat, depthFormat, 0, RenderTargetUsage.DiscardContents); tags = new FastList <PooledRenderTarget2D>(); tags.Add(tag); renderTargetPools.Add(key, tags); return(tag); } for (int i = 0; i < tags.Count; ++i) { if ((tag = tags[i]).RefCount <= 0) { return(tag); } } tag = new PooledRenderTarget2D(graphics, width, height, false, surfaceFormat, depthFormat, 0, RenderTargetUsage.DiscardContents); tags.Add(tag); return(tag); }
//This step is to compile all global bindings, including regular bindings and bindings defined //by pattern matching. private FastList <ElaEquation> ProcessBindings(FastList <ElaEquation> exps, LabelMap map) { var len = exps.Count; var small = len == 1; var list = new FastList <ElaEquation>(len); for (var i = 0; i < len; i++) { var b = exps[i]; if (b.Right != null && b.Left.Type != ElaNodeType.Placeholder) { var hints = Hints.Left; //Unless somebody explicitly told us to compile everything in a //strict manner, we need to check if we need to create some thunks here. if (!options.Strict) { //Thunks are created if we have a binding which is recursive or when we //'suspect' that this one cannot be executed in a strict manner (e.g. //it references non-initialized names). if (ShouldCompileLazy(b.Right)) { #if DEBUG Console.WriteLine("lazy:::" + FormatNode(b)); #endif hints |= Hints.Lazy; } } CompileDeclaration(b, map, hints); } else { list.Add(b); } } return(list); }
public void Output(BlockDBEntry entry) { if (entry.TimeDelta >= start) { for (int i = 0; i < ids.Length; i++) { if (entry.PlayerID == ids[i]) { return; } } } left++; entries.Add(entry); if (entries.Count == 4096) { format.WriteEntries(dst, entries); entries.Count = 0; } }
public override void OnCreated(ILoading loading) { base.OnCreated(loading); if (Instance == null) { Instance = this; } FieldInfo pathManagerInstance = typeof(Singleton <PathManager>).GetField("sInstance", BindingFlags.Static | BindingFlags.NonPublic); PathManager stockPathManager = PathManager.instance; customPathManager = stockPathManager.gameObject.AddComponent <CustomPathManager>(); customPathManager.UpdateWithPathManagerValues(stockPathManager); pathManagerInstance.SetValue(null, customPathManager); FastList <ISimulationManager> managers = typeof(SimulationManager).GetField("m_managers", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null) as FastList <ISimulationManager>; managers.Remove(stockPathManager); managers.Add(customPathManager); GameObject.Destroy(stockPathManager, 10f); }
private AgentController(AllegianceType defaultAllegiance, string controllerName) { if (InstanceManagers.Count > byte.MaxValue) { throw new System.Exception("Cannot have more than 256 AgentControllers"); } OpenLocalIDs.FastClear(); PeakLocalID = 0; ControllerID = (byte)InstanceManagers.Count; ControllerName = controllerName; DefaultAllegiance = defaultAllegiance; for (int i = 0; i < InstanceManagers.Count; i++) { this.SetAllegiance(InstanceManagers[i], AllegianceType.Neutral); } InstanceManagers.Add(this); UpdateDiplomacy(this); this.SetAllegiance(this, AllegianceType.Friendly); }
public override void DoLayout() { base.DoLayout(); _bendGlyphs = new FastList <BendGlyph>(); for (int i = 0; i < Beat.Notes.Count; i++) { var n = Beat.Notes[i]; if (n.HasBend) { var bendValueHeight = 6; var bendHeight = n.MaxBendPoint.Value * bendValueHeight; Renderer.RegisterOverflowTop(bendHeight); var bend = new BendGlyph(n, bendValueHeight); bend.X = OnNotes.X + OnNotes.Width; bend.Renderer = Renderer; _bendGlyphs.Add(bend); } } }
public override void DoLayout() { base.DoLayout(); _bendGlyphs = new FastList<BendGlyph>(); for (int i = 0; i < Beat.Notes.Count; i++) { var n = Beat.Notes[i]; if (n.HasBend) { var bendValueHeight = 6; var bendHeight = n.MaxBendPoint.Value * bendValueHeight; Renderer.RegisterOverflowTop(bendHeight); var bend = new BendGlyph(n, bendValueHeight); bend.X = OnNotes.X + OnNotes.Width; bend.Renderer = Renderer; _bendGlyphs.Add(bend); } } }
private PropertyName UnlikelyGetProperty(LazyStringValue propName) { var propIndex = _docPropNames.Count; propName = _context.GetLazyStringForFieldWithCaching(propName); // PERF: The hash for the property needs to be a hash code, if its not // we will be paying the cost of hash collisions in the sort checks. var prop = new PropertyName(propName.GetHashCode(), propName, -1, propIndex); _docPropNames.Add(prop); _propertiesSortOrder.Add(prop, prop); _propertyNameToId[propName] = prop; _propertiesNeedSorting = true; if (_docPropNames.Count > PropertiesDiscovered + 1) { prop = SwapPropertyIds(prop); } PropertiesDiscovered++; return(prop); }
void GetCoveredSnappedPositionsAABB(long snapSpacing, FastList <Vector2d> output) { long xmin = GetFlooredSnap(m_AABB.m_Min.x - FixedMath.Half, snapSpacing); long ymin = GetFlooredSnap(m_AABB.m_Min.y - FixedMath.Half, snapSpacing); long xmax = GetCeiledSnap(m_AABB.m_Max.x + FixedMath.Half - xmin, snapSpacing) + xmin; long ymax = GetCeiledSnap(m_AABB.m_Max.y + FixedMath.Half - ymin, snapSpacing) + ymin; for (long x = xmin; x < xmax; x += snapSpacing) { for (long y = ymin; y < ymax; y += snapSpacing) { var checkPos = new Vector2d(x, y); if (IsPositionCovered(checkPos)) { output.Add(checkPos); } } } }
private void PushMessage(ref DebugRenderable msg) { if (msg.Lifetime > 0.0f) { renderMessagesWithLifetime.Add(msg); // drop one old message if the tail size has been reached if (renderMessagesWithLifetime.Count > MaxPrimitivesWithLifetime) { renderMessagesWithLifetime.RemoveAt(renderMessagesWithLifetime.Count - 1); } } else { renderMessages.Add(msg); // drop one old message if the tail size has been reached if (renderMessages.Count > MaxPrimitives) { renderMessages.RemoveAt(renderMessages.Count - 1); } } }
internal void Duplicate(int start, int finish) { var sh = Offset - start; ops.AddRange(ops, start, finish); opData.AddRange(opData, start, finish); var nf = new FastList<Int32>(); foreach (var i in fixups) { if (i >= start && i <= finish) { var l = labels[opData[i]]; var nl = DefineLabel(); opData[sh + i] = nl.GetIndex(); labels[nl.GetIndex()] = l + sh; nf.Add(sh + i); } } fixups.AddRange(nf); }
byte[] BuildVertexPBNT1Data(Vector3[] positions, Vector3[] normals, Vector2[] texVtx, Index3i[] texIdx, VertexWeight[] vtxWeights, MeshFace[] faces) { Dictionary<string, int> table = new Dictionary<string, int>(faces.Length * 3); FastList<VertexPBNT1> vertices = new FastList<VertexPBNT1>(faces.Length * 3); float[] blendBuf = new float[4]; byte[] blendBuf2 = new byte[4]; for (int i = 0; i < faces.Length; i++) { int index; VertexPBNT1 vtx; int vtxIdx = faces[i].IndexA; vtx.pos = positions[vtxIdx]; vtx.n = normals[vtxIdx]; vtx.u = texVtx[texIdx[i].A].X; vtx.v = texVtx[texIdx[i].A].Y; for (int j = 0; j < 4; j++) { if (j < vtxWeights[vtxIdx].BoneID.Length) { blendBuf[j] = vtxWeights[vtxIdx].Weight[j]; blendBuf2[j] = (byte)vtxWeights[vtxIdx].BoneID[j]; } else { blendBuf2[j] = 0; blendBuf[j] = 0; } } vtx.blend = new Vector4(blendBuf[0], blendBuf[1], blendBuf[2], blendBuf[3]); vtx.boneId1 = blendBuf2[0]; vtx.boneId2 = blendBuf2[1]; vtx.boneId3 = blendBuf2[2]; vtx.boneId4 = blendBuf2[3]; string desc = vtx.ToString(); if (!table.TryGetValue(desc, out index)) { table.Add(desc, vertices.Count); faces[i].IndexA = vertices.Count; vertices.Add(ref vtx); } else { faces[i].IndexA = index; } // ========================================= vtxIdx = faces[i].IndexB; vtx.pos = positions[vtxIdx]; vtx.n = normals[vtxIdx]; vtx.u = texVtx[texIdx[i].B].X; vtx.v = texVtx[texIdx[i].B].Y; for (int j = 0; j < 4; j++) { if (j < vtxWeights[vtxIdx].BoneID.Length) { blendBuf[j] = vtxWeights[vtxIdx].Weight[j]; blendBuf2[j] = (byte)vtxWeights[vtxIdx].BoneID[j]; } else { blendBuf2[j] = 0; blendBuf[j] = 0; } } vtx.blend = new Vector4(blendBuf[0], blendBuf[1], blendBuf[2], blendBuf[3]); vtx.boneId1 = blendBuf2[0]; vtx.boneId2 = blendBuf2[1]; vtx.boneId3 = blendBuf2[2]; vtx.boneId4 = blendBuf2[3]; desc = vtx.ToString(); if (!table.TryGetValue(desc, out index)) { table.Add(desc, vertices.Count); faces[i].IndexB = vertices.Count; vertices.Add(ref vtx); } else { faces[i].IndexB = index; } // ========================================= vtx.pos = positions[faces[i].IndexC]; vtx.n = normals[faces[i].IndexC]; vtx.u = texVtx[texIdx[i].C].X; vtx.v = texVtx[texIdx[i].C].Y; for (int j = 0; j < 4; j++) { if (j < vtxWeights[vtxIdx].BoneID.Length) { blendBuf[j] = vtxWeights[vtxIdx].Weight[j]; blendBuf2[j] = (byte)vtxWeights[vtxIdx].BoneID[j]; } else { blendBuf2[j] = 0; blendBuf[j] = 0; } } vtx.blend = new Vector4(blendBuf[0], blendBuf[1], blendBuf[2], blendBuf[3]); vtx.boneId1 = blendBuf2[0]; vtx.boneId2 = blendBuf2[1]; vtx.boneId3 = blendBuf2[2]; vtx.boneId4 = blendBuf2[3]; desc = vtx.ToString(); if (!table.TryGetValue(desc, out index)) { table.Add(desc, vertices.Count); faces[i].IndexC = vertices.Count; vertices.Add(ref vtx); } else { faces[i].IndexC = index; } } byte[] buffer = new byte[vertices.Count * sizeof(VertexPBNT1)]; fixed (byte* dst = &buffer[0]) { fixed (VertexPBNT1* src = &vertices.Elements[0]) { Memory.Copy(src, dst, buffer.Length); } } return buffer; }
byte[] BuildVertexPNData(Vector3[] positions, Vector3[] normals, MeshFace[] faces) { Dictionary<string, int> table = new Dictionary<string, int>(faces.Length * 3); FastList<VertexPN> vertices = new FastList<VertexPN>(faces.Length * 3); for (int i = 0; i < faces.Length; i++) { int index; VertexPN vtx; int vtxIdx = faces[i].IndexA; vtx.pos = positions[vtxIdx]; vtx.n = normals[vtxIdx]; string desc = vtx.ToString(); if (!table.TryGetValue(desc, out index)) { table.Add(desc, vertices.Count); faces[i].IndexA = vertices.Count; vertices.Add(ref vtx); } else { faces[i].IndexA = index; } // ========================================= vtxIdx = faces[i].IndexB; vtx.pos = positions[vtxIdx]; vtx.n = normals[vtxIdx]; desc = vtx.ToString(); if (!table.TryGetValue(desc, out index)) { table.Add(desc, vertices.Count); faces[i].IndexB = vertices.Count; vertices.Add(ref vtx); } else { faces[i].IndexB = index; } // ========================================= vtx.pos = positions[faces[i].IndexC]; vtx.n = normals[faces[i].IndexC]; desc = vtx.ToString(); if (!table.TryGetValue(desc, out index)) { table.Add(desc, vertices.Count); faces[i].IndexC = vertices.Count; vertices.Add(ref vtx); } else { faces[i].IndexC = index; } } byte[] buffer = new byte[vertices.Count * sizeof(VertexPN)]; fixed (byte* dst = &buffer[0]) { fixed (VertexPN* src = &vertices.Elements[0]) { Memory.Copy(src, dst, buffer.Length); } } return buffer; }
private void MetaData() { var anyMeta = false; while (_sy == AlphaTexSymbols.MetaCommand) { var syData = _syData.ToString().ToLower(); if (syData == "title") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.Title = _syData.ToString(); } else { Error("title", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "subtitle") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.SubTitle = _syData.ToString(); } else { Error("subtitle", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "artist") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.Artist = _syData.ToString(); } else { Error("artist", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "album") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.Album = _syData.ToString(); } else { Error("album", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "words") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.Words = _syData.ToString(); } else { Error("words", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "music") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.Music = _syData.ToString(); } else { Error("music", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "copyright") { NewSy(); if (_sy == AlphaTexSymbols.String) { _score.Copyright = _syData.ToString(); } else { Error("copyright", AlphaTexSymbols.String); } NewSy(); anyMeta = true; } else if (syData == "tempo") { NewSy(); if (_sy == AlphaTexSymbols.Number) { _score.Tempo = (int)_syData; } else { Error("tempo", AlphaTexSymbols.Number); } NewSy(); anyMeta = true; } else if (syData == "capo") { NewSy(); if (_sy == AlphaTexSymbols.Number) { _track.Capo = (int)_syData; } else { Error("capo", AlphaTexSymbols.Number); } NewSy(); anyMeta = true; } else if (syData == "tuning") { NewSy(); if (_sy == AlphaTexSymbols.Tuning) // we require at least one tuning { var tuning = new FastList<int>(); do { tuning.Add(ParseTuning(_syData.ToString().ToLower())); NewSy(); } while (_sy == AlphaTexSymbols.Tuning); _track.Tuning = tuning.ToArray(); } else { Error("tuning", AlphaTexSymbols.Tuning); } anyMeta = true; } else if (syData == "instrument") { NewSy(); if (_sy == AlphaTexSymbols.Number) { var instrument = (int)(_syData); if (instrument >= 0 && instrument <= 128) { _track.PlaybackInfo.Program = (int)_syData; } else { Error("instrument", AlphaTexSymbols.Number, false); } } else if (_sy == AlphaTexSymbols.String) // Name { var instrumentName = _syData.ToString().ToLower(); _track.PlaybackInfo.Program = GeneralMidi.GetValue(instrumentName); } else { Error("instrument", AlphaTexSymbols.Number); } NewSy(); anyMeta = true; } else { Error("metaDataTags", AlphaTexSymbols.String, false); } } if (anyMeta) { if (_sy != AlphaTexSymbols.Dot) { Error("song", AlphaTexSymbols.Dot); } NewSy(); } }
void ParseObject(XmlReader xml, ParsedXmlModel data, ref XmlModelObject obj) { int depth = xml.Depth; Vector3[] positions = null; Vector3[] normals = null; MeshFace[] faces = null; Vector2[] texVtx = null; Index3i[] texIdx = null; VertexWeight[] vtxWeights = null; #region 从Xml中读取数据 while (xml.Read() && xml.Depth > depth) { if (xml.IsStartElement() && !xml.IsEmptyElement) { switch (xml.Name) { case "Parent": obj.ID = int.Parse(xml.GetAttribute("ID")); break; case "LocalTM": obj.LocalTM = ParseMatrix(xml); break; case "WorldTM": obj.WorldTM = ParseMatrix(xml); break; case "BoundingBox": obj.AABB = ParseBoundingBox(xml); break; case "Vertex": positions = ParseMeshVector3Array(xml); break; case "VertexNormal": normals = ParseMeshVector3Array(xml); for (int i = 0; i < normals.Length; i++) { normals[i].Normalize(); } break; case "TexVertex": texVtx = ParseMeshVector2Array(xml); break; case "TriIndex": faces = ParseMeshFaces(xml); break; case "TexIndex": texIdx = ParseTexIndex(xml, faces.Length); break; case "VertexWeight": vtxWeights = ParseVertexWeightArray(xml, positions.Length); break; case "Key": obj.BoneData = ParseBoneData(xml); break; } } } #endregion if (obj.Type == XmlModelObjectType.Mesh) { FastList<VertexElement> elementsList = new FastList<VertexElement>(); int ofs = 0; if (positions != null) { VertexElement e = new VertexElement(ofs, VertexElementFormat.Vector3, VertexElementUsage.Position); elementsList.Add(e); ofs += e.Size; } if (normals != null) { VertexElement e = new VertexElement(ofs, VertexElementFormat.Vector3, VertexElementUsage.Normal); elementsList.Add(e); ofs += e.Size; } if (texVtx != null) { VertexElement e = new VertexElement(ofs, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0); elementsList.Add(e); ofs += e.Size; } if (vtxWeights != null) { VertexElement e = new VertexElement(ofs, VertexElementFormat.Byte4, VertexElementUsage.BlendWeight, 0); elementsList.Add(e); ofs += e.Size; } VertexElement[] elements = new VertexElement[elementsList.Count]; Array.Copy(elementsList.Elements, elements, elementsList.Count); obj.Mesh = new MeshData((RenderSystem)null); MeshData mesh = obj.Mesh; mesh.Faces = faces; mesh.Name = obj.Name; byte[] buffer = null; if (VertexElement.Compare(elements, VertexPBNT1.Elements)) { buffer = BuildVertexPBNT1Data(positions, normals, texVtx, texIdx, vtxWeights, faces); mesh.VertexSize = sizeof(VertexPBNT1); mesh.VertexElements = VertexPBNT1.Elements; } else if (VertexElement.Compare(elements, VertexPNT1.Elements)) { buffer = BuildVertexPNT1Data(positions, normals, texVtx, texIdx, faces); mesh.VertexSize = sizeof(VertexPNT1); mesh.VertexElements = VertexPNT1.Elements; } else if (VertexElement.Compare(elements, VertexPT1.Elements)) { buffer = BuildVertexPT1Data(positions, texVtx, texIdx, faces); mesh.VertexSize = sizeof(VertexPT1); mesh.VertexElements = VertexPT1.Elements; } else if (VertexElement.Compare(elements, VertexPN.Elements)) { buffer = BuildVertexPNData(positions, normals, faces); mesh.VertexSize = sizeof(VertexPN); mesh.VertexElements = VertexPN.Elements; } else if (VertexElement.Compare(elements, VertexP.Elements)) { buffer = BuildVertexPData(positions, faces); mesh.VertexSize = sizeof(VertexP); mesh.VertexElements = VertexP.Elements; } if (buffer != null) { if (mesh.VertexSize != 0) { mesh.VertexCount = buffer.Length / mesh.VertexSize; } fixed (byte* src = &buffer[0]) { mesh.SetData(src, buffer.Length); } } } }
private void ParseBeatProperties(IXmlNode node, Beat beat) { bool isWhammy = false; BendPoint whammyOrigin = null; int? whammyMiddleValue = null; int? whammyMiddleOffset1 = null; int? whammyMiddleOffset2 = null; BendPoint whammyDestination = null; node.IterateChildren(c => { if (c.NodeType == XmlNodeType.Element) { switch (c.LocalName) { case "Property": var name = c.Attributes.Get("name").Value; switch (name) { case "Brush": if (GetValue(FindChildElement(c, "Direction")) == "Up") { beat.BrushType = BrushType.BrushUp; } else { beat.BrushType = BrushType.BrushDown; } break; // TODO: brush duration case "PickStroke": if (GetValue(FindChildElement(c, "Direction")) == "Up") { beat.PickStroke = PickStrokeType.Up; } else { beat.PickStroke = PickStrokeType.Down; } break; // TODO: brush duration case "Slapped": if (FindChildElement(c, "Enable") != null) beat.Slap = true; break; case "Popped": if (FindChildElement(c, "Enable") != null) beat.Pop = true; break; case "VibratoWTremBar": switch (GetValue(FindChildElement(c, "Strength"))) { case "Wide": beat.Vibrato = VibratoType.Wide; break; case "Slight": beat.Vibrato = VibratoType.Slight; break; } break; case "WhammyBar": isWhammy = true; break; case "WhammyBarExtend": case "WhammyBarOriginValue": if (whammyOrigin == null) whammyOrigin = new BendPoint(); whammyOrigin.Value = ToBendValue(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "WhammyBarOriginOffset": if (whammyOrigin == null) whammyOrigin = new BendPoint(); whammyOrigin.Offset = ToBendOffset(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "WhammyBarMiddleValue": whammyMiddleValue = ToBendValue(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "WhammyBarMiddleOffset1": whammyMiddleOffset1 = ToBendOffset(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "WhammyBarMiddleOffset2": whammyMiddleOffset2 = ToBendOffset(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "WhammyBarDestinationValue": if (whammyDestination == null) whammyDestination = new BendPoint(BendPoint.MaxPosition); whammyDestination.Value = ToBendValue(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "WhammyBarDestinationOffset": if (whammyDestination == null) whammyDestination = new BendPoint(); whammyDestination.Offset = ToBendOffset(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; } break; } } }); if (isWhammy) { if (whammyOrigin == null) whammyOrigin = new BendPoint(); if (whammyDestination == null) whammyDestination = new BendPoint(BendPoint.MaxPosition); var whammy = new FastList<BendPoint>(); whammy.Add(whammyOrigin); if (whammyMiddleOffset1 != null && whammyMiddleValue != null) { whammy.Add(new BendPoint(whammyMiddleOffset1.Value, whammyMiddleValue.Value)); } if (whammyMiddleOffset2 != null && whammyMiddleValue != null) { whammy.Add(new BendPoint(whammyMiddleOffset2.Value, whammyMiddleValue.Value)); } if (whammyMiddleOffset1 == null && whammyMiddleOffset2 == null && whammyMiddleValue != null) { whammy.Add(new BendPoint(BendPoint.MaxPosition / 2, whammyMiddleValue.Value)); } whammy.Add(whammyDestination); beat.WhammyBarPoints = whammy; } }
private void ParseNoteProperties(IXmlNode node, Note note, string noteId) { bool isBended = false; BendPoint bendOrigin = null; int? bendMiddleValue = null; int? bendMiddleOffset1 = null; int? bendMiddleOffset2 = null; BendPoint bendDestination = null; node.IterateChildren(c => { if (c.NodeType == XmlNodeType.Element) { switch (c.LocalName) { case "Property": var name = c.Attributes.Get("name").Value; switch (name) { case "String": note.String = Std.ParseInt(GetValue(FindChildElement(c, "String"))) + 1; break; case "Fret": note.Fret = Std.ParseInt(GetValue(FindChildElement(c, "Fret"))); break; case "Tapped": _tappedNotes[noteId] = true; break; case "HarmonicType": var htype = FindChildElement(c, "HType"); if (htype != null) { switch (GetValue(htype)) { case "NoHarmonic": note.HarmonicType = HarmonicType.None; break; case "Natural": note.HarmonicType = HarmonicType.Natural; break; case "Artificial": note.HarmonicType = HarmonicType.Artificial; break; case "Pinch": note.HarmonicType = HarmonicType.Pinch; break; case "Tap": note.HarmonicType = HarmonicType.Tap; break; case "Semi": note.HarmonicType = HarmonicType.Semi; break; case "Feedback": note.HarmonicType = HarmonicType.Feedback; break; } } break; case "HarmonicFret": var hfret = FindChildElement(c, "HFret"); if (hfret != null) { note.HarmonicValue = Std.ParseFloat(GetValue(hfret)); } break; case "Muted": if (FindChildElement(c, "Enable") != null) note.IsDead = true; break; case "PalmMuted": if (FindChildElement(c, "Enable") != null) note.IsPalmMute = true; break; // case "Element": // case "Variation": // case "Tone": case "Octave": note.Octave = Std.ParseInt(GetValue(FindChildElement(c, "Number"))) - 1; break; case "Tone": note.Tone = Std.ParseInt(GetValue(FindChildElement(c, "Step"))); break; case "Bended": isBended = true; break; case "BendOriginValue": if (bendOrigin == null) bendOrigin = new BendPoint(); bendOrigin.Value = ToBendValue(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "BendOriginOffset": if (bendOrigin == null) bendOrigin = new BendPoint(); bendOrigin.Offset = ToBendOffset(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "BendMiddleValue": bendMiddleValue = ToBendValue(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "BendMiddleOffset1": bendMiddleOffset1 = ToBendOffset(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "BendMiddleOffset2": bendMiddleOffset2 = ToBendOffset(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "BendDestinationValue": if (bendDestination == null) bendDestination = new BendPoint(BendPoint.MaxPosition); // NOTE: If we directly cast the expression of value to (int) it is 3 instead of 4, strange compiler // optimizations happening here: // (int)(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))* BendPointValueFactor) => (int)(100f * 0.04f) => 3 // (Std.ParseFloat(GetValue(FindChildElement(c, "Float")))* BendPointValueFactor) => (100f * 0.04f) => 4.0 bendDestination.Value = ToBendValue(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "BendDestinationOffset": if (bendDestination == null) bendDestination = new BendPoint(); bendDestination.Offset = ToBendOffset(Std.ParseFloat(GetValue(FindChildElement(c, "Float")))); break; case "HopoOrigin": if (FindChildElement(c, "Enable") != null) note.IsHammerPullOrigin = true; break; case "HopoDestination": // NOTE: gets automatically calculated // if (FindChildElement(node, "Enable") != null) // note.isHammerPullDestination = true; break; case "Slide": var slideFlags = Std.ParseInt(GetValue(FindChildElement(c, "Flags"))); if ((slideFlags & 0x01) != 0) note.SlideType = SlideType.Shift; if ((slideFlags & 0x02) != 0) note.SlideType = SlideType.Legato; if ((slideFlags & 0x04) != 0) note.SlideType = SlideType.OutDown; if ((slideFlags & 0x08) != 0) note.SlideType = SlideType.OutUp; if ((slideFlags & 0x10) != 0) note.SlideType = SlideType.IntoFromBelow; if ((slideFlags & 0x20) != 0) note.SlideType = SlideType.IntoFromAbove; break; } break; } } }); if (isBended) { if (bendOrigin == null) bendOrigin = new BendPoint(); if (bendDestination == null) bendDestination = new BendPoint(BendPoint.MaxPosition); var bend = new FastList<BendPoint>(); bend.Add(bendOrigin); if (bendMiddleOffset1 != null && bendMiddleValue != null) { bend.Add(new BendPoint(bendMiddleOffset1.Value, bendMiddleValue.Value)); } if (bendMiddleOffset2 != null && bendMiddleValue != null) { bend.Add(new BendPoint(bendMiddleOffset2.Value, bendMiddleValue.Value)); } if (bendMiddleOffset1 == null && bendMiddleOffset2 == null && bendMiddleValue != null) { bend.Add(new BendPoint(BendPoint.MaxPosition / 2, bendMiddleValue.Value)); } bend.Add(bendDestination); note.BendPoints = bend; } }
/// <summary> /// Calls <see cref="Texture.OnDestroyed"/> for all children of the specified texture /// </summary> /// <param name="parentTexture">Specified parent texture</param> /// <returns>A list of the children textures which were destroyed</returns> private FastList<Texture> DestroyChildrenTextures(Texture parentTexture) { var fastList = new FastList<Texture>(); foreach (var resource in GraphicsDevice.Resources) { var texture = resource as Texture; if (texture != null && texture.ParentTexture == parentTexture) { texture.OnDestroyed(); fastList.Add(texture); } } return fastList; }
private float LayoutAndRenderScoreInfo(float x, float y) { HeaderFooterElements flags = Renderer.Settings.Layout.Get("hideInfo", false) ? HeaderFooterElements.None : HeaderFooterElements.All; var score = Renderer.Score; var scale = Scale; var canvas = Renderer.Canvas; var res = Renderer.RenderingResources; var glyphs = new FastList<TextGlyph>(); string str; if (!string.IsNullOrEmpty(score.Title) && (flags & HeaderFooterElements.Title) != 0) { glyphs.Add(new TextGlyph(Width / 2f, y, score.Title, res.TitleFont, TextAlign.Center)); y += (35 * scale); } if (!string.IsNullOrEmpty(score.SubTitle) && (flags & HeaderFooterElements.SubTitle) != 0) { glyphs.Add(new TextGlyph(Width / 2f, y, score.SubTitle, res.SubTitleFont, TextAlign.Center)); y += (20 * scale); } if (!string.IsNullOrEmpty(score.Artist) && (flags & HeaderFooterElements.Artist) != 0) { glyphs.Add(new TextGlyph(Width / 2f, y, score.Artist, res.SubTitleFont, TextAlign.Center)); y += (20 * scale); } if (!string.IsNullOrEmpty(score.Album) && (flags & HeaderFooterElements.Album) != 0) { glyphs.Add(new TextGlyph(Width / 2f, y, score.Album, res.SubTitleFont, TextAlign.Center)); y += (20 * scale); } if (!string.IsNullOrEmpty(score.Music) && score.Music == score.Words && (flags & HeaderFooterElements.WordsAndMusic) != 0) { glyphs.Add(new TextGlyph(Width / 2f, y, "Music and Words by " + score.Words, res.WordsFont, TextAlign.Center)); y += (20 * scale); } else { if (!string.IsNullOrEmpty(score.Music) && (flags & HeaderFooterElements.Music) != 0) { glyphs.Add(new TextGlyph(Width - PagePadding[2], y, "Music by " + score.Music, res.WordsFont, TextAlign.Right)); } if (!string.IsNullOrEmpty(score.Words) && (flags & HeaderFooterElements.Words) != 0) { glyphs.Add(new TextGlyph(x, y, "Words by " + score.Music, res.WordsFont, TextAlign.Left)); } y += (20 * scale); } y += (20 * scale); // tuning info if (Renderer.Tracks.Length == 1 && !Renderer.Tracks[0].IsPercussion) { var tuning = Tuning.FindTuning(Renderer.Tracks[0].Tuning); if (tuning != null) { // Name glyphs.Add(new TextGlyph(x, y, tuning.Name, res.EffectFont, TextAlign.Left)); y += (15 * scale); if (!tuning.IsStandard) { // Strings var stringsPerColumn = (int)Math.Ceiling(Renderer.Tracks[0].Tuning.Length / 2.0); var currentX = x; var currentY = y; for (int i = 0, j = Renderer.Tracks[0].Tuning.Length; i < j; i++) { str = "(" + (i + 1) + ") = " + Tuning.GetTextForTuning(Renderer.Tracks[0].Tuning[i], false); glyphs.Add(new TextGlyph(currentX, currentY, str, res.EffectFont, TextAlign.Left)); currentY += (15 * scale); if (i == stringsPerColumn - 1) { currentY = y; currentX += (43 * scale); } } y += (stringsPerColumn * (15 * scale)); } } } y += 25 * scale; canvas.BeginRender(Width, y); canvas.Color = res.ScoreInfoColor; canvas.TextAlign = TextAlign.Center; for (int i = 0; i < glyphs.Count; i++) { glyphs[i].Paint(0, 0, canvas); } var result = canvas.EndRender(); OnPartialRenderFinished(new RenderFinishedEventArgs { Width = Width, Height = y, RenderResult = result, TotalWidth = Width, TotalHeight = y }); return y; }
public override void DoLayoutAndRender() { if (Renderer.Settings.Staves.Count == 0) return; var score = Renderer.Score; var canvas = Renderer.Canvas; var startIndex = Renderer.Settings.Layout.Get("start", 1); startIndex--; // map to array index startIndex = Math.Min(score.MasterBars.Count - 1, Math.Max(0, startIndex)); var currentBarIndex = startIndex; var endBarIndex = Renderer.Settings.Layout.Get("count", score.MasterBars.Count); endBarIndex = startIndex + endBarIndex - 1; // map count to array index endBarIndex = Math.Min(score.MasterBars.Count - 1, Math.Max(0, endBarIndex)); _group = CreateEmptyStaveGroup(); _group.X = PagePadding[0]; _group.Y = PagePadding[1]; var countPerPartial = Renderer.Settings.Layout.Get("countPerPartial", 10); var partials = new FastList<HorizontalScreenLayoutPartialInfo>(); var currentPartial = new HorizontalScreenLayoutPartialInfo(); while (currentBarIndex <= endBarIndex) { var result = _group.AddBars(Renderer.Tracks, currentBarIndex); // if we detect that the new renderer is linked to the previous // renderer, we need to put it into the previous partial var renderer = _group.GetBarRenderer(currentBarIndex); if (currentPartial.MasterBars.Count == 0 && result.IsLinkedToPrevious && partials.Count > 0) { var previousPartial = partials[partials.Count - 1]; previousPartial.MasterBars.Add(score.MasterBars[currentBarIndex]); previousPartial.Width += renderer.Width; } else { currentPartial.MasterBars.Add(score.MasterBars[currentBarIndex]); currentPartial.Width += renderer.Width; // no targetPartial here because previous partials already handled this code if (currentPartial.MasterBars.Count >= countPerPartial) { if (partials.Count == 0) { currentPartial.Width += _group.X + _group.AccoladeSpacing; } partials.Add(currentPartial); currentPartial = new HorizontalScreenLayoutPartialInfo(); } } currentBarIndex++; } // don't miss the last partial if not empty if (currentPartial.MasterBars.Count >= 0) { if (partials.Count == 0) { currentPartial.Width += _group.X + _group.AccoladeSpacing; } partials.Add(currentPartial); } _group.FinalizeGroup(this); Height = _group.Y + _group.Height + PagePadding[3]; Width = _group.X + _group.Width + PagePadding[2]; // TODO: Find a good way to render the score partwise // we need to precalculate the final height somehow //canvas.BeginRender(Width, Height); //canvas.Color = Renderer.RenderingResources.MainGlyphColor; //canvas.TextAlign = TextAlign.Left; //_group.Paint(0, 0, Renderer.Canvas); //var result = canvas.EndRender(); //OnPartialRenderFinished(new RenderFinishedEventArgs //{ // TotalWidth = Width, // TotalHeight = y, // Width = Width, // Height = Height, // RenderResult = result //}); currentBarIndex = 0; for (var i = 0; i < partials.Count; i++) { var partial = partials[i]; canvas.BeginRender(partial.Width, Height); canvas.Color = Renderer.RenderingResources.MainGlyphColor; canvas.TextAlign = TextAlign.Left; var renderer = _group.GetBarRenderer(partial.MasterBars[0].Index); var renderX = renderer.X + _group.AccoladeSpacing; if (i == 0) { renderX -= _group.X + _group.AccoladeSpacing; } _group.PaintPartial(-renderX, _group.Y, Renderer.Canvas, currentBarIndex, partial.MasterBars.Count); var result = canvas.EndRender(); OnPartialRenderFinished(new RenderFinishedEventArgs { TotalWidth = Width, TotalHeight = Height, Width = partial.Width, Height = Height, RenderResult = result }); currentBarIndex += partial.MasterBars.Count; } }
/// <summary> /// Finds a path and outputs it to <c>OutputPath</c>. Note: OutputPath is unpredictably changed. /// </summary> /// <returns> /// Returns <c>true</c> if path was found and necessary, <c>false</c> if path to End is impossible or not found. /// </returns> /// <param name="startNode">Start node.</param> /// <param name="endNode">End node.</param> /// <param name="OutputPath">Return path.</param> public static bool FindPath(GridNode startNode, GridNode endNode, FastList<GridNode> OutputPath) { #region Broadphase and Preperation if (endNode.Unwalkable) { return false; } if (startNode.Unwalkable) { return false; } if (true) { #region Obstruction Test //Tests if there is a direct path. If there is, no need to run AStar. x0 = startNode.gridX; y0 = startNode.gridY; x1 = endNode.gridX; y1 = endNode.gridY; if (y1 > y0) compare1 = y1 - y0; else compare1 = y0 - y1; if (x1 > x0) compare2 = x1 - x0; else compare2 = x0 - x1; steep = compare1 > compare2; if (steep) { t = x0; // swap x0 and y0 x0 = y0; y0 = t; t = x1; // swap x1 and y1 x1 = y1; y1 = t; } if (x0 > x1) { t = x0; // swap x0 and x1 x0 = x1; x1 = t; t = y0; // swap y0 and y1 y0 = y1; y1 = t; } dx = x1 - x0; dy = (y1 - y0); if (dy < 0) dy = -dy; error = dx / 2; ystep = (y0 < y1) ? 1 : -1; y = y0; for (x = x0; x <= x1; x++) { retX = (steep ? y : x); retY = (steep ? x : y); if (GridManager.Grid [retX * GridManager.NodeCount + retY].Unwalkable) { break; } else if (x == x1) { OutputPath.FastClear (); OutputPath.Add (startNode); OutputPath.Add (endNode); return true; } error = error - dy; if (error < 0) { y += ystep; error += dx; } } #endregion } GridHeap.FastClear (); GridClosedSet.FastClear (); #endregion #region AStar Algorithm GridHeap.Add (startNode); GridNode.HeuristicTargetX = endNode.gridX; GridNode.HeuristicTargetY = endNode.gridY; while (GridHeap.Count > 0) { currentNode = GridHeap.RemoveFirst (); GridClosedSet.Add (currentNode); if (currentNode.gridIndex == endNode.gridIndex) { OutputPath.FastClear (); //Retraces the path then outputs it into OutputPath //Also Simplifies the path oldNode = endNode; currentNode = endNode.parent; oldX = int.MaxValue; oldY = int.MaxValue; StartNodeIndex = startNode.gridIndex; //if (!endNode.Obstructed) OutputPath.Add (endNode); while (oldNode.gridIndex != StartNodeIndex) { newX = currentNode.gridX - oldNode.gridX; newY = currentNode.gridY - oldNode.gridY; if ((newX != oldX || newY != oldY)) { OutputPath.Add (oldNode); oldX = newX; oldY = newY; } oldNode = currentNode; currentNode = currentNode.parent; } OutputPath.Add (startNode); OutputPath.Reverse (); return true; } for (i = 0; i < 8; i++) { neighbor = currentNode.NeighborNodes [i]; if (neighbor == null|| neighbor.Unwalkable || GridClosedSet.Contains (neighbor)) { continue; } newMovementCostToNeighbor = currentNode.gCost + (currentNode.NeighborDiagnal [i] ? 141 : 100); if (!GridHeap.Contains (neighbor)) { neighbor.gCost = newMovementCostToNeighbor; //Optimized heuristic calculation neighbor.CalculateHeurustic (); neighbor.parent = currentNode; GridHeap.Add (neighbor); } else if (newMovementCostToNeighbor < neighbor.gCost) { neighbor.gCost = newMovementCostToNeighbor; //Optimized heuristic calculation neighbor.CalculateHeurustic (); neighbor.parent = currentNode; GridHeap.UpdateItem (neighbor); } } } #endregion return false; }
public void SetTracks(dynamic tracksData, bool render = true) { FastList<int> tracks = new FastList<int>(); // decode string if (JsTypeOf(tracksData) == JsTypes.@string) { try { tracksData = JSON.parse((string)tracksData); } catch { tracksData = new[] { 0 }; } } // decode array if (JsTypeOf(tracksData) == JsTypes.number) { tracks.Add((int)tracksData); } else if (tracksData.length) { for (var i = 0; i < tracksData.length; i++) { int value; if (JsTypeOf(tracksData[i]) == JsTypes.number) { value = (int)tracksData[i]; } else { value = Std.ParseInt(tracksData[i].ToString()); } if (value >= 0) { tracks.Add(value); } } } TrackIndexes = tracks.ToArray(); if (render) { Render(); } }
public void OnSaveData() { Debug.Log("Saving Mod Data."); var data = new FastList<byte>(); GenerateUniqueId(); Debug.Log("UniqueID: " + UniqueId); var uniqueIdBytes = BitConverter.GetBytes(UniqueId); foreach (var uniqueIdByte in uniqueIdBytes) { data.Add(uniqueIdByte); } var dataToSave = data.ToArray(); SerializableData.SaveData(DataId, dataToSave); var filepath = Path.Combine(Application.dataPath, "trafficManagerSave_" + UniqueId + ".xml"); Debug.Log("Save Location: " + filepath); var configuration = new Configuration(); for (var i = 0; i < 32768; i++) { if (TrafficPriority.PrioritySegments.ContainsKey(i)) { if (TrafficPriority.PrioritySegments[i].Node1 != 0) { configuration.PrioritySegments.Add(new[] { TrafficPriority.PrioritySegments[i].Node1, i, (int)TrafficPriority.PrioritySegments[i].Instance1.Type }); } if (TrafficPriority.PrioritySegments[i].Node2 != 0) { configuration.PrioritySegments.Add(new[] { TrafficPriority.PrioritySegments[i].Node2, i, (int)TrafficPriority.PrioritySegments[i].Instance2.Type }); } } if (CustomRoadAI.NodeDictionary.ContainsKey((ushort) i)) { var nodeDict = CustomRoadAI.NodeDictionary[(ushort)i]; configuration.NodeDictionary.Add(new[] {nodeDict.NodeId, Convert.ToInt32(nodeDict.ManualTrafficLights), Convert.ToInt32(nodeDict.TimedTrafficLights), Convert.ToInt32(nodeDict.TimedTrafficLightsActive)}); } if (TrafficLightsManual.ManualSegments.ContainsKey(i)) { if (TrafficLightsManual.ManualSegments[i].Node1 != 0) { var manualSegment = TrafficLightsManual.ManualSegments[i].Instance1; configuration.ManualSegments.Add(new[] { manualSegment.Node, manualSegment.Segment, (int)manualSegment.CurrentMode, (int)manualSegment.LightLeft, (int)manualSegment.LightMain, (int)manualSegment.LightRight, (int)manualSegment.LightPedestrian, (int)manualSegment.LastChange, (int)manualSegment.LastChangeFrame, Convert.ToInt32(manualSegment.PedestrianEnabled) }); } if (TrafficLightsManual.ManualSegments[i].Node2 != 0) { var manualSegment = TrafficLightsManual.ManualSegments[i].Instance2; configuration.ManualSegments.Add(new[] { manualSegment.Node, manualSegment.Segment, (int)manualSegment.CurrentMode, (int)manualSegment.LightLeft, (int)manualSegment.LightMain, (int)manualSegment.LightRight, (int)manualSegment.LightPedestrian, (int)manualSegment.LastChange, (int)manualSegment.LastChangeFrame, Convert.ToInt32(manualSegment.PedestrianEnabled) }); } } if (!TrafficLightsTimed.TimedScripts.ContainsKey((ushort) i)) continue; var timedNode = TrafficLightsTimed.GetTimedLight((ushort) i); configuration.TimedNodes.Add(new[] { timedNode.NodeId, timedNode.CurrentStep, timedNode.NumSteps(), Convert.ToInt32(timedNode.IsStarted())}); var nodeGroup = new ushort[timedNode.NodeGroup.Count]; for (var j = 0; j < timedNode.NodeGroup.Count; j++) { nodeGroup[j] = timedNode.NodeGroup[j]; } configuration.TimedNodeGroups.Add(nodeGroup); for (var j = 0; j < timedNode.NumSteps(); j++) { configuration.TimedNodeSteps.Add(new[] { timedNode.Steps[j].NumSteps, timedNode.Steps[j].Segments.Count }); for (var k = 0; k < timedNode.Steps[j].Segments.Count; k++) { configuration.TimedNodeStepSegments.Add(new[] { (int)timedNode.Steps[j].LightLeft[k], (int)timedNode.Steps[j].LightMain[k], (int)timedNode.Steps[j].LightRight[k], (int)timedNode.Steps[j].LightPedestrian[k], }); } } } for (var i = 0; i < Singleton<NetManager>.instance.m_nodes.m_buffer.Length; i++) { var nodeFlags = Singleton<NetManager>.instance.m_nodes.m_buffer[i].m_flags; if (nodeFlags == 0) continue; if (Singleton<NetManager>.instance.m_nodes.m_buffer[i].Info.m_class.m_service != ItemClass.Service.Road) continue; configuration.NodeTrafficLights += Convert.ToInt16((nodeFlags & NetNode.Flags.TrafficLights) != NetNode.Flags.None); configuration.NodeCrosswalk += Convert.ToInt16((nodeFlags & NetNode.Flags.Junction) != NetNode.Flags.None); } for (var i = 0; i < Singleton<NetManager>.instance.m_lanes.m_buffer.Length; i++) { var laneSegment = Singleton<NetManager>.instance.m_lanes.m_buffer[i].m_segment; if (TrafficPriority.PrioritySegments.ContainsKey(laneSegment)) { configuration.LaneFlags += i + ":" + Singleton<NetManager>.instance.m_lanes.m_buffer[i].m_flags + ","; } } Configuration.SaveConfigurationToFile(filepath, configuration); }
public override void FillParameterCollections(FastList<ParameterCollection> parameterCollections) { var material = Material; if (material != null && material.Parameters != null) { parameterCollections.Add(material.Parameters); } var modelInstance = RenderModel.ModelComponent; if (modelInstance != null && modelInstance.Parameters != null) { parameterCollections.Add(modelInstance.Parameters); } // TODO: Should we add RenderMesh.Parameters before ModelComponent.Parameters to allow user overiddes at component level? parameterCollections.Add(parameters); }
/// <summary> /// BuildBlendTree is called every frame from the animation system when the <see cref="AnimationComponent"/> needs to be evaluated /// It overrides the default behavior of the <see cref="AnimationComponent"/> by setting a custom blend tree /// </summary> /// <param name="blendStack">The stack of animation operations to be blended</param> public void BuildBlendTree(FastList<AnimationOperation> blendStack) { switch (state) { case AnimationState.Walking: { // Note! The tree is laid out as a stack and has to be flattened before returning it to the animation system! blendStack.Add(AnimationOperation.NewPush(animEvaluatorWalkLerp1, TimeSpan.FromTicks((long)(currentTime * animationClipWalkLerp1.Duration.Ticks)))); blendStack.Add(AnimationOperation.NewPush(animEvaluatorWalkLerp2, TimeSpan.FromTicks((long)(currentTime * animationClipWalkLerp2.Duration.Ticks)))); blendStack.Add(AnimationOperation.NewBlend(AnimationBlendOperation.LinearBlend, walkLerpFactor)); } break; case AnimationState.Jumping: { blendStack.Add(AnimationOperation.NewPush(animEvaluatorJumpStart, TimeSpan.FromTicks((long)(currentTime * AnimationJumpStart.Duration.Ticks)))); } break; case AnimationState.Airborne: { blendStack.Add(AnimationOperation.NewPush(animEvaluatorJumpMid, TimeSpan.FromTicks((long)(currentTime * AnimationJumpMid.Duration.Ticks)))); } break; case AnimationState.Landing: { blendStack.Add(AnimationOperation.NewPush(animEvaluatorJumpEnd, TimeSpan.FromTicks((long)(currentTime * AnimationJumpEnd.Duration.Ticks)))); } break; } }
ModelObject ParseMeshData(XmlReader xml) { Vector3[] positions = null; Vector3[] normals = null; MeshFace[] faces = null; //Vector2[] tex1 = null; Vector2[] texVtx = null; TexIndex[] texIdx = null; ModelObject result; result.ParentId = -1; result.Mesh = null; result.LocalTransform = Matrix.Identity; result.ParentName = string.Empty; result.Index = -1; int depth = xml.Depth; while (xml.Read() && xml.Depth > depth) { if (xml.IsStartElement() && !xml.IsEmptyElement) { switch (xml.Name) { case "Parent": result.ParentId = int.Parse(xml.GetAttribute("ID")); result.ParentName = xml.GetAttribute("Name"); break; case "WorldTM": result.LocalTransform = ParseMatrix(xml); break; case "Vertex": positions = ParseVector3Array(xml); break; case "VertexNormal": normals = ParseVector3Array(xml); for (int i = 0; i < normals.Length; i++) { normals[i].Normalize(); } break; case "TriIndex": faces = ParseMeshFaces(xml); break; case "TexVertex": texVtx = ParseVector2Array(xml); break; case "TexIndex": texIdx = new TexIndex[faces.Length]; ParseTexIndex(xml, texIdx); break; } } } Dictionary<string, int> table = new Dictionary<string, int>(faces.Length * 3); FastList<VertexPNT1> vertices = new FastList<VertexPNT1>(faces.Length * 3); for (int i = 0; i < faces.Length; i++) { int index; VertexPNT1 vtx; vtx.pos = positions[faces[i].IndexA]; vtx.n = normals[faces[i].IndexA]; vtx.u = texVtx[texIdx[i].a].X; vtx.v = texVtx[texIdx[i].a].Y; string desc = vtx.ToString(); if (!table.TryGetValue(desc, out index)) { table.Add(desc, vertices.Count); faces[i].IndexA = vertices.Count; vertices.Add(ref vtx); } else { faces[i].IndexA = index; } // ========================================= vtx.pos = positions[faces[i].IndexB]; vtx.n = normals[faces[i].IndexB]; vtx.u = texVtx[texIdx[i].b].X; vtx.v = texVtx[texIdx[i].b].Y; desc = vtx.ToString(); if (!table.TryGetValue(desc, out index)) { table.Add(desc, vertices.Count); faces[i].IndexB = vertices.Count; vertices.Add(ref vtx); } else { faces[i].IndexB = index; } // ========================================= vtx.pos = positions[faces[i].IndexC]; vtx.n = normals[faces[i].IndexC]; vtx.u = texVtx[texIdx[i].c].X; vtx.v = texVtx[texIdx[i].c].Y; desc = vtx.ToString(); if (!table.TryGetValue(desc, out index)) { table.Add(desc, vertices.Count); faces[i].IndexC = vertices.Count; vertices.Add(ref vtx); } else { faces[i].IndexC = index; } } MeshData data = new MeshData((RenderSystem)null); data.Faces = faces; data.VertexElements = VertexPNT1.Elements; data.VertexSize = VertexPNT1.Size; data.VertexCount = vertices.Count; fixed (VertexPNT1* src = &vertices.Elements[0]) { data.SetData(src, VertexPNT1.Size * vertices.Count); } result.Mesh = data; return result; }
void SetNodeMarkers(ushort nodeId, FastList<NodeLaneMarker> nodeMarkers) { NetNode node = NetManager.instance.m_nodes.m_buffer[nodeId]; int offsetMultiplier = node.CountSegments() <= 2 ? 3 : 1; ushort segmentId = node.m_segment0; for (int i = 0; i < 8 && segmentId != 0; i++) { NetSegment segment = NetManager.instance.m_segments.m_buffer[segmentId]; bool isEndNode = segment.m_endNode == nodeId; Vector3 offset = segment.FindDirection(segmentId, nodeId) * offsetMultiplier; NetInfo.Lane[] lanes = segment.Info.m_lanes; uint laneId = segment.m_lanes; for (int j = 0; j < lanes.Length && laneId != 0; j++) { if ((lanes[j].m_laneType & NetInfo.LaneType.Vehicle) == NetInfo.LaneType.Vehicle) { Vector3 pos = Vector3.zero; NetInfo.Direction laneDir = ((segment.m_flags & NetSegment.Flags.Invert) == NetSegment.Flags.None) ? lanes[j].m_finalDirection : NetInfo.InvertDirection(lanes[j].m_finalDirection); bool isSource = false; if (isEndNode) { if ((laneDir & (NetInfo.Direction.Forward | NetInfo.Direction.Avoid)) == NetInfo.Direction.Forward) isSource = true; pos = NetManager.instance.m_lanes.m_buffer[laneId].m_bezier.d; } else { if ((laneDir & (NetInfo.Direction.Backward | NetInfo.Direction.Avoid)) == NetInfo.Direction.Backward) isSource = true; pos = NetManager.instance.m_lanes.m_buffer[laneId].m_bezier.a; } nodeMarkers.Add(new NodeLaneMarker() { m_lane = laneId, m_node = nodeId, m_position = pos + offset, m_color = colors[nodeMarkers.m_size], m_isSource = isSource, }); } laneId = NetManager.instance.m_lanes.m_buffer[laneId].m_nextLane; } segmentId = segment.GetRightSegment(nodeId); if (segmentId == node.m_segment0) segmentId = 0; } for (int i = 0; i < nodeMarkers.m_size; i++) { if (!nodeMarkers.m_buffer[i].m_isSource) continue; uint[] connections = RoadManager.GetLaneConnections(nodeMarkers.m_buffer[i].m_lane); if (connections == null || connections.Length == 0) continue; for (int j = 0; j < nodeMarkers.m_size; j++) { if (nodeMarkers.m_buffer[j].m_isSource) continue; if (connections.Contains(nodeMarkers.m_buffer[j].m_lane)) nodeMarkers.m_buffer[i].m_connections.Add(nodeMarkers.m_buffer[j]); } } }
private float LayoutAndRenderScore(float x, float y) { var score = Renderer.Score; var canvas = Renderer.Canvas; var startIndex = Renderer.Settings.Layout.Get("start", 1); startIndex--; // map to array index startIndex = Math.Min(score.MasterBars.Count - 1, Math.Max(0, startIndex)); var currentBarIndex = startIndex; var endBarIndex = Renderer.Settings.Layout.Get("count", score.MasterBars.Count); if (endBarIndex < 0) endBarIndex = score.MasterBars.Count; endBarIndex = startIndex + endBarIndex - 1; // map count to array index endBarIndex = Math.Min(score.MasterBars.Count - 1, Math.Max(0, endBarIndex)); _groups = new FastList<StaveGroup>(); if (Renderer.Settings.Staves.Count > 0) { while (currentBarIndex <= endBarIndex) { // create group and align set proper coordinates var group = CreateStaveGroup(currentBarIndex, endBarIndex); _groups.Add(group); group.X = x; group.Y = y; // finalize group (sizing etc). FitGroup(group); group.FinalizeGroup(this); // paint into canvas var height = group.Height + (GroupSpacing * Scale); canvas.BeginRender(Width, height); Renderer.Canvas.Color = Renderer.RenderingResources.MainGlyphColor; Renderer.Canvas.TextAlign = TextAlign.Left; // NOTE: we use this negation trick to make the group paint itself to 0/0 coordinates // since we use partial drawing group.Paint(0, -group.Y, canvas); // calculate coordinates for next group y += height; currentBarIndex = group.LastBarIndex + 1; var result = canvas.EndRender(); OnPartialRenderFinished(new RenderFinishedEventArgs { TotalWidth = Width, TotalHeight = y, Width = Width, Height = height, RenderResult = result }); } } return y; }