Esempio n. 1
0
        private VmdLightFrame[] CreateLightFrames([NotNull] ScenarioObject scenarioObject)
        {
            var lightFrameList = new List <VmdLightFrame>();
            var lightControls  = scenarioObject.Scenario.WhereToArray(s => s.Type == ScenarioDataType.LightColor);

            foreach (var lightControl in lightControls)
            {
                var n = (int)((float)lightControl.AbsoluteTime * 60.0f);
                int frameIndex;

                if (_conversionConfig.Transform60FpsTo30Fps)
                {
                    frameIndex = n / 2;
                }
                else
                {
                    frameIndex = n;
                }

                var frame = new VmdLightFrame(frameIndex);

                frame.Position = new Vector3(0.5f, -1f, -0.5f);

                var c = lightControl.Color;
                frame.Color = new Vector3(c.R, c.G, c.B);

                lightFrameList.Add(frame);
            }

            return(lightFrameList.ToArray());
        }
Esempio n. 2
0
        public static ScenarioObject Load([NotNull] string path)
        {
            ScenarioObject result = null;

            using (var fileStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                using (var bundle = new BundleFile(fileStream, false)) {
                    foreach (var asset in bundle.AssetFiles)
                    {
                        foreach (var preloadData in asset.PreloadDataList)
                        {
                            if (preloadData.KnownType != KnownClassID.MonoBehaviour)
                            {
                                continue;
                            }

                            var behaviour = preloadData.LoadAsMonoBehaviour(true);

                            if (!behaviour.Name.EndsWith("scenario_sobj"))
                            {
                                continue;
                            }

                            behaviour = preloadData.LoadAsMonoBehaviour(false);

                            var serializer = new MonoBehaviourSerializer();
                            result = serializer.Deserialize <ScenarioObject>(behaviour);
                            break;
                        }
                    }
                }
            }

            return(result);
        }
Esempio n. 3
0
        public MvdMotion CreateFrom([CanBeNull] CharacterImasMotionAsset bodyMotion, [CanBeNull] Avatar avatar, [CanBeNull] PmxModel mltdPmxModel,
                                    [CanBeNull] CharacterImasMotionAsset cameraMotion,
                                    [CanBeNull] ScenarioObject scenarioObject, int songPosition)
        {
            IReadOnlyList <MvdCameraMotion> cameraFrames;

            if (ProcessCameraFrames && cameraMotion != null)
            {
                cameraFrames = CreateCameraMotions(cameraMotion);
            }
            else
            {
                cameraFrames = EmptyArray.Of <MvdCameraMotion>();
            }

            var mvd = new MvdMotion(cameraFrames);

            if (ConversionConfig.Current.Transform60FpsTo30Fps)
            {
                mvd.Fps = 30;
            }
            else
            {
                mvd.Fps = 60;
            }

            return(mvd);
        }
Esempio n. 4
0
    public void Initialize(ScenarioObject a_ScenarioObject, GameReferences a_GameReferences)
    {
        m_GameReferences = a_GameReferences;

        gameObject.name = a_ScenarioObject.Template.Name;

        m_SpriteRenderer.sortingOrder = -32767 + a_ScenarioObject.SortOrder;

        if (a_ScenarioObject.Template.IsLowPrioritySortOrder)
        {
            m_SpriteRenderer.sortingLayerName = "MapLowPriorityObjects";
        }

        var _Operation = Addressables.LoadAssetAsync <MapObjectVisualData>($"MapObjects/{gameObject.name}.asset");

        // Synchonously, because underground objects are initially disabled, which break their coroutines
        MapObjectVisualData _Data = _Operation.WaitForCompletion();

        if (_Operation.Status == UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationStatus.Failed)
        {
            Debug.Log(gameObject.name);
        }
        else
        {
            Renderer.SetSprites(_Operation.Result.Sprites);
            ShadowRenderer.SetSprites(_Operation.Result.ShadowSprites);
        }
    }
    public void Initialize(ScenarioObject a_ScenarioObject, GameReferences a_GameReferences)
    {
        m_GameReferences = a_GameReferences;

        gameObject.name = a_ScenarioObject.Template.Name;

        m_SpriteRenderer.sortingOrder = -32767 + a_ScenarioObject.SortOrder;

        uint _ColorIndex = a_ScenarioObject.DwellingOwner;

        // Seems neutral objects can represent multiple different values
        if (_ColorIndex > 8)
        {
            _ColorIndex = 8;
        }

        m_SpriteRenderer.material.SetColor("_PlayerColor", m_PlayerColors.Colors[_ColorIndex]);

        var _Operation = Addressables.LoadAssetAsync <MapObjectVisualData>($"MapObjects/{gameObject.name}.asset");

        // Synchonously, because underground objects are initially disabled, which break their coroutines
        MapObjectVisualData _Data = _Operation.WaitForCompletion();

        if (_Operation.Status == UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationStatus.Failed)
        {
            Debug.Log(gameObject.name);
        }
        else
        {
            m_Renderer.SetSprites(_Operation.Result.Sprites);
            m_ShadowRenderer.SetSprites(_Operation.Result.ShadowSprites);
        }
    }
Esempio n. 6
0
        private static TimedList <int, int> CollectSeekFrames([CanBeNull] ScenarioObject scenario, int formationNumber)
        {
            var result = new TimedList <int, int>();

            if (scenario == null)
            {
                return(result);
            }

            if (scenario.HasSeekFrameEvents())
            {
                var events = scenario.Scenario.WhereToArray(s => s.Type == ScenarioDataType.DanceAnimationSeekFrame);

                foreach (var ev in events)
                {
                    Debug.Assert(ev != null, nameof(ev) + " != null");

                    if (ev.Idol != formationNumber + 10)
                    {
                        continue;
                    }

                    var frameIndex  = (int)Math.Round(ev.AbsoluteTime * FrameRate.Mltd);
                    var targetFrame = ev.SeekFrame;

                    result.AddOrUpdate(frameIndex, targetFrame);
                }
            }

            return(result);
        }
Esempio n. 7
0
 private void ManageInteract(ScenarioObject so)
 {
     fButtonPressTime += Time.deltaTime;
     if (fButtonPressTime >= REGISTER_INTERACT_IN)
     {
         SetButtonCooldown();
         gc.SaveUndoDatas();
         so.Interact((Input.GetAxis(MMConstants.INPUT_TRIGGERS) > 0), (Input.GetAxis(MMConstants.INPUT_TRIGGERS) < 0));
     }
 }
        public static bool HasFacialExpressionEvents([NotNull] this ScenarioObject scrobj)
        {
            foreach (var obj in scrobj.Scenario)
            {
                if (obj.Type == ScenarioDataType.FacialExpression)
                {
                    return(true);
                }
            }

            return(false);
        }
        public static bool HasSeekFrameEvents([NotNull] this ScenarioObject scrobj)
        {
            foreach (var obj in scrobj.Scenario)
            {
                if (obj.Type == ScenarioDataType.DanceAnimationSeekFrame)
                {
                    return(true);
                }
            }

            return(false);
        }
        public static bool HasFormationChangeEvents([NotNull] this ScenarioObject scrobj)
        {
            foreach (var obj in scrobj.Scenario)
            {
                if (obj.Type == ScenarioDataType.FormationChange)
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 11
0
        public static AppealTimeInfo CollectAppealTimeInfo([NotNull] ScenarioObject scenario)
        {
            var startEvent = scenario.Scenario.Single(ev => ev.Type == ScenarioDataType.AppealStart);
            var poseEvent  = scenario.Scenario.Single(ev => ev.Type == ScenarioDataType.AppealPose);
            var endEvent   = scenario.Scenario.Single(ev => ev.Type == ScenarioDataType.AppealEnd);

            var startFrame = (int)(startEvent.AbsoluteTime * FrameRate.Mltd);
            var poseFrame  = (int)(poseEvent.AbsoluteTime * FrameRate.Mltd);
            var endFrame   = (int)(endEvent.AbsoluteTime * FrameRate.Mltd);

            return(new AppealTimeInfo(startFrame, poseFrame, endFrame));
        }
Esempio n. 12
0
        public static (ScenarioObject, ScenarioObject, ScenarioObject) LoadScenario([NotNull] string filePath)
        {
            ScenarioObject main = null, landscape = null, portrait = null;

            const string mainScenarioEnds      = "scenario_sobj";
            const string landscapeScenarioEnds = "scenario_yoko_sobj";
            const string portraitScenarioEnds  = "scenario_tate_sobj";

            var manager = new AssetsManager();

            manager.LoadFiles(filePath);

            var ser = new ScriptableObjectSerializer();

            foreach (var assetFile in manager.assetsFileList)
            {
                foreach (var obj in assetFile.Objects)
                {
                    if (obj.type != ClassIDType.MonoBehaviour)
                    {
                        continue;
                    }

                    var behaviour = obj as MonoBehaviour;

                    if (behaviour == null)
                    {
                        throw new ArgumentException("An object serialized as MonoBehaviour is actually not a MonoBehaviour.");
                    }

                    if (behaviour.m_Name.EndsWith(mainScenarioEnds))
                    {
                        main = ser.Deserialize <ScenarioObject>(behaviour);
                    }
                    else if (behaviour.m_Name.EndsWith(landscapeScenarioEnds))
                    {
                        landscape = ser.Deserialize <ScenarioObject>(behaviour);
                    }
                    else if (behaviour.m_Name.EndsWith(portraitScenarioEnds))
                    {
                        portrait = ser.Deserialize <ScenarioObject>(behaviour);
                    }

                    if (main != null && landscape != null && portrait != null)
                    {
                        break;
                    }
                }
            }

            return(main, landscape, portrait);
        }
Esempio n. 13
0
        public VmdMotion CreateFrom([CanBeNull] CharacterImasMotionAsset bodyMotion, [CanBeNull] Avatar avatar, [CanBeNull] PmxModel mltdPmxModel,
                                    [CanBeNull] CharacterImasMotionAsset cameraMotion,
                                    [CanBeNull] ScenarioObject scenarioObject, int songPosition)
        {
            IReadOnlyList <VmdBoneFrame>   boneFrames;
            IReadOnlyList <VmdCameraFrame> cameraFrames;
            IReadOnlyList <VmdFacialFrame> facialFrames;
            IReadOnlyList <VmdLightFrame>  lightFrames;

            if (ProcessBoneFrames && (bodyMotion != null && avatar != null && mltdPmxModel != null))
            {
                boneFrames = CreateBoneFrames(bodyMotion, avatar, mltdPmxModel);
            }
            else
            {
                boneFrames = EmptyArray.Of <VmdBoneFrame>();
            }

            if (ProcessCameraFrames && cameraMotion != null)
            {
                cameraFrames = CreateCameraFrames(cameraMotion, FixedFov);
            }
            else
            {
                cameraFrames = EmptyArray.Of <VmdCameraFrame>();
            }

            if (ProcessFacialFrames && scenarioObject != null)
            {
                facialFrames = CreateFacialFrames(scenarioObject, songPosition);
            }
            else
            {
                facialFrames = EmptyArray.Of <VmdFacialFrame>();
            }

            if (ProcessLightFrames && scenarioObject != null)
            {
                lightFrames = CreateLightFrames(scenarioObject);
            }
            else
            {
                lightFrames = EmptyArray.Of <VmdLightFrame>();
            }

            const string modelName = "MODEL_00";

            var vmd = new VmdMotion(modelName, boneFrames, facialFrames, cameraFrames, lightFrames, null);

            return(vmd);
        }
        public VmdMotion CreateLipSync([CanBeNull] ScenarioObject baseScenario, int songPosition)
        {
            IReadOnlyList <VmdFacialFrame> frames;

            if (ProcessFacialFrames && baseScenario != null)
            {
                frames = CreateLipSyncFrames(baseScenario, songPosition);
            }
            else
            {
                frames = null;
            }

            return(new VmdMotion(ModelName, null, frames, null, null, null));
        }
Esempio n. 15
0
        public VmdMotion CreateLight([CanBeNull] ScenarioObject lights)
        {
            VmdLightFrame[] frames;

            if (ProcessLightFrames && lights != null)
            {
                frames = CreateLightFrames(lights);
            }
            else
            {
                frames = null;
            }

            return(new VmdMotion(ModelName, null, null, null, frames, null));
        }
        public VmdMotion CreateFacialExpressions([CanBeNull] ScenarioObject facialExpr, int songPosition)
        {
            IReadOnlyList <VmdFacialFrame> frames;

            if (ProcessFacialFrames && facialExpr != null)
            {
                frames = CreateFacialExpressionFrames(facialExpr, songPosition);
            }
            else
            {
                frames = null;
            }

            return(new VmdMotion(ModelName, null, frames, null, null, null));
        }
Esempio n. 17
0
        public VmdMotion CreateLipSync([CanBeNull] ScenarioObject baseScenario, int formationNumber, bool ignoreSingControl)
        {
            VmdFacialFrame[] frames;

            if (ProcessFacialFrames && baseScenario != null)
            {
                frames = CreateLipSyncFrames(baseScenario, formationNumber, ignoreSingControl);
            }
            else
            {
                frames = null;
            }

            return(new VmdMotion(ModelName, null, frames, null, null, null));
        }
Esempio n. 18
0
        public VmdMotion CreateFacialExpressions([CanBeNull] ScenarioObject facialExpr, int formationNumber)
        {
            VmdFacialFrame[] frames;

            if (ProcessFacialFrames && facialExpr != null)
            {
                frames = CreateFacialExpressionFrames(facialExpr, formationNumber);
            }
            else
            {
                frames = null;
            }

            return(new VmdMotion(ModelName, null, frames, null, null, null));
        }
Esempio n. 19
0
 //updates the pax demands for the scenario
 private static void UpdatePassengerDemands(ScenarioObject scenario)
 {
     foreach (ScenarioPassengerDemand demand in scenario.Scenario.PassengerDemands)
     {
         if (GameObject.GetInstance().GameTime.ToShortDateString() == demand.EndDate.ToShortDateString())
         {
             if (demand.Airport != null)
             {
                 PassengerHelpers.ChangePaxDemand(-demand.Factor);
             }
             if (demand.Country != null)
             {
                 PassengerHelpers.ChangePaxDemand(Airports.GetAllAirports(a => a.Profile.Country == demand.Country), -demand.Factor);
             }
         }
     }
 }
Esempio n. 20
0
    public void Initialize(ScenarioObject a_ScenarioObject, GameReferences a_GameReferences)
    {
        gameObject.name = a_ScenarioObject.Template.Name;

        m_SpriteRenderer.sortingOrder = -32767 + a_ScenarioObject.SortOrder;

        switch (a_ScenarioObject.Template.Name)
        {
        case "avtwood0":
            Resource = m_Resources.Resources[0];
            break;

        case "avtmerc0":
            Resource = m_Resources.Resources[1];
            break;

        case "avtore0":
            Resource = m_Resources.Resources[2];
            break;

        case "avtsulf0":
            Resource = m_Resources.Resources[3];
            break;

        case "avtcrys0":
            Resource = m_Resources.Resources[4];
            break;

        case "avtgems0":
            Resource = m_Resources.Resources[5];
            break;

        case "avtgold0":
            Resource = m_Resources.Resources[6];
            break;

        default:
            Resource = m_Resources.Resources[Random.Range(0, m_Resources.Resources.Count)];
            break;
        }

        m_Renderer.SetSprites(Resource.m_Sprites);
        m_ShadowRenderer.SetSprites(Resource.m_ShadowSprites);

        m_DynamicObstacle.Initialize(a_GameReferences.Pathfinding, this);
    }
Esempio n. 21
0
        private void FillList([NotNull] ScenarioObject scrobj)
        {
            lv.Items.Clear();

            var invariantCulture = CultureInfo.InvariantCulture;

            foreach (var obj in scrobj.Scenario)
            {
                var ts = TimeSpan.FromSeconds(obj.AbsoluteTime);

                var lvi = new ListViewItem(ts.ToString("g"));
                lvi.SubItems.Add(obj.AbsoluteTime.ToString(invariantCulture));
                lvi.SubItems.Add(obj.Param.ToString());
                lvi.SubItems.Add(obj.Idol.ToString());

                lv.Items.Add(lvi);
            }
        }
Esempio n. 22
0
        //adds another month for where the scenario parameter has not been fulfilled and returns if failing scenario
        private static Boolean UpdateFailureValue(ScenarioObject scenario, ScenarioFailure failure)
        {
            ScenarioFailureObject failureObject = scenario.getScenarioFailure(failure);
            int monthsSinceLastFailure          = MathHelpers.GetMonthsBetween(failureObject.LastFailureTime, GameObject.GetInstance().GameTime);

            if (monthsSinceLastFailure == 1)
            {
                failureObject.Failures++;
            }
            else
            {
                failureObject.Failures = 1;
            }

            failureObject.LastFailureTime = GameObject.GetInstance().GameTime;

            return(failureObject.Failures == failure.MonthsOfFailure);
        }
Esempio n. 23
0
        private static TimedList <int, Vector4[]> CollectFormationChanges([CanBeNull] ScenarioObject scenario, AppealType appealType)
        {
            var result = new TimedList <int, Vector4[]>();

            if (scenario == null)
            {
                return(result);
            }

            if (scenario.HasFormationChangeEvents())
            {
                var events = scenario.Scenario.WhereToArray(s => s.Type == ScenarioDataType.FormationChange);

                foreach (var ev in events)
                {
                    Debug.Assert(ev != null, nameof(ev) + " != null");

                    // Layer=0: applied to all appeal variants (including no appeal)
                    // Layer>0: applied to that appeal only
                    if (ev.Layer == 0 || ev.Layer == (int)appealType)
                    {
                        var formations = ev.Formation;
                        Debug.Assert(formations != null && formations.Length > 0);

                        var frameIndex = (int)Math.Round(ev.AbsoluteTime * FrameRate.Mltd);

                        var f = new Vector4[formations.Length];

                        for (var i = 0; i < formations.Length; i += 1)
                        {
                            var v = formations[i];
                            f[i] = new Vector4(v.X, v.Y, v.Z, v.W);
                        }

                        result.AddOrUpdate(frameIndex, f);
                    }
                }
            }

            return(result);
        }
Esempio n. 24
0
        public static ScenarioObject Load([NotNull] string path)
        {
            ScenarioObject result = null;

            const string scenarioEnds = "scenario_sobj";

            var manager = new AssetsManager();

            manager.LoadFiles(path);

            foreach (var assetFile in manager.assetsFileList)
            {
                foreach (var obj in assetFile.Objects)
                {
                    if (obj.type != ClassIDType.MonoBehaviour)
                    {
                        continue;
                    }

                    var behaviour = obj as MonoBehaviour;

                    if (behaviour == null)
                    {
                        throw new ArgumentException("An object serialized as MonoBehaviour is actually not a MonoBehaviour.");
                    }

                    if (!behaviour.m_Name.EndsWith(scenarioEnds))
                    {
                        continue;
                    }

                    var ser = new ScriptableObjectSerializer();

                    result = ser.Deserialize <ScenarioObject>(behaviour);

                    break;
                }
            }

            return(result);
        }
Esempio n. 25
0
        /*public static string GetScenarioInfo(string id, string path)
         * {
         *  string folder = new DirectoryInfo(path).Name;
         *  //string topicsPath = Path.Combine(path, "topics");
         *  DescModel scenario = JsonConvert.DeserializeObject<DescModel>(File.ReadAllText(Path.Combine(path, folder + ".info")));
         *  ScenarioObject sc = new ScenarioObject();
         *  sc.id = id;
         *  sc.name = scenario.title;
         *  sc.topics = GetTopics(id);
         *  sc.description = scenario.desc;// Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(scenario.desc));
         *  string json = "{ scenario:" + JsonConvert.SerializeObject(sc) + "}";
         *  return json;
         * }*/

        public static ScenarioModel GetScenarioInfoModel(string id, string path)
        {
            string folder = new DirectoryInfo(path).Name;
            //string topicsPath = Path.Combine(path, "topics");
            DescModel scenario =
                JsonConvert.DeserializeObject <DescModel>(File.ReadAllText(Path.Combine(path, folder + ".info")));
            ScenarioObject sc = new ScenarioObject();

            sc.id          = id;
            sc.name        = scenario.title;
            sc.topics      = GetTopics(id);
            sc.description =
                scenario.desc; // Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(scenario.desc));

            /*foreach (string topic in Directory.GetFiles(topicsPath))
             * {
             *  sc.topics.Add(new FileInfo(topic).Name);
             * }*/

            ScenarioModel model = new ScenarioModel();

            model.scenario = sc;
            return(model);
        }
Esempio n. 26
0
        private VmdFacialFrame[] CreateLipSyncFrames([NotNull] ScenarioObject lipSync, int formationNumber, bool ignoreSingControl)
        {
            var frameList = new List <VmdFacialFrame>();

            var lipSyncControls = lipSync.Scenario.WhereToArray(s => s.Type == ScenarioDataType.LipSync);

            EventScenarioData[] singControls;
            double[]            singControlTimes;

            if (ignoreSingControl)
            {
                singControls     = Array.Empty <EventScenarioData>();
                singControlTimes = Array.Empty <double>();
            }
            else
            {
                var singControlList = lipSync.Scenario.WhereToList(s => s.Type == ScenarioDataType.SingControl);

                // Make sure the events are sorted.
                singControlList.Sort((s1, s2) => s1.AbsoluteTime.CompareTo(s2.AbsoluteTime));

                singControls     = singControlList.ToArray();
                singControlTimes = singControls.SelectToArray(s => s.AbsoluteTime);
            }

            Trace.Assert(lipSyncControls.Length > 0, "Lip-sync controls should exist.");
            Trace.Assert(lipSyncControls[0].Param == (int)LipCode.Closed, "The first control op should be 54.");
            Trace.Assert(lipSyncControls[lipSyncControls.Length - 1].Param == (int)LipCode.Closed, "The last control op should be 54.");

            var lastFrameTime = float.NaN;

            for (var i = 0; i < lipSyncControls.Length; i++)
            {
                var sync = lipSyncControls[i];

                Debug.Assert(sync != null, nameof(sync) + " != null");

                var currentTime = (float)sync.AbsoluteTime;

                if (currentTime < 0)
                {
                    // Some facial control frames have negative time (e.g. scrobj_s02ann), which eventually leads to negative frame indices when writing VMD file.
                    // MMM interprets this as uint64 (read int32 -> convert to int64 -> unchecked convert to uint64), MMD interprets this as int32.
                    // Both of them crash on negative frame indices. We have to avoid that.
                    continue;
                }

                if (float.IsNaN(lastFrameTime) && !currentTime.Equals(0))
                {
                    // Manually insert a silence frame at the beginning.
                    AddSilenceFrame(frameList, 0);
                }

                var isSinging = IsSingingAt(singControls, singControlTimes, sync.AbsoluteTime, formationNumber);
                var shouldUpdateLastFrameTime = true;

                if (isSinging)
                {
                    var lipCode = (LipCode)sync.Param;

                    switch (lipCode)
                    {
                    case LipCode.A:
                    case LipCode.I:
                    case LipCode.U:
                    case LipCode.E:
                    case LipCode.O:
                    case LipCode.N: {
                        // The whole song ends with a "mouse-closed" (54) op.
                        Debug.Assert(i < lipSyncControls.Length - 1, "The song should end with control op 54 (mouse closed).");
                        // The whole song starts with a "mouse-closed" (54) op.
                        Debug.Assert(i > 0, "The song should start with control op 54 (mouse closed).");

                        string morphName;

                        switch (lipCode)
                        {
                        case LipCode.A:
                            morphName = "M_a";
                            break;

                        case LipCode.I:
                            morphName = "M_i";
                            break;

                        case LipCode.U:
                            morphName = "M_u";
                            break;

                        case LipCode.E:
                            morphName = "M_e";
                            break;

                        case LipCode.O:
                            morphName = "M_o";
                            break;

                        case LipCode.N:
                            morphName = "M_n";
                            break;

                        default:
                            throw new ArgumentOutOfRangeException(nameof(lipCode), lipCode, "Not possible.");
                        }

                        var prevFrame = FindPreviousActiveLipSyncFrame(lipSyncControls, i);

                        if (prevFrame == null)
                        {
                            throw new KeyNotFoundException($"Cannot find the previous active lip sync frame of frame at {sync.AbsoluteTime.ToString(CultureInfo.InvariantCulture)}.");
                        }

                        var prevTime = (float)prevFrame.AbsoluteTime;

                        if (currentTime - prevTime > LipTransitionTime)
                        {
                            frameList.Add(CreateFacialFrame(currentTime - LipTransitionTime, morphName, 0));
                        }
                        else
                        {
                            frameList.Add(CreateFacialFrame(prevTime, morphName, 0));
                        }

                        frameList.Add(CreateFacialFrame(currentTime, morphName, 1));

                        var nextFrame = FindNextActiveLipSyncFrame(lipSyncControls, i);

                        if (nextFrame == null)
                        {
                            throw new KeyNotFoundException($"Cannot find the next active lip sync frame of frame at {sync.AbsoluteTime.ToString(CultureInfo.InvariantCulture)}.");
                        }

                        var nextTime = (float)nextFrame.AbsoluteTime;

                        if (nextTime - currentTime > LipTransitionTime)
                        {
                            frameList.Add(CreateFacialFrame(nextTime - LipTransitionTime, morphName, 1));
                            frameList.Add(CreateFacialFrame(nextTime, morphName, 0));
                        }
                        else
                        {
                            frameList.Add(CreateFacialFrame(nextTime, morphName, 0));
                        }

                        break;
                    }

                    case LipCode.Closed: {
                        AddSilenceFrame(frameList, currentTime);
                        break;
                    }

                    // Don't generate frames for these control codes(?)
                    case LipCode.Control1:
                    case LipCode.Control2:
                    case LipCode.Control3: {
                        shouldUpdateLastFrameTime = false;
                        break;
                    }

                    default:
                        throw new ArgumentOutOfRangeException(nameof(lipCode), lipCode, "Invalid lip code.");
                    }
                }
                else
                {
                    // Muted
                    AddSilenceFrame(frameList, currentTime);
                }

                if (shouldUpdateLastFrameTime)
                {
                    lastFrameTime = currentTime;
                }
            }

            return(frameList.ToArray());
        }
Esempio n. 27
0
        private VmdFacialFrame[] CreateFacialExpressionFrames([NotNull] ScenarioObject facialExpr, int formationNumber)
        {
            var frameList = new List <VmdFacialFrame>();

            var expControls = facialExpr.Scenario.WhereToArray(s => s.Type == ScenarioDataType.FacialExpression && s.Idol == formationNumber - 1);

            Debug.Assert(expControls.Length > 0, "Expression controls should exist.");

            var mappings = _conversionConfig.FacialExpressionMappings;

            // Note that here we don't process blinks (which happens in MLTD)
            for (var i = 0; i < expControls.Length; i++)
            {
                var exp         = expControls[i];
                var currentTime = (float)exp.AbsoluteTime;

                bool areEyesOpen;

                var eyesClosedRatio = exp.EyeClosed ? 1.0f : 0.0f;

                frameList.Add(CreateFacialFrame(currentTime, "E_metoji_r", eyesClosedRatio));
                frameList.Add(CreateFacialFrame(currentTime, "E_metoji_l", eyesClosedRatio));

                if (i > 0)
                {
                    if (expControls[i - 1].EyeClosed != exp.EyeClosed)
                    {
                        frameList.Add(CreateFacialFrame(currentTime - HalfEyeBlinkTime, "E_metoji_r", 1 - eyesClosedRatio));
                        frameList.Add(CreateFacialFrame(currentTime - HalfEyeBlinkTime, "E_metoji_l", 1 - eyesClosedRatio));
                    }
                }

                if (exp.EyeClosed)
                {
                    areEyesOpen = false;
                }
                else
                {
                    do
                    {
                        if (i > 0)
                        {
                            if (expControls[i - 1].EyeClosed)
                            {
                                areEyesOpen = false;
                                break;
                            }
                        }

                        if (i < expControls.Length - 1)
                        {
                            if (expControls[i + 1].EyeClosed)
                            {
                                if (currentTime >= expControls[i + 1].AbsoluteTime - HalfEyeBlinkTime)
                                {
                                    areEyesOpen = false;
                                    break;
                                }
                            }
                        }

                        areEyesOpen = true;
                    } while (false);
                }

                {
                    // The key associated with a group of morph values, representing a whole facial expression
                    var expressionKey = exp.Param;

                    if (!mappings.ContainsKey(expressionKey))
                    {
                        Trace.TraceWarning("Facial expression key {0} is not found (at time {1}), using default emotion instead.", exp.Param, currentTime);

                        expressionKey = 0;
                    }

                    foreach (var kv in mappings[expressionKey])
                    {
                        var morphName = kv.Key;

                        if (EyesFilteredMorphs.Contains(morphName))
                        {
                            continue;
                        }

                        if (EyesAffectedMorphs.Contains(morphName) && !areEyesOpen)
                        {
                            continue;
                        }

                        frameList.Add(CreateFacialFrame(currentTime, morphName, kv.Value));
                    }

                    // TODO: There is still one problem though, if an eye morph (say, E_wink_l) is activated BEFORE blinking, there is still a disaster.
                    //       But I am not sure how to handle that case. If that happens, it probably means something went wrong in animation directing.
                    //       Logical animations won't let you blink while you are winking.

                    if (i > 0)
                    {
                        if (expControls[i - 1].Param != exp.Param)
                        {
                            var lastExpressionKey = expControls[i - 1].Param;

                            if (!mappings.ContainsKey(lastExpressionKey))
                            {
                                Trace.TraceWarning("Facial expression key {0} is not found (at time {1}), using default emotion instead.", expControls[i - 1].Param, (float)expControls[i - 1].AbsoluteTime);

                                lastExpressionKey = 0;
                            }

                            var expectedTransitionStartTime = currentTime - FacialExpressionTransitionTime;

                            foreach (var kv in mappings[lastExpressionKey])
                            {
                                var morphName = kv.Key;

                                if (EyesFilteredMorphs.Contains(morphName))
                                {
                                    continue;
                                }

                                if (EyesAffectedMorphs.Contains(morphName) && !areEyesOpen)
                                {
                                    continue;
                                }

                                // So... do we have to "restore" some morphs after blinking? I think not. Otherwise it will become very strange.
                                frameList.Add(CreateFacialFrame(expectedTransitionStartTime, morphName, kv.Value));
                            }
                        }
                    }
                }
            }

            return(frameList.ToArray());
        }
Esempio n. 28
0
        //checks for the different failure scenarios
        public static void UpdateScenario(ScenarioObject scenario)
        {
            double monthsSinceStart = MathHelpers.GetMonthsBetween(GameObject.GetInstance().StartDate, GameObject.GetInstance().GameTime);

            var failuresToCheck = scenario.Scenario.Failures.FindAll(f => f.CheckMonths == 1 || f.CheckMonths == monthsSinceStart);

            foreach (ScenarioFailure failure in failuresToCheck)
            {
                Boolean failureOk = true;
                if (failure.Type == ScenarioFailure.FailureType.Cash)
                {
                    double totalMoney = GameObject.GetInstance().MainAirline.Money;

                    totalMoney += GameObject.GetInstance().MainAirline.Subsidiaries.Sum(s => s.Money);

                    failureOk = totalMoney > Convert.ToInt64(failure.Value);
                }
                if (failure.Type == ScenarioFailure.FailureType.Fleet)
                {
                    int fleetSize = GameObject.GetInstance().MainAirline.Fleet.Count + GameObject.GetInstance().MainAirline.Subsidiaries.Sum(s => s.Fleet.Count);
                    failureOk = fleetSize > Convert.ToInt32(failure.Value);
                }
                if (failure.Type == ScenarioFailure.FailureType.Domestic)
                {
                    int domesticDestinations = GameObject.GetInstance().MainAirline.Airports.FindAll(a => a.Profile.Country == GameObject.GetInstance().MainAirline.Profile.Country).Count;

                    domesticDestinations += GameObject.GetInstance().MainAirline.Subsidiaries.Sum(s => s.Airports.Count(a => a.Profile.Country == s.Profile.Country));

                    failureOk = domesticDestinations > Convert.ToInt32(failure.Value);
                }
                if (failure.Type == ScenarioFailure.FailureType.Intl)
                {
                    int intlDestinations = GameObject.GetInstance().MainAirline.Airports.FindAll(a => a.Profile.Country != GameObject.GetInstance().MainAirline.Profile.Country).Count;

                    intlDestinations += GameObject.GetInstance().MainAirline.Subsidiaries.Sum(s => s.Airports.Count(a => a.Profile.Country != s.Profile.Country));

                    failureOk = intlDestinations > Convert.ToInt32(failure.Value);
                }
                if (failure.Type == ScenarioFailure.FailureType.PaxGrowth)
                {
                    double paxLastYear    = GameObject.GetInstance().MainAirline.Statistics.getStatisticsValue(GameObject.GetInstance().GameTime.Year - 2, StatisticsTypes.GetStatisticsType("Passengers")) + GameObject.GetInstance().MainAirline.Subsidiaries.Sum(s => s.Statistics.getStatisticsValue(GameObject.GetInstance().GameTime.Year - 2, StatisticsTypes.GetStatisticsType("Passengers")));
                    double paxCurrentYear = GameObject.GetInstance().MainAirline.Statistics.getStatisticsValue(GameObject.GetInstance().GameTime.Year - 1, StatisticsTypes.GetStatisticsType("Passengers")) + GameObject.GetInstance().MainAirline.Subsidiaries.Sum(s => s.Statistics.getStatisticsValue(GameObject.GetInstance().GameTime.Year - 1, StatisticsTypes.GetStatisticsType("Passengers")));

                    double change = (paxCurrentYear - paxLastYear) / paxLastYear * 100;

                    failureOk = change > Convert.ToDouble(failure.Value);
                }
                if (failure.Type == ScenarioFailure.FailureType.FleetAge)
                {
                    double avgFleetAge = (GameObject.GetInstance().MainAirline.getAverageFleetAge() + GameObject.GetInstance().MainAirline.Subsidiaries.Sum(s => s.getAverageFleetAge())) / (1 + GameObject.GetInstance().MainAirline.Subsidiaries.Count);
                    failureOk = Convert.ToDouble(failure.Value) > avgFleetAge;
                }
                if (failure.Type == ScenarioFailure.FailureType.Pax)
                {
                    double totalPassengers = GameObject.GetInstance().MainAirline.Statistics.getStatisticsValue(StatisticsTypes.GetStatisticsType("Passengers")) + GameObject.GetInstance().MainAirline.Subsidiaries.Sum(s => s.Statistics.getStatisticsValue(StatisticsTypes.GetStatisticsType("Passengers")));

                    failureOk = Convert.ToDouble(failure.Value) * 1000 < totalPassengers;
                }
                if (failure.Type == ScenarioFailure.FailureType.Bases)
                {
                    int homeBases = GameObject.GetInstance().MainAirline.Airports.FindAll(a => a.getCurrentAirportFacility(GameObject.GetInstance().MainAirline, AirportFacility.FacilityType.Service).TypeLevel > 0).Count;
                    homeBases += GameObject.GetInstance().MainAirline.Subsidiaries.Sum(s => s.Airports.Count(a => a.getCurrentAirportFacility(s, AirportFacility.FacilityType.Service).TypeLevel > 0));

                    failureOk = homeBases <= Convert.ToInt32(failure.Value);
                }
                if (failure.Type == ScenarioFailure.FailureType.Debt)
                {
                    double debt = GameObject.GetInstance().MainAirline.Loans.Sum(l => l.PaymentLeft) + GameObject.GetInstance().MainAirline.Money;
                    debt += GameObject.GetInstance().MainAirline.Subsidiaries.Sum(s => s.Loans.Sum(l => l.PaymentLeft) + s.Money);


                    failureOk = debt <= Convert.ToDouble(failure.Value);
                }

                if (failure.Type == ScenarioFailure.FailureType.JetRation)
                {
                    double totalFleet = Convert.ToDouble(GameObject.GetInstance().MainAirline.Fleet.Count) + Convert.ToDouble(GameObject.GetInstance().MainAirline.Subsidiaries.Sum(s => s.Fleet.Count));
                    double totalJets  = Convert.ToDouble(GameObject.GetInstance().MainAirline.Fleet.Count(f => f.Airliner.Type.Engine == AirlinerType.EngineType.Jet)) + Convert.ToDouble(GameObject.GetInstance().MainAirline.Subsidiaries.Sum(s => s.Fleet.Count(f => f.Airliner.Type.Engine == AirlinerType.EngineType.Jet)));

                    double jetRation = totalJets / totalFleet;

                    failureOk = jetRation >= Convert.ToDouble(failure.Value);
                }

                if (!failureOk)
                {
                    if (failure.MonthsOfFailure == 1)
                    {
                        EndScenario(failure);
                    }
                    else
                    {
                        Boolean failingScenario = UpdateFailureValue(scenario, failure);

                        if (failingScenario)
                        {
                            EndScenario(failure);
                        }
                    }
                }
                //( Safety, Debt, Security,  Crime)
            }
            UpdatePassengerDemands(GameObject.GetInstance().Scenario);

            if (GameObject.GetInstance().Scenario.Scenario.EndYear == GameObject.GetInstance().GameTime.Year)
            {
                GameObject.GetInstance().Scenario.IsSuccess = true;
            }
        }
Esempio n. 29
0
 public void Draw(TagIdent item)
 {
     if (objects.ContainsKey(item))
     {
         IRenderable @object = objects[item] as IRenderable;
         @object.Render(new[] { program, systemProgram });
     }
     else
     {
         var data = Halo2.GetReferenceObject(item);
         objects[item] = new ScenarioObject((HierarchyModel)data);
     }
 }
Esempio n. 30
0
 public void Add(TagIdent item)
 {
     var data = Halo2.GetReferenceObject(item);
     objects[item] = new ScenarioObject((HierarchyModel)data);
 }
Esempio n. 31
0
 internal void Add(HierarchyModel model, TagIdent id)
 {
     objects[id] = new ScenarioObject(model);
 }
Esempio n. 32
0
        private void Button1_Click(object sender, System.EventArgs e)
        {
            ofd.Filter          = "Unity3D (*.unity3d)|*.unity3d";
            ofd.CheckFileExists = true;
            ofd.ValidateNames   = true;
            ofd.Multiselect     = false;
            ofd.ReadOnlyChecked = false;
            ofd.ShowReadOnly    = false;

            var r = ofd.ShowDialog(this);

            if (r == DialogResult.Cancel)
            {
                return;
            }

            var filePath = ofd.FileName;

            textBox1.Text = filePath;

            ScenarioObject scenarioObject = null;

            try {
                using (var fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                    using (var bundle = new BundleFile(fileStream, false)) {
                        foreach (var asset in bundle.AssetFiles)
                        {
                            foreach (var preloadData in asset.PreloadDataList)
                            {
                                if (preloadData.KnownType != KnownClassID.MonoBehaviour)
                                {
                                    continue;
                                }

                                var behaviour = preloadData.LoadAsMonoBehaviour(true);

                                if (!behaviour.Name.EndsWith("scenario_sobj"))
                                {
                                    continue;
                                }

                                behaviour = preloadData.LoadAsMonoBehaviour(false);

                                var serializer = new MonoBehaviourSerializer();
                                scenarioObject = serializer.Deserialize <ScenarioObject>(behaviour);
                                break;
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                var error = ex.ToString();

                MessageBox.Show(error, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Debug.Print(error);
            }


            if (scenarioObject != null)
            {
                foreach (var s in scenarioObject.Scenario.Where(ev => ev.Type == ScenarioDataType.Lyrics))
                {
                    Debug.Print("{0} @ {1}", s.Lyrics, s.AbsoluteTime);
                }

                Debug.Print("Success");
            }
        }
        private List <VmdFacialFrame> CreateLipSyncFrames([NotNull] ScenarioObject lipSync, int idolPosition)
        {
            var frameList = new List <VmdFacialFrame>();

            var lipSyncControls = lipSync.Scenario.Where(s => s.Type == ScenarioDataType.LipSync).ToArray();
            var singControlList = lipSync.Scenario.Where(s => s.Type == ScenarioDataType.SingControl).ToList();

            // Make sure the events are sorted.
            singControlList.Sort((s1, s2) => s1.AbsoluteTime.CompareTo(s2.AbsoluteTime));

            var singControls     = singControlList.ToArray();
            var singControlTimes = singControls.Select(s => s.AbsoluteTime).ToArray();

            Trace.Assert(lipSyncControls.Length > 0, "Lip-sync controls should exist.");
            Trace.Assert(lipSyncControls[0].Param == (int)LipCode.Closed, "The first control op should be 54.");
            Trace.Assert(lipSyncControls[lipSyncControls.Length - 1].Param == (int)LipCode.Closed, "The last control op should be 54.");

            var lastFrameTime = float.NaN;

            for (var i = 0; i < lipSyncControls.Length; i++)
            {
                var sync        = lipSyncControls[i];
                var currentTime = (float)sync.AbsoluteTime;

                if (currentTime < 0)
                {
                    // Some facial control frames have negative time (e.g. scrobj_s02ann), which eventually leads to negative frame indices when writing VMD file.
                    // MMM interprets this as uint64 (read int32 -> convert to int64 -> unchecked convert to uint64), MMD interprets this as int32.
                    // Both of them crash on negative frame indices. We have to avoid that.
                    continue;
                }

                if (float.IsNaN(lastFrameTime) && !currentTime.Equals(0))
                {
                    // Manually insert a silence frame at the beginning.
                    AddSilenceFrame(frameList, 0);
                }

                var isSinging = IsSingingAt(singControls, singControlTimes, sync.AbsoluteTime, idolPosition);

                if (isSinging)
                {
                    var lipCode = (LipCode)sync.Param;

                    switch (lipCode)
                    {
                    case LipCode.A:
                    case LipCode.I:
                    case LipCode.U:
                    case LipCode.E:
                    case LipCode.O:
                    case LipCode.E2:
                    case LipCode.U2:
                    case LipCode.N: {
                        // The whole song ends with a "mouse-closed" (54) op.
                        Debug.Assert(i < lipSyncControls.Length - 1, "The song should end with control op 54 (mouse closed).");
                        // The whole song starts with a "mouse-closed" (54) op.
                        Debug.Assert(i > 0, "The song should start with control op 54 (mouse closed).");

                        string morphName;

                        switch (lipCode)
                        {
                        case LipCode.A:
                            morphName = "M_a";
                            break;

                        case LipCode.I:
                            morphName = "M_i";
                            break;

                        case LipCode.U:
                        case LipCode.U2:
                            morphName = "M_u";
                            break;

                        case LipCode.E:
                        case LipCode.E2:
                            morphName = "M_e";
                            break;

                        case LipCode.O:
                            morphName = "M_o";
                            break;

                        case LipCode.N:
                            morphName = "M_n";
                            break;

                        default:
                            throw new ArgumentOutOfRangeException(nameof(lipCode), lipCode, "Not possible.");
                        }

                        var prevTime = (float)lipSyncControls[i - 1].AbsoluteTime;

                        if (currentTime - prevTime > LipTransitionTime)
                        {
                            frameList.Add(CreateFacialFrame(currentTime - LipTransitionTime, morphName, 0));
                        }
                        else
                        {
                            frameList.Add(CreateFacialFrame(prevTime, morphName, 0));
                        }

                        frameList.Add(CreateFacialFrame(currentTime, morphName, 1));

                        var nextTime = (float)lipSyncControls[i + 1].AbsoluteTime;

                        if (nextTime - currentTime > LipTransitionTime)
                        {
                            frameList.Add(CreateFacialFrame(nextTime - LipTransitionTime, morphName, 1));
                            frameList.Add(CreateFacialFrame(nextTime, morphName, 0));
                        }
                        else
                        {
                            frameList.Add(CreateFacialFrame(nextTime, morphName, 0));
                        }

                        break;
                    }

                    case LipCode.Closed: {
                        AddSilenceFrame(frameList, currentTime);
                        break;
                    }

                    default:
                        throw new ArgumentOutOfRangeException(nameof(lipCode), lipCode, "Not possible");
                    }
                }
                else
                {
                    // Muted
                    AddSilenceFrame(frameList, currentTime);
                }

                lastFrameTime = currentTime;
            }

            return(frameList);
        }