/// <summary> /// Creates a new serializable object for the specified object type. /// </summary> /// <param name="objectType">C# type of the object.</param> /// <param name="parentObject">Specific instance of the object of <paramref name="objectType"/>.</param> public SerializableObject(Type objectType, object parentObject) { Internal_CreateInstance(this, objectType); this.parentProperty = null; this.parentObject = parentObject; }
/// <summary> /// Creates a new serializable object for the specified object. Object must not be null. /// </summary> /// <param name="parentObject">Specific instance of the object.</param> public SerializableObject(object parentObject) { Internal_CreateInstance(this, parentObject.GetType()); this.parentProperty = null; this.parentObject = parentObject; }
/// <summary> /// Constructor for use by the runtime only. /// </summary> /// <param name="keyType">C# type of the keys in the dictionary.</param> /// <param name="valueType">C# type of the values in the dictionary.</param> /// <param name="parentProperty">Property used for retrieving this entry.</param> private SerializableDictionary(Type keyType, Type valueType, SerializableProperty parentProperty) { this.parentProperty = parentProperty; this.keyType = keyType; this.valueType = valueType; keyPropertyType = SerializableProperty.DetermineFieldType(keyType); valuePropertyType = SerializableProperty.DetermineFieldType(valueType); }
public FieldInfo GetArgsField(SerializableProperty ser) { FieldInfo field; if (!_argFields.TryGetValue(ser, out field)) throw new ArgumentException("Could not find the visit args field for the property " + ser.Ref.Name); return field; }
/// <summary> /// Creates a new inspectable field GUI for the specified property. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="type">Type of property this field will be used for displaying.</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the array whose contents to display.</param> public InspectableField(Inspector parent, string title, string path, SerializableProperty.FieldType type, int depth, InspectableFieldLayout layout, SerializableProperty property) { this.parent = parent; this.layout = layout; this.title = title; this.path = path; this.type = type; this.depth = depth; Property = property; }
private IGraphProperty Create(SerializableProperty ser) { Func<SerializableProperty, IGraphProperty> factory; if (PredefinedGraphPropertyFactories.TryGetValue(ser.Ref.PropertyType, out factory)) return factory(ser); DictionaryContainerTypeInfo dictionaryTypeInfo; if (ser.Ext.TryGetDictionaryTypeInfo(out dictionaryTypeInfo)) { } CollectionContainerTypeInfo collectionTypeInfo; if (ser.Ext.TryGetCollectionTypeInfo(out collectionTypeInfo)) { } return new ComplexGraphProperty(ser, GetOrCreate(ser.Ref.PropertyType)); //throw new ArgumentException(string.Format("Could not create a graph property of property {0} with type {1}", ser.Ref.Name, ser.Ref.PropertyType.FullName)); }
public ItemComponent(Item item, XElement element) { this.item = item; originalElement = element; name = element.Name.ToString(); SerializableProperties = SerializableProperty.GetProperties(this); requiredItems = new Dictionary <RelatedItem.RelationType, List <RelatedItem> >(); requiredSkills = new List <Skill>(); #if CLIENT hasSoundsOfType = new bool[Enum.GetValues(typeof(ActionType)).Length]; sounds = new Dictionary <ActionType, List <ItemSound> >(); #endif SelectKey = InputType.Select; try { string selectKeyStr = element.GetAttributeString("selectkey", "Select"); selectKeyStr = ToolBox.ConvertInputType(selectKeyStr); SelectKey = (InputType)Enum.Parse(typeof(InputType), selectKeyStr, true); } catch (Exception e) { DebugConsole.ThrowError("Invalid select key in " + element + "!", e); } PickKey = InputType.Select; try { string pickKeyStr = element.GetAttributeString("pickkey", "Select"); pickKeyStr = ToolBox.ConvertInputType(pickKeyStr); PickKey = (InputType)Enum.Parse(typeof(InputType), pickKeyStr, true); } catch (Exception e) { DebugConsole.ThrowError("Invalid pick key in " + element + "!", e); } SerializableProperties = SerializableProperty.DeserializeProperties(this, element); ParseMsg(); foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "activeconditional": case "isactive": IsActiveConditionals = IsActiveConditionals ?? new List <PropertyConditional>(); foreach (XAttribute attribute in subElement.Attributes()) { if (PropertyConditional.IsValid(attribute)) { IsActiveConditionals.Add(new PropertyConditional(attribute)); } } break; case "requireditem": case "requireditems": SetRequiredItems(subElement); break; case "requiredskill": case "requiredskills": if (subElement.Attribute("name") != null) { DebugConsole.ThrowError("Error in item config \"" + item.ConfigFile + "\" - skill requirement in component " + GetType().ToString() + " should use a skill identifier instead of the name of the skill."); continue; } string skillIdentifier = subElement.GetAttributeString("identifier", ""); requiredSkills.Add(new Skill(skillIdentifier, subElement.GetAttributeInt("level", 0))); break; case "statuseffect": var statusEffect = StatusEffect.Load(subElement, item.Name); if (statusEffectLists == null) { statusEffectLists = new Dictionary <ActionType, List <StatusEffect> >(); } List <StatusEffect> effectList; if (!statusEffectLists.TryGetValue(statusEffect.type, out effectList)) { effectList = new List <StatusEffect>(); statusEffectLists.Add(statusEffect.type, effectList); } effectList.Add(statusEffect); break; default: if (LoadElemProjSpecific(subElement)) { break; } ItemComponent ic = Load(subElement, item, item.ConfigFile, false); if (ic == null) { break; } ic.Parent = this; ic.IsActive = isActive; OnActiveStateChanged += ic.SetActiveState; item.AddComponent(ic); break; } } }
/// <inheritdoc/> protected internal override bool Contains(object key) { SerializableProperty keyProperty = (SerializableProperty)key; return(dictionary.Contains(keyProperty.GetValue <object>()));; }
public NonDefaultConstructorHelper( IEnumerable<ConstructorWrapper> constructors, IEnumerable<SerializableProperty> serializableProperties, SerializableProperty textNodeProperty, IDictionary<string, SerializableProperty> attributeProperties, IDictionary<string, SerializableProperty> caseSensitiveSerializableProperties, XSerializerXmlReader reader) { _constructors = constructors; _serializableProperties = serializableProperties; _textNodeProperty = textNodeProperty; _attributeProperties = attributeProperties; _caseSensitiveSerializableProperties = caseSensitiveSerializableProperties; _reader = reader; }
private void GeneratePropertyCode(ILCodeVariable graphVariable, SerializableProperty target) { var extPropertyType = target.Ext; var argsField = _context.GetArgsField(target); var argsFieldVariable = _il.Var.Field(_il.Var.This(), argsField); if (target.Ext.IsValueOrNullableOfValue()) { var valueType = target.Ext.IsEnum() ? target.Ext.GetUnderlyingEnumType() : target.Ref.PropertyType; var propertyParameter = _il.Var.Property(graphVariable, target.Ref).AsNullable(); _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorVisitValue[valueType], propertyParameter, argsFieldVariable); } else if (extPropertyType.Class == TypeClass.Dictionary) { var container = extPropertyType.Container.AsDictionary(); var dictionaryType = container.DictionaryInterfaceType; var cLocal = _il.DeclareLocal("dictionary", dictionaryType); _il.Snippets.SetVariable(cLocal, _il.Var.Property(graphVariable, target.Ref).Cast(dictionaryType)); _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorVisit, cLocal, argsFieldVariable); _il.IfNotEqual(cLocal, null) .Then(() => GenerateDictionaryCode(cLocal, container.ElementType)) .End(); _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorLeave, cLocal, argsFieldVariable); } else if (extPropertyType.Class == TypeClass.Collection) { var container = extPropertyType.Container.AsCollection(); var collectionType = extPropertyType.Ref.IsArray && extPropertyType.Container.AsArray().Ranks > 1 ? extPropertyType.Ref : container.CollectionInterfaceType; var cLocal = _il.DeclareLocal("collection", collectionType); _il.Snippets.SetVariable(cLocal, _il.Var.Property(graphVariable, target.Ref).Cast(collectionType)); _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorVisit, cLocal, argsFieldVariable); _il.IfNotEqual(cLocal, null).Then( () => GenerateEnumerateCollectionContentCode(extPropertyType, cLocal)) .End(); _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorLeave, cLocal, argsFieldVariable); } else { var singleLocal = _il.DeclareLocal("single", target.Ref.PropertyType); _il.Snippets.GetPropertyValue(graphVariable, target.Ref); _il.Var.Set(singleLocal); _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorVisit, singleLocal, argsFieldVariable); var checkIfNullLabel = _il.DefineLabel(); _il.TransferIfNull(singleLocal, checkIfNullLabel); GenerateChildCall(singleLocal); _il.MarkLabel(checkIfNullLabel); _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorLeave, singleLocal, argsFieldVariable); } }
private void LoadSettings() { XDocument doc = null; if (File.Exists(SettingsFile)) { doc = XMLExtensions.TryLoadXml(SettingsFile); } if (doc == null || doc.Root == null) { doc = new XDocument(new XElement("serversettings")); } SerializableProperties = SerializableProperty.DeserializeProperties(this, doc.Root); AutoRestart = doc.Root.GetAttributeBool("autorestart", false); Voting.AllowSubVoting = SubSelectionMode == SelectionMode.Vote; Voting.AllowModeVoting = ModeSelectionMode == SelectionMode.Vote; selectedLevelDifficulty = doc.Root.GetAttributeFloat("LevelDifficulty", 20.0f); GameMain.NetLobbyScreen.SetLevelDifficulty(selectedLevelDifficulty); var traitorsEnabled = TraitorsEnabled; Enum.TryParse(doc.Root.GetAttributeString("TraitorsEnabled", "No"), out traitorsEnabled); TraitorsEnabled = traitorsEnabled; GameMain.NetLobbyScreen.SetTraitorsEnabled(traitorsEnabled); var botSpawnMode = BotSpawnMode.Fill; Enum.TryParse(doc.Root.GetAttributeString("BotSpawnMode", "Fill"), out botSpawnMode); BotSpawnMode = botSpawnMode; //"65-90", "97-122", "48-59" = upper and lower case english alphabet and numbers string[] allowedClientNameCharsStr = doc.Root.GetAttributeStringArray("AllowedClientNameChars", new string[] { "65-90", "97-122", "48-59" }); foreach (string allowedClientNameCharRange in allowedClientNameCharsStr) { string[] splitRange = allowedClientNameCharRange.Split('-'); if (splitRange.Length == 0 || splitRange.Length > 2) { DebugConsole.ThrowError("Error in server settings - " + allowedClientNameCharRange + " is not a valid range for characters allowed in client names."); continue; } int min = -1; if (!int.TryParse(splitRange[0], out min)) { DebugConsole.ThrowError("Error in server settings - " + allowedClientNameCharRange + " is not a valid range for characters allowed in client names."); continue; } int max = min; if (splitRange.Length == 2) { if (!int.TryParse(splitRange[1], out max)) { DebugConsole.ThrowError("Error in server settings - " + allowedClientNameCharRange + " is not a valid range for characters allowed in client names."); continue; } } if (min > -1 && max > -1) { AllowedClientNameChars.Add(new Pair <int, int>(min, max)); } } AllowedRandomMissionTypes = new List <MissionType>(); string[] allowedMissionTypeNames = doc.Root.GetAttributeStringArray( "AllowedRandomMissionTypes", Enum.GetValues(typeof(MissionType)).Cast <MissionType>().Select(m => m.ToString()).ToArray()); foreach (string missionTypeName in allowedMissionTypeNames) { if (Enum.TryParse(missionTypeName, out MissionType missionType)) { if (missionType == Barotrauma.MissionType.None) { continue; } AllowedRandomMissionTypes.Add(missionType); } } ServerName = doc.Root.GetAttributeString("name", ""); ServerMessageText = doc.Root.GetAttributeString("ServerMessage", ""); GameMain.NetLobbyScreen.SelectedModeIdentifier = GameModeIdentifier; GameMain.NetLobbyScreen.MissionTypeName = MissionType; GameMain.NetLobbyScreen.SetBotSpawnMode(BotSpawnMode); GameMain.NetLobbyScreen.SetBotCount(BotCount); List <string> monsterNames = GameMain.Instance.GetFilesOfType(ContentType.Character).ToList(); for (int i = 0; i < monsterNames.Count; i++) { monsterNames[i] = Path.GetFileName(Path.GetDirectoryName(monsterNames[i])); } MonsterEnabled = new Dictionary <string, bool>(); foreach (string s in monsterNames) { if (!MonsterEnabled.ContainsKey(s)) { MonsterEnabled.Add(s, true); } } AutoBanTime = doc.Root.GetAttributeFloat("autobantime", 60); MaxAutoBanTime = doc.Root.GetAttributeFloat("maxautobantime", 360); }
public ItemComponent(Item item, XElement element) { this.item = item; properties = SerializableProperty.GetProperties(this); //canBePicked = ToolBox.GetAttributeBool(element, "canbepicked", false); //canBeSelected = ToolBox.GetAttributeBool(element, "canbeselected", false); //msg = ToolBox.GetAttributeString(element, "msg", ""); requiredItems = new List <RelatedItem>(); requiredSkills = new List <Skill>(); #if CLIENT sounds = new Dictionary <ActionType, List <ItemSound> >(); #endif SelectKey = InputType.Select; try { string selectKeyStr = element.GetAttributeString("selectkey", "Select"); selectKeyStr = ToolBox.ConvertInputType(selectKeyStr); SelectKey = (InputType)Enum.Parse(typeof(InputType), selectKeyStr, true); } catch (Exception e) { DebugConsole.ThrowError("Invalid select key in " + element + "!", e); } PickKey = InputType.Select; try { string pickKeyStr = element.GetAttributeString("selectkey", "Select"); pickKeyStr = ToolBox.ConvertInputType(pickKeyStr); PickKey = (InputType)Enum.Parse(typeof(InputType), pickKeyStr, true); } catch (Exception e) { DebugConsole.ThrowError("Invalid pick key in " + element + "!", e); } properties = SerializableProperty.DeserializeProperties(this, element); foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "requireditem": case "requireditems": RelatedItem ri = RelatedItem.Load(subElement); if (ri != null) { requiredItems.Add(ri); } break; case "requiredskill": case "requiredskills": string skillName = subElement.GetAttributeString("name", ""); requiredSkills.Add(new Skill(skillName, subElement.GetAttributeInt("level", 0))); break; case "statuseffect": var statusEffect = StatusEffect.Load(subElement); if (statusEffectLists == null) { statusEffectLists = new Dictionary <ActionType, List <StatusEffect> >(); } List <StatusEffect> effectList; if (!statusEffectLists.TryGetValue(statusEffect.type, out effectList)) { effectList = new List <StatusEffect>(); statusEffectLists.Add(statusEffect.type, effectList); } effectList.Add(statusEffect); break; default: if (LoadElemProjSpecific(subElement)) { break; } ItemComponent ic = Load(subElement, item, item.ConfigFile, false); if (ic == null) { break; } ic.Parent = this; item.components.Add(ic); break; } } }
/// <summary> /// Constructor for use by the runtime only. /// </summary> /// <param name="elementType">C# type of the elements in the list.</param> /// <param name="parentProperty">Property used for retrieving this entry.</param> private SerializableList(Type elementType, SerializableProperty parentProperty) { this.parentProperty = parentProperty; this.elementType = elementType; elementPropertyType = SerializableProperty.DetermineFieldType(elementType); }
/// <summary> /// Creates a new inspectable list GUI object that displays the contents of the provided serializable property. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Label to display on the list GUI title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties). /// </param> /// <param name="property">Serializable property referencing a list.</param> /// <param name="layout">Layout to which to append the list GUI elements to.</param> /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple /// nested containers whose backgrounds are overlaping. Also determines background style, /// depths divisible by two will use an alternate style.</param> public static InspectableListGUI Create(Inspector parent, LocString title, string path, SerializableProperty property, GUILayout layout, int depth) { InspectableListGUI listGUI = new InspectableListGUI(parent, title, path, property, layout, depth); listGUI.BuildGUI(); return listGUI; }
/// <summary> /// Constructs a new empty inspectable list GUI. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Label to display on the list GUI title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties). /// </param> /// <param name="property">Serializable property referencing a list.</param> /// <param name="layout">Layout to which to append the list GUI elements to.</param> /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple /// nested containers whose backgrounds are overlaping. Also determines background style, /// depths divisible by two will use an alternate style.</param> public InspectableListGUI(Inspector parent, LocString title, string path, SerializableProperty property, GUILayout layout, int depth) : base(title, layout, depth) { this.property = property; this.parent = parent; this.path = path; list = property.GetValue<IList>(); if (list != null) numElements = list.Count; }
/// <summary> /// Triggered when the user selects a field. /// </summary> /// <param name="element">Row element for the field that was selected.</param> /// <param name="type">Data type stored in the field.</param> private void DoOnElementSelected(Element element, SerializableProperty.FieldType type) { if (OnElementSelected != null) OnElementSelected(element.so, element.comp, element.path, type); }
/// <summary> /// Registers a new row in the layout for the provided property. The type of row is determined by the property type. /// </summary> /// <param name="parent">Parent foldout row to which to append the new elements.</param> /// <param name="name">Name of the field the property belongs to.</param> /// <param name="path">Slash separated path to the field from its parent object.</param> /// <param name="property">Property to create the row for.</param> /// <param name="element">Element containing data for the newly created row. Only valid if method returns true. /// </param> /// <returns>Returns true if the row was successfully added, false otherwise.</returns> private bool AddPropertyRow(Element parent, string name, string path, SerializableProperty property, out Element element) { switch (property.Type) { case SerializableProperty.FieldType.Bool: case SerializableProperty.FieldType.Float: case SerializableProperty.FieldType.Int: case SerializableProperty.FieldType.Color: case SerializableProperty.FieldType.Vector2: case SerializableProperty.FieldType.Vector3: case SerializableProperty.FieldType.Vector4: element = AddFieldRow(parent.childLayout, name, parent.so, parent.comp, path, property.Type); return true; case SerializableProperty.FieldType.Object: { Action<Element, bool> toggleCallback = (toggleParent, expand) => { SerializableObject childObject = new SerializableObject(property.InternalType, null); ToggleObjectFoldout(toggleParent, childObject, expand); }; element = AddFoldoutRow(parent.childLayout, null, name, parent.so, parent.comp, path, toggleCallback); } return true; case SerializableProperty.FieldType.Array: { Action<Element, bool> toggleCallback = (toggleParent, expand) => { SerializableArray childObject = property.GetArray(); if (childObject != null) ToggleArrayFoldout(toggleParent, childObject, expand); }; element = AddFoldoutRow(parent.childLayout, null, name, parent.so, parent.comp, path, toggleCallback); } return true; case SerializableProperty.FieldType.List: { Action<Element, bool> toggleCallback = (toggleParent, expand) => { SerializableList childObject = property.GetList(); if (childObject != null) ToggleListFoldout(toggleParent, childObject, expand); }; element = AddFoldoutRow(parent.childLayout, null, name, parent.so, parent.comp, path, toggleCallback); } return true; } element = new Element(); return false; }
/// <summary> /// Registers a new row in the layout. The row cannot have any further children and can be selected as the output /// field. /// </summary> /// <param name="layout">Layout to append the row GUI elements to.</param> /// <param name="name">Name of the field.</param> /// <param name="so">Parent scene object of the field.</param> /// <param name="component">Parent component of the field. Can be null if field belongs to <see cref="SceneObject"/>. /// </param> /// <param name="path">Slash separated path to the field from its parent object.</param> /// <param name="type">Data type stored in the field.</param> /// <returns>Element object storing all information about the added field.</returns> private Element AddFieldRow(GUILayout layout, string name, SceneObject so, Component component, string path, SerializableProperty.FieldType type) { Element element = new Element(so, component, path); GUILayoutX elementLayout = layout.AddLayoutX(); elementLayout.AddSpace(PADDING); elementLayout.AddSpace(foldoutWidth); GUILabel label = new GUILabel(new LocEdString(name)); elementLayout.AddElement(label); GUIButton selectBtn = new GUIButton(new LocEdString("Select")); selectBtn.OnClick += () => { DoOnElementSelected(element, type); }; elementLayout.AddFlexibleSpace(); elementLayout.AddElement(selectBtn); elementLayout.AddSpace(5); element.path = path; return element; }
/// <summary> /// Creates a new inspectable float GUI for the specified property. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the array whose contents to display.</param> /// <param name="style">Contains information about the field style</param> public InspectableFloat(Inspector parent, string title, string path, int depth, InspectableFieldLayout layout, SerializableProperty property, InspectableFieldStyleInfo style) : base(parent, title, path, SerializableProperty.FieldType.Float, depth, layout, property) { this.style = style; }
/// <summary> /// Constructs a new inspectable array GUI. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Label to display on the list GUI title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties). /// </param> /// <param name="property">Serializable property referencing a single-dimensional array.</param> /// <param name="layout">Layout to which to append the list GUI elements to.</param> /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple /// nested containers whose backgrounds are overlaping. Also determines background style, /// depths divisible by two will use an alternate style.</param> /// <param name="style">Information that can be used for customizing field rendering and behaviour.</param> public InspectableArrayGUI(Inspector parent, LocString title, string path, SerializableProperty property, GUILayout layout, int depth, InspectableFieldStyleInfo style) : base(title, layout, depth) { this.property = property; this.parent = parent; this.path = path; this.style = style; array = property.GetValue <Array>(); if (array != null) { numElements = array.Length; } }
/// <summary> /// Creates a new inspectable array GUI for the specified property. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the array whose contents to display.</param> public InspectableObject(Inspector parent, string title, string path, int depth, InspectableFieldLayout layout, SerializableProperty property) : base(parent, title, path, SerializableProperty.FieldType.Object, depth, layout, property) { isExpanded = parent.Persistent.GetBool(path + "_Expanded"); }
public NetPropertyData(object parentObject, SerializableProperty property, string typeString) { this.property = property; this.typeString = typeString; this.parentObject = parentObject; }
/// <summary> /// Constructs a new dictionary GUI. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Label to display on the list GUI title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties). /// </param> /// <param name="property">Serializable property referencing a dictionary</param> /// <param name="layout">Layout to which to append the list GUI elements to.</param> /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple /// nested containers whose backgrounds are overlaping. Also determines background style, /// depths divisible by two will use an alternate style.</param> protected InspectableDictionaryGUI(Inspector parent, LocString title, string path, SerializableProperty property, GUILayout layout, int depth = 0) : base(title, layout, depth) { this.property = property; this.parent = parent; this.path = path; dictionary = property.GetValue<IDictionary>(); if (dictionary != null) numElements = dictionary.Count; UpdateKeys(); }
/// <summary> /// Creates a new inspectable list GUI for the specified property. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the list whose contents to display.</param> public InspectableList(Inspector parent, string title, string path, int depth, InspectableFieldLayout layout, SerializableProperty property) : base(parent, title, path, SerializableProperty.FieldType.List, depth, layout, property) { }
/// <inheritdoc/> protected internal override KeyValuePair<object, object> CloneElement(int index) { SerializableProperty keyProperty = (SerializableProperty)GetKey(index); SerializableProperty valueProperty = (SerializableProperty)GetValue(keyProperty); SerializableDictionary dictionary = property.GetDictionary(); DictionaryDataWrapper keyData = new DictionaryDataWrapper(); keyData.value = SerializableUtility.Clone(keyProperty.GetValue<object>()); SerializableProperty clonedKeyProperty = new SerializableProperty(dictionary.KeyPropertyType, dictionary.KeyType, () => keyData.value, (x) => keyData.value = x); DictionaryDataWrapper valueData = new DictionaryDataWrapper(); valueData.value = SerializableUtility.Clone(valueProperty.GetValue<object>()); SerializableProperty clonedValueProperty = new SerializableProperty(dictionary.ValuePropertyType, dictionary.ValueType, () => valueData.value, (x) => valueData.value = x); return new KeyValuePair<object,object>(clonedKeyProperty, clonedValueProperty); }
/// <summary> /// Creates a new inspectable AABox GUI for the specified property. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the field whose contents to display.</param> /// <param name="style">Information that can be used for customizing field rendering and behaviour.</param> public InspectableAABox(Inspector parent, string title, string path, int depth, InspectableFieldLayout layout, SerializableProperty property, InspectableFieldStyleInfo style) : base(parent, title, path, SerializableProperty.FieldType.Object, depth, layout, property) { }
private void LoadSettings() { XDocument doc = null; if (File.Exists(SettingsFile)) { doc = XMLExtensions.TryLoadXml(SettingsFile); } if (doc == null || doc.Root == null) { doc = new XDocument(new XElement("serversettings")); } SerializableProperties = SerializableProperty.DeserializeProperties(this, doc.Root); AutoRestart = doc.Root.GetAttributeBool("autorestart", false); #if CLIENT if (autoRestart) { GameMain.NetLobbyScreen.SetAutoRestart(autoRestart, AutoRestartInterval); } #endif subSelectionMode = SelectionMode.Manual; Enum.TryParse <SelectionMode>(doc.Root.GetAttributeString("SubSelection", "Manual"), out subSelectionMode); Voting.AllowSubVoting = subSelectionMode == SelectionMode.Vote; modeSelectionMode = SelectionMode.Manual; Enum.TryParse <SelectionMode>(doc.Root.GetAttributeString("ModeSelection", "Manual"), out modeSelectionMode); Voting.AllowModeVoting = modeSelectionMode == SelectionMode.Vote; var traitorsEnabled = TraitorsEnabled; Enum.TryParse <YesNoMaybe>(doc.Root.GetAttributeString("TraitorsEnabled", "No"), out traitorsEnabled); TraitorsEnabled = traitorsEnabled; GameMain.NetLobbyScreen.SetTraitorsEnabled(traitorsEnabled); if (GameMain.NetLobbyScreen != null #if CLIENT && GameMain.NetLobbyScreen.ServerMessage != null #endif ) { GameMain.NetLobbyScreen.ServerMessageText = doc.Root.GetAttributeString("ServerMessage", ""); } #if CLIENT showLogButton.Visible = SaveServerLogs; #endif List <string> monsterNames = Directory.GetDirectories("Content/Characters").ToList(); for (int i = 0; i < monsterNames.Count; i++) { monsterNames[i] = monsterNames[i].Replace("Content/Characters", "").Replace("/", "").Replace("\\", ""); } monsterEnabled = new Dictionary <string, bool>(); foreach (string s in monsterNames) { monsterEnabled.Add(s, true); } extraCargo = new Dictionary <string, int>(); }
/// <summary> /// Creates a new inspectable color GUI for the specified property. /// </summary> /// <param name="context">Context shared by all inspectable fields created by the same parent.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the field whose contents to display.</param> /// <param name="style">Contains information about the field style.</param> public InspectableColor(InspectableContext context, string title, string path, int depth, InspectableFieldLayout layout, SerializableProperty property, InspectableFieldStyleInfo style) : base(context, title, path, SerializableProperty.FieldType.Color, depth, layout, property) { hdr = style?.StyleFlags.HasFlag(InspectableFieldStyleFlags.HDR) ?? false; }
/// <summary> /// Creates a new inspectable color GUI for the specified property. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the array whose contents to display.</param> public InspectableColor(Inspector parent, string title, string path, int depth, InspectableFieldLayout layout, SerializableProperty property) : base(parent, title, path, SerializableProperty.FieldType.Color, depth, layout, property) { }
/// <summary> /// Creates a new inspectable field, automatically detecting the most appropriate implementation for the type /// contained in the provided serializable property. This may be one of the built-in inspectable field implemetations /// (like ones for primitives like int or bool), or a user defined implementation defined with a /// <see cref="CustomInspector"/> attribute. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="layoutIndex">Index into the parent layout at which to insert the GUI elements for the field .</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the array whose contents to display.</param> /// <param name="style">Information that can be used for customizing field rendering and behaviour.</param> /// <returns>Inspectable field implementation that can be used for displaying the GUI for a serializable property /// of the provided type.</returns> public static InspectableField CreateInspectable(Inspector parent, string title, string path, int layoutIndex, int depth, InspectableFieldLayout layout, SerializableProperty property, InspectableFieldStyleInfo style = null) { InspectableField field = null; Type type = property.InternalType; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(RRef <>)) { type = type.GenericTypeArguments[0]; } Type customInspectable = InspectorUtility.GetCustomInspectable(type); if (customInspectable != null) { field = (InspectableField)Activator.CreateInstance(customInspectable, depth, title, property); } else { switch (property.Type) { case SerializableProperty.FieldType.Int: if (style != null && style.StyleFlags.HasFlag(InspectableFieldStyleFlags.UseLayerMask)) { field = new InspectableLayerMask(parent, title, path, depth, layout, property); } else { if (style?.RangeStyle == null || !style.RangeStyle.Slider) { field = new InspectableInt(parent, title, path, depth, layout, property, style); } else { field = new InspectableRangedInt(parent, title, path, depth, layout, property, style); } } break; case SerializableProperty.FieldType.Float: if (style?.RangeStyle == null || !style.RangeStyle.Slider) { field = new InspectableFloat(parent, title, path, depth, layout, property, style); } else { field = new InspectableRangedFloat(parent, title, path, depth, layout, property, style); } break; case SerializableProperty.FieldType.Bool: field = new InspectableBool(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Color: field = new InspectableColor(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.ColorGradient: field = new InspectableColorGradient(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Curve: field = new InspectableCurve(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.FloatDistribution: field = new InspectableFloatDistribution(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Vector2Distribution: field = new InspectableVector2Distribution(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Vector3Distribution: field = new InspectableVector3Distribution(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.ColorDistribution: field = new InspectableColorDistribution(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.String: field = new InspectableString(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Vector2: field = new InspectableVector2(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Vector3: field = new InspectableVector3(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Vector4: field = new InspectableVector4(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Quaternion: if (style != null && style.StyleFlags.HasFlag(InspectableFieldStyleFlags.AsQuaternion)) { field = new InspectableQuaternion(parent, title, path, depth, layout, property); } else { field = new InspectableEuler(parent, title, path, depth, layout, property); } break; case SerializableProperty.FieldType.Resource: field = new InspectableResource(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.RRef: field = new InspectableRRef(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.GameObjectRef: field = new InspectableGameObjectRef(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Object: field = new InspectableObject(parent, title, path, depth, layout, property, style); break; case SerializableProperty.FieldType.Array: field = new InspectableArray(parent, title, path, depth, layout, property, style); break; case SerializableProperty.FieldType.List: field = new InspectableList(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Dictionary: field = new InspectableDictionary(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Enum: field = new InspectableEnum(parent, title, path, depth, layout, property); break; } } if (field == null) { throw new Exception("No inspector exists for the provided field type."); } field.Initialize(layoutIndex); field.Refresh(layoutIndex); return(field); }
public DefaultConstructorHelper( Func<T> createInstance, Dictionary<string, SerializableProperty> caseSensitiveSerializableProperties, SerializableProperty textNodeProperty, IDictionary<string, SerializableProperty> attributeProperties, XSerializerXmlReader reader) { _reader = reader; _caseSensitiveSerializableProperties = caseSensitiveSerializableProperties; _textNodeProperty = textNodeProperty; _attributeProperties = attributeProperties; _instance = createInstance(); }
/// <summary> /// Builds the inspectable dictionary GUI elements. Must be called at least once in order for the contents to /// be populated. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Label to display on the list GUI title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties). /// </param> /// <param name="property">Serializable property referencing a dictionary</param> /// <param name="layout">Layout to which to append the list GUI elements to.</param> /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple /// nested containers whose backgrounds are overlaping. Also determines background style, /// depths divisible by two will use an alternate style.</param> public static InspectableDictionaryGUI Create(Inspector parent, LocString title, string path, SerializableProperty property, GUILayout layout, int depth = 0) { InspectableDictionaryGUI guiDictionary = new InspectableDictionaryGUI(parent, title, path, property, layout, depth); guiDictionary.BuildGUI(); return guiDictionary; }
/// <summary> /// Creates a new inspectable field, automatically detecting the most appropriate implementation for the type /// contained in the provided serializable property. This may be one of the built-in inspectable field implemetations /// (like ones for primitives like int or bool), or a user defined implementation defined with a /// <see cref="CustomInspector"/> attribute. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="layoutIndex">Index into the parent layout at which to insert the GUI elements for the field .</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the array whose contents to display.</param> /// <param name="style">Information related the field style</param> /// <returns>Inspectable field implementation that can be used for displaying the GUI for a serializable property /// of the provided type.</returns> public static InspectableField CreateInspectable(Inspector parent, string title, string path, int layoutIndex, int depth, InspectableFieldLayout layout, SerializableProperty property, InspectableFieldStyleInfo style = null) { InspectableField field = null; Type customInspectable = InspectorUtility.GetCustomInspectable(property.InternalType); if (customInspectable != null) { field = (InspectableField) Activator.CreateInstance(customInspectable, depth, title, property); } else { switch (property.Type) { case SerializableProperty.FieldType.Int: if (style?.RangeStyle == null || !style.RangeStyle.Slider) { field = new InspectableInt(parent, title, path, depth, layout, property, style); } else { field = new InspectableRangedInt(parent, title, path, depth, layout, property, style); } break; case SerializableProperty.FieldType.Float: if (style?.RangeStyle == null || !style.RangeStyle.Slider) { field = new InspectableFloat(parent, title, path, depth, layout, property, style); } else { field = new InspectableRangedFloat(parent, title, path, depth, layout, property, style); } break; case SerializableProperty.FieldType.Bool: field = new InspectableBool(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Color: field = new InspectableColor(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.String: field = new InspectableString(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Vector2: field = new InspectableVector2(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Vector3: field = new InspectableVector3(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Vector4: field = new InspectableVector4(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.ResourceRef: field = new InspectableResourceRef(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.GameObjectRef: field = new InspectableGameObjectRef(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Object: field = new InspectableObject(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Array: field = new InspectableArray(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.List: field = new InspectableList(parent, title, path, depth, layout, property); break; case SerializableProperty.FieldType.Dictionary: field = new InspectableDictionary(parent, title, path, depth, layout, property); break; } } if (field == null) throw new Exception("No inspector exists for the provided field type."); field.Initialize(layoutIndex); field.Refresh(layoutIndex); return field; }
/// <inheritdoc/> protected internal override object CreateValue() { SerializableDictionary dictionary = property.GetDictionary(); DictionaryDataWrapper data = new DictionaryDataWrapper(); data.value = SerializableUtility.Create(dictionary.ValueType); SerializableProperty valueProperty = new SerializableProperty(dictionary.ValuePropertyType, dictionary.ValueType, () => data.value, (x) => data.value = x); return valueProperty; }
/// <summary> /// Registers a new animation curve field. /// </summary> /// <param name="path">Path of the field, see <see cref="GUIFieldSelector.OnElementSelected"/></param> /// <param name="type">Type of the field (float, vector, etc.)</param> private void AddNewField(string path, SerializableProperty.FieldType type) { bool noSelection = selectedFields.Count == 0; bool isPropertyCurve = !clipInfo.isImported && !EditorAnimClipInfo.IsMorphShapeCurve(path); switch (type) { case SerializableProperty.FieldType.Vector4: { FieldAnimCurves fieldCurves = new FieldAnimCurves(); fieldCurves.type = type; fieldCurves.isPropertyCurve = isPropertyCurve; fieldCurves.curveInfos = new CurveDrawInfo[4]; string[] subPaths = { ".x", ".y", ".z", ".w" }; for (int i = 0; i < subPaths.Length; i++) { string subFieldPath = path + subPaths[i]; fieldCurves.curveInfos[i].curve = new EdAnimationCurve(); selectedFields.Add(subFieldPath); } clipInfo.curves[path] = fieldCurves; } break; case SerializableProperty.FieldType.Vector3: { FieldAnimCurves fieldCurves = new FieldAnimCurves(); fieldCurves.type = type; fieldCurves.isPropertyCurve = isPropertyCurve; fieldCurves.curveInfos = new CurveDrawInfo[3]; string[] subPaths = { ".x", ".y", ".z" }; for (int i = 0; i < subPaths.Length; i++) { string subFieldPath = path + subPaths[i]; fieldCurves.curveInfos[i].curve = new EdAnimationCurve(); selectedFields.Add(subFieldPath); } clipInfo.curves[path] = fieldCurves; } break; case SerializableProperty.FieldType.Vector2: { FieldAnimCurves fieldCurves = new FieldAnimCurves(); fieldCurves.type = type; fieldCurves.isPropertyCurve = isPropertyCurve; fieldCurves.curveInfos = new CurveDrawInfo[2]; string[] subPaths = { ".x", ".y" }; for (int i = 0; i < subPaths.Length; i++) { string subFieldPath = path + subPaths[i]; fieldCurves.curveInfos[i].curve = new EdAnimationCurve(); selectedFields.Add(subFieldPath); } clipInfo.curves[path] = fieldCurves; } break; case SerializableProperty.FieldType.Color: { FieldAnimCurves fieldCurves = new FieldAnimCurves(); fieldCurves.type = type; fieldCurves.isPropertyCurve = isPropertyCurve; fieldCurves.curveInfos = new CurveDrawInfo[4]; string[] subPaths = { ".r", ".g", ".b", ".a" }; for (int i = 0; i < subPaths.Length; i++) { string subFieldPath = path + subPaths[i]; fieldCurves.curveInfos[i].curve = new EdAnimationCurve(); selectedFields.Add(subFieldPath); } clipInfo.curves[path] = fieldCurves; } break; default: // Primitive type { FieldAnimCurves fieldCurves = new FieldAnimCurves(); fieldCurves.type = type; fieldCurves.isPropertyCurve = isPropertyCurve; fieldCurves.curveInfos = new CurveDrawInfo[1]; fieldCurves.curveInfos[0].curve = new EdAnimationCurve(); selectedFields.Add(path); clipInfo.curves[path] = fieldCurves; } break; } UpdateCurveColors(); UpdateDisplayedFields(); EditorApplication.SetProjectDirty(); UpdateDisplayedCurves(noSelection); }
/// <summary> /// Creates a new instance of <see cref="ConstructStateArgs"/> /// </summary> /// <param name="property"></param> /// <param name="attributes"></param> /// <param name="levelType"></param> public ConstructStateArgs(SerializableProperty property, EnigmaSerializationAttributes attributes, LevelType levelType) { Property = property; Attributes = attributes; LevelType = levelType; }
/// <summary> /// Triggered by the field selector, when user selects a new curve field. /// </summary> /// <param name="path">Path of the selected curve field.</param> /// <param name="type">Type of the selected curve field (float, vector, etc.).</param> private void OnFieldAdded(string path, SerializableProperty.FieldType type) { // Remove the root scene object from the path (we know which SO it is, no need to hardcode its name in the path) string pathNoRoot = path.TrimStart('/'); int separatorIdx = pathNoRoot.IndexOf("/"); if (separatorIdx == -1 || (separatorIdx + 1) >= pathNoRoot.Length) return; pathNoRoot = pathNoRoot.Substring(separatorIdx + 1, pathNoRoot.Length - separatorIdx - 1); AddNewField(pathNoRoot, type); ApplyClipChanges(); }
/// <summary> /// Constructs a new dictionary GUI. /// </summary> /// <param name="context">Context shared by all inspectable fields created by the same parent.</param> /// <param name="title">Label to display on the list GUI title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties). /// </param> /// <param name="property">Serializable property referencing a dictionary</param> /// <param name="layout">Layout to which to append the list GUI elements to.</param> /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple /// nested containers whose backgrounds are overlaping. Also determines background style, /// depths divisible by two will use an alternate style.</param> protected InspectableDictionaryGUI(InspectableContext context, LocString title, string path, SerializableProperty property, GUILayout layout, int depth = 0) : base(title, layout, depth) { this.property = property; this.context = context; this.path = path; dictionary = property.GetValue <IDictionary>(); if (dictionary != null) { numElements = dictionary.Count; } UpdateKeys(); }
private static extern void Internal_CreateInstance(SerializableProperty instance, Type type);
public VineSprite(XElement element) { SerializableProperty.DeserializeProperties(this, element); AbsoluteOrigin = new Vector2(SourceRect.Width * Origin.X, SourceRect.Height * Origin.Y); }
public Limb(Ragdoll ragdoll, Character character, LimbParams limbParams) { this.ragdoll = ragdoll; this.character = character; this.Params = limbParams; wearingItems = new List <WearableSprite>(); dir = Direction.Right; body = new PhysicsBody(limbParams); type = limbParams.Type; if (limbParams.IgnoreCollisions) { body.CollisionCategories = Category.None; body.CollidesWith = Category.None; ignoreCollisions = true; } else { //limbs don't collide with each other body.CollisionCategories = Physics.CollisionCharacter; body.CollidesWith = Physics.CollisionAll & ~Physics.CollisionCharacter & ~Physics.CollisionItem & ~Physics.CollisionItemBlocking; } body.UserData = this; pullJoint = new FixedMouseJoint(body.FarseerBody, ConvertUnits.ToSimUnits(limbParams.PullPos * Scale)) { Enabled = false, //MaxForce = ((type == LimbType.LeftHand || type == LimbType.RightHand) ? 400.0f : 150.0f) * body.Mass // 150 or even 400 is too low if the joint is used for moving the character position from the mainlimb towards the collider position MaxForce = 1000 * Mass }; GameMain.World.Add(pullJoint); var element = limbParams.Element; body.BodyType = BodyType.Dynamic; foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "attack": attack = new Attack(subElement, (character == null ? "null" : character.Name) + ", limb " + type); if (attack.DamageRange <= 0) { switch (body.BodyShape) { case PhysicsBody.Shape.Circle: attack.DamageRange = body.radius; break; case PhysicsBody.Shape.Capsule: attack.DamageRange = body.height / 2 + body.radius; break; case PhysicsBody.Shape.Rectangle: attack.DamageRange = new Vector2(body.width / 2.0f, body.height / 2.0f).Length(); break; } attack.DamageRange = ConvertUnits.ToDisplayUnits(attack.DamageRange); } break; case "damagemodifier": DamageModifiers.Add(new DamageModifier(subElement, character.Name)); break; case "statuseffect": statusEffects.Add(StatusEffect.Load(subElement, Name)); break; } } SerializableProperties = SerializableProperty.GetProperties(this); InitProjSpecific(element); }
public static bool MergeFromLineContainer(LineContainer lc) { CheckTime ct = new CheckTime(false, "MergeFromLineContainer() entered"); long lOperationMask = 0L; eServerSourceType esst = eServerSourceType.BtrPre; if (lc.Attributes.ContainsKey("line")) { string sLine = lc.Attributes["line"]; ExcpHelper.ThrowIf(!Enum.TryParse(sLine, true, out esst), "Cannot parse LineType from '{0}'", sLine); } string sType = lc.Attributes["type"]; string sMessageId = lc.Attributes["messageid"]; try { /* * sTrace += string.Format("{0} docid={1}\r\n", sTrace, sMessageId); * * if (bExtendTrace) * { * sTrace += lc.BuildTraceString(); * } */ // TimeTypeLn { TimeTypeDictionary ttd = LineSr.Instance.AllObjects.GetLineObjectCollection <TimeTypeLn>() as TimeTypeDictionary; int iCount = LineSr.MergeLineObjects <TimeTypeLn>(lc, ttd, new LineSr.MergeLineObjectsCallBack <TimeTypeLn>() { GetLineObject = delegate(ISerializableObject so) { SerializableProperty <string> spTag = so.GetSerializableProperty("Tag") as SerializableProperty <string>; return(ttd.GetObject(spTag.Value)); }, CreateLineObject = delegate() { return(new TimeTypeLn()); } }); ct.AddEvent("TimeType(s) Succeeded ({0})", iCount); } // ScoreTypeLn { ScoreTypeDictionary std = LineSr.Instance.AllObjects.GetLineObjectCollection <ScoreTypeLn>() as ScoreTypeDictionary; int iCount = LineSr.MergeLineObjects <ScoreTypeLn>(lc, std, new LineSr.MergeLineObjectsCallBack <ScoreTypeLn>() { GetLineObject = delegate(ISerializableObject so) { SerializableProperty <string> spTag = so.GetSerializableProperty("Tag") as SerializableProperty <string>; return(std.GetObject(spTag.Value)); }, CreateLineObject = delegate() { return(new ScoreTypeLn()); } }); ct.AddEvent("ScoreType(s) Succeeded ({0})", iCount); } // BetTypeLn { BetTypeDictionary btd = LineSr.Instance.AllObjects.GetLineObjectCollection <BetTypeLn>() as BetTypeDictionary; int iCount = LineSr.MergeLineObjects <BetTypeLn>(lc, btd, new LineSr.MergeLineObjectsCallBack <BetTypeLn>() { GetLineObject = delegate(ISerializableObject so) { SerializableProperty <string> spTag = so.GetSerializableProperty("Tag") as SerializableProperty <string>; return(btd.GetObject(spTag.Value)); }, CreateLineObject = delegate() { return(new BetTypeLn()); } }); ct.AddEvent("BetType(s) Succeeded ({0})", iCount); } // BetDomainTypeLn { BetDomainTypeDictionary bdtd = LineSr.Instance.AllObjects.GetLineObjectCollection <BetDomainTypeLn>() as BetDomainTypeDictionary; int iCount = LineSr.MergeLineObjects <BetDomainTypeLn>(lc, bdtd, new LineSr.MergeLineObjectsCallBack <BetDomainTypeLn>() { GetLineObject = delegate(ISerializableObject so) { SerializableProperty <string> spTag = so.GetSerializableProperty("Tag") as SerializableProperty <string>; return(bdtd.GetObject(spTag.Value)); }, CreateLineObject = delegate() { return(new BetDomainTypeLn()); } }); ct.AddEvent("BetDomainType(s) Succeeded ({0})", iCount); } // Groups { GroupDictionary gd = LineSr.Instance.AllObjects.GetLineObjectCollection <GroupLn>() as GroupDictionary; int iCount = LineSr.MergeLineObjects <GroupLn>(lc, gd, new LineSr.MergeLineObjectsCallBack <GroupLn>() { GetLineObject = delegate(ISerializableObject so) { // 143881406612 SerializableProperty <string> spType = so.GetSerializableProperty("Type") as SerializableProperty <string>; SerializableProperty <long> spSvrId = so.GetSerializableProperty("SvrGroupId") as SerializableProperty <long>; Debug.Assert(spType != null); Debug.Assert(spSvrId != null); return(gd.SafelyGetGroupByKeyName(spType.Value, spSvrId.Value)); }, CreateLineObject = delegate() { return(new GroupLn()); } }); ct.AddEvent("Group(s) Succeeded ({0})", iCount); } // Competitors { CompetitorDictionary cd = LineSr.Instance.AllObjects.GetLineObjectCollection <CompetitorLn>() as CompetitorDictionary; int iCount = LineSr.MergeLineObjects <CompetitorLn>(lc, cd, new LineSr.MergeLineObjectsCallBack <CompetitorLn>() { GetLineObject = delegate(ISerializableObject so) { SerializableProperty <long> spCompetitor = so.GetSerializableProperty("CompetitorId") as SerializableProperty <long>; Debug.Assert(spCompetitor != null); return(cd.GetObject(spCompetitor.Value)); }, CreateLineObject = delegate() { return(new CompetitorLn()); } }); ct.AddEvent("Competitor(s) Succeeded ({0})", iCount); } // CompetitorToOutrightLn { var cd = LineSr.Instance.AllObjects.GetLineObjectCollection <CompetitorToOutrightLn>() as CompetitorToOutrightDictionary; int iCount = LineSr.MergeLineObjects <CompetitorToOutrightLn>(lc, cd, new LineSr.MergeLineObjectsCallBack <CompetitorToOutrightLn>() { GetLineObject = delegate(ISerializableObject so) { SerializableProperty <long> spCompetitor = so.GetSerializableProperty("match2competitorid") as SerializableProperty <long>; Debug.Assert(spCompetitor != null); return(cd.GetObject(spCompetitor.Value)); }, CreateLineObject = delegate() { return(new CompetitorToOutrightLn()); } }); ct.AddEvent("Competitor(s) Succeeded ({0})", iCount); } // Strings { TaggedStringDictionary tsd = LineSr.Instance.AllObjects.GetLineObjectCollection <TaggedStringLn>() as TaggedStringDictionary; int iCount = LineSr.MergeLineObjects <TaggedStringLn>(lc, tsd, new LineSr.MergeLineObjectsCallBack <TaggedStringLn>() { GetLineObject = delegate(ISerializableObject so) { SerializableProperty <long> spStringId = so.GetSerializableProperty("StringId") as SerializableProperty <long>; return(tsd.GetObject(spStringId.Value)); }, CreateLineObject = delegate() { return(new TaggedStringLn()); } }); ct.AddEvent("String(s) Succeeded ({0})", iCount); } SyncList <MatchLn> lMatchesToRemove = new SyncList <MatchLn>(); // Matches { SyncHashSet <long> lMatchIds = new SyncHashSet <long>(); MatchDictionary md = LineSr.Instance.AllObjects.GetLineObjectCollection <MatchLn>() as MatchDictionary; int iCount = LineSr.MergeLineObjects <MatchLn>(lc, md, new LineSr.MergeLineObjectsCallBack <MatchLn>() { GetLineObject = delegate(ISerializableObject so) { SerializableProperty <long> spMatchId = so.GetSerializableProperty("MatchId") as SerializableProperty <long>; lMatchIds.Add(spMatchId.Value); return(md.GetObject(spMatchId.Value)); }, CreateLineObject = delegate() { return(new MatchLn()); }, OnLineObjectMerged = delegate(MatchLn match) { if (match != null) { if (match.Code.Value == 0) { match.Code.Value = Math.Abs((int)(match.MatchId % 100000)); } if (match.EndDate.Value == null) { match.EndDate.Value = new DateTimeSr(DateTime.MaxValue); } } }, RemoveLineObject = delegate(MatchLn match) { lMatchesToRemove.Add(match); } }, ref lOperationMask); if (sType.ToLowerInvariant() == "initial") { SyncList <MatchLn> lAllLiveMatches = LineSr.Instance.QuickSearchMatches(delegate(MatchLn match) { return(match.IsLiveBet.Value && match.SourceType == esst); }); foreach (var match in lAllLiveMatches) { if (!lMatchIds.Contains(match.MatchId)) { lMatchesToRemove.Add(match); } } } ct.AddEvent("Match(es) Succeeded ({0})", iCount); } // MatchToGroup items { MatchToGroupDictionary mtogd = LineSr.Instance.AllObjects.GetLineObjectCollection <MatchToGroupLn>() as MatchToGroupDictionary; int iCount = LineSr.MergeLineObjects <MatchToGroupLn>(lc, mtogd, new LineSr.MergeLineObjectsCallBack <MatchToGroupLn>() { GetLineObject = delegate(ISerializableObject so) { SerializableProperty <long> spMatchId = so.GetSerializableProperty("MatchId") as SerializableProperty <long>; SerializableProperty <long> spGroupId = so.GetSerializableProperty("GroupId") as SerializableProperty <long>; return(mtogd.GetObject(MatchToGroupLn.GetKeyName(spMatchId.Value, spGroupId.Value))); }, CreateLineObject = delegate() { return(new MatchToGroupLn()); } }); ct.AddEvent("MatchToGroup(s) Succeeded ({0})", iCount); } // LiveMatchInfo { LiveMatchInfoDictionary lmid = LineSr.Instance.AllObjects.GetLineObjectCollection <LiveMatchInfoLn>() as LiveMatchInfoDictionary; int iCount = LineSr.MergeLineObjects <LiveMatchInfoLn>(lc, lmid, new LineSr.MergeLineObjectsCallBack <LiveMatchInfoLn>() { GetLineObject = delegate(ISerializableObject so) { SerializableProperty <long> spMatchId = so.GetSerializableProperty("MatchId") as SerializableProperty <long>; return(lmid.GetObject(spMatchId.Value)); }, CreateLineObject = delegate() { return(new LiveMatchInfoLn()); }, OnLineObjectMerged = delegate(LiveMatchInfoLn matchInfo) { if (matchInfo != null) { if (matchInfo.ExpiryDate.Value == null) { matchInfo.ExpiryDate.Value = new DateTimeSr(DateTime.Now.AddMinutes(30)); // Half an hour } if (matchInfo.ChangedProps.Contains(matchInfo.PeriodInfo)) { lOperationMask |= (long)eOperationMask.MatchPeriodInfoChanged; } } }, RemoveLineObject = delegate(LiveMatchInfoLn lmi) { } }); ct.AddEvent("LiveMatchInfo(s) Succeeded ({0})", iCount); } // BetDomainLn { BetDomainDictionary bdmd = LineSr.Instance.AllObjects.GetLineObjectCollection <BetDomainLn>() as BetDomainDictionary; int iCount = LineSr.MergeLineObjects <BetDomainLn>(lc, bdmd, new LineSr.MergeLineObjectsCallBack <BetDomainLn>() { GetLineObject = delegate(ISerializableObject so) { SerializableProperty <long> spBetDomainId = so.GetSerializableProperty("BetDomainId") as SerializableProperty <long>; return(bdmd.GetObject(spBetDomainId.Value)); }, CreateLineObject = delegate() { return(new BetDomainLn()); }, RemoveLineObject = delegate(BetDomainLn bdmn) { LineSr.Instance.RemoveBetDomain(bdmn); } }, ref lOperationMask); ct.AddEvent("BetDomain(s) Succeeded ({0})", iCount); } // OddLn { OddDictionary oddd = LineSr.Instance.AllObjects.GetLineObjectCollection <OddLn>() as OddDictionary; int iCount = LineSr.MergeLineObjects <OddLn>(lc, oddd, new LineSr.MergeLineObjectsCallBack <OddLn>() { GetLineObject = delegate(ISerializableObject so) { SerializableProperty <long> spOutcomeId = so.GetSerializableProperty("OutcomeId") as SerializableProperty <long>; return(oddd.GetObject(spOutcomeId.Value)); }, CreateLineObject = delegate() { return(new OddLn()); }, RemoveLineObject = delegate(OddLn odd) { odd.Active.Value = false; //LineSr.Instance.RemoveOdd(odd); } }); ct.AddEvent("Odd(s) Succeeded ({0})", iCount); } // Process Removed matches foreach (var match in lMatchesToRemove) { LiveMatchInfoLn lmi = match.LiveMatchInfo; if (lmi.Status.Value == eMatchStatus.Ended && match.SourceType == eServerSourceType.BtrLive) { MergeMatchResult(match); } LineSr.Instance.RemoveMatch(match); } } catch (Exception excp) { ct.AddEvent("ERROR"); m_logger.Error(excp.Message, excp); m_logger.Excp(excp, "MergeFromLigaStavok() ERROR"); throw; } finally { //m_logger.Info(sTrace); //m_logger.DebugFormat("LineContainer Trace Length = {0}", sTrace.Length); ct.AddEvent("MergeFromLigaStavok(Type={0}, MessageId={1}) completed", sType, sMessageId); ct.Info(m_logger); } #if DEBUG if ((lOperationMask & EVENT_REASON_MASK) > 0) { m_logger.InfoFormat("MergeFromLineContainer() result {0}", lOperationMask); } #endif return(true); }
/// <summary> /// Creates a new inspectable texture reference GUI for the specified property. /// </summary> /// <param name="context">Context shared by all inspectable fields created by the same parent.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the field whose contents to display.</param> public InspectableTexture(InspectableContext context, string title, string path, int depth, InspectableFieldLayout layout, SerializableProperty property, InspectableFieldStyleInfo style) : base(context, title, path, property.Type, depth, layout, property) { }
/// <summary> /// Creates a new inspectable array GUI for the specified property. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the array whose contents to display.</param> /// <param name="style">Information that can be used for customizing field rendering and behaviour.</param> public InspectableArray(Inspector parent, string title, string path, int depth, InspectableFieldLayout layout, SerializableProperty property, InspectableFieldStyleInfo style) : base(parent, title, path, SerializableProperty.FieldType.Array, depth, layout, property) { this.style = style; }
/// <summary> /// Creates a new inspectable 2D vector distribution GUI for the specified property. /// </summary> /// <param name="context">Context shared by all inspectable fields created by the same parent.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the field whose contents to display.</param> public InspectableVector2Distribution(InspectableContext context, string title, string path, int depth, InspectableFieldLayout layout, SerializableProperty property) : base(context, title, path, SerializableProperty.FieldType.Vector2Distribution, depth, layout, property) { }
public ServerSettings(NetworkMember networkMember, string serverName, int port, int queryPort, int maxPlayers, bool isPublic, bool enableUPnP) { ServerLog = new ServerLog(serverName); Voting = new Voting(); Whitelist = new WhiteList(); BanList = new BanList(); ExtraCargo = new Dictionary <ItemPrefab, int>(); PermissionPreset.LoadAll(PermissionPresetFile); InitProjSpecific(); ServerName = serverName; Port = port; QueryPort = queryPort; EnableUPnP = enableUPnP; MaxPlayers = maxPlayers; IsPublic = isPublic; netProperties = new Dictionary <UInt32, NetPropertyData>(); using (MD5 md5 = MD5.Create()) { var saveProperties = SerializableProperty.GetProperties <Serialize>(this); foreach (var property in saveProperties) { object value = property.GetValue(this); if (value == null) { continue; } string typeName = SerializableProperty.GetSupportedTypeName(value.GetType()); if (typeName != null || property.PropertyType.IsEnum) { NetPropertyData netPropertyData = new NetPropertyData(this, property, typeName); UInt32 key = ToolBox.StringToUInt32Hash(property.Name, md5); if (netProperties.ContainsKey(key)) { throw new Exception("Hashing collision in ServerSettings.netProperties: " + netProperties[key] + " has same key as " + property.Name + " (" + key.ToString() + ")"); } netProperties.Add(key, netPropertyData); } } var karmaProperties = SerializableProperty.GetProperties <Serialize>(networkMember.KarmaManager); foreach (var property in karmaProperties) { object value = property.GetValue(networkMember.KarmaManager); if (value == null) { continue; } string typeName = SerializableProperty.GetSupportedTypeName(value.GetType()); if (typeName != null || property.PropertyType.IsEnum) { NetPropertyData netPropertyData = new NetPropertyData(networkMember.KarmaManager, property, typeName); UInt32 key = ToolBox.StringToUInt32Hash(property.Name, md5); if (netProperties.ContainsKey(key)) { throw new Exception("Hashing collision in ServerSettings.netProperties: " + netProperties[key] + " has same key as " + property.Name + " (" + key.ToString() + ")"); } netProperties.Add(key, netPropertyData); } } } }
public override void GenerateSerializationMethod(StringBuilder source, string indent, SerializableProperty property) { var expectedRule = RuleName; var ruleName = property.Rule; if (expectedRule != ruleName) { throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}."); } var propertyName = property.Name; source.AppendLine($"{indent}writer.Write({propertyName});"); }
private void GeneratePropertyCode(MethodArgILCodeVariable graphVariable, SerializableProperty target) { var extPropertyType = target.Ext; var argsField = _context.GetArgsField(target); var argsFieldVariable = _il.Var.Field(_il.Var.This(), argsField); if (extPropertyType.IsValueOrNullableOfValue()) { var isNullable = extPropertyType.Class == TypeClass.Nullable; var isEnum = extPropertyType.IsEnum(); var isValueType = extPropertyType.Ref.IsValueType; var mediatorPropertyType = isEnum ? extPropertyType.GetUnderlyingEnumType() : extPropertyType.Ref; var valueType = !isNullable && isValueType ? Members.Nullable[mediatorPropertyType].NullableType : mediatorPropertyType; var valueLocal = _il.DeclareLocal("value", valueType); _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorTryVisitValue[valueType], argsFieldVariable, valueLocal); if (isValueType && !isNullable) { var labelValueNotFound = _il.DefineLabel(); _il.TransferLongIfFalse(labelValueNotFound); _il.Snippets.InvokeMethod(valueLocal, Members.Nullable[mediatorPropertyType].GetHasValue); _il.Negate(); var nullableHasValueLabel = _il.DefineLabel(); _il.TransferLong(nullableHasValueLabel); _il.MarkLabel(labelValueNotFound); _il.LoadValue(true); _il.MarkLabel(nullableHasValueLabel); } else { _il.Negate(); } var skipSetValueLabel = _il.DefineLabel(); _il.TransferLongIfTrue(skipSetValueLabel); var valueToAdd = (isValueType && !isNullable) ? new CallMethodILCode(valueLocal, Members.Nullable[mediatorPropertyType].GetValue) : (ILCodeParameter)valueLocal; _il.Snippets.SetPropertyValue(graphVariable, target.Ref, valueToAdd); _il.MarkLabel(skipSetValueLabel); } else if (extPropertyType.Class == TypeClass.Dictionary) { _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorTryVisit, argsFieldVariable); var stateLocal = _il.DeclareLocal("state", typeof(ValueState)); _il.Var.Set(stateLocal); _il.Snippets.AreEqual(stateLocal, (int)ValueState.NotFound); var endLabel = _il.DefineLabel(); _il.TransferLongIfTrue(endLabel); _il.Snippets.AreEqual(stateLocal, (int)ValueState.Found); var nullLabel = _il.DefineLabel(); _il.TransferLongIfFalse(nullLabel); var dictionaryLocal = GenerateDictionaryEnumerateCode(target.Ref.PropertyType, target.Ref.Name); _il.Snippets.SetPropertyValue(graphVariable, target.Ref, dictionaryLocal.Cast(target.Ref.PropertyType)); _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorLeave, argsFieldVariable); _il.TransferLong(endLabel); _il.MarkLabel(nullLabel); _il.Snippets.SetPropertyValue(graphVariable, target.Ref, null); _il.MarkLabel(endLabel); } else if (extPropertyType.Class == TypeClass.Collection) { _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorTryVisit, argsFieldVariable); var stateLocal = _il.DeclareLocal("state", typeof(ValueState)); _il.Var.Set(stateLocal); _il.Snippets.AreEqual(stateLocal, (int)ValueState.NotFound); var endLabel = _il.DefineLabel(); _il.TransferLongIfTrue(endLabel); _il.Snippets.AreEqual(stateLocal, (int)ValueState.Found); var nullLabel = _il.DefineLabel(); _il.TransferLongIfFalse(nullLabel); var collectionParam = GenerateCollectionContent(extPropertyType, target.Ref.Name); _il.Snippets.SetPropertyValue(graphVariable, target.Ref, collectionParam); _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorLeave, argsFieldVariable); _il.TransferLong(endLabel); _il.MarkLabel(nullLabel); _il.Snippets.SetPropertyValue(graphVariable, target.Ref, null); _il.MarkLabel(endLabel); } else { _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorTryVisit, argsFieldVariable); var stateLocal = _il.DeclareLocal("state", typeof(ValueState)); _il.Var.Set(stateLocal); _il.IfNotEqual(stateLocal, (int)ValueState.NotFound) .Then(() => { _il.IfEqual(stateLocal, (int)ValueState.Found) .Then(() => { var singleLocal = _il.DeclareLocal("single", extPropertyType.Ref); GenerateCreateAndChildCallCode(singleLocal); _il.Snippets.SetPropertyValue(graphVariable, target.Ref, singleLocal); _il.Snippets.InvokeMethod(_visitorVariable, Members.VisitorLeave, argsFieldVariable); }).Else(() => { _il.Snippets.SetPropertyValue(graphVariable, target.Ref, null); }).End(); }).End(); } }
public void GenerateDeserializationMethod(StringBuilder source, string indent, SerializableProperty property, string?parentReference) { var expectedRule = RuleName; var ruleName = property.Rule; if (expectedRule != ruleName) { throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}."); } var ruleArguments = property.RuleArguments; var index = 1; var keyType = ruleArguments ![index++];
/// <summary> /// Constructs a new empty inspectable list GUI. /// </summary> /// <param name="parent">Parent Inspector this field belongs to.</param> /// <param name="title">Label to display on the list GUI title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties). /// </param> /// <param name="property">Serializable property referencing a list.</param> /// <param name="layout">Layout to which to append the list GUI elements to.</param> /// <param name="depth">Determines at which depth to render the background. Useful when you have multiple /// nested containers whose backgrounds are overlaping. Also determines background style, /// depths divisible by two will use an alternate style.</param> public InspectableListGUI(Inspector parent, LocString title, string path, SerializableProperty property, GUILayout layout, int depth) : base(title, layout, depth) { this.property = property; this.parent = parent; this.path = path; list = property.GetValue <IList>(); if (list != null) { numElements = list.Count; } }
public ComplexGraphProperty(SerializableProperty property, IGraphType propertyType) { _property = property; _propertyType = propertyType; _args = property.CreateVisitArgs(); }
public void GenerateDeserializationMethod(StringBuilder source, string indent, SerializableProperty property, string?parentReference) { var expectedRule = RuleName; var ruleName = property.Rule; if (expectedRule != ruleName) { throw new ArgumentException($"Invalid rule applied to property {ruleName}. Expecting {expectedRule}, but received {ruleName}."); } source.AppendLine($"{indent}{property.Name} = reader.ReadEnum<{property.Type}>();"); }
private void LoadSettings() { XDocument doc = null; if (File.Exists(SettingsFile)) { doc = XMLExtensions.TryLoadXml(SettingsFile); } if (doc == null) { doc = new XDocument(new XElement("serversettings")); } SerializableProperties = SerializableProperty.DeserializeProperties(this, doc.Root); AutoRestart = doc.Root.GetAttributeBool("autorestart", false); Voting.AllowSubVoting = SubSelectionMode == SelectionMode.Vote; Voting.AllowModeVoting = ModeSelectionMode == SelectionMode.Vote; selectedLevelDifficulty = doc.Root.GetAttributeFloat("LevelDifficulty", 20.0f); GameMain.NetLobbyScreen.SetLevelDifficulty(selectedLevelDifficulty); GameMain.NetLobbyScreen.SetTraitorsEnabled(traitorsEnabled); string[] defaultAllowedClientNameChars = new string[] { "32-33", "38-46", "48-57", "65-90", "91", "93", "95-122", "192-255", "384-591", "1024-1279", "19968-40959", "13312-19903", "131072-15043983", "15043985-173791", "173824-178207", "178208-183983", "63744-64255", "194560-195103" //CJK }; string[] allowedClientNameCharsStr = doc.Root.GetAttributeStringArray("AllowedClientNameChars", defaultAllowedClientNameChars); if (doc.Root.GetAttributeString("AllowedClientNameChars", "") == "65-90,97-122,48-59") { allowedClientNameCharsStr = defaultAllowedClientNameChars; } foreach (string allowedClientNameCharRange in allowedClientNameCharsStr) { string[] splitRange = allowedClientNameCharRange.Split('-'); if (splitRange.Length == 0 || splitRange.Length > 2) { DebugConsole.ThrowError("Error in server settings - " + allowedClientNameCharRange + " is not a valid range for characters allowed in client names."); continue; } int min = -1; if (!int.TryParse(splitRange[0], out min)) { DebugConsole.ThrowError("Error in server settings - " + allowedClientNameCharRange + " is not a valid range for characters allowed in client names."); continue; } int max = min; if (splitRange.Length == 2) { if (!int.TryParse(splitRange[1], out max)) { DebugConsole.ThrowError("Error in server settings - " + allowedClientNameCharRange + " is not a valid range for characters allowed in client names."); continue; } } if (min > -1 && max > -1) { AllowedClientNameChars.Add(new Pair <int, int>(min, max)); } } AllowedRandomMissionTypes = new List <MissionType>(); string[] allowedMissionTypeNames = doc.Root.GetAttributeStringArray( "AllowedRandomMissionTypes", Enum.GetValues(typeof(MissionType)).Cast <MissionType>().Select(m => m.ToString()).ToArray()); foreach (string missionTypeName in allowedMissionTypeNames) { if (Enum.TryParse(missionTypeName, out MissionType missionType)) { if (missionType == Barotrauma.MissionType.None) { continue; } AllowedRandomMissionTypes.Add(missionType); } } ServerName = doc.Root.GetAttributeString("name", ""); if (ServerName.Length > NetConfig.ServerNameMaxLength) { ServerName = ServerName.Substring(0, NetConfig.ServerNameMaxLength); } ServerMessageText = doc.Root.GetAttributeString("ServerMessage", ""); GameMain.NetLobbyScreen.SelectedModeIdentifier = GameModeIdentifier; //handle Random as the mission type, which is no longer a valid setting //MissionType.All offers equivalent functionality if (MissionType == "Random") { MissionType = "All"; } GameMain.NetLobbyScreen.MissionTypeName = MissionType; GameMain.NetLobbyScreen.SetBotSpawnMode(BotSpawnMode); GameMain.NetLobbyScreen.SetBotCount(BotCount); List <string> monsterNames = CharacterPrefab.Prefabs.Select(p => p.Identifier).ToList(); MonsterEnabled = new Dictionary <string, bool>(); foreach (string s in monsterNames) { if (!MonsterEnabled.ContainsKey(s)) { MonsterEnabled.Add(s, true); } } }
public Int16GraphProperty(SerializableProperty property) { _property = property; _args = property.CreateVisitArgs(); }
protected SpriteDeformation(XElement element, SpriteDeformationParams deformationParams) { this.Params = deformationParams; SerializableProperty.DeserializeProperties(deformationParams, element); Deformation = new Vector2[deformationParams.Resolution.X, deformationParams.Resolution.Y]; }
/// <summary> /// Creates a new inspectable color GUI for the specified property. /// </summary> /// <param name="context">Context shared by all inspectable fields created by the same parent.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the field whose contents to display.</param> public InspectableColor(InspectableContext context, string title, string path, int depth, InspectableFieldLayout layout, SerializableProperty property) : base(context, title, path, SerializableProperty.FieldType.Color, depth, layout, property) { }
public virtual void Save(XElement element) { SerializableProperty.SerializeProperties(Params, element); }
/// <summary> /// Creates a new inspectable ranged field GUI for the specified property. /// </summary> /// <param name="context">Context shared by all inspectable fields created by the same parent.</param> /// <param name="title">Name of the property, or some other value to set as the title.</param> /// <param name="path">Full path to this property (includes name of this property and all parent properties).</param> /// <param name="type">Type of property this field will be used for displaying.</param> /// <param name="depth">Determines how deep within the inspector nesting hierarchy is this field. Some fields may /// contain other fields, in which case you should increase this value by one.</param> /// <param name="layout">Parent layout that all the field elements will be added to.</param> /// <param name="property">Serializable property referencing the field whose contents to display.</param> /// <param name="style">Contains information about the field style</param> public InspectableRangedField(InspectableContext context, string title, string path, SerializableProperty.FieldType type, int depth, InspectableFieldLayout layout, SerializableProperty property, InspectableFieldStyleInfo style) : base(context, title, path, type, depth, layout, property) { this.style = style; }
/// <summary> /// Searches the scene object hierarchy to find a property at the given path. /// </summary> /// <param name="root">Root scene object to which the path is relative to.</param> /// <param name="path">Path to the property, where each element of the path is separated with "/". /// /// Path elements prefixed with "!" signify names of child scene objects (first one relative to /// <paramref name="root"/>. Name of the root element should not be included in the path. /// /// Path element prefixed with ":" signify names of components. If a path doesn't have a /// component element, it is assumed the field is relative to the scene object itself (only /// "Translation", "Rotation" and "Scale" fields are supported in such case). Only one component /// path element per path is allowed. /// /// Path entries with no prefix are considered regular script object fields. Each path must have /// at least one such entry. /// /// A field path can be followed by an indexer [n] where n is a zero-based index. Such paths /// are assumed to be referencing an index within an array or a list. /// /// A field path can also be followed by a suffix (after the indexer, if any) separated from the /// path name with ".". This suffix is not parsed internally, but will be returned as /// <paramref name="suffix"/>. /// /// Path examples: /// :MyComponent/myInt (path to myInt variable on a component attached to this object) /// :MyComponent/myArray[0] (path to first element of myArray on the same component) /// !childSO/:MyComponent/myInt (path to myInt variable on a child scene object) /// !childSO/Translation (path to the scene object translation) /// :MyComponent/myVector.z (path to the z component of myVector on this object) /// </param> /// <param name="suffix">Suffix of the last field entry, if it has any. Contains the suffix separator ".".</param> /// <returns>If found, property object you can use for setting and getting the value from the property, otherwise /// null.</returns> internal static SerializableProperty FindProperty(SceneObject root, string path, out string suffix) { suffix = null; if (string.IsNullOrEmpty(path) || root == null) return null; string trimmedPath = path.Trim('/'); string[] entries = trimmedPath.Split('/'); // Find scene object referenced by the path SceneObject so = root; int pathIdx = 0; for (; pathIdx < entries.Length; pathIdx++) { string entry = entries[pathIdx]; if (string.IsNullOrEmpty(entry)) continue; // Not a scene object, break if (entry[0] != '!') break; string childName = entry.Substring(1, entry.Length - 1); so = so.FindChild(childName); if (so == null) break; } // Child scene object couldn't be found if (so == null) return null; // Path too short, no field entry if (pathIdx >= entries.Length) return null; // Check if path is referencing a component, and if so find it Component component = null; { string entry = entries[pathIdx]; if (entry[0] == ':') { string componentName = entry.Substring(1, entry.Length - 1); Component[] components = so.GetComponents(); component = Array.Find(components, x => x.GetType().Name == componentName); // Cannot find component with specified type if (component == null) return null; } } // Look for a field within a component if (component != null) { pathIdx++; if (pathIdx >= entries.Length) return null; SerializableObject componentObj = new SerializableObject(component); StringBuilder pathBuilder = new StringBuilder(); for (; pathIdx < entries.Length - 1; pathIdx++) pathBuilder.Append(entries[pathIdx] + "/"); // Check last path entry for suffix and remove it int suffixIdx = entries[pathIdx].LastIndexOf("."); if (suffixIdx != -1) { string entryNoSuffix = entries[pathIdx].Substring(0, suffixIdx); suffix = entries[pathIdx].Substring(suffixIdx, entries[pathIdx].Length - suffixIdx); pathBuilder.Append(entryNoSuffix); } else pathBuilder.Append(entries[pathIdx]); return componentObj.FindProperty(pathBuilder.ToString()); } else // Field is one of the builtin ones on the SceneObject itself { if ((pathIdx + 1) < entries.Length) return null; string entry = entries[pathIdx]; if (entry == "Position") { SerializableProperty property = new SerializableProperty( SerializableProperty.FieldType.Vector3, typeof(Vector3), () => so.LocalPosition, (x) => so.LocalPosition = (Vector3)x); return property; } else if (entry == "Rotation") { SerializableProperty property = new SerializableProperty( SerializableProperty.FieldType.Vector3, typeof(Vector3), () => so.LocalRotation.ToEuler(), (x) => so.LocalRotation = Quaternion.FromEuler((Vector3)x)); return property; } else if (entry == "Scale") { SerializableProperty property = new SerializableProperty( SerializableProperty.FieldType.Vector3, typeof(Vector3), () => so.LocalScale, (x) => so.LocalScale = (Vector3)x); return property; } return null; } }