public static KeybindingsOverlay CreateOverlayGameObject(PrefabManager prefabManager)
    {
        // Heavily inspired by hazmox's VAMOverlays https://hub.virtamate.com/resources/vamoverlays.2438/
        // Thanks a lot for allowing me to use the result of your hard work!

        var go = new GameObject(nameof(KeybindingsOverlay))
        {
            layer = 5
        };

        go.SetActive(false);
        try
        {
            go.transform.SetParent(SuperController.singleton.MonitorCenterCamera.transform, false);

            var canvas = go.AddComponent <Canvas>();
            canvas.renderMode   = RenderMode.ScreenSpaceCamera;
            canvas.sortingOrder = LayerMask.NameToLayer("ScreenUI");
            canvas.worldCamera  = CameraTarget.centerTarget.targetCamera;

            // To make the area visible
            // var bg = go.AddComponent<Image>();
            // bg.raycastTarget = false;
            // bg.color = new Color(1f, 1f, 1f, 0.01f);

            var overlay = go.AddComponent <KeybindingsOverlay>();
            overlay._canvas = canvas;

            {
                var textContainerGo = new GameObject("text")
                {
                    layer = 5
                };
                textContainerGo.transform.SetParent(go.transform, false);

                var textRect = textContainerGo.AddComponent <RectTransform>();
                textRect.pivot            = new Vector2(1, 0);
                textRect.anchorMin        = new Vector2(0, 0);
                textRect.anchorMax        = new Vector2(1, 0);
                textRect.anchoredPosition = new Vector2(-15, 10f);

                var text = textContainerGo.AddComponent <Text>();
                text.raycastTarget = false;
                text.color         = Color.white;
                text.font          = prefabManager.font;
                text.fontSize      = 28;
                text.alignment     = TextAnchor.LowerRight;
                overlay.text       = text;

                var textShadow = textContainerGo.AddComponent <Shadow>();
                textShadow.effectColor    = Color.black;
                textShadow.effectDistance = new Vector2(2f, -3f);
            }

            {
                var textInputGo = new GameObject();
                textInputGo.transform.SetParent(go.transform, false);

                var textRect = textInputGo.AddComponent <RectTransform>();
                textRect.pivot            = new Vector2(1, 0);
                textRect.anchorMin        = new Vector2(0, 0);
                textRect.anchorMax        = new Vector2(1, 0);
                textRect.anchoredPosition = new Vector2(-18, -20f);

                var text = textInputGo.AddComponent <Text>();
                text.raycastTarget = true;
                text.font          = prefabManager.font;
                text.alignment     = TextAnchor.UpperRight;
                text.fontSize      = 16;

                var textShadow = textInputGo.AddComponent <Shadow>();
                textShadow.effectColor    = Color.black;
                textShadow.effectDistance = new Vector2(1f, -1.5f);

                var input = textInputGo.AddComponent <InputField>();
                input.textComponent  = text;
                input.interactable   = true;
                input.selectionColor = new Color(0f, 0.3f, 0f, 0.1f);
                overlay.input        = input;
            }

            return(overlay);
        }
        catch (Exception e)
        {
            Destroy(go);
            SuperController.LogError("Keybindings: Failed creating overlays" + e);
            return(null);
        }
    }
示例#2
0
            public Animation(DAZMorph morph, string animString, float scale)
            {
                this.morph = morph;

                List <char> frames = new List <char>(animString);

                List <Keyframe> keyframes = new List <Keyframe>();

                Keyframe?lastKeyframe  = null;
                char     lastChar      = '\0';
                float    time          = 0;
                float    timeIncrement = 0.08f;

                //float inTangent = 0.0f;
                //float outTangent = 0.0f;
                //float inWeight = 0.0f;
                //float outWeight = 0.0f;
                foreach (var character in frames)
                {
                    if (valueLookup.ContainsKey(character) == false)
                    {
                        SuperController.LogError("Morphanimation: Bad frame character: " + character);
                        throw new Exception("Bad frame character: " + character);
                    }

                    float value = valueLookup[character] * scale;

                    if (lastKeyframe == null)
                    {
                        lastChar     = character;
                        lastKeyframe = new Keyframe(0, value);
                        keyframes.Add(lastKeyframe.Value);
                    }

                    // character change
                    if (lastChar != character)
                    {
                        //keyframes.Add(new Keyframe(time - timeIncrement, lastKeyframe.Value.value));

                        lastKeyframe = new Keyframe(time, value);
                        keyframes.Add(lastKeyframe.Value);

                        lastChar = character;
                    }

                    time += timeIncrement;
                }

                duration = time - timeIncrement;

                //foreach(var k in keyframes)
                //{
                //    Debug.Log(k.time + " " + k.value);
                //}

                curve = new AnimationCurve(keyframes.ToArray());

                for (int i = 0; i < curve.keys.Length; i++)
                {
                    curve.SmoothTangents(i, 0.5f);
                }
            }
示例#3
0
        public List <AtomAnimationClip> ImportClip(AtomAnimationClip clip)
        {
            var clips = new List <AtomAnimationClip>();

            var matchingLayer = _animation.clips.FirstOrDefault(c =>
            {
                // We only need to match float params and controllers, triggers can be in any layers
                if (!clip.targetFloatParams.All(t => c.targetFloatParams.Any(t.TargetsSameAs)))
                {
                    return(false);
                }
                if (!clip.targetControllers.All(t => c.targetControllers.Any(t.TargetsSameAs)))
                {
                    return(false);
                }
                return(true);
            });

            if (matchingLayer != null)
            {
                clip.animationLayer = matchingLayer.animationLayer;

                // Add missing targets
                foreach (var target in matchingLayer.targetFloatParams)
                {
                    if (!clip.targetFloatParams.Any(t => target.TargetsSameAs(t)))
                    {
                        var missing = new FloatParamAnimationTarget(target);
                        missing.AddEdgeFramesIfMissing(clip.animationLength);
                        clip.Add(missing);
                    }
                }
                foreach (var target in matchingLayer.targetControllers)
                {
                    if (!clip.targetControllers.Any(t => target.TargetsSameAs(t)))
                    {
                        var missing = new FreeControllerAnimationTarget(target.controller);
                        missing.AddEdgeFramesIfMissing(clip.animationLength);
                        clip.Add(missing);
                    }
                }
            }
            else if (_animation.index.ByLayer(clip.animationLayer).Any())
            {
                clip.animationLayer = new LayersOperations(_animation, clip).GetNewLayerName();
            }

            foreach (var controller in clip.targetControllers.Select(t => t.controller))
            {
                if (_animation.clips.Where(c => c.animationLayer != clip.animationLayer).Any(c => c.targetControllers.Any(t => t.controller == controller)))
                {
                    if (!_silent)
                    {
                        SuperController.LogError($"Timeline: Imported animation contains controller {controller.name} in layer {clip.animationLayer}, but that controller is already used elsewhere in your animation. To import, a layer is needed with targets: {string.Join(", ", clip.GetAllCurveTargets().Select(c => c.GetShortName()).ToArray())}");
                    }
                    return(clips);
                }
            }

            foreach (var floatParam in clip.targetFloatParams.Select(t => t.name))
            {
                if (_animation.clips.Where(c => c.animationLayer != clip.animationLayer).Any(c => c.targetFloatParams.Any(t => t.name == floatParam)))
                {
                    if (!_silent)
                    {
                        SuperController.LogError($"Timeline: Imported animation contains storable float {floatParam} in layer {clip.animationLayer}, but that storable is already used elsewhere in your animation. To import, a layer is needed with targets: {string.Join(", ", clip.GetAllCurveTargets().Select(c => c.GetShortName()).ToArray())}");
                    }
                    return(clips);
                }
            }

            var existingClip = _animation.GetClip(clip.animationLayer, clip.animationName);

            if (existingClip != null)
            {
                if (existingClip.IsEmpty())
                {
                    _animation.clips.Remove(existingClip);
                    existingClip.Dispose();
                }
                else
                {
                    var newAnimationName = GenerateUniqueAnimationName(clip.animationLayer, clip.animationName);
                    if (!_silent)
                    {
                        SuperController.LogError($"Timeline: Imported clip '{clip.animationNameQualified}' already exists and will be imported with the name {newAnimationName}");
                    }
                    clip.animationName = newAnimationName;
                }
            }

            clips.Add(clip);
            return(clips);
        }
        private void DeserializeClip(AtomAnimationClip clip, JSONClass clipJSON)
        {
            var animationPatternUID = clipJSON["AnimationPattern"]?.Value;

            if (!string.IsNullOrEmpty(animationPatternUID))
            {
                var animationPattern = SuperController.singleton.GetAtomByUid(animationPatternUID)?.GetComponentInChildren <AnimationPattern>();
                if (animationPattern == null)
                {
                    SuperController.LogError($"Animation Pattern '{animationPatternUID}' linked to animation '{clip.animationName}' of atom '{_atom.uid}' was not found in scene");
                }
                else
                {
                    clip.animationPattern = animationPattern;
                }
            }

            JSONArray controllersJSON = clipJSON["Controllers"].AsArray;

            if (controllersJSON != null)
            {
                foreach (JSONClass controllerJSON in controllersJSON)
                {
                    var controllerName = controllerJSON["Controller"].Value;
                    var controller     = _atom.freeControllers.Single(fc => fc.name == controllerName);
                    if (controller == null)
                    {
                        SuperController.LogError($"VamTimeline: Atom '{_atom.uid}' does not have a controller '{controllerName}'");
                        continue;
                    }
                    var target = new FreeControllerAnimationTarget(controller);
                    clip.Add(target);
                    DeserializeCurve(target.x, controllerJSON["X"], clip.animationLength, target.settings);
                    DeserializeCurve(target.y, controllerJSON["Y"], clip.animationLength);
                    DeserializeCurve(target.z, controllerJSON["Z"], clip.animationLength);
                    DeserializeCurve(target.rotX, controllerJSON["RotX"], clip.animationLength);
                    DeserializeCurve(target.rotY, controllerJSON["RotY"], clip.animationLength);
                    DeserializeCurve(target.rotZ, controllerJSON["RotZ"], clip.animationLength);
                    DeserializeCurve(target.rotW, controllerJSON["RotW"], clip.animationLength);
                    AddMissingKeyframeSettings(target);
                    target.AddEdgeFramesIfMissing(clip.animationLength);
                }
            }

            JSONArray floatParamsJSON = clipJSON["FloatParams"].AsArray;

            if (floatParamsJSON != null)
            {
                foreach (JSONClass paramJSON in floatParamsJSON)
                {
                    var storableId     = paramJSON["Storable"].Value;
                    var floatParamName = paramJSON["Name"].Value;
                    var target         = new FloatParamAnimationTarget(_atom, storableId, floatParamName);
                    clip.Add(target);
                    DeserializeCurve(target.value, paramJSON["Value"], clip.animationLength, target.settings);
                    AddMissingKeyframeSettings(target);
                    target.AddEdgeFramesIfMissing(clip.animationLength);
                }
            }

            JSONArray triggersJSON = clipJSON["Triggers"].AsArray;

            if (triggersJSON != null)
            {
                foreach (JSONClass triggerJSON in triggersJSON)
                {
                    var target = new TriggersAnimationTarget
                    {
                        name = DeserializeString(triggerJSON["Name"], "Trigger")
                    };
                    foreach (JSONClass entryJSON in triggerJSON["Triggers"].AsArray)
                    {
                        var trigger = new AtomAnimationTrigger();
                        trigger.RestoreFromJSON(entryJSON);
                        target.SetKeyframe(trigger.startTime, trigger);
                    }
                    target.AddEdgeFramesIfMissing(clip.animationLength);
                    clip.Add(target);
                }
            }
        }
示例#5
0
        private IEnumerator RefreshCurrentUIDeferred(string screen)
        {
            // Let every event trigger a UI refresh
            yield return(0);

            _uiRefreshScheduled = false;

            // Cannot proceed
            if (_plugin == null || _plugin.animation == null || _plugin.animation.Current == null)
            {
                yield break;
            }

            // Same UI, just refresh
            if (_current != null && _current.name == screen)
            {
                yield break;
            }

            // UI Change
            _uiRefreshInProgress = true;

            // Dispose previous
            if (_current != null)
            {
                try
                {
                    _current.Dispose();
                }
                catch (Exception exc)
                {
                    SuperController.LogError($"VamTimeline.{nameof(ScreensManager)}.{nameof(RefreshCurrentUIDeferred)} (while removing {_current.name}): {exc}");
                }

                _current = null;
            }

            yield return(0);

            // Create new screen
            switch (screen)
            {
            case SettingsScreen.ScreenName:
                _current = new SettingsScreen(_plugin);
                break;

            case TargetsScreen.ScreenName:
                _current = new TargetsScreen(_plugin);
                break;

            case EditScreen.ScreenName:
                _current = new EditScreen(_plugin);
                break;

            case BulkScreen.ScreenName:
                _current = new BulkScreen(_plugin);
                break;

            case AdvancedScreen.ScreenName:
                _current = new AdvancedScreen(_plugin);
                break;

            case MocapScreen.ScreenName:
                _current = new MocapScreen(_plugin);
                break;

            case MoreScreen.ScreenName:
                _current = new MoreScreen(_plugin);
                break;

            case EditAnimationScreen.ScreenName:
                _current = new EditAnimationScreen(_plugin);
                break;

            case EditSequenceScreen.ScreenName:
                _current = new EditSequenceScreen(_plugin);
                break;

            case AddAnimationScreen.ScreenName:
                _current = new AddAnimationScreen(_plugin);
                break;

            case ManageAnimationsScreen.ScreenName:
                _current = new ManageAnimationsScreen(_plugin);
                break;

            case PerformanceScreen.ScreenName:
                _current = new PerformanceScreen(_plugin);
                break;

            case HelpScreen.ScreenName:
                _current = new HelpScreen(_plugin);
                break;

            default:
                throw new InvalidOperationException($"Unknown screen {screen}");
            }

            try
            {
                _current.onScreenChangeRequested.AddListener(ChangeScreen);
                _current.Init();
            }
            catch (Exception exc)
            {
                SuperController.LogError($"VamTimeline.{nameof(ScreensManager)}.{nameof(RefreshCurrentUIDeferred)} (while initializing {_current.name}): {exc}");
            }

            yield return(0);

            _uiRefreshInProgress = false;

            if (_uiRefreshInvalidated)
            {
                _uiRefreshInvalidated = false;
                _uiRefreshScheduled   = true;
                _plugin.StartCoroutine(RefreshCurrentUIDeferred(_currentScreen));
            }

            if (_animationUI.popup.visible)
            {
                // Fix for when the popup is open, it becomes hidden by newer components
                _animationUI.popup.visible = false;
            }
        }
示例#6
0
        private IEnumerator RefreshCurrentUIDeferred(string screen)
        {
            // Let every event trigger a UI refresh
            yield return(0);

            _uiRefreshScheduled = false;

            // Cannot proceed
            if (_plugin == null || _plugin.animation == null || _plugin.animationEditContext.current == null)
            {
                yield break;
            }

            // Same UI, just refresh
            if (_current != null && _current.screenId == screen)
            {
                _uiRefreshCoroutine = null;
                yield break;
            }

            // UI Change
            _uiRefreshInProgress = true;

            // Dispose previous
            if (_current != null)
            {
                try
                {
                    Destroy(_current.gameObject);
                }
                catch (Exception exc)
                {
                    SuperController.LogError($"Timeline.{nameof(ScreensManager)}.{nameof(RefreshCurrentUIDeferred)} (while removing {_current.screenId}): {exc}");
                }

                _current = null;
            }

            yield return(0);

            var screenContainer = CreateScreenContainer();

            switch (screen)
            {
            case OptionsScreen.ScreenName:
                _current = screenContainer.AddComponent <OptionsScreen>();
                break;

            case AddRemoveTargetsScreen.ScreenName:
                _current = screenContainer.AddComponent <AddRemoveTargetsScreen>();
                break;

            case TargetsScreen.ScreenName:
                _current = screenContainer.AddComponent <TargetsScreen>();
                break;

            case AnimationsScreen.ScreenName:
                _current = screenContainer.AddComponent <AnimationsScreen>();
                break;

            case BulkScreen.ScreenName:
                _current = screenContainer.AddComponent <BulkScreen>();
                break;

            case AdvancedKeyframeToolsScreen.ScreenName:
                _current = screenContainer.AddComponent <AdvancedKeyframeToolsScreen>();
                break;

            case MocapScreen.ScreenName:
                _current = screenContainer.AddComponent <MocapScreen>();
                break;

            case RecordScreen.ScreenName:
                _current = screenContainer.AddComponent <RecordScreen>();
                break;

            case ReduceScreen.ScreenName:
                _current = screenContainer.AddComponent <ReduceScreen>();
                break;

            case MoreScreen.ScreenName:
                _current = screenContainer.AddComponent <MoreScreen>();
                break;

            case ImportExportScreen.ScreenName:
                _current = screenContainer.AddComponent <ImportExportScreen>();
                break;

            case EditAnimationScreen.ScreenName:
                _current = screenContainer.AddComponent <EditAnimationScreen>();
                break;

            case SequencingScreen.ScreenName:
                _current = screenContainer.AddComponent <SequencingScreen>();
                break;

            case AddAnimationScreen.ScreenName:
                _current = screenContainer.AddComponent <AddAnimationScreen>();
                break;

            case ManageAnimationsScreen.ScreenName:
                _current = screenContainer.AddComponent <ManageAnimationsScreen>();
                break;

            case LockedScreen.ScreenName:
                _current = screenContainer.AddComponent <LockedScreen>();
                break;

            case DiagnosticsScreen.ScreenName:
                _current = screenContainer.AddComponent <DiagnosticsScreen>();
                break;

            case HelpScreen.ScreenName:
                _current = screenContainer.AddComponent <HelpScreen>();
                break;

            case ControllerTargetSettingsScreen.ScreenName:
                _current = screenContainer.AddComponent <ControllerTargetSettingsScreen>();
                break;

            default:
                throw new InvalidOperationException($"Unknown screen {screen}");
            }

            try
            {
                _current.transform.SetParent(transform, false);
                _current.popupParent = popupParent;
                _current.onScreenChangeRequested.AddListener(ChangeScreen);
                _current.Init(_plugin, _currentScreenArg);
                onScreenChanged.Invoke(new ScreenChangedEventArgs {
                    screenName = _current.screenId, screenArg = _currentScreenArg
                });
            }
            catch (Exception exc)
            {
                SuperController.LogError($"Timeline.{nameof(ScreensManager)}.{nameof(RefreshCurrentUIDeferred)} (while initializing {_current.screenId}): {exc}");
            }

            yield return(0);

            _uiRefreshInProgress = false;

            _uiRefreshCoroutine = null;

            if (_uiRefreshInvalidated)
            {
                _uiRefreshInvalidated = false;
                _uiRefreshScheduled   = true;
                _uiRefreshCoroutine   = StartCoroutine(RefreshCurrentUIDeferred(_currentScreen));
            }
        }
示例#7
0
        private void UpdateAnimationLength(float newLength)
        {
            if (_lengthWhenLengthModeChanged == 0f)
            {
                return;
            }

            newLength = newLength.Snap(plugin.snapJSON.val);
            if (newLength < 0.1f)
            {
                newLength = 0.1f;
            }
            var time = plugin.animation.Time.Snap();

            switch (_lengthModeJSON.val)
            {
            case ChangeLengthModeStretch:
                current.StretchLength(newLength);
                _lengthWhenLengthModeChanged = newLength;
                break;

            case ChangeLengthModeCropExtendEnd:
                current.CropOrExtendLengthEnd(newLength);
                _lengthWhenLengthModeChanged = newLength;
                break;

            case ChangeLengthModeCropExtendBegin:
                current.CropOrExtendLengthBegin(newLength);
                _lengthWhenLengthModeChanged = newLength;
                break;

            case ChangeLengthModeCropExtendAtTime:
            {
                if (plugin.animation.IsPlaying())
                {
                    _lengthJSON.valNoCallback = current.animationLength;
                    return;
                }
                var previousKeyframe = current.AllTargets.SelectMany(t => t.GetAllKeyframesTime()).Where(t => t <= time + 0.0011f).Max();
                var nextKeyframe     = current.AllTargets.SelectMany(t => t.GetAllKeyframesTime()).Where(t => t > time + 0.0001f).Min();

                var keyframeAllowedDiff = (nextKeyframe - time - 0.001f).Snap();

                if ((current.animationLength - newLength) > keyframeAllowedDiff)
                {
                    newLength = current.animationLength - keyframeAllowedDiff;
                }

                current.CropOrExtendLengthAtTime(newLength, time);
                break;
            }

            case ChangeLengthModeAddKeyframeEnd:
            {
                if (newLength <= _lengthWhenLengthModeChanged + float.Epsilon)
                {
                    _lengthJSON.valNoCallback = current.animationLength;
                    return;
                }
                var snapshot = current.Copy(_lengthWhenLengthModeChanged, true);
                current.CropOrExtendLengthEnd(newLength);
                current.Paste(_lengthWhenLengthModeChanged, snapshot);
                break;
            }

            case ChangeLengthModeAddKeyframeBegin:
            {
                if (newLength <= _lengthWhenLengthModeChanged + float.Epsilon)
                {
                    _lengthJSON.valNoCallback = current.animationLength;
                    return;
                }
                var snapshot = current.Copy(0f, true);
                current.CropOrExtendLengthBegin(newLength);
                current.Paste((newLength - _lengthWhenLengthModeChanged).Snap(), snapshot);
                break;
            }

            case ChangeLengthModeLoop:
            {
                newLength = newLength.Snap(_lengthWhenLengthModeChanged);
                var loops = (int)Math.Round(newLength / _lengthWhenLengthModeChanged);
                if (loops <= 1 || newLength <= _lengthWhenLengthModeChanged)
                {
                    _lengthJSON.valNoCallback = current.animationLength;
                    return;
                }
                var frames = current
                             .TargetControllers.SelectMany(t => t.GetLeadCurve().keys.Select(k => k.time))
                             .Concat(current.TargetFloatParams.SelectMany(t => t.value.keys.Select(k => k.time)))
                             .Select(t => t.Snap())
                             .Where(t => t < _lengthWhenLengthModeChanged)
                             .Distinct()
                             .ToList();

                var snapshots = frames.Select(f => current.Copy(f, true)).ToList();
                foreach (var c in snapshots[0].controllers)
                {
                    c.snapshot.curveType = CurveTypeValues.Smooth;
                }

                current.CropOrExtendLengthEnd(newLength);

                for (var repeat = 0; repeat < loops; repeat++)
                {
                    for (var i = 0; i < frames.Count; i++)
                    {
                        var pasteTime = frames[i] + (_lengthWhenLengthModeChanged * repeat);
                        if (pasteTime >= newLength)
                        {
                            continue;
                        }
                        current.Paste(pasteTime, snapshots[i]);
                    }
                }
            }
            break;

            default:
                SuperController.LogError($"VamTimeline: Unknown animation length type: {_lengthModeJSON.val}");
                break;
            }

            current.DirtyAll();

            plugin.animation.Time = Math.Max(time, newLength);
        }
示例#8
0
 public static void Message(string message)
 {
     SuperController.LogMessage($"{nameof(EmissiveClothing)}: {message}");
 }
        public override void Init()
        {
            try {
                UpdateInitialMorphs();
                UpdateNewMorphs();
                UpdateCurrentMorphs();

                Dictionary <string, UIDynamicToggle> toggles         = new Dictionary <string, UIDynamicToggle>();
                Dictionary <string, UIDynamicButton> buttons         = new Dictionary <string, UIDynamicButton>();
                Dictionary <string, string>          toggleRelations = new Dictionary <string, string>();

                #region Sliders
                minSlider           = new JSONStorableFloat("Minimum value", -0.3f, -1f, 1.0f, true);
                minSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(minSlider);
                CreateSlider(minSlider, false);

                maxSlider           = new JSONStorableFloat("Maximum value", 0.3f, -1f, 1.0f, true);
                maxSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(maxSlider);
                CreateSlider(maxSlider, false);

                multiSlider           = new JSONStorableFloat("Multiplier", 1f, 0f, 2f, true);
                multiSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(multiSlider);
                CreateSlider(multiSlider, false);
                #endregion

                #region Region Buttons Preparation
                JSONStorable               geometry     = containingAtom.GetStorableByID("geometry");
                DAZCharacterSelector       character    = geometry as DAZCharacterSelector;
                GenerateDAZMorphsControlUI morphControl = character.morphsControlUI;

                HashSet <string>            regions          = new HashSet <string>();
                HashSet <string>            LastRegions      = new HashSet <string>();
                Dictionary <string, string> temporaryToggles = new Dictionary <string, string>();

                JSONStorableBool playingBool = new JSONStorableBool("Play", false);
                playingBool.storeType = JSONStorableParam.StoreType.Full;
                RegisterBool(playingBool);
                toggles["Play"] = CreateToggle((playingBool), false);

                morphControl.GetMorphDisplayNames().ForEach((name) =>
                {
                    DAZMorph morph = morphControl.GetMorphByDisplayName(name);
                    regions.Add(morph.region);

                    if (
                        poseRegion.Any((str) => morph.region.Contains(str)) &&
                        !bodyRegion.Any((str) => morph.region.Contains(str)) &&
                        !morph.region.Contains("Reloaded")
                        )
                    {
                        string[] posePaths      = Regex.Split(morph.region, "/");
                        string morphUpperRegion = "";

                        foreach (string posePath in posePaths)
                        {
                            morphUpperRegion = posePath;
                        }

                        LastRegions.Add(morphUpperRegion);
                        toggleRelations[name]  = morphUpperRegion;
                        temporaryToggles[name] = morphUpperRegion + "/" + name;
                    }
                });

                #region Region Helper Buttons
                UIDynamicButton selectAll = CreateButton("Select All", true);
                selectAll.button.onClick.AddListener(delegate() {
                    toggles.Values.ToList().ForEach((toggle) =>
                    {
                        toggle.toggle.isOn = true;
                    });
                });
                UIDynamicButton selectNone = CreateButton("Select None", true);
                selectNone.button.onClick.AddListener(delegate() {
                    toggles.Values.ToList().ForEach((toggle) =>
                    {
                        toggle.toggle.isOn = false;
                    });
                });

                foreach (string LastRegion in LastRegions)
                {
                    buttons[LastRegion] = CreateButton(LastRegion, true);
                    buttons[LastRegion].button.onClick.AddListener(delegate() {
                        ResetMorphs();
                        foreach (KeyValuePair <string, UIDynamicToggle> entry in toggles)
                        {
                            if (toggleRelations.ContainsKey(entry.Key))
                            {
                                entry.Value.toggle.isOn = (toggleRelations[entry.Key] == LastRegion);
                            }
                        }
                    });
                }
                #endregion

                #region Region checkbox generation
                foreach (KeyValuePair <string, string> entry in temporaryToggles)
                {
                    JSONStorableBool checkBoxTick = new JSONStorableBool(entry.Value, false);
                    checkBoxTick.storeType = JSONStorableParam.StoreType.Full;
                    RegisterBool(checkBoxTick);

                    toggles[entry.Key] = CreateToggle(checkBoxTick, true);
                }
                #endregion

                #endregion

                #region Play Loop

                new Thread(() =>
                {
                    Thread.CurrentThread.IsBackground = true;

                    while (true)
                    {
                        if (toggles["Play"].toggle.isOn)
                        {
                            // define the random values to switch to
                            morphControl.GetMorphDisplayNames().ForEach((name) =>
                            {
                                DAZMorph morph = morphControl.GetMorphByDisplayName(name);
                                if (toggles.ContainsKey(name) == false)
                                {
                                    return;
                                }

                                if (toggles[name].toggle.isOn)
                                {
                                    if (morph.animatable == false)
                                    {
                                        float valeur         = UnityEngine.Random.Range(minSlider.val, maxSlider.val) * multiSlider.val;
                                        newMorphValues[name] = valeur;
                                    }
                                }
                            });

                            // morph progressively every morphs to their new values
                            int etape = (int)(1000 * animLengthSlider.val / 60);
                            for (int i = 0; i < etape; i++)
                            {
                                morphControl.GetMorphDisplayNames().ForEach((name) =>
                                {
                                    DAZMorph morph = morphControl.GetMorphByDisplayName(name);
                                    if (toggles.ContainsKey(name) == false)
                                    {
                                        return;
                                    }

                                    if (toggles[name].toggle.isOn)
                                    {
                                        if (morph.animatable == false)
                                        {
                                            morph.morphValue += ((newMorphValues[name] - CurrentMorphsValues[name]) / (etape)) * 0.99f;
                                        }
                                    }
                                });
                                System.Threading.Thread.Sleep((int)(1000 * animLengthSlider.val / 60));
                            }
                            // update current state without touching the initial value for later reset
                            UpdateCurrentMorphs();
                        }
                        // sleep so no fast empty loop if no morph has been selected
                        System.Threading.Thread.Sleep((int)(100));
                    }
                }).Start();
                #endregion

                //CreateSpacer();

                #region SetAsDef button
                UIDynamicButton setasdefButton = CreateButton("Set current as default", false);
                setasdefButton.button.onClick.AddListener(delegate()
                {
                    UpdateInitialMorphs();
                });
                #endregion

                UIDynamicButton animatableButton = CreateButton("Clear Animatable", false);
                animatableButton.button.onClick.AddListener(delegate()
                {
                    morphControl.GetMorphDisplayNames().ForEach((name) =>
                    {
                        DAZMorph morph   = morphControl.GetMorphByDisplayName(name);
                        morph.animatable = false;
                    });
                });

                #region Reset button
                UIDynamicButton resetButton = CreateButton("Reset", false);
                resetButton.button.onClick.AddListener(delegate()
                {
                    ResetMorphs();
                });
                #endregion


                animLengthSlider           = new JSONStorableFloat("Loop Length (s)", 3.0f, 0.01f, 10f, true);
                animLengthSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(animLengthSlider);
                CreateSlider(animLengthSlider, false);
            }
            catch (Exception e) {
                SuperController.LogError("Exception caught: " + e);
            }
        }
示例#10
0
 public static void RestoreFromJSON(JSONClass config, IConfigProvider provider)
 {
     provider.RestoreConfig(config);
     SuperController.LogMessage("Loaded config from json!");
 }
示例#11
0
 private void Log(string message)
 {
     SuperController.LogMessage(message);
 }
示例#12
0
        public override void Init()
        {
            try {
                UpdateInitialMorphs();
                UpdateNewMorphs();
                UpdateCurrentMorphs();

                #region Sliders
                minSlider           = new JSONStorableFloat("Minimum value", -0.3f, -1f, 1.0f, true);
                minSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(minSlider);
                CreateSlider(minSlider, false);

                maxSlider           = new JSONStorableFloat("Maximum value", 0.3f, -1f, 1.0f, true);
                maxSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(maxSlider);
                CreateSlider(maxSlider, false);

                multiSlider           = new JSONStorableFloat("Multiplier", 1f, 0f, 2f, true);
                multiSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(multiSlider);
                CreateSlider(multiSlider, false);
                #endregion

                #region Region Buttons Preparation
                JSONStorable               geometry     = containingAtom.GetStorableByID("geometry");
                DAZCharacterSelector       character    = geometry as DAZCharacterSelector;
                GenerateDAZMorphsControlUI morphControl = character.morphsControlUI;

                HashSet <string>            regions          = new HashSet <string>();
                HashSet <string>            LastRegions      = new HashSet <string>();
                Dictionary <string, string> temporaryToggles = new Dictionary <string, string>();

                JSONStorableBool playingBool = new JSONStorableBool("Play", false);
                playingBool.storeType = JSONStorableParam.StoreType.Full;
                RegisterBool(playingBool);
                toggles["Play"] = CreateToggle((playingBool), false);

                morphControl.GetMorphDisplayNames().ForEach((name) =>
                {
                    DAZMorph morph = morphControl.GetMorphByDisplayName(name);
                    regions.Add(morph.region);

                    if (
                        poseRegion.Any((str) => morph.region.Contains(str)) &&
                        !bodyRegion.Any((str) => morph.region.Contains(str)) &&
                        !morph.region.Contains("Reloaded")
                        )
                    {
                        string[] posePaths      = Regex.Split(morph.region, "/");
                        string morphUpperRegion = "";

                        foreach (string posePath in posePaths)
                        {
                            morphUpperRegion = posePath;
                        }

                        LastRegions.Add(morphUpperRegion);
                        toggleRelations[name]  = morphUpperRegion;
                        temporaryToggles[name] = morphUpperRegion + "/" + name;
                    }
                });

                #region Region Helper Buttons
                UIDynamicButton selectAll = CreateButton("Select All", true);
                selectAll.button.onClick.AddListener(delegate() {
                    toggles.Values.ToList().ForEach((toggle) =>
                    {
                        toggle.toggle.isOn = true;
                    });
                });
                UIDynamicButton selectNone = CreateButton("Select None", true);
                selectNone.button.onClick.AddListener(delegate() {
                    toggles.Values.ToList().ForEach((toggle) =>
                    {
                        toggle.toggle.isOn = false;
                    });
                });

                foreach (string LastRegion in LastRegions)
                {
                    buttons[LastRegion] = CreateButton(LastRegion, true);
                    buttons[LastRegion].button.onClick.AddListener(delegate() {
                        ResetMorphs();
                        foreach (KeyValuePair <string, UIDynamicToggle> entry in toggles)
                        {
                            if (toggleRelations.ContainsKey(entry.Key))
                            {
                                entry.Value.toggle.isOn = (toggleRelations[entry.Key] == LastRegion);
                            }
                        }
                    });
                }
                #endregion

                #region Region checkbox generation
                foreach (KeyValuePair <string, string> entry in temporaryToggles)
                {
                    JSONStorableBool checkBoxTick = new JSONStorableBool(entry.Value, false);
                    checkBoxTick.storeType = JSONStorableParam.StoreType.Full;
                    RegisterBool(checkBoxTick);

                    toggles[entry.Key] = CreateToggle(checkBoxTick, true);
                }
                #endregion

                #endregion

                //CreateSpacer();

                #region SetAsDef button
                UIDynamicButton setasdefButton = CreateButton("Set current as default", false);
                setasdefButton.button.onClick.AddListener(delegate()
                {
                    UpdateInitialMorphs();
                });
                #endregion

                UIDynamicButton animatableButton = CreateButton("Clear Animatable", false);
                animatableButton.button.onClick.AddListener(delegate()
                {
                    morphControl.GetMorphDisplayNames().ForEach((name) =>
                    {
                        DAZMorph morph   = morphControl.GetMorphByDisplayName(name);
                        morph.animatable = false;
                    });
                });

                #region Reset button
                UIDynamicButton resetButton = CreateButton("Reset", false);
                resetButton.button.onClick.AddListener(delegate()
                {
                    ResetMorphs();
                });
                #endregion

                animWaitSlider           = new JSONStorableFloat("Loop length", 1f, 0.1f, 20f, true);
                animWaitSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(animWaitSlider);
                CreateSlider(animWaitSlider, false);

                animLengthSlider           = new JSONStorableFloat("Morphing speed", 1.0f, 0.1f, 20f, true);
                animLengthSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(animLengthSlider);
                CreateSlider(animLengthSlider, false);
            }
            catch (Exception e) {
                SuperController.LogError("Exception caught: " + e);
            }
        }
示例#13
0
 private int ConfigureSimHair(DAZHairGroup hair)
 {
     SuperController.LogError("Hair " + hair.name + " is not supported!");
     return(HandlerConfigurationResult.CannotApply);
 }
示例#14
0
    private void InitControls()
    {
        try
        {
            {
                _cameraDepthJSON = new JSONStorableFloat("Camera depth", 0.054f, 0f, 0.2f, false);
                RegisterFloat(_cameraDepthJSON);
                var cameraDepthSlider = CreateSlider(_cameraDepthJSON, false);
                cameraDepthSlider.slider.onValueChanged.AddListener(delegate(float val)
                {
                    ApplyCameraPosition(_lastActive);
                });
            }

            {
                _cameraHeightJSON = new JSONStorableFloat("Camera height", 0f, -0.05f, 0.05f, false);
                RegisterFloat(_cameraHeightJSON);
                var cameraHeightSlider = CreateSlider(_cameraHeightJSON, false);
                cameraHeightSlider.slider.onValueChanged.AddListener(delegate(float val)
                {
                    ApplyCameraPosition(_lastActive);
                });
            }

            {
                _cameraPitchJSON = new JSONStorableFloat("Camera pitch", 0f, -135f, 45f, true);
                RegisterFloat(_cameraPitchJSON);
                var cameraPitchSlider = CreateSlider(_cameraPitchJSON, false);
                cameraPitchSlider.slider.onValueChanged.AddListener(delegate(float val)
                {
                    ApplyCameraPosition(_lastActive);
                });
            }

            {
                _clipDistanceJSON = new JSONStorableFloat("Clip distance", 0.01f, 0.01f, .2f, true);
                RegisterFloat(_clipDistanceJSON);
                var clipDistanceSlider = CreateSlider(_clipDistanceJSON, false);
                clipDistanceSlider.slider.onValueChanged.AddListener(delegate(float val)
                {
                    ApplyCameraPosition(_lastActive);
                });
            }

            {
                _autoWorldScaleJSON = new JSONStorableBool("Auto world scale", false);
                RegisterBool(_autoWorldScaleJSON);
                var autoWorldScaleToggle = CreateToggle(_autoWorldScaleJSON, true);
                autoWorldScaleToggle.toggle.onValueChanged.AddListener(delegate(bool val)
                {
                    _dirty = true;
                });
            }

            {
                var possessedOnlyDefaultValue = true;
#if (POV_DIAGNOSTICS)
                // NOTE: Easier to test when it's always on
                possessedOnlyDefaultValue = false;
#endif
                _possessedOnlyJSON = new JSONStorableBool("Activate only when possessed", possessedOnlyDefaultValue);
                RegisterBool(_possessedOnlyJSON);
                var possessedOnlyCheckbox = CreateToggle(_possessedOnlyJSON, true);
                possessedOnlyCheckbox.toggle.onValueChanged.AddListener(delegate(bool val)
                {
                    _dirty = true;
                });
            }

            {
                _hideFaceJSON = new JSONStorableBool("Hide face", true);
                RegisterBool(_hideFaceJSON);
                var hideFaceToggle = CreateToggle(_hideFaceJSON, true);
                hideFaceToggle.toggle.onValueChanged.AddListener(delegate(bool val)
                {
                    _dirty = true;
                });
            }

            {
                _hideHairJSON = new JSONStorableBool("Hide hair", true);
                RegisterBool(_hideHairJSON);
                var hideHairToggle = CreateToggle(_hideHairJSON, true);
                hideHairToggle.toggle.onValueChanged.AddListener(delegate(bool val)
                {
                    _dirty = true;
                });
            }
        }
        catch (Exception e)
        {
            SuperController.LogError("Failed to register controls: " + e);
        }
    }
示例#15
0
        protected void ConvertMaterial(List <Renderer> allRenderers)
        {
            List <Material> invalidMaterials = new List <Material>();

            if (allRenderers.Count == 0)
            {
                SuperController.LogMessage("Make sure you have an .assetbundle loaded and a prop selected from the Asset dropdown. Then reload this plugin.");
                return;
            }

            // filter renderers by supported materials
            foreach (Renderer renderer in allRenderers)
            {
                //SuperController.LogError(renderer.material.shader.name);
                var origMats = renderer.materials;
                var vamMats  = new List <Material>();
                foreach (var mat in origMats)
                {
                    if (IsValidMaterial(mat))
                    {
                        vamMats.Add(new Material(vamPropShader));
                    }
                    else
                    {
                        vamMats.Add(null);
                        invalidMaterials.Add(mat);
                    }
                }
                if (vamMats.Count > 0)
                {
                    renderers.Add(renderer);
                    origMaterials.Add(origMats);
                    vamMaterials.Add(vamMats.ToArray());
                }
            }

            // output invalid/skipped materials
            foreach (Material invalidMaterial in invalidMaterials)
            {
                SuperController.LogMessage("Material skipped: " + invalidMaterial.name + " -- Shader: [" + invalidMaterial.shader.name + "]");
            }



            if (renderers.Count == 0)
            {
                SuperController.LogError("No compatible material could be found on this asset. Check message log for skipped materials/shaders.");
                return;
            }


            for (int i = 0; i < renderers.Count; i++)
            {
                var renderer  = renderers[i];
                var materials = renderers[i].materials;
                for (int j = 0; j < renderer.materials.Length; j++)
                {
                    if (vamMaterials[i][j] == null)
                    {
                        continue;
                    }
                    // reassign textures from unity to vam material
                    vamMaterials[i][j].name = origMaterials[i][j].name + "vamified";
                    vamMaterials[i][j].SetTexture("_MainTex", origMaterials[i][j].GetTexture("_MainTex"));
                    vamMaterials[i][j].SetTexture("_BumpMap", origMaterials[i][j].GetTexture("_BumpMap"));
                    try { vamMaterials[i][j].SetTexture("_SpecTex", origMaterials[i][j].GetTexture("_SpecGlossMap")); } catch { }
                    try { vamMaterials[i][j].SetTexture("_GlossTex", origMaterials[i][j].GetTexture("_MetallicGlossMap")); } catch { }
                    // assign VAM material to prop renderer
                    materials[j] = vamMaterials[i][j];
                }
                renderers[i].materials = materials;
            }
            SuperController.LogMessage($"total {vamMaterials.SelectMany(x => x).Where(x => x != null).Count()}");

            // apply values initially
            SetDiffColor(jDiffColor);
            SetSpecColor(jSpecColor);
            SetSpecIntensity(jSpecIntensityFloat);
            SetSpecSharpness(jSpecSharpnessFloat);
            SetSpecFresnel(jSpecFresnelFloat);
            SetDiffOffset(jDiffOffsetFloat);
            SetSpecOffset(jSpecOffsetFloat);
            SetGlossOffset(jGlossOffsetFloat);
            SetSubdermisColor(jSubdermisColor);
        }
        bool _enabledPrev = false; // allows for performant disabling
        public void Update()
        {
            if (SuperController.singleton.freezeAnimation)
            {
                return;
            }

            // allows for performant disabling with OnEnable/Disable
            // if disabling, the Update should still try and shut off
            // components one last time
            if (_enabledPrev == false && !_enabled)
            {
                return;
            }
            _enabledPrev = _enabled;

            if (_ui == null)
            {
                return;
            }

            try {
                _autoMeasurements = AutoMeasurements(_ui, containingAtom);

                _manualMeasurements = StaticMeasurements(_ui);
                _manualMeasurements.HeelToFloorOffset = _autoMeasurements.HeelToFloorOffset;

                if (containingAtom.type == "Person" && _ui.manualMarkersCopy.val)
                {
                    _ui.manualHeightStorable.val           = (_autoMeasurements.Height ?? 0) * 100;
                    _ui.manualChinHeightStorable.val       = (_autoMeasurements.ChinHeight ?? 0) * 100;
                    _ui.manualShoulderHeightStorable.val   = (_autoMeasurements.ShoulderHeight ?? 0) * 100;
                    _ui.manualNippleHeightStorable.val     = (_autoMeasurements.NippleHeight ?? 0) * 100;
                    _ui.manualUnderbustHeightStorable.val  = (_autoMeasurements.UnderbustHeight ?? 0) * 100;
                    _ui.manualNavelHeightStorable.val      = (_autoMeasurements.NavelHeight ?? 0) * 100;
                    _ui.manualCrotchHeightStorable.val     = (_autoMeasurements.CrotchHeight ?? 0) * 100;
                    _ui.manualKneeBottomHeightStorable.val = (_autoMeasurements.KneeHeight ?? 0) * 100;
                }

                _ui.headSizeHeightStorable.val   = _autoMeasurements.HeadHeight ?? 0;
                _ui.headSizeWidthStorable.val    = _autoMeasurements.HeadWidth ?? 0;
                _ui.fullHeightStorable.val       = _autoMeasurements.Height ?? 0;
                _ui.heightInHeadsStorable.val    = _ui.headSizeHeightStorable.val == 0 ? 0 : _ui.fullHeightStorable.val / _ui.headSizeHeightStorable.val;
                _ui.chinHeightStorable.val       = _autoMeasurements.ChinHeight ?? 0;
                _ui.shoulderHeightStorable.val   = _autoMeasurements.ShoulderHeight ?? 0;
                _ui.nippleHeightStorable.val     = _autoMeasurements.NippleHeight ?? 0;
                _ui.underbustHeightStorable.val  = _autoMeasurements.UnderbustHeight ?? 0;
                _ui.navelHeightStorable.val      = _autoMeasurements.NavelHeight ?? 0;
                _ui.crotchHeightStorable.val     = _autoMeasurements.CrotchHeight ?? 0;
                _ui.kneeBottomHeightStorable.val = _autoMeasurements.KneeHeight ?? 0;

                _ui.waistSizeStorable.val = _autoMeasurements.WaistSize ?? 0;
                _ui.hipSizeStorable.val   = _autoMeasurements.HipSize ?? 0;

                _ui.breastBustStorable.val      = _autoMeasurements.BustSize ?? 0;
                _ui.breastUnderbustStorable.val = _autoMeasurements.UnderbustSize ?? 0;
                _ui.breastBandStorable.val      = _autoMeasurements.BandSize ?? 0;
                _ui.breastCupStorable.val       = _autoMeasurements.CupSize ?? "";

                _ui.penisLength.val = _autoMeasurements.PenisLength ?? 0;
                _ui.penisWidth.val  = _autoMeasurements.PenisWidth ?? 0;
                _ui.penisGirth.val  = _autoMeasurements.PenisGirth ?? 0;

                UpdateVisuals();
                UpdatePenisMarkers();
            }
            catch (Exception e) {
                SuperController.LogError(e.ToString());
            }
        }
示例#17
0
 public override Init()
 {
     SuperController.LogMessage("This is a simple script (v2.0.0)");
 }
示例#18
0
        private IEnumerator InitCoroutine()
        {
            yield return(new WaitUntil(() => _uiCreated));

// #if LFE_DEBUG
//             SuperController.LogMessage($"isLoading: {SuperController.singleton.isLoading}");
// #endif
//             yield return new WaitUntil(() => SuperController.singleton.isLoading == false);
// #if LFE_DEBUG
//             SuperController.LogMessage($"isLoading: {SuperController.singleton.isLoading}");
// #endif

            // find any unused layer mask and just pick that
            _layerMask = Enumerable.Range(0, 31).FirstOrDefault(i => LayerMask.LayerToName(i).Equals(""));
#if LFE_DEBUG
            for (var i = 0; i < 32; i++)
            {
                SuperController.LogMessage($"layer {i}: {LayerMask.LayerToName(i)}");
            }
#endif

            var sc   = SuperController.singleton;
            var head = containingAtom.rigidbodies.FirstOrDefault(rb => rb.name.Equals("head"));

            if (_screenAtomUid.val == String.Empty)
            {
                _screenAtomUid.val = GenerateAtomName("LightDetector", 5);
            }
            var screen = sc.GetAtomByUid(_screenAtomUid.val);

            // create the screen that the camera will be looking at for light colors
            // place it on a special layer so we can show just this later on
            if (screen == null)
            {
#if LFE_DEBUG
                SuperController.LogMessage($"creating ImagePanel: {_screenAtomUid.val}");
#endif
                yield return(sc.AddAtomByType("ImagePanel", useuid: _screenAtomUid.val));

                screen = sc.GetAtomByUid(_screenAtomUid.val);
            }
#if LFE_DEBUG
            else
            {
                SuperController.LogMessage($"reusing ImagePanel: {_screenAtomUid.val}");
            }
#endif
            var imageObject          = screen.reParentObject.Find("object");
            var detectorOffset       = (Vector3.up * 0.06f) + (Vector3.forward * 0.11f);
            var detectorCameraOffset = detectorOffset + (Vector3.forward * 0.05f);

            screen.hidden = true;
            screen.collisionEnabledJSON.val = false;
            foreach (var t in ChildTransforms(imageObject))
            {
                t.gameObject.layer = _layerMask;
            }

            foreach (var r in imageObject.GetComponentsInChildren <Renderer>())
            {
                r.material.color = Color.black;
            }

            var mainControl = screen.freeControllers[0];
            mainControl.transform.parent        = head.transform;
            mainControl.transform.localPosition = detectorOffset;
            mainControl.transform.localRotation = Quaternion.identity;
#if !LFE_DEBUG
            mainControl.currentRotationState = FreeControllerV3.RotationState.Off;
            mainControl.currentPositionState = FreeControllerV3.PositionState.Off;
#endif
            imageObject.localScale = new Vector3(0.105f, 0.08f, 0.05f);

#if LFE_DEBUG
            SuperController.LogMessage($"targetCamera = {CameraTarget.centerTarget.targetCamera}");
#endif

            // create the camera that reads the light
            _detector = gameObject.AddComponent <BrightnessDetector>();
            _detector.PollFrequency = BRIGHTNESS_POLL_DEFAULT;
            _detector.Detector.CopyFrom(SuperController.singleton.MonitorCenterCamera);
            _detector.Detector.transform.parent        = head.transform;
            _detector.Detector.transform.localPosition = detectorCameraOffset;
            _detector.Detector.transform.localRotation = Quaternion.identity * Quaternion.Euler(0, 180, 0);
            _detector.Detector.name            = "BrightnessDetector";
            _detector.Detector.tag             = "BrightnessDetector";
            _detector.Detector.clearFlags      = CameraClearFlags.SolidColor;
            _detector.Detector.backgroundColor = Color.black;
            _detector.Detector.depth           = CameraTarget.centerTarget.targetCamera.depth - 1;
            _detector.Detector.cullingMask    |= 1 << _layerMask;

            // hide the screen created above from all cameras except out _detector
            foreach (var camera in Camera.allCameras)
            {
                if (camera.tag != _detector.Detector.tag)
                {
                    camera.cullingMask &= ~(1 << _layerMask);
                }
            }
#if LFE_DEBUG
            // enable the visibility of the screen in debug
            foreach (var camera in Camera.allCameras)
            {
                camera.cullingMask |= 1 << _layerMask;
            }
#endif

            _initCompleted = true;
        }
示例#19
0
        public void InitStorables()
        {
            animationJSON = new JSONStorableStringChooser(StorableNames.Animation, new List <string>(), "", "Animation", val => ChangeAnimation(val))
            {
                isStorable = false
            };
            RegisterStringChooser(animationJSON);

            nextAnimationJSON = new JSONStorableAction(StorableNames.NextAnimation, () =>
            {
                var i = animationJSON.choices.IndexOf(animationJSON.val);
                if (i < 0 || i > animationJSON.choices.Count - 2)
                {
                    return;
                }
                animationJSON.val = animationJSON.choices[i + 1];
            });
            RegisterAction(nextAnimationJSON);

            previousAnimationJSON = new JSONStorableAction(StorableNames.PreviousAnimation, () =>
            {
                var i = animationJSON.choices.IndexOf(animationJSON.val);
                if (i < 1 || i > animationJSON.choices.Count - 1)
                {
                    return;
                }
                animationJSON.val = animationJSON.choices[i - 1];
            });
            RegisterAction(previousAnimationJSON);

            scrubberJSON = new JSONStorableFloat(StorableNames.Scrubber, 0f, v => UpdateTime(v, true), 0f, AtomAnimationClip.DefaultAnimationLength, true)
            {
                isStorable = false
            };
            RegisterFloat(scrubberJSON);

            timeJSON = new JSONStorableFloat(StorableNames.Time, 0f, v => UpdateTime(v, false), 0f, AtomAnimationClip.DefaultAnimationLength, true)
            {
                isStorable = false
            };
            RegisterFloat(timeJSON);

            playJSON = new JSONStorableAction(StorableNames.Play, () =>
            {
                if (animation?.Current == null)
                {
                    SuperController.LogError($"VamTimeline: Cannot play animation, Timeline is still loading");
                    return;
                }
                if (SuperController.singleton.freezeAnimation)
                {
                    _resumePlayOnUnfreeze = true;
                    return;
                }
                animation.Play();
                isPlayingJSON.valNoCallback = true;
                SendToControllers(nameof(IAnimationController.OnTimelineTimeChanged));
            });
            RegisterAction(playJSON);

            playIfNotPlayingJSON = new JSONStorableAction(StorableNames.PlayIfNotPlaying, () =>
            {
                if (animation?.Current == null)
                {
                    SuperController.LogError($"VamTimeline: Cannot play animation, Timeline is still loading");
                    return;
                }
                if (SuperController.singleton.freezeAnimation)
                {
                    _resumePlayOnUnfreeze = true;
                    return;
                }
                if (animation.IsPlaying())
                {
                    return;
                }
                animation.Play();
                isPlayingJSON.valNoCallback = true;
                SendToControllers(nameof(IAnimationController.OnTimelineTimeChanged));
            });
            RegisterAction(playIfNotPlayingJSON);

            isPlayingJSON = new JSONStorableBool(StorableNames.IsPlaying, false, (bool val) =>
            {
                if (val)
                {
                    playIfNotPlayingJSON.actionCallback();
                }
                else
                {
                    stopJSON.actionCallback();
                }
            })
            {
                isStorable = false
            };
            RegisterBool(isPlayingJSON);

            stopJSON = new JSONStorableAction(StorableNames.Stop, () =>
            {
                if (animation.IsPlaying())
                {
                    _resumePlayOnUnfreeze = false;
                    animation.Stop();
                    animation.Time = animation.Time.Snap(snapJSON.val);
                    isPlayingJSON.valNoCallback = false;
                    SendToControllers(nameof(IAnimationController.OnTimelineTimeChanged));
                }
                else
                {
                    animation.Time = 0f;
                }
            });
            RegisterAction(stopJSON);

            stopIfPlayingJSON = new JSONStorableAction(StorableNames.StopIfPlaying, () =>
            {
                if (!animation.IsPlaying())
                {
                    return;
                }
                animation.Stop();
                animation.Time = animation.Time.Snap(snapJSON.val);
                isPlayingJSON.valNoCallback = false;
                SendToControllers(nameof(IAnimationController.OnTimelineTimeChanged));
            });
            RegisterAction(stopIfPlayingJSON);

            nextFrameJSON = new JSONStorableAction(StorableNames.NextFrame, () => NextFrame());
            RegisterAction(nextFrameJSON);

            previousFrameJSON = new JSONStorableAction(StorableNames.PreviousFrame, () => PreviousFrame());
            RegisterAction(previousFrameJSON);

            snapJSON = new JSONStorableFloat(StorableNames.Snap, 0.01f, (float val) =>
            {
                var rounded = val.Snap();
                if (val != rounded)
                {
                    snapJSON.valNoCallback = rounded;
                }
                if (animation != null && animation.Time % rounded != 0)
                {
                    UpdateTime(animation.Time, true);
                }
            }, 0.001f, 1f, true)
            {
                isStorable = true
            };
            RegisterFloat(snapJSON);

            cutJSON   = new JSONStorableAction("Cut", () => Cut());
            copyJSON  = new JSONStorableAction("Copy", () => Copy());
            pasteJSON = new JSONStorableAction("Paste", () => Paste());

            lockedJSON = new JSONStorableBool(StorableNames.Locked, false, (bool val) =>
            {
                _ui.UpdateLocked(val);
                if (_controllerInjectedControlerPanel != null)
                {
                    _controllerInjectedControlerPanel.locked = val;
                }
            });
            RegisterBool(lockedJSON);

            autoKeyframeAllControllersJSON = new JSONStorableBool("Auto Keyframe All Controllers", false)
            {
                isStorable = false
            };

            speedJSON = new JSONStorableFloat(StorableNames.Speed, 1f, v => UpdateAnimationSpeed(v), 0f, 5f, false)
            {
                isStorable = false
            };
            RegisterFloat(speedJSON);
        }
示例#20
0
        private void Update()
        {
            if (!_initCompleted)
            {
                return;
            }
            if (SuperController.singleton.freezeAnimation)
            {
                return;
            }
#if LFE_DEBUG
            if (Input.GetKey("up"))
            {
                CameraTarget.centerTarget.targetCamera.enabled = false;
                _detector.Detector.enabled = true;
            }
            else
            {
                CameraTarget.centerTarget.targetCamera.enabled = true;
                _detector.Detector.enabled = true;
            }
#endif

            try
            {
                _brightnessChangeCountdown -= Time.deltaTime;
                // run the scheduled animation
                if (_currentAnimation != null)
                {
                    _pupilMorph.morphValueAdjustLimits = Math.Clamp(_currentAnimation.Update(), -1.5f, 2.0f);
                    if (_currentAnimation.IsFinished)
                    {
                        _currentAnimation = null;

                        // schedule a new idle
                        _idleCountDown = UnityEngine.Random.Range(0.01f, Math.Max(IdleMaxDelayStorable.val, 0.01f));
                    }
                }

                var brightness   = CalculateBrightness();
                var currentValue = _pupilMorph.morphValue;
                var targetValue  = BrightnessToMorphValue(brightness);
                var duration     = 0f;

                if (_lastBrightness == brightness)
                {
                    // maybe schedule an idle animation - but do not interrupt an animation in progress just for idle
                    if (_currentAnimation == null && _idleCountDown < 0)
                    {
                        duration    = Math.Max(IdleAdjustSpeedStorable.val, 0.01f);
                        _idleSign   = _idleSign * -1;
                        targetValue = targetValue + (_idleSign * UnityEngine.Random.Range(0.01f, IdleStrengthStorable.val));

                        _currentAnimation = new EyeDialationAnimation(currentValue, targetValue, duration, (p) => Easings.BackEaseOut(p));
                    }
                    else
                    {
                        _idleCountDown -= Time.deltaTime;
                    }
                }
                else
                {
                    if (_brightnessChangeCountdown <= 0)
                    {
                        // schedule brightness adjustment animation - override any currently running animation for this one. light always wins
                        duration = targetValue > currentValue
                            ? DarkAdjustSpeedStorable.val
                            : LightAdjustSpeedStorable.val;
                        _currentAnimation          = new EyeDialationAnimation(currentValue, targetValue, duration, (p) => Easings.ElasticEaseOut(p));
                        _brightnessChangeCountdown = _brightnessChangeThrottle;
                    }
                }

                _lastBrightness = brightness;
            }
            catch (Exception ex)
            {
                SuperController.LogError(ex.ToString());
            }
        }
示例#21
0
        public override void Init()
        {
            try
            {
                receiverChoices             = new List <string>();
                receiverNameToForceReceiver = new Dictionary <string, ForceReceiver>();
                foreach (ForceReceiver fr in containingAtom.forceReceivers)
                {
                    receiverChoices.Add(fr.name);
                    receiverNameToForceReceiver.Add(fr.name, fr);
                }
                receiverChoiceJSON           = new JSONStorableStringChooser("receiver", receiverChoices, null, "Receiver", SyncReceiver);
                receiverChoiceJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterStringChooser(receiverChoiceJSON);
                UIDynamicPopup dp = CreateScrollablePopup(receiverChoiceJSON);
                dp.popupPanelHeight = 1100f;
                dp.popup.alwaysOpen = true;

                forceDirectionXJSON           = new JSONStorableFloat("Force direction X", 0f, -1f, 1f, false, true);
                forceDirectionXJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(forceDirectionXJSON);
                CreateSlider(forceDirectionXJSON, true);

                forceDirectionYJSON           = new JSONStorableFloat("Force direction Y", 0f, -1f, 1f, false, true);
                forceDirectionYJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(forceDirectionYJSON);
                CreateSlider(forceDirectionYJSON, true);

                forceDirectionZJSON           = new JSONStorableFloat("Force direction Z", 0f, -1f, 1f, false, true);
                forceDirectionZJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(forceDirectionZJSON);
                CreateSlider(forceDirectionZJSON, true);

                torqueDirectionXJSON           = new JSONStorableFloat("Torque direction X", 0f, -1f, 1f, false, true);
                torqueDirectionXJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(torqueDirectionXJSON);
                CreateSlider(torqueDirectionXJSON, true);

                torqueDirectionYJSON           = new JSONStorableFloat("Torque direction Y", 0f, -1f, 1f, false, true);
                torqueDirectionYJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(torqueDirectionYJSON);
                CreateSlider(torqueDirectionYJSON, true);

                torqueDirectionZJSON           = new JSONStorableFloat("Torque direction Z", 0f, -1f, 1f, false, true);
                torqueDirectionZJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(torqueDirectionZJSON);
                CreateSlider(torqueDirectionZJSON, true);

                periodJSON           = new JSONStorableFloat("period", 0.5f, 0f, 10f, false);
                periodJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(periodJSON);
                CreateSlider(periodJSON, true);

                periodRatioJSON           = new JSONStorableFloat("periodRatio", 0.5f, 0f, 1f, true);
                periodRatioJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(periodRatioJSON);
                CreateSlider(periodRatioJSON, true);

                forceDurationJSON           = new JSONStorableFloat("forceDuration", 1f, 0f, 1f, true);
                forceDurationJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(forceDurationJSON);
                CreateSlider(forceDurationJSON, true);

                forceFactorJSON           = new JSONStorableFloat("forceFactor", 0f, 0f, 1000f, false, true);
                forceFactorJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(forceFactorJSON);
                CreateSlider(forceFactorJSON, true);

                forceQuicknessJSON           = new JSONStorableFloat("forceQuickness", 10f, 0f, 50f, false, true);
                forceQuicknessJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(forceQuicknessJSON);
                CreateSlider(forceQuicknessJSON, true);

                torqueFactorJSON           = new JSONStorableFloat("torqueFactor", 5f, 0f, 100f, false, true);
                torqueFactorJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(torqueFactorJSON);
                CreateSlider(torqueFactorJSON, true);

                torqueQuicknessJSON           = new JSONStorableFloat("torqueQuickness", 10f, 0f, 50f, false, true);
                torqueQuicknessJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(torqueQuicknessJSON);
                CreateSlider(torqueQuicknessJSON, true);

                applyForceOnReturnJSON           = new JSONStorableBool("applyForceOnReturn", true);
                applyForceOnReturnJSON.storeType = JSONStorableParam.StoreType.Full;
                RegisterBool(applyForceOnReturnJSON);
                CreateToggle(applyForceOnReturnJSON, true);
            }
            catch (Exception e)
            {
                SuperController.LogError("Exception caught: " + e);
            }
        }
示例#22
0
        void Update()
        {
            if (Detector.targetTexture != null)
            {
                // get a copy of the pixels into a Texture2D

                // the script assumes the 2d and rendertexture are the same size if ever minds are changed this is a reminder
                // if (cameraTexture2d.width != cameraRenderTexture.width || cameraTexture2d.height != cameraRenderTexture.height)
                // {
                //     cameraTexture2d.Resize(cameraRenderTexture.width, cameraRenderTexture.height);
                // }

                var previous = RenderTexture.active;
                RenderTexture.active = cameraRenderTexture;
                cameraTexture2d.ReadPixels(new Rect(0, 0, cameraRenderTexture.width, cameraRenderTexture.height), 0, 0);
                cameraTexture2d.Apply(false, false);
                RenderTexture.active = previous;

                // average the colors in the image
                var colors = cameraTexture2d.GetPixels32();
                var total = colors.Length;
                var r = 0; var g = 0; var b = 0;
                for (int i = 0; i < total; i++)
                {
                    r += colors[i].r;
                    g += colors[i].g;
                    b += colors[i].b;
                }
                var color = new Color(r / total, g / total, b / total);
                // https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
                var brightness = Math.Sqrt(
                    color.r * color.r * .299f +
                    color.g * color.g * .587f +
                    color.b * color.b * .114f
                    ) / 255;
                if (brightness > 1)
                {
                    brightness = 1;
                }
                else if (brightness < 0)
                {
                    brightness = 0;
                }

                // set our public properties now
                DetectedColor      = color;
                DetectedBrightness = brightness;
#if LFE_DEBUG
                SuperController.LogMessage($"color = {color} brightness = {brightness}");
#endif

                // stop capturing the screen
                Detector.targetTexture = null;
#if !LFE_DEBUG
                if (PollFrequency > 0)
                {
                    Detector.enabled = false;
                }
#endif
            }

            pollCountdown -= Time.deltaTime;
            if (pollCountdown > 0)
            {
                // wait
                return;
            }
            else
            {
                // schedule the next update to capture the screen
#if !LFE_DEBUG
                if (PollFrequency > 0)
                {
                    Detector.enabled = true;
                }
#endif
                pollCountdown          = PollFrequency;
                Detector.targetTexture = cameraRenderTexture;
            }
        }
示例#23
0
    private IEnumerator WizardCoroutine()
    {
        context.diagnostics.TakeSnapshot("Start Wizard");

        context.embody.activeJSON.val = false;

        yield return(0);

        SuperController.singleton.worldScale = 1f;

        context.embody.presetsJSON.val = "Improved Possession";

        var steps = BuildSteps();
        var error = false;

        for (var i = 0; i < steps.Count; i++)
        {
            _step = steps[i];
            if (error)
            {
                statusJSON.val  = $"ERROR: {_step.lastError ?? "[No error message]"} / {steps.Count}\n\n{_step.helpText}";
                error           = false;
                _step.lastError = null;
            }
            else
            {
                statusJSON.val = $"Step {i + 1} / {steps.Count}\n\n{_step.helpText}";
            }

            // NOTE: Not strictly necessary, but allows physics to settle and ensures final leave will be invoked
            yield return(new WaitForSecondsRealtime(0.2f));

            try
            {
                context.diagnostics.Log($"Wizard: Enter {_step}");
                _step.Enter();
            }
            catch (Exception exc)
            {
                SuperController.LogError($"Embody: Wizard {_step}.Enter failed: {exc}");
                StopWizard("An error prevented the wizard from finishing");
                yield break;
            }

            while (!AreAnyStartRecordKeysDown())
            {
                ReopenIfClosed();

                if (_skip)
                {
                    break;
                }

                yield return(0);

                try
                {
                    _step.Update();
                }
                catch (Exception exc)
                {
                    SuperController.LogError($"Embody: Wizard {_step}.Update failed: {exc}");
                    StopWizard("An error prevented the wizard from finishing");
                    yield break;
                }
            }

            ReopenIfClosed();

            try
            {
                if (_skip)
                {
                    _skip = false;
                }
                else
                {
                    if (!_step.Apply())
                    {
                        i--;
                        error = true;
                    }
                }
            }
            catch (Exception exc)
            {
                SuperController.LogError($"Embody: Wizard {_step}.Apply failed: {exc}");
                StopWizard("An error prevented the wizard from finishing");
                yield break;
            }
            finally
            {
                try
                {
                    _step?.Leave(false);
                }
                catch (Exception exc)
                {
                    SuperController.LogError($"Embody: Wizard {_step}.Leave failed: {exc}");
                    StopWizard("An error prevented the wizard from finishing");
                }
            }
        }

        StopWizard("<b>All done!</b>\n\nYou can now activate Embody.\n\nYou can tweak your settings manually by pressing Back, or start this wizard again if you prefer.\n\nYou can save tweaks in your default profile in the <i>Import, Export & Default Settings</i> screen. Default settings will automatically apply whenever you load this plugin on an atom.\n\nNow, have fun living in the future!");
    }
示例#24
0
    // Function to initiate plugin
    public override void Init()
    {
        try {
            pluginLabelJSON.val = "Animation Sequencer";

            _startButton = CreateButton("Start Animations", false);
            if (_startButton != null)
            {
                _startButton.button.onClick.AddListener(startButtonCallback);
            }
            _stopButton = CreateButton("Stop Animations", false);
            if (_stopButton != null)
            {
                _stopButton.button.onClick.AddListener(stopButtonCallback);
            }
            _resetButton = CreateButton("Reset Animations", false);
            if (_resetButton != null)
            {
                _resetButton.button.onClick.AddListener(resetButtonCallback);
            }
            _runOnStartup = new JSONStorableBool("Run on Startup", false, runOnStartUpCallback);
            RegisterBool(_runOnStartup);
            CreateToggle(_runOnStartup, true);

            _syncStartButton = CreateButton("Reserved for Future Feature", true);
            if (_syncStartButton != null)
            {
                // Method to align all start steps
            }

            _syncEndButton = CreateButton("Reserved for Future Feature", true);
            if (_syncEndButton != null)
            {
                // Method to align end step with next start step
            }

            // Modifier used to adjust the animation switching threshold
            _animModifier = new JSONStorableFloat("SwitchTime Modifier", 0.05f, 0f, 1f, true, true);
            RegisterFloat(_animModifier);
            CreateSlider(_animModifier, false);

            // Add Random Loop Count
            _animRandomizer = new JSONStorableFloat("Loop Count Randomizer", 0.0f, 0f, 100f, true, true);
            RegisterFloat(_animRandomizer);
            CreateSlider(_animRandomizer, true);

            // Get a list of all Animations
            _animationPattern = SuperController.singleton.GetAllAnimationPatterns();
            // Create List of Animations for the Dropdown Menu
            for (var i = 0; i < _animationPattern.Count; i++)
            {
                _animList.Add(_animationPattern[i].uid.ToString());
            }
            CreateSpacer(false).height = 12;
            // Setup Pull Down Interface for Each Animation
            for (var i = 0; i < _animationPattern.Count; i++)
            {
                _animAtoms.Add(SuperController.singleton.GetAtomByUid(_animationPattern[i].uid.ToString()));
                _animChooser.Add(new JSONStorableStringChooser("Animation Chooser", _animList, _animationPattern[i].uid.ToString(), "Select Animation " + i.ToString(), AnimChooserCallback));
                _animChooserPopup.Add(CreatePopup(_animChooser[i], false));
                _animChooserPopup[i].labelWidth = 200f;
                CreateSpacer(false).height      = 24;
                _animLoops.Add(new JSONStorableFloat("Animation " + i.ToString() + " Loops", 1f, 1f, 100f, true, true));
                RegisterFloat(_animLoops[i]);
                CreateSlider(_animLoops[i], true);
            }
            // Turn off all Animation to Initialize Scene
            for (var i = 0; i < _animationPattern.Count; i++)
            {
                if (_animAtoms[i].on)
                {
                    _animAtoms[i].ToggleOn();
                }
            }
            _animTotal     = _animList.Count;
            _animTotalTime = _animationPattern[_animSequence].GetTotalTime();
            _randomNum     = _rng.Next((int)Math.Round(_animRandomizer.val));
        } catch (Exception e) {
            SuperController.LogError("Exception caught: " + e);
        }
    }
示例#25
0
        //SelectJsonStorable<AudioSource> selector;

        public override void Init()
        {
#if vamdebug
            try
            {
#endif
            audioSource = containingAtom.GetStorableByID("HeadAudioSource") as AudioSourceControl;
            if (audioSource == null)
            {
                audioSource = containingAtom.GetStorableByID("AudioSource") as AudioSourceControl;
            }
            if (audioSource == null)
            {
                SuperController.LogError($"{this} is not applicable to {containingAtom.name} ({containingAtom.type})");
            }

            playRandom = new JSONStorableAction("Play Random", playRandomClipAction);
            playNext   = new JSONStorableAction("Play Next", playNextClipAction);
            RegisterAction(playNext);
            RegisterAction(playRandom);

            pitchshift = new JSONStorableFloat("pitch shift",
                                               0f, f => playlist.pitchshift = playlist.pitchshift = f,
                                               -0.3f, 0.3f, true)
            {
                storeType = JSONStorableParam.StoreType.Full
            };
            RegisterFloat(pitchshift);
            CreateSlider(pitchshift, true);

            folderpath = new JSONStorableString("loadpath",
                                                Application.dataPath + "/../custom/assets/audio")
            {
                storeType = JSONStorableParam.StoreType.Full
            };
            RegisterString(folderpath);

            audioBulk = new AudioBulk();
            nacs      = new List <NamedAudioClip>();

            audioBulk.InitUI(this, nacs, folderpath);
            playlist = new PlayList(nacs);

            playIfClear = new JSONStorableBool("Play if clear", true);
            RegisterBool(playIfClear);
            playIfClear.storeType = JSONStorableParam.StoreType.Full;
            CreateToggle(playIfClear, true);

            delay = new JSONStorableFloat("delay", 0f, 0f, 2f, false);
            CreateSlider(delay, true);

            //CreateButton("callback").button.onClick.AddListener(() =>playNext.actionCallback());
            CreateButton("Load Audio Folder").button.onClick.AddListener(
                () => {
                audioBulk.OpenLoadFolder(nacs, folderpath);
                Loaded(nacs);
            });
            CreateButton("Load Embeded").button.onClick.AddListener(() => {
                if (!validInputNameAsEmbedded())
                {
                    SuperController.LogError("no valid source");
                    return;
                }
                LoadEmbeddedInput();
                Loaded(nacs);
            });
            CreateButton("Play next", true).button.onClick.AddListener(playNextClipAction);
            CreateButton("Play random", true).button.onClick.AddListener(playRandomClipAction);
            CreateButton("Stop", false).button.onClick.AddListener(audioSource.Stop);
            CreateTextField(folderpath, false).height = 10;
            CreateButton("Reload", false).button.onClick.AddListener(() => {
                audioBulk.Load(nacs, folderpath.val);
                Loaded(nacs);
            }
                                                                     );
            clipsLoaded = new JSONStorableString("loaded clips", "No clips loaded");

            CreateTextField(clipsLoaded, false).height = 10;

#if vamdebug
        }

        catch (Exception e)
        {
            SuperController.LogError("woops" + e);
        }
#endif
        }
示例#26
0
        public override void Init()
        {
            try
            {
                THRUST_FORCE_NAME += ":" + containingAtom.name;
                AUDIO_SOURCE_NAME += ":" + containingAtom.name;

                /*
                 * List<string> peopleIds = SuperController.singleton.GetAtoms()
                 * .Where(atom => atom.GetStorableByID("geometry") != null && (atom != containingAtom))
                 * .Select(atom => atom.name).ToList();
                 *
                 * JSONStorableStringChooser receiverChoiceJSON = new JSONStorableStringChooser("target", peopleIds, peopleIds.Count>0?peopleIds[0]:null, "Thrust Target", delegate (string receiverName)
                 * {
                 *  Atom receiver = GetAtomById(receiverName);
                 *  StartCoroutine(CreateThrustForce(receiver));
                 * });
                 * receiverChoiceJSON.storeType = JSONStorableParam.StoreType.Full;
                 * UIDynamicPopup dp = CreateScrollablePopup(receiverChoiceJSON, false);
                 * RegisterStringChooser(receiverChoiceJSON);
                 */

                StartCoroutine(CreateThrustForce());

                CreateButton("Select Thrust Force", true).button.onClick.AddListener(() =>
                {
                    if (thrustAtom != null)
                    {
                        SelectController(thrustAtom.mainController);
                    }
                });


                thrustAmount           = new JSONStorableFloat("thrustAmount", 0f, (float value) => { }, 0f, 1f, true, true);
                thrustAmount.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(thrustAmount);
                CreateSlider(thrustAmount, true);

                grindAmount            = new JSONStorableFloat("grindAmount", 0f, (float value) => { }, 0f, 1f, true, true);
                thrustAmount.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(grindAmount);
                CreateSlider(grindAmount, true);

                skinSlapSFX = new JSONStorableStringChooser("SkinSlapSound", GetAllAudioClipIds(), null, "Skin Slap Sound", (string uid) => {
                    skinSlapClip = URLAudioClipManager.singleton.GetClip(uid);
                });
                skinSlapSFX.storeType = JSONStorableParam.StoreType.Full;
                CreateScrollablePopup(skinSlapSFX).popup.onOpenPopupHandlers += () =>
                {
                    skinSlapSFX.choices = GetAllAudioClipIds();
                };
                RegisterStringChooser(skinSlapSFX);

                grindSFX = new JSONStorableStringChooser("GrindSoundFile", GetAllAudioClipIds(), null, "Grind Sound", (string uid) => {
                    grindClip = URLAudioClipManager.singleton.GetClip(uid);
                });
                grindSFX.storeType = JSONStorableParam.StoreType.Full;
                CreateScrollablePopup(grindSFX).popup.onOpenPopupHandlers += () =>
                {
                    grindSFX.choices = GetAllAudioClipIds();
                };
                RegisterStringChooser(grindSFX);

                StartCoroutine(CreateAudioSource());
            }
            catch (Exception e)
            {
                SuperController.LogError("Exception caught: " + e);
            }
        }
示例#27
0
 public override Init()
 {
     SuperController.LogMessage("This is the third script of a cslist (v1.1.0)");
 }
示例#28
0
        public override void Init()
        {
            try {
                UpdateInitialMorphs();
                UpdateNewMorphs();
                UpdateCurrentMorphs();

                #region Sliders
                minSlider           = new JSONStorableFloat("Minimum value", -0.15f, -1f, 1.0f, true);
                minSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(minSlider);
                CreateSlider(minSlider, false);

                maxSlider           = new JSONStorableFloat("Maximum value", 0.35f, -1f, 1.0f, true);
                maxSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(maxSlider);
                CreateSlider(maxSlider, false);

                multiSlider           = new JSONStorableFloat("Multiplier", 1f, 0f, 2f, true);
                multiSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(multiSlider);
                CreateSlider(multiSlider, false);
                #endregion

                #region Region Buttons Preparation
                GenerateDAZMorphsControlUI morphControl = returnMorphs();

                HashSet <string>            regions          = new HashSet <string>();
                HashSet <string>            LastRegions      = new HashSet <string>();
                Dictionary <string, string> temporaryToggles = new Dictionary <string, string>();

                JSONStorableBool playingBool = new JSONStorableBool("Play", true);
                playingBool.storeType = JSONStorableParam.StoreType.Full;
                RegisterBool(playingBool);
                toggles["Play"] = CreateToggle((playingBool), false);

                smoothToggle = new JSONStorableBool("Smooth transitions", true);
                RegisterBool(smoothToggle);
                CreateToggle((smoothToggle), false);

                abaToggle = new JSONStorableBool("Reset used expressions at loop", true);
                RegisterBool(abaToggle);
                CreateToggle((abaToggle), false);

                manualToggle = new JSONStorableBool("Trigger transitions manually", false);
                RegisterBool(manualToggle);
                CreateToggle((manualToggle), false);

                JSONStorableAction manualTrigger = new JSONStorableAction("Trigger transition", () => { UpdateRandomParams(); });
                RegisterAction(manualTrigger);

                morphControl.GetMorphDisplayNames().ForEach((name) =>
                {
                    DAZMorph morph = morphControl.GetMorphByDisplayName(name);
                    regions.Add(morph.region);

                    if (
                        (poseRegion.Any((str) => morph.region.Contains(str)) &&
                         !bodyRegion.Any((str) => morph.region.Contains(str))) ||
                        tailorList.Any((str) => name.Contains(str))
                        )
                    {
                        string[] posePaths      = Regex.Split(morph.region, "/");
                        string morphUpperRegion = "";

                        foreach (string posePath in posePaths)
                        {
                            morphUpperRegion = posePath;
                        }

                        LastRegions.Add(morphUpperRegion);
                        toggleRelations[name]  = morphUpperRegion;
                        temporaryToggles[name] = morphUpperRegion + "/" + name;
                    }
                });

                #region Region Helper Buttons
                UIDynamicButton selectAll = CreateButton("Select All", true);
                selectAll.button.onClick.AddListener(delegate() {
                    toggles.Values.ToList().ForEach((toggle) =>
                    {
                        toggle.toggle.isOn = true;
                    });
                });

                UIDynamicButton selectNone = CreateButton("Select None", true);
                selectNone.button.onClick.AddListener(delegate() {
                    toggles.Values.ToList().ForEach((toggle) =>
                    {
                        toggle.toggle.isOn = false;
                    });
                });

                UIDynamicButton selectDefault = CreateButton("Select Default", true);
                selectDefault.button.onClick.AddListener(delegate() {
                    foreach (KeyValuePair <string, UIDynamicToggle> entry in toggles)
                    {
                        if (entry.Key != "Play")
                        {
                            toggles[entry.Key].toggle.isOn = defaultOn.Any((str) => entry.Key.Equals(str));
                        }
                    }
                    ;
                });

                UIDynamicButton selectPres1 = CreateButton("Select preset 1", true);
                selectPres1.button.onClick.AddListener(delegate() {
                    foreach (KeyValuePair <string, UIDynamicToggle> entry in toggles)
                    {
                        if (entry.Key != "Play")
                        {
                            toggles[entry.Key].toggle.isOn = preset1.Any((str) => entry.Key.Equals(str));
                        }
                    }
                    ;
                });

                UIDynamicButton selectPres2 = CreateButton("Select preset 2", true);
                selectPres2.button.onClick.AddListener(delegate() {
                    foreach (KeyValuePair <string, UIDynamicToggle> entry in toggles)
                    {
                        if (entry.Key != "Play")
                        {
                            toggles[entry.Key].toggle.isOn = preset2.Any((str) => entry.Key.Equals(str));
                        }
                    }
                    ;
                });
                CreateSpacer(true).height = 10f;;
                #endregion

                #region Region checkbox generation
                foreach (KeyValuePair <string, string> entry in temporaryToggles)
                {
                    JSONStorableBool checkBoxTick = new JSONStorableBool(entry.Value, defaultOn.Any((str) => entry.Key.Equals(str)), (bool on) => {
                        togglesOn = toggles.Where(t => t.Value.toggle.isOn).ToDictionary(p => p.Key, p => p.Value);

                        if (!on && entry.Key != "Play")
                        {
                            DAZMorph morph   = morphControl.GetMorphByDisplayName(entry.Key);
                            morph.morphValue = 0;
                        }
                    });
                    checkBoxTick.storeType = JSONStorableParam.StoreType.Full;
                    RegisterBool(checkBoxTick);

                    toggles[entry.Key] = CreateToggle(checkBoxTick, true);
                }
                togglesOn = toggles.Where(t => t.Value.toggle.isOn).ToDictionary(p => p.Key, p => p.Value);
                #endregion

                #endregion

                //CreateSpacer();
                UIDynamicButton transitionButton = CreateButton("Trigger transition", false);
                transitionButton.button.onClick.AddListener(delegate() {
                    UpdateRandomParams();
                });
                transitionButton.buttonColor = new Color(0.5f, 1f, 0.5f);

                UIDynamicButton animatableButton = CreateButton("Clear Animatable (from selected)", false);
                animatableButton.button.onClick.AddListener(delegate()
                {
                    morphControl.GetMorphDisplayNames().ForEach((name) =>
                    {
                        DAZMorph morph = morphControl.GetMorphByDisplayName(name);
                        if (toggles.ContainsKey(name) && toggles[name].toggle.isOn)
                        {
                            morph.animatable = false;
                        }
                    });
                });

                #region SetAsDef button
                UIDynamicButton setasdefButton = CreateButton("Set current state as default", false);
                setasdefButton.button.onClick.AddListener(delegate()
                {
                    UpdateInitialMorphs();
                });
                #endregion

                #region Reset button
                UIDynamicButton resetButton = CreateButton("Reset", false);
                resetButton.button.onClick.AddListener(delegate()
                {
                    toggles["Play"].toggle.isOn = false;
                    ResetMorphs();
                });
                #endregion

                #region ZeroMorph button
                UIDynamicButton ZeroMorphButton = CreateButton("Zero Selected", false);
                ZeroMorphButton.button.onClick.AddListener(delegate()
                {
                    toggles["Play"].toggle.isOn = false;
                    ZeroMorphs();
                });
                #endregion

                masterSpeedSlider           = new JSONStorableFloat("Master speed", 1f, 0f, 10f, true);
                masterSpeedSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(masterSpeedSlider);
                CreateSlider(masterSpeedSlider, false);

                animWaitSlider           = new JSONStorableFloat("Loop length", 2f, 0.1f, 20f, true);
                animWaitSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(animWaitSlider);
                CreateSlider(animWaitSlider, false);

                animLengthSlider           = new JSONStorableFloat("Morphing speed", 1.0f, 0.1f, 20f, true);
                animLengthSlider.storeType = JSONStorableParam.StoreType.Full;
                RegisterFloat(animLengthSlider);
                CreateSlider(animLengthSlider, false);

                morphList = new JSONStorableString("FooString", "");
                UIDynamic morphListText = CreateTextField(morphList, false);
                morphListText.height = 320;
            }
            catch (Exception e) {
                SuperController.LogError("Exception caught: " + e);
            }
        }
示例#29
0
        public override void Init()
        {
            try
            {
                if (containingAtom.type != "Person")
                {
                    SuperController.LogError("Please add Doll Master to a Person atom");
                    return;
                }

                lastAtomName = containingAtom.uid;

                PLUGIN_PATH    = GetPluginPath();
                ASSETS_PATH    = PLUGIN_PATH + "/Assets";
                VAMASUTRA_PATH = ASSETS_PATH + "/VAMasutra";
                LOAD_PATH      = SuperController.singleton.currentLoadDir;

                headAudioSource = containingAtom.GetStorableByID("HeadAudioSource") as AudioSourceControl;

                RegisterActions();

                ui = new UI(this, 0.001f);
                ui.canvas.transform.Translate(0, 0.2f, 0);

                config = new Config(this);

                personas = new Personas(this);

                ps = new PluginState(this);

                arousal = new Arousal(this);

                expressions = new Expressions(this);

                expressionController = new ExpressionController(this);

                sfxController = new SFXController(this);

                thrustController = new ThrustController(this);

                thrustAutoController = new ThrustAutoController(this);

                breathController = new BreathController(this);

                headController = new HeadController(this);

                poseController = new PoseController(this);

                montageController = new MontageController(this, poseController);

                dressController = new DressController(this);

                climaxController = new ClimaxController(this);

                kissController = new KissController(this);

                new TopButtons(this);

                //new WorldUI(this);

                CreateSpacer().height = 200;

                //SuperController singleton = SuperController.singleton;
                //singleton.onAtomUIDRenameHandlers = (SuperController.OnAtomUIDRename)Delegate.Combine(singleton.onAtomUIDRenameHandlers, new SuperController.OnAtomUIDRename(HandleRename));
            }
            catch (Exception e)
            {
                SuperController.LogError("Exception caught: " + e);
            }
        }
示例#30
0
        Node CreateNode(AnimationPattern ap)
        {
            Node foundNode = nodes.Find((other) =>
            {
                return(other.ap == ap);
            });

            if (foundNode != null)
            {
                sc.SelectController(containingAtom.mainController);
                return(foundNode);
            }

            Node node = new Node(ui, ap);

            //ap.containingAtom.SetOn(false);
            ap.SetBoolParamValue("on", false);
            ap.Pause();
            ap.ResetAnimation();

            lineMaterial = ap.rootLineDrawerMaterial;

            if (nodes.Contains(node) == false)
            {
                nodes.Add(node);
            }

            node.connectButton.button.onClick.AddListener(() =>
            {
                sc.SelectModeAtom((atom) =>
                {
                    if (atom == ap.containingAtom)
                    {
                        SuperController.LogError("Can't make a connection to itself.");
                        return;
                    }
                    AnimationPattern childAP = atom.GetStorableByID("AnimationPattern") as AnimationPattern;
                    if (childAP == null)
                    {
                        SuperController.LogError("Only Animation Patterns can be selected.");
                        return;
                    }

                    Node childNode        = CreateNode(childAP);
                    Transition transition = CreateTransition(node.atom, childNode.atom);
                    if (transition != null)
                    {
                        node.transitions.Add(transition);
                        PerformSave();
                    }
                });
            });

            node.disconnectButton.button.onClick.AddListener(() =>
            {
                node.transitions.ForEach((t) =>
                {
                    t.OnDestroy();
                    transitions.Remove(t);
                });

                node.transitions.Clear();
            });

            sc.SelectController(containingAtom.mainController);

            return(node);
        }