Beispiel #1
0
        public static VisualElement GetElementOfFloatField(float startValue, string fieldName, Action <object> setValue, Action <object> getValue)
        {
            FloatField field = new FloatField(fieldName);

            field.SetValueWithoutNotify(startValue);
            field.RegisterValueChangedCallback(s => setValue.Invoke(s.newValue));
            getValue += o => field.SetValueWithoutNotify((float)o);
            return(field);
        }
Beispiel #2
0
        public ValueSlider(string label, float start, float end, SliderDirection direction, int pageSize,
                           float defaultValue = 0f) : base(label, start, end, direction, pageSize)
        {
            var newFloatField = new FloatField();

            value = defaultValue;
            this.RegisterValueChangedCallback(evt => { newFloatField.SetValueWithoutNotify(evt.newValue); });
            newFloatField.RegisterValueChangedCallback(evt => { value = evt.newValue; });
            Add(newFloatField);
            newFloatField.SetValueWithoutNotify(value);
        }
 static void ClampFloatFieldValue(float value, FloatField ff)
 {
     (float item1, float item2) = k_FloatFieldRanges[ff];
     if (value < item1)
     {
         ff.SetValueWithoutNotify(item1);
     }
     else if (value > item2)
     {
         ff.SetValueWithoutNotify(item2);
     }
 }
Beispiel #4
0
        VisualElement CreateLightExposureContent()
        {
            var exposure = SceneView.s_DrawModeExposure;

            var root = new VisualElement();

            root.AddToClassList(k_SliderRowClass);

            var icon = new Image()
            {
                name = "exposure-label"
            };

            m_ExposureSlider = new Slider(-m_ExposureMax, m_ExposureMax)
            {
                name = "exposure-slider"
            };
            m_ExposureSlider.AddToClassList(k_SliderClass);
            m_ExposureSlider.RegisterValueChangedCallback(SetBakedExposure);
            m_ExposureSlider.SetValueWithoutNotify(exposure);

            m_ExposureField = new FloatField()
            {
                name = "exposure-float-field"
            };
            m_ExposureField.AddToClassList(k_SliderFloatFieldClass);
            m_ExposureField.RegisterValueChangedCallback(SetBakedExposure);
            m_ExposureField.SetValueWithoutNotify(exposure);

            root.Add(icon);
            root.Add(m_ExposureSlider);
            root.Add(m_ExposureField);
            return(root);
        }
        public virtual void LoadData(AnimationGraphView graphView, NodeAsset nodeAsset, Dictionary <NodeAsset, BaseNodeUI> nodeMap)
        {
            ID = string.IsNullOrEmpty(nodeAsset.ID) ? Guid.NewGuid().ToString() : nodeAsset.ID;

            NameField.SetValueWithoutNotify(string.IsNullOrEmpty(nodeAsset.Data.Name) ? DefaultName : nodeAsset.Data.Name);
            _speedField.SetValueWithoutNotify(nodeAsset.Data.Speed);
        }
        public BaseNodeUI()
        {
            VisualElement container = new VisualElement();

            title = DefaultName;
            Label titleLabel = (Label)titleContainer[0];

            titleContainer.RemoveAt(0);

            NameField = new TextField();
            NameField.style.flexGrow = 1f;

            container.Add(titleLabel);
            container.Add(NameField);

            titleContainer.Insert(0, container);

            _speedField = new FloatField("Speed");
            _speedField.SetValueWithoutNotify(1f);
            _speedField.AddToClassList("speed-field");
            mainContainer.Insert(1, _speedField);

            RefreshExpandedState();
            RefreshPorts();
        }
Beispiel #7
0
        VisualElement CreateSliderWithField(GUIContent label, float value, float min, float max, EventCallback <ChangeEvent <float> > callback)
        {
            var root = new VisualElement()
            {
                name = "Slider Float Field"
            };

            root.AddToClassList(k_SliderRowClass);

            var slider = new Slider(min, max);

            slider.AddToClassList(k_SliderClass);
            slider.RegisterValueChangedCallback(callback);
            slider.SetValueWithoutNotify(value);

            if (label != null && !string.IsNullOrEmpty(label.text))
            {
                slider.label   = label.text;
                slider.tooltip = label.tooltip;
            }

            var field = new FloatField();

            field.AddToClassList(k_SliderFloatFieldClass);
            field.RegisterValueChangedCallback(callback);
            field.SetValueWithoutNotify(value);

            root.Add(slider);
            root.Add(field);

            return(root);
        }
Beispiel #8
0
        public void Bind(TransitionInfoCondition condition)
        {
            _condition = condition;

            if (_parameterFinder.Item != null)
            {
                _parameterFinder.Item.OnTypeChanged -= ParameterTypeChanged;
            }

            _parameterFinder.SelectItemWithoutNotify(_condition.Parameter, true);

            if (_parameterFinder.Item != null)
            {
                _parameterFinder.Item.OnTypeChanged += ParameterTypeChanged;
            }

            _stateFinder.SelectItemWithoutNotify(_condition.State, true);
            _stateValueProvider.SetValueWithoutNotify(_condition.StateValueProvider);

            SetProviderSourceType(_condition.ProviderSourceType);

            _boolComparisonValueField.SetValueWithoutNotify(_condition.BoolComparisonValue ? Bool.True : Bool.False);

            _intComparisonField.SetValueWithoutNotify(_condition.IntComparison);
            _intComparisonValueField.SetValueWithoutNotify(_condition.IntComparisonValue);

            _floatComparisonField.SetValueWithoutNotify(_condition.FloatComparison);
            _floatComparisonValueField.SetValueWithoutNotify(_condition.FloatComparisonValue);
        }
        public void LoadData(Parameter parameter)
        {
            Name = parameter.Name;

            ParameterTypeField.SetValueWithoutNotify(parameter.Type);
            ChangeParameterType(parameter.Type, default);

            switch (parameter.ValueProvider)
            {
            case BoolProvider boolProvider:
                BoolField.SetValueWithoutNotify(boolProvider.Value);
                break;

            case IntProvider intProvider:
                IntField.SetValueWithoutNotify(intProvider.Value);
                break;

            case FloatProvider floatProvider:
                FloatField.SetValueWithoutNotify(floatProvider.Value);
                break;

            default:
                break;
            }
        }
Beispiel #10
0
 void SetFPSLabelText()
 {
     if (TaggedClip != null && TaggedClip.Valid)
     {
         if (ActiveTick.style.display == DisplayStyle.Flex)
         {
             if (TimelineUnits == TimelineViewMode.frames)
             {
                 m_ActiveTimeField.SetValueWithoutNotify(ActiveTime * TaggedClip.SampleRate);
             }
             else
             {
                 m_ActiveTimeField.SetValueWithoutNotify(ActiveTime);
             }
         }
     }
 }
Beispiel #11
0
        public override void Update()
        {
            var value = TypeConversion.Convert <TValue, float>(Target);

            if (value != m_ValueField.value)
            {
                m_ValueField.SetValueWithoutNotify(TypeConversion.Convert <TValue, float>(Target));
            }
        }
        public static void RenderFloatProperty(VisualElement container, string name, object value,
                                               Action <object> setter)
        {
            var field = new FloatField(name);

            field.SetValueWithoutNotify((float)value);
            field.MarkDirtyRepaint();
            field.RegisterValueChangedCallback(evt => setter(evt.newValue));
            container.Add(field);
        }
Beispiel #13
0
        protected override void OnEnable()
        {
            base.OnEnable();

            rootVisualElement.styleSheets.Add((StyleSheet)EditorGUIUtility.Load("StyleSheets/SceneViewToolbarElements/SnapWindowsCommon.uss"));
            rootVisualElement.Add(new SnapSettingsHeader(L10n.Tr("Increment Snapping"), ResetValues));

            // Move
            m_MoveLinkedField = new LinkedVector3Field(L10n.Tr("Move"))
            {
                name = "Move"
            };
            m_MoveLinkedField.value  = EditorSnapSettings.move;
            m_MoveLinkedField.linked = Mathf.Approximately(m_MoveLinkedField.value.x, m_MoveLinkedField.value.y) &&
                                       Mathf.Approximately(m_MoveLinkedField.value.x, m_MoveLinkedField.value.z);
            rootVisualElement.Add(m_MoveLinkedField);

            EditorSnapSettings.moveChanged += (value) => m_MoveLinkedField.SetValueWithoutNotify(value);
            m_MoveLinkedField.RegisterValueChangedCallback(OnMoveValueChanged);

            // Rotate
            var rotate = new FloatField(L10n.Tr("Rotate"))
            {
                name = "Rotate"
            };

            rotate.value = EditorSnapSettings.rotate;
            rootVisualElement.Add(rotate);

            EditorSnapSettings.rotateChanged += (value) => rotate.SetValueWithoutNotify(value);
            rotate.RegisterValueChangedCallback(evt =>
            {
                EditorSnapSettings.rotate = evt.newValue;
                EditorSnapSettings.Save();
            });

            // Scale
            var scale = new FloatField(L10n.Tr("Scale"))
            {
                name = "Scale"
            };

            scale.value = EditorSnapSettings.scale;
            rootVisualElement.Add(scale);

            EditorSnapSettings.scaleChanged += (value) => scale.SetValueWithoutNotify(value);
            scale.RegisterValueChangedCallback(evt =>
            {
                EditorSnapSettings.scale = evt.newValue;
                EditorSnapSettings.Save();
            });
        }
 private void BindTransitionFields(TransitionInfo transition)
 {
     DurationTypeField.SetValueWithoutNotify(transition.DurationType);
     DurationField.SetValueWithoutNotify(transition.Duration);
     OffsetTypeField.SetValueWithoutNotify(transition.OffsetType);
     OffsetField.SetValueWithoutNotify(transition.Offset);
     InterruptionSourceField.SetValueWithoutNotify(transition.InterruptionSource);
     OrderedInterruptionToggle.SetValueWithoutNotify(transition.OrderedInterruption);
     InterruptableByAnyStateToggle.SetValueWithoutNotify(transition.InterruptableByAnyState);
     PlayAfterTransitionToggle.SetValueWithoutNotify(transition.PlayAfterTransition);
     _conditions.itemsSource   = transition.Conditions;
     _conditions.selectedIndex = -1;
     _conditions.Refresh();
 }
Beispiel #15
0
    public override void Update()
    {
        _isCreatedField.SetValueWithoutNotify(Target.Collider.IsCreated);

        unsafe
        {
            long address = (long)Target.Collider.GetUnsafePtr();
            _addressField.SetValueWithoutNotify(address);
        }

        if (Target.Collider.IsCreated)
        {
            _radiusField.SetValueWithoutNotify(Target.Collider.Value.Radius);
            _typeField.SetValueWithoutNotify(Target.Collider.Value.ColliderType);
        }
    }
Beispiel #16
0
    private void OnRadiusSliderChange(ChangeEvent <float> evt)
    {
        var value = Math.Pow(evt.newValue, 10) * 10000;

        if (value >= 10)
        {
            value = Math.Round(value, 0);
        }
        else
        {
            value = Math.Round(value, 4);
        }
        _radiusInput.SetValueWithoutNotify((float)value);
        _star.Radius = (float)value;
        EditorUtility.SetDirty(_star);
    }
Beispiel #17
0
        public void Bind(Environment environment)
        {
            this.environment = environment;
            if (environment == null || environment.Equals(null))
            {
                return;
            }

            if (latlong != null && !latlong.Equals(null))
            {
                latlong.image = GetLatLongThumbnailTexture();
            }
            skyCubemapField.SetValueWithoutNotify(environment.sky.cubemap);
            skyRotationOffset.SetValueWithoutNotify(environment.sky.rotation);
            skyExposureField.SetValueWithoutNotify(environment.sky.exposure);
            shadowCubemapField.SetValueWithoutNotify(environment.shadow.cubemap);
            sunPosition.SetValueWithoutNotify(new Vector2(environment.shadow.sunLongitude, environment.shadow.sunLatitude));
            shadowColor.SetValueWithoutNotify(environment.shadow.color);
            environmentName.SetValueWithoutNotify(environment.name);
        }
Beispiel #18
0
        void SetBakedExposure(ChangeEvent <float> evt)
        {
            var value = Mathf.Clamp(evt.newValue, -k_ExposureSliderAbsoluteMax, k_ExposureSliderAbsoluteMax);

            // This will allow the user to set a new max value for the current session
            if (Mathf.Abs(value) > m_ExposureMax)
            {
                m_ExposureMax              = Mathf.Min(k_ExposureSliderAbsoluteMax, Mathf.Abs(value));
                m_ExposureSlider.lowValue  = -m_ExposureMax;
                m_ExposureSlider.highValue = m_ExposureMax;
            }

            m_ExposureSlider.SetValueWithoutNotify(value);
            if (evt.target != m_ExposureField || evt.newValue != 0)
            {
                m_ExposureField.SetValueWithoutNotify(value);
            }

            SceneView.s_DrawModeExposure.value = value;
        }
Beispiel #19
0
        public void RefreshSettingsValues()
        {
            outputSizeMode?.SetValueWithoutNotify(settings.sizeMode);
            outputDimension?.SetValueWithoutNotify(settings.dimension);
            outputChannels?.SetValueWithoutNotify(settings.outputChannels);
            outputPrecision?.SetValueWithoutNotify(settings.outputPrecision);
            wrapMode?.SetValueWithoutNotify(settings.wrapMode);
            filterMode?.SetValueWithoutNotify(settings.filterMode);
            potSize?.SetValueWithoutNotify(settings.potSize);

            outputWidth?.SetValueWithoutNotify(settings.width);
            outputWidthScale?.SetValueWithoutNotify(SizeScaleToInt(settings.widthScale));
            outputHeight?.SetValueWithoutNotify(settings.height);
            outputHeightScale?.SetValueWithoutNotify(SizeScaleToInt(settings.heightScale));
            outputDepth?.SetValueWithoutNotify(settings.depth);
            outputDepthScale?.SetValueWithoutNotify(SizeScaleToInt(settings.depthScale));

            doubleBuffered?.SetValueWithoutNotify(settings.doubleBuffered);

            refreshMode?.SetValueWithoutNotify(settings.refreshMode);
            period?.SetValueWithoutNotify(settings.period);
        }
Beispiel #20
0
        public override VisualElement CreateInspectorGUI()
        {
            m_Root = new VisualElement();
            UIElementsUtils.ApplyStyleSheet(BuilderWindow.k_Stylesheet, m_Root);
            UIElementsUtils.CloneTemplateInto(k_TemplatePath, m_Root);
            m_Root.AddToClassList("mainContainer");

            m_Asset = target as Asset;
            m_Asset.BuildStarted += BuildStarted;
            m_Asset.BuildStopped += BuildStopped;

            m_AssetSettingsInput = m_Root.Q <VisualElement>("assetSettings");
            //set restrictions on asset settings
            var sampleRateInput = m_AssetSettingsInput.Q <FloatField>("sampleRate");

            sampleRateInput.isDelayed = true;
            var   sampleRateSlider = m_AssetSettingsInput.Q <Slider>("sampleRateSlider");
            float sampleRate       = Mathf.Clamp(m_Asset.SampleRate, 1f, m_Asset.SampleRate);

            sampleRateInput.value  = sampleRate;
            sampleRateSlider.value = sampleRate;
            sampleRateInput.RegisterValueChangedCallback(evt =>
            {
                float newSampleRate = Mathf.Clamp(evt.newValue, k_MinSampleRate, k_MaxSampleRate);
                m_Asset.SampleRate  = newSampleRate;
                sampleRateSlider.SetValueWithoutNotify(newSampleRate);
                ClampTimeHorizonInput(1f / newSampleRate);
            });
            sampleRateSlider.RegisterValueChangedCallback(evt =>
            {
                float newSampleRate = Mathf.Clamp(evt.newValue, k_MinSampleRate, k_MaxSampleRate);
                m_Asset.SampleRate  = newSampleRate;
                sampleRateInput.SetValueWithoutNotify(newSampleRate);
                ClampTimeHorizonInput(1f / newSampleRate);
            });
            sampleRateInput.SetFloatFieldRange(sampleRateSlider.lowValue, sampleRateSlider.highValue);

            m_TimeHorizonInput           = m_AssetSettingsInput.Q <FloatField>("timeHorizon");
            m_TimeHorizonInput.isDelayed = true;
            m_TimeHorizonSlider          = m_AssetSettingsInput.Q <Slider>("timeHorizonSlider");
            m_TimeHorizonSlider.value    = m_Asset.TimeHorizon;
            m_TimeHorizonInput.value     = m_Asset.TimeHorizon;
            m_TimeHorizonInput.RegisterValueChangedCallback(evt =>
            {
                float newTimeHorizon = Mathf.Clamp(evt.newValue, k_MinTimeHorizon, k_MaxTimeHorizon);
                m_Asset.TimeHorizon  = newTimeHorizon;
                m_TimeHorizonSlider.SetValueWithoutNotify(newTimeHorizon);
            });
            m_TimeHorizonSlider.RegisterValueChangedCallback(evt =>
            {
                float newTimeHorizon = Mathf.Clamp(evt.newValue, k_MinTimeHorizon, k_MaxTimeHorizon);
                m_Asset.TimeHorizon  = newTimeHorizon;
                m_TimeHorizonInput.SetValueWithoutNotify(newTimeHorizon);
            });

            m_TimeHorizonSlider.lowValue = 1f / sampleRateSlider.lowValue;
            m_TimeHorizonInput.SetFloatFieldRange(m_TimeHorizonSlider.lowValue, m_TimeHorizonSlider.highValue);

            var avatarSelector = m_Root.Q <ObjectField>("destinationAvatar");

            avatarSelector.objectType = typeof(Avatar);

            avatarSelector.value = m_Asset.DestinationAvatar;
            avatarSelector.RegisterValueChangedCallback(OnAvatarSelectionChanged);

            UIElementsUtils.ApplyStyleSheet(k_Stylesheet, m_Root);

            m_MetricsEditor = new MetricsEditor(m_Asset);
            m_Root.Q <VisualElement>("metrics").Add(m_MetricsEditor);

            var buildButton = m_Root.Q <Button>("buildButton");

            buildButton.clickable.clicked += BuildButtonClicked;

            if (EditorApplication.isPlaying || m_Asset.BuildInProgress)
            {
                SetInputEnabled(false);
            }

            EditorApplication.playModeStateChanged += OnPlayModeStateChanged;

            return(m_Root);
        }
        public void RefreshPropertyValue(object val, int specificity)
        {
            if (val is StyleFloat)
            {
                var        style = (StyleFloat)val;
                FloatField field = GetOrCreateField <FloatField, float>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(style.value);
                }
            }
            else if (val is StyleInt)
            {
                var          style = (StyleInt)val;
                IntegerField field = GetOrCreateField <IntegerField, int>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(style.value);
                }
            }
            else if (val is StyleLength)
            {
                var style = (StyleLength)val;
                StyleLengthField field = GetOrCreateField <StyleLengthField, StyleLength>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(style);
                }
            }
            else if (val is StyleColor)
            {
                var        style = (StyleColor)val;
                ColorField field = GetOrCreateField <ColorField, Color>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(style.value);
                }
            }
            else if (val is StyleFont)
            {
                var         style = (StyleFont)val;
                ObjectField field = GetOrCreateObjectField <Font>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(style.value);
                }
            }
            else if (val is StyleBackground)
            {
                var         background = ((StyleBackground)val).value;
                ObjectField field;
                if (background.vectorImage != null)
                {
                    field = GetOrCreateObjectField <VectorImage>();
                }
                else
                {
                    field = GetOrCreateObjectField <Texture2D>();
                }
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(background.vectorImage != null ? (UnityEngine.Object)background.vectorImage : (UnityEngine.Object)background.texture);
                }
            }
            else if (val is StyleCursor)
            {
                // Recreate the cursor fields every time since StyleCursor
                // can be made of different fields (based on the value)
                Clear();

                StyleCursor style = (StyleCursor)val;
                if (style.value.texture != null)
                {
                    var uiTextureField = new ObjectField(m_PropertyName)
                    {
                        value = style.value.texture
                    };
                    uiTextureField.RegisterValueChangedCallback(e =>
                    {
                        StyleCursor styleCursor = (StyleCursor)StyleDebug.GetComputedStyleValue(m_SelectedElement.computedStyle, m_PropertyInfo.id);
                        var currentCursor       = styleCursor.value;
                        currentCursor.texture   = e.newValue as Texture2D;
                        SetPropertyValue(new StyleCursor(currentCursor));
                    });
                    Add(uiTextureField);

                    var uiHotspotField = new Vector2Field("hotspot")
                    {
                        value = style.value.hotspot
                    };
                    uiHotspotField.RegisterValueChangedCallback(e =>
                    {
                        StyleCursor styleCursor = (StyleCursor)StyleDebug.GetComputedStyleValue(m_SelectedElement.computedStyle, m_PropertyInfo.id);
                        var currentCursor       = styleCursor.value;
                        currentCursor.hotspot   = e.newValue;
                        SetPropertyValue(new StyleCursor(currentCursor));
                    });
                    Add(uiHotspotField);
                }
                else
                {
                    int mouseId = style.value.defaultCursorId;
                    var uiField = new EnumField(m_PropertyName, (MouseCursor)mouseId);
                    uiField.RegisterValueChangedCallback(e =>
                    {
                        int cursorId = Convert.ToInt32(e.newValue);
                        var cursor   = new Cursor()
                        {
                            defaultCursorId = cursorId
                        };
                        SetPropertyValue(new StyleCursor(cursor));
                    });
                    Add(uiField);
                }
                Add(m_SpecificityLabel);
                SetSpecificity(specificity);
            }
            else
            {
                // StyleEnum<T>
                var       type      = val.GetType();
                var       propInfo  = type.GetProperty("value");
                Enum      enumValue = propInfo.GetValue(val, null) as Enum;
                EnumField field     = GetOrCreateEnumField(enumValue);
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(enumValue);
                }
            }

            SetSpecificity(specificity);
        }
Beispiel #22
0
 public override void SetValueWithoutNotify(float newValue)
 {
     base.SetValueWithoutNotify(newValue);
     m_Slider.SetValueWithoutNotify(newValue);
     m_FloatField.SetValueWithoutNotify(newValue);
 }
Beispiel #23
0
 void OnCostChanged(float _newCost)
 {
     costField.SetValueWithoutNotify(_newCost);
 }
Beispiel #24
0
    void SetArtistTool()
    {
        VisualElement root = rootVisualElement;

        root.Clear();
        VisualTreeAsset ArtistToolVisualTree = Resources.Load <VisualTreeAsset>("ArtistTool");

        ArtistToolVisualTree.CloneTree(root);
        root.styleSheets.Add(Resources.Load <StyleSheet>("ArtistTool"));

        SerializedObject Tso        = new SerializedObject(TimeController);
        Slider           timeSlider = root.Q <Slider>(name: "Time");

        timeSlider.Bind(Tso);


        #region SkyColor
        VisualElement gradientVisualElement = root.Q <VisualElement>(name: "SkyGradient");

        if (gradientVisualElement != null)
        {
            GradientField gradientField = gradientVisualElement.Q <GradientField>();

            if (gradientField != null)
            {
                skyColorSetter = GameObject.Find("Light - Sky").GetComponent <MaterialColorSetter>();
                SerializedObject serialized_MaterialSetter = new SerializedObject(skyColorSetter);
                gradientField.bindingPath = "gradient";
                gradientField.Bind(serialized_MaterialSetter);
                gradientVisualElement.Q <Label>().text = "Sky Gradient";
            }
        }

        #endregion

        #region Ruins
        GradientEditorSetter("RuinsGradient", "Ruins Gradient", RuinsColorSetter);
        #endregion

        #region Trees
        GradientEditorSetter("TreesGradient", "Trees Gradient", TreesColorSetter);
        #endregion

        #region Rim
        GradientEditorSetter("RimColor", "Rim Gradient", RimColorSetter);
        #endregion



        #region Lights

        #region SunLights
        SerializedObject serialized_SunSpot = new SerializedObject(SunSpot_Group);

        VisualElement sunLightVisualElement = root.Q <VisualElement>(name: "Sunlight");
        if (sunLightVisualElement.Q <VisualElement>(name: "LightGradient") != null)
        {
            GradientField sunLightGradient  = sunLightVisualElement.Q <VisualElement>(name: "LightGradient").Q <GradientField>();
            FloatField    sunLightIntensity = root.Q <FloatField>(name: "Intensity");
            if (sunLightGradient != null)
            {
                sunLightGradient.bindingPath = "gradient";
                sunLightGradient.Bind(serialized_SunSpot);
                sunLightGradient.label = "Gradient";
            }

            sunLightIntensity.value = GetSpotLightIntensity();
            sunLightIntensity.RegisterCallback <ChangeEvent <float> >(ChangeIntensitySpotLightsEvent);
        }

        #endregion

        #region GrassLight
        SerializedObject serialized_GrassLight_Group = new SerializedObject(GrassLight_Group);

        VisualElement grassLightVisualElement = root.Q <VisualElement>(name: "GrassLight");
        if (grassLightVisualElement.Q <VisualElement>(name: "LightGradient") != null)
        {
            GradientField grassLightGradient  = grassLightVisualElement.Q <VisualElement>(name: "LightGradient").Q <GradientField>();
            FloatField    grassLightIntensity = grassLightVisualElement.Q <FloatField>(name: "Intensity");

            if (grassLightGradient != null)
            {
                grassLightGradient.bindingPath = "gradient";
                grassLightGradient.Bind(serialized_GrassLight_Group);
                grassLightGradient.label = "Gradient";
            }

            grassLightIntensity.value = GrassLight.intensity;

            SerializedObject serialized_GrassLight = new SerializedObject(GrassLight);
            grassLightIntensity.Bind(serialized_GrassLight);
        }
        #endregion

        #region cave Light
        SerializedObject serialized_CaveHoleLight = new SerializedObject(CaveHoleLight);

        VisualElement caveLightVisualElement = root.Q <VisualElement>(name: "CaveHoleLight");
        caveLightVisualElement.Q <FloatField>(name: "Falloff").Bind(serialized_CaveHoleLight);

        Slider     fallOffSlider = caveLightVisualElement.Q <Slider>(name: "FalloffIntencity");
        FloatField fallOffField  = fallOffSlider.Q <FloatField>(name: "CurrentValue");
        fallOffSlider.Bind(serialized_CaveHoleLight);

        fallOffField.SetValueWithoutNotify(CaveHoleLight.falloffIntensity);

        fallOffField.RegisterCallback <ChangeEvent <float> >((evt) => fallOffSlider.value = evt.newValue);

        fallOffSlider.RegisterCallback <ChangeEvent <float> >((evt) => fallOffField.SetValueWithoutNotify(evt.newValue));

        #endregion

        #region Visualisers
        var AllGradientElements = root.Query <GradientField>();
        AllGradientElements.ForEach((element) =>
        {
            //registerCallback for Gradient to apply changes on scene
            element.RegisterCallback <ChangeEvent <Gradient> >(ChangeGradientEvent);

            VisualElement visualiser = element.Q <VisualElement>(name: "VisualisationColor");

            //Init color of visualisation cube
            float currentTime = TimeController.timeValue;
            visualiser.style.backgroundColor = element.value.Evaluate(currentTime);

            //register Callback for each visualisation cube when gradient Changes
            element.RegisterCallback <ChangeEvent <Gradient> >((evt) =>
            {
                float timeOfChange = TimeController.timeValue;
                visualiser.style.backgroundColor = evt.newValue.Evaluate(currentTime);
            });

            //register Callback for each visualisation cube when Time Changes
            timeSlider.RegisterCallback <ChangeEvent <float> >((evt) =>
            {
                visualiser.style.backgroundColor = element.value.Evaluate(evt.newValue);
            });
        });
        #endregion

        #endregion

        #region Wind Shader
        // Set Initial Values
        VisualElement windComponent = root.Q <VisualElement>(name: "Wind");
        if (windComponent != null)
        {
            Vector4Field windDirectionQuaternion = windComponent.Q <Vector4Field>(name: "WindDirection");
            windDirectionQuaternion.value = GetWindDirection();

            FloatField windScaleFloat = windComponent.Q <FloatField>(name: "WindScale");
            windScaleFloat.value = GetWindScale();

            MinMaxValue minMaxStrength = GetWindStrength();

            VisualElement windStrengthHolder = windComponent.Q <VisualElement>(name: "WinStrengthHolder");

            MinMaxSlider windStrengthSlider = windStrengthHolder.Q <MinMaxSlider>(name: "WindStrength");
            windStrengthSlider.highLimit = minMaxStrength.HighLimit;
            windStrengthSlider.lowLimit  = minMaxStrength.LowLimit;
            windStrengthSlider.value     = new Vector2(minMaxStrength.minValue, minMaxStrength.maxValue);

            windStrengthHolder.Q <Label>(name: "MinValue").text = "Min Value :" + minMaxStrength.minValue;
            windStrengthHolder.Q <Label>(name: "MaxValue").text = "Max Value :" + minMaxStrength.maxValue;

            FloatField windSpeedFloat = windComponent.Q <FloatField>(name: "WindSpeed");
            windSpeedFloat.value = GetWindSpeed();

            //Set Callbacks values
            windDirectionQuaternion.RegisterCallback <ChangeEvent <Vector4> >(ChangeWindDirection);
            windScaleFloat.RegisterCallback <ChangeEvent <float> >(ChangeWindScale);
            windStrengthSlider.RegisterCallback <ChangeEvent <Vector2> >(ChangeWindStrength);
            windSpeedFloat.RegisterCallback <ChangeEvent <float> >(ChangeWindSpeed);
        }

        #endregion

        #region Postprocessing
        #region WhiteBalance
        //serialize White balance property
        SerializedObject serialized_whiteBalanceProperty = new SerializedObject(whiteBalanceProperty);
        //Get White balance Visual Element
        VisualElement whiteBalanceVisualElement = root.Q <VisualElement>(name: "WhiteBalance");

        #region Temperature
        //Get White Balance temperature Visual Element
        VisualElement whiteBalanceTemperatureVE = whiteBalanceVisualElement.Q <VisualElement>(name: "Temperature");

        //Get White Balance temperature Slider
        Slider whiteBalanceTemperatureSlider = whiteBalanceTemperatureVE.Q <Slider>(name: "SliderValue");

        //Bind Slider to value
        whiteBalanceTemperatureSlider.bindingPath = "temperature.m_Value";
        whiteBalanceTemperatureSlider.Bind(serialized_whiteBalanceProperty);

        //Get White Balance temperature Float Field
        FloatField whiteBalanceTemperatureFloat = whiteBalanceTemperatureVE.Q <FloatField>(name: "CurrentValue");
        //Set default Temperature
        whiteBalanceTemperatureFloat.SetValueWithoutNotify(whiteBalanceProperty.temperature.value);

        //Register change callback for the float field to change the slider value. Changing slider value will change the values bound with it.
        whiteBalanceTemperatureFloat.RegisterCallback <ChangeEvent <float> >((evt) => whiteBalanceTemperatureSlider.value = evt.newValue);

        //Register change Callback for the slider, to change the float fiel Without notification (to avoid triggering Float field callback)
        whiteBalanceTemperatureSlider.RegisterCallback <ChangeEvent <float> >((evt) => whiteBalanceTemperatureFloat.SetValueWithoutNotify(evt.newValue));
        #endregion

        #region Tint

        //Get White Balance Tint Visual Element
        VisualElement whiteBalanceTintVE = whiteBalanceVisualElement.Q <VisualElement>(name: "Tint");

        //Get White Balance Tint Slider
        Slider whiteBalanceTintSlider = whiteBalanceTintVE.Q <Slider>(name: "SliderValue");

        //Bind Slider to value
        whiteBalanceTintSlider.bindingPath = "tint.m_Value";
        whiteBalanceTintSlider.Bind(serialized_whiteBalanceProperty);

        //Get White Balance Tint Float Field
        FloatField whiteBalanceTintFloat = whiteBalanceTintVE.Q <FloatField>(name: "CurrentValue");
        //Set default Tint
        whiteBalanceTintFloat.SetValueWithoutNotify(whiteBalanceProperty.tint.value);

        //Register change callback for the float field to change the slider value. Changing slider value will change the values bound with it.
        whiteBalanceTintFloat.RegisterCallback <ChangeEvent <float> >((evt) => whiteBalanceTintSlider.value = evt.newValue);

        //Register change Callback for the slider, to change the float fiel Without notification (to avoid triggering Float field callback)
        whiteBalanceTintSlider.RegisterCallback <ChangeEvent <float> >((evt) => whiteBalanceTintFloat.SetValueWithoutNotify(evt.newValue));
        #endregion

        #endregion

        #region Bloom

        //serialize bloom property
        SerializedObject serialized_BloomProperty = new SerializedObject(BloomProperty);
        //Get Bloom Visual Element
        VisualElement bloomVisualElement = root.Q <VisualElement>(name: "Bloom");

        //Get Bloom Tint Color
        ColorField bloomTint = bloomVisualElement.Q <ColorField>(name: "Tint");

        //Bind color to value
        bloomTint.bindingPath = "tint.m_Value";
        bloomTint.Bind(serialized_BloomProperty);

        //Get Bloom Intensity
        FloatField bloomIntensity = bloomVisualElement.Q <FloatField>(name: "Intensity");

        //Bind Intensity to value
        bloomIntensity.Bind(serialized_BloomProperty);

        #endregion
        #endregion


        #region VFX

        SerializedObject serialized_GlowParticleSystem = new SerializedObject(GlowParticleSystem);

        VisualElement VFXVisualElement = root.Q <VisualElement>(name: "VFX");


        VFXVisualElement.Q <FloatField>(name: "Emission").bindingPath = "EmissionModule.rateOverTime.scalar";
        VFXVisualElement.Q <FloatField>(name: "Emission").Bind(serialized_GlowParticleSystem);

        VFXVisualElement.Q <EnumField>(name: "RenderMode").Init(GlowParticleSystem.GetComponent <ParticleSystemRenderer>().renderMode);
        VFXVisualElement.Q <EnumField>(name: "RenderMode").RegisterCallback <ChangeEvent <string> >(ChangeRenderMode);

        VFXVisualElement.Q <ObjectField>(name: "Material").objectType = typeof(Material);
        VFXVisualElement.Q <ObjectField>(name: "Material").RegisterCallback <ChangeEvent <string> >(ChangeRenderMaterial);
        #endregion

        root.Q <Button>(name: "SaveButton").clicked  += SaveButton;
        root.Q <Button>(name: "ResetButton").clicked += ResetToInitialSceneValues;
    }
Beispiel #25
0
 protected override void Refresh()
 {
     _slider.SetValueWithoutNotify(Value);
     _minText.SetValueWithoutNotify(Value.x);
     _maxText.SetValueWithoutNotify(Value.y);
 }
        public void RefreshPropertyValue(object val, int specificity)
        {
            if (val is float floatValue)
            {
                FloatField field = GetOrCreateField <FloatField, float>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(floatValue);
                }
            }
            else if (val is int intValue)
            {
                IntegerField field = GetOrCreateField <IntegerField, int>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(intValue);
                }
            }
            else if (val is Length lengthValue)
            {
                StyleLengthField field = GetOrCreateField <StyleLengthField, StyleLength>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(new StyleLength(lengthValue));
                }
            }
            else if (val is Color colorValue)
            {
                ColorField field = GetOrCreateField <ColorField, Color>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(colorValue);
                }
            }
            // Note: val may be null in case of reference type like "Font"
            else if (m_PropertyInfo.type == typeof(StyleFont))
            {
                ObjectField field;
                field = GetOrCreateObjectField <Font>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(val as Font);
                }
            }
            else if (val is FontDefinition fontDefinition)
            {
                ObjectField field;
                if (fontDefinition.fontAsset != null)
                {
                    if (childCount == 0)
                    {
                        field = GetObjectFieldOfTypeFontAsset();
                        SetField(field);
                    }
                    else
                    {
                        field = (ObjectField)ElementAt(0);
                    }
                }
                else
                {
                    field = GetOrCreateObjectField <Font>();
                }

                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(fontDefinition.fontAsset != null ? fontDefinition.fontAsset : fontDefinition.font);
                }
            }
            else if (val is Background bgValue)
            {
                ObjectField field;
                if (bgValue.vectorImage != null)
                {
                    field = GetOrCreateObjectField <VectorImage>();
                }
                else if (bgValue.sprite != null)
                {
                    field = GetOrCreateObjectField <Sprite>();
                }
                else if (bgValue.renderTexture != null)
                {
                    field = GetOrCreateObjectField <RenderTexture>();
                }
                else
                {
                    field = GetOrCreateObjectField <Texture2D>();
                }
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(
                        bgValue.vectorImage != null ? (UnityEngine.Object)bgValue.vectorImage :
                        (bgValue.sprite != null ? (UnityEngine.Object)bgValue.sprite :
                         (bgValue.renderTexture != null ? (UnityEngine.Object)bgValue.renderTexture :
                          (UnityEngine.Object)bgValue.texture)));
                }
            }
            else if (val is Cursor cursorValue)
            {
                // Recreate the cursor fields every time since StyleCursor
                // can be made of different fields (based on the value)
                Clear();

                if (cursorValue.texture != null)
                {
                    var uiTextureField = new ObjectField(m_PropertyName)
                    {
                        value = cursorValue.texture
                    };
                    uiTextureField.RegisterValueChangedCallback(e =>
                    {
                        var currentCursor     = (Cursor)StyleDebug.GetComputedStyleActualValue(m_SelectedElement.computedStyle, m_PropertyInfo.id);
                        currentCursor.texture = e.newValue as Texture2D;
                        SetPropertyValue(new StyleCursor(currentCursor));
                    });
                    Add(uiTextureField);

                    var uiHotspotField = new Vector2Field("hotspot")
                    {
                        value = cursorValue.hotspot
                    };
                    uiHotspotField.RegisterValueChangedCallback(e =>
                    {
                        var currentCursor     = (Cursor)StyleDebug.GetComputedStyleActualValue(m_SelectedElement.computedStyle, m_PropertyInfo.id);
                        currentCursor.hotspot = e.newValue;
                        SetPropertyValue(new StyleCursor(currentCursor));
                    });
                    Add(uiHotspotField);
                }
                else
                {
                    int mouseId = cursorValue.defaultCursorId;
                    var uiField = new EnumField(m_PropertyName, (MouseCursor)mouseId);
                    uiField.RegisterValueChangedCallback(e =>
                    {
                        int cursorId = Convert.ToInt32(e.newValue);
                        var cursor   = new Cursor()
                        {
                            defaultCursorId = cursorId
                        };
                        SetPropertyValue(new StyleCursor(cursor));
                    });
                    Add(uiField);
                }
                Add(m_SpecificityLabel);
                SetSpecificity(specificity);
            }
            else if (val is TextShadow textShadow)
            {
                ColorField colorFieldfield = GetOrCreateFields <ColorField, Color>(m_PropertyName, 0);
                if (!IsFocused(colorFieldfield))
                {
                    colorFieldfield.SetValueWithoutNotify(textShadow.color);
                }

                Vector2Field vector2Field = GetOrCreateFields <Vector2Field, Vector2>("offset", 1);
                if (!IsFocused(vector2Field))
                {
                    vector2Field.SetValueWithoutNotify(textShadow.offset);
                }

                FloatField floatField = GetOrCreateFields <FloatField, float>("blur", 2);
                if (!IsFocused(floatField))
                {
                    floatField.SetValueWithoutNotify(textShadow.blurRadius);
                }

                if (childCount == 3)
                {
                    Add(m_SpecificityLabel);
                }
            }
            else
            {
                // Enum
                Debug.Assert(val is Enum, "Expected Enum value");
                Enum      enumValue = (Enum)val;
                EnumField field     = GetOrCreateEnumField(enumValue);
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(enumValue);
                }
            }

            SetSpecificity(specificity);
        }
 public void SetValueWithoutNotify(float value)
 {
     m_SecondsField.SetValueWithoutNotify(value);
     m_FrameField.SetValueWithoutNotify(Mathematics.Missing.roundToInt(value * m_Clip.SampleRate));
 }
Beispiel #28
0
        protected VisualElement CreateParameterControl(SingularSerializableParameter parameter, string controlName, Action <SingularSerializableParameter> clampAction = null)
        {
            VisualElement control;

            switch (parameter.Type)
            {
            case ParameterType.behaviorAction:

                control = new VisualElement();

                var buttons = new VisualElement {
                    style = { flexDirection = FlexDirection.Row, paddingRight = 2f, paddingLeft = 2f }
                };
                var actionLabel = new Label {
                    style = { paddingLeft = 8f, paddingRight = 8f }
                };

                var configureButton = new Button {
                    text = "Configure"
                };
                configureButton.clickable.clickedWithEventInfo +=
                    clickEvent =>
                {
                    var worldPosition = clickEvent.originalMousePosition + GraphView.editorWindow.position.position;

                    GraphView.actionSearcher.TargetParameter = parameter;
                    SearchWindow.Open(new SearchWindowContext(worldPosition), GraphView.actionSearcher);
                };

                var removeButton = new Button(() => parameter.BehaviorActionValue = null)
                {
                    text = "Remove"
                };

                buttons.Add(configureButton);
                buttons.Add(removeButton);

                control.Add(actionLabel);
                control.Add(buttons);

                parameter.OnValueChangedMethods += OnBehaviorActionChanged;
                OnBehaviorActionChanged();                         //Trigger a refresh

                void OnBehaviorActionChanged()
                {
                    parameter.LoadBehaviorAction(GraphView.editorWindow.ImportData);                             //Refresh action name
                    actionLabel.text = parameter.BehaviorActionValue == null ? "Missing Action" : parameter.BehaviorActionValue.ToString();

                    //Behavior action parameter controls
                    const string  ParameterGroupName = "Behavior Action Parameters Group";
                    VisualElement group = control.Q <VisualElement>(ParameterGroupName);

                    if (group != null)
                    {
                        control.Remove(group);                                            //If had old group remove/destroy it
                    }
                    var parameters = parameter.BehaviorActionValue?.method.Parameters;

                    if (parameters == null || parameters.Count == 0)
                    {
                        return;                                                                          //If no parameter for this action
                    }
                    group = new VisualElement {
                        name = ParameterGroupName
                    };                                                                                 //Create group
                    var accessor = ((SerializableParameter)parameter).BehaviorActionParameters;

                    for (int i = 0; i < parameters.Count; i++)
                    {
                        BehaviorActionParameterInfo parameterInfo = parameters[i];
                        group.Add(CreateParameterControl(accessor[i], parameterInfo.name));
                    }

                    control.Add(group);
                }

                break;

            case ParameterType.boolean:

                var toggle = new Toggle(controlName)
                {
                    value = parameter.BooleanValue
                };
                toggle.RegisterValueChangedCallback(
                    changeEvent =>
                {
                    parameter.BooleanValue = changeEvent.newValue;
                    clampAction?.Invoke(parameter);
                    toggle.SetValueWithoutNotify(parameter.BooleanValue);
                }
                    );

                control = toggle;
                break;

            case ParameterType.enumeration:

                control = new EnumField();
                //TODO

                break;

            case ParameterType.integer1:

                var integerField = new IntegerField(controlName)
                {
                    value = parameter.Integer1Value
                };
                integerField.RegisterValueChangedCallback(
                    changeEvent =>
                {
                    parameter.Integer1Value = changeEvent.newValue;
                    clampAction?.Invoke(parameter);
                    integerField.SetValueWithoutNotify(parameter.Integer1Value);
                }
                    );

                control = integerField;
                break;

            case ParameterType.integer2:

                var vector2IntField = new Vector2IntField(controlName)
                {
                    value = parameter.Integer2Value
                };
                vector2IntField.RegisterValueChangedCallback(
                    changeEvent =>
                {
                    parameter.Integer2Value = changeEvent.newValue;
                    clampAction?.Invoke(parameter);
                    vector2IntField.SetValueWithoutNotify(parameter.Integer2Value);
                }
                    );

                control = vector2IntField;
                break;

            case ParameterType.integer3:

                var vector3IntField = new Vector3IntField(controlName)
                {
                    value = parameter.Integer3Value
                };
                vector3IntField.RegisterValueChangedCallback(
                    changeEvent =>
                {
                    parameter.Integer3Value = changeEvent.newValue;
                    clampAction?.Invoke(parameter);
                    vector3IntField.SetValueWithoutNotify(parameter.Integer3Value);
                }
                    );

                control = vector3IntField;
                break;

            case ParameterType.float1:

                var floatField = new FloatField(controlName)
                {
                    value = parameter.Float1Value
                };
                floatField.RegisterValueChangedCallback(
                    changeEvent =>
                {
                    parameter.Float1Value = changeEvent.newValue;
                    clampAction?.Invoke(parameter);
                    floatField.SetValueWithoutNotify(parameter.Float1Value);
                }
                    );

                control = floatField;
                break;

            case ParameterType.float2:

                var vector2Field = new Vector2Field(controlName)
                {
                    value = parameter.Float2Value
                };
                vector2Field.RegisterValueChangedCallback(
                    changeEvent =>
                {
                    parameter.Float2Value = changeEvent.newValue;
                    clampAction?.Invoke(parameter);
                    vector2Field.SetValueWithoutNotify(parameter.Float2Value);
                }
                    );

                control = vector2Field;
                break;

            case ParameterType.float3:

                var vector3Field = new Vector3Field(controlName)
                {
                    value = parameter.Float3Value
                };
                vector3Field.RegisterValueChangedCallback(
                    changeEvent =>
                {
                    parameter.Float3Value = changeEvent.newValue;
                    clampAction?.Invoke(parameter);
                    vector3Field.SetValueWithoutNotify(parameter.Float3Value);
                }
                    );

                control = vector3Field;
                break;

            default: throw ExceptionHelper.Invalid(nameof(parameter.Type), parameter.Type, InvalidType.unexpected);
            }

            control.Query <FloatField>().ForEach(field => field.style.minWidth = 60f);
            Label label = control.Q <Label>();

            if (label != null)
            {
                label.style.minWidth     = 0f;
                label.style.paddingRight = 20f;
            }

            return(control);
        }
Beispiel #29
0
        public void RefreshPropertyValue(object val, int specificity)
        {
            if (val is float floatValue)
            {
                FloatField field = GetOrCreateField <FloatField, float>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(floatValue);
                }
            }
            else if (val is int intValue)
            {
                IntegerField field = GetOrCreateField <IntegerField, int>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(intValue);
                }
            }
            else if (val is Length lengthValue)
            {
                StyleLengthField field = GetOrCreateField <StyleLengthField, StyleLength>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(new StyleLength(lengthValue));
                }
            }
            else if (val is Color colorValue)
            {
                ColorField field = GetOrCreateField <ColorField, Color>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(colorValue);
                }
            }
            // Note: val may be null in case of reference type like "Font"
            else if (m_PropertyInfo.type == typeof(StyleFont))
            {
                ObjectField field;
                field = GetOrCreateObjectField <Font>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(val as Font);
                }
            }
            else if (val is FontDefinition fontDefinition)
            {
                ObjectField field;
                if (fontDefinition.fontAsset != null)
                {
                    if (childCount == 0)
                    {
                        var o = new ObjectField();
                        o.objectType = typeof(FontAsset);
                        field        = o;

                        SetField(field);
                    }
                    else
                    {
                        field = (ObjectField)ElementAt(0);
                    }
                }
                else
                {
                    field = GetOrCreateObjectField <Font>();
                }

                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(fontDefinition.fontAsset != null ? (UnityEngine.Object)fontDefinition.fontAsset : (UnityEngine.Object)fontDefinition.font);
                }
            }
            else if (val is Background bgValue)
            {
                ObjectField field;
                if (bgValue.vectorImage != null)
                {
                    field = GetOrCreateObjectField <VectorImage>();
                }
                else if (bgValue.sprite != null)
                {
                    field = GetOrCreateObjectField <Sprite>();
                }
                else if (bgValue.renderTexture != null)
                {
                    field = GetOrCreateObjectField <RenderTexture>();
                }
                else
                {
                    field = GetOrCreateObjectField <Texture2D>();
                }
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(
                        bgValue.vectorImage != null ? (UnityEngine.Object)bgValue.vectorImage :
                        (bgValue.sprite != null ? (UnityEngine.Object)bgValue.sprite :
                         (bgValue.renderTexture != null ? (UnityEngine.Object)bgValue.renderTexture :
                          (UnityEngine.Object)bgValue.texture)));
                }
            }
            else if (val is Cursor cursorValue)
            {
                // Recreate the cursor fields every time since StyleCursor
                // can be made of different fields (based on the value)
                Clear();

                if (cursorValue.texture != null)
                {
                    var uiTextureField = new ObjectField(m_PropertyName)
                    {
                        value = cursorValue.texture
                    };
                    uiTextureField.RegisterValueChangedCallback(e =>
                    {
                        var currentCursor     = (Cursor)StyleDebug.GetComputedStyleValue(m_SelectedElement.computedStyle, m_PropertyInfo.id);
                        currentCursor.texture = e.newValue as Texture2D;
                        SetPropertyValue(new StyleCursor(currentCursor));
                    });
                    Add(uiTextureField);

                    var uiHotspotField = new Vector2Field("hotspot")
                    {
                        value = cursorValue.hotspot
                    };
                    uiHotspotField.RegisterValueChangedCallback(e =>
                    {
                        var currentCursor     = (Cursor)StyleDebug.GetComputedStyleValue(m_SelectedElement.computedStyle, m_PropertyInfo.id);
                        currentCursor.hotspot = e.newValue;
                        SetPropertyValue(new StyleCursor(currentCursor));
                    });
                    Add(uiHotspotField);
                }
                else
                {
                    int mouseId = cursorValue.defaultCursorId;
                    var uiField = new EnumField(m_PropertyName, (MouseCursor)mouseId);
                    uiField.RegisterValueChangedCallback(e =>
                    {
                        int cursorId = Convert.ToInt32(e.newValue);
                        var cursor   = new Cursor()
                        {
                            defaultCursorId = cursorId
                        };
                        SetPropertyValue(new StyleCursor(cursor));
                    });
                    Add(uiField);
                }
                Add(m_SpecificityLabel);
                SetSpecificity(specificity);
            }
            else if (val is TextShadow textShadow)
            {
                ColorField colorFieldfield = GetOrCreateFields <ColorField, Color>(m_PropertyName, 0);
                if (!IsFocused(colorFieldfield))
                {
                    colorFieldfield.SetValueWithoutNotify(textShadow.color);
                }

                Vector2Field vector2Field = GetOrCreateFields <Vector2Field, Vector2>("offset", 1);
                if (!IsFocused(vector2Field))
                {
                    vector2Field.SetValueWithoutNotify(textShadow.offset);
                }

                FloatField floatField = GetOrCreateFields <FloatField, float>("blur", 2);
                if (!IsFocused(floatField))
                {
                    floatField.SetValueWithoutNotify(textShadow.blurRadius);
                }

                if (childCount == 3)
                {
                    Add(m_SpecificityLabel);
                }
            }
            else if (val is Rotate rotate)
            {
                FloatField floatField = GetOrCreateFields <FloatField, float>(m_PropertyName, 0);
                if (!IsFocused(floatField))
                {
                    floatField.SetValueWithoutNotify(rotate.angle.value);
                }
                Add(m_SpecificityLabel);
                SetSpecificity(specificity);
            }
            else if (val is Scale scale)
            {
                Vector3Field vector3Field = GetOrCreateFields <Vector3Field, Vector3>(m_PropertyName, 0);
                if (!IsFocused(vector3Field))
                {
                    vector3Field.SetValueWithoutNotify(scale.value);
                }
                Add(m_SpecificityLabel);
                SetSpecificity(specificity);
            }
            else if (val is Translate translate)
            {
                StyleLengthField fieldx = GetOrCreateFields <StyleLengthField, StyleLength>(m_PropertyName, 0);
                if (!IsFocused(fieldx))
                {
                    fieldx.SetValueWithoutNotify(translate.x);
                }
                StyleLengthField fieldy = GetOrCreateFields <StyleLengthField, StyleLength>("y", 1);
                if (!IsFocused(fieldy))
                {
                    fieldy.SetValueWithoutNotify(translate.x);
                }
                FloatField floatField = GetOrCreateFields <FloatField, float>("z", 2);
                if (!IsFocused(floatField))
                {
                    floatField.SetValueWithoutNotify(translate.z);
                }
                Add(m_SpecificityLabel);
                SetSpecificity(specificity);
                SetEnabled(false);
            }
            else if (val is TransformOrigin transformOrigin)
            {
                StyleLengthField fieldx = GetOrCreateFields <StyleLengthField, StyleLength>(m_PropertyName, 0);
                if (!IsFocused(fieldx))
                {
                    fieldx.SetValueWithoutNotify(transformOrigin.x);
                }
                StyleLengthField fieldy = GetOrCreateFields <StyleLengthField, StyleLength>("y", 1);
                if (!IsFocused(fieldy))
                {
                    fieldy.SetValueWithoutNotify(transformOrigin.x);
                }
                FloatField floatField = GetOrCreateFields <FloatField, float>("z", 2);
                if (!IsFocused(floatField))
                {
                    floatField.SetValueWithoutNotify(transformOrigin.z);
                }
                Add(m_SpecificityLabel);
                SetSpecificity(specificity);
                SetEnabled(false);
            }
            else if (val is Enum)
            {
                Enum      enumValue = (Enum)val;
                EnumField field     = GetOrCreateEnumField(enumValue);
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(enumValue);
                }
            }
            else
            {
                var type = val.GetType();
                Debug.Assert(type.IsArrayOrList(), "Expected List type");

                var listValue   = val as System.Collections.IList;
                var valueString = listValue[0].ToString();
                for (int i = 1; i < listValue.Count; i++)
                {
                    valueString += $", {listValue[i]}";
                }
                TextField field = GetOrCreateField <TextField, string>();
                if (!IsFocused(field))
                {
                    field.SetValueWithoutNotify(valueString);
                }
            }

            SetSpecificity(specificity);
        }
        private void AddMainUI(VisualElement mainView)
        {
            var visualTree = AssetDatabase.LoadAssetAtPath <VisualTreeAsset>("Packages/com.unity.2d.sprite/Editor/UI/SpriteEditor/SpriteFrameModuleInspector.uxml") as VisualTreeAsset;

            m_SelectedFrameInspector = visualTree.CloneTree().Q("spriteFrameModuleInspector");

            m_NameElement = m_SelectedFrameInspector.Q("name");
            m_NameField   = m_SelectedFrameInspector.Q <TextField>("spriteName");
            m_NameField.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    selectedSpriteName = evt.newValue;
                }
            });

            m_NameField.RegisterCallback <FocusOutEvent>((focus) =>
            {
                if (hasSelected)
                {
                    m_NameField.SetValueWithoutNotify(selectedSpriteName);
                }
            });


            m_PositionElement = m_SelectedFrameInspector.Q("position");
            m_PositionFieldX  = m_PositionElement.Q <IntegerField>("positionX");
            m_PositionFieldX.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    var rect           = selectedSpriteRect;
                    rect.x             = evt.newValue;
                    selectedSpriteRect = rect;
                    UpdatePositionField(selectedSpriteRect);
                }
            });

            m_PositionFieldY = m_PositionElement.Q <IntegerField>("positionY");
            m_PositionFieldY.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    var rect           = selectedSpriteRect;
                    rect.y             = evt.newValue;
                    selectedSpriteRect = rect;
                    UpdatePositionField(selectedSpriteRect);
                }
            });

            m_PositionFieldW = m_PositionElement.Q <IntegerField>("positionW");
            m_PositionFieldW.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    var rect           = selectedSpriteRect;
                    rect.width         = evt.newValue;
                    selectedSpriteRect = rect;
                    UpdatePositionField(selectedSpriteRect);
                }
            });

            m_PositionFieldH = m_PositionElement.Q <IntegerField>("positionH");
            m_PositionFieldH.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    var rect           = selectedSpriteRect;
                    rect.height        = evt.newValue;
                    selectedSpriteRect = rect;
                    UpdatePositionField(selectedSpriteRect);
                }
            });

            var borderElement = m_SelectedFrameInspector.Q("border");

            m_BorderFieldL = borderElement.Q <IntegerField>("borderL");
            m_BorderFieldL.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    var border           = selectedSpriteBorder;
                    border.x             = evt.newValue;
                    selectedSpriteBorder = border;
                    m_BorderFieldL.SetValueWithoutNotify((int)selectedSpriteBorder.x);
                }
            });

            m_BorderFieldT = borderElement.Q <IntegerField>("borderT");
            m_BorderFieldT.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    var border           = selectedSpriteBorder;
                    border.w             = evt.newValue;
                    selectedSpriteBorder = border;
                    m_BorderFieldT.SetValueWithoutNotify((int)selectedSpriteBorder.w);
                    evt.StopPropagation();
                }
            });

            m_BorderFieldR = borderElement.Q <IntegerField>("borderR");
            m_BorderFieldR.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    var border           = selectedSpriteBorder;
                    border.z             = evt.newValue;
                    selectedSpriteBorder = border;
                    m_BorderFieldR.SetValueWithoutNotify((int)selectedSpriteBorder.z);
                }
            });

            m_BorderFieldB = borderElement.Q <IntegerField>("borderB");
            m_BorderFieldB.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    var border           = selectedSpriteBorder;
                    border.y             = evt.newValue;
                    selectedSpriteBorder = border;
                    m_BorderFieldB.SetValueWithoutNotify((int)selectedSpriteBorder.y);
                }
            });

            m_PivotField = m_SelectedFrameInspector.Q <EnumField>("pivotField");
            m_PivotField.Init(SpriteAlignment.Center);
            m_PivotField.label = L10n.Tr("Pivot");
            m_PivotField.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    SpriteAlignment alignment = (SpriteAlignment)evt.newValue;
                    SetSpritePivotAndAlignment(selectedSpritePivot, alignment);
                    m_CustomPivotElement.SetEnabled(selectedSpriteAlignment == SpriteAlignment.Custom);
                    Vector2 pivot = selectedSpritePivotInCurUnitMode;
                    m_CustomPivotFieldX.SetValueWithoutNotify(pivot.x);
                    m_CustomPivotFieldY.SetValueWithoutNotify(pivot.y);
                }
            });


            m_PivotUnitModeField = m_SelectedFrameInspector.Q <EnumField>("pivotUnitModeField");
            m_PivotUnitModeField.Init(PivotUnitMode.Normalized);
            m_PivotUnitModeField.label = L10n.Tr("Pivot Unit Mode");
            m_PivotUnitModeField.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    m_PivotUnitMode = (PivotUnitMode)evt.newValue;

                    Vector2 pivot = selectedSpritePivotInCurUnitMode;
                    m_CustomPivotFieldX.SetValueWithoutNotify(pivot.x);
                    m_CustomPivotFieldY.SetValueWithoutNotify(pivot.y);
                }
            });


            m_CustomPivotElement = m_SelectedFrameInspector.Q("customPivot");
            m_CustomPivotFieldX  = m_CustomPivotElement.Q <FloatField>("customPivotX");
            m_CustomPivotFieldX.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    float newValue = (float)evt.newValue;
                    float pivotX   = m_PivotUnitMode == PivotUnitMode.Pixels
                        ? ConvertFromRectToNormalizedSpace(new Vector2(newValue, 0.0f), selectedSpriteRect).x
                        : newValue;

                    var pivot = selectedSpritePivot;
                    pivot.x   = pivotX;
                    SetSpritePivotAndAlignment(pivot, selectedSpriteAlignment);
                }
            });

            m_CustomPivotFieldY = m_CustomPivotElement.Q <FloatField>("customPivotY");
            m_CustomPivotFieldY.RegisterValueChangedCallback((evt) =>
            {
                if (hasSelected)
                {
                    float newValue = (float)evt.newValue;
                    float pivotY   = m_PivotUnitMode == PivotUnitMode.Pixels
                        ? ConvertFromRectToNormalizedSpace(new Vector2(0.0f, newValue), selectedSpriteRect).y
                        : newValue;

                    var pivot = selectedSpritePivot;
                    pivot.y   = pivotY;
                    SetSpritePivotAndAlignment(pivot, selectedSpriteAlignment);
                }
            });

            //// Force an update of all the fields.
            PopulateSpriteFrameInspectorField();

            mainView.RegisterCallback <SpriteSelectionChangeEvent>(SelectionChange);

            // Stop mouse events from reaching the main view.
            m_SelectedFrameInspector.pickingMode = PickingMode.Ignore;
            m_SelectedFrameInspector.RegisterCallback <MouseDownEvent>((e) => { e.StopPropagation(); });
            m_SelectedFrameInspector.RegisterCallback <MouseUpEvent>((e) => { e.StopPropagation(); });
            m_SelectedFrameInspector.AddToClassList("moduleWindow");
            m_SelectedFrameInspector.AddToClassList("bottomRightFloating");
            mainView.Add(m_SelectedFrameInspector);
        }