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 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(); } }
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(); }
public void LoadSf2(IReadable input) { Reset(); Logger.Debug("Reading SF2"); var sf = new SoundFont(); sf.Load(input); Logger.Debug("Building patchbank"); Name = sf.Info.BankName; Comments = sf.Info.Comments; //load samples foreach (var sampleHeader in sf.Presets.SampleHeaders) { _assets.SampleAssets.Add(new SampleDataAsset(sampleHeader, sf.SampleData)); } //create instrument regions first var sfinsts = ReadSf2Instruments(sf.Presets.Instruments); //load each patch foreach (var p in sf.Presets.PresetHeaders) { Generator[] globalGens = null; int i; if (p.Zones[0].Generators.Length == 0 || p.Zones[0].Generators[p.Zones[0].Generators.Length - 1].GeneratorType != GeneratorEnum.Instrument) { globalGens = p.Zones[0].Generators; i = 1; } else { i = 0; } var regionList = new FastList<Sf2Region>(); while (i < p.Zones.Length) { byte presetLoKey = 0; byte presetHiKey = 127; byte presetLoVel = 0; byte presetHiVel = 127; if (p.Zones[i].Generators[0].GeneratorType == GeneratorEnum.KeyRange) { if (TypeUtils.IsLittleEndian) { presetLoKey = TypeUtils.ToUInt8(p.Zones[i].Generators[0].AmountInt16 & 0xFF); presetHiKey = TypeUtils.ToUInt8((p.Zones[i].Generators[0].AmountInt16 >> 8) & 0xFF); } else { presetHiKey = TypeUtils.ToUInt8(p.Zones[i].Generators[0].AmountInt16 & 0xFF); presetLoKey = TypeUtils.ToUInt8((p.Zones[i].Generators[0].AmountInt16 >> 8) & 0xFF); } if (p.Zones[i].Generators.Length > 1 && p.Zones[i].Generators[1].GeneratorType == GeneratorEnum.VelocityRange) { if (TypeUtils.IsLittleEndian) { presetLoVel = TypeUtils.ToUInt8(p.Zones[i].Generators[1].AmountInt16 & 0xFF); presetHiVel = TypeUtils.ToUInt8((p.Zones[i].Generators[1].AmountInt16 >> 8) & 0xFF); } else { presetHiVel = TypeUtils.ToUInt8(p.Zones[i].Generators[1].AmountInt16 & 0xFF); presetLoVel = TypeUtils.ToUInt8((p.Zones[i].Generators[1].AmountInt16 >> 8) & 0xFF); } } } else if (p.Zones[i].Generators[0].GeneratorType == GeneratorEnum.VelocityRange) { if (TypeUtils.IsLittleEndian) { presetLoVel = TypeUtils.ToUInt8(p.Zones[i].Generators[0].AmountInt16 & 0xFF); presetHiVel = TypeUtils.ToUInt8((p.Zones[i].Generators[0].AmountInt16 >> 8) & 0xFF); } else { presetHiVel = TypeUtils.ToUInt8(p.Zones[i].Generators[0].AmountInt16 & 0xFF); presetLoVel = TypeUtils.ToUInt8((p.Zones[i].Generators[0].AmountInt16 >> 8) & 0xFF); } } if (p.Zones[i].Generators[p.Zones[i].Generators.Length - 1].GeneratorType == GeneratorEnum.Instrument) { var insts = sfinsts[p.Zones[i].Generators[p.Zones[i].Generators.Length - 1].AmountInt16]; foreach (var inst in insts) { byte instLoKey; byte instHiKey; byte instLoVel; byte instHiVel; if (TypeUtils.IsLittleEndian) { instLoKey = TypeUtils.ToUInt8(inst.Generators[(int)GeneratorEnum.KeyRange] & 0xFF); instHiKey = TypeUtils.ToUInt8((inst.Generators[(int)GeneratorEnum.KeyRange] >> 8) & 0xFF); instLoVel = TypeUtils.ToUInt8(inst.Generators[(int)GeneratorEnum.VelocityRange] & 0xFF); instHiVel = TypeUtils.ToUInt8((inst.Generators[(int)GeneratorEnum.VelocityRange] >> 8) & 0xFF); } else { instHiKey = TypeUtils.ToUInt8(inst.Generators[(int)GeneratorEnum.KeyRange] & 0xFF); instLoKey = TypeUtils.ToUInt8((inst.Generators[(int)GeneratorEnum.KeyRange] >> 8) & 0xFF); instHiVel = TypeUtils.ToUInt8(inst.Generators[(int)GeneratorEnum.VelocityRange] & 0xFF); instLoVel = TypeUtils.ToUInt8((inst.Generators[(int)GeneratorEnum.VelocityRange] >> 8) & 0xFF); } if ((instLoKey <= presetHiKey && presetLoKey <= instHiKey) && (instLoVel <= presetHiVel && presetLoVel <= instHiVel)) { var r = new Sf2Region(); Std.ArrayCopy(inst.Generators, 0, r.Generators, 0, r.Generators.Length); ReadSf2Region(r, globalGens, p.Zones[i].Generators, true); regionList.Add(r); } } } i++; } var mp = new MultiPatch(p.Name); mp.LoadSf2(regionList.ToArray(), _assets); _assets.PatchAssets.Add(new PatchAsset(mp.Name, mp)); AssignPatchToBank(mp, p.BankNumber, p.PatchNumber, p.PatchNumber); } }
public static IReward[] XMLStringToActiveRewards(string xml) { FastList<IReward> rewards = new FastList<IReward> (); XmlDocument doc = new XmlDocument (); doc.LoadXml (xml); foreach (XmlNode rewardNode in doc.SelectNodes("boost")) { XmlAttributeCollection atts = rewardNode.Attributes; Boost b = new Boost(); b.ValueID = Data.StringToValueID(atts ["name"].Value); b.Value = float.Parse(atts ["value"].Value); if (atts ["endDate"] != null) { b.EndDate = DateTime.Parse (atts ["endDate"].Value); } b.Activate (); rewards.Add (b); } return rewards.ToArray (); }
public void FormatDetails() { FastList<UIComponent> comps = new FastList<UIComponent> (); comps.Add (m_challengeName); comps.Add (m_challengeDesc); comps.Add (m_challengeBreakdown); if (!m_challengeReward.text.Equals ("")) { comps.Add(m_challengeReward); } if (!m_challengePenalty.text.Equals ("")) { comps.Add (m_challengePenalty); } comps.Add (m_challengeDeadline); AutoSpace (comps.ToArray ()); }
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(); } }
public Selection(FastEnumerable <LSAgent> selectedAgents) { bufferAgents.FastClear(); selectedAgents.Enumerate(bufferAgents); this.AddAgents(bufferAgents.ToArray()); }
public void LoadSf2(IReadable input) { Reset(); Logger.Debug("PatchBank", "Reading SF2"); var sf = new SoundFont(); sf.Load(input); Logger.Debug("PatchBank", "Building patchbank"); Name = sf.Info.BankName; Comments = sf.Info.Comments; //load samples foreach (var sampleHeader in sf.Presets.SampleHeaders) { _assets.SampleAssets.Add(new SampleDataAsset(sampleHeader, sf.SampleData)); } //create instrument regions first var sfinsts = ReadSf2Instruments(sf.Presets.Instruments); //load each patch foreach (var p in sf.Presets.PresetHeaders) { Sf2.Generator[] globalGens = null; int i; if (p.Zones[0].Generators.Length == 0 || p.Zones[0].Generators[p.Zones[0].Generators.Length - 1].GeneratorType != GeneratorEnum.Instrument) { globalGens = p.Zones[0].Generators; i = 1; } else { i = 0; } var regionList = new FastList <Sf2Region>(); while (i < p.Zones.Length) { byte presetLoKey = 0; byte presetHiKey = 127; byte presetLoVel = 0; byte presetHiVel = 127; if (p.Zones[i].Generators[0].GeneratorType == GeneratorEnum.KeyRange) { presetLoKey = Platform.Platform.ToUInt8(p.Zones[i].Generators[0].AmountInt16 & 0xFF); presetHiKey = Platform.Platform.ToUInt8((p.Zones[i].Generators[0].AmountInt16 >> 8) & 0xFF); if (p.Zones[i].Generators.Length > 1 && p.Zones[i].Generators[1].GeneratorType == GeneratorEnum.VelocityRange) { presetLoVel = Platform.Platform.ToUInt8(p.Zones[i].Generators[1].AmountInt16 & 0xFF); presetHiVel = Platform.Platform.ToUInt8((p.Zones[i].Generators[1].AmountInt16 >> 8) & 0xFF); } } else if (p.Zones[i].Generators[0].GeneratorType == GeneratorEnum.VelocityRange) { presetLoVel = Platform.Platform.ToUInt8(p.Zones[i].Generators[0].AmountInt16 & 0xFF); presetHiVel = Platform.Platform.ToUInt8((p.Zones[i].Generators[0].AmountInt16 >> 8) & 0xFF); } if (p.Zones[i].Generators[p.Zones[i].Generators.Length - 1].GeneratorType == GeneratorEnum.Instrument) { var insts = sfinsts[p.Zones[i].Generators[p.Zones[i].Generators.Length - 1].AmountInt16]; foreach (var inst in insts) { byte instLoKey; byte instHiKey; byte instLoVel; byte instHiVel; instLoKey = Platform.Platform.ToUInt8(inst.Generators[(int)GeneratorEnum.KeyRange] & 0xFF); instHiKey = Platform.Platform.ToUInt8((inst.Generators[(int)GeneratorEnum.KeyRange] >> 8) & 0xFF); instLoVel = Platform.Platform.ToUInt8(inst.Generators[(int)GeneratorEnum.VelocityRange] & 0xFF); instHiVel = Platform.Platform.ToUInt8((inst.Generators[(int)GeneratorEnum.VelocityRange] >> 8) & 0xFF); if ((instLoKey <= presetHiKey && presetLoKey <= instHiKey) && (instLoVel <= presetHiVel && presetLoVel <= instHiVel)) { var r = new Sf2Region(); Platform.Platform.ArrayCopy(inst.Generators, 0, r.Generators, 0, r.Generators.Length); ReadSf2Region(r, globalGens, p.Zones[i].Generators, true); regionList.Add(r); } } } i++; } var mp = new MultiPatch(p.Name); mp.LoadSf2(regionList.ToArray(), _assets); _assets.PatchAssets.Add(new PatchAsset(mp.Name, mp)); AssignPatchToBank(mp, p.BankNumber, p.PatchNumber, p.PatchNumber); } }
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; } }
private void AddToRecentlyFoundPages(FastList <long> c, TreePage p, bool leftmostPage, bool rightmostPage) { Debug.Assert(p.IsCompressed == false); ByteStringContext.Scope firstScope, lastScope; Slice firstKey; if (leftmostPage) { firstScope = new ByteStringContext <ByteStringMemoryCache> .Scope(); firstKey = Slices.BeforeAllKeys; } else { // We are going to store the slice, therefore we copy. firstScope = p.GetNodeKey(_llt, 0, ByteStringType.Immutable, out firstKey); } Slice lastKey; if (rightmostPage) { lastScope = new ByteStringContext <ByteStringMemoryCache> .Scope(); lastKey = Slices.AfterAllKeys; } else { // We are going to store the slice, therefore we copy. lastScope = p.GetNodeKey(_llt, p.NumberOfEntries - 1, ByteStringType.Immutable, out lastKey); } var foundPage = new RecentlyFoundTreePages.FoundTreePage(p.PageNumber, p, firstKey, lastKey, c.ToArray(), firstScope, lastScope); _recentlyFoundPages.Add(foundPage); }
public byte[] DownloadData() { Stopwatch sw = Stopwatch.StartNew(); try { if (_currentStream == null) { Trace.WriteLine("Connecting to " + _ip + " for " + _uri); _errored = false; _currentTcpClient = new TcpClient(); _currentTcpClient.NoDelay = true; _currentTcpClient.ReceiveTimeout = 500; _currentTcpClient.SendTimeout = 500; _currentTcpClient.Connect(_ip, _uri.Port); _currentStream = _currentTcpClient.GetStream(); _currentStream.ReadTimeout = 500; _currentStream.WriteTimeout = 500; byte[] initialBuffer = Encoding.ASCII.GetBytes(string.Format(_initialRequestFormat, _uri.ToString(), _uri.Host)); _currentStream.Write(initialBuffer, 0, initialBuffer.Length); //_readyNextRequest = Encoding.ASCII.GetBytes(string.Format(_nextRequestFormat, uri.ToString(), uri.Host)); _readyNextRequest = initialBuffer; } else { _currentStream.Write(_readyNextRequest, 0, _readyNextRequest.Length); } _responseBuffer.Clear(); int bytesRead; int bytesAnalyzed; bool endOfHeadersReached = false; int contentLength = -1; string httpVersion = null; do { bytesRead = _currentStream.Read(_buffer, 0, _buffer.Length); _responseBuffer.AddRange(_buffer, 0, bytesRead); IList <string> newHeaders = AnalyzeHeaders(_responseBuffer.GetInternalBuffer(), _responseBuffer.Count, out bytesAnalyzed, out endOfHeadersReached); _responseBuffer.RemoveRange(0, bytesAnalyzed); foreach (string header in newHeaders) { Trace.WriteLine(header); if (header.StartsWith("HTTP/1")) { string[] splitted = header.Split(_spaceCharArray); string httpResponseCode = splitted[1]; if (httpResponseCode != "200") { throw new InvalidDataException("httpResponseCode is " + httpResponseCode); } httpVersion = splitted[0]; } else if (header.StartsWith("Content-Length:")) { contentLength = int.Parse(header.Split(_spaceCharArray)[1]); } else if (header == "Connection: keep-alive") { _keepAlive = true; } else if (header == "Connection: close") { _keepAlive = false; } } }while (!endOfHeadersReached); if (contentLength < 0 && httpVersion != "HTTP/1.0") { throw new InvalidDataException("Content-Length is " + contentLength); } Trace.WriteLine("HTTP Version is " + httpVersion); if (httpVersion != "HTTP/1.0") { while (_responseBuffer.Count < contentLength) { bytesRead = _currentStream.Read(_buffer, 0, _buffer.Length); _responseBuffer.AddRange(_buffer, 0, bytesRead); } } else { _keepAlive = false; try { while ((bytesRead = _currentStream.Read(_buffer, 0, _buffer.Length)) > 0) { _responseBuffer.AddRange(_buffer, 0, bytesRead); } } catch (Exception) { } } byte[] result = _responseBuffer.ToArray(); return(result); } catch (Exception ex) { Trace.WriteLine("Connecting to " + _ip + " for " + _uri); Trace.WriteLine("Exception from " + _ip + " for " + _uri + ": " + ex.ToString()); _errored = true; _keepAlive = false; if (_currentStream != null) { _currentStream.Close(); _currentStream = null; } if (_currentTcpClient != null) { _currentTcpClient.Close(); _currentTcpClient = null; } throw; } finally { if (!_keepAlive) { if (_currentStream != null) { _currentStream.Close(); _currentStream = null; } if (_currentTcpClient != null) { _currentTcpClient.Close(); _currentTcpClient = null; } } Trace.WriteLine("DownloadData " + sw.Elapsed); } //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); ////request.KeepAlive = true; ////request.IfModifiedSince = _lastModified; ////request.Host = "www.oref.org.il"; //using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) //{ // //_lastModified = response.LastModified; // using (Stream responseStream = response.GetResponseStream()) // using (StreamReader reader = new StreamReader(responseStream, Encoding.Unicode)) // { // return reader.ReadToEnd(); // } //} }
public void ReadTrack() { var newTrack = new Track(); _score.AddTrack(newTrack); var flags = _data.ReadByte(); newTrack.Name = ReadStringByteLength(40); newTrack.IsPercussion = (flags & 0x01) != 0; var stringCount = ReadInt32(); var tuning = new FastList <int>(); for (int i = 0; i < 7; i++) { var stringTuning = ReadInt32(); if (stringCount > i) { tuning.Add(stringTuning); } } newTrack.Tuning = tuning.ToArray(); var port = ReadInt32(); var index = ReadInt32() - 1; var effectChannel = ReadInt32() - 1; _data.Skip(4); // Fretcount if (index >= 0 && index < _playbackInfos.Count) { var info = _playbackInfos[index]; info.Port = port; info.IsSolo = (flags & 0x10) != 0; info.IsMute = (flags & 0x20) != 0; info.SecondaryChannel = effectChannel; newTrack.PlaybackInfo = info; } newTrack.Capo = ReadInt32(); newTrack.Color = ReadColor(); if (_versionNumber >= 500) { // flags for // 0x01 -> show tablature // 0x02 -> show standard notation _data.ReadByte(); // flags for // 0x02 -> auto let ring // 0x04 -> auto brush _data.ReadByte(); // unknown _data.Skip(43); } // unknown if (_versionNumber >= 510) { _data.Skip(4); ReadStringIntByte(); ReadStringIntByte(); } }
private static void OnSaveData() { FastList <byte> data = new FastList <byte>(); try { SerializableDataExtension.WriteString(VehicleManagerMod._dataVersion, data); for (int index = 0; index < VehicleManagerMod.MaxVehicleCount; ++index) { if (!VehicleManagerMod.m_cachedVehicleData[index].IsEmpty) { SerializableDataExtension.WriteInt32(index, data); SerializableDataExtension.WriteInt32(VehicleManagerMod.m_cachedVehicleData[index].LastStopNewPassengers, data); SerializableDataExtension.WriteInt32(VehicleManagerMod.m_cachedVehicleData[index].LastStopGonePassengers, data); SerializableDataExtension.WriteInt32(VehicleManagerMod.m_cachedVehicleData[index].PassengersThisWeek, data); SerializableDataExtension.WriteInt32(VehicleManagerMod.m_cachedVehicleData[index].PassengersLastWeek, data); SerializableDataExtension.WriteInt32(VehicleManagerMod.m_cachedVehicleData[index].IncomeThisWeek, data); SerializableDataExtension.WriteInt32(VehicleManagerMod.m_cachedVehicleData[index].IncomeLastWeek, data); SerializableDataExtension.WriteFloatArray(VehicleManagerMod.m_cachedVehicleData[index].PassengerData, data); SerializableDataExtension.WriteFloatArray(VehicleManagerMod.m_cachedVehicleData[index].IncomeData, data); SerializableDataExtension.WriteUInt16(VehicleManagerMod.m_cachedVehicleData[index].CurrentStop, data); } } SerializableDataExtension.instance.SerializableData.SaveData(VehicleManagerMod._dataID, data.ToArray()); } catch (Exception ex) { Utils.LogError((object)("Error while saving vehicle data! " + ex.Message + " " + (object)ex.InnerException)); } }
/// <summary> /// Draw this effect mesh. /// </summary> public void Draw(RenderContext context) { // Retrieve effect parameters var mesh = Mesh; var currentRenderData = mesh.Draw; var material = Material; var vao = vertexArrayObject; var drawCount = currentRenderData.DrawCount; if (context.IsPicking()) // TODO move this code corresponding to picking outside of the runtime code! { parameters.Set(ModelComponentPickingShaderKeys.ModelComponentId, new Color4(RenderModel.ModelComponent.Id)); parameters.Set(ModelComponentPickingShaderKeys.MeshId, new Color4(Mesh.NodeIndex)); parameters.Set(ModelComponentPickingShaderKeys.MaterialId, new Color4(Mesh.MaterialIndex)); } if (material != null && material.TessellationMethod != ParadoxTessellationMethod.None) { var tessellationMethod = material.TessellationMethod; // adapt the primitive type and index buffer to the tessellation used if (tessellationMethod.PerformsAdjacentEdgeAverage()) { vao = GetOrCreateVertexArrayObjectAEN(context); drawCount = 12 / 3 * drawCount; } currentRenderData.PrimitiveType = tessellationMethod.GetPrimitiveType(); } //using (Profiler.Begin(ProfilingKeys.PrepareMesh)) { // Order of application of parameters: // - RenderPass.Parameters // - ModelComponent.Parameters // - RenderMesh.Parameters (originally copied from mesh parameters) // The order is based on the granularity level of each element and how shared it can be. Material is heavily shared, a model contains many meshes. An renderMesh is unique. // TODO: really copy mesh parameters into renderMesh instead of just referencing the meshDraw parameters. //var modelComponent = RenderModel.ModelComponent; //var hasModelComponentParams = modelComponent != null && modelComponent.Parameters != null; //var materialParameters = material != null && material.Parameters != null ? material.Parameters : null; parameterCollections.Clear(); parameterCollections.Add(context.Parameters); FillParameterCollections(parameterCollections); // Check if we need to recreate the EffectParameterCollectionGroup // TODO: We can improve performance by redesigning FillParameterCollections to avoid ArrayExtensions.ArraysReferenceEqual (or directly check the appropriate parameter collections) // This also happens in another place: DynamicEffectCompiler (we probably want to factorize it when doing additional optimizations) if (parameterCollectionGroup == null || parameterCollectionGroup.Effect != Effect || !ArrayExtensions.ArraysReferenceEqual(previousParameterCollections, parameterCollections)) { parameterCollectionGroup = new EffectParameterCollectionGroup(context.GraphicsDevice, Effect, parameterCollections); previousParameterCollections = parameterCollections.ToArray(); } Effect.Apply(context.GraphicsDevice, parameterCollectionGroup, true); } //using (Profiler.Begin(ProfilingKeys.RenderMesh)) { if (currentRenderData != null) { var graphicsDevice = context.GraphicsDevice; graphicsDevice.SetVertexArrayObject(vao); if (currentRenderData.IndexBuffer == null) { graphicsDevice.Draw(currentRenderData.PrimitiveType, drawCount, currentRenderData.StartLocation); } else { graphicsDevice.DrawIndexed(currentRenderData.PrimitiveType, drawCount, currentRenderData.StartLocation); } } } }
public void OnSaveData() { FastList<byte> data = new FastList<byte>(); GenerateUniqueID(); byte[] uniqueIdBytes = BitConverter.GetBytes(uniqueID); foreach (byte uniqueIdByte in uniqueIdBytes) { data.Add(uniqueIdByte); } byte[] dataToSave = data.ToArray(); SerializableData.SaveData(dataID, dataToSave); var filepath = Path.Combine(Application.dataPath, "trafficManagerSave_" + uniqueID + ".xml"); var configuration = new Configuration(); for (var i = 0; i < 32768; i++) { if (TrafficPriority.prioritySegments.ContainsKey(i)) { if (TrafficPriority.prioritySegments[i].node_1 != 0) { configuration.prioritySegments.Add(new int[3] { TrafficPriority.prioritySegments[i].node_1, i, (int)TrafficPriority.prioritySegments[i].instance_1.type }); } if (TrafficPriority.prioritySegments[i].node_2 != 0) { configuration.prioritySegments.Add(new int[3] { TrafficPriority.prioritySegments[i].node_2, i, (int)TrafficPriority.prioritySegments[i].instance_2.type }); } } if (CustomRoadAI.nodeDictionary.ContainsKey((ushort) i)) { var nodeDict = CustomRoadAI.nodeDictionary[(ushort)i]; configuration.nodeDictionary.Add(new int[4] {nodeDict.NodeId, Convert.ToInt32(nodeDict._manualTrafficLights), Convert.ToInt32(nodeDict._timedTrafficLights), Convert.ToInt32(nodeDict.TimedTrafficLightsActive)}); } if (TrafficLightsManual.ManualSegments.ContainsKey(i)) { if (TrafficLightsManual.ManualSegments[i].node_1 != 0) { var manualSegment = TrafficLightsManual.ManualSegments[i].instance_1; configuration.manualSegments.Add(new int[10] { (int)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].node_2 != 0) { var manualSegment = TrafficLightsManual.ManualSegments[i].instance_2; configuration.manualSegments.Add(new int[10] { (int)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)) { var timedNode = TrafficLightsTimed.GetTimedLight((ushort) i); configuration.timedNodes.Add(new int[4] { 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 int[2] { 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[4] { (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) { if (Singleton<NetManager>.instance.m_nodes.m_buffer[i].Info.m_class.m_service == ItemClass.Service.Road) { 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.Serialize(filepath, configuration); }
private static void OnSaveData() { FastList <byte> data = new FastList <byte>(); try { SerializableDataExtension.WriteString(_dataVersion, data); for (ushort lineID = 0; (int)lineID < 256; ++lineID) { SerializableDataExtension.AddToData( BitConverter.GetBytes(GetTargetVehicleCount(lineID)), data); SerializableDataExtension.AddToData( BitConverter.GetBytes(Mathf.Max( GetNextSpawnTime(lineID) - SimHelper.SimulationTime, 0.0f)), data); SerializableDataExtension.AddToData( BitConverter.GetBytes(GetBudgetControlState(lineID)), data); SerializableDataExtension.AddToData(BitConverter.GetBytes(GetDepot(lineID)), data); int num = 0; HashSet <string> prefabs = GetPrefabs(lineID); if (prefabs != null) { num = prefabs.Count; } SerializableDataExtension.AddToData(BitConverter.GetBytes(num), data); if (num > 0) { foreach (string s in prefabs) { SerializableDataExtension.WriteString(s, data); } } string[] enqueuedVehicles = GetEnqueuedVehicles(lineID); SerializableDataExtension.AddToData(BitConverter.GetBytes(enqueuedVehicles.Length), data); if (enqueuedVehicles.Length != 0) { foreach (string s in enqueuedVehicles) { SerializableDataExtension.WriteString(s, data); } } SerializableDataExtension.WriteBool(GetUnbunchingState(lineID), data); } SerializableDataExtension.instance.SerializableData.SaveData(_dataID, data.ToArray()); } catch (Exception ex) { string msg = "Error while saving transport line data! " + ex.Message + " " + (object)ex.InnerException; Utils.LogError((object)msg); CODebugBase <LogChannel> .Log(LogChannel.Modding, msg, ErrorLevel.Error); } }
public UserInterface() { instance = this; UIView view = GameObject.FindObjectOfType<UIView> (); if (view == null) return; UIComponent bulldozerBar = UIView.Find ("BulldozerBar"); if (bulldozerBar == null) return; try { XmlSerializer serializer = new XmlSerializer (typeof(XmlData)); using (StreamReader reader = new StreamReader("V10Bulldoze.xml")) { data = (XmlData)serializer.Deserialize (reader); reader.Close (); } } catch (FileNotFoundException) { // No options file yet data = new XmlData (); data.needSave = true; } catch (Exception e) { Debug.Log ("V10Bulldoze: " + e.GetType ().Name + " while reading xml file: " + e.Message + "\n" + e.StackTrace + "\n\n"); if (e.InnerException != null) Debug.Log ("Caused by: " + e.InnerException.GetType ().Name + ": " + e.InnerException.Message + "\n" + e.InnerException.StackTrace); return; } //1.X -> 1.3 if (data.version < 1.3d) { // Everything has already been setted to its default value, so let's just adjust the version and save. data.version = 1.3d; data.needSave = true; } abandonedButton = new GameObject ("V10Bulldoze abandoned button"); burnedButton = new GameObject ("V10Bulldoze burned button"); audioButton = new GameObject ("V10Bulldoze audio button"); Transform parent = bulldozerBar.transform; abandonedButton.transform.parent = parent; burnedButton.transform.parent = parent; audioButton.transform.parent = parent; Shader shader = Shader.Find ("UI/Default UI Shader"); if (shader == null) { Debug.Log ("V10Bulldoze: Can't find default UI shader."); shader = new Shader (); shader.name = "V10Bulldoze dummy shader"; } UITextureAtlas atlas = ScriptableObject.CreateInstance<UITextureAtlas> (); atlas.name = "V10Bulldoze Atlas"; atlas.material = new Material (shader); atlas.material.mainTexture = new Texture2D (0, 0, TextureFormat.DXT5, false); FastList<Texture2D> list = new FastList<Texture2D> (); list.EnsureCapacity (18); UIButton button = abandonedButton.AddComponent<UIButton> (); button.relativePosition = new Vector3 (7.0f, -57.0f); initButton ("AbandonedButton", button, list, data.abandoned, "Demolish Abandoned", view); button.atlas = atlas; button = burnedButton.AddComponent<UIButton> (); button.relativePosition = new Vector3 ((float)(7 + buttonSize + 7), -57.0f); initButton ("BurnedButton", button, list, data.burned, "Demolish Burned", view); button.atlas = atlas; button = audioButton.AddComponent<UIButton> (); button.relativePosition = new Vector3 ((float)(7 + buttonSize + 7 + buttonSize + 7), -57.0f); initButton ("AudioButton", button, list, !data.disableEffect, "Mute Bulldozing", view); button.atlas = atlas; atlas.AddTextures (list.ToArray ()); }
public unsafe void ReadDataTypesTest() { using (var context = new JsonOperationContext(1024, 1024 * 4, SharedMultipleUseFlag.None)) { BlittableJsonReaderObject embeddedReader; using (var builder = new ManualBlittableJsonDocumentBuilder <UnmanagedWriteBuffer>(context)) { builder.Reset(BlittableJsonDocumentBuilder.UsageMode.None); builder.StartWriteObjectDocument(); builder.StartWriteObject(); builder.WritePropertyName("Value"); builder.WriteValue(1000); builder.WriteObjectEnd(); builder.FinalizeDocument(); embeddedReader = builder.CreateReader(); } using (var builder = new ManualBlittableJsonDocumentBuilder <UnmanagedWriteBuffer>(context)) { var lonEscapedCharsString = string.Join(",", Enumerable.Repeat("\"Cool\"", 200).ToArray()); var longEscapedCharsAndNonAsciiString = string.Join(",", Enumerable.Repeat("\"מגניב\"", 200).ToArray()); builder.Reset(BlittableJsonDocumentBuilder.UsageMode.None); builder.StartWriteObjectDocument(); builder.StartWriteObject(); builder.WritePropertyName("FloatMin"); builder.WriteValue(float.MinValue); builder.WritePropertyName("FloatMax"); builder.WriteValue(float.MaxValue); builder.WritePropertyName("UshortMin"); builder.WriteValue(ushort.MinValue); builder.WritePropertyName("UshortMax"); builder.WriteValue(ushort.MaxValue); builder.WritePropertyName("UintMin"); builder.WriteValue(uint.MinValue); builder.WritePropertyName("UintMax"); builder.WriteValue(uint.MaxValue); builder.WritePropertyName("DoubleMin"); builder.WriteValue(double.MinValue); builder.WritePropertyName("DoubleMax"); builder.WriteValue(double.MaxValue); builder.WritePropertyName("LongMin"); builder.WriteValue(long.MinValue); builder.WritePropertyName("LongMax"); builder.WriteValue(long.MaxValue); builder.WritePropertyName("StringEmpty"); builder.WriteValue(string.Empty); builder.WritePropertyName("StringSimple"); builder.WriteValue("StringSimple"); builder.WritePropertyName("StringEscapedChars"); builder.WriteValue("\"Cool\""); builder.WritePropertyName("StringLongEscapedChars"); builder.WriteValue(lonEscapedCharsString); builder.WritePropertyName("StringEscapedCharsAndNonAscii"); builder.WriteValue(longEscapedCharsAndNonAsciiString); var lsvString = "\"fooאbar\""; var lsvStringBytes = Encoding.UTF8.GetBytes(lsvString); fixed(byte *b = lsvStringBytes) { var escapePositionsMaxSize = JsonParserState.FindEscapePositionsMaxSize(lsvString); var lsv = context.AllocateStringValue(null, b, lsvStringBytes.Length); var escapePositions = new FastList <int>(); JsonParserState.FindEscapePositionsIn(escapePositions, b, lsvStringBytes.Length, escapePositionsMaxSize); lsv.EscapePositions = escapePositions.ToArray(); builder.WritePropertyName("LSVString"); builder.WriteValue(lsv); } builder.WritePropertyName("Embedded"); builder.WriteEmbeddedBlittableDocument(embeddedReader); builder.WriteObjectEnd(); builder.FinalizeDocument(); var reader = builder.CreateReader(); reader.BlittableValidation(); Assert.Equal(17, reader.Count); Assert.Equal(float.MinValue, float.Parse(reader["FloatMin"].ToString(), CultureInfo.InvariantCulture)); Assert.Equal(float.MaxValue, float.Parse(reader["FloatMax"].ToString(), CultureInfo.InvariantCulture)); Assert.Equal(ushort.MinValue, ushort.Parse(reader["UshortMin"].ToString(), CultureInfo.InvariantCulture)); Assert.Equal(ushort.MaxValue, ushort.Parse(reader["UshortMax"].ToString(), CultureInfo.InvariantCulture)); Assert.Equal(uint.MinValue, uint.Parse(reader["UintMin"].ToString(), CultureInfo.InvariantCulture)); Assert.Equal(uint.MaxValue, uint.Parse(reader["UintMax"].ToString(), CultureInfo.InvariantCulture)); Assert.Equal(double.MinValue, double.Parse(reader["DoubleMin"].ToString(), CultureInfo.InvariantCulture)); Assert.Equal(double.MaxValue, double.Parse(reader["DoubleMax"].ToString(), CultureInfo.InvariantCulture)); Assert.Equal(long.MinValue, long.Parse(reader["LongMin"].ToString(), CultureInfo.InvariantCulture)); Assert.Equal(long.MaxValue, long.Parse(reader["LongMax"].ToString(), CultureInfo.InvariantCulture)); Assert.Equal(string.Empty, reader["StringEmpty"].ToString()); Assert.Equal("StringSimple", reader["StringSimple"].ToString()); Assert.Equal("\"Cool\"", reader["StringEscapedChars"].ToString()); Assert.Equal(lonEscapedCharsString, reader["StringLongEscapedChars"].ToString()); Assert.Equal(longEscapedCharsAndNonAsciiString, reader["StringEscapedCharsAndNonAscii"].ToString()); Assert.Equal(lsvString, reader["LSVString"].ToString()); Assert.Equal(1000, int.Parse((reader["Embedded"] as BlittableJsonReaderObject)["Value"].ToString(), CultureInfo.InvariantCulture)); } } }
/* * ----------------------- * DrawCategories() * ----------------------- */ void DrawCategories(Event e) { // do any housework before we start drawing if (moveQueued) { // make a temp copy List <SoundFX> origSoundList = new List <SoundFX>(audioManager.soundGroupings[origGroup].soundList); SoundFX temp = origSoundList[origIndex]; List <SoundFX> moveToSoundList = new List <SoundFX>(audioManager.soundGroupings[moveToGroup].soundList); // add it to the move to group moveToSoundList.Add(temp); audioManager.soundGroupings[moveToGroup].soundList = moveToSoundList.ToArray(); // and finally, remove it from the original group origSoundList.RemoveAt(origIndex); audioManager.soundGroupings[origGroup].soundList = origSoundList.ToArray(); Debug.Log("> Moved '" + temp.name + "' from " + "'" + audioManager.soundGroupings[origGroup].name + "' to '" + audioManager.soundGroupings[moveToGroup].name); MarkDirty(); moveQueued = false; } // switch to the next group if (nextGroup > -1) { selectedGroup = nextGroup; nextGroup = -1; } // add a sound if (addSound) { List <SoundFX> soundList = new List <SoundFX>(audioManager.soundGroupings[selectedGroup].soundList); SoundFX soundFX = new SoundFX(); soundFX.name = audioManager.soundGroupings[selectedGroup].name.ToLower() + "_new_unnamed_sound_fx"; soundList.Add(soundFX); audioManager.soundGroupings[selectedGroup].soundList = soundList.ToArray(); MarkDirty(); addSound = false; } // sort the sounds if (sortSounds) { List <SoundFX> soundList = new List <SoundFX>(audioManager.soundGroupings[selectedGroup].soundList); soundList.Sort(delegate(SoundFX sfx1, SoundFX sfx2) { return(string.Compare(sfx1.name, sfx2.name)); }); audioManager.soundGroupings[selectedGroup].soundList = soundList.ToArray(); MarkDirty(); sortSounds = false; } // delete a sound if (deleteSoundIdx > -1) { List <SoundFX> soundList = new List <SoundFX>(audioManager.soundGroupings[selectedGroup].soundList); soundList.RemoveAt(deleteSoundIdx); audioManager.soundGroupings[selectedGroup].soundList = soundList.ToArray(); MarkDirty(); deleteSoundIdx = -1; } // duplicate a sound if (dupeSoundIdx > -1) { List <SoundFX> soundList = new List <SoundFX>(audioManager.soundGroupings[selectedGroup].soundList); SoundFX origSoundFX = soundList[dupeSoundIdx]; // clone this soundFX string json = JsonUtility.ToJson(origSoundFX); SoundFX soundFX = JsonUtility.FromJson <SoundFX>(json); soundFX.name += "_duplicated"; soundList.Insert(dupeSoundIdx + 1, soundFX); audioManager.soundGroupings[selectedGroup].soundList = soundList.ToArray(); MarkDirty(); dupeSoundIdx = -1; } if (e.type == EventType.Repaint) { groups.Clear(); } GUILayout.Space(6f); Color defaultColor = GUI.contentColor; BeginContents(); if (DrawHeader("Sound FX Groups", true)) { EditorGUILayout.BeginVertical(GUI.skin.box); soundGroups.Clear(); for (int i = 0; i < audioManager.soundGroupings.Length; i++) { soundGroups.Add(audioManager.soundGroupings[i]); } for (int i = 0; i < soundGroups.size; i++) { EditorGUILayout.BeginHorizontal(); { if (i == selectedGroup) { GUI.contentColor = (i == editGroup) ? Color.white : Color.yellow; } else { GUI.contentColor = defaultColor; } if ((e.type == EventType.KeyDown) && ((e.keyCode == KeyCode.Return) || (e.keyCode == KeyCode.KeypadEnter))) { // toggle editing if (editGroup >= 0) { editGroup = -1; } Event.current.Use(); } if (i == editGroup) { soundGroups[i].name = GUILayout.TextField(soundGroups[i].name, GUILayout.MinWidth(Screen.width - 80f)); } else { GUILayout.Label(soundGroups[i].name, (i == selectedGroup) ? EditorStyles.whiteLabel : EditorStyles.label, GUILayout.ExpandWidth(true)); } GUILayout.FlexibleSpace(); if (GUILayout.Button(GUIContent.none, "OL Minus", GUILayout.Width(17f))) // minus button { if (EditorUtility.DisplayDialog("Delete '" + soundGroups[i].name + "'", "Are you sure you want to delete the selected sound group?", "Continue", "Cancel")) { soundGroups.RemoveAt(i); MarkDirty(); } } } EditorGUILayout.EndHorizontal(); // build a list of items Rect lastRect = GUILayoutUtility.GetLastRect(); if (e.type == EventType.Repaint) { groups.Add(new ItemRect(i, lastRect, null)); } if ((e.type == EventType.MouseDown) && lastRect.Contains(e.mousePosition)) { if ((i != selectedGroup) || (e.clickCount == 2)) { nextGroup = i; if (e.clickCount == 2) { editGroup = i; } else if (editGroup != nextGroup) { editGroup = -1; } Repaint(); } } } // add the final plus button EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(GUIContent.none, "OL Plus", GUILayout.Width(17f))) // plus button { soundGroups.Add(new SoundGroup("unnamed sound group")); selectedGroup = editGroup = soundGroups.size - 1; MarkDirty(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); // reset the color GUI.contentColor = defaultColor; // the sort and import buttons EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Sort", GUILayout.Width(70f))) { soundGroups.Sort(delegate(SoundGroup sg1, SoundGroup sg2) { return(string.Compare(sg1.name, sg2.name)); }); MarkDirty(); } EditorGUILayout.EndHorizontal(); // draw a rect around the selected item if ((selectedGroup >= 0) && (selectedGroup < groups.size)) { EditorGUI.DrawRect(groups[selectedGroup].rect, new Color(1f, 1f, 1f, 0.06f)); } // finally move the sound groups back into the audio manager if (soundGroups.size > 0) { audioManager.soundGroupings = soundGroups.ToArray(); } // calculate the drop area rect if ((e.type == EventType.Repaint) && (groups.size > 0)) { dropArea.x = groups[0].rect.x; dropArea.y = groups[0].rect.y; dropArea.width = groups[0].rect.width; dropArea.height = (groups[groups.size - 1].rect.y - groups[0].rect.y) + groups[groups.size - 1].rect.height; } } // draw the sound group properties now DrawSoundGroupProperties(); EndContents(); EditorGUILayout.HelpBox("Create and delete sound groups by clicking + and - respectively. Double click to rename sound groups. Drag and drop sounds from below to the groups above to move them.", MessageType.Info); }
public void OnSaveData() { if (Debugger.Enabled) { Debugger.Log("Building Themes: SerializableDataExtension.OnSaveData was called."); Debugger.Log("ON_SAVE_DATA"); } var data = new FastList<byte>(); GenerateUniqueId(); var uniqueIdBytes = BitConverter.GetBytes(UniqueId); foreach (var uniqueIdByte in uniqueIdBytes) { data.Add(uniqueIdByte); } var dataToSave = data.ToArray(); SerializableData.SaveData(DataId, dataToSave); var filepath = BuildSaveFilePath(); var configuration = new DistrictsConfiguration(); var themesManager = Singleton<BuildingThemesManager>.instance; for (byte i = 0; i < 128; i++) { if (!themesManager.IsThemeManagementEnabled(i)) continue; var themes = themesManager.GetDistrictThemes(i, false); if (themes == null) { continue; ; } var themesNames = new string[themes.Count]; var j = 0; foreach (var theme in themes) { themesNames[j] = theme.name; j++; } configuration.Districts.Add(new DistrictsConfiguration.District() { id = i, blacklistMode = themesManager.IsBlacklistModeEnabled(i), themes = themesNames }); if (Debugger.Enabled) { Debugger.LogFormat("Building Themes: Saving: {0} themes enabled for district {1}", themes.Count, i); } } if (configuration.Districts.Count > 0) DistrictsConfiguration.Serialize(filepath, configuration); if (Debugger.Enabled) { Debugger.LogFormat("Building Themes: Serialization done."); Debugger.AppendThemeList(); } }
public static Challenge ChallengeNodeToChallenge(XmlNode challengeNode, bool loadStates) { XmlAttributeCollection challengeAtts = challengeNode.Attributes; FastList<IGoal> goalsToAdd = new FastList<IGoal> (); FastList<IReward> rewardsToAdd = new FastList<IReward> (); FastList<IReward> penaltiesToAdd = new FastList<IReward> (); int years = -1, months = -1; foreach (XmlNode node in challengeNode.ChildNodes) { //Debug.PrintMessage(node.Name); if (node.Name == "goal") { string name = node.Attributes ["name"].Value; float passValue = float.Parse (node.Attributes ["passValue"].Value); float failValue = float.Parse (node.Attributes ["failValue"].Value); NumericalGoal goal = new NumericalGoal (StringToValueID (name), GoalTypeExtension.FromComparison (failValue, passValue), failValue, passValue); if (node.Attributes ["passOnce"] != null) { goal.PassOnce = bool.Parse (node.Attributes ["passOnce"].Value); } if (node.Attributes ["failOnce"] != null) { goal.FailOnce = bool.Parse (node.Attributes ["failOnce"].Value); } if (loadStates && node.Attributes["hasAlreadyFailed"] != null) { goal.HasAlreadyFailed = bool.Parse(node.Attributes ["hasAlreadyFailed"].Value); } if (loadStates && node.Attributes["hasAlreadyPassed"] != null) { goal.HasAlreadyPassed = bool.Parse(node.Attributes ["hasAlreadyPassed"].Value); } goalsToAdd.Add (goal); } else if (node.Name == "deadline") { if (node.Attributes ["years"] != null) years = int.Parse (node.Attributes ["years"].Value); if (node.Attributes ["months"] != null) months = int.Parse (node.Attributes ["months"].Value); } else if (node.Name == "reward") { foreach (XmlNode rewardNode in node.ChildNodes) { if (rewardNode.Name == "boost") { Boost newBoost = new Boost (); newBoost.ValueID = Data.StringToValueID(rewardNode.Attributes ["name"].Value); newBoost.Value = float.Parse (rewardNode.Attributes ["value"].Value); if (rewardNode.Attributes ["years"] != null){ newBoost.Years = int.Parse (rewardNode.Attributes ["years"].Value); } if (rewardNode.Attributes ["months"] != null){ newBoost.Months = int.Parse (rewardNode.Attributes ["months"].Value); } rewardsToAdd.Add (newBoost); } else if (rewardNode.Name == "payment") { rewardsToAdd.Add(new Payment (int.Parse (rewardNode.Attributes ["amount"].Value))); } } } else if (node.Name == "penalty") { foreach (XmlNode rewardNode in node.ChildNodes) { if (rewardNode.Name == "payment") { penaltiesToAdd.Add(new Payment (int.Parse(rewardNode.Attributes ["amount"].Value))); } } } } Challenge newChallenge = new Challenge (challengeAtts ["name"].Value, challengeAtts ["desc"].Value, goalsToAdd.ToArray (), rewardsToAdd.ToArray(), penaltiesToAdd.ToArray()); //Debug.PrintMessage(challengeNode.OuterXml); if (challengeAtts ["requires"] != null) { newChallenge.PassTolerance = int.Parse (challengeAtts ["requires"].Value); } if (challengeAtts ["failTolerance"] != null) { newChallenge.FailTolerance = int.Parse (challengeAtts ["failTolerance"].Value); } if (loadStates && challengeAtts ["startDate"] != null) { newChallenge.MapStartTime = DateTime.Parse (challengeAtts ["startDate"].Value); } if (years >= 0) { newChallenge.Years = years; } if (months >= 0) { newChallenge.Months = months; } return newChallenge; }
private MidiTrack ReadTrack(IReadable input) { var instList = new FastList<Byte>(); var drumList = new FastList<Byte>(); var channelList = new FastList<Byte>(); var eventList = new FastList<MidiEvent>(); var noteOnCount = 0; var totalTime = 0; while (input.Read8BitChars(4) != "MTrk") { var length = input.ReadInt32BE(); while (length > 0) { length--; input.ReadByte(); } } var endPosition = input.ReadInt32BE() + input.Position; var prevStatus = 0; while (input.Position < endPosition) { var delta = ReadVariableLength(input); totalTime += delta; var status = input.ReadByte(); if (status >= 0x80 && status <= 0xEF) {//voice message prevStatus = status; eventList.Add(ReadVoiceMessage(input, delta, (byte)status, (byte)input.ReadByte())); noteOnCount = TrackVoiceStats(eventList[eventList.Count - 1], instList, drumList, channelList, noteOnCount); } else if (status >= 0xF0 && status <= 0xF7) {//system common message prevStatus = 0; eventList.Add(ReadSystemCommonMessage(input, delta, (byte)status)); } else if (status >= 0xF8 && status <= 0xFF) {//realtime message eventList.Add(ReadRealTimeMessage(input, delta, (byte)status)); } else {//data bytes if (prevStatus == 0) {//if no running status continue to next status byte while ((status & 0x80) != 0x80) { status = input.ReadByte(); } if (status >= 0x80 && status <= 0xEF) {//voice message prevStatus = status; eventList.Add(ReadVoiceMessage(input, delta, (byte)status, (byte)input.ReadByte())); noteOnCount = TrackVoiceStats(eventList[eventList.Count - 1], instList, drumList, channelList, noteOnCount); } else if (status >= 0xF0 && status <= 0xF7) {//system common message eventList.Add(ReadSystemCommonMessage(input, delta, (byte)status)); } else if (status >= 0xF8 && status <= 0xFF) {//realtime message eventList.Add(ReadRealTimeMessage(input, delta, (byte)status)); } } else {//otherwise apply running status eventList.Add(ReadVoiceMessage(input, delta, (byte)prevStatus, (byte)status)); noteOnCount = TrackVoiceStats(eventList[eventList.Count - 1], instList, drumList, channelList, noteOnCount); } } } if (input.Position != endPosition) throw new Exception("The track length was invalid for the current MTrk chunk."); if (channelList.IndexOf(MidiHelper.DrumChannel) != -1) { if (drumList.IndexOf(0) == -1) drumList.Add(0); } else { if (instList.IndexOf(0) == -1) instList.Add(0); } var track = new MidiTrack(instList.ToArray(), drumList.ToArray(), channelList.ToArray(), eventList.ToArray()); track.NoteOnCount = noteOnCount; track.EndTime = totalTime; return track; }
public void OnSaveData() { FastList<byte> data = new FastList<byte>(); // Debug.Log("OnSaveData() 1"); GenerateUniqueID(); byte[] uniqueIdBytes = BitConverter.GetBytes(uniqueID); foreach (byte uniqueIdByte in uniqueIdBytes) { data.Add(uniqueIdByte); } // Debug.Log("OnSaveData() 2"); byte[] dataToSave = data.ToArray(); SerializableData.SaveData(dataID, dataToSave); // Debug.Log("OnSaveData() 3"); var filepath = Path.Combine(Application.dataPath, "trafficManagerSave_" + uniqueID + ".xml"); // Debug.Log("OnSaveData()"); var configuration = new Configuration(); // Debug.Log("OnSaveData() 4"); configuration.laneFlags = ""; configuration.nodeCrosswalk = ""; configuration.nodeTrafficLights = ""; for (var i = 0; i < 32768; i++) { if (TrafficPriority.prioritySegments.ContainsKey(i)) { if (TrafficPriority.prioritySegments[i].node_1 != 0) { configuration.prioritySegments.Add(new int[3] { TrafficPriority.prioritySegments[i].node_1, i, (int)TrafficPriority.prioritySegments[i].instance_1.type }); } //Debug.Log("OnSaveData() 5"); if (TrafficPriority.prioritySegments[i].node_2 != 0) { configuration.prioritySegments.Add(new int[3] { TrafficPriority.prioritySegments[i].node_2, i, (int)TrafficPriority.prioritySegments[i].instance_2.type }); } } //Debug.Log("OnSaveData() 6"); if (CustomRoadAI.nodeDictionary.ContainsKey((ushort)i)) { var nodeDict = CustomRoadAI.nodeDictionary[(ushort)i]; configuration.nodeDictionary.Add(new int[4] { nodeDict.NodeId, Convert.ToInt32(nodeDict._manualTrafficLights), Convert.ToInt32(nodeDict._timedTrafficLights), Convert.ToInt32(nodeDict.TimedTrafficLightsActive) }); } // Debug.Log("OnSaveData() 7"); if (TrafficLightsManual.ManualSegments.ContainsKey(i)) { if (TrafficLightsManual.ManualSegments[i].node_1 != 0) { var manualSegment = TrafficLightsManual.ManualSegments[i].instance_1; configuration.manualSegments.Add(new int[10] { (int)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) }); } //Debug.Log("OnSaveData() 8"); if (TrafficLightsManual.ManualSegments[i].node_2 != 0) { var manualSegment = TrafficLightsManual.ManualSegments[i].instance_2; //Debug.Log("OnSaveData() 9"); configuration.manualSegments.Add(new int[10] { (int)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) }); } } // Debug.Log("OnSaveData() 10"); if (TrafficLightsTimed.timedScripts.ContainsKey((ushort)i)) { var timedNode = TrafficLightsTimed.GetTimedLight((ushort)i); configuration.timedNodes.Add(new int[4] { 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 int[2] { 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[4] { (int)timedNode.steps[j].lightLeft[k], (int)timedNode.steps[j].lightMain[k], (int)timedNode.steps[j].lightRight[k], (int)timedNode.steps[j].lightPedestrian[k], }); } } } } //Debug.Log("OnSaveData() 11"); 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) { if (Singleton<NetManager>.instance.m_nodes.m_buffer[i].Info.m_class.m_service == ItemClass.Service.Road) { configuration.nodeTrafficLights += Convert.ToInt16((nodeFlags & NetNode.Flags.TrafficLights) != NetNode.Flags.None); configuration.nodeCrosswalk += Convert.ToInt16((nodeFlags & NetNode.Flags.Junction) != NetNode.Flags.None); } } } //Debug.Log("OnSaveData() 12"); var laneCount = 0; 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 + ","; laneCount++; } } if (configuration.laneFlags != null && configuration.laneFlags.Length > 0) { configuration.laneFlags = configuration.laneFlags.TrimEnd(','); } configuration.aiConfig.congestionCostFactor = CustomPathFind.congestionCostFactor; configuration.aiConfig.minLaneSpace = CustomPathFind.minLaneSpace; configuration.aiConfig.lookaheadLanes = CustomPathFind.lookaheadLanes; configuration.aiConfig.congestedLaneThreshold = CustomPathFind.congestedLaneThreshold; configuration.aiConfig.obeyTMLaneFlags = CustomPathFind.obeyTMLaneFlags; for (var i = 0; i < CSL_Traffic.RoadManager.sm_lanes.Length; i++) { var lane = CSL_Traffic.RoadManager.sm_lanes[i]; if (lane != null && lane.ConnectionCount() > 0) { configuration.laneMarkers.Add(lane); } } Configuration.Serialize(filepath, configuration); }
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); } }
public void ReadTrack() { var newTrack = new Track(1); _score.AddTrack(newTrack); var flags = Data.ReadByte(); newTrack.Name = ReadStringByteLength(40); newTrack.IsPercussion = (flags & 0x01) != 0; var stringCount = ReadInt32(); var tuning = new FastList<int>(); for (int i = 0; i < 7; i++) { var stringTuning = ReadInt32(); if (stringCount > i) { tuning.Add(stringTuning); } } newTrack.Tuning = tuning.ToArray(); var port = ReadInt32(); var index = ReadInt32() - 1; var effectChannel = ReadInt32() - 1; Data.Skip(4); // Fretcount if (index >= 0 && index < _playbackInfos.Count) { var info = _playbackInfos[index]; info.Port = port; info.IsSolo = (flags & 0x10) != 0; info.IsMute = (flags & 0x20) != 0; info.SecondaryChannel = effectChannel; newTrack.PlaybackInfo = info; } newTrack.Capo = ReadInt32(); newTrack.Color = ReadColor(); if (_versionNumber >= 500) { // flags for // 0x01 -> show tablature // 0x02 -> show standard notation Data.ReadByte(); // flags for // 0x02 -> auto let ring // 0x04 -> auto brush Data.ReadByte(); // unknown Data.Skip(43); } // unknown if (_versionNumber >= 510) { Data.Skip(4); ReadStringIntByte(); ReadStringIntByte(); } }
public MidiTrack MergeTracks() { var eventCount = 0; var notesPlayed = 0; var programsUsed = new FastList<byte>(); var drumProgramsUsed = new FastList<byte>(); var channelsUsed = new FastList<byte>(); for (int x = 0; x < Tracks.Length; x++) { eventCount += Tracks[x].MidiEvents.Length; notesPlayed += Tracks[x].NoteOnCount; for (int i = 0; i < Tracks[x].Instruments.Length; i++) { var p = Tracks[x].Instruments[i]; if (programsUsed.IndexOf(p) == -1) programsUsed.Add(p); } for (int i = 0; i < Tracks[x].DrumInstruments.Length; i++) { var p = Tracks[x].DrumInstruments[i]; if (drumProgramsUsed.IndexOf(p) == -1) drumProgramsUsed.Add(p); } for (int i = 0; i < Tracks[x].ActiveChannels.Length; i++) { var p = Tracks[x].ActiveChannels[i]; if (channelsUsed.IndexOf(p) == -1) channelsUsed.Add(p); } } var track = new MidiTrack(programsUsed.ToArray(), drumProgramsUsed.ToArray(), channelsUsed.ToArray(), new MidiEvent[eventCount]); track.NoteOnCount = notesPlayed; return track; }
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); }
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(); }
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(); } }
private static void OnSaveData() { FastList <byte> data = new FastList <byte>(); try { SerializableDataExtension.WriteString(NetManagerMod._dataVersion, data); for (int index = 0; index < 32768; ++index) { if (!NetManagerMod.m_cachedNodeData[index].IsEmpty) { SerializableDataExtension.WriteInt32(index, data); SerializableDataExtension.WriteInt32(NetManagerMod.m_cachedNodeData[index].PassengersIn, data); SerializableDataExtension.WriteInt32(NetManagerMod.m_cachedNodeData[index].PassengersOut, data); SerializableDataExtension.WriteInt32(NetManagerMod.m_cachedNodeData[index].LastWeekPassengersIn, data); SerializableDataExtension.WriteInt32(NetManagerMod.m_cachedNodeData[index].LastWeekPassengersOut, data); SerializableDataExtension.WriteFloatArray(NetManagerMod.m_cachedNodeData[index].PassengerInData, data); SerializableDataExtension.WriteFloatArray(NetManagerMod.m_cachedNodeData[index].PassengerOutData, data); SerializableDataExtension.WriteBool(NetManagerMod.m_cachedNodeData[index].Unbunching, data); } } SerializableDataExtension.instance.SerializableData.SaveData(NetManagerMod._dataID, data.ToArray()); } catch (Exception ex) { Utils.LogError((object)("Error while saving net node data! " + ex.Message + " " + (object)ex.InnerException)); } }